Amazon Pay Charge ID Always Showing Nil

44 Views Asked by At

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.

1

There are 1 best solutions below

4
Debbie Martindale On

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).