Stripe PaymentIntent返回requires_payment_method状态,如何集成PaymentMethod?
解决PaymentIntent返回"requires_payment_method"的方案
你的PaymentIntent返回requires_payment_method状态,核心原因是创建时未关联有效的支付方式,也没有触发支付确认流程。以下是两种直接可行的处理方案:
方案一:关联已有的PaymentMethod并确认支付
如果你已经通过其他方式获取了客户的PaymentMethod ID(比如客户已保存的支付方式),可以在创建PaymentIntent时直接传入该ID,并开启自动确认:
stripe_charge_response = Stripe::PaymentIntent.create({ amount: amount_cents, currency: candidate.candidate_country[candidate.country.to_s.to_sym][:currency], customer: customer.id, payment_method: "pm_xxxxxx", # 替换为实际的PaymentMethod ID confirm: true, # 自动触发支付确认,需确保客户已授权该支付方式 statement_descriptor_suffix: "EON to Stripe test", on_behalf_of: candidate.stripe_gateway_id, transfer_data: { destination: candidate.stripe_gateway_id, }, }, stripe_version: '2019-12-03')
如果不需要立即确认,可去掉confirm: true,之后手动调用确认接口:
Stripe::PaymentIntent.confirm( stripe_charge_response.id, payment_method: "pm_xxxxxx", stripe_version: '2019-12-03' )
方案二:配合前端收集支付方式完成流程
如果还未收集客户的支付信息,需要前后端配合完成:
- 后端创建未关联支付方式的PaymentIntent:返回
client_secret给前端用于后续确认
stripe_charge_response = Stripe::PaymentIntent.create({ amount: amount_cents, currency: candidate.candidate_country[candidate.country.to_s.to_sym][:currency], customer: customer.id, statement_descriptor_suffix: "EON to Stripe test", on_behalf_of: candidate.stripe_gateway_id, transfer_data: { destination: candidate.stripe_gateway_id, }, }, stripe_version: '2019-12-03') # 返回client_secret给前端 render json: { client_secret: stripe_charge_response.client_secret }
- 前端用Stripe Elements收集支付信息并确认(示例为JavaScript代码):
// 假设已初始化Stripe和Elements const { error } = await stripe.confirmCardPayment(clientSecret, { payment_method: { card: elements.getElement(CardElement), billing_details: { name: "客户姓名", }, }, }); if (error) { // 处理支付错误 } else { // 支付成功,可通知后端更新状态 }
或者前端先创建PaymentMethod再传给后端确认:
const { error, paymentMethod } = await stripe.createPaymentMethod({ type: "card", card: elements.getElement(CardElement), billing_details: { name: "客户姓名" }, }); if (!error) { // 将paymentMethod.id和PaymentIntent ID传给后端 fetch("/api/confirm-payment", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ payment_method_id: paymentMethod.id, payment_intent_id: "pi_xxxxxx" // 替换为后端返回的PaymentIntent ID }), }); }
后端收到PaymentMethod ID后执行确认:
payment_intent = Stripe::PaymentIntent.confirm( params[:payment_intent_id], payment_method: params[:payment_method_id], stripe_version: '2019-12-03' )
注意事项
- 若要获取客户已保存的PaymentMethod,可调用
Stripe::Customer.list_payment_methods(customer.id)获取列表后选择合适的ID - 使用
confirm: true时,需确保客户已授权该支付方式(比如已保存的卡无需再次验证,新卡则需前端完成收集) - 你的Stripe版本
2019-12-03完全支持上述参数和流程
内容的提问来源于stack exchange,提问作者shashank barman
相关产品推荐
相关产品推荐

