# Amazon Pay API Integration

* [Creating Amazon Pay App And Adding Your Domain](#checkoutchampamazonpayapiintegration-creatingamazonpayappandaddingyourdomain)
* [Obtain Amazon Pay MID Credentials](#checkoutchampamazonpayapiintegration-obtainamazonpaymidcredentials)
* [Create Amazon Pay MID](#checkoutchampamazonpayapiintegration-createamazonpaymid)
* [Add Amazon Pay Widgets and JavaScript to Your Lander Code](#checkoutchampamazonpayapiintegration-addamazonpaywidgetsandjavascripttoyourlandercode)
* [Send Amazon Pay Parameters with Import Order API Call](#checkoutchampamazonpayapiintegration-sendamazonpayparameterswithimportorderapicall)
* [Transaction Flow](#checkoutchampamazonpayapiintegration-transactionflow)
* [Upsells](#checkoutchampamazonpayapiintegration-upsells)
* [Enable Recurring Payments](#checkoutchampamazonpayapiintegration-enablerecurringpayments)
* [Errors/Decline Messages](#checkoutchampamazonpayapiintegration-errors-declinemessages)

### Creating Amazon Pay App And Adding Your Domain <a href="#checkoutchampamazonpayapiintegration-creatingamazonpayappandaddingyourdomain" id="checkoutchampamazonpayapiintegration-creatingamazonpayappandaddingyourdomain"></a>

1. Log in to <https://sellercentral.amazon.com>
2. Go to **Integration → Integration Central**
3. Go to **Manage client ID/store ID(s)** section at the bottom of the page and click “**Create new client ID/store ID**” or click “**View client ID/store ID(s)**” and “**Edit**” to update existing app.
4. Add your lander domain to **JavaScript origins** and **return URLs** and create or update.

### Obtain Amazon Pay MID Credentials <a href="#checkoutchampamazonpayapiintegration-obtainamazonpaymidcredentials" id="checkoutchampamazonpayapiintegration-obtainamazonpaymidcredentials"></a>

1. Log in to <https://sellercentral.amazon.com>
2. Go to **Integration** → **MWS Access Key**
3. Click the gold “**Copy your keys**” button at the top right
4. Copy the credentials shown in the popup.

### Create Amazon Pay MID <a href="#checkoutchampamazonpayapiintegration-createamazonpaymid" id="checkoutchampamazonpayapiintegration-createamazonpaymid"></a>

1. In the CRM, go to Merchants->MID List
2. Click the green plus sign to create a new MID
3. Select **Amazon Pay** as Gateway field
4. Fill in copied credentials (**merchant\_id, access\_key, secret\_key, client\_id, client\_secret**)
5. Fill in MID Title, Descriptor, MID #
6. Click “Create MID”

### Add Amazon Pay Widgets and JavaScript to Your Lander Code <a href="#checkoutchampamazonpayapiintegration-addamazonpaywidgetsandjavascripttoyourlandercode" id="checkoutchampamazonpayapiintegration-addamazonpaywidgetsandjavascripttoyourlandercode"></a>

Sample Code from Amazon docs:

```
<head>
  <script type='text/javascript'>
    window.onAmazonLoginReady = function() {
      amazon.Login.setClientId('your Amazon Pay client_id');
    };
    window.onAmazonPaymentsReady = function() {
      //get parameters from the URL query string
      const urlParams = new URLSearchParams(window.location.search);
      //access_token will be returned in URL after customer has logged into Amazon
      //access_token needs to be sent in Import Order API calls as amazonAddressConsent parameter
      if(urlParams.has("access_token")) {
        const amazonAccessToken = urlParams.get("access_token");
        //get Amazon profile details: username, email address, userID
        //Send profileResponse.email as emailAddress parameter on Import Order API call
        //Parse profileResponse.name and send as firstName and lastName parameters on Import Order API call
        let profileResponse;
        $.ajax({
            async: false,
            type: "GET",
            // cors: true,
            headers: {
                "Authorization": "bearer "+amazonAccessToken 
            },
            url: "https://api.amazon.com/user/profile",
            success: function (result) {
                profileResponse = result;
            },
            error: function (xhr) {
                return xhr.status;
            }
        });
        showAddressBook();
        showWallet();
      } else {
         showButton();
      }
    };
  </script>
    <script async="async" src='https://static-na.payments-amazon.com/OffAmazonPayments/us/js/Widgets.js'>
  </script>
</head>

<body>
. . .
 <div id="AmazonPayButton">
 </div>
 <div id="addressBookWidgetDiv">
 </div>
 <div id="walletWidgetDiv">
 </div>
  ...
 <script type="text/javascript">
    function showButton(){
      var authRequest; 
      OffAmazonPayments.Button("AmazonPayButton", "your Amazon Pay merchant_id", { 
        type:  "TYPE (choose LwA or PwA)", 
        color: "COLOR (choose between Gold, LightGray, DarkGray)", 
        size:  "SIZE (choose between small, medium, large, x-large)", 

        authorization: function() { 
        loginOptions = {scope: "profile payments:widget payments:shipping_address", 
          popup: "true"}; 
        authRequest = amazon.Login.authorize (loginOptions, 
          window.location.href); 
        }, 
 
        onError: function(error) { 
          // your error handling code.
          // alert("The following error occurred: " 
          //        + error.getErrorCode() 
          //        + ' - ' + error.getErrorMessage());
        } 
     });
    }; 
   </script>
   <script>
   function showAddressBook() {
    new OffAmazonPayments.Widgets.AddressBook({
      sellerId: 'your Amazon Pay merchant_id',
      onOrderReferenceCreate: function(orderReference) {
        // Here is where you can grab the Order Reference ID.
        //send this in the Import Order API as the amazonOrderId parameter
        orderReference.getAmazonOrderReferenceId();
      },
      onAddressSelect: function(orderReference) {
        // Replace the following code with the action that you want
        // to perform after the address is selected. The
        // amazonOrderReferenceId can be used to retrieve the address
        // details by calling the GetOrderReferenceDetails operation.
  
        // If rendering the AddressBook and Wallet widgets
        // on the same page, you do not have to provide any additional
        // logic to load the Wallet widget after the AddressBook widget.
  
        // The Wallet widget will re-render itself on all subsequent
        // onAddressSelect events without any action from you.
        // We don't recommend that you explicitly refresh it.
      },
      design: {
        designMode: 'responsive'
      },
      onReady: function(orderReference) {
        // Enter code here that you want to be executed
        // when the address widget has been rendered.
      },
  
      onError: function(error) {
        // Your error handling code.
        // During development you can use the following
        // code to view error messages:
        // console.log(error.getErrorCode() + ': ' + error.getErrorMessage());
        // See "Handling Errors" for more information.
      }
    }).bind("addressBookWidgetDiv");
  }
</script>
<script>
function showWallet(){
  new OffAmazonPayments.Widgets.Wallet({
    sellerId: 'your Amazon Pay merchant_id',
    onPaymentSelect: function(orderReference) {
      // Replace this code with the action that you want to perform
      // after the payment method is chosen.

      // Ideally this would enable the next action for the buyer
      // including either a "Continue" or "Place Order" button.
    },
    design: {
      designMode: 'responsive'
    },

    onError: function(error) {
      // Your error handling code.
      // During development you can use the following
      // code to view error messages:
      // console.log(error.getErrorCode() + ': ' + error.getErrorMessage());
      // See "Handling Errors" for more information.
    }
  }).bind("walletWidgetDiv");
}
</script>
   . . .
   <script type="text/javascript">
     document.getElementById('Logout').onclick = function() {
       amazon.Login.logout();
     };
   </script>

</body>
```

For more information on adding Amazon Pay widgets and Javascript visit <https://developer.amazon.com/docs/amazon-pay-onetime/add-a-button.html>

### Send Amazon Pay Parameters with Import Order API Call <a href="#checkoutchampamazonpayapiintegration-sendamazonpayparameterswithimportorderapicall" id="checkoutchampamazonpayapiintegration-sendamazonpayparameterswithimportorderapicall"></a>

Send these parameters during Import Order API call

* **paySource**: “AMAZON”
* **amazonBillerId**: ID of Amazon Pay MID in the CRM (found on the MID List page)
* **amazonAddressConsent**: access\_token returned to your checkout page via the URL by Amazon
* **amazonOrderId**: obtained in the AddressBook `onOrderReferenceCreate` function with `orderReference.getAmazonOrderReferenceId();`

### Transaction Flow <a href="#checkoutchampamazonpayapiintegration-transactionflow" id="checkoutchampamazonpayapiintegration-transactionflow"></a>

Customer clicks Amazon-generated Amazon Pay button on checkout page.

<figure><img src="/files/E4M7s1qG7oXqzPX3seXB" alt=""><figcaption></figcaption></figure>

New window pops up for customer to log into Amazon

<figure><img src="/files/iFyEIvNAj8M9AfP785WW" alt=""><figcaption></figcaption></figure>

Customer returned to checkout page with **access\_token** in URL query string.

access\_token is used with Amazon profile API to obtain the firstName, lastName, and emailAddress parameters to send on Import Order API call. Send profileResponse.email as **emailAddress** parameter on Import Order API call. Parse profileResponse.name and send as **firstName** and **lastName** parameters on Import Order API call.

Call functions to display the Amazon AddressBook and Wallet widgets.

Obtain Amazon Order Reference ID to send on Import Order API call as **amazonOrderId** parameter in the AddressBook `onOrderReferenceCreate` function with `orderReference.getAmazonOrderReferenceId();`

Customer chooses shipping address and payment method from Amazon-generated widgets.

<figure><img src="/files/eJnzcs3RsXDtANr8kn2n" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/96LU5ce77FMUmyezz1NV" alt=""><figcaption></figcaption></figure>

Import Order with parameters: **paySource**=AMAZON, **amazonBillerId**, **amazonOrderId**, **amazonAddressConsent** (access\_token).

### Upsells <a href="#checkoutchampamazonpayapiintegration-upsells" id="checkoutchampamazonpayapiintegration-upsells"></a>

Repeat JavaScript process on your upsell page and send **amazonBillerId**, **amazonOrderId**, **amazonAddressConsent** on Import Upsale API call.

### Enable Recurring Payments <a href="#checkoutchampamazonpayapiintegration-enablerecurringpayments" id="checkoutchampamazonpayapiintegration-enablerecurringpayments"></a>

Follow the same integration steps as for one-time payments above and replace the Amazon AddressBook and Wallet widget code and add the Consent widget code as follows:

```
<script>
  new OffAmazonPayments.Widgets.AddressBook({
    sellerId: 'your Amazon Pay merchant_id',
    agreementType: 'BillingAgreement',
     
    onReady: function(billingAgreement) {
      var billingAgreementId = billingAgreement.
      getAmazonBillingAgreementId();
    },
    onAddressSelect: function(billingAgreement) {
      // Replace the following code with the action that you want to perform
      // after the address is selected.
      // The amazonBillingAgreementId can be used to retrieve
      // the address details by calling the GetBillingAgreementDetails operation.
      // If rendering the AddressBook and Wallet widgets on the same page, you
      // should wait for this event before you render the Wallet widget for
      // the first time.
      // The Wallet widget re-renders itself on all subsequent
      // onAddressSelect events without any action from you. We don't
      // recommend that you explicitly refresh it.
    },
    design: {
      designMode: 'responsive'
    },
    onError: function(error) {
      // your error handling code
    }
  }).bind("addressBookWidgetDiv");
</script>
```

```
<script>
  new OffAmazonPayments.Widgets.Wallet({
    sellerId: 'your Amazon Pay merchant_id',
    // amazonBillingAgreementId obtained from the AddressBook widget
    amazonBillingAgreementId: amazonBillingAgreementId,
    onPaymentSelect: function(billingAgreement) {
      // Replace this code with the action that you want to perform
      // after the payment method is selected.
    },
    design: {
      designMode: 'responsive'
    },
    onError: function(error) {
      // your error handling code
    }
  }).bind("walletWidgetDiv");
</script>
```

```
<div id="consentWidgetDiv">
</div>
<script>
new OffAmazonPayments.Widgets.Consent({
  sellerId: 'your Amazon Pay merchant_id',
  // amazonBillingAgreementId obtained from the Amazon Address Book widget. 
  amazonBillingAgreementId: amazonBillingAgreementId, 
  design: {
    designMode: 'responsive'
  },
  onReady: function(billingAgreementConsentStatus){
    // Called after widget renders
    buyerBillingAgreementConsentStatus =
      billingAgreementConsentStatus.getConsentStatus();
    // getConsentStatus returns true or false
    // true - checkbox is selected
    // false - checkbox is unselected - default
  },
  onConsent: function(billingAgreementConsentStatus) {
    buyerBillingAgreementConsentStatus =
      billingAgreementConsentStatus.getConsentStatus();
    // getConsentStatus returns true or false
    // true - checkbox is selected - buyer has consented
    // false - checkbox is unselected - buyer has not consented

    // Replace this code with the action that you want to perform
    // after the consent checkbox is selected/unselected.
   },
  onError: function(error) {
    // your error handling code
   }
}).bind("consentWidgetDiv ");
</script>
```

For more information on adding Amazon Pay widgets and Javascript visit <https://developer.amazon.com/docs/amazon-pay-automatic/add-address-and-wallet-widgets.html>

The customer will be required to check the “Use my selected payment method for future purchases and payments to this merchant” box in the Amazon-generated consent widget to complete the purchase.

<figure><img src="/files/KJVCaMoB6baIy0Nqt2vq" alt=""><figcaption></figcaption></figure>

Send the `amazonBillingAgreementId` as the **amazonOrderId** parameter on your Import Order API call.

***

### Errors/Decline Messages <a href="#checkoutchampamazonpayapiintegration-errors-declinemessages" id="checkoutchampamazonpayapiintegration-errors-declinemessages"></a>

Below you will find common errors that other users have encountered when using Amazon Pay.

| Error                | Cause                                                           | Fix                                                                                  |
| -------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| InvalidPaymentMethod | The customer’s payment method inside Amazon is no longer valid. | Customer must ensure that all payment methods inside their Amazon account are valid. |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.checkoutchamp.com/crm/gateway-setup/gateway-integrations/amazon-pay-api-integration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
