Node.js集成Stripe遇PaymentIntent需支付方式错误求助
修复Stripe「PaymentIntent requires a payment method」错误
问题原因
你的代码存在两个核心问题:
- 使用了Stripe旧版的
sourceAPI关联支付方式,但当前PaymentIntent需要明确指定payment_method参数才能推进支付流程。 - 创建PaymentIntent后未触发支付确认操作,导致支付状态停留在Incomplete。
修复方案
以下是修改后的代码,采用Stripe推荐的Payment Method API,并完成支付确认:
exports.StripePayment = async (req, res) => { const { amount, token } = req.body; const idempotencyKey = uuid(); try { // 将旧版Card Token转换为PaymentMethod(如果前端仍使用createToken) const paymentMethod = await stripe.paymentMethods.create({ type: 'card', card: { token: token.id }, }); // 创建客户并设置默认支付方式 const customer = await stripe.customers.create({ email: token.email, payment_method: paymentMethod.id, invoice_settings: { default_payment_method: paymentMethod.id, }, }); // 创建并自动确认支付Intent const paymentIntent = await stripe.paymentIntents.create({ amount: amount, currency: "INR", customer: customer.id, payment_method: paymentMethod.id, // 指定本次支付使用的支付方式 receipt_email: token.email, shipping: { name: token.card.name, address: { line_1: token.card.address_1, line_2: token.card.address_2, city: token.card.address_city, country: token.card.address_country, postal_code: token.card.address_zip, }, }, confirm: true, // 触发支付确认 automatic_payment_methods: { enabled: true }, }, { idempotencyKey }); console.log("Result", paymentIntent); return res.status(200).json(paymentIntent); } catch (err) { console.error(err); return res.status(400).json({ error: err.message }); } };
额外优化建议
如果前端还在使用旧版的stripe.createToken生成支付令牌,建议升级为stripe.createPaymentMethod,直接获取PaymentMethod ID传给后端,省去转换步骤:
前端示例(React Stripe.js):
const { error, paymentMethod } = await stripe.createPaymentMethod({ type: 'card', card: elements.getElement(CardElement), }); // 将paymentMethod.id传给后端
内容的提问来源于stack exchange,提问作者Subhanshu Sahani
相关产品推荐
相关产品推荐

