Skip to content

Instantly share code, notes, and snippets.

@joshbeckman
Created October 10, 2015 17:37
Show Gist options
  • Save joshbeckman/5c4f0244914adfd312e4 to your computer and use it in GitHub Desktop.
Save joshbeckman/5c4f0244914adfd312e4 to your computer and use it in GitHub Desktop.
An example Node.js server that can verify a Shopify webhook's integrity. Run with `node index.js`.
const PORT = 3000;
const SECRET = 'APP_SHARED_SECRET';
var http = require('http'),
crypto = require('crypto'),
server;
function verifyShopifyHook(req) {
var digest = crypto.createHmac('SHA256', SECRET)
.update(new Buffer(req.body, 'utf8'))
.digest('base64');
return digest === req.headers['X-Shopify-Hmac-Sha256'];
}
function parseRequestBody(req, res) {
req.body = '';
req.on('data', function(chunk) {
req.body += chunk.toString('utf8');
});
req.on('end', function() {
handleRequest(req, res);
});
}
function handleRequest(req, res) {
if (verifyShopifyHook(req)) {
res.writeHead(200);
res.end('Verified webhook');
} else {
res.writeHead(401);
res.end('Unverified webhook');
}
}
server = http.createServer(parseRequestBody);
server.listen(PORT, function(){
console.log("Server listening on: http://localhost:%s", PORT);
});
@TopoR1
Copy link

TopoR1 commented Jul 16, 2019

@Kushan- Thanks you!

@wrsalex
Copy link

wrsalex commented Jan 27, 2020

I tried this. But not working. Am I doing anything wrong?

    let jsonString = JSON.stringify(req.body);

    const generated_hash = crypto
        .createHmac('sha256', secret)
        .update(jsonString,'utf8','hex')
        .digest('base64');

@Kushan-
Copy link

Kushan- commented Jan 28, 2020

It's been a long time i worked with shopify api, perhaps, uppercase secret might help, what error you are getting?

@wrsalex
Copy link

wrsalex commented Jan 28, 2020

thank you for your reply. tried the uppercase approach. did not work.

got this error
0|wmbi | HASH COMPARE FAILED - Unable to verify request HMAC

0|wmbi  | POST /webhook/ads-hkg - - ms - -
0|wmbi  | { sp_hmac: 'aAwa1U3uPwRl4fJVLmxuLkaKMiyZRnCwlHMl3q8iDxI=',
0|wmbi  |   sp_topic: 'orders/create',
0|wmbi  |   sp_shopDomain: 'ads-api-testing.myshopify.com' }
0|wmbi  | HASH COMPARE FAILED - Unable to verify request HMAC
0|wmbi  | generated_hash: iiKQ9W/kInYASnwL+j2oG2cjbHBFj9CqrMlyd76yaew=
0|wmbi  | sp_hmac: aAwa1U3uPwRl4fJVLmxuLkaKMiyZRnCwlHMl3q8iDxI=

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment