Reputation: 7996
I am running into a strange issue when I try to verify the signature coming from the WooCommerce webhooks. Here is the part I use to create the signature:
verified = crypto.createHmac('SHA256', secret).update(new Buffer(JSON.stringify(body), 'utf8')).digest('base64');
It works for every webhook with a removed
topic, and the request body is equal to something like this:
{"id":360}
Unfortunately, for every webhook with an updated
or created
topic, my signatures aren't the same. The request body is also more complex.
{"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}}
I think there is something wrong that happens with JSON.stringify() when the request body is more complex.
What is the proper way to verify the signature coming from WooCommerce webhooks?
Upvotes: 1
Views: 1676
Reputation: 194
I have run into a similar issue as you, using the same code (It apparently works for some people, as mentioned here: SHA256 webhook signature from WooCommerce never verifies)
What finally worked for me was getting the raw body value in a different way, using the bodyParser middleware:
app.use(bodyParser.json({verify:function(req,res,buf){req.rawBody=buf}}))
(As explained in: https://github.com/expressjs/body-parser/issues/83#issuecomment-80784100)
So now instead of using
new Buffer(JSON.stringify(body), 'utf8')
I just use req.rawBody
I hope this solves your problems too.
Upvotes: 1