Sample code for 30+ languages & platforms
Perl

Amazon SP-API Get Order Items

See more Amazon SP-API Examples

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

Chilkat Perl Downloads

Perl
use strict;
use warnings;
use Chilkat2;

# 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
my $orderId = 'TEST_CASE_200';

my $authAws = Chilkat2::AuthAws->new;
$authAws->AccessKey('AWS_ACCESS_KEY');
$authAws->SecretKey('AWS_SECRET_KEY');
$authAws->ServiceName('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
my $jsonLwaToken = Chilkat2::JsonObject->new;
my $success = $jsonLwaToken->LoadFile('qa_data/tokens/sp_api_lwa_token.json');
if (!$success) {
    print "Failed to load LWA access token.\n";
    exit;
}

# Must use the non-sandbox domain for getting the RDT.
my $rest = Chilkat2::Rest->new;
$success = $rest->Connect('sellingpartnerapi-eu.amazon.com', 443, 1, 1);
if (!$success) {
    print $rest->LastErrorText, "\n";
    exit;
}

$success = $rest->SetAuthAws($authAws);

# Add the x-amz-access-token request header.
my $lwa_token = $jsonLwaToken->StringOf('access_token');
$rest->ClearAllHeaders();
$rest->AddHeader('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"]
#     }
#   ]
# }

my $sbPath = Chilkat2::StringBuilder->new;
$sbPath->Append('/orders/v0/orders/');
$sbPath->Append($orderId);
$sbPath->Append('/orderItems');

my $jsonRc = Chilkat2::JsonObject->new;
$jsonRc->UpdateString('restrictedResources[0].method', 'GET');
$jsonRc->UpdateString('restrictedResources[0].path', $sbPath->GetAsString());
$jsonRc->UpdateString('restrictedResources[0].dataElements[0]', 'buyerInfo');

my $sbRequest = Chilkat2::StringBuilder->new;
$jsonRc->EmitSb($sbRequest);

my $sbResponse = Chilkat2::StringBuilder->new;
my $uri = '/tokens/2021-03-01/restrictedDataToken';
$success = $rest->FullRequestSb('POST', $uri, $sbRequest, $sbResponse);
if (!$success) {
    print $rest->LastErrorText, "\n";
    exit;
}

# Examine the response status.
my $statusCode = $rest->ResponseStatusCode;
if ($statusCode != 200) {
    print 'Response status code: ', $statusCode, "\n";
    print 'Response status text: ', $rest->ResponseStatusText, "\n";
    print "Response body: \n";
    print $sbResponse->GetAsString(), "\n";
    print "Failed.\n";
    exit;
}

# Get the restricted data token.
my $jsonResp = Chilkat2::JsonObject->new;
$jsonResp->LoadSb($sbResponse);
my $restrictedDataToken = $jsonResp->StringOf('restrictedDataToken');
print 'Restricted Data Token: ', $restrictedDataToken, "\n";

# ------------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------
# 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, 1, 1);
if (!$success) {
    print $rest->LastErrorText, "\n";
    exit;
}

$success = $rest->SetAuthAws($authAws);

$rest->ClearAllHeaders();
$rest->AddHeader('x-amz-access-token', $restrictedDataToken);

$rest->ClearAllQueryParams();
$rest->AddQueryParam('MarketplaceIds', 'ATVPDKIKX0DER');

$rest->ClearAllPathParams();
$rest->AddPathParam('{orderId}', $orderId);

$uri = '/orders/v0/orders/{orderId}/orderItems';
$success = $rest->FullRequestNoBodySb('GET', $uri, $sbResponse);
if (!$success) {
    print $rest->LastErrorText, "\n";
    exit;
}

# Examine the response status.
$statusCode = $rest->ResponseStatusCode;
if ($statusCode != 200) {
    print 'Response status text: ', $rest->ResponseStatusText, "\n";
    print "Response body: \n";
    print $sbResponse->GetAsString(), "\n";
    print "Failed.\n";
    exit;
}

# 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

my $json = Chilkat2::JsonObject->new;

$json->LoadSb($sbResponse);
$json->EmitCompact(0);
print $json->Emit(), "\n";

my $ASIN = '';
my $OrderItemId = '';
my $SellerSKU = '';
my $Title = '';
my $QuantityOrdered = 0;
my $QuantityShipped = 0;
my $NumberOfItems = 0;
my $CurrencyCode = '';
my $Amount = '';
my $ItemTaxCurrencyCode = '';
my $ItemTaxAmount = '';
my $PromotionDiscountCurrencyCode = '';
my $PromotionDiscountAmount = '';
my $IsGift = 0;
my $ConditionId = '';
my $ConditionSubtypeId = '';
my $IsTransparency = 0;
my $SerialNumberRequired = 0;
my $IossNumber = '';
my $DeemedResellerCategory = '';
my $StoreChainStoreId = '';
my $IsBuyerRequestedCancel = 0;
my $BuyerCancelReason = '';

my $AmazonOrderId = $json->StringOf('payload.AmazonOrderId');
my $i = 0;
my $count_i = $json->SizeOfArray('payload.OrderItems');
while ($i < $count_i) {
    $json->I($i);
    $ASIN = $json->StringOf('payload.OrderItems[i].ASIN');
    $OrderItemId = $json->StringOf('payload.OrderItems[i].OrderItemId');
    $SellerSKU = $json->StringOf('payload.OrderItems[i].SellerSKU');
    $Title = $json->StringOf('payload.OrderItems[i].Title');
    $QuantityOrdered = $json->IntOf('payload.OrderItems[i].QuantityOrdered');
    $QuantityShipped = $json->IntOf('payload.OrderItems[i].QuantityShipped');
    $NumberOfItems = $json->IntOf('payload.OrderItems[i].ProductInfo.NumberOfItems');
    $CurrencyCode = $json->StringOf('payload.OrderItems[i].ItemPrice.CurrencyCode');
    $Amount = $json->StringOf('payload.OrderItems[i].ItemPrice.Amount');
    $ItemTaxCurrencyCode = $json->StringOf('payload.OrderItems[i].ItemTax.CurrencyCode');
    $ItemTaxAmount = $json->StringOf('payload.OrderItems[i].ItemTax.Amount');
    $PromotionDiscountCurrencyCode = $json->StringOf('payload.OrderItems[i].PromotionDiscount.CurrencyCode');
    $PromotionDiscountAmount = $json->StringOf('payload.OrderItems[i].PromotionDiscount.Amount');
    $IsGift = $json->BoolOf('payload.OrderItems[i].IsGift');
    $ConditionId = $json->StringOf('payload.OrderItems[i].ConditionId');
    $ConditionSubtypeId = $json->StringOf('payload.OrderItems[i].ConditionSubtypeId');
    $IsTransparency = $json->BoolOf('payload.OrderItems[i].IsTransparency');
    $SerialNumberRequired = $json->BoolOf('payload.OrderItems[i].SerialNumberRequired');
    $IossNumber = $json->StringOf('payload.OrderItems[i].IossNumber');
    $DeemedResellerCategory = $json->StringOf('payload.OrderItems[i].DeemedResellerCategory');
    $StoreChainStoreId = $json->StringOf('payload.OrderItems[i].StoreChainStoreId');
    $IsBuyerRequestedCancel = $json->BoolOf('payload.OrderItems[i].BuyerRequestedCancel.IsBuyerRequestedCancel');
    $BuyerCancelReason = $json->StringOf('payload.OrderItems[i].BuyerRequestedCancel.BuyerCancelReason');
    $i = $i + 1;
}

print "Success!\n";