基于Django:如何让Stripe第二次支付自动填充信息,第三、四次不填充?
问题:Stripe Checkout 支付信息自动填充控制需求
我用以下Django代码在test模式下测试Stripe Checkout的payment_method_options.card.setup_future_usage功能:
# "views.py" def test(request): # Here customer = stripe.Customer.search(query="email:'mytest@gmail.com'", limit=1) checkout_session = stripe.checkout.Session.create( customer=customer["data"][0]["id"] if customer.has_more else None, line_items=[ { "price_data": { "currency": "USD", "unit_amount_decimal": 1000, "product_data": { "name": "T-shirt", "description": "Good T-shirt", }, }, "quantity": 2, } ], payment_method_options={ # Here "card": { "setup_future_usage": "on_session", }, }, mode='payment', success_url='http://localhost:8000', cancel_url='http://localhost:8000' ) return redirect(checkout_session.url, code=303)
测试情况:
- 首次用mytest@gmail.com支付:需手动填写全部信息
- 第二次、第三次支付:仍需手动填写,未自动填充
- 第四次支付:信息自动填充
需求:在test和live模式下,实现第二次支付自动填充全部信息,第三次及之后不自动填充。
解决方案
要实现这个精准控制,核心是管理Stripe客户的支付方式关联,以及动态调整Checkout Session的参数,具体操作如下:
1. 核心逻辑梳理
- 首次支付:让Stripe绑定支付方式到客户,但此时无已存方式,需手动填写
- 第二次支付:主动指定复用已绑定的支付方式,实现自动填充
- 第三次及以后:不关联任何已存支付方式,强制用户重新输入
2. 代码实现步骤
第一步:维护客户支付次数
你需要在自己的数据库中记录每个客户的支付次数(比如给Django的Customer关联模型加一个payment_count字段),因为Stripe不会主动统计客户的支付次数。
第二步:动态生成Checkout Session参数
根据支付次数调整Session的创建参数:
def test(request): # 查询目标客户 customer_search = stripe.Customer.search(query="email:'mytest@gmail.com'", limit=1) customer_id = customer_search["data"][0]["id"] if customer_search.data else None if not customer_id: # 处理客户不存在的情况,比如创建新客户 customer = stripe.Customer.create(email="mytest@gmail.com") customer_id = customer.id payment_count = 0 else: # 从自己的数据库获取该客户的支付次数 payment_count = get_customer_payment_count(customer_id) # 自定义函数,需自己实现 # 基础Session参数 checkout_params = { "customer": customer_id, "line_items": [ { "price_data": { "currency": "USD", "unit_amount_decimal": 1000, "product_data": { "name": "T-shirt", "description": "Good T-shirt", }, }, "quantity": 2, } ], "mode": 'payment', "success_url": 'http://localhost:8000', "cancel_url": 'http://localhost:8000' } # 根据支付次数调整参数 if payment_count == 0: # 首次支付:绑定支付方式 checkout_params["payment_method_options"] = { "card": { "setup_future_usage": "on_session", }, } elif payment_count == 1: # 第二次支付:复用已绑定的支付方式 # 获取客户已保存的卡片支付方式 payment_methods = stripe.PaymentMethod.list(customer=customer_id, type="card", limit=1) if payment_methods.data: checkout_params["payment_method"] = payment_methods.data[0].id # 不设置setup_future_usage,避免后续复用提示 # 第三次及以后:不额外设置参数,Stripe不会自动填充支付信息 # 创建Session并跳转 checkout_session = stripe.checkout.Session.create(**checkout_params) # 支付成功后记得更新数据库中的payment_count return redirect(checkout_session.url, code=303)
第三步:可选操作——清理支付方式(彻底禁用后续复用)
如果希望第三次及以后完全无法复用之前的支付方式,可以在第二次支付成功后,调用Stripe API解绑该支付方式:
# 支付成功的回调视图中执行 payment_method_id = "已绑定的支付方式ID" stripe.PaymentMethod.detach(payment_method_id)
3. 注意事项
- Test模式测试时,使用Stripe官方测试卡号(如4242 4242 4242 4242)即可验证绑定和复用逻辑
- Live模式下确保Webhook配置正确,用于支付成功后更新支付次数或解绑支付方式
内容的提问来源于stack exchange,提问作者Super Kai - Kazuya Ito
相关产品推荐
相关产品推荐

