Can't verify the Webhook HMAC for cloud functions

PercyMcfly
New Member
1 0 1

Hello there,

 

i configured a web hock where I get a json from Shopify sent to my cloud functions nodes connection point

 

there I use Express and try to generate the hash from the data I get and from the secretKey I got from shopify

I am getting the data from Shopify as json and the code below is a combination of the following links

Can-t-verify-Webhooks-in-Node-js-serverless-AWS-lambda/td-p/656291 

validating-shopify-webhooks-with-aws-lambda-and-node 

how-to-validate-the-shopify-webhook-api-using-nodejs 

My code never worked. The last state of my code is below

app.use(bodyParser.raw());

app.post("/", async (req, res) => { 
    console.log("Webhook heard!");
  // Verify
  const hmac = req.header("X-Shopify-Hmac-Sha256");
  const topic = req.header("X-Shopify-Topic");
  const shop = req.header("X-Shopify-Shop-Domain");

  const verified = verifyWebhook(req.body, hmac);

  if (!verified) {
    console.log("Failed to verify the incoming request.");
    res.status(401).send("Could not verify request.");
    return;
  }

  const data = JSON.stringify(req.body);
  //const payload = JSON.parse(data);
  console.log(
    `Verified webhook request. Shop: ${shop} Topic: ${topic} \n Payload: \n ${data}`
  );

  res.status(200).send("OK");
});

function verifyWebhook(payload:any , hmac:string|undefined) {
    const genHash = crypto
      .createHmac("sha256", shopifySecret)
      .update(JSON.stringify(payload))
      .digest("base64");
    console.log(payload);
    console.log('mine   : ' + genHash);
    console.log('shopify: ' + hmac);
    return genHash === hmac;
  }

 

kokokenada
New Member
1 0 0

This works for me:

 

    const hash = crypto
      .createHmac('sha256', serverInfo.shopifySecret)
      .update(body, 'utf8', 'hex')
      .digest('base64');

 

I've seen other examples without the hex 

0 Likes