gpt4 book ai didi

node.js - Nodejs - Expressjs - 验证 shopify webhook

转载 作者:搜寻专家 更新时间:2023-11-01 00:22:51 25 4
gpt4 key购买 nike

我正在尝试在开发环境中验证从 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);
});

最佳答案

我做的有点不同 -- 不确定我在哪里看到的建议,但我在正文解析器中进行了验证。 IIRC 的一个原因是我在任何其他处理程序可能接触它之前就可以访问它:

app.use( bodyParser.json({verify: function(req, res, buf, encoding) {
var shopHMAC = req.get('x-shopify-hmac-sha256');
if(!shopHMAC) return;
if(req.get('x-kotn-webhook-verified')) throw "Unexpected webhook verified header";
var sharedSecret = process.env.API_SECRET;
var digest = crypto.createHmac('SHA256', sharedSecret).update(buf).digest('base64');
if(digest == req.get('x-shopify-hmac-sha256')){
req.headers['x-kotn-webhook-verified']= '200';
}
}}));

然后任何网络 Hook 只处理经过验证的 header :

if('200' != req.get('x-kotn-webhook-verified')){
console.log('invalid signature for uninstall');
res.status(204).send();
return;
}
var shop = req.get('x-shopify-shop-domain');
if(!shop){
console.log('missing shop header for uninstall');
res.status(400).send('missing shop');
return;
}

关于node.js - Nodejs - Expressjs - 验证 shopify webhook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36745204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com