Nodejs – Expressjs – validationwebify的shopify

我正在尝试validation在开发环境中从shopify webhook发送的hmac代码。 然而shopify不会发送一个webhook发送到一个非活的端点的请求,所以我使用requestbin捕获请求,然后使用postman发送到我的本地networking服务器。

从shopify 文档 ,我似乎做的一切正常,也尝试应用在node-shopify-auth verifyWebhookHMAC函数中使用的方法。 但迄今为止这一切都没有奏效。 代码从来不匹配。 我在这里做错了什么?

我的代码来validationwebhook:

  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); }); 

我做了一点不同 – 不知道我在哪里看到build议,但我在身体分析器中进行validation。 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'; } }})); 

然后任何Web钩子只处理validation的头文件:

 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; }