WooCommerce Webhooks Auth (secret & signature) - how to use
The signature needs to be checked against the body and not the JSON it contains. i.e. the raw bytes of the req.body.
Modify the bodyParser
first:
const rawBodySaver = (req, res, buf, encoding) => {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8');
}
};
app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: '*/*' }));
and then, using crypto (it is distributed with node you don't need to npm install
anything.)
import crypto from 'crypto'; //Let's try with built-in crypto lib instead of cryptoJS
router.post('/', function (req, res) {
const secret = 'ciPV6gjCbu&efdgbhfgj&¤"#&¤GDA';
const signature = req.header("X-WC-Webhook-Signature");
const hash = crypto.createHmac('SHA256', secret).update(req.rawBody).digest('base64');
if(hash === signature){
res.send('match');
} else {
res.send("no match");
}
});