Sample code for 30+ languages & platforms
Zig

Amazon SP-API Get Order Items

See more Amazon SP-API Examples

Returns detailed order item information for the order that you specify.

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 detailed order item information for a specified 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}/orderItems",
    //       "dataElements": ["buyerInfo"]
    //     }
    //   ]
    // }

    const sb_path = try chilkat.StringBuilder.init();
    defer sb_path.deinit();
    sb_path.append("/orders/v0/orders/") catch {};
    sb_path.append(order_id) catch {};
    sb_path.append("/orderItems") 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 {};

    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}/orderItems";
    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;
    }

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

    // {
    //   "payload": {
    //     "AmazonOrderId": "902-1845936-5435065",
    //     "OrderItems": [
    //       {
    //         "ASIN": "B00551Q3CS",
    //         "OrderItemId": "05015851154158",
    //         "SellerSKU": "NABetaASINB00551Q3CS",
    //         "Title": "B00551Q3CS [Card Book]",
    //         "QuantityOrdered": 1,
    //         "QuantityShipped": 0,
    //         "ProductInfo": {
    //           "NumberOfItems": 1
    //         },
    //         "ItemPrice": {
    //           "CurrencyCode": "USD",
    //           "Amount": "10.00"
    //         },
    //         "ItemTax": {
    //           "CurrencyCode": "USD",
    //           "Amount": "1.01"
    //         },
    //         "PromotionDiscount": {
    //           "CurrencyCode": "USD",
    //           "Amount": "0.00"
    //         },
    //         "IsGift": false,
    //         "ConditionId": "New",
    //         "ConditionSubtypeId": "New",
    //         "IsTransparency": false,
    //         "SerialNumberRequired": false,
    //         "IossNumber": "",
    //         "DeemedResellerCategory": "IOSS",
    //         "StoreChainStoreId": "ISPU_StoreId",
    //         "BuyerRequestedCancel": {
    //           "IsBuyerRequestedCancel": true,
    //           "BuyerCancelReason": "Found cheaper somewhere else."
    //         }
    //       }
    //     ]
    //   }
    // }

    // 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 {};
    json.setEmitCompact(false);
    std.debug.print("{s}\n", .{try json.emit(alloc)});

    var asin: [:0]const u8 = "";
    var order_item_id: [:0]const u8 = "";
    var seller_sku: [:0]const u8 = "";
    var title: [:0]const u8 = "";
    var quantity_ordered: i32 = 0;
    var quantity_shipped: i32 = 0;
    var number_of_items: i32 = 0;
    var currency_code: [:0]const u8 = "";
    var amount: [:0]const u8 = "";
    var item_tax_currency_code: [:0]const u8 = "";
    var item_tax_amount: [:0]const u8 = "";
    var promotion_discount_currency_code: [:0]const u8 = "";
    var promotion_discount_amount: [:0]const u8 = "";
    var is_gift: bool = false;
    var condition_id: [:0]const u8 = "";
    var condition_subtype_id: [:0]const u8 = "";
    var is_transparency: bool = false;
    var serial_number_required: bool = false;
    var ioss_number: [:0]const u8 = "";
    var deemed_reseller_category: [:0]const u8 = "";
    var store_chain_store_id: [:0]const u8 = "";
    var is_buyer_requested_cancel: bool = false;
    var buyer_cancel_reason: [:0]const u8 = "";

    _ = try json.stringOf(alloc, "payload.AmazonOrderId");
    var i: i32 = 0;
    const count_i = json.sizeOfArray("payload.OrderItems");
    while (i < count_i) {
        json.setI(i);
        asin = try json.stringOf(alloc, "payload.OrderItems[i].ASIN");
        order_item_id = try json.stringOf(alloc, "payload.OrderItems[i].OrderItemId");
        seller_sku = try json.stringOf(alloc, "payload.OrderItems[i].SellerSKU");
        title = try json.stringOf(alloc, "payload.OrderItems[i].Title");
        quantity_ordered = json.intOf("payload.OrderItems[i].QuantityOrdered");
        quantity_shipped = json.intOf("payload.OrderItems[i].QuantityShipped");
        number_of_items = json.intOf("payload.OrderItems[i].ProductInfo.NumberOfItems");
        currency_code = try json.stringOf(alloc, "payload.OrderItems[i].ItemPrice.CurrencyCode");
        amount = try json.stringOf(alloc, "payload.OrderItems[i].ItemPrice.Amount");
        item_tax_currency_code = try json.stringOf(alloc, "payload.OrderItems[i].ItemTax.CurrencyCode");
        item_tax_amount = try json.stringOf(alloc, "payload.OrderItems[i].ItemTax.Amount");
        promotion_discount_currency_code = try json.stringOf(alloc, "payload.OrderItems[i].PromotionDiscount.CurrencyCode");
        promotion_discount_amount = try json.stringOf(alloc, "payload.OrderItems[i].PromotionDiscount.Amount");
        is_gift = json.boolOf("payload.OrderItems[i].IsGift");
        condition_id = try json.stringOf(alloc, "payload.OrderItems[i].ConditionId");
        condition_subtype_id = try json.stringOf(alloc, "payload.OrderItems[i].ConditionSubtypeId");
        is_transparency = json.boolOf("payload.OrderItems[i].IsTransparency");
        serial_number_required = json.boolOf("payload.OrderItems[i].SerialNumberRequired");
        ioss_number = try json.stringOf(alloc, "payload.OrderItems[i].IossNumber");
        deemed_reseller_category = try json.stringOf(alloc, "payload.OrderItems[i].DeemedResellerCategory");
        store_chain_store_id = try json.stringOf(alloc, "payload.OrderItems[i].StoreChainStoreId");
        is_buyer_requested_cancel = json.boolOf("payload.OrderItems[i].BuyerRequestedCancel.IsBuyerRequestedCancel");
        buyer_cancel_reason = try json.stringOf(alloc, "payload.OrderItems[i].BuyerRequestedCancel.BuyerCancelReason");
        i = i + 1;
    }

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