我有一个调用Firebase功能的条纹webhook。在此函数中,我需要验证此请求是否来自Stripe服务器。这是代码:
const functions = require('firebase-functions');
const bodyParser = require('body-parser');
const stripe = require("stripe")("sk_test_****");
const endpointSecret = 'whsec_****';
const app = require('express')();
app.use(bodyParser.json({
verify: function (req, res, buf) {
var url = req.originalUrl;
if (url.startsWith('/webhook')) {
req.rawBody = buf.toString()
}
}
}));
app.post('/webhook/example', (req, res) => {
let sig = req.headers["stripe-signature"];
try {
console.log(req.bodyRaw)
let event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
console.log(event);
res.status(200).end()
// Do something with event
}
catch (err) {
console.log(err);
res.status(400).end()
}
});
exports.app = functions.https.onRequest(app);
如Stripe Documentation所述,我必须使用原始身体来执行此安全检查。
我已尝试使用我当前的代码并使用:
app.use(require('body-parser').raw({type: '*/*'}));
但我总是得到这个错误:
Error: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing
云功能自动parses body content of known types。如果您正在获取JSON,那么它已经在req.body
中解析并可供您使用。您不应该添加其他正文解析中间件。
如果你需要处理原始数据,你应该使用req.rawBody
,但我认为你不需要在这里做。
这是为我工作的代码:
app.use(bodyParser.json({
verify: function (req, res, buf) {
var url = req.originalUrl;
if (url.startsWith('/stripe'))
req.rawBody = buf.toString();
}
}));
然后传递req.rawBody进行验证
stripe.checkWebHook(req.rawBody, signature);
参考:qazxsw poi