You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PayPal PHP支付对接咨询:自定义交易ID+WebHook/IPN回调及示例代码

方案可行性确认

这个方案完全可行——PayPal的v2 REST API完美匹配你的需求:支持创建包含商品明细的订单、传入自定义交易标识,并且可以通过WebHook接收支付完成后的状态通知,实现订单的闭环确认。

示例代码实现

1. 前端产品选择表单

带复选框的产品选择表格,用户勾选后提交到后端下单接口:

<form method="post" action="create-paypal-order.php">
  <table border="1">
    <tr>
      <th>选择</th>
      <th>产品名称</th>
      <th>单价</th>
    </tr>
    <tr>
      <td><input type="checkbox" name="products[]" value="product_2"></td>
      <td>产品2</td>
      <td>$19.99</td>
    </tr>
    <tr>
      <td><input type="checkbox" name="products[]" value="product_3"></td>
      <td>产品3</td>
      <td>$29.99</td>
    </tr>
  </table>
  <button type="submit" style="margin-top:10px;">下单</button>
</form>

2. 后端创建PayPal订单脚本(create-paypal-order.php)

负责生成自定义交易ID、调用PayPal API创建订单并引导用户跳转支付页面。
首先通过Composer安装PayPal官方SDK:composer require paypal/paypal-checkout-sdk

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

use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;

// PayPal沙箱环境凭证(上线替换为生产环境凭证)
$clientId = '你的PayPal客户端ID';
$clientSecret = '你的PayPal客户端密钥';

// 生成自定义交易ID(格式可自定义,确保唯一)
$customTransactionId = 'ORD-' . time() . '-' . mt_rand(1000, 9999);

// 获取用户勾选的产品
$selectedProducts = $_POST['products'] ?? [];
if (empty($selectedProducts)) {
    die('请至少选择一个产品');
}

// 产品价格映射(实际项目建议从数据库读取)
$productData = [
    'product_2' => ['name' => '产品2', 'price' => 19.99],
    'product_3' => ['name' => '产品3', 'price' => 29.99]
];

// 构建商品明细与总价
$items = [];
$totalAmount = 0.00;
foreach ($selectedProducts as $prodId) {
    if (isset($productData[$prodId])) {
        $prod = $productData[$prodId];
        $items[] = [
            'name' => $prod['name'],
            'unit_amount' => [
                'currency_code' => 'USD',
                'value' => number_format($prod['price'], 2)
            ],
            'quantity' => '1'
        ];
        $totalAmount += $prod['price'];
    }
}

// 初始化PayPal客户端
$environment = new SandboxEnvironment($clientId, $clientSecret);
$client = new PayPalHttpClient($environment);

// 创建订单请求
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = [
    'intent' => 'CAPTURE',
    'application_context' => [
        'return_url' => 'https://你的域名/payment-success.php', // 支付成功跳转页
        'cancel_url' => 'https://你的域名/payment-cancel.php'   // 支付取消跳转页
    ],
    'purchase_units' => [[
        'reference_id' => $customTransactionId, // 传入自定义交易ID
        'amount' => [
            'currency_code' => 'USD',
            'value' => number_format($totalAmount, 2),
            'breakdown' => [
                'item_total' => [
                    'currency_code' => 'USD',
                    'value' => number_format($totalAmount, 2)
                ]
            ]
        ],
        'items' => $items // 传递商品明细,PayPal支付页会展示
    ]]
];

try {
    $response = $client->execute($request);
    // 跳转至PayPal支付授权页
    foreach ($response->result->links as $link) {
        if ($link->rel === 'approve') {
            header("Location: {$link->href}");
            exit;
        }
    }
} catch (Exception $e) {
    die('订单创建失败:' . $e->getMessage());
}
?>

3. WebHook回调处理脚本(paypal-webhook.php)

接收并验证PayPal的支付状态通知,根据自定义交易ID更新订单状态。

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

use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Webhooks\WebhooksVerifySignatureRequest;

// PayPal凭证与WebHook ID(在PayPal开发者后台创建WebHook时获取)
$clientId = '你的PayPal客户端ID';
$clientSecret = '你的PayPal客户端密钥';
$webhookId = '你的WebHook ID';

// 获取PayPal发送的通知内容与请求头
$payload = file_get_contents('php://input');
$headers = getallheaders();

// 初始化PayPal客户端
$environment = new SandboxEnvironment($clientId, $clientSecret);
$client = new PayPalHttpClient($environment);

// 构建签名验证请求
$request = new WebhooksVerifySignatureRequest();
$request->body = [
    'auth_algo' => $headers['PayPal-Auth-Algo'],
    'cert_url' => $headers['PayPal-Cert-Url'],
    'transmission_id' => $headers['PayPal-Transmission-Id'],
    'transmission_sig' => $headers['PayPal-Transmission-Sig'],
    'transmission_time' => $headers['PayPal-Transmission-Time'],
    'webhook_id' => $webhookId,
    'webhook_event' => json_decode($payload, true)
];

try {
    $response = $client->execute($request);
    if ($response->result->verification_status === 'SUCCESS') {
        $event = json_decode($payload, true);
        // 处理支付完成事件
        if ($event['event_type'] === 'CHECKOUT.ORDER.APPROVED') {
            $customTransactionId = $event['resource']['purchase_units'][0]['reference_id'];
            $paypalOrderId = $event['resource']['id'];

            // 此处编写业务逻辑:更新数据库订单状态、记录支付信息等
            file_put_contents('payment_logs.txt', "订单{$customTransactionId}支付成功 | PayPal订单ID:{$paypalOrderId}\n", FILE_APPEND);

            // 返回200状态码告知PayPal已接收通知
            http_response_code(200);
            echo 'OK';
        } else {
            // 其他事件类型可按需处理
            http_response_code(200);
            echo 'Event ignored';
        }
    } else {
        http_response_code(400);
        echo 'Invalid signature';
    }
} catch (Exception $e) {
    http_response_code(500);
    echo 'WebHook处理失败:' . $e->getMessage();
}
?>
关键配置说明
  1. 在PayPal开发者后台创建应用,获取clientId和clientSecret(沙箱环境用于测试,生产环境用于正式上线)
  2. 创建WebHook,选择CHECKOUT.ORDER.APPROVED事件,设置回调URL为你的paypal-webhook.php地址(必须为HTTPS)
  3. 测试时使用PayPal沙箱账号进行支付验证
  4. 正式上线前需将沙箱环境替换为生产环境

内容的提问来源于stack exchange,提问作者Steve Brown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 23:32:08