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

Django集成Stripe:Webhook无法获取展开的line_items数据求助

解决Stripe Checkout Session Webhook无法获取line_items的问题

问题核心

Stripe的Webhook事件(如checkout.session.completed)默认不会携带line_items的完整数据——即便你创建Session时使用了expand=['line_items'],这个参数仅作用于创建Session时的即时响应,不会自动同步到后续Webhook推送的事件对象中。

可行解决方案

方案1:Webhook中主动请求完整Session数据

收到Webhook事件后,不要直接使用事件内的data.object,而是通过Stripe API传入Session ID,主动拉取并展开line_items:

# 以Python Stripe SDK为例
import stripe

stripe.api_key = "你的API密钥"

def stripe_webhook_handler(request):
    payload = request.body
    sig_header = request.META.get('HTTP_STRIPE_SIGNATURE')
    endpoint_secret = "你的Webhook密钥"

    # 验证Webhook签名
    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, endpoint_secret
        )
    except (ValueError, stripe.error.SignatureVerificationError):
        return HttpResponse(status=400)

    # 处理支付完成事件
    if event['type'] == 'checkout.session.completed':
        session_id = event['data']['object']['id']
        # 主动获取Session并展开line_items
        full_session = stripe.checkout.Session.retrieve(
            session_id,
            expand=['line_items']
        )
        # 提取line_items数据用于创建订单/支付记录
        line_items = full_session.line_items
        # 此处编写你的业务逻辑
        create_order_and_payment_record(line_items)

    return HttpResponse(status=200)

方案2:精简数据存入metadata(适合小体量订单信息)

如果line_items中的核心数据可以精简,可将关键信息打包成JSON字符串存入metadata,避免额外API调用:

# 创建Checkout Session时的代码
import json

checkout_session = stripe.checkout.Session.create(
    payment_method_types=['card'],
    line_items=[
        {
            'price': 'price_xxx',
            'quantity': 1,
        },
        # 更多商品项
    ],
    metadata={
        'order_summary': json.dumps({
            'order_id': 'ORD-20240501-001',
            'product_ids': ['PROD-001', 'PROD-002'],
            'total_amount': 999
        })
    },
    mode='payment',
    success_url='https://your-domain.com/success',
    cancel_url='https://your-domain.com/cancel',
)

Webhook中解析metadata:

if event['type'] == 'checkout.session.completed':
    session = event['data']['object']
    order_summary = json.loads(session['metadata']['order_summary'])
    # 基于解析后的信息创建订单

注意:metadata总容量不能超过50KB,单个键值对限制20KB,仅存储必要信息即可。

额外注意事项

  • 主动调用Stripe API时,建议添加简单重试机制,避免网络波动导致请求失败;
  • Webhook处理需保证幂等性,可使用Session ID作为唯一标识,防止重复创建订单或支付记录。

内容的提问来源于stack exchange,提问作者itan mare

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 14:05:59