Lua
Lua
Amazon SP-API Get Order Items
See more Amazon SP-API Examples
Returns detailed order item information for the order that you specify.Chilkat Lua Downloads
local chilkat = require("chilkat")
-- 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
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}/orderItems",
-- "dataElements": ["buyerInfo"]
-- }
-- ]
-- }
local sbPath = chilkat.StringBuilder.new()
sbPath:append("/orders/v0/orders/")
sbPath:append(orderId)
sbPath:append("/orderItems")
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")
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}/orderItems"
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
-- 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
local json = chilkat.JsonObject.new()
json:load_sb(sbResponse)
json.emit_compact = false
print(json:emit())
local ASIN = ""
local OrderItemId = ""
local SellerSKU = ""
local Title = ""
local QuantityOrdered = 0
local QuantityShipped = 0
local NumberOfItems = 0
local CurrencyCode = ""
local Amount = ""
local ItemTaxCurrencyCode = ""
local ItemTaxAmount = ""
local PromotionDiscountCurrencyCode = ""
local PromotionDiscountAmount = ""
local IsGift = false
local ConditionId = ""
local ConditionSubtypeId = ""
local IsTransparency = false
local SerialNumberRequired = false
local IossNumber = ""
local DeemedResellerCategory = ""
local StoreChainStoreId = ""
local IsBuyerRequestedCancel = false
local BuyerCancelReason = ""
local AmazonOrderId = json:string_of("payload.AmazonOrderId")
local i = 0
local count_i = json:size_of_array("payload.OrderItems")
while i < count_i do
json.i = i
ASIN = json:string_of("payload.OrderItems[i].ASIN")
OrderItemId = json:string_of("payload.OrderItems[i].OrderItemId")
SellerSKU = json:string_of("payload.OrderItems[i].SellerSKU")
Title = json:string_of("payload.OrderItems[i].Title")
QuantityOrdered = json:int_of("payload.OrderItems[i].QuantityOrdered")
QuantityShipped = json:int_of("payload.OrderItems[i].QuantityShipped")
NumberOfItems = json:int_of("payload.OrderItems[i].ProductInfo.NumberOfItems")
CurrencyCode = json:string_of("payload.OrderItems[i].ItemPrice.CurrencyCode")
Amount = json:string_of("payload.OrderItems[i].ItemPrice.Amount")
ItemTaxCurrencyCode = json:string_of("payload.OrderItems[i].ItemTax.CurrencyCode")
ItemTaxAmount = json:string_of("payload.OrderItems[i].ItemTax.Amount")
PromotionDiscountCurrencyCode = json:string_of("payload.OrderItems[i].PromotionDiscount.CurrencyCode")
PromotionDiscountAmount = json:string_of("payload.OrderItems[i].PromotionDiscount.Amount")
IsGift = json:bool_of("payload.OrderItems[i].IsGift")
ConditionId = json:string_of("payload.OrderItems[i].ConditionId")
ConditionSubtypeId = json:string_of("payload.OrderItems[i].ConditionSubtypeId")
IsTransparency = json:bool_of("payload.OrderItems[i].IsTransparency")
SerialNumberRequired = json:bool_of("payload.OrderItems[i].SerialNumberRequired")
IossNumber = json:string_of("payload.OrderItems[i].IossNumber")
DeemedResellerCategory = json:string_of("payload.OrderItems[i].DeemedResellerCategory")
StoreChainStoreId = json:string_of("payload.OrderItems[i].StoreChainStoreId")
IsBuyerRequestedCancel = json:bool_of("payload.OrderItems[i].BuyerRequestedCancel.IsBuyerRequestedCancel")
BuyerCancelReason = json:string_of("payload.OrderItems[i].BuyerRequestedCancel.BuyerCancelReason")
i = i + 1
end
print("Success!")