Stripe问题:已保存source令牌但无法为客户发起扣款
解决Stripe扣款提示“Cannot charge a customer that has no active card”的问题
我之前踩过完全一样的坑!你现在的问题核心很明确:你只是把Stripe返回的source令牌存在了自己数据库的Customer模型里,但根本没把这个令牌同步到Stripe平台上对应的Customer对象——这就是为什么Stripe后台看不到用户的卡片,扣款时会报错。
Stripe不会自动读取你本地数据库里的令牌,必须显式调用API把支付方式关联到它的Customer记录上,具体步骤如下:
1. 关联令牌到Stripe Customer
在用户提交卡片并返回source令牌后,立刻调用Stripe的Customer修改API,把令牌绑定到已创建的Stripe Customer上。
Python示例
import stripe stripe.api_key = "你的Stripe秘钥" # 从你的数据库获取用户记录(假设你存了stripe_customer_id和source_token) local_customer = Customer.objects.get(id=当前用户ID) # 调用Stripe API绑定卡片 stripe.Customer.modify( local_customer.stripe_customer_id, source=local_customer.source_token )
Node.js示例
const stripe = require('stripe')('你的Stripe秘钥'); // 假设你拿到了用户的stripe客户ID和source令牌 await stripe.customers.update( 'stripe平台的客户ID', { source: '用户提交的source令牌' } );
2. 验证绑定结果
调用完上面的API后,去Stripe后台找到这个Customer,查看“支付方式”,就能看到刚添加的卡片了,状态会是活跃(active)。
3. 发起扣款操作
这时候再调用扣款API就不会报错了,推荐使用新版的PaymentIntent API(支持3D Secure等合规要求):
Python示例(PaymentIntent)
stripe.PaymentIntent.create( amount=1000, # 金额单位为分,这里是10美元 currency='usd', customer=local_customer.stripe_customer_id, payment_method_types=['card'] )
额外注意:如果使用PaymentMethod(替代旧版Source)
如果你用的是Stripe新版的PaymentMethod流程,需要先把PaymentMethod附加到Customer,再设置为默认支付方式:
# 附加PaymentMethod到Customer payment_method = stripe.PaymentMethod.attach( 'pm_xxxxxx', # 用户提交的PaymentMethod ID customer=local_customer.stripe_customer_id ) # 设置为默认支付方式 stripe.Customer.modify( local_customer.stripe_customer_id, invoice_settings={ 'default_payment_method': payment_method.id } )
总结一下:本地存令牌只是你自己的记录,必须告诉Stripe把这个令牌对应的卡片绑定到它的Customer上,之后才能正常扣款。
内容的提问来源于stack exchange,提问作者questnofinterest
相关产品推荐
相关产品推荐

