CSharpAmazonSpAPI 1.9.27

dotnet add package CSharpAmazonSpAPI --version 1.9.27
                    
NuGet\Install-Package CSharpAmazonSpAPI -Version 1.9.27
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CSharpAmazonSpAPI" Version="1.9.27" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CSharpAmazonSpAPI" Version="1.9.27" />
                    
Directory.Packages.props
<PackageReference Include="CSharpAmazonSpAPI" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CSharpAmazonSpAPI --version 1.9.27
                    
#r "nuget: CSharpAmazonSpAPI, 1.9.27"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package [email protected]
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=CSharpAmazonSpAPI&version=1.9.27
                    
Install as a Cake Addin
#tool nuget:?package=CSharpAmazonSpAPI&version=1.9.27
                    
Install as a Cake Tool

β˜•Amazon Selling Partner API C# πŸš€ .NET NuGet Gitter 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
Name Description
Marketplace Marketplace region List of Marketplaces
ClientId Your amazon app id
ClientSecret Your amazon app secret
RefreshToken Check 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

Heads-up: Amazon-side changes affecting this library

  • Catalog Items API v0 was removed by Amazon on 2025-03-31. CatalogItem.ListCatalogItems, CatalogItem.ListCatalogCategories, and CatalogItem.GetCatalogItemJson are now marked obsolete because the underlying endpoints no longer exist. Use the 2022-04-01 methods (SearchCatalogItems202204, GetCatalogItem202204) instead.
  • XML feed types (e.g. the legacy inventory feed) were turned off on 2025-07-31. If you previously submitted inventory updates with _POST_INVENTORY_AVAILABILITY_DATA_ or similar XML feed types, migrate to FeedType.JSON_LISTINGS_FEED with a JSON-Patch payload (see FeedsSample.cs).
  • Orders API v0 will be removed on 2027-03-27. All six v0 operations (getOrders, getOrder, getOrderBuyerInfo, getOrderAddress, getOrderItems, getOrderItemsBuyerInfo) will start failing on that date. For new code, prefer amazonConnection.OrdersV20260101 (Orders API v2026-01-01), which collapses those six operations into getOrder and searchOrders.
  • Address.Name (Orders v0) is now optional as of Amazon's 2025-10 release. The constructor in AmazonSpApiSDK.Models.Orders.Address no longer throws when name is null β€” handle null Name defensively in your code.

Configuration

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

AmazonConnection amazonConnection = new AmazonConnection(new AmazonCredential()
{
     ClientId = "amzn1.application-XXX-client.XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     ClientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     RefreshToken= "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     MarketPlace = MarketPlace.UnitedArabEmirates, //MarketPlace.GetMarketPlaceByID("A2VIGQ35RCS4UG") 
});

or 

AmazonConnection amazonConnection = new AmazonConnection(new AmazonCredential()
{
     ClientId = "amzn1.application-XXX-client.XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     ClientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     RefreshToken= "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     MarketPlaceID = "A2VIGQ35RCS4UG"
});

Configuration using a proxy

Please see here for the relevant code file.

The Proxy property accepts any IWebProxy implementation:

AmazonConnection amazonConnection = new AmazonConnection(new AmazonCredential()
{
     ClientId = "amzn1.application-XXX-client.XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     ClientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     RefreshToken= "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     MarketPlaceID = "A2VIGQ35RCS4UG",
     Proxy = new System.Net.WebProxy("http://xxx.xxx.xxx.xxx:xxxx"),
});

For an authenticated proxy, assign any IWebProxy implementation -- for example, a WebProxy with credentials:

AmazonConnection amazonConnection = new AmazonConnection(new AmazonCredential()
{
     ClientId = "amzn1.application-XXX-client.XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     ClientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     RefreshToken= "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     MarketPlaceID = "A2VIGQ35RCS4UG",
     Proxy = new System.Net.WebProxy("http://xxx.xxx.xxx.xxx:xxxx")
     {
         Credentials = new System.Net.NetworkCredential("username", "password")
     },
});

Proxy is not required and will operate normally without it being set.


Order List

For more order samples, please check Here.

ParameterOrderList searchOrderList = new ParameterOrderList();
searchOrderList.CreatedAfter = DateTime.UtcNow.AddMinutes(-600000);
searchOrderList.OrderStatuses = new List<OrderStatuses>();
searchOrderList.OrderStatuses.Add(OrderStatuses.Canceled);
var orders = amazonConnection.Orders.GetOrders(searchOrderList);

Order List with parameter

ParameterOrderList searchOrderList = new ParameterOrderList();
searchOrderList.CreatedAfter = DateTime.UtcNow.AddHours(-24);
searchOrderList.OrderStatuses = new List<OrderStatuses>();
searchOrderList.OrderStatuses.Add(OrderStatuses.Unshipped);
searchOrderList.MarketplaceIds = new List<string> { MarketPlace.UnitedArabEmirates.ID };

var orders = amazonConnection.Orders.GetOrders(searchOrderList);

Order List with parameter including PII data Simple

var parameterOrderList = new ParameterOrderList
        {
            CreatedAfter = DateTime.UtcNow.AddHours(-24),
            OrderStatuses = new List<OrderStatuses> { OrderStatuses.Unshipped },
            MarketplaceIds = new List<string> { MarketPlace.UnitedArabEmirates.ID },
            IsNeedRestrictedDataToken = true
        };

var orders = _amazonConnection.Orders.GetOrders(parameterOrderList);

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

var parameterOrderList = new ParameterOrderList
        {
            CreatedAfter = DateTime.UtcNow.AddHours(-24),
            OrderStatuses = new List<OrderStatuses> { OrderStatuses.Unshipped },
            MarketplaceIds = new List<string> { MarketPlace.UnitedArabEmirates.ID },
            IsNeedRestrictedDataToken = true,
            RestrictedDataTokenRequest = new CreateRestrictedDataTokenRequest
            {
                restrictedResources = new List<RestrictedResource>
                {
                    new RestrictedResource
                    {
                        method = Method.GET.ToString(),
                        path = ApiUrls.OrdersApiUrls.Orders,
                        dataElements = new List<string> { "buyerInfo", "shippingAddress" }
                    }
                }
            }
        };

var orders = _amazonConnection.Orders.GetOrders(parameterOrderList);

Order List data from Sandbox

AmazonConnection amazonConnection = new AmazonConnection(new AmazonCredential()
{
     ClientId = "amzn1.application-XXX-client.XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     ClientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     RefreshToken= "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
     Environment=Environments.Sandbox
});

var orders = amazonConnection.Orders.GetOrders
(
     new FikaAmazonAPI.Parameter.Order.ParameterOrderList
     {
         TestCase = Constants.TestCase200
     }
);

Report List

For more report samples, please check Here.

var parameters = new ParameterReportList();
parameters.pageSize = 100;
parameters.reportTypes = new List<ReportTypes>();
parameters.reportTypes.Add(ReportTypes.GET_AFN_INVENTORY_DATA);
parameters.marketplaceIds = new List<string>();
parameters.marketplaceIds.Add(MarketPlace.UnitedArabEmirates.ID);
var reports=amazonConnection.Reports.GetReports(parameters);

Custom Report

var parameters = new ParameterCreateReportSpecification();
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 = new MarketplaceIds();
parameters.marketplaceIds.Add(MarketPlace.UnitedArabEmirates.ID);
parameters.reportOptions = new AmazonSpApiSDK.Models.Reports.ReportOptions();

var report= amazonConnection.Reports.CreateReport(parameters);

Get Report with PII


//use this method automatically know if the report are RDT or not
var data2 = 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 data

var data = 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.

ReportManager reportManager = new ReportManager(amazonConnection);
var products = reportManager.GetProducts(); //GET_MERCHANT_LISTINGS_ALL_DATA
var inventoryAging = reportManager.GetInventoryAging(); //GET_FBA_INVENTORY_AGED_DATA
var ordersByDate = reportManager.GetOrdersByOrderDate(90); //GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL
var ordersByLastUpdate = reportManager.GetOrdersByLastUpdate(90); //GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL
var settlementOrder = reportManager.GetSettlementOrder(90); //GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2
var returnMFNOrder = reportManager.GetReturnMFNOrder(90); //GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE
var returnFBAOrder = reportManager.GetReturnFBAOrder(90); //GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA
var reimbursementsOrder = reportManager.GetReimbursementsOrder(180); //GET_FBA_REIMBURSEMENTS_DATA
var feedbacks = reportManager.GetFeedbackFromDays(180); //GET_SELLER_FEEDBACK_DATA
var LedgerDetails = reportManager.GetLedgerDetailAsync(10); //GET_LEDGER_DETAIL_VIEW_DATA
var UnsuppressedInventory = reportManager.GetUnsuppressedInventoryDataAsync().ConfigureAwait(false).GetAwaiter().GetResult(); //GET_FBA_MYI_UNSUPPRESSED_INVENTORY_DATA
var sellerPerformance = reportManager.GetSellerPerformance(); //GET_V2_SELLER_PERFORMANCE_REPORT

Report GET_MERCHANT_LISTINGS_ALL_DATA sample

var parameters = new ParameterCreateReportSpecification();
parameters.reportType = ReportTypes.GET_MERCHANT_LISTINGS_ALL_DATA;

parameters.marketplaceIds = new MarketplaceIds();
parameters.marketplaceIds.Add(MarketPlace.UnitedArabEmirates.ID);

parameters.reportOptions = new FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.ReportOptions();

var reportId = amazonConnection.Reports.CreateReport(parameters);
var filePath = string.Empty;
string ReportDocumentId = string.Empty;

while (string.IsNullOrEmpty(ReportDocumentId))
{
    Thread.Sleep(1000 * 60);
    var reportData = 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

var data = await amazonConnection.CatalogItem.GetCatalogItem202204Async(
    new Parameter.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

var data = await amazonConnection.CatalogItem.SearchCatalogItems202204Async(
    new Parameter.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.


var data = amazonConnection.ProductPricing.GetPricing(
    new Parameter.ProductPricing.ParameterGetPricing()
    {
        MarketplaceId = MarketPlace.UnitedArabEmirates.ID,
        Asins = new string[] { "B00CZC5F0G" }
    });

Product Competitive Price


var data = amazonConnection.ProductPricing.GetCompetitivePricing(
    new Parameter.ProductPricing.ParameterGetCompetitivePricing()
    {
        MarketplaceId = MarketPlace.UnitedArabEmirates.ID,
        Asins = new string[] { "B00CZC5F0G" },
    });

GetFeaturedOfferExpectedPriceBatch


 var priceDemo = new ProductPricingSample(amazonConnection);
 await priceDemo.GetFeaturedOfferExpectedPriceBatch();

GetCompetitiveSummary (v2022-05-01)

The 2022-05-01 batch operation returns featured buying options, reference prices, lowest priced offers, and similar items (the similarItems array Amazon added in April 2026) for up to 20 ASIN/marketplace pairs per call. Rate limit is strict β€” 0.033 req/s, burst 1.

var response = await amazonConnection.ProductPricing.GetCompetitiveSummaryAsync(new CompetitiveSummaryBatchRequest
{
    Requests = new List<CompetitiveSummaryRequest>
    {
        new CompetitiveSummaryRequest
        {
            Asin          = "B00CZC5F0G",
            MarketplaceId = MarketPlace.UnitedArabEmirates.ID,
            IncludedData  = new List<CompetitiveSummaryIncludedData>
            {
                CompetitiveSummaryIncludedData.similarItems
            },
        }
    }
});

// Read the new similarItems array.
foreach (var r in response.Responses)
    foreach (var group in r.Body?.SimilarItems ?? new List<SimilarItems>())
        foreach (var item in group.Items)
            Console.WriteLine($"Similar ASIN: {item.Asin}");

Notifications β€” Create Destination

For more notification samples, please check Here.


//EventBridge
var data = amazonConnection.Notification.CreateDestination(
    new Notifications.CreateDestinationRequest()
    {
        Name = "CompanyName",
        ResourceSpecification = new Notifications.DestinationResourceSpecification()
        {
            EventBridge = new Notifications.EventBridgeResourceSpecification("us-east-2", "999999999")
        }
    });

//SQS
var dataSqs = amazonConnection.Notification.CreateDestination(
    new Notifications.CreateDestinationRequest()
    {
        Name = "CompanyName_AE",
        ResourceSpecification = new Notifications.DestinationResourceSpecification
        {
            Sqs = new Notifications.SqsResource("arn:aws:sqs:us-east-2:9999999999999:NAME")
        }
    });

Notifications β€” Create Subscription

For more notification samples, please check Here.


//SQS
var result = amazonConnection.Notification.CreateSubscription(
    new ParameterCreateSubscription()
    {
        destinationId = "xxxxxxxxxxxxxxx", // take this from CreateDestination or GetDestinations response 
        notificationType = NotificationType.ANY_OFFER_CHANGED, // or B2B_ANY_OFFER_CHANGED for B2B prices
        payloadVersion = "1.0"
    });

One subscription per NotificationType. Amazon doesn't let a single subscription cover multiple notification types β€” call CreateSubscription once per type. You can reuse the same destinationId (the same SQS queue) across all of them. To handle LWA secret rotation, add two extra calls pointing at the same destination:

// Receive the new secret on rotation.
amazonConnection.Notification.CreateSubscription(new ParameterCreateSubscription
{
    notificationType = NotificationType.APPLICATION_OAUTH_CLIENT_NEW_SECRET,
    destinationId    = "xxxxxxxxxxxxxxx",   // same destination as your other subscriptions
    payloadVersion   = "1.0",
});

// Get advance warning before the current secret expires.
amazonConnection.Notification.CreateSubscription(new ParameterCreateSubscription
{
    notificationType = NotificationType.APPLICATION_OAUTH_CLIENT_SECRET_EXPIRY,
    destinationId    = "xxxxxxxxxxxxxxx",
    payloadVersion   = "1.0",
});

See Application Management β€” rotate the LWA client secret for the full rotation flow.

Notifications β€” Read Messages

Tip: if your subscriptions include APPLICATION_OAUTH_CLIENT_NEW_SECRET, wrap your IMessageReceiver with RotationApplyingMessageReceiver so a rotated client secret is applied to amazonConnection.Credentials.ClientSecret automatically before your receiver sees the message.


var SQS_URL = Environment.GetEnvironmentVariable("SQS_URL");
var param = new ParameterMessageReceiver(
    Environment.GetEnvironmentVariable("AccessKey"),
    Environment.GetEnvironmentVariable("SecretKey"),
    SQS_URL,
    Amazon.RegionEndpoint.USEast2,
    WaitTimeSeconds: 20); // Enable SQS long polling to reduce empty receives and cost

var messageReceiver = new CustomMessageReceiver();

// Use CancellationToken for graceful shutdown and wrap in a restart loop
// so the listener recovers from transient errors automatically.
var cts = new CancellationTokenSource();
while (!cts.Token.IsCancellationRequested)
{
    try
    {
        // Static method β€” no instance needed
        await NotificationService.StartReceivingNotificationMessagesAsync(
            param, messageReceiver, cancellationToken: cts.Token);
    }
    catch (OperationCanceledException) when (cts.Token.IsCancellationRequested)
    {
        break; // Graceful shutdown
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Notification listener crashed, restarting in 10s: {ex.Message}");
        await Task.Delay(TimeSpan.FromSeconds(10), cts.Token);
    }
}

public class CustomMessageReceiver : IMessageReceiver
{
    // Track processed notification IDs to handle SQS duplicate delivery
    private readonly ConcurrentDictionary<string, byte> _processedNotificationIds = new();
    private readonly ConcurrentQueue<string> _idQueue = new();
    private const int MaxTrackedIds = 10_000;

    public void ErrorCatch(Exception ex)
    {
        Console.WriteLine($"Notification error: {ex.Message}");
    }

    public void NewMessageRevicedTriger(NotificationMessageResponce message)
    {
        // Deduplicate: SQS standard queues may deliver the same message more than once
        var notificationId = message?.NotificationMetadata?.NotificationId;
        if (notificationId != null && !_processedNotificationIds.TryAdd(notificationId, 0))
            return;

        // Cap the dedup cache so it doesn't grow forever
        if (notificationId != null)
        {
            _idQueue.Enqueue(notificationId);
            while (_idQueue.Count > MaxTrackedIds && _idQueue.TryDequeue(out var oldId))
                _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.

If you also subscribe to APPLICATION_OAUTH_CLIENT_NEW_SECRET here, see Notifications β€” Read Messages for the RotationApplyingMessageReceiver wrapper that auto-applies rotated secrets.


// Step 3: Create a destination (grantless operation β€” no seller authorization needed)
var destination = amazonConnection.Notification.CreateDestination(
    new Notifications.CreateDestinationRequest()
    {
        Name = "CompanyName_SQS",
        ResourceSpecification = new Notifications.DestinationResourceSpecification
        {
            Sqs = new Notifications.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_CHANGE
var subscription = amazonConnection.Notification.CreateSubscription(
    new ParameterCreateSubscription()
    {
        destinationId = destination.DestinationId,
        notificationType = NotificationType.ANY_OFFER_CHANGED,
        payloadVersion = "1.0",
        processingDirective = new Notifications.ProcessingDirective
        {
            EventFilter = new Notifications.EventFilter
            {
                EventFilterType = "ANY_OFFER_CHANGED",
                MarketplaceIds = new List<string> { "ATVPDKIKX0DER" },
                AggregationSettings = new Notifications.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.

ConstructFeedService createDocument = new ConstructFeedService("{SellerID}", "1.02");

var list = new List<PriceMessage>();
list.Add(new PriceMessage()
{
    SKU = "8201031206122...",
    StandardPrice = new StandardPrice()
    {
        currency = amazonConnection.GetCurrentMarketplace.CurrencyCode.ToString(),
        Value = (201.0522M).ToString("0.00")
    }
});
createDocument.AddPriceMessage(list);

var xml = createDocument.GetXML();

var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_PRODUCT_PRICING_DATA);

Thread.Sleep(1000*30);

var feedOutput=amazonConnection.Feed.GetFeed(feedID);

var outPut=amazonConnection.Feed.GetFeedDocument(feedOutput.ResultFeedDocumentId);

var reportOutpit = outPut.Url;

var processingReport = amazonConnection.Feed.GetFeedDocumentProcessingReport(outPut.Url);

JSON_LISTINGS_FEED Submit for change price
string sellerId = "SellerId";
string sku = "SKU";
decimal price = 19.99m;

string jsonString = $@"
{{
    ""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}
                    }}
                    ]
                }}
                ]
            }}
            ]
        }}
        ]
    }}
    ]
}}";

string feedID = await amazonConnection.Feed.SubmitFeedAsync(jsonString, FeedType.JSON_LISTINGS_FEED, new List<string>() { MarketPlace.UnitedArabEmirates.ID }, null, ContentType.JSON);

Thread.Sleep(1000*60);

var feedOutput = amazonConnection.Feed.GetFeed(feedID);

var outPut = amazonConnection.Feed.GetFeedDocument(feedOutput.ResultFeedDocumentId);

var reportOutpit = outPut.Url;

var processingReport = await amazonConnection.Feed.GetJsonFeedDocumentProcessingReportAsync(output);

Website authorization workflow.
    [HttpGet("AuthorizeAmazon")]
    public async Task<IActionResult> AuthorizeAmazon()
    {
        // Step 2-5 of the website authorization workflow.

        // Step 2-3: Amazon calls our log-in URI with amazon_callback_uri.
        var amazonCallbackUri = Request.Query["amazon_callback_uri"].ToString();
        if (!string.IsNullOrEmpty(amazonCallbackUri))
        {
            var amazonState = Request.Query["amazon_state"].ToString();
            var version = configuration["FikaAmazonAPI:AuthorizeVersion"];
            var redirectUri = configuration["FikaAmazonAPI:AmazonCallbackUri"];

            var generatedState = Guid.NewGuid().ToString("N");
            Response.Cookies.Append("amazon_oauth_state", generatedState, new CookieOptions
            {
                HttpOnly = true,
                Secure = true,
                SameSite = SameSiteMode.Lax,
                Expires = DateTimeOffset.UtcNow.AddMinutes(5)
            });

            var query = new Dictionary<string, string?>
            {
                ["redirect_uri"] = redirectUri,
                ["amazon_state"] = amazonState,
                ["state"] = generatedState
            };

            if (!string.IsNullOrEmpty(version))
            {
                query["version"] = version;
            }

            Response.Headers["Referrer-Policy"] = "no-referrer";
            var redirectUrl = QueryHelpers.AddQueryString(amazonCallbackUri, query!);
            return Redirect(redirectUrl);
        }

        // Step 4-5: Amazon redirects back to our redirect_uri with authorization code.
        var state = Request.Query["state"].ToString();
        var sellingPartnerId = Request.Query["selling_partner_id"].ToString();
        var mwsAuthToken = Request.Query["mws_auth_token"].ToString();
        var code = Request.Query["spapi_oauth_code"].ToString();

        var storedState = Request.Cookies["amazon_oauth_state"];
        if (string.IsNullOrEmpty(state) || storedState != state)
        {
            return BadRequest("Invalid state");
        }

        Response.Cookies.Delete("amazon_oauth_state");

        if (string.IsNullOrEmpty(code))
        {
            return BadRequest("Missing spapi_oauth_code");
        }

        var clientId = configuration["FikaAmazonAPI:ClientId"];
        var clientSecret = configuration["FikaAmazonAPI:ClientSecret"];
        var callbackUri = configuration["FikaAmazonAPI:AmazonCallbackUri"];

        using var httpClient = new HttpClient();
        var form = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "authorization_code",
            ["code"] = code,
            ["client_id"] = clientId ?? string.Empty,
            ["client_secret"] = clientSecret ?? string.Empty,
            ["redirect_uri"] = callbackUri ?? string.Empty
        });

        using var response = await httpClient.PostAsync("https://api.amazon.com/auth/o2/token", form);
        var responseBody = await response.Content.ReadAsStringAsync();
        if (!response.IsSuccessStatusCode)
        {
            return BadRequest(responseBody);
        }

        using var document = JsonDocument.Parse(responseBody);
        var refreshToken = document.RootElement.GetProperty("refresh_token").GetString();
        var accessToken = document.RootElement.GetProperty("access_token").GetString();

        return Json(new
        {
            state,
            selling_partner_id = sellingPartnerId,
            mws_auth_token = mwsAuthToken,
            refresh_token = refreshToken,
            access_token = accessToken
        });
    }

Feed Submit β€” Change Quantity
ConstructFeedService createDocument = new ConstructFeedService("{SellerID}", "1.02");

var list = new List<InventoryMessage>();
list.Add(new InventoryMessage()
  {
    SKU = "82010312061.22...",
    Quantity = 2,
    FulfillmentLatency = "11",
 });

createDocument.AddInventoryMessage(list);

var xml = createDocument.GetXML();

var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_INVENTORY_AVAILABILITY_DATA);

Thread.Sleep(1000*30);

var feedOutput=amazonConnection.Feed.GetFeed(feedID);

var outPut=amazonConnection.Feed.GetFeedDocument(feedOutput.ResultFeedDocumentId);

var reportOutpit = outPut.Url;

var processingReport = amazonConnection.Feed.GetFeedDocumentProcessingReport(outPut.Url);

Feed Submit β€” Change Product Image
public void SubmitFeedProductImage()
{
    ConstructFeedService createDocument = new ConstructFeedService("A3J37AJU4O9RHK", "1.02");
    var list = new List<ProductImageMessage>();
    list.Add(new ProductImageMessage()
    {
	SKU = "8201031206122...",
	ImageLocation = "http://xxxx.com/1.jpeg",
	ImageType = ImageType.Main
    }) ;
    createDocument.AddProductImageMessage(list);
    var xml = createDocument.GetXML();

    var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_PRODUCT_IMAGE_DATA);

}
Feed Submit β€” Fulfillment Data (add tracking number for shipment)

ConstructFeedService createDocument = new ConstructFeedService("{sellerId}", "1.02");

var list = new List<OrderFulfillmentMessage>();
list.Add(new OrderFulfillmentMessage()
    {
       AmazonOrderID = "{orderId}",
       FulfillmentDate = DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"),
       FulfillmentData = new FulfillmentData()
          {
              CarrierName = "Correos Express",
              ShippingMethod = "ePaq",
              ShipperTrackingNumber = "{trackingNumber}"
           }
    });
    createDocument.AddOrderFulfillmentMessage(list);

    var xml = createDocument.GetXML();

    var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_ORDER_FULFILLMENT_DATA);

Feed Submit β€” Order Adjustments
public void SubmitFeedOrderAdjustment()
{
            ConstructFeedService createDocument = new ConstructFeedService("A3J37AJU4O9RHK", "1.02");
            var list = new List<OrderAdjustmentMessage>();
            list.Add(new OrderAdjustmentMessage()
            {
                AmazonOrderID = "AMZ1234567890123",
                ActionType = AdjustmentActionType.Refund,
                AdjustedItem = new List<AdjustedItem>() {
                   new AdjustedItem() {
                       AmazonOrderItemCode = "52986411826454",
                       AdjustmentReason = AdjustmentReason.CustomerCancel,
                       DirectPaymentAdjustments = new List<DirectPaymentAdjustments>()
                           {
                               new DirectPaymentAdjustments()
                               {
                                   Component = new List<DirectPaymentAdjustmentsComponent>()
                                   {
                                       new DirectPaymentAdjustmentsComponent() {
                                            DirectPaymentType = "Credit Card Refund",
                                            Amount = new CurrencyAmount() {
                                                Value = 10.50M,
                                                currency = amazonConnection.GetCurrentMarketplace.CurrencyCode
                                            }
                                       }
                                   }
                               }
                           }
                       }
                }
            });
            createDocument.AddOrderAdjustmentMessage(list);
            var xml = createDocument.GetXML();

            var feedID = 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:

var amazonConnection = new AmazonConnection(new AmazonCredential()
{
      .
      .
      IsActiveLimitRate=false
});

Enable Debug Mode

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

var amazonConnection = new AmazonConnection(new AmazonCredential()
{
      .
      .
      IsDebugMode = true
});

Get Restrictions Before Adding New Listings

var result = amazonConnection.Restrictions.GetListingsRestrictions(
    new Parameter.Restrictions.ParameterGetListingsRestrictions
            {
                asin = "AAAAAAAAAA",
                sellerId = "AXXXXXXXXXXXX"
            });

Create shipment operation from MerchantFulfillment

ShipmentRequestDetails shipmentRequestDetails = new ShipmentRequestDetails()
{
    AmazonOrderId = "999-9999-999999",
    ItemList = new ItemList()
    {
        new FikaAmazonAPI.AmazonSpApiSDK.Models.MerchantFulfillment.Item()
        {
		OrderItemId = "52986411826454",
            Quantity = 1
        }

    },
    ShipFromAddress = new Address()
    {
        AddressLine1 = "300 St",
        City = "City",
        PostalCode = "48123",
        Email = "[[email protected]](mailto:[email protected])",
        Phone = "999999999",
        StateOrProvinceCode = "MI",
        CountryCode = "US",
        Name = "FirstName LastName"
    },
    PackageDimensions = new PackageDimensions()
    {
        Height = 10,
        Width = 10,
        Length = 10,
        Unit = UnitOfLength.Inches
    },
    Weight = new Weight()
    {
        Value = 10,
        Unit = UnitOfWeight.Oz
    },
    ShippingServiceOptions = new ShippingServiceOptions()
    {
        DeliveryExperience = DeliveryExperienceType.NoTracking,
        CarrierWillPickUp = false,
        CarrierWillPickUpOption = CarrierWillPickUpOption.ShipperWillDropOff
    }
};

var shipmentRequest = new CreateShipmentRequest(
			shipmentRequestDetails, 
			shippingServiceId: "UPS_PTP_2ND_DAY_AIR", 
			shippingServiceOfferId: "WHgxtyn6qjGGaC");

 var shipmentResponse = amazonConnection.MerchantFulfillment.CreateShipment(shipmentRequest);

ProductTypes SearchDefinitions

var list = amazonConnection.ProductType.SearchDefinitionsProductTypes(
  new Parameter.ProductTypes.SearchDefinitionsProductTypesParameter()
   {
    keywords = new List<string> { String.Empty },
   });

ProductTypes GetDefinitions

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

Sales Performance Sample

     DateTime queryStart = DateTime.UtcNow.AddDays(-11).Date;
     DateTime queryEnd = DateTime.UtcNow;
     var parameters = new ParameterGetOrderMetrics();
     parameters.marketplaceIds = new MarketplaceIds();
     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;

     var sales = amazonConnection.Sales.GetOrderMetrics(parameters);

Services β€” Get a service job by ID

For more samples, see ServicesSample.cs.

var serviceJob = amazonConnection.Services.GetServiceJobByServiceJobId("SJ-1234567890");

// As of Amazon's April 2026 release, the response contains a payments[] array.
var totalPaid = serviceJob.Payments?
    .Where(p => p.Amount?.Value != null)
    .Sum(p => p.Amount.Value);

Application Management (v2023-11-30) β€” rotate the LWA client secret

ApplicationManagementSample.cs shows the full flow.

The HTTP response carries no useful body β€” the rotated secret is delivered asynchronously to a developer-registered SQS queue subscribed to the APPLICATION_OAUTH_CLIENT_NEW_SECRET notification. The pattern is:

// 1. One-time setup: subscribe to the rotation notifications.
amazonConnection.Notification.CreateSubscription(new ParameterCreateSubscription
{
    notificationType = NotificationType.APPLICATION_OAUTH_CLIENT_NEW_SECRET,
    destinationId    = yourSqsDestinationId,   // pre-existing destination on an SQS queue
    payloadVersion   = "1.0",
});

// 2. Trigger rotation. Uses LWA grant_type=client_credentials with the rotation scope β€”
//    the SDK handles that special auth path internally.
amazonConnection.ApplicationManagement.RotateApplicationClientSecret();

// 3. Poll your SQS queue. The SDK already deserializes the payload into
//    NotificationMessageResponce.Payload.ApplicationOAuthClientNewSecret
//    (an ApplicationOAuthClientNewSecretNotification with NewClientSecret +
//    NewClientSecretExpiryTime + OldClientSecretExpiryTime).
Auto-applying the rotated secret

If you already use NotificationService.StartReceivingNotificationMessages* for SQS, wrap your existing receiver in RotationApplyingMessageReceiver to apply rotated secrets automatically β€” your code keeps doing what it did before, the credential bag updates transparently, and your onRotated callback persists the rotated values to your database so the next process start picks them up.

Persist all four fields:

Field What to do with it
payload.ClientId Row key.
payload.NewClientSecret Store encrypted (Key Vault / KMS / encrypted column).
payload.NewClientSecretExpiryTime When this new secret itself expires β€” schedule the next rotation before this.
payload.OldClientSecretExpiryTime Deadline to finish the cutover. Until this passes, both secrets work; after, only the new one does.
var wrapped = new RotationApplyingMessageReceiver(
    inner: myReceiver,
    credentials: amazonConnection.Credentials,
    onRotated: payload =>
    {
        // TODO: save these four values to your database, with NewClientSecret encrypted at rest.
        // The SDK has already applied payload.NewClientSecret to amazonConnection.Credentials,
        // so a transient DB error here doesn't break the running process β€” log and continue.
        myDb.SaveRotatedSecret(
            clientId:                 payload.ClientId,
            newClientSecret:          payload.NewClientSecret,
            newClientSecretExpiresAt: payload.NewClientSecretExpiryTime,
            oldClientSecretExpiresAt: payload.OldClientSecretExpiryTime);
    });

NotificationService.StartReceivingNotificationMessages(param, wrapped);

A reference IClientSecretStore interface is in ApplicationManagementSample.cs.

To get advance warning before a secret expires, also subscribe to NotificationType.APPLICATION_OAUTH_CLIENT_SECRET_EXPIRY β€” its payload is ApplicationOAuthClientSecretExpiryNotification with a ClientSecretExpiryTime.

Replenishment (v2022-11-07) β€” Subscribe & Save

For more samples, see ReplenishmentSample.cs. All three operations are rate-limited to 1 req/s, burst 1.

// 1. Find offers with paused or at-risk deliveries, sorted by inventory ascending.
var atRisk = await amazonConnection.Replenishment.ListOffersAsync(new ListOffersRequest
{
    Pagination = new ListOffersRequestPagination { Limit = 100 },
    Filters = new ListOffersRequestFilters
    {
        MarketplaceId = MarketPlace.US.ID,
        ProgramTypes  = new List<ProgramType> { ProgramType.SUBSCRIBE_AND_SAVE },
        DeliveriesConditions = new List<DeliveryConditionType>
        {
            DeliveryConditionType.NEXT_30_DAYS_DELIVERIES_PAUSED_PRICING,
            DeliveryConditionType.NEXT_30_DAYS_DELIVERIES_AT_LOW_INVENTORY_RISK,
        },
    },
    Sort = new ListOffersRequestSort { Order = SortOrder.ASC, Key = ListOffersSortKey.INVENTORY },
});

// 2. Per-offer metrics β€” now offer-level (SKU + FulfillmentChannelType) per April 2026 release.
var perOffer = await amazonConnection.Replenishment.ListOfferMetricsAsync(new ListOfferMetricsRequest { /*...*/ });

// 3. Seller-level metrics including the new REVENUE_PENETRATION metric.
var spMetrics = await amazonConnection.Replenishment.GetSellingPartnerMetricsAsync(new GetSellingPartnerMetricsRequest
{
    AggregationFrequency = AggregationFrequency.MONTH,
    TimeInterval = new TimeInterval { StartDate = monthStart, EndDate = monthEnd },
    TimePeriodType = TimePeriodType.PERFORMANCE,
    MarketplaceId = MarketPlace.US.ID,
    ProgramTypes  = new List<ProgramType> { ProgramType.SUBSCRIBE_AND_SAVE },
    Metrics = new List<Metric> { Metric.REVENUE_PENETRATION, Metric.TOTAL_SUBSCRIPTIONS_REVENUE },
});

Services β€” List, cancel, and complete service jobs

// Auto-pages through every result page and returns a flat list.
var upcoming = amazonConnection.Services.GetServiceJobs(new ParameterGetServiceJobs
{
    scheduleStartDate = DateTime.UtcNow,
    scheduleEndDate   = DateTime.UtcNow.AddDays(14),
    serviceJobStatus  = new List<string> { "SCHEDULED", "PENDING_SCHEDULE" },
    pageSize          = 50,
    sortField         = "JOB_DATE",
    sortOrder         = "ASC",
});

// Returns true when the request succeeds with no errors in the response body.
amazonConnection.Services.CancelServiceJobByServiceJobId("SJ-1234567890", "BUYER_REQUESTED_CANCELLATION");
amazonConnection.Services.CompleteServiceJobByServiceJobId("SJ-1234567890");

Q & A

If you have questions, please ask in GitHub discussions

discussions


ToDo

  • Improve documentation

Selling Partner API
Amazon MWS to SP-API Migration Guide
SP-API models
Using Postman for Selling Partner API models
Test Project with pure C# code
Sample Code
Creating And Configuring AWS

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.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on CSharpAmazonSpAPI:

Package Downloads
NoonConnector

Package Description

BizDoc.Infrastructure.Amazon

Amazon for BizDoc

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.9.27 114 4/25/2026
1.9.26 37 4/25/2026
1.9.25 31 4/25/2026
1.9.23 1,969 3/1/2026
1.9.22 102 3/1/2026
1.9.21 320 2/23/2026
1.9.20 1,923 1/17/2026
1.9.19 1,590 12/19/2025
1.9.18 1,144 11/27/2025
1.9.17 1,783 10/27/2025
1.9.16 253 10/24/2025
1.9.15 276 10/23/2025
1.9.14 266 10/23/2025
1.9.13 1,260 10/8/2025
1.9.11 6,467 8/31/2025
1.9.10 2,258 8/5/2025
1.9.9 362 8/5/2025
1.9.8 1,064 7/17/2025
1.9.7 290 7/17/2025
1.9.5 290 7/15/2025
Loading failed