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

使用Braintree支付提示金额无效,传入浮点型数值仍报错该如何解决?

核心错误点

你代码中获取金额的逻辑存在明显错误:
$amount = Sponsorship::where('price', $data['price'])->first() 这行代码返回的是Sponsorship模型的实例对象,不是你预期的金额数值,你直接将这个对象传入Braintree交易接口的amount参数,接口无法识别对象类型,自然会抛出金额无效的报错。

修复方案

先判断查询结果是否存在,再取出对应价格字段的值传给接口,参考修改后的代码:

public function payment(Request $request) {
    $data = $request->all();
    $gateway = new Braintree\Gateway([
        'environment' => config('services.braintree.environment'),
        'merchantId' => config('services.braintree.merchantId'),
        'publicKey' => config('services.braintree.publicKey'),
        'privateKey' => config('services.braintree.privateKey')
    ]);
    // 先查询对应的档位
    $sponsorship = Sponsorship::where('price', $data['price'])->first();
    if (!$sponsorship) {
        return back()->withErrors('无效的赞助金额档位');
    }
    // 取出price字段作为金额
    $amount = $sponsorship->price;
    $nonce = $request->payment_method_nonce;

    $result = $gateway->transaction()->sale([
        'amount' => $amount,
        'paymentMethodNonce' => $nonce,
        'customer' => [
            'firstName' => 'Tony',
            'lastName' => 'Stark',
            'email' => 'tony@avengers.com',
        ],
        'options' => [
            'submitForSettlement' => true
        ]
    ]);

    if ($result->success) {
        $transaction = $result->transaction;
        return back()->with('success_message', 'Transaction successful. The ID is:'. $transaction->id);
    } else {
        $errorString = "";
        foreach ($result->errors->deepAll() as $error) {
            $errorString .= 'Error: ' . $error->code . ": " . $error->message . "\n";
        }
        return back()->withErrors('An error occurred with the message: '.$result->message);
    }
}

优化建议

  • 不要直接用前端传入的price作为查询条件,容易被恶意篡改,建议前端传赞助档位ID,后端通过ID查询对应金额,避免支付金额被篡改的风险
  • 传入Braintree接口的金额可以提前格式化为保留两位小数的字符串或浮点型,避免浮点精度问题导致的金额识别错误

内容的提问来源于stack exchange,提问作者D.D.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:18:04