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

Omnipay PayPal PHP多商品结算问题:请求无效故障排查

PayPal多商品支付请求报错"Invalid request - see details"问题排查与修复

核心问题:订单总金额与商品总价不匹配

你代码里purchase方法设置的amount是60.00,但通过setItems传入的商品总价是2*10.00 + 1*50.00 = 70.00,PayPal会严格校验订单总金额和商品明细的总价是否一致,不一致就会触发"Invalid request"错误。

其他潜在问题与优化建议

  • 别手动硬编码总金额,最好通过商品明细自动计算,避免人为计算错误
  • 确保商品明细里的价格、数量格式符合PayPal要求(比如价格必须保留两位小数)
  • 回调里的数据库操作建议用预处理语句,比你当前用sprintf加real_escape_string更能防范SQL注入风险

修正后的代码示例

支付请求页面代码

<?php
require_once 'config.php';

if (isset($_POST['submit'])) {
    try {
        // 定义商品列表
        $items = [
            ['name' => 'item1', 'quantity' => 2, 'price' => '10.00'],
            ['name' => 'item2', 'quantity' => 1, 'price' => '50.00']
        ];
        
        // 自动计算总金额并格式化
        $totalAmount = 0;
        foreach ($items as $item) {
            $totalAmount += $item['quantity'] * $item['price'];
        }
        $totalAmount = number_format($totalAmount, 2);

        $response = $gateway->purchase([
            'amount' => $totalAmount, // 使用计算后的正确总价
            'returnUrl' => 'http://localhost:3000/success.php',
            'cancelUrl' => 'http://localhost:3000/cancel.php'
        ])->setItems($items)->send();

        if ($response->isRedirect()) {
            $response->redirect();
        } else {
            echo $response->getMessage();
        }
    } catch(Exception $e) {
        echo $e->getMessage();
    }
}
?>

回调页面优化(预处理语句防注入)

<?php
require_once 'config.php';

if (array_key_exists('paymentId', $_GET) && array_key_exists('PayerID', $_GET)) {
    $transaction = $gateway->completePurchase([
        'payer_id'             => $_GET['PayerID'],
        'transactionReference' => $_GET['paymentId'],
    ]);
    $response = $transaction->send();

    if ($response->isSuccessful()) {
        $arr_body = $response->getData();

        $payment_id = $arr_body['id'];
        $payer_id = $arr_body['payer']['payer_info']['payer_id'];
        $payer_email = $arr_body['payer']['payer_info']['email'];
        $amount = $arr_body['transactions'][0]['amount']['total'];
        $currency = PAYPAL_CURRENCY;
        $payment_status = $arr_body['state'];

        // 预处理语句更安全
        $sql = "INSERT INTO payments(payment_id, payer_id, payer_email, amount, currency, payment_status) VALUES(?, ?, ?, ?, ?, ?)";
        $stmt = $db->prepare($sql);
        $stmt->bind_param("ssssss", $payment_id, $payer_id, $payer_email, $amount, $currency, $payment_status);
        $stmt->execute();
        
        echo "Payment is successful. Your transaction id is: ". $payment_id;
    } else {
        echo $response->getMessage();
    }
} else {
    echo 'Transaction is declined';
}
?>

内容的提问来源于stack exchange,提问作者Aaron Catolico

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 21:02:39