Webhook HMAC-SHA256 Verifier · Shopify + FastAPI

Shopify Base64 HMAC Webhook Verification in Python FastAPI

Verify and generate Shopify + FastAPI HMAC-SHA256 signatures locally using crypto.subtle. Compare raw-body vs re-serialized JSON hashes side by side and copy constant-time verification code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust payload/secret or load a test scenario2. Inspect live HMAC & diagnostics3. Copy handler code
Quick-Test Scenarios:

1. Provider, Secret & Header

Whitespace and line endings affect the HMAC digest. Edit the raw payload below to test byte-level changes.

Test Signature Generated·X-Shopify-Hmac-Sha256

X-Shopify-Hmac-Sha256: WPAGjN6P1svncYIrvMtVq/+sCo7osVm845gI0+qFyy8=

# app/routers/webhooks.py — Python FastAPI Raw Body Verification
import base64
import hashlib
import hmac
import json
import os
import time
from fastapi import APIRouter, HTTPException, Request

router = APIRouter()

@router.post("/webhooks/shopify")
async def handle_shopify_webhook(request: Request):
    # Read exact raw bytes BEFORE Pydantic JSON parsing
    raw_body: bytes = await request.body()
    secret = os.environ["WEBHOOK_SECRET"].encode("utf-8")

    received = request.headers.get("x-shopify-hmac-sha256", "")
    digest = hmac.new(secret, raw_body, hashlib.sha256).digest()
    expected = base64.b64encode(digest).decode("utf-8")
    if not hmac.compare_digest(expected, received):
        raise HTTPException(status_code=401, detail="Invalid Shopify HMAC")

    payload = json.loads(raw_body)
    return {"received": True, "event": payload.get("type", "ok")}
1. Raw Body HMAC (BASE64)Valid

WPAGjN6P1svncYIrvMtVq/+sCo7osVm845gI0+qFyy8=

Untouched raw request bytes (indentation and newlines preserved).

2. Re-Serialized JSON HMACMismatch

frmvz4ZIQiinaak1p6gt9rKb3iqNcVj9GdvCdk+fprE=

Digest produced if JSON middleware parses and re-encodes the body.

HMAC & Raw-Body Diagnostics

  • criticalRaw Body vs. Re-Serialized JSON Produces Two Different Signatures

    Notice in the comparison box below: hashing this exact raw payload produces a completely different HMAC than hashing JSON.stringify(JSON.parse(payload)). Never run express.json(), request.json(), or json_encode($request->all()) before verifying webhook signatures.

  • infoAlways Use Constant-Time Comparison (Never === or ==)

    Compare computed and received digests with hash_equals() (PHP/Laravel), hmac.compare_digest() (Python/FastAPI), crypto.timingSafeEqual() (Node.js/Next.js/Express), or CryptographicOperations.FixedTimeEquals() (ASP.NET Core) to prevent timing side-channel attacks.

Runs locally in your browser using window.crypto.subtle. Webhook secrets and payloads are never sent to a server.

Typical Webhook Signature Verification Error (Shopify + FastAPI)

When middleware consumes the raw HTTP stream, JSON gets re-serialized before hashing, or encoding/prefixes mismatch in Shopify + FastAPI, your server logs an exception matching the output below:

Server Exception / Webhook Delivery Log

HTTP 401 Unauthorized: Invalid Shopify HMAC — computed lowercase hex digest instead of Base64-encoded raw HMAC-SHA256 bytes.

Raw Request Stream Handling & Replay Protection in Shopify + FastAPI

Shopify webhooks catch Python FastAPI developers with one critical difference compared to Stripe and GitHub: Shopify encodes the X-Shopify-Hmac-Sha256 header in **Base64** rather than lowercase Hex. Calling hmac.new(..).hexdigest(), the most common Python idiom, produces a 64-character hex string that will NEVER match Shopify's 44-character Base64 header.

To match Shopify's signing algorithm accurately in Python, you must compute raw binary digest bytes via hmac.new(secret_bytes, raw_body, hashlib.sha256).digest() (NOT .hexdigest()!) and wrap those 32 raw bytes in base64.b64encode(..).decode("utf-8"). Comparing that string against request.headers.get("X-Shopify-Hmac-Sha256") using hmac.compare_digest() verifies authentic Shopify orders, inventory updates, and GDPR compliance hooks reliably.

Just like Stripe and GitHub, Shopify hashes the untouched raw HTTP request body bytes. Declaring a Pydantic model parameter on your FastAPI route parses JSON before your handler executes and breaks HMAC matching whenever Shopify formats decimal strings, whitespace, or UTF-8 characters. Always inject request: Request and call raw_body = await request.body().

Shopify enforces an aggressive 5-second timeout and automatically deletes your webhook subscription if 19 consecutive deliveries fail. Immediately verify the Base64 HMAC, record X-Shopify-Webhook-Id for idempotency, enqueue a Celery or Redis job, and return HTTP 200 OK in under 100 milliseconds.

Test both Hex vs. Base64 encoding diagnostics and raw-body JSON re-serialization differences live in the browser Web Crypto debugger above.

Because Shopify enforces both strict 5-second delivery timeouts and mandatory App Store GDPR compliance checks (asserting HTTP 401 on invalid HMAC headers), automated pytest coverage testing both valid Base64 signatures and tampered payloads is essential for FastAPI Shopify apps. Pairing raw-body verification with X-Shopify-Webhook-Id deduplication and Celery background processing keeps multi-store order sync rock-solid during flash-sale spikes.

Step-by-Step Shopify + FastAPI Webhook Verification Setup

Follow each step below to preserve untouched raw request bytes, enforce constant-time HMAC verification, and offload webhook jobs asynchronously for fast 2xx acknowledgments.

  1. 1Compute Base64 HMAC Over Raw Bytes in FastAPI

    app/routers/shopify_webhooks.py

    Call .digest() (raw 32 bytes) followed by base64.b64encode(), compare using hmac.compare_digest(), and decode JSON only after verification succeeds.

    app/routers/shopify_webhooks.pypython
    import base64
    import hashlib
    import hmac
    import json
    import os
    from fastapi import APIRouter, BackgroundTasks, Header, HTTPException, Request
    
    router = APIRouter(prefix="/webhooks", tags=["shopify"])
    
    def handle_shopify_order(webhook_id: str, shop_domain: str, payload: dict):
        # Idempotent order fulfillment via Celery / DB
        pass
    
    @router.post("/shopify")
    async def shopify_webhook(
        request: Request,
        background_tasks: BackgroundTasks,
        shopify_hmac: str | None = Header(default=None, alias="X-Shopify-Hmac-Sha256"),
        shop_domain: str = Header(default="", alias="X-Shopify-Shop-Domain"),
        webhook_id: str = Header(default="", alias="X-Shopify-Webhook-Id"),
    ):
        raw_body: bytes = await request.body()
        secret = os.environ["SHOPIFY_WEBHOOK_SECRET"].encode("utf-8")
    
        if not shopify_hmac:
            raise HTTPException(status_code=401, detail="Missing X-Shopify-Hmac-Sha256")
    
        raw_digest = hmac.new(secret, raw_body, hashlib.sha256).digest()
        expected_b64 = base64.b64encode(raw_digest).decode("utf-8")
    
        if not hmac.compare_digest(expected_b64, shopify_hmac):
            raise HTTPException(status_code=401, detail="Invalid Shopify HMAC signature")
    
        payload = json.loads(raw_body)
        background_tasks.add_task(handle_shopify_order, webhook_id, shop_domain, payload)
        return {"ok": True}
  2. 2Verify Which Shopify Secret Key Applies to Your App Type

    .env

    Public/Custom Partner Apps sign webhooks with the App Client Secret (shpss_..), whereas Admin-created Store Webhooks use the webhook signing key shown at the bottom of Shopify Admin -> Settings -> Notifications -> Webhooks.

    .envdotenv
    SHOPIFY_WEBHOOK_SECRET="shpss_replace_with_partner_client_secret"
  3. 3Deduplicate At-Least-Once Deliveries With X-Shopify-Webhook-Id

    app/services/idempotency.py

    Shopify guarantees at-least-once delivery and frequently sends the same order event twice. Store X-Shopify-Webhook-Id in Redis or PostgreSQL with a unique constraint.

    app/services/idempotency.pypython
    async def claim_webhook(redis, webhook_id: str) -> bool:
        if not webhook_id:
            return True
        return bool(await redis.set(f"shopify:wh:{webhook_id}", "1", ex=86400, nx=True))
  4. 4Test Shopify Base64 Verification Locally With curl

    terminal

    Copy the generated Base64 X-Shopify-Hmac-Sha256 value from the tool above and verify FastAPI returns HTTP 200 OK.

    terminalbash
    curl -i -X POST http://127.0.0.1:8000/webhooks/shopify \
      -H "Content-Type: application/json" \
      -H "X-Shopify-Shop-Domain: demo-store.myshopify.com" \
      -H "X-Shopify-Webhook-Id: wh-test-001" \
      -H "X-Shopify-Hmac-Sha256: <paste_base64_from_tool>" \
      --data-binary @order.json

Common Shopify + FastAPI Webhook Pitfalls

Avoid these three subtle production failure modes when verifying external webhook signatures.

Pitfall 1

Base64-Encoding hexdigest() Instead of Binary digest()

Writing base64.b64encode(hmac.new(..).hexdigest().encode()) produces an 88-character Base64 string of ASCII hex characters instead of the 44-character Base64 encoding of the 32 raw SHA-256 bytes.

Pitfall 2

Using the Admin API Access Token (shpat_) Instead of the Client Secret (shpss_)

Shopify signs app webhooks using the App Client Secret (API secret key), NOT the store access token (shpat_). Double-check the secret source in Partner Dashboard vs. Store Admin.

Pitfall 3

Missing Mandatory Shopify GDPR Compliance Webhooks Returning 401 on Bad HMAC

Shopify's App Store automated review intentionally sends GDPR webhooks with INVALID HMAC headers and rejects apps that return 200 instead of 401 Unauthorized.

Related Tools

Audit Your Webhook Signing Secrets & Nginx Reverse Proxy Headers

Make sure your .env signing secret has no trailing spaces or unquoted # truncation and your Nginx proxy forwards raw POST payloads without 301 redirects:

Frequently Asked Questions

Why does Shopify use Base64 while Stripe and GitHub use Hex?
Base64 encodes 32 SHA-256 bytes into 44 characters instead of 64 hex characters. Always match each provider's exact encoding; our debugger above detects Base64 vs. Hex mix-ups automatically.
What HTTP status code does Shopify require when HMAC verification fails?
Return HTTP 401 Unauthorized immediately whenever X-Shopify-Hmac-Sha256 is missing or does not match. Shopify's automated App Store compliance checks explicitly assert a 401 status on tampered payloads.
How fast must FastAPI respond to Shopify webhooks?
Shopify enforces a 5-second response deadline. Verify the signature, enqueue an async Celery/Redis task, and return HTTP 200 OK immediately so Shopify never retries or auto-deletes your webhook.
Why does Shopify's "Send test notification" button in Admin fail with my App Client Secret?
Webhooks created manually in Store Admin -> Settings -> Notifications use the store-specific webhook signing secret displayed at the bottom of that page; NOT your Partner App Client Secret.
Browse all 10 webhook guides →