【发布时间】:2016-04-20 13:22:11
【问题描述】:
我正在尝试在开发环境中验证从 shopify webhook 发送的 hmac 代码。但是shopify 不会将webhook 的发布请求发送到非实时端点,因此我使用requestbin 捕获请求,然后使用postman 将其发送到我的本地网络服务器。
来自shopify documentation,我似乎做的一切都是正确的,并且也尝试过应用node-shopify-auth verifyWebhookHMAC function 中使用的方法。但到目前为止,这些都没有奏效。 代码永远不会匹配。 我在这里做错了什么?
我的验证 webhook 的代码:
function verifyWebHook(req, res, next) {
var message = JSON.stringify(req.body);
//Shopify seems to be escaping forward slashes when the build the HMAC
// so we need to do the same otherwise it will fail validation
// Shopify also seems to replace '&' with \u0026 ...
//message = message.replace('/', '\\/');
message = message.split('/').join('\\/');
message = message.split('&').join('\\u0026');
var signature = crypto.createHmac('sha256', shopifyConfig.secret).update(message).digest('base64');
var reqHeaderHmac = req.headers['x-shopify-hmac-sha256'];
var truthCondition = signature === reqHeaderHmac;
winston.info('sha256 signature: ' + signature);
winston.info('x-shopify-hmac-sha256 from header: ' + reqHeaderHmac);
winston.info(req.body);
if (truthCondition) {
winston.info('webhook verified');
req.body = JSON.parse(req.body.toString());
res.sendStatus(200);
res.end();
next();
} else {
winston.info('Failed to verify web-hook');
res.writeHead(401);
res.end('Unverified webhook');
}
}
我收到请求的路由:
router.post('/update-product', useBodyParserJson, verifyWebHook, function (req, res) {
var shopName = req.headers['x-shopify-shop-domain'].slice(0, -14);
var itemId = req.headers['x-shopify-product-id'];
winston.info('Shopname from webhook is: ' + shopName + ' For item: ' + itemId);
});
【问题讨论】:
标签: node.js shopify hmac webhooks