使用PHP SDK实现AmazonPay登录后同页跳转的技术咨询
Got it, let's walk through how to wrap up this Amazon Pay integration flow once the user logs in successfully. Based on your current setup with checkout.php, here's a practical, step-by-step breakdown to get you across the finish line:
1. Capture Authorization & Fetch Access Tokens
Right after the user logs in via the Amazon popup, Amazon Pay will redirect them to your configured redirectUrl (you set this when initializing the Amazon Pay button) with an authorization code in the URL parameters.
First, create a callback page (e.g., amazon-pay-callback.php) to exchange this code for an access token—this token lets you access the user's Amazon Pay data:
session_start(); // Replace with your Amazon Pay credentials $clientId = 'YOUR_CLIENT_ID'; $clientSecret = 'YOUR_CLIENT_SECRET'; $authorizationCode = $_GET['code']; // Call Amazon's token endpoint $tokenUrl = 'https://api.amazon.com/auth/o2/token'; $postData = [ 'grant_type' => 'authorization_code', 'code' => $authorizationCode, 'client_id' => $clientId, 'client_secret' => $clientSecret ]; $ch = curl_init($tokenUrl); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $tokenData = json_decode($response, true); // Store the access token in session for later use $_SESSION['amazon_access_token'] = $tokenData['access_token'];
2. Pull User's Shipping Address & Payment Method
With the access token, you can now fetch the user's default shipping address and saved payment methods via Amazon Pay's APIs:
// Fetch shipping addresses $addressUrl = 'https://pay-api.amazon.com/v2/addresses'; // Use EU/JP endpoints if needed $headers = [ 'Authorization: Bearer ' . $_SESSION['amazon_access_token'], 'Content-Type: application/json' ]; $ch = curl_init($addressUrl); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $addressResponse = curl_exec($ch); curl_close($ch); $addressData = json_decode($addressResponse, true); // Grab the user's default address (adjust index if needed) $_SESSION['amazon_shipping_address'] = $addressData['addresses'][0]; // Fetch payment methods (similar pattern) $paymentUrl = 'https://pay-api.amazon.com/v2/paymentMethods'; $ch = curl_init($paymentUrl); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $paymentResponse = curl_exec($ch); curl_close($ch); $paymentData = json_decode($paymentResponse, true); $_SESSION['amazon_payment_method'] = $paymentData['paymentMethods'][0];
3. Redirect Back to Checkout & Populate Data
Once you have the user's address and payment details, redirect them back to checkout.php and auto-populate the checkout form with the Amazon Pay data:
// In amazon-pay-callback.php, after fetching data header('Location: checkout.php?amazon_pay_connected=1'); exit; // In checkout.php, handle the redirect session_start(); if (isset($_GET['amazon_pay_connected']) && isset($_SESSION['amazon_shipping_address'])) { $shippingAddr = $_SESSION['amazon_shipping_address']; // Auto-fill your checkout form fields echo '<div class="checkout-section"> <h3>Shipping Address (from Amazon)</h3> <p>' . $shippingAddr['name'] . '</p> <p>' . $shippingAddr['addressLine1'] . ', ' . $shippingAddr['city'] . '</p> <p>' . $shippingAddr['postalCode'] . ', ' . $shippingAddr['countryCode'] . '</p> </div>'; // Do the same for payment method details }
4. Initiate Payment & Complete the Order
When the user confirms their order, create a checkout session via Amazon Pay's API to trigger the payment flow:
// In checkout.php, when user clicks "Complete Order" $checkoutUrl = 'https://pay-api.amazon.com/v2/checkoutSessions'; $orderData = [ 'storeId' => 'YOUR_STORE_ID', 'webCheckoutDetails' => [ 'checkoutReviewReturnUrl' => 'https://yourdomain.com/checkout-review.php', 'checkoutResultReturnUrl' => 'https://yourdomain.com/checkout-success.php' ], 'paymentDetails' => [ 'paymentIntent' => 'AuthorizeWithCapture', 'chargeAmount' => [ 'amount' => '49.99', // Your order total 'currencyCode' => 'USD' ] ], 'shippingAddress' => $_SESSION['amazon_shipping_address'] ]; $ch = curl_init($checkoutUrl); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($orderData)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $_SESSION['amazon_access_token'], 'Content-Type: application/json', 'x-amz-pay-idempotency-key: ' . uniqid() // Prevent duplicate requests ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $checkoutResponse = curl_exec($ch); curl_close($ch); $checkoutData = json_decode($checkoutResponse, true); // Redirect user to Amazon's payment confirmation page header('Location: ' . $checkoutData['webCheckoutDetails']['amazonPayRedirectUrl']); exit;
5. Handle Final Payment Result
After the user completes payment, Amazon will redirect them to your checkoutResultReturnUrl. On this page, you can verify the payment status and update your order system:
// In checkout-success.php session_start(); $checkoutSessionId = $_GET['checkoutSessionId']; $statusUrl = "https://pay-api.amazon.com/v2/checkoutSessions/{$checkoutSessionId}"; $ch = curl_init($statusUrl); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $_SESSION['amazon_access_token'], 'Content-Type: application/json' ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $statusResponse = curl_exec($ch); curl_close($ch); $statusData = json_decode($statusResponse, true); if ($statusData['paymentStatus'] === 'Captured') { // Mark order as paid in your database echo '<h1>Payment Successful!</h1>'; } else { // Handle failed payment echo '<h1>Payment Failed. Please try again.</h1>'; }
A quick note: Make sure you're using the correct API endpoints for your region (US, EU, JP) and test with Amazon's sandbox accounts first to iron out any kinks.
内容的提问来源于stack exchange,提问作者Ris Peterson

