首页 > 解决方案 > 使用 Stripe 订阅 Node.js 进行身份验证

问题描述

我无法确定使用 Stripe 攻击订阅身份验证的最佳方法。我有一个预先存在的 MERN 堆栈,它使用 JWT 进行身份验证,存储订阅 ID。但是,要检测取消、发票不完整等更改,我想不出没有套接字的解决方案。

有任何想法吗?

标签: node.jsmongodbmongoosejwtstripe-payments

解决方案


查看用于接收事件通知的条带 webhook。

https://stripe.com/docs/webhooks

侦听您的 Stripe 帐户上的事件,以便您的集成可以自动触发反应。

当您的帐户发生事件时,Stripe 使用 webhook 通知您的应用程序。Webhook 对于异步事件特别有用,例如当客户的银行确认付款、客户对收费提出异议或重复付款成功时。

只需三个步骤即可开始在您的 Stripe 集成中使用 webhook:

1.在您的服务器上创建一个 webhook 端点。

2.使用 Stripe CLI 测试您的端点是否正常工作。

3.向 Stripe 注册端点以上线。

创建 webhook 的基本示例

// This example uses Express to receive webhooks
const app = require('express')();

// Use body-parser to retrieve the raw body as a buffer
const bodyParser = require('body-parser');

// Match the raw body to content type application/json
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
  let event;

  try {
    event = JSON.parse(request.body);
  } catch (err) {
    response.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Handle the event
  switch (event.type) {
    case 'payment_intent.succeeded':
      const paymentIntent = event.data.object;
      // Then define and call a method to handle the successful payment intent.
      // handlePaymentIntentSucceeded(paymentIntent);
      break;
    case 'payment_method.attached':
      const paymentMethod = event.data.object;
      // Then define and call a method to handle the successful attachment of a PaymentMethod.
      // handlePaymentMethodAttached(paymentMethod);
      break;
    // ... handle other event types
    default:
      // Unexpected event type
      return response.status(400).end();
  }

  // Return a response to acknowledge receipt of the event
  response.json({received: true});
});

app.listen(8000, () => console.log('Running on port 8000'));

推荐阅读