Solved

subscribe webhook and verify it

AW1234
Shopify Partner
44 7 12

Hello,

I have a problem with webhooks,

I subscribe to a webhook with graphql admin api with webhookSubscriptionCreate and it works well,

but when I try to verify it when I get a call on my callbackUrl I can't find the same hmac as sent in request headers.

I'm using nodejs

here is my code to verify the hmac

const hmac = req.get('X-Shopify-Hmac-Sha256');
    const store = config.shopifyStores[req.get('x-shopify-shop-domain').slice(0, -14)];
    getRawBody(req, { length: req.get('content-length'), limit: '20mb' }, (err, rawBody) => {
      if (err) next(err);
      let hash = crypto.createHmac('sha256', store.webhookKey).update(rawBody, 'utf8', 'hex').digest('base64');
      if (hmac !== hash) {
        const calculatedWebHookKey = crypto.createHmac('sha256', store.keysAndSecretKeys.webhook.secretKey).update(rawBody, 'utf8', 'hex').digest('base64');
        hash = crypto.createHmac('sha256', calculatedWebHookKey).update(rawBody, 'utf8', 'hex').digest('base64');
        if (hmac !== hash) {
          console.error('Error');
          req.body = false;
        }
      } else {
        req.body = JSON.parse(rawBody.toString());
      }
    next();
});

there is 2 verification because I also use webhook subscription from shopify admin back office (this part works well)

 

so the not working part is this one

const calculatedWebHookKey = crypto.createHmac('sha256', store.keysAndSecretKeys.webhook.secretKey).update(rawBody, 'utf8', 'hex').digest('base64');
hash = crypto.createHmac('sha256', calculatedWebHookKey).update(rawBody, 'utf8', 'hex').digest('base64');

what I do there is that I take the secretKey of the app I used to subscribe to the webhook and calculate a key with the rawBody and then just verify as before but it does not work.

 

I'm sorry I can't find the docs where I found this.

I don't know if this was clear enough but thanks to anyone that can help me.

Accepted Solution (1)

AW1234
Shopify Partner
44 7 12

This is an accepted solution.

Hi I found the solution some days ago, I reply so maybe it will help someone,

you just have to use the secretKey of the token you used to subscribe to the webhook:

hash = crypto.createHmac('sha256', token.secretKey).update(rawBody, 'utf8', 'hex').digest('base64');

 

View solution in original post

Reply 1 (1)

AW1234
Shopify Partner
44 7 12

This is an accepted solution.

Hi I found the solution some days ago, I reply so maybe it will help someone,

you just have to use the secretKey of the token you used to subscribe to the webhook:

hash = crypto.createHmac('sha256', token.secretKey).update(rawBody, 'utf8', 'hex').digest('base64');