Sample code for 30+ languages & platforms
Swift

Amazon Pay - Create Checkout Session

See more Amazon Pay Examples

Create a new Amazon Pay Checkout Session.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    let http = CkoHttp()!

    // Implements the following CURL command:

    // curl "https://pay-api.amazon.com/:version/checkoutSessions/" \
    // -X POST
    // -H "authorization:Px2e5oHhQZ88vVhc0DO%2FsShHj8MDDg%3DEXAMPLESIGNATURE"
    // -H "x-amz-pay-date:20201012T235046Z"
    // -H "x-amz-pay-idempotency-key:AVLo5tI10BHgEk2jEXAMPLEKEY"
    // -d '{
    //     "webCheckoutDetails": {
    //         "checkoutReviewReturnUrl": "https://a.com/merchant-review-page"
    //     },
    //     "storeId": "amzn1.application-oa2-client.8b5e45312b5248b69eeaStoreId",
    //     "scopes": ["name", "email", "phoneNumber", "billingAddress"],
    //     "deliverySpecifications": {
    //         "specialRestrictions": ["RestrictPOBoxes"],
    //         "addressRestrictions": {
    //             "type": "Allowed",
    //             "restrictions": {
    //                 "US": {
    //                     "statesOrRegions": ["WA"],
    //                     "zipCodes": ["95050", "93405"]
    //                 },
    //                 "GB": {
    //                     "zipCodes": ["72046", "72047"]
    //                 },
    //                 "IN": {
    //                     "statesOrRegions": ["AP"]
    //                 },
    //                 "JP": {}
    //             }
    //         }
    //     }
    // }'

    // Use the following online tool to generate HTTP code from a CURL command
    // Convert a cURL Command to HTTP Source Code

    // Use this online tool to generate code from sample JSON:
    // Generate Code to Create JSON

    // The following JSON is sent in the request body.

    // {
    //   "webCheckoutDetails": {
    //     "checkoutReviewReturnUrl": "https://a.com/merchant-review-page"
    //   },
    //   "storeId": "amzn1.application-oa2-client.8b5e45312b5248b69eeaStoreId",
    //   "scopes": [
    //     "name",
    //     "email",
    //     "phoneNumber",
    //     "billingAddress"
    //   ],
    //   "deliverySpecifications": {
    //     "specialRestrictions": [
    //       "RestrictPOBoxes"
    //     ],
    //     "addressRestrictions": {
    //       "type": "Allowed",
    //       "restrictions": {
    //         "US": {
    //           "statesOrRegions": [
    //             "WA"
    //           ],
    //           "zipCodes": [
    //             "95050",
    //             "93405"
    //           ]
    //         },
    //         "GB": {
    //           "zipCodes": [
    //             "72046",
    //             "72047"
    //           ]
    //         },
    //         "IN": {
    //           "statesOrRegions": [
    //             "AP"
    //           ]
    //         },
    //         "JP": {}
    //       }
    //     }
    //   }
    // }

    let json = CkoJsonObject()!
    json.updateString(jsonPath: "webCheckoutDetails.checkoutReviewReturnUrl", value: "https://a.com/merchant-review-page")
    // Make sure to use your storeId here:
    json.updateString(jsonPath: "storeId", value: "amzn1.application-oa2-client.8b5e45312b5248b69eeaStoreId")
    var i: Int = 0
    json.i = i
    json.updateString(jsonPath: "scopes[i]", value: "name")
    i = i + 1
    json.i = i
    json.updateString(jsonPath: "scopes[i]", value: "email")
    i = i + 1
    json.i = i
    json.updateString(jsonPath: "scopes[i]", value: "phoneNumber")
    i = i + 1
    json.i = i
    json.updateString(jsonPath: "scopes[i]", value: "billingAddress")
    json.updateString(jsonPath: "deliverySpecifications.specialRestrictions[0]", value: "RestrictPOBoxes")
    json.updateString(jsonPath: "deliverySpecifications.addressRestrictions.type", value: "Allowed")
    json.updateString(jsonPath: "deliverySpecifications.addressRestrictions.restrictions.US.statesOrRegions[0]", value: "WA")
    json.updateString(jsonPath: "deliverySpecifications.addressRestrictions.restrictions.US.zipCodes[0]", value: "95050")
    json.updateString(jsonPath: "deliverySpecifications.addressRestrictions.restrictions.US.zipCodes[1]", value: "93405")
    json.updateString(jsonPath: "deliverySpecifications.addressRestrictions.restrictions.GB.zipCodes[0]", value: "72046")
    json.updateString(jsonPath: "deliverySpecifications.addressRestrictions.restrictions.GB.zipCodes[1]", value: "72047")
    json.updateString(jsonPath: "deliverySpecifications.addressRestrictions.restrictions.IN.statesOrRegions[0]", value: "AP")
    json.updateNew(jsonPath: "deliverySpecifications.addressRestrictions.restrictions.JP")

    // Load your Amazon Pay private key.  
    // There are many other ways to load private keys into the Chilkat private key object, such as from different formats,
    // or from in-memory strings or bytes.
    let privKey = CkoPrivateKey()!
    success = privKey.loadPemFile(path: "C:/someDir/myAmazonPayPrivateKey.pem")
    if success == false {
        print("\(privKey.lastErrorText!)")
        return
    }

    // Provide your Amazon Pay private key and Public Key ID 
    // Use your public key ID here.  It must be the one associated with the private key.
    // Note: The SetAuthPrivateKey method was added in Chilkat v9.5.0.89
    var publicKeyId: String? = "SANDBOX-AHEGSJCM3L2S637RBGABLAFW"
    success = http.setAuthPrivateKey(publicKeyId: publicKeyId, privKey: privKey)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    // Note: When the private key is provided as shown above, Chilkat will automatically add the required x-amz-pay-* headers to the HTTP request,
    // and will also sign the request.  Nothing more is needed.
    // Chilkat automatically generates and adds the following headers:
    // 
    // x-amz-pay-date
    // x-amz-pay-host
    // x-amz-pay-region
    // x-amz-pay-idempotency-key
    // Authorization

    http.accept = "application/json"

    // To use the live system, replace "sandbox" with "live" in the URL passed to HttpJson.
    // Also, make sure to use the correct region: pay-api.amazon.com, pay-api.amazon.eu, or pay-api.amazon.jp
    let resp = CkoHttpResponse()!
    success = http.httpJson(verb: "POST", url: "https://pay-api.amazon.eu/sandbox/v2/checkoutSessions/", json: json, contentType: "application/json", response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    let sbResponseBody = CkoStringBuilder()!
    resp.getBodySb(sb: sbResponseBody)
    let jResp = CkoJsonObject()!
    jResp.loadSb(sb: sbResponseBody)
    jResp.emitCompact = false

    // If the status code is not equal to 201, this will display error information.
    print("Response Body:")
    print("\(jResp.emit()!)")

    var respStatusCode: Int = resp.statusCode.intValue
    print("Response Status Code = \(respStatusCode)")
    if respStatusCode != 201 {

        // The jResp would've contained an error message, similar to this:
        // 	{
        // 	  "reasonCode": "InvalidHeaderValue",
        // 	  "message": "The value AF2EGWREIPHV2S2TUFFBRDGM provided for PublicKeyId is invalid. Please verify that you are using the PublicKeyId in the correct region and environment."
        // 	}

        print("Failed.")
        return
    }

    // Sample JSON response:
    // (Sample code for parsing the JSON response is shown below)

    // {
    //   "checkoutSessionId": "bd504926-f659-4ad7-a1a9-9a747aaf5275",
    //   "webCheckoutDetails": {
    //     "checkoutReviewReturnUrl": "https://a.com/merchant-review-page",
    //     "checkoutResultReturnUrl": null,
    //     "checkoutCancelUrl": null,
    //     "amazonPayRedirectUrl": null
    //   },
    //   "productType": "PayAndShip",
    //   "chargePermissionType": "Recurring",
    //   "recurringMetadata": {
    //     "frequency": {
    //       "unit": "Month",
    //       "value": "1"
    //     },
    //     "amount": {
    //       "amount": "30",
    //       "currencyCode": "USD"
    //     }
    //   },
    //   "paymentDetails": {
    //     "paymentIntent": null,
    //     "canHandlePendingAuthorization": false,
    //     "chargeAmount": null,
    //     "totalOrderAmount": null,
    //     "softDescriptor": null,
    //     "presentmentCurrency": null,
    //     "allowOvercharge": null,
    //     "extendExpiration": null
    //   },
    //   "merchantMetadata": {
    //     "merchantReferenceId": null,
    //     "merchantStoreName": null,
    //     "noteToBuyer": null,
    //     "customInformation": null
    //   },
    //   "supplementaryData": null,
    //   "buyer": null,
    //   "billingAddress": null,
    //   "paymentPreferences": [
    //     null
    //   ],
    //   "statusDetails": {
    //     "state": "Open",
    //     "reasonCode": null,
    //     "reasonDescription": null,
    //     "lastUpdatedTimestamp": "20191015T204327Z"
    //   },
    //   "shippingAddress": null,
    //   "platformId": null,
    //   "chargePermissionId": null,
    //   "chargeId": null,
    //   "constraints": [
    //     {
    //       "constraintId": "BuyerNotAssociated",
    //       "description": "There is no buyer associated with the Checkout Session. Return the checkout session id to the Amazon Pay Button to allow buyer to login."
    //     },
    //     {
    //       "constraintId": "ChargeAmountNotSet",
    //       "description": "chargeAmount is not set."
    //     },
    //     {
    //       "constraintId": "CheckoutResultReturnUrlNotSet",
    //       "description": "checkoutResultReturnUrl is not set."
    //     },
    //     {
    //       "constraintId": "PaymentIntentNotSet",
    //       "description": "paymentIntent is not set."
    //     }
    //   ],
    //   "creationTimestamp": "20191015T204313Z",
    //   "expirationTimestamp": "20191016T204313Z",
    //   "storeId": "amzn1.application-oa2-client.8b5e45312b5248b69eeaStoreId",
    //   "deliverySpecifications": {
    //     "specialRestrictions": [
    //       "RestrictPOBoxes"
    //     ],
    //     "addressRestrictions": {
    //       "type": "Allowed",
    //       "restrictions": {
    //         "US": {
    //           "statesOrRegions": [
    //             "WA"
    //           ],
    //           "zipCodes": [
    //             "95050",
    //             "93405"
    //           ]
    //         },
    //         "GB": {
    //           "zipCodes": [
    //             "72046",
    //             "72047"
    //           ]
    //         },
    //         "IN": {
    //           "statesOrRegions": [
    //             "AP"
    //           ]
    //         },
    //         "JP": {}
    //       }
    //     }
    //   },
    //   "providerMetadata": {
    //     "providerReferenceId": null
    //   },
    //   "releaseEnvironment": "Sandbox"
    // }

    // Sample code for parsing the JSON response...
    // Use the following online tool to generate parsing code from sample JSON:
    // Generate Parsing Code from JSON

    var nullVal: Bool
    var constraintId: String?
    var description: String?
    var strVal: String?

    var checkoutSessionId: String? = jResp.string(of: "checkoutSessionId")
    var webCheckoutDetailsCheckoutReviewReturnUrl: String? = jResp.string(of: "webCheckoutDetails.checkoutReviewReturnUrl")
    var webCheckoutDetailsCheckoutResultReturnUrl: String? = jResp.string(of: "webCheckoutDetails.checkoutResultReturnUrl")
    var webCheckoutDetailsCheckoutCancelUrl: String? = jResp.string(of: "webCheckoutDetails.checkoutCancelUrl")
    var webCheckoutDetailsAmazonPayRedirectUrl: String? = jResp.string(of: "webCheckoutDetails.amazonPayRedirectUrl")
    var productType: String? = jResp.string(of: "productType")
    var chargePermissionType: String? = jResp.string(of: "chargePermissionType")
    var recurringMetadataFrequencyUnit: String? = jResp.string(of: "recurringMetadata.frequency.unit")
    var recurringMetadataFrequencyValue: String? = jResp.string(of: "recurringMetadata.frequency.value")
    var recurringMetadataAmountAmount: String? = jResp.string(of: "recurringMetadata.amount.amount")
    var recurringMetadataAmountCurrencyCode: String? = jResp.string(of: "recurringMetadata.amount.currencyCode")
    var paymentDetailsPaymentIntent: String? = jResp.string(of: "paymentDetails.paymentIntent")
    var paymentDetailsCanHandlePendingAuthorization: Bool = jResp.bool(of: "paymentDetails.canHandlePendingAuthorization")
    var paymentDetailsChargeAmount: String? = jResp.string(of: "paymentDetails.chargeAmount")
    var paymentDetailsTotalOrderAmount: String? = jResp.string(of: "paymentDetails.totalOrderAmount")
    var paymentDetailsSoftDescriptor: String? = jResp.string(of: "paymentDetails.softDescriptor")
    var paymentDetailsPresentmentCurrency: String? = jResp.string(of: "paymentDetails.presentmentCurrency")
    var paymentDetailsAllowOvercharge: String? = jResp.string(of: "paymentDetails.allowOvercharge")
    var paymentDetailsExtendExpiration: String? = jResp.string(of: "paymentDetails.extendExpiration")
    var merchantMetadataMerchantReferenceId: String? = jResp.string(of: "merchantMetadata.merchantReferenceId")
    var merchantMetadataMerchantStoreName: String? = jResp.string(of: "merchantMetadata.merchantStoreName")
    var merchantMetadataNoteToBuyer: String? = jResp.string(of: "merchantMetadata.noteToBuyer")
    var merchantMetadataCustomInformation: String? = jResp.string(of: "merchantMetadata.customInformation")
    var supplementaryData: String? = jResp.string(of: "supplementaryData")
    var buyer: String? = jResp.string(of: "buyer")
    var billingAddress: String? = jResp.string(of: "billingAddress")
    var statusDetailsState: String? = jResp.string(of: "statusDetails.state")
    var statusDetailsReasonCode: String? = jResp.string(of: "statusDetails.reasonCode")
    var statusDetailsReasonDescription: String? = jResp.string(of: "statusDetails.reasonDescription")
    var statusDetailsLastUpdatedTimestamp: String? = jResp.string(of: "statusDetails.lastUpdatedTimestamp")
    var shippingAddress: String? = jResp.string(of: "shippingAddress")
    var platformId: String? = jResp.string(of: "platformId")
    var chargePermissionId: String? = jResp.string(of: "chargePermissionId")
    var chargeId: String? = jResp.string(of: "chargeId")
    var creationTimestamp: String? = jResp.string(of: "creationTimestamp")
    var expirationTimestamp: String? = jResp.string(of: "expirationTimestamp")
    var storeId: String? = jResp.string(of: "storeId")
    var deliverySpecificationsAddressRestrictionsType: String? = jResp.string(of: "deliverySpecifications.addressRestrictions.type")
    var providerMetadataProviderReferenceId: String? = jResp.string(of: "providerMetadata.providerReferenceId")
    var releaseEnvironment: String? = jResp.string(of: "releaseEnvironment")
    i = 0
    var count_i: Int = jResp.size(ofArray: "paymentPreferences").intValue
    while i < count_i {
        jResp.i = i
        nullVal = jResp.isNull(of: "paymentPreferences[i]")
        i = i + 1
    }

    i = 0
    count_i = jResp.size(ofArray: "constraints").intValue
    while i < count_i {
        jResp.i = i
        constraintId = jResp.string(of: "constraints[i].constraintId")
        description = jResp.string(of: "constraints[i].description")
        i = i + 1
    }

    i = 0
    count_i = jResp.size(ofArray: "deliverySpecifications.specialRestrictions").intValue
    while i < count_i {
        jResp.i = i
        strVal = jResp.string(of: "deliverySpecifications.specialRestrictions[i]")
        i = i + 1
    }

    i = 0
    count_i = jResp.size(ofArray: "deliverySpecifications.addressRestrictions.restrictions.US.statesOrRegions").intValue
    while i < count_i {
        jResp.i = i
        strVal = jResp.string(of: "deliverySpecifications.addressRestrictions.restrictions.US.statesOrRegions[i]")
        i = i + 1
    }

    i = 0
    count_i = jResp.size(ofArray: "deliverySpecifications.addressRestrictions.restrictions.US.zipCodes").intValue
    while i < count_i {
        jResp.i = i
        strVal = jResp.string(of: "deliverySpecifications.addressRestrictions.restrictions.US.zipCodes[i]")
        i = i + 1
    }

    i = 0
    count_i = jResp.size(ofArray: "deliverySpecifications.addressRestrictions.restrictions.GB.zipCodes").intValue
    while i < count_i {
        jResp.i = i
        strVal = jResp.string(of: "deliverySpecifications.addressRestrictions.restrictions.GB.zipCodes[i]")
        i = i + 1
    }

    i = 0
    count_i = jResp.size(ofArray: "deliverySpecifications.addressRestrictions.restrictions.IN.statesOrRegions").intValue
    while i < count_i {
        jResp.i = i
        strVal = jResp.string(of: "deliverySpecifications.addressRestrictions.restrictions.IN.statesOrRegions[i]")
        i = i + 1
    }


}