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

如何创建带可移除预填优惠码的Stripe订阅结账会话

解决Stripe结账页面预填优惠码后无法更换的问题

你当前的代码逻辑是通过discounts参数强制应用优惠码,但这种方式下用户无法移除优惠码;同时Stripe API不允许同时设置discounts和allow_promotion_codes: true,导致无法支持用户自定义优惠码的需求。

正确的解决思路是放弃使用discounts参数,改用URL参数预填优惠码,同时始终开启allow_promotion_codes: true,这样既可以预填优惠码,又允许用户移除并输入其他优惠码。

修改后的代码示例

const sessionParams: Stripe.Checkout.SessionCreateParams = {
  customer_email: user.email,
  mode: 'subscription',
  line_items: [
    {
      price: process.env.STRIPE_PRICE_CODE,
      quantity: 1,
    },
  ],
  metadata: {
    userId: user.userId,
  },
  success_url: `${origin}/account/download-app?session_id={CHECKOUT_SESSION_ID}`,
  cancel_url: `${origin}/account/plan-preview`,
  allow_promotion_codes: true, // 始终允许用户输入/更换优惠码
};

const session = await stripe.checkout.sessions.create(sessionParams);

// 根据业务逻辑决定是否预填优惠码
let checkoutUrl = session.url;
if (req.query.coupon !== 'special-access') {
  const prefilledPromoCode = '***'; // 替换为你的预填优惠码
  checkoutUrl = `${checkoutUrl}?promo_code=${encodeURIComponent(prefilledPromoCode)}`;
}

// 重定向用户到带预填优惠码的结账页面
res.redirect(checkoutUrl);

方案说明

  1. 开启自定义优惠码支持:通过allow_promotion_codes: true让结账页面显示优惠码输入框和移除按钮
  2. URL参数预填优惠码:Stripe Checkout支持通过promo_code URL参数预填优惠码,这种方式属于用户可修改的预填项,而非强制应用的折扣
  3. 避免API冲突:完全避开discounts参数,解决和allow_promotion_codes的兼容问题

如果需要限制预填优惠码的使用范围(比如仅特定用户可用),可以在Stripe后台给对应的促销码设置限制条件(如绑定用户ID、限制新用户等),确保优惠码的安全性。

内容的提问来源于stack exchange,提问作者Ilya Libin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:15:36