Tutoriel : Automatisez vos appels SP-API à l'aide d'un SDK C#

Automatisez vos appels SP-API grâce à l'échange de jetons et à l'authentification Login with Amazon (LWA).

Ce didacticiel vous fournit toutes les informations nécessaires pour générer un SDK C# avec échange de jetons Login with Amazon (LWA) et une authentification pour créer votre application.

Vous pouvez utiliser ce SDK pour intégrer les fonctionnalités de la place de marché Amazon à vos applications, notamment l'accès aux informations sur les produits, la gestion des commandes, la gestion des expéditions, etc.

Didacticiel

Le didacticiel suivant vous aidera à configurer votre propre SDK C# pour automatiser les appels SP-API.

Conditions préalables

Pour terminer ce didacticiel, vous devez remplir les prérequis suivants :

  • Une application hybride ou SP-API en état de brouillon ou de publication
  • Logiciel d'environnement de développement intégré (IDE) (cette procédure pas à pas utilise Visual Studio IDE sur le système d'exploitation 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.

Configurez ensuite votre espace de travail pour le didacticiel.

Étape 1 Configurez votre espace de travail

  1. Sur votre disque local, créez un répertoire pour ce projet et nommez-le SwaggerToCL.

  2. Téléchargez les outils suivants.

  3. Exécutez la commande suivante pour télécharger le générateur de code 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
  4. Copier swagger-codegen-cli.jar dans votre répertoire local C:\\SwaggerToCL.

  5. In GitHub, go to https://github.com/amzn/selling-partner-api-models/tree/main/models and use the following command to clone the selling-partner-api-models repository to your local directory C:\\SwaggerToCL.

    git clone https://github.com/amzn/selling-partner-api-models
  6. 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 into C:\\SwaggerToCL. This tutorial uses the Sellers.json file.

  7. In GitHub, go to https://github.com/amzn/selling-partner-api-models/tree/main/clients/sellingpartner-api-aa-csharp and download the sellingpartner-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.

Étape 2 Générez un SDK C# avec échange de jetons LWA et authentification

  1. Ouvrez Visual Studio.

  2. Dans le sellingpartner-api-aa-csharp dossier, sélectionnez SellingPartnerAPIAuthAndAuthCSharp.sln fichier et compilez-le à l'aide du construire option dans Visual Studio. Cela génère le Amazon.SellingPartnerAPIAA.dll assemblage dans le dossier sellingpartner-api-aa-csharp\\src\\Amazon.SellingPartnerAPIAA\\bin\\Debug\\netstandard2.0.

  3. Ouvrez un terminal et exécutez les commandes suivantes pour générer la bibliothèque cliente C#. Le nom de package par défaut pour la bibliothèque cliente générée est Swagger.IO. Ces commandes génèrent les bibliothèques clientes avec leurs noms d'API respectifs comme nom de package au lieu de Swagger.IO.

    • Dans C:\\SwaggerToCL, créez un fichier JSON nommé csharpConfig.json, ouvrez un éditeur et ajoutez le code suivant. Pour packageName, utilisez le même nom que l'API pour laquelle vous souhaitez générer la bibliothèque cliente :
    {"packageName":"SellingPartnerAPI.SellerAPI","targetFramework":"v4.7.2"}

    Exécutez cette commande pour générer du code C# avec un nom de package personnalisé :

    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

    Cette commande utilise Sellers.json pour générer du code 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.json

    Le SDK est créé dans C:\\SwaggerToCL\\Sellers_CsharpCL. L'étape suivante consiste à écrire l'application proprement dite et à se connecter à l'API SP à l'aide du SDK C# généré.

Étape 3 Connectez-vous à l'API Selling Partner à l'aide du SDK C# généré

  1. 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 is SellingPartnerAPI.SellerAPI.sln.

  2. Cliquez avec le bouton droit SellingPartnerAPI.SellerAPI fichier et sélectionnez Ajouter > Références.

  3. Dans le Références fenêtre, choisissez Naviguez, accédez à sellingpartner-api-aa csharp/src/Amazon.SellingPartnerAPIAA/bin/Debug/netstandard2.0 et choisissez Amazon.SellingPartnerAPIAA.dll.

  4. Répétez les étapes 1 à 3 pour SellingPartnerAPI.SellerAPI.Test dossier.

  5. Accédez au dossier Sellers_CsharpCL de votre bibliothèque générée, cliquez avec le bouton droit de la souris sur le fichier SellingPartnerAPI.SellerAPI, sélectionnez Options > Général, puis modifiez la structure cible en structure .net v4.7 et versions ultérieures.

  6. Répétez l'étape 5 pour SellingPartnerAPI.SellerAPI.Test dossier.

  7. Cliquez avec le bouton droit SellingPartnerAPI.SellerAPI archivez et choisissez Gérer les packages NuGet. Assurez-vous de disposer des versions de package suivantes (si ce n'est pas le cas, installez les packages NuGet correspondants) :

    • JsonSubTypes 1.2.0 ou tout
    • Newtonsoft.json 12.0.3 ou tout
    • RestSharp 106.12.0
    • RateLimiter 2.2.0 ou plus récent (cela installera également ComposableAsync.Core)
  8. Cliquez avec le bouton droit SellingPartnerAPI.SellerAPI.Test archivez et choisissez Gérer les packages NuGet. Installez le Nunit 2.6.4 colis.

    📘

    Installation manuelle des packages NuGet

    Dans certains scénarios (par exemple, avec iOS), les versions requises dans les packages NuGet apparaissent, mais vous pouvez rencontrer une erreur. Dans ce cas, vous devez ajouter manuellement les packages depuis le dossier des packages dans le système de fichiers :

    1. Dans Sellers_CsharpCL, accédez au dossier .sln de votre bibliothèque générée et ouvrez le fichier {{2}}.
    2. Cliquez avec le bouton droit SellingPartnerAPI.SellerAPI fichier et sélectionnez Ajouter > Références.
    3. Dans le Références fenêtre, choisissez Naviguez, accédez à sellingpartner-api-aa csharp/src/Amazon.SellingPartnerAPIAA/bin/Debug/netstandard2.0, choisissez le dossier de bibliothèque client généré (par exemple, Sellers_CsharpCL), puis choisissez paquets et ajoutez le package pour lequel vous rencontrez l'erreur.
  9. Dans le SellingPartnerAPI.SellerAPI.Test > Api dossier, ouvrez le [Modelname]Tests.cs fichier et ajoutez le code suivant :

    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 paramètres d'instance :

NomDescriptionObligatoire
ClientIdYour LWA client identifier. For more information, refer to Viewing your application information and credentials.Oui
ClientSecretYour LWA client secret. For more information, refer to Viewing your application information and credentialsOui
RefreshTokenThe 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.
ScopesThe 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.
EndpointURI du serveur d'authentification LWA.Oui
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"")
};
```
  1. Pour afficher la sortie du code, vous devez le convertir en application console. Pour ce faire, cliquez avec le bouton droit sur SellingPartnerAPI.SellerAPI.Test archivez et choisissez Options.

  2. Sur le Options du projet fenêtre, dans le volet de navigation de gauche, développez Construire, puis choisissez Général. Dans le Génération de code section, choisissez Compiler la cible et sélectionnez Exécutable avec interface graphique. Choisissez OK..

  3. Créez et exécutez le projet.

Résoudre les problèmes liés à un SDK C#

Erreurs IRestRequest : “RestSharp Version=105.0.0.0. Culture=neutral. PublicKevToken=598062e77f915f75 est défini dans un assemblage qui n'est pas référencé. Vous devez ajouter une référence à l'assemblage {{2}}”

Sélectionnez pour développer la réponse. Mettez à jour le package {{0}} vers la version 106.12.0.0. Vérifiez la référence pour vous assurer que la version 106.12 a été correctement mise à jour. Si la version 105.0.0.0 s'affiche toujours, supprimez l'ancienne version de la référence et ajoutez le package 106.12.0.0 manuellement depuis le dossier des packages contenant la bibliothèque client générée.

“Le nom du type ou de l'espace de noms {{0}} est introuvable (vous manque-t-il une directive d'utilisation ou une référence d'assemblage ?)”

Sélectionnez pour développer la réponse.

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:

  1. In Visual Studio, right-click your generated SDK package and choose Add, then References.

  2. Dans la fenêtre des références de .Net Assembly, sélectionnez browse**.

  3. Navigate to the generated client library folder in localpackages and add the specific package for Newtonsoft.

“Message : impossible de charger le type de champ SellingPartnerAPI.servicesApi.Client.ApiClient:rateLimiter (3) en raison de : impossible de charger le fichier ou l'assemblage ComposableAsync.Core, Version=1.1.1.0, Culture=neutral, PublicKeyToken=null ou l'une de ses dépendances.”

Sélectionnez pour développer la réponse.

Si vous recevez cette erreur après avoir créé et exécuté votre code, le package de dépendances ComposableAsync.Core a été téléchargé mais n'a pas été inclus comme référence. Assurez-vous d'ajouter manuellement la bibliothèque dll comme référence.

Problèmes de mappage liés aux modèles

Sélectionnez pour développer la réponse.

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() : aucune méthode appropriée à ignorer n'a été trouvée.”

Sélectionnez pour développer la réponse.

Modifiez le mot-clé override avec virtual. Déclarez les méthodes comme virtual afin qu'elles puissent être ignorées.

public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); }

“Le nom BaseValidate n'existe pas dans le contexte actuel”

Sélectionnez pour développer la réponse.

Supprimez les commentaires des méthodes mentionnées dans la classe :

// IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) // { // foreach (var x in BaseValidate(validationContext)) // yield return x; // yield break; // }

Cette page vous a-t-elle été utile ?