Development discussions around Shopify APIs
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.
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();
}
User | RANK |
---|---|
49 | |
11 | |
5 | |
5 | |
5 |
Thanks to all Community members that participated in our inaugural 2 week AMA on the new E...
By Jacqui Mar 10, 2023Upskill and stand out with the new Shopify Foundations Certification program
By SarahF_Shopify Mar 6, 2023One of the key components to running a successful online business is having clear and co...
By Ollie Mar 6, 2023