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

调用/create-payment-intent接口报错,需同步HTML与Ruby订单总额

问题分析与解决方法

核心问题定位

  • Ruby后端/create-payment-intent路由未正确解析请求体数据,data变量未定义直接使用,引发后端报错。
  • index.html中尝试操作不存在的total-input元素,导致前端脚本执行错误。
  • 调用接口时未按要求传递JSON格式的请求参数。

代码修正方案

1. Ruby后端脚本修正(/create-payment-intent路由)

在获取total前先解析POST请求体:

post '/create-payment-intent' do
  request.body.rewind
  data = JSON.parse(request.body.read)
  total = data['total'].to_i # 转换为整数,Stripe金额要求以最小货币单位计算(如欧元分)
  
  payment_intent = Stripe::PaymentIntent.create({
    amount: total,
    currency: 'eur',
    automatic_payment_methods: { enabled: true }
  })
  { clientSecret: payment_intent.client_secret }.to_json
end

2. index.html页面修正

添加隐藏的total-input元素,确保脚本能找到目标元素:

<form id="payment-form" method="POST">
  <input type="text" name="email" id="email" placeholder="E-Mail" required>
  <input type="text" name="name" id="name" placeholder="Full Name" required>
  <!-- 添加隐藏输入框用于存储总额 -->
  <input type="hidden" id="total-input" name="total">
  
  <div id="payment-element"></div>
  <button>Pay</button>
  <div id="error-messages"></div>
</form>

3. 正确调用接口的PowerShell命令

传递JSON格式的请求体参数:

Invoke-WebRequest -Method POST -Uri http://localhost:4242/create-payment-intent -Body '{"total": 1000}' -ContentType "application/json"

注:示例中1000代表10欧元,Stripe金额需以最小货币单位(分)传入。

额外注意事项

  • 确保后端$cart_items的总额计算逻辑正确,传递给前端的total值是最小货币单位的整数。
  • 前端提交支付请求时,需通过payment.js将页面中的total值以JSON格式发送到/create-payment-intent接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 02:12:01