HMAC Validation Failed and Mismatched

I was creating the simple webhook for “order payment”, where I’m receiving the order data correctly but the issue is that I’m continuously getting HMAC VALIDATION FAILED . I have checked all the basic things specially SHOPIFY_API_SECRET.

import crypto from “crypto”;

const SHOPIFY_API_SECRET = process.env.SHOPIFY_API_SECRET;

export const handleOrderWebhook = (req, res) => {
try {
const rawBody = req.body;
const hmacHeader = req.get(“x-shopify-hmac-sha256”)?.trim();

if (!hmacHeader) {
  console.error("❌ Missing HMAC header");
  return res.status(400).send("Missing HMAC header");
}

if (!Buffer.isBuffer(rawBody)) {
  console.error("❌ req.body is not a Buffer");
  return res.status(500).send("Invalid body format – expected Buffer");
}

const generatedHmac = crypto
  .createHmac("sha256", SHOPIFY_API_SECRET)
  .update(rawBody)
  .digest("base64");

const isValid =
  Buffer.byteLength(hmacHeader) === Buffer.byteLength(generatedHmac) &&
  crypto.timingSafeEqual(
    Buffer.from(hmacHeader, "utf8"),
    Buffer.from(generatedHmac, "utf8")
  );

if (!isValid) {
  console.error("❌ HMAC Mismatch");
  console.log("🔐 HMAC Header:", hmacHeader);
  console.log("🧮 Generated   :", generatedHmac);
  console.log("📦 Raw body    :", rawBody.toString("utf8")); // 👈 Log raw body here
  return res.status(401).send("HMAC validation failed");
}

const order = JSON.parse(rawBody.toString("utf8"));
console.log("✅ Webhook verified. Order received:");
console.dir(order, { depth: null }); // Pretty print the whole object

return res.status(200).send("Webhook received");

} catch (error) {
console.error(“:cross_mark: Error handling webhook:”, error.message);
return res.status(500).send(“Internal Server Error”);
}
};

1 Like