如何在 Stripe 中指定订阅时长

How to specify the duration of subscription in Stripe

我正在实施条带订阅,但在 api 文档中找不到如何在创建结帐会话时指定订阅持续时间的任何地方。这是我目前所拥有的:

    const customer = await stripe.customers.create({
      description: "My First Test Customer (created for API docs)",
      email: "some.email@gmail.com",
      address: {
        city: 'Toronto',
        country: 'CA',
        line1: "Some Address",
        line2: "Some unit number",
        postal_code: "M5G0V1",
        state: "ON",
      },
      name: "Some Name",
      phone: "Some Number",
    }); 
    const price = await stripe.prices.create({
      unit_amount: 599,
      currency: 'cad',
      recurring: {interval: 'month', interval_count: '1'},
      product: 'prod_KZfHFK4nfCqlGS',
    });
    const subscriptionSchedule = await stripe.subscriptionSchedules.create({
      customer: customer.id,
      start_date: 'now',
      end_behavior: 'cancel',
      phases: [
        {
          items: [
            {
              price: price.id,
              quantity: 1,
            },
          ],
          iterations: 24,
        },
      ],
    });
    console.log(subscriptionSchedule);
    const session = await stripe.checkout.sessions.create({
      success_url: 'http://localhost:8080/stripeSessionSuccessHook',
      cancel_url: 'http://localhost:8080/stripeSessionCancelHook',
      payment_method_types: ['card'],
      customer: customer.id,
      line_items: [
        {price: price.id, quantity: 1},
      ],
      mode: 'subscription',
    });

我正在尝试创建客户每月支付 24 个月的订阅。我正在使用答案中建议的订阅时间表,实际上正在创建 24 个月的订阅。但是,在创建新的结帐时,如果付款成功,它将创建一个跨越 12 个月的订阅...最后,我有 2 个订阅。一个由 Subscription Schedule 创建(24 个月,需要一个),和其他 Subscription(12 个月)。有没有什么办法可以将此订阅计划传递给结账,这样就不会创建 2 个订阅。

如果付费,订阅通常会在每个计费周期后自动续订。 recurring.interval在Price中设置,最大循环间隔为一年。

如果您想在 2 年后结束订阅,您可以使用订阅时间表:https://stripe.com/docs/billing/subscriptions/subscription-schedules

对于您的用例,如果价格为 recurring.interval=year,您将创建一个订阅计划,其中包含一个具有 iterations=2end_behavior=cancel 的阶段。

你可以参考这个例子:https://stripe.com/docs/billing/subscriptions/subscription-schedules/use-cases#installment-plans

请注意,订阅计划当前不适用于 Checkout 或客户门户。如果您想使用 Checkout,解决方法是:

  1. 客户通过结帐支付订阅费用
  2. 为现有(且已付费)订阅创建订阅计划:https://stripe.com/docs/billing/subscriptions/subscription-schedules/use-cases#existing-subscription
  3. 更新新创建的订阅计划参数以在 2 年后结束订阅:https://stripe.com/docs/api/subscription_schedules/update

您不应依赖成功重定向来在客户端上执行任何重要操作。在客户端上,客户可以在重定向发生之前关闭浏览器 window 或退出应用程序。您可能希望设置一个 webhook 来侦听 checkout.session.completed 事件并在收到此事件后创建订阅计划。

您可以在此处阅读有关设置 webhook 的更多信息: