チュートリアル:C# SDKを使用してSP-API呼び出しを自動化する
Amazonアカウントでログイン(LWA)トークンの交換と認証により、SP-API呼び出しを自動化します。
このチュートリアルでは、Login with Amazon (LWA) トークン交換とアプリケーション構築用の認証を使用して C# SDK を生成するために必要なすべての情報を提供します。
このSDKを使用すると、商品情報へのアクセス、注文の管理、出荷の処理など、Amazonマーケットプレイスの機能をアプリケーションに統合できます。
チュートリアル
次のチュートリアルは、SP-API 呼び出しを自動化するための独自の C# SDK の設定に役立ちます。
前提条件
このチュートリアルを完了するには、次の前提条件が必要です。
- ドラフトまたは公開状態のハイブリッドアプリまたはSP-APIアプリ
- 統合開発環境 (IDE) ソフトウェア (このチュートリアルでは Windows OS 上の Visual Studio IDE を使用します)
Before your application can connect to the Selling Partner API, you must register it, and it must be authorized by a selling partner. If you do not have a hybrid or SP-API app, follow the steps to register as a developer, register your application, and Authorizing Selling Partner API applications. Then, return to this tutorial.
次に、チュートリアル用のワークスペースを設定します。
ステップ1. ワークスペースをセットアップします。
-
ローカルドライブに、このプロジェクトのディレクトリを作成して名前を付けます
SwaggerToCL
。 -
以下のツールをダウンロードしてください。
- IDE software (this walkthrough uses Visual Studio IDE on Windows OS)
- GNU Wget
- Java 8 またはそれ以降
-
次のコマンドを実行してSwagger Code Generatorをダウンロードします。
wget https://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.4.13/swagger-codegen-cli-2.4.13.jar -O swagger-codegen-cli.jar -
swagger-codegen-cli.jar
をローカルディレクトリC:\\SwaggerToCL
にコピーします。 -
In GitHub, go to
https://github.com/amzn/selling-partner-api-models/tree/main/models
and use the following command to clone theselling-partner-api-models
repository to your local directoryC:\\SwaggerToCL
.git clone https://github.com/amzn/selling-partner-api-models -
Navigate to the
selling-partner-api-models\\models
folder in your local copy of the repository and copy a JSON file from the models subfolders intoC:\\SwaggerToCL
. This tutorial uses theSellers.json
file. -
In GitHub, go to
https://github.com/amzn/selling-partner-api-models/tree/main/clients/sellingpartner-api-aa-csharp
and download thesellingpartner-api-aa-csharp
folder to your local computer.
This folder provides helper classes to generate an access token for Amazon Selling Partner APIs. It is intended for use with the Selling Partner API Client Libraries generated by Swagger Codegen using the RestSharp library. It can also be integrated into custom projects.
Now that you have completed the required setup, the next step is to generate the C# SDK with the authentication and authorization classes provided in the sellingpartner-api-aa-csharp
folder.
ステップ 2:LWA トークンの交換と認証を含む C# SDK を生成する
-
ビジュアルスタジオを開きます。
-
の中に
sellingpartner-api-aa-csharp
フォルダを選択し、SellingPartnerAPIAuthAndAuthCSharp.sln
ファイルを作成し、以下を使用してビルドします。 ビルド ビジュアルスタジオのオプション。これにより、次のものが生成されます。Amazon.SellingPartnerAPIAA.dll
フォルダー内のアセンブリsellingpartner-api-aa-csharp\\src\\Amazon.SellingPartnerAPIAA\\bin\\Debug\\netstandard2.0
。 -
ターミナルを開き、次のコマンドを実行して C# クライアントライブラリを生成します。生成されたクライアントライブラリの既定のパッケージ名は
Swagger.IO
。これらのコマンドは、それぞれの API 名をパッケージ名として使用してクライアントライブラリを生成します。Swagger.IO
。- で
C:\\SwaggerToCL
、という名前の JSON ファイルを作成しますcsharpConfig.json
、エディターを開いて次のコードを追加します。にとってpackageName
、クライアントライブラリを生成したい API と同じ名前を使用してください。
{"packageName":"SellingPartnerAPI.SellerAPI","targetFramework":"v4.7.2"}次のコマンドを実行して、カスタマイズされたパッケージ名で C# コードを生成します。
java -jar C:\SwaggerToCL\swagger-codegen-cli.jar generate -i C:\SwaggerToCL\[name of model].json -l csharp -t [path to selling-partner-api-models\clients\sellingpartner-api-aa-csharp folder]\src\Amazon.SellingPartnerAPIAA\resources\swagger-codegen\templates\ -o C:\SwaggerToCL\[name of client library] -c C:\SwaggerToCL\csharpConfig.jsonこのコマンドは
Sellers.json
C# コードを生成するには:java -jar C:\SwaggerToCL\swagger-codegen-cli.jar generate -i C:\SwaggerToCL\Sellers.json -l csharp -t C:\SwaggerToCL\sellingpartner-api-aa-csharp\src\Amazon.SellingPartnerAPIAA\resources\swagger-codegen\templates\ -o C:\SwaggerToCL\Sellers_CsharpCL -c C:\SwaggerToCL\csharpConfig.jsonSDK はで作成されます。
C:\\SwaggerToCL\\Sellers_CsharpCL
。次のステップは、実際のアプリケーションを記述し、生成された C# SDK を使用して SP-API に接続することです。 - で
ステップ 3:生成された C# SDK を使用して販売パートナー API に接続します。
-
In Visual Studio IDE, navigate to your generated library Sellers_CsharpCL folder and open the
.sln
file. The.sln
package file will have the name as provided in Step 2. Generate a C# SDK with LWA token exchange and authentication. In this example, the package file name isSellingPartnerAPI.SellerAPI.sln
. -
を右クリックします
SellingPartnerAPI.SellerAPI
ファイルを作成して選択 追加 > 参考文献。 -
の中に 参考文献 ウィンドウ、選択 ブラウズ、に移動
sellingpartner-api-aa csharp/src/Amazon.SellingPartnerAPIAA/bin/Debug/netstandard2.0
そして選んでAmazon.SellingPartnerAPIAA.dll
。 -
についても手順 1 ~ 3 を繰り返します。
SellingPartnerAPI.SellerAPI.Test
ファイル。 -
生成されたライブラリ
Sellers_CsharpCL
フォルダーに移動し、SellingPartnerAPI.SellerAPI
ファイルを右クリックして、「オプション」>「一般」を選択します。次に、ターゲットフレームワークを.net Framework v4.7以降に変更します。 -
についても手順 5 を繰り返します。
SellingPartnerAPI.SellerAPI.Test
ファイル。 -
を右クリックします
SellingPartnerAPI.SellerAPI
ファイルして選択 NuGet パッケージの管理。以下のパッケージバージョンがあることを確認してください (ない場合は、それぞれの NuGet パッケージをインストールしてください)。JsonSubTypes 1.2.0
またはallNewtonsoft.json 12.0.3
またはallRestSharp 106.12.0
RateLimiter 2.2.0
またはそれ以降 (これもインストールされます)ComposableAsync.Core
)
-
を右クリックします
SellingPartnerAPI.SellerAPI.Test
ファイルを保存して選択 NuGet パッケージの管理。をインストールします。 ヌニット 2.6.4 パッケージ。NuGetパッケージの手動インストール
シナリオによっては(IOSを使用する場合など)、NuGetパッケージに必要なバージョンが表示されますが、エラーが発生することがあります。このシナリオでは、ファイルシステムのパッケージフォルダーからパッケージを手動で追加する必要があります。
Sellers_CsharpCL
で、生成されたライブラリ.sln
フォルダーに移動し、{{2}}ファイルを開きます。- を右クリックします
SellingPartnerAPI.SellerAPI
ファイルを作成して選択 追加 > 参考文献。 - の中に 参考文献 ウィンドウ、選択 ブラウズ、に移動
sellingpartner-api-aa csharp/src/Amazon.SellingPartnerAPIAA/bin/Debug/netstandard2.0
、生成されたクライアントライブラリフォルダを選択します (たとえば、Sellers_CsharpCL
)、次に選択してください パッケージ そして、エラーが発生しているパッケージを追加してください。
-
の中に
SellingPartnerAPI.SellerAPI.Test > Api
フォルダを開いて[Modelname]Tests.cs
ファイルを作成して次のコードを追加します。using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using RestSharp; using SellingPartnerAPI.SellerAPI.Client; using SellingPartnerAPI.SellerAPI.Api; using SellingPartnerAPI.SellerAPI.Model; using Amazon.SellingPartnerAPIAA; namespace SellingPartnerAPI.SellerAPI.Test { class SellersApiTests { public static void Main(string[] args) { try { LWAAuthorizationCredentials lwaAuthorizationCredentials = new LWAAuthorizationCredentials { ClientId = "amzn1.application-oa2-client.******************", ClientSecret = "***********************************", RefreshToken = "Atzr|***********************************", Endpoint = new Uri("https://api.amazon.com/auth/o2/token") }; SellersApi sellersApi = new SellersApi.Builder() .SetLWAAuthorizationCredentials(lwaAuthorizationCredentials) .Build(); GetMarketplaceParticipationsResponse result = sellersApi.GetMarketplaceParticipations(); Console.WriteLine(result.ToJson()); } catch (LWAException e) { Console.WriteLine("LWA Exception when calling SellersApi#getMarketplaceParticipations"); Console.WriteLine(e.getErrorCode()); Console.WriteLine(e.getErrorMessage()); Console.WriteLine(e.Message); } catch (ApiException e) { Console.WriteLine("Exception when calling SellersApi#getMarketplaceParticipations"); Console.WriteLine(e.Message); } } } }LWAAuthorizationCredentials
インスタンスパラメーター:
名前 | 説明 | 必須 |
---|---|---|
ClientId | Your LWA client identifier. For more information, refer to Viewing your application information and credentials. | はい |
ClientSecret | Your LWA client secret. For more information, refer to Viewing your application information and credentials | はい |
RefreshToken | The LWA refresh token. Get this value when the selling partner authorizes your application. For more information, refer to Authorizing Selling Partner API Applications. | No. Include RefreshToken if the operation that you call in the following step requires selling partner authorization. All operations that are not grantless operations require selling partner authorization. If you include RefreshToken , do not include Scopes. |
Scopes | The scope of the LWA authorization grant. You can specify one or more Scopes values:- ScopeNotificationsAPI . For the Notifications API.- ScopeMigrationAPI . For the Authorization API. | No. Include Scopes if the operation that you call in the following step is a grantless operation. If you include Scopes , do not include the RefreshToken . |
Endpoint | LWA認証サーバーのURI。 | はい |
Example of an operation call that requires selling partner authorization:
```csharp
using Amazon.SellingPartnerAPIAA;
LWAAuthorizationCredentials lwaAuthorizationCredentials = new LWAAuthorizationCredentials
{
ClientId = "myClientId",
ClientSecret = "myClientSecret",
RefreshToken = "Aztr|...",
Endpoint = new Uri(""https://api.amazon.com/auth/o2/token"")
};
```
Example of a grantless operation call:
```csharp
using Amazon.SellingPartnerAPIAA;
LWAAuthorizationCredentials lwaAuthorizationCredentials = new LWAAuthorizationCredentials
{
ClientId = "myClientId",
ClientSecret = "myClientSecret",
Scopes = new List<string>() { ScopeConstants.ScopeNotificationsAPI, ScopeConstants.ScopeMigrationAPI }
Endpoint = new Uri(""https://api.amazon.com/auth/o2/token"")
};
```
-
コードの出力を表示するには、コードをコンソールアプリケーションに変換する必要があります。そのためには、を右クリックします。
SellingPartnerAPI.SellerAPI.Test
ファイルを保存して選択 オプション。 -
で プロジェクトオプション ウィンドウの左のナビゲーションペインで展開します ビルドそして、選択してください 将軍。で コード生成 セクション、選択 コンパイルターゲット そして選択してください GUI で実行可能。選ぶ OK。
-
プロジェクトをビルドして実行します。
C# SDKのトラブルシューティング
IRestRequest
エラー:「RestSharp Version=105.0.0.0. Culture=neutral. PublicKevToken=598062e77f915f75
は、参照されていないアセンブリに定義されています。アセンブリ{{2}}に参照を追加する必要があります。」
IRestRequest
エラー:「RestSharp Version=105.0.0.0. Culture=neutral. PublicKevToken=598062e77f915f75
は、参照されていないアセンブリに定義されています。アセンブリ{{2}}に参照を追加する必要があります。」選択すると回答が展開されます。
{{0}}パッケージをバージョン106.12.0.0に更新します。参照をチェックして、バージョン106.12が正常に更新されていることを確認してください。引き続き105.0.0.0が表示される場合は、古いバージョンを参照から削除し、生成されたクライアントライブラリでパッケージフォルダーから106.12.0.0パッケージを手動で追加してください。「型または名前空間の名前{{0}}が見つかりません(使用の指示やアセンブリ参照があることを確認してください)」
回答を表示する場合は、ここを選択してください。
In some scenarios, even though you have the required version in the NuGet
packages for Newtonsoft, you need to manually add the package from the package folder in the file system. To resolve this, use the following steps:
-
In Visual Studio, right-click your generated SDK package and choose
Add
, thenReferences
. -
.Netアセンブリの参照ウィンドウで、
browse
**を選択します。 -
Navigate to the generated client library folder in local → packages and add the specific package for Newtonsoft.
「メッセージ:フィールドのタイプSellingPartnerAPI.servicesApi.Client.ApiClient:rateLimiter
を読み込めませんでした。(3)理由:ファイルまたはアセンブリComposableAsync.Core, Version=1.1.1.0, Culture=neutral, PublicKeyToken=null
、またはその依存関係の1つを読み込めませんでした。」
SellingPartnerAPI.servicesApi.Client.ApiClient:rateLimiter
を読み込めませんでした。(3)理由:ファイルまたはアセンブリComposableAsync.Core, Version=1.1.1.0, Culture=neutral, PublicKeyToken=null
、またはその依存関係の1つを読み込めませんでした。」回答を表示する場合は、ここを選択してください。
コードをビルドして実行した後にこのエラーが表示される場合、ComposableAsync.Core
dependency packageがダウンロードされましたが、参照として含まれていません。dllを必ず参照として手動で追加してください。
モデルとのマッピングの問題
回答を表示する場合は、ここを選択してください。
The ItemAsin
model was generated with the JsonObject
type, but the required string ItemAttributes
requires the JsonObjectAttribute
. You can use this command, which uses the Catalog Items API, to import the required mapping for the models :
`java -jar swagger-codegen-cli.jar generate -i catalogItems_2022-04-01.json -l csharp -t sellingpartner-api-aa-csharp\src\Amazon.SellingPartnerAPIAA\resources\swagger-codegen\templates —import-mappings ItemAttributes=Newtonsoft.Json.JsonObjectAttribute —import-mappings ItemAsin=System.string -o catalogItems2022-04-01_import`
「HttpRequestHeaders.ToJson()
:オーバーライドする適切なメソッドが見つかりませんでした。」
HttpRequestHeaders.ToJson()
:オーバーライドする適切なメソッドが見つかりませんでした。」回答を表示する場合は、ここを選択してください。
override
キーワードを、virtual
を使って修正します。メソッドをvirtual
として宣言して、オーバーライドできるようにします。
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
「現在のコンテキストにBaseValidate
という名前は存在しません。」
BaseValidate
という名前は存在しません。」回答を表示する場合は、ここを選択してください。
クラス内の前述のメソッドのコメントアウトを解除します。
// IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
// {
// foreach (var x in BaseValidate(validationContext))
// yield return x;
// yield break;
// }
Updated 23 days ago