教程:使用 C# SDK 自动调用 SP-API
借助“使用亚马逊账户登录” (LWA) 令牌交换和身份验证,自动执行 SP-API 调用。
本教程为您提供使用 “用亚马逊登录” (LWA) 令牌交换和身份验证生成 C# SDK 所需的所有信息,以构建应用程序。
您可以使用此 SDK 将亚马逊商城功能集成到您的应用程序中,包括访问商品信息、管理订单、处理发货等。
教程
以下教程将帮助您设置自己的 C# 开发工具包来自动执行 SP-API 调用。
先决条件
要完成本教程,您需要满足以下前提条件:
- 处于草稿或发布状态的混合或 SP-API 应用
- 集成开发环境 (IDE) 软件(本演练使用 Windows 操作系统上的 Visual Studio IDE)
在您的应用程序可以连接到销售伙伴 API 之前,您必须对其进行注册,并且它必须获得销售伙伴的授权。如果您没有混合或 SP-API 应用,请按照注册为开发者、注册您的应用程序和授权销售伙伴 API 应用程序步骤进行操作。然后,返回到本教程。
接下来,为教程设置工作区。
第 1 步:设置工作区
-
在您的本地驱动器上,为该项目创建一个目录并将其命名
SwaggerToCL
。 -
下载以下工具。
- IDE 软件(本逐步指南使用的是 Windows 操作系统上的 Visual Studio IDE)
- GNU Wget
- Java 8 或更高版本
-
运行以下命令下载 Swagger 代码生成器:
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
中。 -
在 GitHub 上,转到
https://github.com/amzn/selling-partner-api-models/tree/main/models
并使用以下命令将selling-partner-api-models
存储库克隆到本地目录C:\\SwaggerToCL
。git clone https://github.com/amzn/selling-partner-api-models -
导航到
selling-partner-api-models\\models
将文件夹放在存储库的本地副本中,并将模型子文件夹中的 JSON 文件复制到C:\\SwaggerToCL
。本教程使用Sellers.json
文件。 -
在 GitHub 中,前往
https://github.com/amzn/selling-partner-api-models/tree/main/clients/sellingpartner-api-aa-csharp
然后下载sellingpartner-api-aa-csharp
文件夹到您的本地计算机。
此文件夹提供了帮助类,用于为亚马逊销售伙伴 API 生成访问令牌。它旨在与通过 Swagger Codegen 和 RestSharp 库生成的销售伙伴 API 客户端库一起使用。此外,它也可以集成到自定义项目中。
现在您已经完成了所需的设置,下一步是使用 sellingpartner-api-aa-csharp
文件夹中提供的身份验证和授权类生成 Java SDK。
第 2 步。生成带有 LWA 令牌交换和身份验证的 C# SDK
-
打开 Visual Studio。
-
在
sellingpartner-api-aa-csharp
文件夹,选择SellingPartnerAPIAuthAndAuthCSharp.sln
文件并使用 构建 Visual Studio 中的选项。这会生成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
-
在 Visual Studio IDE 中,导航到生成的库 sellers_csharpcl 文件夹,然后打开
.sln
文件。这个.sln
包文件的名称将与中提供的名称相同 第 2 步。生成带有 LWA 令牌交换和身份验证的 C# SDK。在此示例中,包文件名为SellingPartnerAPI.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
或者全部Newtonsoft.json 12.0.3
或者全部RestSharp 106.12.0
RateLimiter 2.2.0
或更新版本(这也将安装ComposableAsync.Core
)
-
右键单击
SellingPartnerAPI.SellerAPI.Test
文件并选择 管理 NuGet 软件包。安装 Nunit 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 | 您的 LWA 客户端标识符。有关更多信息,请参阅查看您的应用程序信息和凭证。 | 有帮助 |
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. | 否。如果您在以下步骤中调用的操作是免授权操作,则包括 Scopes 。如果您包括 Scopes ,请勿包括 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 执行。选择 行。
-
生成并运行该项目。
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
或者其依赖项之一。”
SellingPartnerAPI.servicesApi.Client.ApiClient:rateLimiter
(3) 的类型,原因如下:无法加载文件或程序集 ComposableAsync.Core, Version=1.1.1.0, Culture=neutral, PublicKeyToken=null
或者其依赖项之一。”点击此处可展开答案。
如果在生成并运行代码后收到此错误,则表示下载了 ComposableAsync.Core
依赖包,但未作为引用包含在其中。确保手动添加 dll 作为引用。
模型的映射问题
点击此处可展开答案。
ItemAsin
模型是使用 JsonObject
类型生成的,但所需的字符串 ItemAttributes
需要 JsonObjectAttribute
。您可以使用此命令(该命令使用目录项 API)导入模型所需的映射:
`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()
:找不到合适的方法进行重写。”点击此处可展开答案。
用 virtual
修改 override
关键字。将方法声明为 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