为何Stripe Confirm方法无法确认支付或更新PaymentIntent状态?
问题
我通过Stripe的create方法创建了PaymentIntent,并启用3D安全验证支付,但PaymentIntent的状态为"status": "requires_action"。为此我实现了Stripe的confirm方法,期望确认支付并将状态改为succeeded,但该方法未能完成支付确认。
以下是confirm方法的相关代码:
let paymentIntent = req.query.payment_intent; let retrieve = await stripe.paymentIntents .retrieve(paymentIntent) .then((response) => { return response; }); if ( typeof retrieve != "undefined" && retrieve.status == "requires_confirmation" ) { let confirmPayment = await stripe.paymentIntents .confirm(paymentIntent, { payment_method: "pm_card_visa" }) .then((response) => { return res.send(response); }); }
调用该API后,返回的状态仍为requires_action,且Stripe仪表盘中的支付显示未完成,请问这是什么原因?
原因及解决方案
核心问题分析
- 状态判断逻辑错误:代码里只判断了
requires_confirmation状态,但当前PaymentIntent的实际状态是requires_action,导致confirm的核心逻辑根本没执行。 - 测试支付方式不匹配:
pm_card_visa是标准测试卡,默认不会触发3D验证流程。要测试3D验证场景,必须使用Stripe专门提供的需验证测试卡对应的Payment Method,比如pm_card_threeDSecure。 - 缺失前端3D验证交互:3D验证需要用户在前端完成身份校验(如输入验证码),仅后端调用
confirm方法无法完成整个流程。当PaymentIntent处于requires_action状态时,后端需要把next_action数据返回给前端,由前端引导用户完成验证。
修正方案
- 调整状态判断条件:同时兼容
requires_confirmation和requires_action两种状态,确保触发confirm逻辑 - 更换测试支付方式:使用
pm_card_threeDSecure作为测试用的Payment Method,触发3D验证流程 - 补充前端处理逻辑:后端返回确认后的PaymentIntent数据后,前端需检查
next_action字段,调用Stripe.js的handleCardAction方法引导用户完成验证
修正后的示例代码
let paymentIntentId = req.query.payment_intent; try { const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId); // 同时处理两种需要操作的状态 if (['requires_confirmation', 'requires_action'].includes(paymentIntent.status)) { const confirmedIntent = await stripe.paymentIntents.confirm(paymentIntentId, { payment_method: 'pm_card_threeDSecure' // 改用需3D验证的测试支付方式 }); // 返回结果给前端,前端需根据next_action判断是否要处理3D验证 res.send(confirmedIntent); } else { res.send({ status: '无需操作', current_status: paymentIntent.status }); } } catch (err) { res.status(400).send({ error: err.message }); }
内容的提问来源于stack exchange,提问作者sumanth.js
相关产品推荐
相关产品推荐

