You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中Stripe结账时如何传递Payment Intent ID并指定已保存卡片

解决方法

你的问题核心是手动创建并立即确认Payment Intent导致两个问题:一是触发3DS验证后未处理,Payment Intent处于INCOMPLETE状态;二是Checkout Session传入无效的Payment Intent后自动生成新的,从而忽略了你指定的支付方式。

方案一:直接用Checkout Session调用已保存的支付方式(推荐)

不需要手动创建Payment Intent,让Stripe Checkout自动关联用户选择的已保存卡片,同时预选中你指定的selected_card_id。修改代码如下:

# 获取当前登录用户
current_user_id = request.user.id
user = User.objects.get(id=current_user_id) 
selected_card_id = request.session.get("selected_card_id")

# 为新用户创建Stripe客户ID
if not user.customer_id:
    customer = stripe.Customer.create()
    user.customer_id = customer.id
    user.save()

# 创建Checkout Session,直接关联用户选择的支付方式
checkout_session = stripe.checkout.Session.create(
    mode='payment',
    payment_method_types=['card'],                
    line_items=[
        {
            'quantity': 1,
            'price': 'price_1NevYPSIWq54gkyCEytMLqZ1',
        }
    ],
    success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
    cancel_url=domain_url + 'cancelled/',
    customer=user.customer_id,
    # 预选中用户选择的已保存卡片
    payment_method=selected_card_id
)

方案二:手动创建Payment Intent并通过Checkout完成验证

如果必须手动创建Payment Intent,不要立即确认,而是让Checkout处理后续的验证流程,确保只生成一个Payment Intent:

# 获取当前登录用户
current_user_id = request.user.id
user = User.objects.get(id=current_user_id) 
selected_card_id = request.session.get("selected_card_id")

# 为新用户创建Stripe客户ID
if not user.customer_id:
    customer = stripe.Customer.create()
    user.customer_id = customer.id
    user.save()

# 创建未确认的Payment Intent
payment_intent = stripe.PaymentIntent.create(
    currency='inr',
    customer=user.customer_id,
    amount=299900,  # 金额必须和Checkout line_items的总金额一致
    payment_method=selected_card_id,
    confirm=False,  # 不要立即确认,交给Checkout处理
)

# 创建Checkout Session并关联这个Payment Intent
checkout_session = stripe.checkout.Session.create(
    mode='payment',
    payment_intent=payment_intent.id,
    payment_method_types=['card'],                
    line_items=[
        {
            'quantity': 1,
            'price': 'price_1NevYPSIWq54gkyCEytMLqZ1',
        }
    ],
    success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
    cancel_url=domain_url + 'cancelled/',
    customer=user.customer_id
)

测试模式下处理3DS验证

测试时使用Stripe提供的3DS测试卡号4000000000003220,在Checkout界面会触发3DS验证流程,按照提示完成验证即可,Payment Intent会正常变为COMPLETED状态。

内容的提问来源于stack exchange,提问作者Yogesh Bhagat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 18:04:53