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

PHP对接Stripe实现自定义捐赠金额时返回0问题求助

问题根因&修复方案

1. 前端取值逻辑错误

你代码中直接使用amount.value读取输入值,未提前通过ID获取输入框的DOM对象。现代浏览器默认不会将DOM元素ID注册为全局变量,此时amount为undefined,经过parseInt转换后得到NaN,最终传给后端的金额就是0。
修复后的前端JS逻辑:

checkoutButton.addEventListener("click", function () {
  // 手动获取金额输入框DOM
  const amountEl = document.getElementById('amount');
  const inputAmount = parseInt(amountEl.value, 10);
  // 前置校验金额合法性
  if (isNaN(inputAmount) || inputAmount < 1) {
    alert('请输入不小于1的有效金额');
    return;
  }
  fetch("create-checkout-session.php", {
    method: "POST", 
    headers: { 'Content-Type': 'application/json'},
    // 金额转美分单位
    body: JSON.stringify({amount: inputAmount * 100})
  })
  .then(function (response) {
    return response.json();
  })
  .then(function (session) {
    return stripe.redirectToCheckout({ sessionId: session.id });
  })
  .then(function (result) {
    if (result.error) {
      alert(result.error.message);
    }
  })
  .catch(function (error) {
    console.error("Error:", error);
  });
});

你也可以给输入框加原生属性限制非法输入:

<input type="number" id="amount" value="100" min="1" step="1"/>

2. 后端代码多余输出破坏响应格式

你在PHP代码中加入了var_dump(file_get_contents('php://input'))调试语句,这行代码会直接向响应体输出调试内容,导致后续返回的JSON格式被污染,前端无法正常解析响应。同时你没有对请求参数做非空校验,参数缺失时$content['amount']为null,转int后也是0。
修复后的后端代码:

<?php
include 'stripe-php/init.php';
header('Content-Type: application/json; charset=UTF-8');
\Stripe\Stripe::setApiKey('sk_test_xxxxxxxxx');
$DOMAIN = 'http://localhost/hro';

// 只读一次请求体,避免重复读取问题
$rawInput = file_get_contents('php://input');
$content = json_decode($rawInput, true);

// 校验金额参数合法性
if (!isset($content['amount']) || intval($content['amount']) < 50) {
  // USD货币最低支付金额为50美分,可根据自己使用的货币调整最低限制
  http_response_code(400);
  echo json_encode(['error' => '金额不能低于0.5美元']);
  exit;
}

$amount = intval($content['amount']);
$session = \Stripe\Checkout\Session::create([
          'payment_method_types' => ['card'],
          'line_items' => [[
            'price_data' => [
              'currency' => 'usd',
              'unit_amount' => $amount,
              'product_data' => [
                'name' => 'Your Donation Amount'
              ]
            ],
            'quantity' => 1
          ]],
          'mode' => 'payment',
          'success_url' => $DOMAIN . '/success.html',
          'cancel_url' => $DOMAIN . '/cancel.html'
        ]);

echo json_encode(['id' => $session->id]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:06:04