Skip to content
HooktierDocs

Shopify webhook HMAC verification fails (401)

You hit one of these problems:

  • Your endpoint answers 401 Unauthorized to real Shopify webhooks, and the log says Webhook HMAC validation failed.
  • The Shopify App Store automated checks fail on verifying webhooks with HMAC signatures or on the mandatory compliance webhooks.
  • The delivery log shows Delivery failed after retries or Removed response.

Shopify’s documentation has no list of causes for a 401: your own handler sends it when its HMAC check fails. In most cases the HMAC is correct and the input to your check is wrong: a parsed body, the wrong secret, or a hex digest compared with a base64 header. This page lists the causes in the order you should check them.

Each HTTPS delivery has an X-Shopify-Hmac-Sha256 header. Its value is the base64 encoding of the HMAC-SHA256 of the raw request body, keyed with your app’s client secret.

Other headers that help with debugging:

Header Content
X-Shopify-Topic The topic, for example orders/create
X-Shopify-Shop-Domain The myshopify.com domain of the store
X-Shopify-Webhook-Id A unique key per delivery; use it to drop duplicate deliveries
X-Shopify-Event-Id One ID shared by all deliveries of the same merchant action
X-Shopify-Triggered-At When Shopify triggered the delivery

Treat header names as case-insensitive. HTTP/2 often sends them in lowercase.

1. A body parser changed the body before the check

Section titled “1. A body parser changed the body before the check”

Shopify signs the exact body bytes. Parsing and re-serializing JSON, for example hashing JSON.stringify(req.body), can change whitespace, number formats or Unicode escapes, and the HMAC then no longer matches. Hash the original raw body.

Shopify’s documentation names this issue: a parser such as express.json() runs before your check. Hash the raw body, then parse it. Put the verification before any body parser. In Express, register the webhook route with express.raw() before any global express.json():

import crypto from "node:crypto";
import express from "express";
const app = express();
const secret = process.env.SHOPIFY_API_SECRET; // the app's client secret
function validShopifyHmac(rawBody, hmacHeader) {
// An empty key would let anyone compute a valid HMAC.
if (typeof secret !== "string" || secret.length === 0) return false;
if (typeof hmacHeader !== "string") return false;
const expected = crypto.createHmac("sha256", secret).update(rawBody).digest();
const given = Buffer.from(hmacHeader, "base64");
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
}
// The webhook route comes first, with a raw body parser.
app.post("/webhooks/shopify", express.raw({ type: "application/json" }), (req, res) => {
if (!validShopifyHmac(req.body, req.get("X-Shopify-Hmac-Sha256"))) {
return res.sendStatus(401);
}
const payload = JSON.parse(req.body.toString("utf8"));
// Queue the payload for a background job, then answer quickly.
console.log(`Received ${req.get("X-Shopify-Topic")} with ${Object.keys(payload).length} fields`);
res.sendStatus(200);
});
// JSON parsing for every other route comes after.
app.use(express.json());
app.listen(3000);

2. You compare a hex digest with a base64 header

Section titled “2. You compare a hex digest with a base64 header”

The header is base64. Many HMAC helpers return hex by default (digest("hex") in Node, hash_hmac() in PHP, hexdigest() in Python). A hex string never equals a base64 string, even when the HMAC is correct.

Either encode your digest as base64, or decode the header from base64 and compare the bytes, as the samples on this page do.

The key is the app’s client secret. Other values do not give the same HMAC, for example the API key (client ID), an access token, or the client secret of a different app (your development app instead of your production app). You find the client secret in the Dev Dashboard: Apps, then your app, then Settings, then Credentials.

If you rotated the client secret, Shopify can take up to an hour to sign with the new secret. During that time, keep accepting the old secret.

A webhook subscription that someone creates in the Shopify admin is not signed with your app’s client secret, so it fails your app’s HMAC check. The guide for Shopify’s API library says so. Shopify’s Help Center adds that these webhooks are signed with an ID that is unique to the store. The library’s log message warns about the same case:

Webhook HMAC validation failed. Please note that events manually triggered from a store's Notifications settings will fail this validation. To test this, please use the CLI or trigger the actual event in a development store.

To test an app webhook, use the Shopify CLI or cause the real event in a development store. shopify app webhook trigger sends a test webhook. Its HMAC matches your secret only when you pass --client-secret. You can’t use this method to validate your API webhook subscriptions. For an end-to-end test, Shopify’s documentation recommends real actions in a development store.

4. Something in front of your code changed the body

Section titled “4. Something in front of your code changed the body”

A proxy, an API gateway or a serverless adapter can re-encode the body. Examples are a body delivered to the function as base64, a changed character set, or re-indented JSON. Hash the bytes exactly as Shopify sent them.

To find the layer that changes the body:

  1. Record the body length and SHA-256 immediately before and after the suspected layer for one test request.
  2. Compare those measurements for that same request.
  3. Different measurements show that the body changed between those points.

Do not compare a real delivery with a CLI sample: they are different requests with different bodies, so the comparison proves nothing.

The Shopify app template does the check for you in authenticate.webhook. It reads the raw body with request.text(), checks the HMAC, and throws a 401 Unauthorized response when the HMAC is invalid. Other validation failures, for example missing headers, give 400 Bad Request, and a method other than POST gives 405.

app/routes/webhooks.app.uninstalled.tsx
import type { ActionFunctionArgs } from "react-router";
import { authenticate } from "../shopify.server";
export const action = async ({ request }: ActionFunctionArgs) => {
// Throws a 401 response when the HMAC is invalid.
const { topic, shop } = await authenticate.webhook(request);
console.log(`Received ${topic} for ${shop}`);
return new Response();
};

The HMAC check then fails only when the request is changed or the secret is wrong:

  • Do not read the body before authenticate.webhook (for example with request.json()). A request body can be read only once.
  • Check that SHOPIFY_API_SECRET in the environment of the deployed app is the client secret of the app that owns the subscription.

6. Compliance webhooks and the App Store checks

Section titled “6. Compliance webhooks and the App Store checks”

Every app in the Shopify App Store must subscribe to three compliance topics:

  • customers/data_request
  • customers/redact
  • shop/redact

Shopify’s privacy documentation sets the response rule: when a compliance webhook arrives with an invalid HMAC, the app must answer 401 Unauthorized. An endpoint that answers 200 to every request does not meet this rule, even when real webhooks work.

Subscribe to the topics in shopify.app.toml, then run shopify app deploy. That command releases the app configuration; it does not deploy your web app.

[webhooks]
api_version = "2026-10"
[[webhooks.subscriptions]]
compliance_topics = ["customers/data_request", "customers/redact", "shop/redact"]
uri = "/webhooks/compliance"

Use a supported API version; 2026-10 is the latest stable version on 2026-10-10. The uri can be a full URL or a relative path that starts with a slash. Shopify forum reports say the review reads the topics from the app configuration, so a subscription created only through the Admin API can fail the check.

The handler must do two things:

  1. Answer 401 Unauthorized when the HMAC is invalid.
  2. Answer with a 200-series code when the HMAC is valid, then do the data request or the deletion. Shopify’s documentation gives 30 days to complete it. The exception: if the law requires you to keep the data, do not complete a redaction request.

A frequent mistake is a handler that answers 401 to every request, because the deployed app reads a different secret. The check then fails on valid requests instead.

7. Slow handlers and removed subscriptions

Section titled “7. Slow handlers and removed subscriptions”

Shopify expects a 200 response quickly. Its documentation gives one second to connect and five seconds for the whole request. Any response outside the 200 range counts as an error, redirects (3XX) included. A delivery that takes too long counts as failed and is retried, so a slow handler can receive the same webhook twice.

When Shopify gets no response or an error, it retries 8 times over the next 4 hours. Warning emails go to the app’s emergency developer email address. After 8 consecutive failures, Shopify deletes the subscription if it was created with the Admin API; you must create it again. App subscriptions from the app configuration (shopify.app.toml) need no new subscription after downtime.

To stay inside the limit, delay the processing until after the response:

  1. Check the HMAC.
  2. Store the raw payload or put it on a queue.
  3. Answer 200.
  4. Do the work in a background job, and drop duplicates by X-Shopify-Webhook-Id.

hash_hmac() returns hex unless the fourth argument is true. Read the raw body, not the parsed input.

<?php
// Plain PHP: the raw body comes from php://input.
$secret = getenv('SHOPIFY_API_SECRET');
if ($secret === false || $secret === '') {
// An empty key would let anyone compute a valid HMAC.
http_response_code(500);
exit;
}
$rawBody = file_get_contents('php://input');
$header = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'] ?? '';
$expected = base64_encode(hash_hmac('sha256', $rawBody, $secret, true));
if (!hash_equals($expected, $header)) {
http_response_code(401);
exit;
}
$payload = json_decode($rawBody, true);
http_response_code(200);

In a Laravel controller, use $request->getContent() for the raw body and $request->header('X-Shopify-Hmac-Sha256') for the header.

package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"io"
"log"
"net/http"
"os"
)
func validShopifyHMAC(body []byte, header, secret string) bool {
// An empty key would let anyone compute a valid HMAC.
if secret == "" {
return false
}
given, err := base64.StdEncoding.DecodeString(header)
if err != nil {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(body)
return hmac.Equal(given, mac.Sum(nil))
}
func shopifyWebhook(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "cannot read body", http.StatusBadRequest)
return
}
if !validShopifyHMAC(body, r.Header.Get("X-Shopify-Hmac-Sha256"), os.Getenv("SHOPIFY_API_SECRET")) {
w.WriteHeader(http.StatusUnauthorized)
return
}
log.Printf("received %s %s", r.Header.Get("X-Shopify-Topic"), r.Header.Get("X-Shopify-Webhook-Id"))
w.WriteHeader(http.StatusOK)
}
func main() {
http.HandleFunc("POST /webhooks/shopify", shopifyWebhook)
log.Fatal(http.ListenAndServe(":3000", nil))
}

Compare in constant time (crypto.timingSafeEqual, hash_equals, hmac.Equal), as Shopify’s own sample does. A plain string comparison leaks timing information.

  1. The code hashes the raw body bytes, before any JSON parser.
  2. The digest is base64, or the header is decoded from base64 before the comparison.
  3. The key is the client secret of the app that owns the subscription. After a rotation, allow up to an hour.
  4. Tests use the Shopify CLI or real events, not events sent from the store’s Notifications settings.
  5. Compliance endpoints answer 401 to an invalid HMAC and 200 to a valid one.
  6. The handler answers within five seconds and does the work in the background.

Checked on 2026-10-10.