如何基于Stripe实现Card On File功能?PaymentIntent无法复用
Stripe Card On File(卡档)功能正确实现流程
由于PaymentIntent是为单次扣款设计的,无法复用,要实现定期扣款的卡档功能,核心是把用户的支付方式绑定到Customer对象上,后续基于该对象发起重复扣款。完整流程如下:
1. 创建Customer对象
首先为用户创建Stripe Customer,这是存储支付方式、管理后续扣款的核心载体。
后端调用API创建:
# Python后端示例代码 stripe.Customer.create( email="user@example.com", description="Card On File 用户" )
创建后会得到cus_xxx格式的Customer ID,后续所有操作需关联该ID。
2. 收集并绑定支付方式到Customer
通过Stripe Elements收集用户信用卡信息后,将支付方式绑定到已创建的Customer上,有两种常用方式:
方式一:使用SetupIntent(推荐,适用于仅保存卡不立即扣款)
后端创建SetupIntent并关联Customer:
setup_intent = stripe.SetupIntent.create( customer="cus_xxx", payment_method_types=["card"] )将
setup_intent.client_secret传给前端。前端用Stripe Elements初始化,收集卡信息后确认SetupIntent:
// 前端示例代码 const stripe = Stripe('你的公钥'); const elements = stripe.elements(); const cardElement = elements.create('card'); cardElement.mount('#card-element'); // 提交时确认SetupIntent const { error } = await stripe.confirmCardSetup( setup_intent_client_secret, { payment_method: { card: cardElement, billing_details: { name: '用户姓名' } } } );确认成功后,支付方式会自动绑定到Customer,可通过
stripe.customers.listPaymentMethods("cus_xxx")查看。
方式二:创建PaymentMethod后手动绑定
前端收集卡信息后创建PaymentMethod:
const { error, paymentMethod } = await stripe.createPaymentMethod({ type: 'card', card: cardElement, billing_details: { name: '用户姓名' } });将
paymentMethod.id(格式pm_xxx)传给后端。后端将PaymentMethod绑定到Customer,可选设置为默认支付方式:
stripe.PaymentMethod.attach( "pm_xxx", customer="cus_xxx" ) # 设置为默认支付方式(可选) stripe.Customer.modify( "cus_xxx", invoice_settings={ "default_payment_method": "pm_xxx" } )
3. 定期发起扣款
根据业务场景,选择两种扣款方式:
场景A:固定周期固定金额(如会员月费)—— 使用Subscription
创建订阅后,Stripe会自动按周期发起扣款:
stripe.Subscription.create( customer="cus_xxx", items=[{ "price": "price_xxx" # 提前创建的价格ID,包含金额和周期 }], payment_behavior="default_incomplete", # 处理3DS等验证需求 expand=["latest_invoice.payment_intent"] )
场景B:灵活金额/不定周期扣款—— 重复创建PaymentIntent
每次扣款时,基于Customer和绑定的支付方式创建新的PaymentIntent:
stripe.PaymentIntent.create( amount=1000, # 金额,单位为分(如1000 = $10) currency="usd", customer="cus_xxx", payment_method="pm_xxx", # 可选,不填则用Customer的默认支付方式 confirm=True, # 自动尝试扣款 automatic_payment_methods={"enabled": True} )
关键注意事项
- 绑定的支付方式状态必须为
attached,才能用于后续扣款。 - 若卡需要3DS验证,SetupIntent或首次PaymentIntent确认时会触发验证流程,需确保前端处理验证弹窗。
- 定期扣款前可调用
stripe.paymentMethods.retrieve("pm_xxx")检查卡的有效性(如是否过期)。
内容的提问来源于stack exchange,提问作者Craig
相关产品推荐
相关产品推荐

