PHP中创建PayPal订阅按钮:支付完成后返回指定数组至成功页
Alright, let's walk through setting up your PayPal subscription button in PHP so that you receive the exact array you need on your success page. We'll cover creating the dynamic button, passing custom parameters, and handling the return data properly.
1. Create the Dynamic PayPal Subscription Button
First, we'll generate a subscription button that sends your custom parameters to PayPal, which will then pass them back to your success page. We'll also include essential subscription details like pricing and recurrence.
<?php session_start(); // Start session to capture PHPSESSID // PayPal environment settings (use sandbox URL for testing) $paypal_url = 'https://www.paypal.com/cgi-bin/webscr'; $return_url = 'https://your-domain.com/success.php'; // Replace with your success page URL $cancel_url = 'https://your-domain.com/cancel.php'; // Define your custom parameters to pass back $custom_data = [ 'rapidsState' => 'MerchantPayments__Subscription__StandardSubscriptionsFlow___StateDone', 'form_charset' => 'UTF-8', 'PHPSESSID' => session_id() // Capture current session ID ]; ?> <form action="<?= $paypal_url ?>" method="post" target="_top"> <!-- PayPal subscription command --> <input type="hidden" name="cmd" value="_xclick-subscriptions"> <!-- Your PayPal business email/ID --> <input type="hidden" name="business" value="your-paypal-business@example.com"> <!-- Subscription details --> <input type="hidden" name="item_name" value="Premium Monthly Subscription"> <input type="hidden" name="currency_code" value="USD"> <input type="hidden" name="a3" value="19.99"> <!-- Monthly price --> <input type="hidden" name="p3" value="1"> <!-- Billing cycle length --> <input type="hidden" name="t3" value="M"> <!-- Billing cycle unit (M=Month, Y=Year) --> <input type="hidden" name="src" value="1"> <!-- Enable automatic renewal --> <input type="hidden" name="sra" value="1"> <!-- Retry failed payments --> <!-- Return URLs --> <input type="hidden" name="return" value="<?= urlencode($return_url) ?>"> <input type="hidden" name="cancel_return" value="<?= urlencode($cancel_url) ?>"> <!-- Pass custom data as JSON (PayPal will send this back) --> <input type="hidden" name="custom" value="<?= json_encode($custom_data) ?>"> <!-- PayPal submit button --> <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"> <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1"> </form>
2. Handle the Success Page and Build Your Target Array
On your success page, we'll retrieve the data PayPal sends back, including your custom parameters, and assemble the array you need. Note: The auth and rapidsStateSignature values may require extra steps (like API calls or custom signing) since PayPal doesn't return these by default.
<?php session_start(); // Retrieve PayPal's return parameters $paypal_return_data = $_GET; // Decode the custom data we sent earlier $custom_data = json_decode($paypal_return_data['custom'] ?? '', true) ?? []; // Get the subscription ID (PayPal returns this as 'subscr_id') $subscription_id = $paypal_return_data['subscr_id'] ?? ''; // -------------------------- // Important Note for `auth`: // To get a valid authorization token, you'll need to use PayPal's REST API // to fetch the subscription details. Here's a quick snippet using the PayPal SDK: // -------------------------- // require 'vendor/autoload.php'; // $api_context = new \PayPal\Rest\ApiContext( // new \PayPal\Auth\OAuthTokenCredential('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET') // ); // $subscription = \PayPal\Api\Subscription::get($subscription_id, $api_context); // $auth_token = $subscription->getPlan()->getId(); // Adjust based on your needs // For this example, we'll use a placeholder (replace with real API logic) $auth_token = $paypal_return_data['auth'] ?? 'A6nD0MjozNYLgA-A05px8rNLr3mKg-gdRPEpu2VMo8jcPB9D0gh5TCuVnVcvBqNZBL1gS1S6AqBXXc8Wqmay9FdH2wFAn-hll26PXuHWv8nQ'; // -------------------------- // Important Note for `rapidsStateSignature`: // This should be a signature YOU generate before sending the button request // to verify data integrity. Generate it with a secret key, then validate it here. // -------------------------- // Example signature generation (on button page): // $signature = hash_hmac('sha1', json_encode($custom_data) . $subscription_id, 'YOUR_SECRET_KEY'); // Validate here: // $received_signature = $paypal_return_data['rapidsStateSignature'] ?? ''; // if (hash_hmac('sha1', json_encode($custom_data) . $subscription_id, 'YOUR_SECRET_KEY') !== $received_signature) { // die('Invalid signature'); // } // Placeholder signature for this example $rapids_signature = $paypal_return_data['rapidsStateSignature'] ?? '6a1cdb1820bfbb59264d5a2869ad09c618034678'; // Build your target array $result_array = [ 'auth' => $auth_token, 'rapidsState' => $custom_data['rapidsState'] ?? '', 'rapidsStateSignature' => $rapids_signature, 'form_charset' => $custom_data['form_charset'] ?? 'UTF-8', 'PHPSESSID' => $custom_data['PHPSESSID'] ?? session_id() ]; // Output the array to verify echo '<pre>'; print_r($result_array); echo '</pre>'; ?>
Key Notes for Production
- Security First: Always validate PayPal's return data using PDT (Payment Data Transfer) or Webhooks to ensure the request is legitimate. Never trust unvalidated data from the URL.
- API Integration: For real
authtokens, use PayPal's official PHP SDK to fetch subscription details. You'll need to create a PayPal Developer account to get your Client ID and Secret. - Signature Validation: Generate
rapidsStateSignatureon the button page using a secret key, then validate it on the success page to prevent tampering.
内容的提问来源于stack exchange,提问作者pratik chatterjee

