我对全栈开发是个新手。我第一次使用webhook时遇到了问题,特别是在条带结账会话中。据我所知,stripe需要请求的原始正文来正确解码签名。我的后端使用了一些中间件,我认为这些中间件妨碍了原始正文解析器的工作。我知道我需要应用if/else的形式,以允许我的后端决定使用哪个中间件,但我不确定如何正确地做到这一点。下面是我的代码:
// only use the raw bodyParser for webhooks
app.use((req, res, next) => {
if (req.originalUrl === '/webhook') {
next();
} else {
cors();
express.json({limit: '50mb'})
express.urlencoded({limit: '50mb', extended: true})
}
});
//app.use(cors());
//app.use(express.json({limit: '50mb'}));
//app.use(express.urlencoded({limit: '50mb', extended: true}));
被注释掉的app.use语句是我的中间件,在我试图让我的webhook正常工作之前,它们是正常工作的。这段代码不能工作,我只是尝试正确地应用中间件。以下是我的webhook的post路径,它只是来自stripe的文档的复制版本,一旦我成功接收到webhook,我将对其进行编辑:
// Stripe requires the raw body to construct the event
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
} catch (err) {
// On error, log and return the error message
console.log(`❌ Error message: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Successfully constructed event
console.log('✅ Success:', event.id);
// Return a response to acknowledge receipt of the event
res.json({received: true});
});
错误消息:找不到与负载的预期签名匹配的签名。您是否正在传递从条纹收到的原始请求正文?https://github.com/stripe/stripe-node#webhook-signing
发布于 2020-07-28 17:24:56
看起来在浪费了几个小时之后,我解决了我自己的问题,就在我决定把它贴在这里的几分钟后!而是course....lol
我的解决方案:
// only use the raw bodyParser for webhooks
app.use((req, res, next) => {
if (req.originalUrl === '/webhook') {
next();
} else {
express.json({limit: '50mb'})(req, res, next);
}
});
app.use(cors());
//app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb', extended: true}));
https://stackoverflow.com/questions/63139268
复制相似问题