Swift
Swift
Amazon SP-API Get Specific Order
See more Amazon SP-API Examples
Get a specific Amazon Seller order.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// 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
var orderId: String? = "TEST_CASE_200"
let authAws = CkoAuthAws()!
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
let jsonLwaToken = CkoJsonObject()!
success = jsonLwaToken.loadFile(path: "qa_data/tokens/sp_api_lwa_token.json")
if success == false {
print("Failed to load LWA access token.")
return
}
// Must use the non-sandbox domain for getting the RDT.
let rest = CkoRest()!
success = rest.connect(hostname: "sellingpartnerapi-eu.amazon.com", port: 443, tls: true, autoReconnect: true)
if success == false {
print("\(rest.lastErrorText!)")
return
}
success = rest.setAuthAws(authProvider: authAws)
// Add the x-amz-access-token request header.
var lwa_token: String? = jsonLwaToken.string(of: "access_token")
rest.clearAllHeaders()
rest.addHeader(name: "x-amz-access-token", value: 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"]
// }
// ]
// }
let sbPath = CkoStringBuilder()!
sbPath.append(value: "/orders/v0/orders/")
sbPath.append(value: orderId)
let jsonRc = CkoJsonObject()!
jsonRc.updateString(jsonPath: "restrictedResources[0].method", value: "GET")
jsonRc.updateString(jsonPath: "restrictedResources[0].path", value: sbPath.getAsString())
jsonRc.updateString(jsonPath: "restrictedResources[0].dataElements[0]", value: "buyerInfo")
jsonRc.updateString(jsonPath: "restrictedResources[0].dataElements[1]", value: "shippingAddress")
let sbRequest = CkoStringBuilder()!
jsonRc.emitSb(sb: sbRequest)
let sbResponse = CkoStringBuilder()!
var uri: String? = "/tokens/2021-03-01/restrictedDataToken"
success = rest.fullRequestSb(httpVerb: "POST", uriPath: uri, requestBody: sbRequest, responseBody: sbResponse)
if success == false {
print("\(rest.lastErrorText!)")
return
}
// Examine the response status.
var statusCode: Int = rest.responseStatusCode.intValue
if statusCode != 200 {
print("Response status code: \(statusCode)")
print("Response status text: \(rest.responseStatusText!)")
print("Response body: ")
print("\(sbResponse.getAsString()!)")
print("Failed.")
return
}
// Get the restricted data token.
let jsonResp = CkoJsonObject()!
jsonResp.loadSb(sb: sbResponse)
var restrictedDataToken: String? = 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(maxWaitMs: 100)
success = rest.connect(hostname: "sandbox.sellingpartnerapi-eu.amazon.com", port: 443, tls: true, autoReconnect: true)
if success == false {
print("\(rest.lastErrorText!)")
return
}
success = rest.setAuthAws(authProvider: authAws)
rest.clearAllHeaders()
rest.addHeader(name: "x-amz-access-token", value: restrictedDataToken)
rest.clearAllQueryParams()
rest.addQueryParam(name: "MarketplaceIds", value: "ATVPDKIKX0DER")
rest.clearAllPathParams()
rest.addPathParam(name: "{orderId}", value: orderId)
uri = "/orders/v0/orders/{orderId}"
success = rest.fullRequestNoBodySb(httpVerb: "GET", uriPath: uri, sb: sbResponse)
if success == false {
print("\(rest.lastErrorText!)")
return
}
// Examine the response status.
statusCode = rest.responseStatusCode.intValue
if statusCode != 200 {
print("Response status text: \(rest.responseStatusText!)")
print("Response body: ")
print("\(sbResponse.getAsString()!)")
print("Failed.")
return
}
print("\(sbResponse.getAsString()!)")
// 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
let json = CkoJsonObject()!
json.loadSb(sb: sbResponse)
var strVal: String?
var AmazonOrderId: String? = json.string(of: "payload.AmazonOrderId")
var PurchaseDate: String? = json.string(of: "payload.PurchaseDate")
var LastUpdateDate: String? = json.string(of: "payload.LastUpdateDate")
var OrderStatus: String? = json.string(of: "payload.OrderStatus")
var FulfillmentChannel: String? = json.string(of: "payload.FulfillmentChannel")
var SalesChannel: String? = json.string(of: "payload.SalesChannel")
var ShipServiceLevel: String? = json.string(of: "payload.ShipServiceLevel")
var CurrencyCode: String? = json.string(of: "payload.OrderTotal.CurrencyCode")
var Amount: String? = json.string(of: "payload.OrderTotal.Amount")
var NumberOfItemsShipped: Int = json.int(of: "payload.NumberOfItemsShipped").intValue
var NumberOfItemsUnshipped: Int = json.int(of: "payload.NumberOfItemsUnshipped").intValue
var PaymentMethod: String? = json.string(of: "payload.PaymentMethod")
var IsReplacementOrder: Bool = json.bool(of: "payload.IsReplacementOrder")
var MarketplaceId: String? = json.string(of: "payload.MarketplaceId")
var ShipmentServiceLevelCategory: String? = json.string(of: "payload.ShipmentServiceLevelCategory")
var OrderType: String? = json.string(of: "payload.OrderType")
var EarliestShipDate: String? = json.string(of: "payload.EarliestShipDate")
var LatestShipDate: String? = json.string(of: "payload.LatestShipDate")
var EarliestDeliveryDate: String? = json.string(of: "payload.EarliestDeliveryDate")
var LatestDeliveryDate: String? = json.string(of: "payload.LatestDeliveryDate")
var IsBusinessOrder: Bool = json.bool(of: "payload.IsBusinessOrder")
var IsPrime: Bool = json.bool(of: "payload.IsPrime")
var IsGlobalExpressEnabled: Bool = json.bool(of: "payload.IsGlobalExpressEnabled")
var IsPremiumOrder: Bool = json.bool(of: "payload.IsPremiumOrder")
var IsSoldByAB: Bool = json.bool(of: "payload.IsSoldByAB")
var IsIBA: Bool = json.bool(of: "payload.IsIBA")
var Name: String? = json.string(of: "payload.DefaultShipFromLocationAddress.Name")
var AddressLine1: String? = json.string(of: "payload.DefaultShipFromLocationAddress.AddressLine1")
var City: String? = json.string(of: "payload.DefaultShipFromLocationAddress.City")
var StateOrRegion: String? = json.string(of: "payload.DefaultShipFromLocationAddress.StateOrRegion")
var PostalCode: String? = json.string(of: "payload.DefaultShipFromLocationAddress.PostalCode")
var CountryCode: String? = json.string(of: "payload.DefaultShipFromLocationAddress.CountryCode")
var Phone: String? = json.string(of: "payload.DefaultShipFromLocationAddress.Phone")
var AddressType: String? = json.string(of: "payload.DefaultShipFromLocationAddress.AddressType")
var FulfillmentSupplySourceId: String? = json.string(of: "payload.FulfillmentInstruction.FulfillmentSupplySourceId")
var IsISPU: Bool = json.bool(of: "payload.IsISPU")
var IsAccessPointOrder: Bool = json.bool(of: "payload.IsAccessPointOrder")
var HasAutomatedShippingSettings: Bool = json.bool(of: "payload.AutomatedShippingSettings.HasAutomatedShippingSettings")
var EasyShipShipmentStatus: String? = json.string(of: "payload.EasyShipShipmentStatus")
var ElectronicInvoiceStatus: String? = json.string(of: "payload.ElectronicInvoiceStatus")
var i: Int = 0
var count_i: Int = json.size(ofArray: "payload.PaymentMethodDetails").intValue
while i < count_i {
json.i = i
strVal = json.string(of: "payload.PaymentMethodDetails[i]")
i = i + 1
}
print("Success!")
}