如何使用HMACSHA256 Node js验证Xero webhook负载



我需要在node-js项目中验证Xero-webhook。这是Xero文档验证步骤:https://developer.xero.com/documentation/webhooks/creating-webhooks#STATUS

var crypto = require("crypto")
function getHmacSha256(message, secret) {
return crypto.createHmac("sha256", secret).update(message).digest("base64")
}
// webhookPayload and signature get from webhook body and header
const webhookPayload = {
events: [],
firstEventSequence: 0,
lastEventSequence: 0,
entropy: 'OSHPXTUSXASRFBBCJFEN'
}
const signature = "OXLaeyZanKI5QDnLkXIVB35XrZygYsPMeK8WfoXUMU8="

const myKey = "1y5VYfv7WbimUQIMXiQCB6W6TKIp+5ZZJNjn3Fsa/veK5X/C8BZ4yzvPkmr7LvuL+yfKwm4imnfAB5tEoJfc4A=="
var hash = getHmacSha256(JSON.stringify(webhookPayload), myKey)
//If the payload is hashed using HMACSHA256 with your webhook signing key and base64 encoded, it should match the signature in the header.
if (signature === hash) {
return res.status(200).end()
}else{
return res.status(401).end() 
}

每次我的签名和哈希都不一样,所以每次都返回401。因此我未能完成接收的意图

根据您的描述,我猜您无意中修改了请求体。您需要接受来自webhook事件的原始请求正文而不进行修改。如果这个主体被修改,您的代码将无法验证签名,并且将无法通过Xero的"接收意向"验证。查看此博客文章了解详细信息。

最新更新