in

How to Verify Shopify Webhook HMACs in PHP with Confidence

Shopify webhook HMAC verification in PHP helps confirm a request came from Shopify and its payload hasn’t been changed. Learn to preserve the raw request body, calculate and compare signatures safely, and respond appropriately. You’ll also find practical tests and troubleshooting tips to help protect your app and handle webhooks with confidence.

Shopify webhooks make it easy to respond to store events, but you’ll want to confirm each request really came from Shopify before acting on it. That’s where Shopify webhook HMAC verification in PHP comes in: it helps protect your app from forged or altered webhook requests.

In this guide, you’ll learn how to verify a webhook’s HMAC using the request body, Shopify’s signature header, and your app’s shared secret. With a few careful steps, you can build a reliable check and handle incoming events with greater confidence.

Shopify webhook HMAC verification PHP: what the check proves

A webhook can look convincing and still come from the wrong sender—or arrive with its contents changed. Before building the PHP check, it helps to know exactly what a valid signature establishes and what your handler needs to perform that check reliably.

The first piece is the way Shopify creates the signature. That process explains why preserving the original request body matters.

How Shopify signs webhook requests

Shopify calculates an HMAC-SHA256 digest from the webhook’s raw request body, using your app’s shared secret as the key. It then Base64-encodes the result and sends it in the X-Shopify-Hmac-Sha256 header.

Your PHP handler performs the same calculation and compares its result with the header value. Use the exact raw body received from the request—not a decoded and re-encoded version—because even small changes in whitespace or character encoding can produce a different digest. For comparisons, PHP’s hashequals() helps avoid timing-based leaks.

Shopify’s webhook verification guidance describes this signature format. Treat the HMAC as a check on the body’s authenticity and integrity; it is not a substitute for validating the event’s contents or handling delivery retries.

With the mechanics clear, the next question is what passing the check means for your app’s decisions.

Why verifying the signature protects your app

A successful comparison provides evidence that the request body was signed with the secret associated with your app and has not been altered since signing. This makes it much harder for an outsider to send a forged event—such as a fabricated order notification—and have your endpoint accept it as genuine.

That protection is useful only when it happens before you act on the event. Reject requests with missing or invalid signatures before updating records, triggering fulfillment, or sending customer messages. Still apply normal validation and authorization rules afterward: a valid signature does not guarantee that the event is appropriate for every operation.

Once the trust boundary is clear, gathering the right inputs makes implementation far more straightforward.

What you need before writing the PHP handler

Prepare the values and request access your verification routine will rely on. Keep the shared secret private; it should come from secure configuration, not from source code committed to a repository.

  • The app’s Shopify client secret, stored securely.
  • The raw request body, typically read from php://input.
  • The HMAC header, retrieved from the incoming request.
  • A way to return an error response when verification fails.

Also make sure your web server and PHP setup expose the header consistently, and avoid consuming or transforming the body before verification. With these pieces in place, your handler can make the signature check an early, clear gate before processing webhook data.

Implement Shopify webhook HMAC verification in PHP

What happens if your handler reads the request correctly but changes the body before checking it? Even an innocent transformation can make a legitimate delivery fail verification. The following steps keep the original bytes intact, calculate the expected signature, and make the result a clear gate before your app processes an event.

Start with the request as PHP receives it; decoding JSON too early can alter the data you need to verify. This step also gives you a reliable place to detect an unreadable or empty body.

Read and preserve the raw request body

Read php://input once and store the result in a variable. Use that same string for both the HMAC calculation and any later JSON decoding—don’t re-encode a decoded object and use the new string for verification.

For example, decode only after the signature passes: $payload = jsondecode($rawBody, true);. If the body cannot be read, stop and return an error rather than treating missing data as a valid event.

Next, use the preserved body and the secret configured for your Shopify app to reproduce Shopify’s calculation. The example below also reads the signature from PHP’s usual server variable for this header.

Calculate the HMAC with your app’s client secret

Use hashhmac() with the sha256 algorithm and its raw-output option, then Base64-encode the result. That sequence produces the same signature format Shopify sends.

Keep the client secret in an environment variable or another secure configuration store, and fail closed if it is unavailable. Don’t substitute a shop-specific access token or place the secret directly in code.

$rawBody = filegetcontents('php://input');
$secret = getenv('SHOPIFYAPISECRET');
$received = $SERVER['HTTPXSHOPIFYHMACSHA256'] ?? '';
if ($rawBody === false || $secret === false || $secret === '' || $received === '') {
    httpresponsecode(401);
    exit;
}
$expected = base64encode(
    hashhmac('sha256', $rawBody, $secret, true)
);

Now that both values are available, compare them without using a regular equality operator. A timing-safe comparison makes the verification step more robust.

Compare signatures safely with hashequals

Pass the locally calculated value first and the header value second: hash

equals($expected, $received). Unlike == or ===, hashequals() is designed to reduce timing differences that could reveal information about a secret comparison.

If the check fails, exit before decoding or acting on the event:

if (!hashequals($expected, $received)) {
    httpresponsecode(401);
    exit;
}

Once verification succeeds, the response code becomes part of reliable delivery handling. Separate authentication failures from problems in an otherwise verified event.

Return the right response after verification

For a missing or invalid signature, return a non-success status such as 401 and do not process the body. For a valid signature, validate the payload and handle the event; malformed data can receive a 400 response.

Shopify expects a timely response, so avoid lengthy work in the webhook request. If processing takes longer, save the verified event for background work and return a success status once it has been safely queued. This keeps verification immediate while giving your application room to handle heavier tasks.

Test and troubleshoot your Shopify webhook HMAC verification PHP

A handler can pass a quick happy-path check and still fail when a real delivery arrives. A small set of deliberate tests can catch those gaps before they lead to missed events or untrusted requests.

Cover valid, invalid, and altered payloads

Build a test for each outcome: a valid delivery should pass, while a bad signature or a changed body should be rejected. Use a fixed sample payload and a test secret to generate a known-good signature, then send that exact pair through your verification code.

Next, change one byte in the payload without updating the signature. The check should fail, just as it should when the header is missing, malformed, or contains a different Base64 value. These cases confirm the handler checks the body it actually receives rather than a reconstructed version.

Include useful edge cases in automated tests:

  • An empty body or unreadable input.
  • A missing signature header.
  • A valid signature paired with malformed JSON.
  • Two identical deliveries, to check that event processing is safe to repeat.

That final case matters because webhook deliveries may be retried; signature verification does not prevent duplicate processing.

Diagnose common signature mismatches

When a legitimate request fails, compare the inputs before changing the verification logic. Most mismatches come from a wrong secret, a modified body, or a header that PHP has not exposed under the server variable your code expects.

Check that the configured value is the app’s client secret, with no accidental whitespace, and confirm the request body is read before any middleware consumes or transforms it. In a safe development environment, inspect whether the HMAC header is present—but never print the secret or full signature into production logs.

Shopify’s webhook verification documentation is a useful reference if you need to confirm the expected header and signing method. Keep a test fixture so changes to PHP, framework middleware, or server configuration can be checked consistently.

Keep secrets and webhook handling secure

Once tests pass, protect the configuration and the verified event throughout its lifecycle. Store the secret outside source control, restrict access to it, and use a separate test secret in development.

After verification, validate the payload and guard against duplicate event effects before performing sensitive actions. Log enough to troubleshoot—such as the event type, timestamp, and rejection reason—but exclude secrets and sensitive customer data. Together, these practices make Shopify webhook HMAC verification in PHP a dependable part of a broader, secure webhook workflow.

Build confidence into every Shopify webhook

Reliable Shopify webhook HMAC verification in PHP gives your app a clear way to distinguish trusted deliveries from requests it should reject. The key is to make verification an early gate, preserve the integrity of the request, and keep your app secret protected.

Pair that check with thoughtful testing, sensible error handling, and safeguards against duplicate events, and you’ll have a webhook workflow that’s both secure and dependable. With these foundations in place, you can respond to Shopify events with greater confidence—and keep your app ready for real-world deliveries.

Leave a Reply

Your email address will not be published. Required fields are marked *

      Written by Maeve Rodriguez

      Maeve is a Business Content Writer and Front-End Developer. She's a versatile professional with a talent for captivating writing and eye-catching design.