Sample code for 30+ languages & platforms
Lua

Amazon SP-API Get Specific Order

See more Amazon SP-API Examples

Get a specific Amazon Seller order.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- 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
local orderId = "TEST_CASE_200"

local authAws = chilkat.AuthAws.new()
authAws.access_key = "AWS_ACCESS_KEY"
authAws.secret_key = "AWS_SECRET_KEY"
authAws.service_name = "execute-api"
-- Use the region that is correct for your needs.
authAws.region = "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
local jsonLwaToken = chilkat.JsonObject.new()
local success = jsonLwaToken:load_file("qa_data/tokens/sp_api_lwa_token.json")
if not success then
    print("Failed to load LWA access token.")
    return
end

-- Must use the non-sandbox domain for getting the RDT.
local rest = chilkat.Rest.new()
success = rest:connect("sellingpartnerapi-eu.amazon.com", 443, true, true)
if not success then
    print(rest.last_error_text)
    return
end

success = rest:set_auth_aws(authAws)

-- Add the x-amz-access-token request header.
local lwa_token = jsonLwaToken:string_of("access_token")
rest:clear_all_headers()
rest:add_header("x-amz-access-token", lwa_token)

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

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

local sbPath = chilkat.StringBuilder.new()
sbPath:append("/orders/v0/orders/")
sbPath:append(orderId)

local jsonRc = chilkat.JsonObject.new()
jsonRc:update_string("restrictedResources[0].method", "GET")
jsonRc:update_string("restrictedResources[0].path", sbPath:get_as_string())
jsonRc:update_string("restrictedResources[0].dataElements[0]", "buyerInfo")
jsonRc:update_string("restrictedResources[0].dataElements[1]", "shippingAddress")

local sbRequest = chilkat.StringBuilder.new()
jsonRc:emit_sb(sbRequest)

local sbResponse = chilkat.StringBuilder.new()
local uri = "/tokens/2021-03-01/restrictedDataToken"
success = rest:full_request_sb("POST", uri, sbRequest, sbResponse)
if not success then
    print(rest.last_error_text)
    return
end

-- Examine the response status.
local statusCode = rest.response_status_code
if statusCode ~= 200 then
    print("Response status code: " .. statusCode)
    print("Response status text: " .. rest.response_status_text)
    print("Response body: ")
    print(sbResponse:get_as_string())
    print("Failed.")
    return
end

-- Get the restricted data token.
local jsonResp = chilkat.JsonObject.new()
jsonResp:load_sb(sbResponse)
local restrictedDataToken = jsonResp:string_of("restrictedDataToken")
print("Restricted Data Token: " .. restrictedDataToken)

-- ------------------------------------------------------------------------------------------------------------
-- ------------------------------------------------------------------------------------------------------------
-- 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)

success = rest:connect("sandbox.sellingpartnerapi-eu.amazon.com", 443, true, true)
if not success then
    print(rest.last_error_text)
    return
end

success = rest:set_auth_aws(authAws)

rest:clear_all_headers()
rest:add_header("x-amz-access-token", restrictedDataToken)

rest:clear_all_query_params()
rest:add_query_param("MarketplaceIds", "ATVPDKIKX0DER")

rest:clear_all_path_params()
rest:add_path_param("{orderId}", orderId)

uri = "/orders/v0/orders/{orderId}"
success = rest:full_request_no_body_sb("GET", uri, sbResponse)
if not success then
    print(rest.last_error_text)
    return
end

-- Examine the response status.
statusCode = rest.response_status_code
if statusCode ~= 200 then
    print("Response status text: " .. rest.response_status_text)
    print("Response body: ")
    print(sbResponse:get_as_string())
    print("Failed.")
    return
end

print(sbResponse:get_as_string())

-- 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

local json = chilkat.JsonObject.new()

json:load_sb(sbResponse)

local strVal = ""

local AmazonOrderId = json:string_of("payload.AmazonOrderId")
local PurchaseDate = json:string_of("payload.PurchaseDate")
local LastUpdateDate = json:string_of("payload.LastUpdateDate")
local OrderStatus = json:string_of("payload.OrderStatus")
local FulfillmentChannel = json:string_of("payload.FulfillmentChannel")
local SalesChannel = json:string_of("payload.SalesChannel")
local ShipServiceLevel = json:string_of("payload.ShipServiceLevel")
local CurrencyCode = json:string_of("payload.OrderTotal.CurrencyCode")
local Amount = json:string_of("payload.OrderTotal.Amount")
local NumberOfItemsShipped = json:int_of("payload.NumberOfItemsShipped")
local NumberOfItemsUnshipped = json:int_of("payload.NumberOfItemsUnshipped")
local PaymentMethod = json:string_of("payload.PaymentMethod")
local IsReplacementOrder = json:bool_of("payload.IsReplacementOrder")
local MarketplaceId = json:string_of("payload.MarketplaceId")
local ShipmentServiceLevelCategory = json:string_of("payload.ShipmentServiceLevelCategory")
local OrderType = json:string_of("payload.OrderType")
local EarliestShipDate = json:string_of("payload.EarliestShipDate")
local LatestShipDate = json:string_of("payload.LatestShipDate")
local EarliestDeliveryDate = json:string_of("payload.EarliestDeliveryDate")
local LatestDeliveryDate = json:string_of("payload.LatestDeliveryDate")
local IsBusinessOrder = json:bool_of("payload.IsBusinessOrder")
local IsPrime = json:bool_of("payload.IsPrime")
local IsGlobalExpressEnabled = json:bool_of("payload.IsGlobalExpressEnabled")
local IsPremiumOrder = json:bool_of("payload.IsPremiumOrder")
local IsSoldByAB = json:bool_of("payload.IsSoldByAB")
local IsIBA = json:bool_of("payload.IsIBA")
local Name = json:string_of("payload.DefaultShipFromLocationAddress.Name")
local AddressLine1 = json:string_of("payload.DefaultShipFromLocationAddress.AddressLine1")
local City = json:string_of("payload.DefaultShipFromLocationAddress.City")
local StateOrRegion = json:string_of("payload.DefaultShipFromLocationAddress.StateOrRegion")
local PostalCode = json:string_of("payload.DefaultShipFromLocationAddress.PostalCode")
local CountryCode = json:string_of("payload.DefaultShipFromLocationAddress.CountryCode")
local Phone = json:string_of("payload.DefaultShipFromLocationAddress.Phone")
local AddressType = json:string_of("payload.DefaultShipFromLocationAddress.AddressType")
local FulfillmentSupplySourceId = json:string_of("payload.FulfillmentInstruction.FulfillmentSupplySourceId")
local IsISPU = json:bool_of("payload.IsISPU")
local IsAccessPointOrder = json:bool_of("payload.IsAccessPointOrder")
local HasAutomatedShippingSettings = json:bool_of("payload.AutomatedShippingSettings.HasAutomatedShippingSettings")
local EasyShipShipmentStatus = json:string_of("payload.EasyShipShipmentStatus")
local ElectronicInvoiceStatus = json:string_of("payload.ElectronicInvoiceStatus")
local i = 0
local count_i = json:size_of_array("payload.PaymentMethodDetails")
while i < count_i do
    json.i = i
    strVal = json:string_of("payload.PaymentMethodDetails[i]")
    i = i + 1
end

print("Success!")