1

I am in the process of integrating Amazon Pay into my website, and I have encountered a persistent issue regarding the charge ID. Despite my efforts, the charge ID consistently appears empty whenever I attempt to run the integration process.

To provide a comprehensive overview of my situation, I'd like to share the relevant portions of the code and files that pertain to this issue.

index.php

<?php

    include 'header.php'; // contains $creds and $amazonpay_config

    $client = new Amazon\Pay\API\Client($amazonpay_config);
    $payload = preg_replace('/[\n ]/', '', '
    {
      "storeId":"$creds['STORE_ID']",
      "webCheckoutDetails":{
        "checkoutReviewReturnUrl":"https://163.154.213.172/review.php",
        "checkoutResultReturnUrl":"https://163.154.213.172/result.php"
      }
    }');

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

    $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";
    }
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Amazon Pay Test</title>
  </head>
  <body>
      <div id="AmazonPayButton"></div>
      <script src="https://static-na.payments-amazon.com/checkout.js"></script>
      <script type="text/javascript" charset="utf-8">
          const amazonPayButton = amazon.Pay.renderButton('#AmazonPayButton', {
              // set checkout environment
              merchantId: '<?php echo $creds['MERCHANT_ID']; ?>',
              publicKeyId: '<?php echo $creds['PUBLIC_KEY']; ?>',
              ledgerCurrency: 'USD',         
              // customize the buyer experience
              checkoutLanguage: 'en_US',
              productType: 'PayOnly',
              placement: 'Checkout',
              buttonColor: 'Gold',
              estimatedOrderAmount: { "amount": "109.99", "currencyCode": "USD"},
              // configure Create Checkout Session request
              createCheckoutSessionConfig: {                     

                <?php
                  echo 'payloadJSON: \'' . $payload . '\',';
                  echo 'signature: \'' . $signature . '\'';
                ?>

              }   
          });
      </script>
  </body>
</html>

review.php The review.php file contains multiple api calls, i am not sure whether or not it is valid and should be used.

<?php
    include 'header.php'; // contains $creds and $amazonpay_config

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

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

    try {
        $checkoutSessionId = $_GET['amazonCheckoutSessionId'];
        $client = new Amazon\Pay\API\Client($amazonpay_config);

        $result = $client->getCheckoutSession($checkoutSessionId);

        $updatedCheckoutSession = $client->updateCheckoutSession($checkoutSessionId, $payload);

        if ($result['status'] === 200) {
            $response = json_decode($result['response'], true);
            $checkoutSessionState = $response['statusDetails']['state'];
            $chargeId = $response['chargeId'];
            $chargePermissionId = $response['chargePermissionId'];

            $updateResponse = json_decode($updatedCheckoutSession['response'], true);
            $amazonPayRedirectUrl = $updateResponse['webCheckoutDetails']['amazonPayRedirectUrl'];
            
            print_r($updateResponse); // chargeId, chargePermissionId, are empty

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

amazon_pay_config

$amazonpay_config = array(
    'public_key_id' => $creds['PUBLIC_KEY'],
    'private_key'   => $creds['PRIVATE_KEY_PATH'],
    'sandbox'       => true,
    'region'        => $creds['REGION']
);
  

I am trying amazon pay first time, i will appriciate your help. Also if the code flow is not correct please correct me.

Black Hawk
  • 11
  • 2

1 Answers1

0

It looks like you are looking for the chargeId in the response of UpdateCheckoutSession, which is at a point where the charge has not yet been created.

I recommend reviewing this integration sequence diagram to understand the steps and how/when the charge is generated. There is an amazonPayRedirectUrl returned in the response of UpdateCheckoutSession, and if the paymentIntent is set to anything other than 'Confirm', a charge will be created when you redirect the customer to this Url (this is when payment processing happens). When the customer arrives back on the page you configured as your checkoutResultReturnUrl, make a request to CompleteCheckoutSession and the ChargePermissionId and ChargeId will be included in the response (assuming successful payment).

  • Hey, check the javascript code in index.php file, the amount and other things are set there, but when we print the result of createCheckoutSession it doesn't show that amount there. One more thing, trust me i visited your stackoverflow profile 10 times since morning, in hope of finding a way to contact you. I am very confuse in my implementation, i am not sure if my implementation is correct or not. – Black Hawk Aug 09 '23 at 18:06
  • One last thing, how can i display the Place Order button after getCheckoutSession()? Thank in advance ❤️ – Black Hawk Aug 09 '23 at 18:08
  • I spend entire day on fiverr and freelancer, there was literally no one who can do it, even though i posted this issue for $300. If amazon pay team somehow provide a demo of integration to a sample site, it will be very useful for everyone. People doesn't understand the workflow of amazonpay. – Black Hawk Aug 09 '23 at 18:20
  • https://m.media-amazon.com/images/G/01/EPSDocumentation/AmazonPay/Integration/IntroToAmazonPay._CB1565018491_.png According to this diagram, after clicking on Continue to checkout button the user should be redirected to place order page, but in my case user is directed to my site the popup automatically closed. But how would i put Place Order button. – Black Hawk Aug 09 '23 at 18:22