如果没有 webhook,我如何知道 Stripe 试用订阅是否已结束?

问题描述 投票:0回答:2

我正在创建 Stripe 客户和 7 天试用期的订阅:


    const stripeCustomer = await stripe.customers.create({
        email: req.body.email
    });

    await stripe.subscriptions.create({
        customer: stripeCustomer.id,
        items: [{
            price: process.env['STRIPE_PRICE_ID']
        }],
        trial_period_days: 7
    })

当我检查状态时,它显示为

trialing
。试用结束后,如果我检索订阅,它会显示
active
状态。但这是不准确的,因为客户尚未支付订阅费用。

我想要的是一个状态,告诉我试用已结束,但客户尚未付款,以便我可以在客户登录时引导他们访问 Stripe 门户。我知道有一个我可以监听的 Webhook,但我不想在审判结束的那一刻担心它。相反,我想在客户下次登录时处理它。

stripe-payments
2个回答
1
投票

您希望以

payment_behavior
'default_incomplete'
开始订阅:https://stripe.com/docs/api/subscriptions/create#create_subscription- payment_behavior

这样,试用结束后订阅状态将为

incomplete
,只有在支付第一张发票后才会转换为
active


0
投票

如果有人遇到这个问题: 您可能想要做的是设置

trial_settings
属性,例如

  const subscription = await stripe.subscriptions.create({
    customer: customerId,
    items: [
      {
        price: priceId,
      },
    ],
    payment_settings: { save_default_payment_method: 'on_subscription' },
    payment_behavior: 'default_incomplete',
    expand: ['latest_invoice.payment_intent', 'pending_setup_intent'],
    trial_period_days: trialPeriodDays,
    // NOTE: These trial_settings are extremly important. If a user visits the payment page, but NEVER completes the flow, we would have a invoice at the next month
    // which would be marked as past due, as there would be no payment method attached to this subscription.
    trial_settings: {
      end_behavior: {
        missing_payment_method: 'cancel',
      },
    },
  });

试用期结束后,这将自动“删除”订阅。 此外,您可能只想检查应用程序中的活动状态,因此用户最终不会在您的应用程序中获得有效的订阅(实际上处于试用模式)。如果您确实想依赖试用模式,例如用户在试用模式下订阅,但只有当他附加了有效的付款方式时,您才可以检查

default_payment_method
字段(假设您也将用户的付款方式附加到订阅本身)。

例如,您的函数可能如下所示:

  const subscription = await getSubscriptionByCustomer({
    customerId: customer.id,
    statuses: ['active', 'trialing', 'canceled'],
  });
  if (subscription === undefined) {
    return null;
  }

  if (subscription.default_payment_method === null) {
    return null;
  }
© www.soinside.com 2019 - 2024. All rights reserved.