Tutorial: Automatice sus llamadas a SP-API con un SDK de C#
Automatice sus llamadas a la SP-API con el intercambio de tokens y la autenticación de Login with Amazon (LWA).
Este tutorial le proporciona toda la información necesaria para generar un SDK de C# con el intercambio de tokens Login with Amazon (LWA) y una autenticación para crear su aplicación.
Puedes usar este SDK para integrar las funciones del mercado de Amazon en tus aplicaciones, incluido el acceso a la información de los productos, la gestión de pedidos, la gestión de envíos, etc.
Tutorial
El siguiente tutorial le ayudará a configurar su propio SDK de C# para automatizar las llamadas a SP-API.
Requisitos
Para completar este tutorial, necesita los siguientes requisitos previos:
- Una aplicación híbrida o SP-API en estado de borrador o publicado
- Software de entorno de desarrollo integrado (IDE) (en este tutorial se usa el IDE de Visual Studio en el sistema operativo Windows)
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.
A continuación, configura tu espacio de trabajo para el tutorial.
Paso 1. Configura tu espacio de trabajo
-
En tu disco local, crea un directorio para este proyecto y asígnale un nombre
SwaggerToCL
. -
Descarga las siguientes herramientas.
- IDE software (this walkthrough uses Visual Studio IDE on Windows OS)
- GNU Wget
- Java 8 o más reciente
-
Ejecute el siguiente comando para descargar el generador de código 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 -
Copiar
swagger-codegen-cli.jar
en tu directorio localC:\\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.
Paso 2. Genere un SDK de C# con autenticación e intercambio de tokens LWA
-
Abra Visual Studio.
-
En el
sellingpartner-api-aa-csharp
carpeta, selecciona elSellingPartnerAPIAuthAndAuthCSharp.sln
archiva y compruébalo usando el construir opción en Visual Studio. Esto genera elAmazon.SellingPartnerAPIAA.dll
montaje en la carpetasellingpartner-api-aa-csharp\\src\\Amazon.SellingPartnerAPIAA\\bin\\Debug\\netstandard2.0
. -
Abre una terminal y ejecuta los siguientes comandos para generar la biblioteca cliente de C#. El nombre de paquete predeterminado para la biblioteca cliente generada es
Swagger.IO
. Estos comandos generan las bibliotecas cliente con sus respectivos nombres de API como nombre del paquete en lugar deSwagger.IO
.- En
C:\\SwaggerToCL
, crea un archivo JSON llamadocsharpConfig.json
, abre un editor y añade el siguiente código. ParapackageName
, usa el mismo nombre de la API para la que quieres generar la biblioteca cliente:
{"packageName":"SellingPartnerAPI.SellerAPI","targetFramework":"v4.7.2"}Ejecute este comando para generar código C# con un nombre de paquete personalizado:
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.jsonEste comando usa
Sellers.json
para generar código en 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.jsonEl SDK se crea en
C:\\SwaggerToCL\\Sellers_CsharpCL
. El siguiente paso es escribir la aplicación real y conectarse a la SP-API mediante el SDK de C# generado. - En
Paso 3. Conéctate a la API del socio vendedor mediante el SDK de C# generado
-
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
. -
Haga clic derecho en el
SellingPartnerAPI.SellerAPI
archivar y seleccionar Añadir > Referencias. -
En el Referencias ventana, elige Navegar, navegue hasta
sellingpartner-api-aa csharp/src/Amazon.SellingPartnerAPIAA/bin/Debug/netstandard2.0
y eligeAmazon.SellingPartnerAPIAA.dll
. -
Repita los pasos 1 a 3 para el
SellingPartnerAPI.SellerAPI.Test
archivo. -
Ve a la carpeta
Sellers_CsharpCL
de la biblioteca que has generado, haz clic con el botón derecho del ratón en el archivoSellingPartnerAPI.SellerAPI
, selecciona Opciones > General y cambia el marco de trabajo de destino a .net Framework v4.7 o superior. -
Repita el paso 5 para
SellingPartnerAPI.SellerAPI.Test
archivo. -
Haga clic derecho en el
SellingPartnerAPI.SellerAPI
archiva y elige Gestione los paquetes NuGet. Asegúrese de tener las siguientes versiones de paquetes (de lo contrario, instale los paquetes NuGet respectivos):JsonSubTypes 1.2.0
o todosNewtonsoft.json 12.0.3
o todosRestSharp 106.12.0
RateLimiter 2.2.0
o más reciente (esto también instalaráComposableAsync.Core
)
-
Haga clic derecho en el
SellingPartnerAPI.SellerAPI.Test
archiva y elige Gestione los paquetes NuGet. Instala el Nunit 2.6.4 paquete.Instalación manual de los paquetes NuGet
En algunos casos (por ejemplo, utilizando IOS), aparecen las versiones requeridas en los paquetes NuGet, pero puedes encontrarte con un error. En este caso, debes añadir manualmente los paquetes desde la carpeta de paquetes del sistema de archivos:
- En
Sellers_CsharpCL
, ve a la carpeta.sln
de la biblioteca que has generado y abre el archivo {{2}}. - Haga clic derecho en el
SellingPartnerAPI.SellerAPI
archivar y seleccionar Añadir > Referencias. - En el Referencias ventana, elige Navegar, navegue hasta
sellingpartner-api-aa csharp/src/Amazon.SellingPartnerAPIAA/bin/Debug/netstandard2.0
, elija la carpeta de la biblioteca cliente generada (por ejemplo,Sellers_CsharpCL
), luego elige paquetes y añada el paquete en el que se produce el error.
- En
-
En el
SellingPartnerAPI.SellerAPI.Test > Api
carpeta, abre el[Modelname]Tests.cs
archiva y añade el siguiente código: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
parámetros de instancia:
Nombre | Descripción | Obligatorio |
---|---|---|
ClientId | Your LWA client identifier. For more information, refer to Viewing your application information and credentials. | Sí |
ClientSecret | Your LWA client secret. For more information, refer to Viewing your application information and credentials | Sí |
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 | El URI del servidor de autenticación de LWA. | Sí |
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"")
};
```
-
Para ver la salida del código, debe convertirlo en una aplicación de consola. Para hacerlo, haga clic con el botón derecho en
SellingPartnerAPI.SellerAPI.Test
archiva y elige Opciones. -
En el Opciones de proyecto ventana, en el panel de navegación izquierdo, expanda Construir, luego elige General. En el Generación de código sección, elige Objetivo de compilación y selecciona Ejecutable con GUI. Elige BIEN.
-
Cree y ejecute el proyecto.
Solución de problemas de un SDK de C#
Errores de IRestRequest
: "RestSharp Version=105.0.0.0. Culture=neutral. PublicKevToken=598062e77f915f75
se define en un ensamblado al que no se hace referencia. Debes añadir una referencia al ensamblado {{2}}"
IRestRequest
: "RestSharp Version=105.0.0.0. Culture=neutral. PublicKevToken=598062e77f915f75
se define en un ensamblado al que no se hace referencia. Debes añadir una referencia al ensamblado {{2}}"Selecciona esta opción para ampliar la respuesta.
Actualiza el paquete {{0}} a la versión 106.12.0.0. Consulta la referencia para asegurarte de que la versión 106.12 se ha actualizado correctamente. Si sigue mostrando 105.0.0.0, elimina la versión anterior de la referencia y añade manualmente el paquete 106.12.0.0 desde la carpeta de paquetes que contiene la biblioteca cliente generada."No se puede encontrar el tipo o nombre del espacio de nombres {{0}} (¿falta una directiva de uso o una referencia de ensamblaje?)"
Selecciona esta opción para ampliar la respuesta.
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
. -
En la ventana de referencias de .Net Assembly, elige
browse
**. -
Navigate to the generated client library folder in local → packages and add the specific package for Newtonsoft.
"Mensaje: No se ha podido cargar el tipo de campo SellingPartnerAPI.servicesApi.Client.ApiClient:rateLimiter
(3) debido a: No se ha podido cargar el archivo o el ensamblado ComposableAsync.Core, Version=1.1.1.0, Culture=neutral, PublicKeyToken=null
o una de sus dependencias".
SellingPartnerAPI.servicesApi.Client.ApiClient:rateLimiter
(3) debido a: No se ha podido cargar el archivo o el ensamblado ComposableAsync.Core, Version=1.1.1.0, Culture=neutral, PublicKeyToken=null
o una de sus dependencias".Selecciona esta opción para ampliar la respuesta.
Si recibes este error después de compilar y ejecutar el código, entonces el paquete de dependencias ComposableAsync.Core
se ha descargado pero no se ha incluido como referencia. Asegúrate de añadir manualmente la dll como referencia.
Problemas de asignación con modelos
Selecciona esta opción para ampliar la respuesta.
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()
: no se ha encontrado ningún método adecuado para sustituir".
HttpRequestHeaders.ToJson()
: no se ha encontrado ningún método adecuado para sustituir".Selecciona esta opción para ampliar la respuesta.
Modifica la palabra clave override
con virtual
. Declara los métodos como virtual
para que puedan anularse.
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
"El nombre BaseValidate
no existe en el contexto actual"
BaseValidate
no existe en el contexto actual"Selecciona esta opción para ampliar la respuesta.
Quita los comentarios de los métodos mencionados en la clase:
// IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
// {
// foreach (var x in BaseValidate(validationContext))
// yield return x;
// yield break;
// }
Updated 23 days ago