当我尝试验证来自WooCommerce webhooks的签名时,我遇到了一个奇怪的问题。这是我用来创建签名的部分:
verified = crypto.createHmac('SHA256', secret).update(new Buffer(JSON.stringify(body), 'utf8')).digest('base64');
它适用于每个具有removed
主题的webhook,请求正文等于:
{"id":360}
不幸的是,对于每个有updated
或created
主题的网络聊天,我的签名都不一样。请求正文也更复杂。
{"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的签名的正确方法是什么?
答案 0 :(得分:1)
我遇到了与你类似的问题,使用相同的代码(它显然适用于某些人,如此处所述:SHA256 webhook signature from WooCommerce never verifies)
最终对我有用的是使用bodyParser中间件以不同的方式获取原始身体价值:
app.use(bodyParser.json({verify:function(req,res,buf){req.rawBody=buf}}))
(如:https://github.com/expressjs/body-parser/issues/83#issuecomment-80784100)
所以现在而不是使用
new Buffer(JSON.stringify(body), 'utf8')
我只使用req.rawBody
我希望这也能解决你的问题。