Git Product home page Git Product logo

amazon-pay-api-sdk-php's Introduction

Amazon Pay API SDK (PHP)

Amazon Pay Integration

Please note that the Amazon Pay API SDK can only be used for API calls to the pay-api.amazon.com|eu|jp endpoint.

If you need to make an Amazon Pay API call that uses the mws.amazonservices.com|jp or mws-eu.amazonservices.com endpoint, then you will need to use the original Amazon Pay SDK (PHP).

Requirements

  • PHP 5.6.1 or higher, but highly recommended to use only the latest PHP version, and update often, to ensure current security fixes are applied
  • Curl 7.18 or higher
  • phpseclib 3.0

SDK Installation

Use composer to install the latest release of the SDK and its dependencies:

    composer require amzn/amazon-pay-api-sdk-php

Verify the installation with the following test script:

    <?php
        include 'vendor/autoload.php';
        echo "SDK_VERSION=" . Amazon\Pay\API\Client::SDK_VERSION . "\n";
    ?>

Public and Private Keys

MWS access keys, MWS secret keys, and MWS authorization tokens from previous MWS integrations cannot be used with this SDK.

You will need to generate your own public/private key pair to make API calls with this SDK.

In Windows 10 this can be done with ssh-keygen commands:

ssh-keygen -t rsa -b 2048 -f private.pem
ssh-keygen -f private.pem -e -m PKCS8 > public.pub

In Linux or macOS this can be done using openssl commands:

openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout > public.pub

The first command above generates a private key and the second line uses the private key to generate a public key.

To associate the key with your account, follow the instructions here to Get your Public Key ID.

Namespace

Namespace for this package is Amazon\Pay\API so that there are no conflicts with the original Amazon Pay MWS SDK's that use the AmazonPay namespace.

Configuration Array

    $amazonpay_config = array(
        'public_key_id' => 'ABC123DEF456XYZ',  // RSA Public Key ID (this is not the Merchant or Seller ID)
        'private_key'   => 'keys/private.pem', // Path to RSA Private Key (or a string representation)
        'sandbox'       => true,               // true (Sandbox) or false (Production) boolean
        'region'        => 'us',                // Must be one of: 'us', 'eu', 'jp'
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2'  //Amazon Signing Algorithm, Optional: uses AMZN-PAY-RSASSA-PSS if not specified
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );

If you have created environment specific keys (i.e Public Key Starts with LIVE or SANDBOX) in Seller Central, then use those PublicKeyId & PrivateKey. In this case, there is no need to pass the Sandbox parameter to the ApiConfiguration.

    $amazonpay_config = array(
	    'public_key_id' => 'MY_PUBLIC_KEY_ID',  // LIVE-XXXXX or SANDBOX-XXXXX
	    'private_key'   => 'keys/private.pem', // Path to RSA Private Key (or a string representation)
	    'region'        => 'us', // Must be one of: 'us', 'eu', 'jp'
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2'  //Amazon Signing Algorithm, Optional: uses AMZN-PAY-RSASSA-PSS if not specified
	);

If you have want to enable proxy support, you can set it in the $amazonpay_config in the following way:

    $amazonpay_config = array(
        'public_key_id' => 'ABC123DEF456XYZ',  // RSA Public Key ID (this is not the Merchant or Seller ID)
        'private_key'   => 'keys/private.pem', // Path to RSA Private Key (or a string representation)
        'sandbox'       => true,               // true (Sandbox) or false (Production) boolean
        'region'        => 'us',               // Must be one of: 'us', 'eu', 'jp'
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',  //Amazon Signing Algorithm, Optional: uses AMZN-PAY-RSASSA-PSS if not specified
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4',            // (optional) Solution Provider Platform Version in Semantic Versioning Format
        'proxy' => [
            'host' => 'proxy_host',
            'port' => 'proxy_port',
            'username' => 'proxy_username',
            'password' => 'proxy_password',
        ]
    );

Versioning

The pay-api.amazon.com|eu|jp endpoint uses versioning to allow future updates. The major version of this SDK will stay aligned with the API version of the endpoint.

If you have downloaded version 1.x.y of this SDK, $version in below examples would be "v1". 2.x.y would be "v2", etc.

Convenience Functions (Overview)

Make use of the built-in convenience functions to easily make API calls. Scroll down further to see example code snippets.

When using the convenience functions, the request payload will be signed using the provided private key, and a HTTPS request is made to the correct regional endpoint. In the event of request throttling, the HTTPS call will be attempted up to three times using an exponential backoff approach.

Alexa Delivery Trackers API

Use this API to provide shipment tracking information to Amazon Pay so that Amazon Pay can notify buyers on Alexa when shipments are out for delivery and when they are delivered. Please refer to the Delivery Trackers API documentation for additional information.

  • deliveryTrackers($payload, $headers = null) → POST to "$version/deliveryTrackers"

Authorization Tokens API

Please note that your solution provider account must have a pre-existing relationship (valid and active MWS authorization token) with the merchant account in order to use this function.

  • getAuthorizationToken($mwsAuthToken, $merchantId, $headers = null) → GET to "$version/authorizationTokens/$mwsAuthToken?merchantId=$merchantId"

Amazon Checkout v2 API

API Integration Guide

The $headers field is not optional for create/POST calls below because it requires, at a minimum, the x-amz-pay-idempotency-key header:

    $headers = array('x-amz-pay-idempotency-key' => uniqid());

Amazon Checkout v2 Buyer object

  • getBuyer($buyerToken, $headers = null) → GET to "$version/buyers/$buyerToken"

Amazon Checkout v2 CheckoutSession object

  • createCheckoutSession($payload, $headers) → POST to "$version/checkoutSessions"
  • getCheckoutSession($checkoutSessionId, $headers = null) → GET to "$version/checkoutSessions/$checkoutSessionId"
  • updateCheckoutSession($checkoutSessionId, $payload, $headers = null) → PATCH to "$version/checkoutSessions/$checkoutSessionId"
  • completeCheckoutSession($checkoutSessionId, $payload, $headers = null) → POST to "$version/checkoutSessions/$checkoutSessionId/complete"

Amazon Checkout v2 ChargePermission object

  • getChargePermission($chargePermissionId, $headers = null) → GET to "$version/chargePermissions/$chargePermissionId"
  • updateChargePermission($chargePermissionId, $payload, $headers = null) → PATCH to "$version/chargePermissions/$chargePermissionId"
  • closeChargePermission($chargePermissionId, $payload, $headers = null) → DELETE to "$version/chargePermissions/$chargePermissionId/close"

Amazon Checkout v2 Charge object

  • createCharge($payload, $headers) → POST to "$version/charges"
  • getCharge($chargeId, $headers = null) → GET to "$version/charges/$chargeId"
  • captureCharge($chargeId, $payload, $headers) → POST to "$version/charges/$chargeId/capture"
  • cancelCharge($chargeId, $payload, $headers = null) → DELETE to "$version/charges/$chargeId/cancel"

Amazon Checkout v2 Refund object

  • createRefund($payload, $headers) → POST to "$version/refunds"
  • getRefund($refundId, $headers = null) → GET to "$version/refunds/$refundId"

In-Store API

Please contact your Amazon Pay Account Manager before using the In-Store API calls in a Production environment to obtain a copy of the In-Store Integration Guide.

  • instoreMerchantScan($payload, $headers = null) → POST to "$version/in-store/merchantScan"
  • instoreCharge($payload, $headers = null) → POST to "$version/in-store/charge"
  • instoreRefund($payload, $headers = null) → POST to "$version/in-store/refund"

Amazon Checkout v2 SPC

  • finalizeCheckoutSession($checkoutSessionId, $payload, $headers = null) → POST to "$version/checkoutSessions/$checkoutSessionId/finalize"

Amazon Checkout v2 Merchant Onboarding & Account Management object

  • registerAmazonPayAccount($payload, $headers = null) → POST to "$version/merchantAccounts"
  • updateAmazonPayAccount($merchantAccountId, $payload, $headers = null) → PATCH to "$version/merchantAccounts/$merchantAccountId"
  • deleteAmazonPayAccount($merchantAccountId, $headers = null) → DELETE to "$version/merchantAccounts/$merchantAccountId"

Amazon Checkout v2 Account Management APIs

  • createMerchantAccount($payload, $headers) → POST to "$version/merchantAccounts"
  • updateMerchantAccount($merchantAccountId, $payload, $headers) → PATCH to "$version/merchantAccounts/$merchantAccountId"
  • claimMerchantAccount($merchantAccountId, $payload, $headers) → POST to "$version/merchantAccounts/$merchantAccountId/claim"

Using Convenience Functions

Four quick steps are needed to make an API call:

Step 1. Construct a Client (using the previously defined Config Array).

    $client = new Amazon\Pay\API\Client($amazonpay_config);

Step 2. Generate the payload.

    $payload = '{"scanData":"UKhrmatMeKdlfY6b","scanReferenceId":"0b8fb271-2ae2-49a5-b35d7","merchantCOE":"US","ledgerCurrency":"USD","chargeTotal":{"currencyCode":"USD","amount":"2.00"},"metadata":{"merchantNote":"Merchant Name","communicationContext":{"merchantStoreName":"Store Name","merchantOrderId":"789123"}}}';

Step 3. Execute the call.

     $result = $client->instoreMerchantScan($payload);

Step 4. Check the result.

The $result will be an array with the following keys:

  • 'status' - integer HTTP status code (200, 201, etc.)
  • 'response' - the JSON response body
  • 'request_id' - the Request ID from Amazon API gateway
  • 'url' - the URL for the REST call the SDK calls, for troubleshooting purposes
  • 'method - POST, GET, PATCH, or DELETE
  • 'headers' - an array containing the various headers generated by the SDK, for troubleshooting purposes
  • 'request' - the JSON request payload
  • 'retries' - usually 0, but reflects the number of times a request was retried due to throttling or other server-side issue
  • 'duration' - duration in milliseconds of SDK function call

The first two items (status, response) are critical. The remaining items are useful in troubleshooting situations.

To parse the response in PHP, you can use the PHP json_decode() function:

    $response = json_decode($result['response'], true);
    $id = $response['chargePermissionId'];

If you are a Solution Provider and need to make an API call on behalf of a different merchant account, you will need to pass along an extra authentication token parameter into the API call.

    $headers = array('x-amz-pay-authtoken' => 'other_merchant_super_secret_token');
    $result = $client->instoreMerchantScan($payload, $headers);

An alternate way to do Step 2 would be to use PHP arrays and programmatically generate the JSON payload:

    $payload = array(
        'scanData' => 'UKhrmatMeKdlfY6b',
        'scanReferenceId' => uniqid(),
        'merchantCOE' => 'US',
        'ledgerCurrency' => 'USD',
        'chargeTotal' => array(
            'currencyCode' => 'USD',
            'amount' => '2.00'
        ),
        'metadata' => array(
            'merchantNote' => 'Merchant Name',
            'communicationContext' => array(
                'merchantStoreName' => 'Store Name',
                'merchantOrderId' => '789123'
            )
        )
    );
    $payload = json_encode($payload);

Convenience Functions Code Samples

Alexa Delivery Notifications

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'MY_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'US',
        'sandbox'       => false,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
    );
    $payload = array(
        'amazonOrderReferenceId' => 'P01-0000000-0000000',
        'deliveryDetails' => array(array(
            'trackingNumber' => '01234567890',
            'carrierCode' => 'FEDEX'
        ))
    );
    try {
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->deliveryTrackers($payload);
        if ($result['status'] === 200) {
            // success
            echo $result['response'] . "\n";
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
    } catch (\Exception $e) {
        // handle the exception
        echo $e . "\n";
    }
    ?>

Amazon Checkout v2 - Create Checkout Session (AJAX service example)

    <?php
    session_start();

    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'MY_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'US',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );
    $payload = array(
        'webCheckoutDetails' => array(
            'checkoutReviewReturnUrl' => 'https://localhost/store/checkout_review',
            'checkoutResultReturnUrl' => 'https://localhost/store/checkout_result'
        ),
        'storeId' => 'amzn1.application-oa2-client.000000000000000000000000000000000'
    );
    $headers = array('x-amz-pay-Idempotency-Key' => uniqid());
    try {
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->createCheckoutSession($payload, $headers);

        header("Content-type:application/json; charset=utf-8");
        echo $result['response'];
        if ($result['status'] !== 201) {
            http_response_code(500);
        }

    } catch (\Exception $e) {
        // handle the exception
        echo $e . "\n";
        http_response_code(500);
    }
    ?>

Amazon Checkout v2 - Create Checkout Session (standalone script example)

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',  // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );
    $payload = array(
        'webCheckoutDetails' => array(
            'checkoutReviewReturnUrl' => 'https://localhost/store/checkout_review',
            'checkoutResultReturnUrl' => 'https://localhost/store/checkout_result'
        ),
        'storeId' => 'amzn1.application-oa2-client.000000000000000000000000000000000'
    );
    $headers = array('x-amz-pay-Idempotency-Key' => uniqid());
    try {
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->createCheckoutSession($payload, $headers);
        if ($result['status'] === 201) {
            // created
            $response = json_decode($result['response'], true);
            $checkoutSessionId = $response['checkoutSessionId'];
            echo "checkoutSessionId=$checkoutSessionId\n";
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
    } catch (\Exception $e) {
        // handle the exception
        echo $e . "\n";
    }
    ?>

Amazon Checkout v2 - Get Checkout Session

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',  // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );

    try {
        $checkoutSessionId = '00000000-0000-0000-0000-000000000000';
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->getCheckoutSession($checkoutSessionId);
        if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            $checkoutSessionState = $response['statusDetails']['state'];
            $chargeId = $response['chargeId'];
            $chargePermissionId = $response['chargePermissionId'];

            // NOTE: Once Checkout Session moves to a "Completed" state, buyer and shipping
            // details must be obtained from the getCharges() function call instead
            $buyerName = $response['buyer']['name'];
            $buyerEmail = $response['buyer']['email'];
            $shipName = $response['shippingAddress']['name'];
            $shipAddrLine1 = $response['shippingAddress']['addressLine1'];
            $shipCity = $response['shippingAddress']['city'];
            $shipState = $response['shippingAddress']['stateOrRegion'];
            $shipZip = $response['shippingAddress']['postalCode'];
            $shipCounty = $response['shippingAddress']['countryCode'];

            echo "checkoutSessionState=$checkoutSessionState\n";
            echo "chargeId=$chargeId; chargePermissionId=$chargePermissionId\n";
            echo "buyer=$buyerName ($buyerEmail)\n";
            echo "shipName=$shipName\n";
            echo "address=$shipAddrLine1; $shipCity $shipState $shipZip ($shipCounty)\n";
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
    } catch (\Exception $e) {
        // handle the exception
        echo $e . "\n";
    }
    ?>

Amazon Checkout v2 - Update Checkout Session

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',  // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );

    $payload = array(
       'paymentDetails' => array(
            'paymentIntent' => 'Authorize',
            'canHandlePendingAuthorization' => false,
            'chargeAmount' => array(
                'amount' => '1.23',
                'currencyCode' => 'USD'
            ),
        ),
        'merchantMetadata' => array(
            'merchantReferenceId' => '2020-00000001',
            'merchantStoreName' => 'Store Name',
            'noteToBuyer' => 'Thank you for your order!'
        )
    );

    try {
        $checkoutSessionId = '00000000-0000-0000-0000-000000000000';
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->updateCheckoutSession($checkoutSessionId, $payload);
        if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            $amazonPayRedirectUrl = $response['webCheckoutDetails']['amazonPayRedirectUrl'];
            echo "amazonPayRedirectUrl=$amazonPayRedirectUrl\n";
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
    } catch (\Exception $e) {
        // handle the exception
        echo $e . "\n";
    }
    ?>

Amazon Checkout v2 - Complete Checkout Session API

<?php
    include 'vendor/autoload.php';
    
    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',  // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );
    
    $payload = array(
        'chargeAmount' => array(
            'amount' => '14.00',
            'currencyCode' => 'USD'
        )
    );
    
    try {
        $checkoutSessionId = '00000000-0000-0000-0000-000000000000';
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->completeCheckoutSession($checkoutSessionId, $payload);
        
        if ($result['status'] === 202) {
            // Charge Permission is in AuthorizationInitiated state
            $response = json_decode($result['response'], true);
            $checkoutSessionState = $response['statusDetails']['state'];
            $chargeId = $response['chargeId'];
            $chargePermissionId = $response['chargePermissionId'];
        } 
        else if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            $checkoutSessionState = $response['statusDetails']['state'];
            $chargePermissionId = $response['chargePermissionId'];
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
    } catch (Exception $e) {
        // handle the exception
        echo $e;
    }
?>

Amazon Checkout v2 - Get Charge Permission API

<?php
    include 'vendor/autoload.php';
    
    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',  // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );

    try {
        $chargePermissionId = 'S01-0000000-0000000';
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->getChargePermission($chargePermissionId);
        
        if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            $chargePermissionState = $response['statusDetails']['state'];

        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'];
        }
    } catch (Exception $e) {
        // handle the exception
        echo $e;
    }
?>

Amazon Checkout v2 - Update Charge Permission API

<?php
    include 'vendor/autoload.php';
    
    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',  // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );

    $payload = array(
        'merchantMetadata' => array(
            'merchantReferenceId' => '32-41-323141-32',
            'merchantStoreName' => 'AmazonTestStoreFront',
            'noteToBuyer' => 'Some Note to buyer',
            'customInformation' => ''   
        )
    );

    try {
        $chargePermissionId = 'S01-0000000-0000000';
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->updateChargePermission($chargePermissionId, $payload);
        
        if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'];
        }
    } catch (Exception $e) {
        // handle the exception
        echo $e;
    }
?>

Amazon Checkout v2 - Close Charge Permission API

<?php
    include 'vendor/autoload.php';
    
    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',  // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );

    $payload = array(
        'closureReason' => 'No more charges required',
        'cancelPendingCharges' => false
    );

    try {
        $chargePermissionId = 'S01-0000000-0000000';
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->closeChargePermission($chargePermissionId, $payload);
        
        if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            $chargePermissionState = $response['statusDetails']['state'];
            
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'];
        }
    } catch (Exception $e) {
        // handle the exception
        echo $e;
    }
?>

Amazon Checkout v2 - Create Charge API

<?php

    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem', // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'sandbox'       => true,
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );
        
    $payload = array(
        'chargePermissionId' => 'S01-0000000-0000000',
        'chargeAmount' => array(
            'amount' => '14.00',
            'currencyCode' => 'USD'
        ),
        'captureNow' => true,
        'softDescriptor' => 'Descriptor',
        'canHandlePendingAuthorization' => false 
    );

    $headers = array('x-amz-pay-Idempotency-Key' => uniqid());

    try {
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->createCharge($payload, $headers);
        
        if ($result['status'] === 201) {
            $response = json_decode($result['response'], true);
            $chargeState = $response['statusDetails']['state'];
            $chargeId = $response['chargeId'];

        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'];
        }
    } catch (Exception $e) {
        // handle the exception
        echo $e;
    }
?>

Amazon Checkout v2 - Get Charge API

<?php

    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem', // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'sandbox'       => true,
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );
        
    try {
        $chargeId = 'S01-0000000-0000000-C000000';
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->getCharge($chargeId);
        
        if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            $chargeState = $response['statusDetails']['state'];

        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'];
        }
    } catch (Exception $e) {
        // handle the exception
        echo $e;
    }
?>

Amazon Checkout v2 - Capture Charge API

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',  // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );

    $payload = array(
        'captureAmount' => array(
            'amount' => '1.23',
            'currencyCode' => 'USD'
        ),
        'softDescriptor' => 'For CC Statement'
    );

    try {
        $chargeId = 'S01-0000000-0000000-C000000';
        $headers = array('x-amz-pay-Idempotency-Key' => uniqid());
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->captureCharge($chargeId, $payload, $headers);

        if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            $state = $response['statusDetails']['state'];
            $reasonCode = $response['statusDetails']['reasonCode'];
            $reasonDescription = $response['statusDetails']['reasonDescription'];
            echo "state=$state; reasonCode=$reasonCode; reasonDescription=$reasonDescription\n";
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
    } catch (\Exception $e) {
        // handle the exception
        echo $e . "\n";
    }
    ?>

Amazon Checkout v2 - Cancel Charge API

<?php 

    include 'vendor/autoload.php';
    
    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem', // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );  

    $payload = array(
        'cancellationReason' => 'REASON DESCRIPTION'
    );

    try {
        $chargeId = 'S01-0000000-0000000-C000000';
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->cancelCharge($chargeId, $payload);
        
        if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            $chargeState = $response['statusDetails']['state'];
            
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'];
        }
    } catch (Exception $e) {
        // handle the exception
        echo $e;
    }
?>

Amazon Checkout v2 - Create Refund API

<?php

    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem', // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );
        
    $payload = array(
        'chargeId' => 'S01-0000000-0000000-C000000',
        'refundAmount' => array(
            'amount' => '14.00',
            'currencyCode' => 'USD'
        ),
        'softDescriptor' => 'Descriptor'
    );

    $headers = array('x-amz-pay-Idempotency-Key' => uniqid());

    try {
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->createRefund($payload, $headers);
        
        if ($result['status'] === 201) {
            $response = json_decode($result['response'], true);
            $refundState = $response['statusDetails']['state'];
            $refundId = $response['refundId'];

        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'];
        }
    } catch (Exception $e) {
        // handle the exception
        echo $e;
    }
?>

Amazon Checkout v2 - Get Refund API

<?php

    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem', // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE',
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );
        
    try {
        $refundId = 'S01-0000000-0000000-R000000'
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->getRefund($refundId);
        
        if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            $chargeState = $response['statusDetails']['state'];

        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'];
        }
    } catch (Exception $e) {
        // handle the exception
        echo $e;
    }
?>

Amazon Checkout v2 - Get Buyer API

<?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem', // Path to RSA Private Key (or a string representation)
        'region'        => 'YOUR_REGION_CODE', 
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
        'integrator_id'      => 'AXXXXXXXXXXXXX',   // (optional) Solution Provider Platform Id in Amz UID Format
        'integrator_version' => '1.2.3',            // (optional) Solution Provider Plugin Version in Semantic Versioning Format
        'platform_version'   => '0.0.4'            // (optional) Solution Provider Platform Version in Semantic Versioning Format
    );
            
    try {
        $buyerToken = 'BUYER_TOKEN';
        
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->getBuyer($buyerToken);
            
        if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);

        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'];
        }
    } catch (Exception $e) {
        // handle the exception
        echo $e;
    }
?>

Generate Button Signature (helper function)

The signatures generated by this helper function are only valid for the Checkout v2 front-end buttons. Unlike API signing, no timestamps are involved, so the result of this function can be considered a static signature that can safely be placed in your website JS source files and used repeatedly (as long as your payload does not change).

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'MY_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'US',
        'sandbox'       => true,
        'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
    );

    $client = new Amazon\Pay\API\Client($amazonpay_config);
    $payload = '{"storeId":"amzn1.application-oa2-client.xxxxx","webCheckoutDetails":{"checkoutReviewReturnUrl":"https://localhost/test/CheckoutReview.php","checkoutResultReturnUrl":"https://localhost/test/CheckoutResult.php"}}';
    $signature = $client->generateButtonSignature($payload);
    echo $signature . "\n";
    ?>

Manual Signing (Advanced Use-Cases Only)

This SDK provides the ability to help you manually sign your API requests if you want to use your own code for sending the HTTPS request over the Internet.

Example call to getPostSignedHeaders function with values:

    /*  getPostSignedHeaders convenience – Takes values for canonical request sorts and parses it and
     *  returns a signature for the request being sent
     *  @param $http_request_method [String]
     *  @param $request_uri [String]
     *  @param $request_parameters [array()]
     *  @param $request_payload [string]
     */

Example request method:

    $method = 'POST';

    // API Merchant Scan
    $url = 'https://pay-api.amazon.com/sandbox/' . $versiom . '/in-store/merchantScan';
    
    $payload = array(
        'scanData' => 'UKhrmatMeKdlfY6b',
        'scanReferenceId' => '0b8fb271-2ae2-49a5-b35d4',
        'merchantCOE' => 'US',
        'ledgerCurrency' => 'USD',
        'chargeTotal' => array(
            'currencyCode' => 'USD',
            'amount' => '2.00'
        ),
        'metadata' => array(
            'merchantNote' => 'Ice Cream',
            'customInformation' => 'In-store Ice Cream',
            'communicationContext' => array(
                'merchantStoreName' => 'Store Name',
                'merchantOrderId' => '789123'
            )
        )
    ); 

    // Convert to json string
    $payload = json_encode($payload);
    
    $requestParameters = array();

    $client = new Amazon\Pay\API\Client($amazonpay_config);

    $postSignedHeaders = $client->getPostSignedHeaders($method, $url, $requestParameters, $payload);

Example call to createSignature function with values:

(This will only be used if you don't use getPostSignedHeaders and want to create your own custom headers.)

  /*    createSignature convenience – Takes values for canonical request sorts and parses it and
   *    returns a signature for the request being sent
   *    @param $http_request_method [String]
   *    @param $request_uri [String]
   *    @param $request_parameters [Array()]
   *    @param $pre_signed_headers [Array()]
   *    @param $request_payload [String]
   *    @param $timeStamp [String]
   */

    // Example request method:

    $method = 'POST';

    // API Merchant Scan
    $url = 'https://pay-api.amazon.com/sandbox/in-store/' . $version . '/merchantScan';
    
    $payload = array(
        'scanData' => 'ScanData',
        'scanReferenceId' => '0b8fb271-2ae2-49a5-b35d4',
        'merchantCOE' => 'US',
        'ledgerCurrency' => 'USD',
        'chargeTotal' => array(
            'currencyCode' => 'USD',
            'amount' => '2.00'
        ),
        'metadata' => array(
            'merchantNote' => 'Ice Cream',
            'customInformation' => 'In-store Ice Cream',
            'communicationContext' => array(
                'merchantStoreName' => 'Store Name',
                'merchantOrderId' => '789123'
            )
        )
    ); 

    // Convert to json string
    $payload = json_encode($payload);
    
    $requestParameters = array();

    $client = new Amazon\Pay\API\Client($amazonpay_config);

    // Create an array that will contain the parameters for the charge API call
    $pre_signed_headers = array();
    $pre_signed_headers['Accept'] = 'application/json';
    $pre_signed_headers['Content-Type'] = 'application/json';
    $pre_signed_headers['X-Amz-Pay-Region'] = 'na';

    $client = new Client($amazonpay_config);
    $signedInput = $client->createSignature($method, $url, $requestParameters, $pre_signed_headers, $payload, '20180326T203730Z');

Reporting APIs code samples

Amazon Checkout v2 Reporting APIs - GetReport API

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'MY_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'US',
        'sandbox'       => false
    );

    $requestPayload = array(
        'reportTypes' => '_GET_FLAT_FILE_OFFAMAZONPAYMENTS_ORDER_REFERENCE_DATA_',
        'processingStatuses' => 'COMPLETED',
        'pageSize' => '10'
    );

    try {
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->getReports($requestPayload);

        if ($result['status'] === 200) {
            // success
            $response = $result['response'];
            echo $response;
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
        } catch (\Exception $e) {
            // handle the exception
            echo $e . "\n";
        }
    ?>

Amazon Checkout v2 Reporting APIs - GetReportById API

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'MY_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'US',
        'sandbox'       => true
    );

    try {
        $reportId = "1234567890";
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->getReportById($reportId);

        if ($result['status'] === 200) {
            // success
            $response = $result['response'];
            echo $response;
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
        } catch (\Exception $e) {
            // handle the exception
            echo $e . "\n";
        }
    ?>

Amazon Checkout v2 Reporting APIs - GetReportDocument API

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'MY_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'US',
        'sandbox'       => true
    );

    try {
        $reportDocumentId = "amzn1.tortuga.0.000000000-0000-0000-0000-000000000000.00000000000000";
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->getReportDocument($reportDocumentId);

        if ($result['status'] === 200) {
            // success
            $response = $result['response'];
            echo $response;
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
        } catch (\Exception $e) {
            // handle the exception
            echo $e . "\n";
        }
    ?>

Amazon Checkout v2 Reporting APIs - GetReportSchedules API

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'MY_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'US',
        'sandbox'       => true
    );

    try {
        $reportTypes = "_GET_FLAT_FILE_OFFAMAZONPAYMENTS_ORDER_REFERENCE_DATA_,_GET_FLAT_FILE_OFFAMAZONPAYMENTS_BILLING_AGREEMENT_DATA_";
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->getReportSchedules($reportTypes);

        if ($result['status'] === 200) {
            // success
            $response = $result['response'];
            echo $response;
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
        } catch (\Exception $e) {
            // handle the exception
            echo $e . "\n";
        }
    ?>

Amazon Checkout v2 Reporting APIs - GetReportScheduleById API

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'MY_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'US',
        'sandbox'       => true
    );

    try {
        $reportScheduleId = "1234567890";
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->getReportScheduleById($reportScheduleId);

        if ($result['status'] === 200) {
            // success
            $response = $result['response'];
            echo $response;
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
        } catch (\Exception $e) {
            // handle the exception
            echo $e . "\n";
        }
    ?>

Amazon Checkout v2 Reporting APIs - CreateReport API

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'MY_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'US',
        'sandbox'       => true
    );

    $headers = array('x-amz-pay-Idempotency-Key' => uniqid());

    try {
        $requestPayload = array(
            'reportType' => '_GET_FLAT_FILE_OFFAMAZONPAYMENTS_AUTHORIZATION_DATA_',
            'startTime' => '20221114T074550Z',
            'endTime' => '20221114T074550Z'
        );
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->createReport($requestPayload);

        if ($result['status'] === 200) {
            // success
            $response = $result['response'];
            echo $response;
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
        } catch (\Exception $e) {
            // handle the exception
            echo $e . "\n";
        }
    ?>

Amazon Checkout v2 Reporting APIs - CreateReportSchedule API

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'MY_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'US',
        'sandbox'       => true
    );

    $headers = array('x-amz-pay-Idempotency-Key' => uniqid());

    try {
        $requestPayload = array(
            'reportType' => '_GET_FLAT_FILE_OFFAMAZONPAYMENTS_ORDER_REFERENCE_DATA_',
            'scheduleFrequency' => 'P1D',
            'nextReportCreationTime' => '20221114T074550Z',
            'deleteExistingSchedule' => false
        );
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->createReportSchedule($requestPayload);

        if ($result['status'] === 200) {
            // success
            $response = $result['response'];
            echo $response;
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
        } catch (\Exception $e) {
            // handle the exception
            echo $e . "\n";
        }
    ?>

Amazon Checkout v2 Reporting APIs - CancelReportSchedule API

    <?php
    include 'vendor/autoload.php';

    $amazonpay_config = array(
        'public_key_id' => 'MY_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'US',
        'sandbox'       => true
    );

    try {
        $reportScheduleId = "1234567890";
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->cancelReportSchedule($reportScheduleId);

        if ($result['status'] === 200) {
            // success
            $response = $result['response'];
            echo $response;
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
        } catch (\Exception $e) {
            // handle the exception
            echo $e . "\n";
        }
    ?>

Amazon Checkout v2 SPC - finalizeCheckoutSession API

<?php
include 'vendor/autoload.php';
require_once 'Amazon/Pay/API/Client.php';
$amazonpay_config = array(
    'public_key_id' => 'MY_PUBLIC_KEY_ID',
    'private_key'   => 'keys/private.pem',
    'region'        => 'US',
    'sandbox'       => true,
    'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
);
try{
    $payload =  array(
        "shippingAddress" => array(
            "name" => "Susie Smith",
            "addressLine1" => "10 Ditka Ave",
            "addressLine2" => "Suite 2500",
            "city" => "Chicago",
            "county" => null,
            "district" => null,
            "stateOrRegion" => "IL",
            "postalCode" => "60602",
            "countryCode" => "US",
            "phoneNumber" => "800-000-0000"
        ),
        "billingAddress" => null,
        "chargeAmount" => array(
            "amount" => "10",
            "currencyCode" => "USD"
        ),
        "totalOrderAmount" => array(
            "amount" => "10",
            "currencyCode" => "USD"
        ),
        "paymentIntent" => "Confirm",
        "canHandlePendingAuthorization" => "false"
    );
    $headers = array('x-amz-pay-Idempotency-Key' => uniqid());
    $client = new Amazon\Pay\API\Client($amazonpay_config);
    $checkoutSessionId = "your-checkout-session-id";
    $result = $client->finalizeCheckoutSession($checkoutSessionId,$payload, $headers);
if ($result['status'] === 200) {
    // success
    $response = $result['response'];
    echo $response;
} else {
    // check the error
    echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
}
} catch (\Exception $e) {
// handle the exception
echo $e . "\n";
}
?>

Sample codes for Account Management APIs

For more details related to Account Management APIs, please refer to this Integration Guide.

Amazon Checkout v2 Account Management APIs - createMerchantAccount API

<?php
    include 'vendor/autoload.php';
    require_once 'Amazon/Pay/API/Client.php';

    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'JP',
        'algorithm'      => 'AMZN-PAY-RSASSA-PSS-V2'
    );

    try {

        $payload = array(
            "uniqueReferenceId" => "Unique_Reference_Id",       // Mandatory
            "ledgerCurrency" => "JPY",
            "businessInfo" => array(
                "email" => "[email protected]",
                "businessType" => "CORPORATE",
                "businessLegalName" => "密林コーヒー",
                "businessCategory" => "Beauty",
                "businessAddress" => array(
                    "addressLine1" => "扇町4丁目5-1",
                    "addressLine2" => "フルフィルメントセンタービル",
                    "city" => "小田原市",
                    "stateOrRegion" => "神奈川県",
                    "postalCode" => "250-0001",
                    "countryCode" => "JP",
                    "phoneNumber" => array(
                        "countryCode" => "81",
                        "number" => "2062062061"
                    )
                ),
                "businessDisplayName" => "Abhi's Cafe",
                "annualSalesVolume" => array(
                    "amount" => "100000",
                    "currencyCode" => "JPY"
                ),
                "countryOfEstablishment" => "JP",
                "customerSupportInformation" => array(
                    "customerSupportEmail" => "[email protected]",
                    "customerSupportPhoneNumber" => array(
                        "countryCode" => "1",
                        "number" => "1234567",
                        "extension" => "123"
                    )
                )
            ),      // Mandatory
            "beneficiaryOwners" => array(
                array(
                    "personId" => "AO1",
                    "personFullName" => "Abhishek Kumar",
                    "residentialAddress" => array(
                        "addressLine1" => "扇町4丁目5-1",
                        "addressLine2" => "フルフィルメントセンタービル",
                        "city" => "小田原市",
                        "stateOrRegion" => "神奈川県",
                        "postalCode" => "250-0001",
                        "countryCode" => "JP",
                        "phoneNumber" => array(
                            "countryCode" => "81",
                            "number" => "2062062061"
                        )
                    )
                ),
                array(
                    "personId" => "AO2",
                    "personFullName" => "Rufus1 Rufus1",
                    "residentialAddress" => array(
                        "addressLine1" => "扇町4丁目5-1",
                        "addressLine2" => "フルフィルメントセンタービル",
                        "city" => "小田原市",
                        "stateOrRegion" => "神奈川県",
                        "postalCode" => "250-0001",
                        "countryCode" => "JP",
                        "phoneNumber" => array(
                            "countryCode" => "81",
                            "number" => "2062062061"
                        )
                    )
                )
            ),      // Mandatory
            "primaryContactPerson" => array(
                "personFullName" => "Abhishek Kumar"
            ),      // Optional
            "integrationInfo" => array(
                "ipnEndpointUrls" => array(
                    "https://yourdomainname.com/ipnendpoint1",
                    "https://yourdomainname.com/ipnendpoint2"
                )
            ),       // Optionals
            "stores" => array(
                array(
                    "domainUrls" => array(
                        "http://www.yourdomainname.com"
                    ),
                    "storeName" => "Rufus's Cafe",
                    "privacyPolicyUrl" => "http://www.yourdomainname.com/privacy",
                    "storeStatus" => array(
                        "state" => "Active",
                        "reasonCode" => null
                    )
                )
            ),      // Mandatory
            "merchantStatus" => array(
                "statusProvider" => "Ayden",
                "state" => "ACTIVE",
                "reasonCode" => null
            )       // Mandatory
        );

        $headers = array('x-amz-pay-Idempotency-Key' => uniqid());
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $result = $client->createMerchantAccount($payload, $headers);
        print_r($result);

        if ($result['status'] === 201) {
            // success
            $response = $result['response'];
            print_r($response);
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
    } catch (\Exception $e) {
        // handle the exception
        echo $e . "\n";
    }
?>

Amazon Checkout v2 Account Management APIs - updateMerchantAccount API

<?php
    include 'vendor/autoload.php';
    require_once 'Amazon/Pay/API/Client.php';

    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'JP',
        'algorithm'      => 'AMZN-PAY-RSASSA-PSS-V2'
    );

    try {

        $payload = array(
            "uniqueReferenceId" => "String",            // Mandatory
            "ownerAccountId" => "String",               // Optional
            "businessInfo" => array(
                "email" => "String",                    // Mandatory
                "businessCategory" => "ENUM",           // Mandatory
                "countryOfEstablishment" => "JP",       // Mandatory (JP for Japan)
                "businessType" => "ENUM",               // Mandatory (e.g., Corporate)
                "businessLegalName" => "String",        // Mandatory
                "businessAddress" => array(
                    "addressLine1" => "String",          // Mandatory
                    "addressLine2" => "String",          // Optional
                    "city" => "String",                  // Optional
                    "stateOrRegion" => "String",         // Optional
                    "postalCode" => "String",            // Mandatory
                    "countryCode" => "String"            // Mandatory
                ),
                "businessDisplayName" => "String",       // Mandatory
                "customerSupportInformation" => array(
                    "customerSupportEmail" => "String",  // Optional
                    "customerSupportPhoneNumber" => array(
                        "countryCode" => "String",        // Mandatory
                        "number" => "String",             // Mandatory
                        "extension" => "String"           // Optional
                    )
                ),
                "annualSalesVolume" => array(
                    "amount" => "String",                  // Mandatory
                    "currencyCode" => "String"             // Optional (ISO 4217)
                )   // Optional
            ),
            "primaryContactPerson" => array(
                "personFullName" => "String",              // Mandatory
                "residentialAddress" => array(
                    "addressLine1" => "String",            // Mandatory
                    "addressLine2" => "String",            // Optional
                    "city" => "String",                    // Optional
                    "stateOrRegion" => "String",           // Optional
                    "postalCode" => "String",              // Mandatory
                    "countryCode" => "String"              // Mandatory
                )   // Optional
            ),
            "beneficiaryOwners" => array(
                array(
                    "personFullName" => "String",          // Mandatory
                    "residentialAddress" => array(
                        "addressLine1" => "String",        // Mandatory
                        "addressLine2" => "String",        // Optional
                        "city" => "String",                // Optional
                        "stateOrRegion" => "String",       // Optional
                        "postalCode" => "String",          // Mandatory
                        "countryCode" => "String"          // Mandatory
                    )   // Optional
                )
            ),  // Mandatory
            "defaultStore" => array(
                "domainUrls" => array("String"),          // Mandatory
                "storeName" => "String",                  // Optional
                "privacyPolicyUrl" => "String",           // Optional
                "storeStatus" => array(
                    "state" => "ENUM",                    // Mandatory
                    "reasonCode" => "ENUM"                // Optional
                )   // Optional
            ),
            "integrationInfo" => array(
                "ipnEndpointUrl" => array("String")      // Optional
            ),
            "merchantStatus" => array(
                "statusProvider" => "String",            // Optional (Mandatory if state is Active)
                "state" => "ENUM",                       // Mandatory
                "reasonCode" => "ENUM"                   // Optional
            )
        );

        $headers = array('x-amz-pay-authtoken' => 'other_merchant_super_secret_token');         // Mandatory
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $merchantAccountId = "YOUR_MERCHANT_ID";
        $result = $client->updateMerchantAccount($merchantAccountId, $payload, $headers);

        if ($result['status'] === 200) {
            // success
            $response = $result['response'];
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
    } catch (\Exception $e) {
        // handle the exception
        echo $e . "\n";
    }
?>

Amazon Checkout v2 Account Management APIs - claimMerchantAccount API

<?php
    include 'vendor/autoload.php';
    require_once 'Amazon/Pay/API/Client.php';

    $amazonpay_config = array(
        'public_key_id' => 'YOUR_PUBLIC_KEY_ID',
        'private_key'   => 'keys/private.pem',
        'region'        => 'JP',
        'algorithm'      => 'AMZN-PAY-RSASSA-PSS-V2'
    );

    try {

        $payload = array(
            "uniqueReferenceId" => "Unique_Reference_Id"    // Mandatory
        );

        $headers = array('x-amz-pay-Idempotency-Key' => uniqid());
        $client = new Amazon\Pay\API\Client($amazonpay_config);
        $merchantAccountId = "YOUR_MERCHANT_ID";
        $result = $client->claimMerchantAccount($merchantAccountId, $payload, $headers = null);

        if ($result['status'] === 303) {
            // success
            $response = $result['response'];
        } else {
            // check the error
            echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
        }
    } catch (\Exception $e) {
        // handle the exception
        echo $e . "\n";
    }
?>

amazon-pay-api-sdk-php's People

Contributors

abhirajnow avatar akshitawaldia avatar aswinigh avatar bjguillot avatar dexterzprotege avatar islandskater43 avatar jamesiri avatar lemked avatar paeddl avatar seasoftjapan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

amazon-pay-api-sdk-php's Issues

Weird behaviour with checkoutLanguage

I don't know if it's the right place for this issue, I post here because I was implementing the Amazon Pay button with this SDK but it's more related to the button itself.

I've noticed a weird behaviour.

The merchant region is EU and was registered from France, althrough I don't know if it's relevant here. Everything that follows was done in the sandbox environment.

If I render the Amazon Pay button with:

{
    "merchantId": "A19Q**********",
    "publicKeyId": "SANDBOX-***********************",
    "ledgerCurrency": "EUR",
    "checkoutLanguage": "en_GB",
    "productType": "PayAndShip",
    "placement": "Cart",
    "buttonColor": "Gold",
    "createCheckoutSessionConfig": {
        "payloadJSON": "{\"webCheckoutDetails\":{\"checkoutReviewReturnUrl\":\"https://www.**********.com/order/review\",\"checkoutResultReturnUrl\":\"https://www.**********.com/order/confirmation\",\"checkoutCancelUrl\":\"https://www.**********.com/order/annulation\"},\"scopes\":[\"name\",\"email\",\"phoneNumber\",\"billingAddress\"],\"storeId\":\"amzn1.application-oa2-client.***************************\"}",
        "signature": "s9dh3Jeic2K48UY0454n******************************HoDfBVdrY0BGQ=="
    }
}

It doesn't work and gives me an error message in German. The same happens with de_DE.

image

However, it works fine just by changing the language to fr_FR, it_IT or es_ES.

Is it something normal / documented somewhere (like en_GB and de_DE are not available in sandbox, something like that)?

Thank you

Cannot install with PHP 5.5

Cannot install with PHP 5.5 because phpseclib 3 supports PHP 5.6.1 and above.

$ php -v
PHP 5.5.38 (cli) (built: Jun 21 2023 01:50:38) 
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies
    with Xdebug v2.5.5, Copyright (c) 2002-2017, by Derick Rethans
$ composer update
Loading composer repositories with package information
Info from https://repo.packagist.org: #StandWithUkraine
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - phpseclib/phpseclib[3.0.0, ..., 3.0.23] require php >=5.6.1 -> your php version (5.5.38) does not satisfy that requirement.
    - Root composer.json requires phpseclib/phpseclib ~3.0 -> satisfiable by phpseclib/phpseclib[3.0.0, ..., 3.0.23].

php_uname is not supported by all the hosting providers

The SDK will throw a fatal error if the hosting provider doesn't allow to call the function php_uname

CRITICAL Uncaught Error: Call to undefined function Amazon\Pay\API\php_uname() in []/vendor/amzn/amazon-pay-api-sdk-php/Amazon/Pay/API/Client.php:324

This is a common issue out there, the SDK should have a fallback method in case php_uname is not available, it has been reported on other SDKs out there (e.g Stripe: stripe/stripe-php#828).

Encountering Random The value X provided for x-amz-pay-date should not be in future

Hello,

I'm using the this dependency for a amazonPay instant checkout option. Every now and then some of the payments fail with this particular error (as mentioned in the title).
`
(
[status] => 400
[method] => PATCH
[url] => https://pay-api.amazon.eu/live/v2/checkoutSessions/e73fcfe0-9791-4a99-814a-92d102dbeca1
[headers] => Array
(
[0] => accept:application/json
[1] => authorization:AMZN-PAY-RSASSA-PSS PublicKeyId={}, SignedHeaders=accept;content-type;x-amz-pay-date;x-amz-pay-host;x-amz-pay-region, Signature={}
[2] => content-type:application/json
[3] => user-agent:amazon-pay-api-sdk-php/2.2.4 (PHP/7.3.27-9+ubuntu20.04.1+deb.sury.org+1; Linux/x86_64/5.4.0-1042-gcp)
[4] => x-amz-pay-date:20220131T094401Z
[5] => x-amz-pay-host:pay-api.amazon.eu
[6] => x-amz-pay-region:eu
)

[request] => {"webCheckoutDetails":{"checkoutResultReturnUrl":"{}"},"paymentDetails":{"paymentIntent":"Authorize","canHandlePendingAuthorization":false,"chargeAmount":{"amount":63.03,"currencyCode":"EUR"}},"merchantMetadata":{"merchantReferenceId":"ORD000000070180","merchantStoreName":"{}","noteToBuyer":"","customInformation":""}}
[response] => {"reasonCode":"InvalidHeaderValue","message":"The value 20220131T094401Z provided for x-amz-pay-date should not be in future"}
[request_id] => bb3dde4d-c33f-4452-a1cd-dc88c87395cc
[retries] => 0
[duration] => 112

)
`

I think most of the information needed is there, let me know what else I should provide.

chargeAmount.Amount Error with JPY

Hi!
I always get "The value '64615.90' provided for 'chargeAmount.Amount' is invalid" when try to checkout with JPY.
If I manually set chargeAmount to an integer seems to work. Is there any problem with decimals in JPY?

Thanks.

How to fix InvalidRequestSignature

Hi I got this error after $client->createCheckoutSession($payload, $headers):
"{"reasonCode":"InvalidRequestSignature","message":"Unable to verify signature, signing String [AMZN-PAY-RSASSA-

My customer gives me the public_key_id and pem file via Amazon Seller Central, the public_key_id is correct.

Could this error be caused by an incorrect PEM file? Should I ask the customer to verify if the PEM file was downloaded from Amazon Seller Central?

I have already run the same code on two different devices and confirmed that the environment meets the SDK requirements.

Thank you.

My code:

<?php
require __DIR__ . '/vendor/autoload.php';
$amazonpay_config = array(
    'public_key_id' => 'SANDBOX-XXXXXXX',
    'private_key'   => './private.pem',
    'region'        => 'US',
    'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
);

$payload = array(
'webCheckoutDetails' => array(
    'checkoutReviewReturnUrl' => 'https://localhost/store/checkout_review',
    'checkoutResultReturnUrl' => 'https://localhost/store/checkout_result'
),
'storeId' => 'amzn1.application-oa2-client.XXXXXXXXXXX'
);
$headers = array('x-amz-pay-Idempotency-Key' => uniqid());
$client = new Amazon\Pay\API\Client($amazonpay_config);
$resultCheckOut = $client->createCheckoutSession($payload, $headers);

var_dump($resultCheckOut);exit;

Button Signature not static

The signature generated by the generateButtonSignature method does not seem to be static for me.
Using this code

<?php
    include "vendor/autoload.php";

    $amazonpay_config = array(
        'public_key_id' => 'AE7IYD6IQKEYXY7UO56MYSJI',
        'private_key'   => 'keys/privatekey.pem',
        'region'        => 'DE',
        'sandbox'       => true
    );

    $client = new Amazon\Pay\API\Client($amazonpay_config);
    $payload = '{"storeId":"amzn1.application-oa2-client.xxxxx","webCheckoutDetails":{"checkoutReviewReturnUrl":"https://localhost/test/CheckoutReview.php","checkoutResultReturnUrl":"https://localhost/test/CheckoutResult.php"}}';
    for($i = 0; $i < 3; $i++){
        $signature = $client->generateButtonSignature($payload);
        echo $signature . "<br>";
    }
    ?>

I get an output like this

lJ9oDH6H3MGXuJqjXayh0KJMdt4AyjCP7EbaRTYuJ7LHP2c+3s7Azo9rIebWUuUg3IT58V3QHQvIG19hjKtiBHHpmtlyipcw6XNW9S2KkpN9L1CGB1lvhyS+qprvHSeWf5V5dKKJoPfH1AHeAHIOIt0TyjtGSYzzh3+cbQQcbIRHTvEM9U2a9oYqCzsr0cnKdFJq10urbnx+dzNMfiwfZuAbce7khWF08BxPo+jJpwoenLQzOuRBYf1R8eC9NUuIhczIR0xxLA9e8SqyijwSA0/TB5tolj2QG5//mkV/8qwH+jPAV9xVLUiXzfslQBBcKuE0WSBxPQPJSWFae7axeQ==
aqjH9g0eXU8c/clF5mAxgw37/mOABxrFPrU+B3Lpn6p8HNoLMBdvHzJyDtf67gDFoFc6dGyEqvemtlOZcVfsY+4YqKJJC91mHop/cuZr7QwK7Bo11ezLhqqs1E77+1praPP4T1qdRToquK+UfpTaJskF6GhBMbt1sIFf0uXlDjF987Xf61r6wPxzf4iubqE80S8oT0XaoiB9LRgr6hxVsMXZ9NHBqoM9Z2rUoDjV0CunhPUDBU1+TNdVMCSJG8XbBhPk31L59qBqzQ3c0/A4Efc+/lZbOcMaoIAKDtTkRMAgZXdq8d4Vq7L8Q+ySF5FmCN6AoQFR+lmrTBRhIgEtsw==
MJmBjZVmWRJUqMFnQRPlPWkhP2GEN62dNXk5cqcK/ttwxCGGYlgkH6hPGazxo89WaVLdo3EcNxvMBhiyyaGnSW2cQ1P2RHL2XJjGB3z+l3oiwOffgWH86yuyK+AKF7Ex4b56B0LaXDVANJNrxA5bRg5fJAR/MBTJNb5hxn2+595AsVgOdcaulFeu5vGkGigKXgESm+h3V5mn3YXh+bj23R3Smo4ZAVrPln0qHjl5QGy3aLlo2vtgSlu/UU5GBypeN9CdX2DjzfrtKEGG4SrEqqnLVSxxwMmtimNr4mXiFJrrUu3ufbVJ0aouCty0DI8Q5CyjcpsC/n5fYUvPttu1rQ==

As the signature changes every time, it of course does not match the expected signature which is why I get a "wrong signature" error when I try to implement the button.
I tried it with my full credentials as well, but it did not work for me on PHP 7.4.1 or 7.4.7.
What am I doing wrong?
Thanks in advance.

Is there a way to generate the checkout URL on server side?

We want to implement the amazon payment checkout v2 in our flutter mobile app.

We are blocked by the fact, that we need to render the checkout button with JS: https://developer.amazon.com/es/docs/amazon-pay-checkout/add-the-amazon-pay-button.html

I expect this JS SDK to render a button with a URL (ready configured) which leads to the checkout.

We cannot do that because we are in a flutter context.

Is there a way to generate this URL on server side with this SDK or with another SDK?

If not, how to actually integrate the ama checkout v2 in mobile?

Missing merchantMetadata information

Hi,
Based on what Amazon Pay docs saying, I should get back in response from getting checkout session information about the 'merchantMetadata', but the object which I'm getting from the SDK always gives me null there, even at I can see this in Amazon Pay portal.
Do you know what is the reason of that?

Headers being sent by empty line

Hey there!

There is one extra blank line in this file, which when being loaded is being considered as headers being sent. Currently blocking all the other's headers that would be sent by any php application.

Thank you!

Missing amazonPayToken

Hi.

I am trying to use an external aquirer for processing the payments as described in: https://amazon-pay-acquirer-guide.s3-eu-west-1.amazonaws.com/v2/amazon-pay-checkout/verify-checkout-info.html

I am not able to get the amazonpayToken. I already contacted the amazon support, but they just answered with a copy and paste of the documentation.

Is there a trick for getting the required amazonpayToken?

In the meantime I switched to normal processing. Everything works as expected, but our company would like to process the amazon pay payments with adyen as aquirer: https://docs.adyen.com/payment-methods/amazon-pay

Thanks Chris

completeCheckoutSession example

Hello,

I'm trying to integrate the api to a self-written shop. But I can't get a value for the chargeId and chargePermissionId in the response after the payer runs the amazonPayRedirectUrl. The constraints array is empty. After checking all my code and after 2-3 times reading the api documentation, I saw the following part in the changelog for version 2.0.0:

There are also non-subtle workflow changes between v1/ and v2/ as the completeCheckoutSession API call will be required now before funds can be captured. See the API Release notes for more details.

I can't find more details in the API Release notes to see how the payload of the completeCheckoutSession API Call looks like. Can you help me out with more information? I tried to contact the amazon pay seller support but they refuse to help me out and said that I need to manually collect every payment. That is not the case if I use the api calls described in the API manual and in the readme.md file.

Can you provide an example api call for the completeCheckoutSession API call? The Payload is my problem.

Unable to retrieve fee component of a payment.

In a legacy Amazon Pay system (I don't know the name/version you refer to it as internally) it was possible to retrieve the fee component of a payment, after it was captured, using GetCaptureDetails by referring to the CaptureFee element of the CaptureDetails object.

This data is does not appear to be exposed via the 'current' API/SDK. Is there a programatic way to get this data on a per-transaction basis (it's fine if it's not realtime with the payment confirmation)?

Testing Amazon Pay button on localhost:

To download the private key two methods are recommended here:

Method 1:
Using the following keys on windows 10 creates ---BEGIN OPENSSH PRIVATE KEY --- file as mentioned in the index page.

ssh-keygen -t rsa -b 2048 -f private.pem
ssh-keygen -f private.pem -e -m PKCS8 > public.pub

Method 2
Using https://sellercentral-europe.amazon.com/external-payments/amazon-pay/integration-central 'Create Api Keys', downloads the private key automatically in the left hand corner of the browser eg. AmazonPay_SANDBOX-AGQNBBAR7LO44CKBVHJWB4AB.
This file is a ---BEGIN PRIVATE KEY --- file ie. without the OPENSSH and the RSA.

I was initially getting an invalid Signature error as follows with Method 1: (Security keys have been adjusted)

image

I am now getting an invalid Login exception as follows with Method 2 thankfully using my live amazon account before I progress to the sandbox.

My question is ... when I begin hosting my website, what type of private key file ie. OPENSSH / RSA / BLANK should I use. It would appear that the ssh-keygen -t rsa -b 2048 -f private.pem is not generating a suitable file.

Under the API\Client generateButtonSignature function, I php echoed the $hashedButtonRequest variable in the controller before signing and the view output did in fact match my merchant details. So it would appear the culprit is the file that was generated by the ssh-keygen -t rsa -b 2048 -f private.pem.

After creating a test buyer on sellercentral using a different email address, I logged into payments.amazon.co.uk using this buyers email address and successfully received the following page.

image

.

Amazon pay always prompts a signature error

I have checked the documentation many times and then followed the integration guide to coding

https://developer.amazon.com/zh/docs/amazon-pay-checkout/add-the-amazon-pay-button.html

PHP

Route::any('t', function () {
        $config = [
            'public_key_id' => 'SANDBOX-AFXFSBQVGCOQVCKVTF3BZDJA',
            'private_key'   => base_path() . '/../' . config('services.amazon_pay.private_key'),
            'region'        => 'us',
            'sandbox'       => true,
        ];

        $client  = new \Amazon\Pay\API\Client($config);
        $payload = [
            'storeId'            => 'amzn1.application-oa2-client.43f65b01ae1448c2b6f2713f20cb31b9',
            "scopes"             => ["billingAddress"],
            'webCheckoutDetails' => [
                'checkoutReviewReturnUrl' => 'http://localhost:3000',
                'checkoutResultReturnUrl' => 'http://localhost:3000',
                'checkoutCancelUrl'       => 'http://localhost:3000',
            ],
        ];

        $signature = $client->generateButtonSignature($payload);

        return response()->json([
            'signature' => $signature, 'payloadString' => $payload,
        ]);
    });

The values in my sandbox

image

Front-end section

import { useEffect } from 'react'
import { amazonCheckoutJs } from 'utils/helper'
import { httpProvider } from 'utils/http'

const AmazonPay = () => {
    useEffect(() => {
        ;(async () => {
            const a = await httpProvider({
                url: `/t`,
                method: 'get',
            })
            console.log(a)
            const amazon = await amazonCheckoutJs()
            console.log(JSON.stringify(a.payloadString))

            amazon.Pay.renderButton('#AmazonPayButton', {
                // set checkout environment
                merchantId: 'A1UV7YCAO4HL9I',
                publicKeyId: 'SANDBOX-AFXFSBQVGCOQVCKVTF3BZDJA',
                ledgerCurrency: 'USD',
                // customize the buyer experience
                checkoutLanguage: 'en_US',
                productType: 'PayAndShip',
                placement: 'Product',
                sandbox: true,
                buttonColor: 'Gold',
                // configure Create Checkout Session request
                createCheckoutSessionConfig: {
                    payloadJSON: JSON.stringify(a.payloadString),
                    signature: a.signature, // signature generated in step 3
                },
            })
        })()
    }, [])

    return (
        <div>
            <div id="AmazonPayButton"></div>
        </div>
    )
}

export default AmazonPay

Format in newwork

api response

{"signature":"D18MTJkq4R3vFqIGIiYvZp4YB6oh0nvoBadb\/yv60SKCdlz+rbBf\/Job6bYMizEwHiNTcnjYhMlZzb+7LmtUMrVpiOBP2NVjsBZpWMdZp6zAKkKu1fysUzk8yVW6WVPeQlP1IULPswlPjT9bgOfViGgtTC7qJk+pWjZ0kjFWLjGgVhKYeUmeu7wMUM6Y3mTuvLJAPZjqBi0hCo5sytfaNHJptDJ0F6wuvTjmA2Rso541rSxCzr4\/uNX32POORyodnEMTvvstL+uz2L3J5HrAqYFw\/h4ml0+GDfgV91wT86abTLzfnBAFKryqEvf+LwbDZHrBOJE8wzyjMP3DUpWkRA==","payloadString":{"storeId":"amzn1.application-oa2-client.43f65b01ae1448c2b6f2713f20cb31b9","scopes":["billingAddress"],"webCheckoutDetails":{"checkoutReviewReturnUrl":"http:\/\/localhost:3000","checkoutResultReturnUrl":"http:\/\/localhost:3000","checkoutCancelUrl":"http:\/\/localhost:3000"}}}

image

error

Clicking the pay button always gets a signature error

image

Deprecation error with php8.1

When using the SDK with php 8.1, attempting to call Client->getCheckoutSession() produces an error:

Deprecated Functionality: hash(): Passing null to parameter #2 ($data) of type string is deprecated in /var/www/html/vendor/amzn/amazon-pay-api-sdk-php/Amazon/Pay/API/Client.php on line 195

This appears to be due to passing null as the payload for apiCall(), which is eventually fed into php's hash() which needs a string. See Amazon\Pay\API\Client::hexAndHash()

IPN Handling?

Is there any plan to add IPN Handling to this package? I'd rather not try and implement it myself if there is already a plan in the works.

Thanks

Error under PHP 8.2

the use of

echo Amazon\Pay\API\Client::SDK_VERSION;

throws an Error under PHP 8.2 "Failed opening required 'ClientInterface.php'".

It works if you change:

require_once 'ClientInterface.php';
require_once 'HttpCurl.php';

To

require_once DIR.'/ClientInterface.php';
require_once DIR.'/HttpCurl.php';

Use of stripcslashes breaks Amazon/Pay/API/Client::generateButtonSignature

I tried using this library today and was getting errors like below when clicking the checkout button in the browser:

Error Code: InvalidSignatureError

I was following the documentation here. After struggling with this issue I tried removing the call to stripcslashes on the line below.

https://github.com/amzn/amazon-pay-api-sdk-php/blob/master/Amazon/Pay/API/Client.php#L404

Without stripcslashes it looked like $hashedButtonRequest = self::AMAZON_SIGNATURE_ALGORITHM . "\n" . $this->hexAndHash($payload);. With that change suddenly my checkouts were working. I also found that mangling the value passed to payloadJSON with stripcslashes got things working as an alternative to editing the library.

Anyway, the stripcslashes seems to be causing issues.

Unable to retrieve fee component of a payment.

As per #14, the 'new' Amazon Pay API apparently provides no way to retrieve the fee that was charged to process a given payment.

This information was available via previous Amazon Pay APIs, and is seemingly still available via those APIs, for payments made via the new API. Given that I've seen multiple suggestions/warnings not to make use of both APIs concurrently for charging customers, It seems extremely odd that the only way to retrieve the fee information currently, is to use both APIs/SDKs - one for creating and checking the charge, and then a different one to retrieve the fee.

I opened issue #14 about this previously, and it was summarily closed by someone who either didn't read what I'd written or didn't comprehend what I was asking about.

Missing functionality for automated chargeback handling (v1 vs v2)

Following the integration guide on handling IPN notifications:
https://amazonpaycheckoutintegrationguide.s3.amazonaws.com/amazon-pay-checkout/set-up-instant-payment-notifications.html#ipn-types

Chargeback notification can be initiated, but the only way to handle it is:

Look up chargeback details in Seller Central using the chargePermissionId

This is inconsistent with v1 API, where chargeback information was normally included in IPN.

Therefore I believe that chargeback object get method is clearly missing in v2 API.

main.CRITICAL: Warning: file_get_contents(): Filename cannot be empty in vendor/amzn/amazon-pay-api-sdk-php/Amazon/Pay/API/Client.php on line 424

Hello,

if $key_spec = $this->config['private_key']; on line 421 in https://github.com/amzn/amazon-pay-api-sdk-php/blob/2.2.5/Amazon/Pay/API/Client.php#L421 is empty, then an error is thrown on line 424 for $contents = file_get_contents($key_spec);:

main.CRITICAL: Warning: file_get_contents(): Filename cannot be empty in vendor/amzn/amazon-pay-api-sdk-php/Amazon/Pay/API/Client.php on line 424

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.