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

Stripe结账IntegrationError:非整数金额触发问题求助

Stripe非整数金额结账报错问题修复指引

问题根源

非整数金额触发报错,核心原因是金额格式处理不当:Stripe要求金额必须以「最小货币单位的整数」传递(如美元需传分,18.99美元对应1899),非整数金额若直接做浮点数运算,会因精度丢失导致会话创建失败,前端拿不到有效sessionId,最终触发redirectToCheckout缺少必填参数的错误。


服务端 order.js 修改

1. 修复金额转换逻辑

将从Strapi获取的价格转换为最小货币单位整数时,用Math.round()避免浮点数精度问题:

// 错误写法(会出现精度丢失:18.99*100=1898.9999999999998)
const amount = item.price * 100;

// 正确写法
const amount = Math.round(parseFloat(item.price) * 100);

2. 完善Stripe会话创建的错误捕获

增加异常捕获,排查会话创建失败的具体原因:

try {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: cartItems.map(item => ({
      price_data: {
        currency: 'usd', // 确保与你使用的货币一致
        product_data: { name: item.name },
        unit_amount: Math.round(parseFloat(item.price) * 100),
      },
      quantity: item.quantity,
    })),
    mode: 'payment',
    success_url: `${process.env.CLIENT_URL}/success`,
    cancel_url: `${process.env.CLIENT_URL}/cart`,
  });
  return { sessionId: session.id };
} catch (error) {
  console.error('Stripe会话创建失败:', error);
  throw new Error('支付会话创建失败,请检查金额设置');
}

前端 Checkout.jsx 修改

1. 确保价格参数正确传递

直接传递Strapi返回的原始价格,不在前端做整数转换:

const handleCheckout = async () => {
  try {
    const response = await fetch('/api/create-order', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        cartItems: cartItems.map(item => ({
          id: item.id,
          name: item.name,
          price: item.price, // 直接传原始价格,避免前端转换出错
          quantity: item.quantity,
        })),
      }),
    });

    if (!response.ok) throw new Error('订单创建失败');
    const { sessionId } = await response.json();

    if (!sessionId) throw new Error('未获取到支付会话ID');

    const { error } = await stripe.redirectToCheckout({ sessionId });
    if (error) console.error('结账跳转错误:', error);
  } catch (error) {
    console.error('结账流程错误:', error);
    alert('结账失败,请稍后重试');
  }
};

前端 CartMenu.jsx 修改

  • 确保购物车中存储的商品价格是纯数值类型(如18.99),而非带货币符号的字符串(如$18.99);
  • 若有价格格式化逻辑,仅用于展示,不要修改存储的原始数值。

额外排查点

  1. 检查Strapi中价格字段类型:必须设置为Number(浮点数),而非String;
  2. 单独测试非整数金额的会话创建:在后端写测试代码,传入18.99,验证生成的Stripe会话是否正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 06:17:01