Node.js 如何从环回自定义方法中检索原始正文缓冲区,以验证webhook帖子中的条带签名?

Node.js 如何从环回自定义方法中检索原始正文缓冲区,以验证webhook帖子中的条带签名?,node.js,express,loopback,Node.js,Express,Loopback,以下是指南: 我在环回自定义方法中尝试了以下代码: "use strict"; module.exports = function(Webhook) { Webhook.stripe = function(req, data, cb) { const stripe = require("stripe")("sk_test_xxxxxxxxxxxxx"); const endpointSecret = "whsec_xxxxxxxxxxxxxxxxxxxxxxxxx";

以下是指南:

我在环回自定义方法中尝试了以下代码:

    "use strict";
module.exports = function(Webhook) {
  Webhook.stripe = function(req, data, cb) {
    const stripe = require("stripe")("sk_test_xxxxxxxxxxxxx");
    const endpointSecret = "whsec_xxxxxxxxxxxxxxxxxxxxxxxxx";

    const sig = req.headers["stripe-signature"];

    let event;

    try {
      event = stripe.webhooks.constructEvent(data, sig, endpointSecret);
      Webhook.create({
        data: data
      }); 
      console.log("Success");
      cb(null, "OK");
    } catch (err) {
      console.log(err);
      Webhook.create({
        data: err 
      }); 
      cb(err);
    }   
  };  

  Webhook.remoteMethod("stripe", {
    accepts: [
      { arg: "req", type: "object", http: { source: "req" } },
      { arg: "data", type: "object", http: { source: "body" } } 

    ],  
    returns: [{ arg: "response", type: "any", root: true }]
  }); 
};

但是当在
stripe.webhooks.constructEvent
中验证签名时,传入主体的数据对象将不起作用,因为它不需要对象,而是需要未编辑的原始主体。(JSON.Stringify()也不起作用,因为这会改变正文,验证失败)我如何才能从环回中获取未经编辑的原始正文,并将其传递到条带库中进行签名验证?

感谢来自的Felipe Figueroa给出了这个答案

主体解析器将根据内容类型根据主体解析器类型(在本例中为json或raw)解析传入请求。不能将原始和json解析器都设置为按顺序应用

为了解决这个问题,我们可以从中间件中删除bodyParser.json,并在server.js中手动配置它

因为我们需要原始主体,但也需要转换后的JSON,所以在JSON解析器激活之前,我们可以向请求对象添加一个附加属性,如下所示:

在middleware.json中:

"parse": {
    "body-parser#json": {"params": {"limit": "10mb", "strict": false}}, // remove this line
    "body-parser#urlencoded": {
      "params": {
        "extended": true,
        "limit": "5mb"
      }
    }
在server.js中:

function rawBodySaver(req, res, buf, encoding) {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8'); // additional property set on req object
  }
}

const bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '10mb', strict: false, verify: rawBodySaver}));
在上面的代码中,我们将使用:

event = stripe.webhooks.constructEvent(req["rawBody"], sig, endpointSecret);

然后验证签名是否正确。

您是否尝试过
源代码:“有效负载”
?尝试过,没有运气