编辑:
comment by CBroe 是解决方案。确保来自 Facebook 的负载在生成哈希之前未被解析。
我正在尝试使用 the steps in the Facebook developer docs 从 Instagram Graph API 验证 Webhook 负载的内容。
尽管遵循了文档中的所有步骤,但我似乎无法生成匹配的哈希值。需要说明的是,我的代码成功创建了一个哈希值,只是与 Facebook 使用 webhook 发送的哈希值不匹配。
我的代码如下(应用 secret 和负载内容使用虚拟值)。任何帮助将不胜感激。
const crypto = require('crypto')
// Escape special characters
const escapeUnicode = str => {
return str.replace(/[\u00A0-\uffff]/gu, function (c) {
return "\\u" + ("000" + c.charCodeAt().toString(16)).slice(-4)
})
}
// Dummy values
const payload = {
"object": "instagram",
"entry": [
{
"id": "some-id",
"time": 1234567890,
"changes": [
{
"value": {
"media_id": "some-id",
"impressions": 0,
"reach": 0,
"taps_forward": 0,
"taps_back": 0,
"exits": 0,
"replies": 0
},
"field": "story_insights"
}
]
}
]
}
// Create hash
const hmac = crypto.createHmac('sha1', 'my-app-secret')
hmac.update(escapeUnicode(JSON.stringify(payload)))
const hash = `sha1=${hmac.digest('hex')}`
最佳答案
我也遇到了同样的问题。对于 future 的读者,如果您使用 ExpresJS
和 bodyparser
( Found here )
app.use(bodyParser.json({
verify: (req, res, buf) => {
req.rawBody = buf
}
}));
然后为了计算有效载荷的校验和,只需将 req.rawBody
作为有效载荷传递,
const crypto = require('crypto');
const calculatedChecksum = crypto.createHmac('sha1', APP_SECRET)
.update(req.rawBody)
.digest('hex');
关于node.js - 从 Facebook webhook 验证负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60875202/