如何使用Stripe Webhooks更新用户订阅日期?

8
我正在使用node.js构建订阅计划,我已经阅读了有关如何将用户订阅到计划的文档,并且它是成功的。Stripe的文档指出,我必须在数据库中存储一个“active_until”字段。它说当有变化时使用webhook,我知道webhook就像是一个事件。
真正的问题是:
1)如何使用active_until每个月重复账单? 2)我应该如何使用webhook,我真的不明白。
以下是迄今为止的代码: var User = new mongoose.Schema({ email: String, stripe: { customerId: String, plan: String }
});

//payment route
router.post('/billing/:plan_name', function(req, res, next) {
  var plan = req.params.plan_name;
  var stripeToken = req.body.stripeToken;
  console.log(stripeToken);

  if (!stripeToken) {
    req.flash('errors', { msg: 'Please provide a valid card.' });
    return res.redirect('/awesome');
  }

  User.findById({ _id: req.user._id}, function(err, user) {
    if (err) return next(err);

    stripe.customers.create({
      source: stripeToken, // obtained with Stripe.js
      plan: plan,
      email: user.email
    }).then(function(customer) {
      user.stripe.plan = customer.plan;
      user.stripe.customerId = customer.id;
      console.log(customer);
      user.save(function(err) {
        console.log("Success");
        if (err) return next(err);
        return next(null);
      });
    }).catch(function(err) {
      // Deal with an error
    });

    return res.redirect('/');

  });
});

我该如何实现active_until时间戳和webhook事件?

2个回答

3

active_until是一个数据库列的名称,您可以在用户表上创建该列以存储代表用户帐户过期时间戳的值。列的名称并不重要。您可以使用任何名称。

为了验证用户的订阅是否有效,Stripe建议您使用以下逻辑:

If today's date <= user.active_until
  allow them access

Else
  show them an account expired message

Webhook是Stripe服务器向您的服务器发出的请求,告诉您发生了某些事情。在这种情况下,您最感兴趣的事件是invoice.payment_succeeded

您的Webhook将包括以下逻辑:

if event type is "invoice.payment_succeeded"
  then update user.active_until to be equal to today's date + 1 month

如果支付失败等情况发生,您还需要响应其他事件。


2
您不需要每个月重复发账单,Stripe会为您完成。一旦您将用户订阅到计划中,Stripe将在付款周期结束之前向其收费。
每次Stripe向客户收费时,它都会生成一个Webhook,即对您的服务器发送到某个指定URL的请求。 Stripe可以为不同的原因生成不同的Webhook。
例如,当客户通过订阅被收费时,Stripe会向您发送有关付款的信息。
router.post('/billing/catch_paid_invoice', function(req, res) {
    // Here you parse JSON data from Stripe
}):

我现在没有访问Stripe设置的权限,但是我记得手动设置Webhooks的URL地址。 选择您的账户名称 > 账户设置 > Webhooks

active_until只是一个提醒,客户仍然活跃并且在您的系统中支付了服务费用。在获取Webhooks时需要更新它。 Stripe文档非常好,所以请再次仔细阅读。 https://stripe.com/docs/guides/subscriptions


1
谢谢您的详细解释,我已经在Stripe网站上添加了所有事件,但是我真的很困惑,我需要为Web钩子使用router.post吗? - Jack Moscovi
能否为我提供一个如何添加active_until的示例代码呢?它需要使用时间戳或布尔值吗? - Jack Moscovi
还有一件事,我该如何测试 Webhooks? - Jack Moscovi
是的,您需要捕获来自Stripe的POST请求。为Webhook中指定的URL设置router.post。然后转储它获取到的所有内容,以查看如何处理它。如果我没记错的话,Stripe在某个地方有一个按钮,允许您发送任何Webhook。 - Anton F
Active until与Stripe无关,Stripe将收取已订阅客户的费用。当创建新的订阅时,您可以设置活动时间,以了解某些订阅的有效期。您可以自行确定格式。 - Anton F
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接