Skip to content

Repository files navigation

☕Amazon Selling Partner API C# 🚀 .NETNuGetGitter Chat

This is an API Binding in .Net C# for the new Amazon Selling Partner API.

This library is based on the output of swagger-codegen with the OpenAPI files provided by Amazon (Models) and has been modified by the contributors.

The purpose of this package is to have an easy way of getting started with the Amazon Selling Partner API using C#. You can watch this 📷 YouTube 📣 video to get started quickly.


Requirements


Installation NuGet

Install-Package CSharpAmazonSpAPI

Tasks

Seller

Vendor


Keys

To get all the keys you need, follow these steps:

  1. Create and configure IAM policies and entities
  2. Register your Application
  3. Authorize Selling Partner API applications
NameDescription
MarketplaceMarketplace region List of Marketplaces
ClientIdYour amazon app id
ClientSecretYour amazon app secret
RefreshTokenCheck how to get RefreshToken

For more information about keys, check the Amazon developer documentation. If you are not registered as a developer, please Register to be able to create an application.


Usage

Please be aware there has been a change to the Orders.GetOrderAddress() method please reference the new sample code for more details.

Configuration

You can configure a connection as shown below. See Here for the relevant code file.

AmazonConnectionamazonConnection=newAmazonConnection(newAmazonCredential(){ClientId="amzn1.application-XXX-client.XXXXXXXXXXXXXXXXXXXXXXXXXXXX",ClientSecret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",RefreshToken="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",MarketPlace=MarketPlace.UnitedArabEmirates,//MarketPlace.GetMarketPlaceByID("A2VIGQ35RCS4UG") });orAmazonConnection amazonConnection =newAmazonConnection(newAmazonCredential(){ClientId="amzn1.application-XXX-client.XXXXXXXXXXXXXXXXXXXXXXXXXXXX",ClientSecret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",RefreshToken="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",MarketPlaceID="A2VIGQ35RCS4UG"});

Configuration using a proxy

Please see here for the relevant code file.

AmazonConnectionamazonConnection=newAmazonConnection(newAmazonCredential(){ClientId="amzn1.application-XXX-client.XXXXXXXXXXXXXXXXXXXXXXXXXXXX",ClientSecret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",RefreshToken="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",MarketPlaceID="A2VIGQ35RCS4UG",ProxyAddress="http(s)://xxx.xxx.xxx.xxx:xxxx",});
  • Assign your proxy address to the ProxyAddress Property and you'll be able to use a proxy account.

This is not required and will operate normally without the ProxyAddress being set.

Order List

For more order samples, please check Here.

ParameterOrderListsearchOrderList=newParameterOrderList();searchOrderList.CreatedAfter=DateTime.UtcNow.AddMinutes(-600000);searchOrderList.OrderStatuses=newList<OrderStatuses>();searchOrderList.OrderStatuses.Add(OrderStatuses.Canceled);varorders=amazonConnection.Orders.GetOrders(searchOrderList);

Order List with parameter

ParameterOrderListsearchOrderList=newParameterOrderList();searchOrderList.CreatedAfter=DateTime.UtcNow.AddHours(-24);searchOrderList.OrderStatuses=newList<OrderStatuses>();searchOrderList.OrderStatuses.Add(OrderStatuses.Unshipped);searchOrderList.MarketplaceIds=newList<string>{MarketPlace.UnitedArabEmirates.ID};varorders=amazonConnection.Orders.GetOrders(searchOrderList);

Order List with parameter including PII data Simple

varparameterOrderList=newParameterOrderList{CreatedAfter=DateTime.UtcNow.AddHours(-24),OrderStatuses=newList<OrderStatuses>{OrderStatuses.Unshipped},MarketplaceIds=newList<string>{MarketPlace.UnitedArabEmirates.ID},IsNeedRestrictedDataToken=true};varorders=_amazonConnection.Orders.GetOrders(parameterOrderList);

Order List with parameter including PII data — Advanced (if you want to get specific data elements only)

varparameterOrderList=newParameterOrderList{CreatedAfter=DateTime.UtcNow.AddHours(-24),OrderStatuses=newList<OrderStatuses>{OrderStatuses.Unshipped},MarketplaceIds=newList<string>{MarketPlace.UnitedArabEmirates.ID},IsNeedRestrictedDataToken=true,RestrictedDataTokenRequest=newCreateRestrictedDataTokenRequest{restrictedResources=newList<RestrictedResource>{newRestrictedResource{method=Method.GET.ToString(),path=ApiUrls.OrdersApiUrls.Orders,dataElements=newList<string>{"buyerInfo","shippingAddress"}}}}};varorders=_amazonConnection.Orders.GetOrders(parameterOrderList);

Order List data from Sandbox

AmazonConnectionamazonConnection=newAmazonConnection(newAmazonCredential(){ClientId="amzn1.application-XXX-client.XXXXXXXXXXXXXXXXXXXXXXXXXXXX",ClientSecret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",RefreshToken="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",Environment=Environments.Sandbox});varorders=amazonConnection.Orders.GetOrders(newFikaAmazonAPI.Parameter.Order.ParameterOrderList{TestCase=Constants.TestCase200});

Report List

For more report samples, please check Here.

varparameters=newParameterReportList();parameters.pageSize=100;parameters.reportTypes=newList<ReportTypes>();parameters.reportTypes.Add(ReportTypes.GET_AFN_INVENTORY_DATA);parameters.marketplaceIds=newList<string>();parameters.marketplaceIds.Add(MarketPlace.UnitedArabEmirates.ID);varreports=amazonConnection.Reports.GetReports(parameters);

Custom Report

varparameters=newParameterCreateReportSpecification();parameters.reportType=ReportTypes.GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL;parameters.dataStartTime=DateTime.UtcNow.AddDays(-30);parameters.dataEndTime=DateTime.UtcNow.AddDays(-10);parameters.marketplaceIds=newMarketplaceIds();parameters.marketplaceIds.Add(MarketPlace.UnitedArabEmirates.ID);parameters.reportOptions=newAmazonSpApiSDK.Models.Reports.ReportOptions();varreport=amazonConnection.Reports.CreateReport(parameters);

Get Report with PII

//use this method automatically know if the report are RDT or notvardata2=amazonConnection.Reports.CreateReportAndDownloadFile(ReportTypes.GET_EASYSHIP_DOCUMENTS,startDate,null,null);// OR USE this method to get the document and pass parameter isRestrictedReport = true in case the report will return PII datavardata=amazonConnection.Reports.GetReportDocument("50039018869997",true);

Report Manager 🚀🧑‍🚀✨

An easy way to get the report you need and convert the file returned from Amazon to a class or list. This feature is only available for some reports, as it takes significant effort to cover all report types.

ReportManagerreportManager=newReportManager(amazonConnection);varproducts=reportManager.GetProducts();//GET_MERCHANT_LISTINGS_ALL_DATAvarinventoryAging=reportManager.GetInventoryAging();//GET_FBA_INVENTORY_AGED_DATAvarordersByDate=reportManager.GetOrdersByOrderDate(90);//GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERALvarordersByLastUpdate=reportManager.GetOrdersByLastUpdate(90);//GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERALvarsettlementOrder=reportManager.GetSettlementOrder(90);//GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2varreturnMFNOrder=reportManager.GetReturnMFNOrder(90);//GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATEvarreturnFBAOrder=reportManager.GetReturnFBAOrder(90);//GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATAvarreimbursementsOrder=reportManager.GetReimbursementsOrder(180);//GET_FBA_REIMBURSEMENTS_DATAvarfeedbacks=reportManager.GetFeedbackFromDays(180);//GET_SELLER_FEEDBACK_DATAvarLedgerDetails=reportManager.GetLedgerDetailAsync(10);//GET_LEDGER_DETAIL_VIEW_DATAvarUnsuppressedInventory=reportManager.GetUnsuppressedInventoryDataAsync().ConfigureAwait(false).GetAwaiter().GetResult();//GET_FBA_MYI_UNSUPPRESSED_INVENTORY_DATA

Report GET_MERCHANT_LISTINGS_ALL_DATA sample

varparameters=newParameterCreateReportSpecification();parameters.reportType=ReportTypes.GET_MERCHANT_LISTINGS_ALL_DATA;parameters.marketplaceIds=newMarketplaceIds();parameters.marketplaceIds.Add(MarketPlace.UnitedArabEmirates.ID);parameters.reportOptions=newFikaAmazonAPI.AmazonSpApiSDK.Models.Reports.ReportOptions();varreportId=amazonConnection.Reports.CreateReport(parameters);varfilePath=string.Empty;stringReportDocumentId=string.Empty;while(string.IsNullOrEmpty(ReportDocumentId)){Thread.Sleep(1000*60);varreportData=amazonConnection.Reports.GetReport(reportId);if(!string.IsNullOrEmpty(reportData.ReportDocumentId)){filePath=amazonConnection.Reports.GetReportFile(reportData.ReportDocumentId);break;}}//filePath for report

Product GetCatalogItem Version 2022-04-01

vardata=awaitamazonConnection.CatalogItem.GetCatalogItem202204Async(newParameter.CatalogItems.ParameterGetCatalogItem{ASIN="B00JK2YANC",includedData=new[]{IncludedData.attributes,IncludedData.salesRanks,IncludedData.summaries,IncludedData.productTypes,IncludedData.relationships,IncludedData.dimensions,IncludedData.identifiers,IncludedData.images}});

Product SearchCatalogItems Version 2022-04-01

vardata=awaitamazonConnection.CatalogItem.SearchCatalogItems202204Async(newParameter.CatalogItems.ParameterSearchCatalogItems202204{keywords=new[]{"vitamin c"},includedData=new[]{IncludedData.attributes,IncludedData.salesRanks,IncludedData.summaries,IncludedData.productTypes,IncludedData.relationships,IncludedData.dimensions,IncludedData.identifiers,IncludedData.images}});

Product Pricing, For more Pricing sample please check Here.

vardata=amazonConnection.ProductPricing.GetPricing(newParameter.ProductPricing.ParameterGetPricing(){MarketplaceId=MarketPlace.UnitedArabEmirates.ID,Asins=newstring[]{"B00CZC5F0G"}});

Product Competitive Price

vardata=amazonConnection.ProductPricing.GetCompetitivePricing(newParameter.ProductPricing.ParameterGetCompetitivePricing(){MarketplaceId=MarketPlace.UnitedArabEmirates.ID,Asins=newstring[]{"B00CZC5F0G"},});

GetFeaturedOfferExpectedPriceBatch

varpriceDemo=newProductPricingSample(amazonConnection);awaitpriceDemo.GetFeaturedOfferExpectedPriceBatch();

Notifications — Create Destination

For more notification samples, please check Here.

//EventBridgevardata=amazonConnection.Notification.CreateDestination(newNotifications.CreateDestinationRequest(){Name="CompanyName",ResourceSpecification=newNotifications.DestinationResourceSpecification(){EventBridge=newNotifications.EventBridgeResourceSpecification("us-east-2","999999999")}});//SQSvardataSqs=amazonConnection.Notification.CreateDestination(newNotifications.CreateDestinationRequest(){Name="CompanyName_AE",ResourceSpecification=newNotifications.DestinationResourceSpecification{Sqs=newNotifications.SqsResource("arn:aws:sqs:us-east-2:9999999999999:NAME")}});

Notifications — Create Subscription

For more notification samples, please check Here.

//SQSvarresult=amazonConnection.Notification.CreateSubscription(newParameterCreateSubscription(){destinationId="xxxxxxxxxxxxxxx",// take this from CreateDestination or GetDestinations response notificationType=NotificationType.ANY_OFFER_CHANGED,// or B2B_ANY_OFFER_CHANGED for B2B pricespayloadVersion="1.0"});

Notifications — Read Messages

varSQS_URL=Environment.GetEnvironmentVariable("SQS_URL");varparam=newParameterMessageReceiver(Environment.GetEnvironmentVariable("AccessKey"),Environment.GetEnvironmentVariable("SecretKey"),SQS_URL,Amazon.RegionEndpoint.USEast2,WaitTimeSeconds:20);// Enable SQS long polling to reduce empty receives and costvarmessageReceiver=newCustomMessageReceiver();// Use CancellationToken for graceful shutdown and wrap in a restart loop// so the listener recovers from transient errors automatically.varcts=newCancellationTokenSource();while(!cts.Token.IsCancellationRequested){try{// Static method — no instance neededawaitNotificationService.StartReceivingNotificationMessagesAsync(param,messageReceiver,cancellationToken:cts.Token);}catch(OperationCanceledException)when(cts.Token.IsCancellationRequested){break;// Graceful shutdown}catch(Exceptionex){Console.WriteLine($"Notification listener crashed, restarting in 10s: {ex.Message}");awaitTask.Delay(TimeSpan.FromSeconds(10),cts.Token);}}publicclassCustomMessageReceiver:IMessageReceiver{// Track processed notification IDs to handle SQS duplicate deliveryprivatereadonlyConcurrentDictionary<string,byte>_processedNotificationIds=new();privatereadonlyConcurrentQueue<string>_idQueue=new();privateconstintMaxTrackedIds=10_000;publicvoidErrorCatch(Exceptionex){Console.WriteLine($"Notification error: {ex.Message}");}publicvoidNewMessageRevicedTriger(NotificationMessageResponcemessage){// Deduplicate: SQS standard queues may deliver the same message more than oncevarnotificationId=message?.NotificationMetadata?.NotificationId;if(notificationId!=null&&!_processedNotificationIds.TryAdd(notificationId,0))return;// Cap the dedup cache so it doesn't grow foreverif(notificationId!=null){_idQueue.Enqueue(notificationId);while(_idQueue.Count>MaxTrackedIds&&_idQueue.TryDequeue(outvaroldId))_processedNotificationIds.TryRemove(oldId,out_);}//Your Code here}}

Notifications — End-to-End SQS Setup

Complete workflow following the Amazon SQS notification setup guide. Before running this code, grant SP-API permission to write to your SQS queue in the AWS Console.

// Step 3: Create a destination (grantless operation — no seller authorization needed)vardestination=amazonConnection.Notification.CreateDestination(newNotifications.CreateDestinationRequest(){Name="CompanyName_SQS",ResourceSpecification=newNotifications.DestinationResourceSpecification{Sqs=newNotifications.SqsResource("arn:aws:sqs:us-east-2:9999999999999:NAME")}});// Step 4: Create a subscription using the destinationId from Step 3// processingDirective is optional — only supported for ANY_OFFER_CHANGED and ORDER_CHANGEvarsubscription=amazonConnection.Notification.CreateSubscription(newParameterCreateSubscription(){destinationId=destination.DestinationId,notificationType=NotificationType.ANY_OFFER_CHANGED,payloadVersion="1.0",processingDirective=newNotifications.ProcessingDirective{EventFilter=newNotifications.EventFilter{EventFilterType="ANY_OFFER_CHANGED",MarketplaceIds=newList<string>{"ATVPDKIKX0DER"},AggregationSettings=newNotifications.AggregationSettings{AggregationTimePeriod=Notifications.AggregationTimePeriod.FiveMinutes}}}});

Feed Submit

Here is a full sample for submitting a feed to change price, generate XML, and get the final processing report, same as in the documentation.

Note: Not all feed types are implemented yet. All classes are partial for easy extension — you can generate XML outside the library and use it to submit data. Currently supported: submit existing product, change quantity, and change price. Most XSD files are listed in Source\FikaAmazonAPI\ConstructFeed\xsd to help you generate classes for your app.

Feed Submit — Change Price

For more feed samples, please check Here.

ConstructFeedServicecreateDocument=newConstructFeedService("{SellerID}","1.02");varlist=newList<PriceMessage>();list.Add(newPriceMessage(){SKU="8201031206122...",StandardPrice=newStandardPrice(){currency=amazonConnection.GetCurrentMarketplace.CurrencyCode.ToString(),Value=(201.0522M).ToString("0.00")}});createDocument.AddPriceMessage(list);varxml=createDocument.GetXML();varfeedID=amazonConnection.Feed.SubmitFeed(xml,FeedType.POST_PRODUCT_PRICING_DATA);Thread.Sleep(1000*30);varfeedOutput=amazonConnection.Feed.GetFeed(feedID);varoutPut=amazonConnection.Feed.GetFeedDocument(feedOutput.ResultFeedDocumentId);varreportOutpit=outPut.Url;varprocessingReport=amazonConnection.Feed.GetFeedDocumentProcessingReport(outPut.Url);

JSON_LISTINGS_FEED Submit for change price

stringsellerId="SellerId";stringsku="SKU";decimalprice=19.99m;stringjsonString=$@"{{ ""header"": {{ ""sellerId"": ""{sellerId}"", ""version"": ""2.0"", ""issueLocale"": ""en_US"" }}, ""messages"": [ {{ ""messageId"": 1, ""sku"": ""{sku}"", ""operationType"": ""PATCH"", ""productType"": ""PRODUCT"", ""patches"": [ {{ ""op"": ""replace"", ""path"": ""/attributes/purchasable_offer"", ""value"": [ {{ ""currency"": ""USD"", ""our_price"": [ {{ ""schedule"": [ {{ ""value_with_tax"": {price} }} ] }} ] }} ] }} ] }} ]}}";stringfeedID=awaitamazonConnection.Feed.SubmitFeedAsync(jsonString,FeedType.JSON_LISTINGS_FEED,newList<string>(){MarketPlace.UnitedArabEmirates.ID},null,ContentType.JSON);Thread.Sleep(1000*60);varfeedOutput=amazonConnection.Feed.GetFeed(feedID);varoutPut=amazonConnection.Feed.GetFeedDocument(feedOutput.ResultFeedDocumentId);varreportOutpit=outPut.Url;varprocessingReport=awaitamazonConnection.Feed.GetJsonFeedDocumentProcessingReportAsync(output);

Website authorization workflow.

[HttpGet("AuthorizeAmazon")]publicasyncTask<IActionResult>AuthorizeAmazon(){// Step 2-5 of the website authorization workflow.// Step 2-3: Amazon calls our log-in URI with amazon_callback_uri.varamazonCallbackUri=Request.Query["amazon_callback_uri"].ToString();if(!string.IsNullOrEmpty(amazonCallbackUri)){varamazonState=Request.Query["amazon_state"].ToString();varversion=configuration["FikaAmazonAPI:AuthorizeVersion"];varredirectUri=configuration["FikaAmazonAPI:AmazonCallbackUri"];vargeneratedState=Guid.NewGuid().ToString("N");Response.Cookies.Append("amazon_oauth_state",generatedState,newCookieOptions{HttpOnly=true,Secure=true,SameSite=SameSiteMode.Lax,Expires=DateTimeOffset.UtcNow.AddMinutes(5)});varquery=newDictionary<string,string?>{["redirect_uri"]=redirectUri,["amazon_state"]=amazonState,["state"]=generatedState};if(!string.IsNullOrEmpty(version)){query["version"]=version;}Response.Headers["Referrer-Policy"]="no-referrer";varredirectUrl=QueryHelpers.AddQueryString(amazonCallbackUri,query!);returnRedirect(redirectUrl);}// Step 4-5: Amazon redirects back to our redirect_uri with authorization code.varstate=Request.Query["state"].ToString();varsellingPartnerId=Request.Query["selling_partner_id"].ToString();varmwsAuthToken=Request.Query["mws_auth_token"].ToString();varcode=Request.Query["spapi_oauth_code"].ToString();varstoredState=Request.Cookies["amazon_oauth_state"];if(string.IsNullOrEmpty(state)||storedState!=state){returnBadRequest("Invalid state");}Response.Cookies.Delete("amazon_oauth_state");if(string.IsNullOrEmpty(code)){returnBadRequest("Missing spapi_oauth_code");}varclientId=configuration["FikaAmazonAPI:ClientId"];varclientSecret=configuration["FikaAmazonAPI:ClientSecret"];varcallbackUri=configuration["FikaAmazonAPI:AmazonCallbackUri"];usingvarhttpClient=newHttpClient();varform=newFormUrlEncodedContent(newDictionary<string,string>{["grant_type"]="authorization_code",["code"]=code,["client_id"]=clientId??string.Empty,["client_secret"]=clientSecret??string.Empty,["redirect_uri"]=callbackUri??string.Empty});usingvarresponse=awaithttpClient.PostAsync("https://api.amazon.com/auth/o2/token",form);varresponseBody=awaitresponse.Content.ReadAsStringAsync();if(!response.IsSuccessStatusCode){returnBadRequest(responseBody);}usingvardocument=JsonDocument.Parse(responseBody);varrefreshToken=document.RootElement.GetProperty("refresh_token").GetString();varaccessToken=document.RootElement.GetProperty("access_token").GetString();returnJson(new{state,selling_partner_id=sellingPartnerId,mws_auth_token=mwsAuthToken,refresh_token=refreshToken,access_token=accessToken});}

Feed Submit — Change Quantity

ConstructFeedServicecreateDocument=newConstructFeedService("{SellerID}","1.02");varlist=newList<InventoryMessage>();list.Add(newInventoryMessage(){SKU="82010312061.22...",Quantity=2,FulfillmentLatency="11",});createDocument.AddInventoryMessage(list);varxml=createDocument.GetXML();varfeedID=amazonConnection.Feed.SubmitFeed(xml,FeedType.POST_INVENTORY_AVAILABILITY_DATA);Thread.Sleep(1000*30);varfeedOutput=amazonConnection.Feed.GetFeed(feedID);varoutPut=amazonConnection.Feed.GetFeedDocument(feedOutput.ResultFeedDocumentId);varreportOutpit=outPut.Url;varprocessingReport=amazonConnection.Feed.GetFeedDocumentProcessingReport(outPut.Url);

Feed Submit — Change Product Image

publicvoidSubmitFeedProductImage(){ConstructFeedServicecreateDocument=newConstructFeedService("A3J37AJU4O9RHK","1.02");varlist=newList<ProductImageMessage>();list.Add(newProductImageMessage(){SKU="8201031206122...",ImageLocation="http://xxxx.com/1.jpeg",ImageType=ImageType.Main});createDocument.AddProductImageMessage(list);varxml=createDocument.GetXML();varfeedID=amazonConnection.Feed.SubmitFeed(xml,FeedType.POST_PRODUCT_IMAGE_DATA);}

Feed Submit — Fulfillment Data (add tracking number for shipment)

ConstructFeedServicecreateDocument=newConstructFeedService("{sellerId}","1.02");varlist=newList<OrderFulfillmentMessage>();list.Add(newOrderFulfillmentMessage(){AmazonOrderID="{orderId}",FulfillmentDate=DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"),FulfillmentData=newFulfillmentData(){CarrierName="Correos Express",ShippingMethod="ePaq",ShipperTrackingNumber="{trackingNumber}"}});createDocument.AddOrderFulfillmentMessage(list);varxml=createDocument.GetXML();varfeedID=amazonConnection.Feed.SubmitFeed(xml,FeedType.POST_ORDER_FULFILLMENT_DATA);

Feed Submit — Order Adjustments

publicvoidSubmitFeedOrderAdjustment(){ConstructFeedServicecreateDocument=newConstructFeedService("A3J37AJU4O9RHK","1.02");varlist=newList<OrderAdjustmentMessage>();list.Add(newOrderAdjustmentMessage(){AmazonOrderID="AMZ1234567890123",ActionType=AdjustmentActionType.Refund,AdjustedItem=newList<AdjustedItem>(){newAdjustedItem(){AmazonOrderItemCode="52986411826454",AdjustmentReason=AdjustmentReason.CustomerCancel,DirectPaymentAdjustments=newList<DirectPaymentAdjustments>(){newDirectPaymentAdjustments(){Component=newList<DirectPaymentAdjustmentsComponent>(){newDirectPaymentAdjustmentsComponent(){DirectPaymentType="Credit Card Refund",Amount=newCurrencyAmount(){Value=10.50M,currency=amazonConnection.GetCurrentMarketplace.CurrencyCode}}}}}}}});createDocument.AddOrderAdjustmentMessage(list);varxml=createDocument.GetXML();varfeedID=amazonConnection.Feed.SubmitFeed(xml,FeedType.POST_PAYMENT_ADJUSTMENT_DATA);}

Usage Plans and Rate Limits in the Selling Partner API

Please read this doc to get all information about this limitation https://developer-docs.amazon.com/sp-api/docs/usage-plans-and-rate-limits

We calculate the waiting time by reading the x-amzn-RateLimit-Limit header:

int sleepTime = (int)((1 / header["x-amzn-RateLimit-Limit"] ) * 1000);

You can also disable the library's rate limit handling by setting IsActiveLimitRate = false in AmazonCredential:

varamazonConnection=newAmazonConnection(newAmazonCredential(){..IsActiveLimitRate=false});

Enable Debug Mode

You can enable logging for all HTTP requests and responses by setting IsDebugMode = true in AmazonCredential:

varamazonConnection=newAmazonConnection(newAmazonCredential(){..IsDebugMode=true});

Get Restrictions Before Adding New Listings

varresult=amazonConnection.Restrictions.GetListingsRestrictions(newParameter.Restrictions.ParameterGetListingsRestrictions{asin="AAAAAAAAAA",sellerId="AXXXXXXXXXXXX"});

Create shipment operation from MerchantFulfillment

ShipmentRequestDetailsshipmentRequestDetails=newShipmentRequestDetails(){AmazonOrderId="999-9999-999999",ItemList=newItemList(){newFikaAmazonAPI.AmazonSpApiSDK.Models.MerchantFulfillment.Item(){OrderItemId="52986411826454",Quantity=1}},ShipFromAddress=newAddress(){AddressLine1="300 St",City="City",PostalCode="48123",Email="[mail@yahoo.com](mailto:mail@yahoo.com)",Phone="999999999",StateOrProvinceCode="MI",CountryCode="US",Name="FirstName LastName"},PackageDimensions=newPackageDimensions(){Height=10,Width=10,Length=10,Unit=UnitOfLength.Inches},Weight=newWeight(){Value=10,Unit=UnitOfWeight.Oz},ShippingServiceOptions=newShippingServiceOptions(){DeliveryExperience=DeliveryExperienceType.NoTracking,CarrierWillPickUp=false,CarrierWillPickUpOption=CarrierWillPickUpOption.ShipperWillDropOff}};varshipmentRequest=newCreateShipmentRequest(shipmentRequestDetails,shippingServiceId:"UPS_PTP_2ND_DAY_AIR",shippingServiceOfferId:"WHgxtyn6qjGGaC");varshipmentResponse=amazonConnection.MerchantFulfillment.CreateShipment(shipmentRequest);

ProductTypes SearchDefinitions

varlist=amazonConnection.ProductType.SearchDefinitionsProductTypes(newParameter.ProductTypes.SearchDefinitionsProductTypesParameter(){keywords=newList<string>{String.Empty},});

ProductTypes GetDefinitions

vardef=amazonConnection.ProductType.GetDefinitionsProductType(newParameter.ProductTypes.GetDefinitionsProductTypeParameter(){productType="PRODUCT",requirements=Requirements.LISTING,locale=AmazonSpApiSDK.Models.ProductTypes.LocaleEnum.en_US});

Sales Performance Sample

DateTimequeryStart=DateTime.UtcNow.AddDays(-11).Date;DateTimequeryEnd=DateTime.UtcNow;varparameters=newParameterGetOrderMetrics();parameters.marketplaceIds=newMarketplaceIds();parameters.marketplaceIds.Add(MarketPlace.UnitedArabEmirates.ID);parameters.interval=queryStart.ToString("yyyy-MM-ddTHH:mm:ss",CultureInfo.InvariantCulture)+"Z--"+queryEnd.ToString("yyyy-MM-ddTHH:mm:ss",CultureInfo.InvariantCulture)+"Z";parameters.granularity=Constants.GranularityEnum.Day;parameters.firstDayOfWeek=Constants.FirstDayOfWeek.monday;varsales=amazonConnection.Sales.GetOrderMetrics(parameters);

Q & A

If you have questions, please ask in GitHub discussions

discussions


ToDo

  • Improve documentation

Useful links


Contributing

  1. Fork it (https://github.com/abuzuhri/Amazon-SP-API-CSharp/fork)
  2. Clone it (git clone https://github.com/{YOUR_USERNAME}/Amazon-SP-API-CSharp)
  3. Create your feature branch (git checkout -b your_branch_name)
  4. Commit your changes (git commit -m 'Description of a commit')
  5. Push to the branch (git push origin your_branch_name)
  6. Create a new Pull Request

Notes

If you are looking for a complete Feedback solution, you might want to consider giving Soon.se a shot.


Support & Consultation

We offer consultation on everything SP-API related. Book your meeting here:

Book Meeting


Thanks

Thanks go out to everybody who worked on this package.

About

.Net C# library for the new Amazon Selling Partner API

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages