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

Django+Stripe项目:验证客户是否已兑换指定促销码

验证客户是否已兑换特定Stripe促销码的方法

针对你的Django项目需求,以下是几种Stripe原生的验证方法,无需依赖第三方工具:

方法1:查询客户的支付记录(适用于单次支付场景)

客户兑换促销码后,对应的Charge会关联该促销码的优惠券ID。你可以通过查询该客户的Charge列表,过滤出使用目标优惠券的记录:

import stripe

# 初始化Stripe客户端(建议在Django配置文件中统一管理API密钥)
stripe.api_key = "your_stripe_secret_key"

def customer_redeemed_promo(customer_id, coupon_id):
    # 查询客户是否存在使用指定优惠券的支付记录
    charges = stripe.Charge.list(
        customer=customer_id,
        coupon=coupon_id,
        limit=1  # 只需检查是否存在至少一条记录
    )
    return len(charges.data) > 0

使用时传入目标客户ID和促销码对应的优惠券ID(即你提供的返回数据中coupon.id字段,此处为test10),返回True则说明客户已兑换该促销码。

方法2:检查客户的折扣关联(适用于订阅场景)

如果促销码用于订阅折扣,客户兑换后会在其discount字段中关联对应的优惠券。直接检索客户信息即可验证:

def customer_has_promo_discount(customer_id, coupon_id):
    customer = stripe.Customer.retrieve(customer_id)
    # 验证客户当前是否绑定了目标优惠券的折扣
    return customer.discount is not None and customer.discount.coupon.id == coupon_id

方法3:利用Stripe内置验证(推荐,覆盖所有场景)

最可靠的方式是主动尝试将促销码应用到客户或支付Intent,通过捕获Stripe的错误判断是否已兑换。这种方法还能自动验证促销码的其他限制(比如你提供的first_time_transaction限制):

def can_redeem_promo_code(customer_id, promo_code_id):
    try:
        # 创建临时PaymentIntent用于验证,不实际扣款
        stripe.PaymentIntent.create(
            amount=100,  # 最小测试金额(单位为币种最小单位,如USD的分)
            currency="usd",
            customer=customer_id,
            promotion_code=promo_code_id,
            capture_method="manual"  # 避免实际扣款
        )
        return True
    except stripe.error.InvalidRequestError as e:
        # 捕获"促销码已被该客户兑换"的错误
        if "promotion_code_already_redeemed" in str(e):
            return False
        # 其他错误(如促销码过期、无效等)可按需处理
        raise

关键说明

  • 你提供的促销码数据中restrictions.first_time_transaction: true表示仅首次交易可兑换,方法3会自动验证该条件,无需额外编写逻辑。
  • 所有方法均基于Stripe官方Python SDK,与你的Django项目完全兼容。

内容的提问来源于stack exchange,提问作者Tarang Patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:25:53