Our Partner & Developer boards on the community are moving to a brand new home: the .dev community forums! While you can still access past discussions here, for all your future app and storefront building questions, head over to the new forums.

Webhook from shopify admin page verify problem

Webhook from shopify admin page verify problem

Kolt
Visitor
1 0 0

Hi i have some problem when test verify webhook it alway return the wrong hash and it never match what did i do wrong?

 

 

public function shopify()
    {
        // Check signature
        $header = $this->request->getHeader('x-shopify-hmac-sha256');   
     
        $body = file_get_contents('php://input');

        $result = ShopifyController::verify_webhook($body, $header);
        
        if ($result) {
          $response = new Response();
          $response->setStatusCode(200);          
          $respone->jsonContent($body);
          return $response;
        }
        // Error
        $response = new Response();
        $response->setStatusCode(400);
        return $response;
    }

 

 

 

 

 

static function verify_webhook($data, $hmac_header)
  {

      $secret = file_get_contents($_ENV['SHOPIFY_WEBHOOK_PATH']) ?? null;
      $calculated_hmac = base64_encode(hash_hmac('sha256', $data, $secret, true));      
      return hash_equals($hmac_header, $calculated_hmac);
  }

 

 

 
The result alway not match i use secret in the buttom of notification admin page
ex
hmc_header "+RpGt0vu...."
calculate_hash: "BIYF+9...."

Any though? Thank you.

Reply 1 (1)

theschoolofux
Shopify Partner
10 0 5

Had the same issue. Using request.rawBody instead of request.body helped. Also note that the secret key you should use for verification is not your Shopify API secret key, but the key under Webhooks section in your admin panel (<yourstore>.myshopify.com/admin/settings/notifications) where it says "All your webhooks will be signed with [SHOPIFY_WEBHOOKS_KEY] so you can verify their integrity".

 

import Router from "koa-router";
import koaBodyParser from "koa-bodyparser";
import crypto from "crypto";

...

koaServer.use(koaBodyParser()); 

...

koaRouter.post(
    "/webhooks/<yourwebhook>",
    verifyShopifyWebhooks,
    async (ctx) => {
      try {
        ctx.res.statusCode = 200;
      } catch (error) {
        console.log(`Failed to process webhook: ${error}`);
      }
    }
);

...

async function verifyShopifyWebhooks(ctx, next) {
  const generateHash = crypto
    .createHmac("sha256", process.env.SHOPIFY_WEBHOOKS_KEY)
    .update(ctx.request.rawBody, "utf-8")
    .digest("base64");

  if (generateHash !== shopifyHmac) {
    ctx.throw(401, "Couldn't verify Shopify webhook HMAC");
  } else {
    console.log("Successfully verified Shopify webhook HMAC");
  }
  await next();
}

 

Sergei Golubev | Devigner @ The School of UX | schoolofux.com