# Amazon Pay API Integration

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

{% hint style="danger" %}
**The Amazon Pay gateway does not work with form code. This document is for a direct API integration only. To integrate Amazon with form code, follow** [**this document**](https://help.konnektive.com/konnektive-crm/gateway-setup/gateways/amazon-pay-api-integration/form-code-login-and-pay-with-amazon)**.**
{% endhint %}

### Creating Amazon Pay App And Adding Your Domain <a href="#amazonpayapiintegration-creatingamazonpayappandaddingyourdomain" id="amazonpayapiintegration-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="#amazonpayapiintegration-obtainamazonpaymidcredentials" id="amazonpayapiintegration-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="#amazonpayapiintegration-createamazonpaymid" id="amazonpayapiintegration-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="#amazonpayapiintegration-addamazonpaywidgetsandjavascripttoyourlandercode" id="amazonpayapiintegration-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="#amazonpayapiintegration-sendamazonpayparameterswithimportorderapicall" id="amazonpayapiintegration-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="#amazonpayapiintegration-transactionflow" id="amazonpayapiintegration-transactionflow"></a>

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

<figure><img src="https://1103784913-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FiAC0G99SjXjSv2GM5PAE%2Fuploads%2FvGDAmfIDi6VCXyaK0h3j%2FUntitled.png?alt=media&#x26;token=12835318-4926-44f8-a902-ac7c87e9b017" alt=""><figcaption></figcaption></figure>

New window pops up for customer to log into Amazon

<figure><img src="https://1103784913-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FiAC0G99SjXjSv2GM5PAE%2Fuploads%2FgUHRMB8phRe96HDObMsO%2FUntitled-1.png?alt=media&#x26;token=483bab91-9699-45f4-bec7-8ec25f0d6c2d" 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="https://1103784913-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FiAC0G99SjXjSv2GM5PAE%2Fuploads%2F9XxHytmlRAbcAc8L2oar%2FUntitled-1.png?alt=media&#x26;token=44c9c597-bbd5-48ae-b6cb-1a503a9298ff" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1103784913-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FiAC0G99SjXjSv2GM5PAE%2Fuploads%2FtUuRcXTx0i71v3rzBY5b%2FUntitled.png?alt=media&#x26;token=c509bef7-f8b3-465a-bc1a-d3790cc90a53" alt=""><figcaption></figcaption></figure>

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

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

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

### Enable Recurring Payments <a href="#amazonpayapiintegration-enablerecurringpayments" id="amazonpayapiintegration-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="https://1103784913-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FiAC0G99SjXjSv2GM5PAE%2Fuploads%2FIx6GVFCJus8Hm6YMV0Y1%2FUntitled-1.png?alt=media&#x26;token=a1b6d977-7b88-474b-966d-e52beeba4ef8" alt=""><figcaption></figcaption></figure>

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

***

### Errors/Decline Messages <a href="#amazonpayapiintegration-errors-declinemessages" id="amazonpayapiintegration-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. |
