Stripe Webhook:未找到与有效负载的预期签名匹配的签名

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

我正在尝试将条带支付方法集成到我正在开发的项目中,但是当我尝试添加签名检查和“最佳实践”时,我收到一些错误,同时确保签名正确且与端点秘密兼容并且正文原始格式正确,这是代码:

export const sessionUpdate = async (req, res) => {
  
    const sig = req.headers['stripe-signature'];
    const stripeInstance = Stripe(process.env.STRIPE_SECRET_KEY);
  let event;
  const rawBody = JSON.stringify(req.body);
  // console.log("this is the raw body==>",rawBody); i used these to check the paramters that 
  // console.log("this is the signature", sig); am gonna add to the construct event
 //   console.log(process.env.ENDPOINT_SECRET);
  try {
    event = stripeInstance.webhooks.constructEvent(rawBody, sig, process.env.ENDPOINT_SECRET);
  } catch (err) {
    console.error('Webhook Error:', err.message);
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  if (!event || !event.type) {
    console.error('Invalid event data:', event);
    return res.status(400).json({ error: 'Invalid event data' });
  }

  console.log('Received event:', event.type);
    switch (event.type) {
      case 'checkout.session.completed':
        try {
          const completedEvent = event.data.object;
  
          const { metadata } = completedEvent;
  
          const { post_id } = metadata;
  
          const updatedPost = await Post.findByIdAndUpdate(
            post_id,
            { paymentStatus: true },
            { new: true }
          );
  
          if (!updatedPost) {
            return res.status(404).json({ error: 'Post not found' });
          }
  
          return res.json({ message: 'Post status updated successfully', updatedPost });
        } catch (error) {
          console.error('Error updating post status:', error);
          return res.status(500).json({ error: 'Internal server error' });
        }
  
      default:
        console.log(`Unhandled event type ${event.type}`);
        return res.status(200).end();
    }
  };

但是我遇到了这个错误: “Webhook 错误:未找到与有效负载的预期签名匹配的签名。您是否正在传递从 Stripe 收到的原始请求正文?

这是路线

router.post(
    "/sessionUpdate",
    express.raw({ type: "application/json" }),
    sessionUpdate
  );

了解有关 Webhook 签名的更多信息并探索各种框架的 Webhook 集成示例,请访问 https://github.com/stripe/stripe-node#webhook-signing” 我还确保端点秘密是正确的。

我正在我的电脑上进行本地测试,我使用 ngrok 来检查它和 stripe cli,但仍然遇到同样的问题,我收到 POST /api/user/sessionUpdate 400 Bad Request 。我希望你能帮助我,我真的很难让它发挥作用。

我尝试使用 stripe cli 和 ngrok 测试付款,但是它们都给了我相同的结果,并且我在不使用 event= stripeInstance.webhooks.constructEvent 的情况下尝试了它,它工作得很好,但是当我阅读 stripe 的文档时,我尝试了它发现实现签名很重要

node.js express stripe-payments checkout ngrok
1个回答
0
投票

由于已在路由中设置了

express.raw({ type: "application/json" })
,因此不需要对请求正文进行字符串化。
req.body
可以直接设置为
stripeInstance.webhooks.constructEvent
。您可以参考这里的示例代码:https://stripe.com/docs/webhooks/quickstart

© www.soinside.com 2019 - 2024. All rights reserved.