Shopify HMAC Verification

We are having our webhooks created on the Client’s end, and we are using our servers to handle the webhooks.

We are getting an HMAC token with a webhook, and we want to add verification using HMAC in our webhook server code.

What is the right way to do it?

Hi @Rushabh_Shah

Are you using Node.js? You can try this code

import crypto from 'crypto';

export function verifyShopifyWebhook(secret) {
  return async (req, res, next) => {
    try {
      const hmacHeader = req.get('X-Shopify-Hmac-Sha256');

      const rawBody = await getRawBody(req);
      const generatedHmac = crypto
        .createHmac('sha256', secret)
        .update(rawBody, 'utf8')
        .digest('base64');

      if (crypto.timingSafeEqual(Buffer.from(generatedHmac), Buffer.from(hmacHeader))) {
        req.rawBody = rawBody;
        next();
      } else {
        return res.status(401).send('HMAC validation failed');
      }
    } catch (error) {
      return res.status(500).send('Server error');
    }
  };
}

// Helper function to get raw body
function getRawBody(req) {
  return new Promise((resolve, reject) => {
    let data = '';
    req.setEncoding('utf8');
    req.on('data', chunk => {
      data += chunk;
    });
    req.on('end', () => resolve(data));
    req.on('error', err => reject(err));
  });
}

You can also refer to the Shopify api source code

Hey folks :waving_hand: just wanted to share this documentation here in case it’s helpful as well when it comes to calculating the HMAC signature:

We do provide a few steps in the guide above that go through how to verify the HMAC token too, but @kyle_liu is correct, that code there should work for Node. If you’re using our Remix template, the HMAC authentication should be handled automatically though.

Hope this helps!