提问者:小点点

验证来自WooCommerce webhooks的签名的正确方法


当我试图验证来自WooCommerce webhooks的签名时,我遇到了一个奇怪的问题。以下是我用来创建签名的部分:

verified = crypto.createHmac('SHA256', secret).update(new Buffer(JSON.stringify(body), 'utf8')).digest('base64');

它适用于每个带有删除主题的网络钩子,请求正文等于这样的内容:

{"id":360}

不幸的是,对于每个具有更新创建主题的网络钩子,我的签名都不一样。请求正文也更复杂。

 {"product":{"title":"Test","id":392,"created_at":"2017-02-11T21:40:37Z","updated_at":"2017-02-11T21:40:37Z","type":"simple","status":"publish","downloadable":false,"virtual":false,"permalink":"http://cedrus.ma/chezalfred/livraison/non classu00e9/test/","sku":"","price":"","regular_price":"","sale_price":null,"price_html":"","taxable":true,"tax_status":"taxable","tax_class":"","managing_stock":false,"stock_quantity":null,"in_stock":true,"backorders_allowed":false,"backordered":false,"sold_individually":false,"purchaseable":false,"featured":false,"visible":true,"catalog_visibility":"visible","on_sale":false,"product_url":"","button_text":"","weight":null,"dimensions":{"length":"","width":"","height":"","unit":"cm"},"shipping_required":true,"shipping_taxable":true,"shipping_class":"","shipping_class_id":null,"description":"","short_description":"","reviews_allowed":true,"average_rating":"0.00","rating_count":0,"related_ids":[],"upsell_ids":[],"cross_sell_ids":[],"parent_id":0,"categories":[],"tags":[],"images":[{"id":0,"created_at":"2017-02-11T21:40:40Z","updated_at":"2017-02-11T21:40:40Z","src":"http://cedrus.ma/chezalfred/wp-content/plugins/woocommerce/assets/images/placeholder.png","title":"Etiquette","alt":"Etiquette","position":0}],"featured_src":"","attributes":[],"downloads":[],"download_limit":0,"download_expiry":0,"download_type":"","purchase_note":"","total_sales":0,"variations":[],"parent":[],"grouped_products":[],"menu_order":0}}

我认为JSON出现了一些问题。当请求正文更复杂时,使用stringify()。

验证来自WooCommerce webhooks的签名的正确方法是什么?


共1个答案

匿名用户

我遇到了一个与您类似的问题,使用了相同的代码(它显然适用于某些人,正如这里提到的:WooCommerce的SHA256 webhook签名从不验证)

最终对我起作用的是使用bodyParser中间件以不同的方式获取原始的body值:
app。使用(bodyParser.json({verify:function(req,res,buf){req.rawBody=buf}}}))
(如中所述:https://github.com/expressjs/body-parser/issues/83#issuecomment-80784100)

因此,现在我不使用新的缓冲区(JSON.stringify(body),'utf8')而是使用req。我希望这也能解决你的问题。