Shopify Webhooks Integration with Node.js

A jigsaw puzzle missing a piece. Illustrating an integration of shopify webhook
A jigsaw puzzle missing a piece. Photo by Pixabay from Pexels

Recently had to integrate one of the existing projects to work with Shopify Webhooks. The task was simple. Whenever a new order is created in Shopify, get the data and process it so the app can use it to do what it does.

There are two ways to do so. One is to simply use a webhook. Another one is to create a Shopify app that uses its API. The latter is more reliable as Shopify does not guarantee the delivery of webhooks.

We went with the first option as its more simpler and quick to test what we are going to do, as we can upgrade later if needed.

So, I created a partner account and then a development store. Then I created a new Webhook and added my server URL.

Now the challenge was that Shopify sends an HMAC in the header to verify the authenticity and integrity of the body, which I did not know how it works.

Fortunately, Node.js has a built-in module for cryptography and I was able to use it to verify the payload. But there was a problem, the HMAC function needs the raw body.

Express v4.16.0 and onwards has a built-in function to get the raw body, i.e. express.raw()

router.post("/webhook", express.raw(), requestHandler);

But we were using express.json() on the app level and changing that would have required more work. So we went with this solution.

app.use(express.json({
  verify: function(req, res, buf) {
      req.rawBody = buf;
  }
}));

This simply saves the raw body buffer to a new property.

Now we have the raw buffer, we can verify the data.

const generatedHash = crypto
    .createHmac('sha256', shopifyWebhookKey)
    .update(req.rawBody)
    .digest('base64');

return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(generatedHash));

timingSafeEqual is a better way to compare two things to prevent time-based attacks.

If the generated hash matches the one provided by Shopify we simply use the req.body and consume the data.

The rest of the work is just to consume the data.

Default image
Muhammad Faheem Akhtar
I am a Software Engineer
Articles: 2

One comment

  1. Good choose, fast delivery time, average prices. All this words about this service. I am a customer of this service 1.5 years, like it

Leave a Reply