Sample code for 30+ languages & platforms
Zig

Amazon SP-API Get Specific Order

See more Amazon SP-API Examples

Get a specific Amazon Seller order.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // Gets information for this order ID
    // The order ID is something like "902-1845936-5435065" and it is the AmazonOrderId returned in the JSON when getting the list of orders.  For example:
    // {
    //   "payload": {
    //     "CreatedBefore": "1.569521782042E9",
    //     "Orders": [
    //       {
    //         "AmazonOrderId": "902-1845936-5435065",
    //         "PurchaseDate": "1970-01-19T03:58:30Z",
    // ...

    // However, when using the sandbox, instead use the explicit keyword TEST_CASE_200
    const order_id = "TEST_CASE_200";

    const auth_aws = try chilkat.AuthAws.init();
    defer auth_aws.deinit();
    auth_aws.setAccessKey("AWS_ACCESS_KEY");
    auth_aws.setSecretKey("AWS_SECRET_KEY");
    auth_aws.setServiceName("execute-api");
    // Use the region that is correct for your needs.
    auth_aws.setRegion("eu-west-1");

    // First get a restricted data token for the given order ID.
    // This requires an LWA access token which cannot be more than 1 hour old.
    // See Fetch SP-API LWA Access Token
    const json_lwa_token = try chilkat.JsonObject.init();
    defer json_lwa_token.deinit();
    json_lwa_token.loadFile("qa_data/tokens/sp_api_lwa_token.json") catch {
        std.debug.print("Failed to load LWA access token.\n", .{});
        return;
    };

    // Must use the non-sandbox domain for getting the RDT.
    const rest = try chilkat.Rest.init();
    defer rest.deinit();
    rest.connect("sellingpartnerapi-eu.amazon.com", 443, true, true) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    try rest.setAuthAws(auth_aws);

    // Add the x-amz-access-token request header.
    const lwa_token = try json_lwa_token.stringOf(alloc, "access_token");
    rest.clearAllHeaders() catch {};
    rest.addHeader("x-amz-access-token", lwa_token) catch {};

    // We're going to send a POST with the following JSON body:

    // {
    //   "restrictedResources": [
    //     {
    //       "method": "GET",
    //       "path": "/orders/v0/orders/{orderId}",
    //       "dataElements": ["buyerInfo", "shippingAddress"]
    //     }
    //   ]
    // }

    const sb_path = try chilkat.StringBuilder.init();
    defer sb_path.deinit();
    sb_path.append("/orders/v0/orders/") catch {};
    sb_path.append(order_id) catch {};

    const json_rc = try chilkat.JsonObject.init();
    defer json_rc.deinit();
    json_rc.updateString("restrictedResources[0].method", "GET") catch {};
    json_rc.updateString("restrictedResources[0].path", try sb_path.getAsString(alloc)) catch {};
    json_rc.updateString("restrictedResources[0].dataElements[0]", "buyerInfo") catch {};
    json_rc.updateString("restrictedResources[0].dataElements[1]", "shippingAddress") catch {};

    const sb_request = try chilkat.StringBuilder.init();
    defer sb_request.deinit();
    json_rc.emitSb(sb_request) catch {};

    const sb_response = try chilkat.StringBuilder.init();
    defer sb_response.deinit();
    var uri: [:0]const u8 = "/tokens/2021-03-01/restrictedDataToken";
    rest.fullRequestSb("POST", uri, sb_request, sb_response) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    // Examine the response status.
    var status_code: i32 = rest.getResponseStatusCode();
    if (status_code != 200) {
        std.debug.print("Response status code: {d}\n", .{status_code});
        std.debug.print("Response status text: {s}\n", .{try rest.getResponseStatusText(alloc)});
        std.debug.print("Response body: \n", .{});
        std.debug.print("{s}\n", .{try sb_response.getAsString(alloc)});
        std.debug.print("Failed.\n", .{});
        return;
    }

    // Get the restricted data token.
    const json_resp = try chilkat.JsonObject.init();
    defer json_resp.deinit();
    json_resp.loadSb(sb_response) catch {};
    const restricted_data_token = try json_resp.stringOf(alloc, "restrictedDataToken");
    std.debug.print("Restricted Data Token: {s}\n", .{restricted_data_token});

    // ------------------------------------------------------------------------------------------------------------
    // ------------------------------------------------------------------------------------------------------------
    // Now that we have the RDT, we can use it to get information about the order.
    //
    // Yes, the SP-API is horribly tedious and painful.  You must use an RDT specifically tailored to each request requiring an RDT,
    // the RDT must not be over an hour old, and if you need to get a new RDT you must get it using an LWA token that itself is not
    // more than an hour old.  If the LWA is more than an hour old, you must get a new one.  Ughhh!!!!!
    // ------------------------------------------------------------------------------------------------------------

    // Disconnect from the non-sandbox domain.  This example will use the sandbox.
    // (The RDT was obtained using the non-sandbox domain.  For some reason, the sandbox domain does not work for getting the RDT.)
    rest.disconnect(100) catch {};

    rest.connect("sandbox.sellingpartnerapi-eu.amazon.com", 443, true, true) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    try rest.setAuthAws(auth_aws);

    rest.clearAllHeaders() catch {};
    rest.addHeader("x-amz-access-token", restricted_data_token) catch {};

    rest.clearAllQueryParams() catch {};
    rest.addQueryParam("MarketplaceIds", "ATVPDKIKX0DER") catch {};

    rest.clearAllPathParams() catch {};
    rest.addPathParam("{orderId}", order_id) catch {};

    uri = "/orders/v0/orders/{orderId}";
    rest.fullRequestNoBodySb("GET", uri, sb_response) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    // Examine the response status.
    status_code = rest.getResponseStatusCode();
    if (status_code != 200) {
        std.debug.print("Response status text: {s}\n", .{try rest.getResponseStatusText(alloc)});
        std.debug.print("Response body: \n", .{});
        std.debug.print("{s}\n", .{try sb_response.getAsString(alloc)});
        std.debug.print("Failed.\n", .{});
        return;
    }

    std.debug.print("{s}\n", .{try sb_response.getAsString(alloc)});

    // If successful, gets a JSON response such as the following:

    // {
    //   "payload": {
    //     "AmazonOrderId": "902-1845936-5435065",
    //     "PurchaseDate": "1970-01-19T03:58:30Z",
    //     "LastUpdateDate": "1970-01-19T03:58:32Z",
    //     "OrderStatus": "Unshipped",
    //     "FulfillmentChannel": "MFN",
    //     "SalesChannel": "Amazon.com",
    //     "ShipServiceLevel": "Std US D2D Dom",
    //     "OrderTotal": {
    //       "CurrencyCode": "USD",
    //       "Amount": "11.01"
    //     },
    //     "NumberOfItemsShipped": 0,
    //     "NumberOfItemsUnshipped": 1,
    //     "PaymentMethod": "Other",
    //     "PaymentMethodDetails": [
    //       "Standard"
    //     ],
    //     "IsReplacementOrder": false,
    //     "MarketplaceId": "ATVPDKIKX0DER",
    //     "ShipmentServiceLevelCategory": "Standard",
    //     "OrderType": "StandardOrder",
    //     "EarliestShipDate": "1970-01-19T03:59:27Z",
    //     "LatestShipDate": "1970-01-19T04:05:13Z",
    //     "EarliestDeliveryDate": "1970-01-19T04:06:39Z",
    //     "LatestDeliveryDate": "1970-01-19T04:15:17Z",
    //     "IsBusinessOrder": false,
    //     "IsPrime": false,
    //     "IsGlobalExpressEnabled": false,
    //     "IsPremiumOrder": false,
    //     "IsSoldByAB": false,
    //     "IsIBA": false,
    //     "DefaultShipFromLocationAddress": {
    //       "Name": "MFNIntegrationTestMerchant",
    //       "AddressLine1": "2201 WESTLAKE AVE",
    //       "City": "SEATTLE",
    //       "StateOrRegion": "WA",
    //       "PostalCode": "98121-2778",
    //       "CountryCode": "US",
    //       "Phone": "+1 480-386-0930 ext. 73824",
    //       "AddressType": "Commercial"
    //     },
    //     "FulfillmentInstruction": {
    //       "FulfillmentSupplySourceId": "sampleSupplySourceId"
    //     },
    //     "IsISPU": false,
    //     "IsAccessPointOrder": false,
    //     "AutomatedShippingSettings": {
    //       "HasAutomatedShippingSettings": false
    //     },
    //     "EasyShipShipmentStatus": "PendingPickUp",
    //     "ElectronicInvoiceStatus": "NotRequired"
    //   }
    // }

    // Use this online tool to generate parsing code from sample JSON:
    // Generate Parsing Code from JSON

    const json = try chilkat.JsonObject.init();
    defer json.deinit();

    json.loadSb(sb_response) catch {};

    var str_val: [:0]const u8 = "";

    _ = try json.stringOf(alloc, "payload.AmazonOrderId");
    _ = try json.stringOf(alloc, "payload.PurchaseDate");
    _ = try json.stringOf(alloc, "payload.LastUpdateDate");
    _ = try json.stringOf(alloc, "payload.OrderStatus");
    _ = try json.stringOf(alloc, "payload.FulfillmentChannel");
    _ = try json.stringOf(alloc, "payload.SalesChannel");
    _ = try json.stringOf(alloc, "payload.ShipServiceLevel");
    _ = try json.stringOf(alloc, "payload.OrderTotal.CurrencyCode");
    _ = try json.stringOf(alloc, "payload.OrderTotal.Amount");
    _ = json.intOf("payload.NumberOfItemsShipped");
    _ = json.intOf("payload.NumberOfItemsUnshipped");
    _ = try json.stringOf(alloc, "payload.PaymentMethod");
    _ = json.boolOf("payload.IsReplacementOrder");
    _ = try json.stringOf(alloc, "payload.MarketplaceId");
    _ = try json.stringOf(alloc, "payload.ShipmentServiceLevelCategory");
    _ = try json.stringOf(alloc, "payload.OrderType");
    _ = try json.stringOf(alloc, "payload.EarliestShipDate");
    _ = try json.stringOf(alloc, "payload.LatestShipDate");
    _ = try json.stringOf(alloc, "payload.EarliestDeliveryDate");
    _ = try json.stringOf(alloc, "payload.LatestDeliveryDate");
    _ = json.boolOf("payload.IsBusinessOrder");
    _ = json.boolOf("payload.IsPrime");
    _ = json.boolOf("payload.IsGlobalExpressEnabled");
    _ = json.boolOf("payload.IsPremiumOrder");
    _ = json.boolOf("payload.IsSoldByAB");
    _ = json.boolOf("payload.IsIBA");
    _ = try json.stringOf(alloc, "payload.DefaultShipFromLocationAddress.Name");
    _ = try json.stringOf(alloc, "payload.DefaultShipFromLocationAddress.AddressLine1");
    _ = try json.stringOf(alloc, "payload.DefaultShipFromLocationAddress.City");
    _ = try json.stringOf(alloc, "payload.DefaultShipFromLocationAddress.StateOrRegion");
    _ = try json.stringOf(alloc, "payload.DefaultShipFromLocationAddress.PostalCode");
    _ = try json.stringOf(alloc, "payload.DefaultShipFromLocationAddress.CountryCode");
    _ = try json.stringOf(alloc, "payload.DefaultShipFromLocationAddress.Phone");
    _ = try json.stringOf(alloc, "payload.DefaultShipFromLocationAddress.AddressType");
    _ = try json.stringOf(alloc, "payload.FulfillmentInstruction.FulfillmentSupplySourceId");
    _ = json.boolOf("payload.IsISPU");
    _ = json.boolOf("payload.IsAccessPointOrder");
    _ = json.boolOf("payload.AutomatedShippingSettings.HasAutomatedShippingSettings");
    _ = try json.stringOf(alloc, "payload.EasyShipShipmentStatus");
    _ = try json.stringOf(alloc, "payload.ElectronicInvoiceStatus");
    var i: i32 = 0;
    const count_i = json.sizeOfArray("payload.PaymentMethodDetails");
    while (i < count_i) {
        json.setI(i);
        str_val = try json.stringOf(alloc, "payload.PaymentMethodDetails[i]");
        i = i + 1;
    }

    std.debug.print("Success!\n", .{});
}