Sample code for 30+ languages & platforms
Unicode C

Amazon Pay - Create Checkout Session

See more Amazon Pay Examples

Create a new Amazon Pay Checkout Session.

Chilkat Unicode C Downloads

Unicode C
#include <C_CkHttpW.h>
#include <C_CkJsonObjectW.h>
#include <C_CkPrivateKeyW.h>
#include <C_CkHttpResponseW.h>
#include <C_CkStringBuilderW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkHttpW http;
    HCkJsonObjectW json;
    int i;
    HCkPrivateKeyW privKey;
    const wchar_t *publicKeyId;
    HCkHttpResponseW resp;
    HCkStringBuilderW sbResponseBody;
    HCkJsonObjectW jResp;
    int respStatusCode;
    BOOL nullVal;
    const wchar_t *constraintId;
    const wchar_t *description;
    const wchar_t *strVal;
    const wchar_t *checkoutSessionId;
    const wchar_t *webCheckoutDetailsCheckoutReviewReturnUrl;
    const wchar_t *webCheckoutDetailsCheckoutResultReturnUrl;
    const wchar_t *webCheckoutDetailsCheckoutCancelUrl;
    const wchar_t *webCheckoutDetailsAmazonPayRedirectUrl;
    const wchar_t *productType;
    const wchar_t *chargePermissionType;
    const wchar_t *recurringMetadataFrequencyUnit;
    const wchar_t *recurringMetadataFrequencyValue;
    const wchar_t *recurringMetadataAmountAmount;
    const wchar_t *recurringMetadataAmountCurrencyCode;
    const wchar_t *paymentDetailsPaymentIntent;
    BOOL paymentDetailsCanHandlePendingAuthorization;
    const wchar_t *paymentDetailsChargeAmount;
    const wchar_t *paymentDetailsTotalOrderAmount;
    const wchar_t *paymentDetailsSoftDescriptor;
    const wchar_t *paymentDetailsPresentmentCurrency;
    const wchar_t *paymentDetailsAllowOvercharge;
    const wchar_t *paymentDetailsExtendExpiration;
    const wchar_t *merchantMetadataMerchantReferenceId;
    const wchar_t *merchantMetadataMerchantStoreName;
    const wchar_t *merchantMetadataNoteToBuyer;
    const wchar_t *merchantMetadataCustomInformation;
    const wchar_t *supplementaryData;
    const wchar_t *buyer;
    const wchar_t *billingAddress;
    const wchar_t *statusDetailsState;
    const wchar_t *statusDetailsReasonCode;
    const wchar_t *statusDetailsReasonDescription;
    const wchar_t *statusDetailsLastUpdatedTimestamp;
    const wchar_t *shippingAddress;
    const wchar_t *platformId;
    const wchar_t *chargePermissionId;
    const wchar_t *chargeId;
    const wchar_t *creationTimestamp;
    const wchar_t *expirationTimestamp;
    const wchar_t *storeId;
    const wchar_t *deliverySpecificationsAddressRestrictionsType;
    const wchar_t *providerMetadataProviderReferenceId;
    const wchar_t *releaseEnvironment;
    int count_i;

    success = FALSE;

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

    http = CkHttpW_Create();

    //  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": {}
    //        }
    //      }
    //    }
    //  }

    json = CkJsonObjectW_Create();
    CkJsonObjectW_UpdateString(json,L"webCheckoutDetails.checkoutReviewReturnUrl",L"https://a.com/merchant-review-page");
    //  Make sure to use your storeId here:
    CkJsonObjectW_UpdateString(json,L"storeId",L"amzn1.application-oa2-client.8b5e45312b5248b69eeaStoreId");
    i = 0;
    CkJsonObjectW_putI(json,i);
    CkJsonObjectW_UpdateString(json,L"scopes[i]",L"name");
    i = i + 1;
    CkJsonObjectW_putI(json,i);
    CkJsonObjectW_UpdateString(json,L"scopes[i]",L"email");
    i = i + 1;
    CkJsonObjectW_putI(json,i);
    CkJsonObjectW_UpdateString(json,L"scopes[i]",L"phoneNumber");
    i = i + 1;
    CkJsonObjectW_putI(json,i);
    CkJsonObjectW_UpdateString(json,L"scopes[i]",L"billingAddress");
    CkJsonObjectW_UpdateString(json,L"deliverySpecifications.specialRestrictions[0]",L"RestrictPOBoxes");
    CkJsonObjectW_UpdateString(json,L"deliverySpecifications.addressRestrictions.type",L"Allowed");
    CkJsonObjectW_UpdateString(json,L"deliverySpecifications.addressRestrictions.restrictions.US.statesOrRegions[0]",L"WA");
    CkJsonObjectW_UpdateString(json,L"deliverySpecifications.addressRestrictions.restrictions.US.zipCodes[0]",L"95050");
    CkJsonObjectW_UpdateString(json,L"deliverySpecifications.addressRestrictions.restrictions.US.zipCodes[1]",L"93405");
    CkJsonObjectW_UpdateString(json,L"deliverySpecifications.addressRestrictions.restrictions.GB.zipCodes[0]",L"72046");
    CkJsonObjectW_UpdateString(json,L"deliverySpecifications.addressRestrictions.restrictions.GB.zipCodes[1]",L"72047");
    CkJsonObjectW_UpdateString(json,L"deliverySpecifications.addressRestrictions.restrictions.IN.statesOrRegions[0]",L"AP");
    CkJsonObjectW_UpdateNewObject(json,L"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.
    privKey = CkPrivateKeyW_Create();
    success = CkPrivateKeyW_LoadPemFile(privKey,L"C:/someDir/myAmazonPayPrivateKey.pem");
    if (success == FALSE) {
        wprintf(L"%s\n",CkPrivateKeyW_lastErrorText(privKey));
        CkHttpW_Dispose(http);
        CkJsonObjectW_Dispose(json);
        CkPrivateKeyW_Dispose(privKey);
        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
    publicKeyId = L"SANDBOX-AHEGSJCM3L2S637RBGABLAFW";
    success = CkHttpW_SetAuthPrivateKey(http,publicKeyId,privKey);
    if (success == FALSE) {
        wprintf(L"%s\n",CkHttpW_lastErrorText(http));
        CkHttpW_Dispose(http);
        CkJsonObjectW_Dispose(json);
        CkPrivateKeyW_Dispose(privKey);
        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

    CkHttpW_putAccept(http,L"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
    resp = CkHttpResponseW_Create();
    success = CkHttpW_HttpJson(http,L"POST",L"https://pay-api.amazon.eu/sandbox/v2/checkoutSessions/",json,L"application/json",resp);
    if (success == FALSE) {
        wprintf(L"%s\n",CkHttpW_lastErrorText(http));
        CkHttpW_Dispose(http);
        CkJsonObjectW_Dispose(json);
        CkPrivateKeyW_Dispose(privKey);
        CkHttpResponseW_Dispose(resp);
        return;
    }

    sbResponseBody = CkStringBuilderW_Create();
    CkHttpResponseW_GetBodySb(resp,sbResponseBody);
    jResp = CkJsonObjectW_Create();
    CkJsonObjectW_LoadSb(jResp,sbResponseBody);
    CkJsonObjectW_putEmitCompact(jResp,FALSE);

    //  If the status code is not equal to 201, this will display error information.
    wprintf(L"Response Body:\n");
    wprintf(L"%s\n",CkJsonObjectW_emit(jResp));

    respStatusCode = CkHttpResponseW_getStatusCode(resp);
    wprintf(L"Response Status Code = %d\n",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."
        //  	}

        wprintf(L"Failed.\n");
        CkHttpW_Dispose(http);
        CkJsonObjectW_Dispose(json);
        CkPrivateKeyW_Dispose(privKey);
        CkHttpResponseW_Dispose(resp);
        CkStringBuilderW_Dispose(sbResponseBody);
        CkJsonObjectW_Dispose(jResp);
        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

    //  Chilkat functions returning "const char *" return a pointer to temporary internal memory owned and managed by Chilkat.
    //  See this example explaining how this memory should be used: const char * functions.

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

    i = 0;
    count_i = CkJsonObjectW_SizeOfArray(jResp,L"constraints");
    while (i < count_i) {
        CkJsonObjectW_putI(jResp,i);
        constraintId = CkJsonObjectW_stringOf(jResp,L"constraints[i].constraintId");
        description = CkJsonObjectW_stringOf(jResp,L"constraints[i].description");
        i = i + 1;
    }

    i = 0;
    count_i = CkJsonObjectW_SizeOfArray(jResp,L"deliverySpecifications.specialRestrictions");
    while (i < count_i) {
        CkJsonObjectW_putI(jResp,i);
        strVal = CkJsonObjectW_stringOf(jResp,L"deliverySpecifications.specialRestrictions[i]");
        i = i + 1;
    }

    i = 0;
    count_i = CkJsonObjectW_SizeOfArray(jResp,L"deliverySpecifications.addressRestrictions.restrictions.US.statesOrRegions");
    while (i < count_i) {
        CkJsonObjectW_putI(jResp,i);
        strVal = CkJsonObjectW_stringOf(jResp,L"deliverySpecifications.addressRestrictions.restrictions.US.statesOrRegions[i]");
        i = i + 1;
    }

    i = 0;
    count_i = CkJsonObjectW_SizeOfArray(jResp,L"deliverySpecifications.addressRestrictions.restrictions.US.zipCodes");
    while (i < count_i) {
        CkJsonObjectW_putI(jResp,i);
        strVal = CkJsonObjectW_stringOf(jResp,L"deliverySpecifications.addressRestrictions.restrictions.US.zipCodes[i]");
        i = i + 1;
    }

    i = 0;
    count_i = CkJsonObjectW_SizeOfArray(jResp,L"deliverySpecifications.addressRestrictions.restrictions.GB.zipCodes");
    while (i < count_i) {
        CkJsonObjectW_putI(jResp,i);
        strVal = CkJsonObjectW_stringOf(jResp,L"deliverySpecifications.addressRestrictions.restrictions.GB.zipCodes[i]");
        i = i + 1;
    }

    i = 0;
    count_i = CkJsonObjectW_SizeOfArray(jResp,L"deliverySpecifications.addressRestrictions.restrictions.IN.statesOrRegions");
    while (i < count_i) {
        CkJsonObjectW_putI(jResp,i);
        strVal = CkJsonObjectW_stringOf(jResp,L"deliverySpecifications.addressRestrictions.restrictions.IN.statesOrRegions[i]");
        i = i + 1;
    }



    CkHttpW_Dispose(http);
    CkJsonObjectW_Dispose(json);
    CkPrivateKeyW_Dispose(privKey);
    CkHttpResponseW_Dispose(resp);
    CkStringBuilderW_Dispose(sbResponseBody);
    CkJsonObjectW_Dispose(jResp);

    }