javascript Stripe - Webhook有效负载必须以字符串或缓冲区的形式提供

eoxn13cs  于 2023-05-21  发布在  Java
关注(0)|答案(2)|浏览(127)

我正在尝试用stripe编写一个订阅系统。我下面的代码主要是从stripe文档复制的,但它总是显示这个错误:

Webhook signature verification failed. Webhook payload must b
e provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
Signature verification is impossible without access to the original signed material.
Learn more about webhook signing and explore webhook integration 
examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing

这是我用JavaScript写的代码:

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

    const endpointSecret = 'whsec_.....';

    if (endpointSecret) {

      const signature = request.headers['stripe-signature'];
      try {
        event = stripe.webhooks.constructEvent(
          request.body,
          signature,
          endpointSecret
        );
      } catch (err) {
        console.log(`⚠️  Webhook signature verification failed.`, err.message);
        return response.sendStatus(400);
      }
    }
    let subscription;
    let status;

    switch (event.type) {
      case 'customer.subscription.created':
        subscription = event.data.object;
        status = subscription.status;
        console.log(`Subscription status is ${status}.`);

        break;
      default:
        console.log(`Unhandled event type ${event.type}.`);
    }
    response.send();
  }
);

有人知道我做错了什么吗?我已经在网上搜索了一个小时了,什么也找不到。先谢谢你了!

whlutmcx

whlutmcx1#

这是因为app.use(express.json());代码。尝试将webhook路由移动到app.use(express.json());之前。

// webhook route
app.post(
  '/webhook',
  express.raw({ type: 'application/json' }),
  (request, response) => {
    let event = request.body;

    const endpointSecret = 'whsec_.....';

    if (endpointSecret) {

      const signature = request.headers['stripe-signature'];
      try {
        event = stripe.webhooks.constructEvent(
          request.body,
          signature,
          endpointSecret
        );
      } catch (err) {
        console.log(`⚠️  Webhook signature verification failed.`, err.message);
        return response.sendStatus(400);
      }
    }
    let subscription;
    let status;

    switch (event.type) {
      case 'customer.subscription.created':
        subscription = event.data.object;
        status = subscription.status;
        console.log(`Subscription status is ${status}.`);

        break;
      default:
        console.log(`Unhandled event type ${event.type}.`);
    }
    response.send();
  }
);

app.use(express.json());
gdrx4gfi

gdrx4gfi2#

看起来你的应用程序中的某些东西正在将传入的请求解析为与函数预期的格式不同的格式(即您是否在应用中全局配置了中间件或解析器?如果是这样的话,您可能希望禁用它,或者只是添加一个异常,使其不接触到要发送到/webhook路由的传入请求主体。

相关问题