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

Stripe嵌入式结账报错:创建价格需指定product或product_data

修复Stripe嵌入式结账“创建价格时必须指定product或product_data”错误

核心问题

你遇到的错误并非product_data未正确传递,而是前端传入的price_wa格式不符合Stripe要求:

  • Stripe的unit_amount要求为整数(以分为单位),例如10美元需传入1000
  • 你的前端代码直接从DOM元素取价格文本,大概率是带格式的字符串(如$19.99或19,99),后端直接将该字符串传给Stripe,导致price_data参数无效,Stripe无法正常解析,进而抛出误导性错误。

修复步骤

1. 前端处理价格格式

修改addItemtoStripe函数,清理价格字符串并转换为分单位:

function addItemtoStripe(event) {
    event.preventDefault(); 
    var button2 = event.target;
    var StripeItem = button2.parentElement.parentElement;
    var title_wa = StripeItem.getElementsByClassName('title')[0].innerText.trim();
    // 清理价格:移除$、逗号等非数字字符,转成数字后乘以100得到分
    var priceText = StripeItem.getElementsByClassName('thingPrice')[0].innerText.trim();
    var price_wa = Math.round(parseFloat(priceText.replace(/[^0-9.]/g, '')) * 100);

    fetch('/checkout', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ title_wa: title_wa, price_wa: price_wa })
    })
    .then(response => response.json())
    .then(data => {
        window.location.href = data.url;
    })
    .catch(error => {
        console.error('Error:', error);
    });
}

2. 后端验证并确保参数有效

修改server.js,添加参数验证,并确保unit_amount为整数:

app.post('/checkout', async (req, res) => {
    try {
        const { title_wa, price_wa} = req.body;

        // 验证必填参数有效性
        if (!title_wa || !price_wa || isNaN(parseInt(price_wa))) {
            return res.status(400).json({ error: '无效的商品信息' });
        }

        const session = await stripe.checkout.sessions.create({
            line_items: [
                {
                    price_data: {
                        currency: 'usd',
                        product_data: {
                            name: title_wa.trim(),
                        },
                        unit_amount: parseInt(price_wa),
                    },
                    quantity: 1
                },         
            ],
            mode: 'payment',
            shipping_address_collection: {
                allowed_countries: ['US', 'BR']
            },
            success_url: `${process.env.BASE_URL}/complete?session_id={CHECKOUT_SESSION_ID}`,
            cancel_url: `${process.env.BASE_URL}/cancel`
        });

        res.json({ url: session.url }); // 适配前端fetch请求,返回JSON格式的跳转链接
    } catch (error) {
        console.error('Stripe错误详情:', error);
        res.status(500).json({ error: error.message });
    }
})

额外注意事项

  • 原后端代码使用res.redirect(session.url),但前端通过fetch发起请求,这种场景下应返回JSON格式的url,由前端完成跳转(你的前端代码已实现window.location.href = data.url,需对应调整后端响应方式)
  • 添加try/catch捕获错误,可直接查看Stripe返回的具体错误详情,方便调试

关于预先创建产品和价格

如果你的商品为固定款,预先创建Product和Price确实更高效,但需注意:

  • 确保每次创建Checkout Session时使用的Price ID有效
  • 可通过商品名称查询已存在的产品,避免重复创建相同资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:00:03