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:
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.
1Compute Base64 HMAC Over Raw Bytes in FastAPI
app/routers/shopify_webhooks.pyCall .digest() (raw 32 bytes) followed by base64.b64encode(), compare using hmac.compare_digest(), and decode JSON only after verification succeeds.
app/routers/shopify_webhooks.pypythonimport 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}2Verify Which Shopify Secret Key Applies to Your App Type
.envPublic/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.
.envdotenvSHOPIFY_WEBHOOK_SECRET="shpss_replace_with_partner_client_secret"3Deduplicate At-Least-Once Deliveries With X-Shopify-Webhook-Id
app/services/idempotency.pyShopify 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.pypythonasync 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))4Test Shopify Base64 Verification Locally With curl
terminalCopy the generated Base64 X-Shopify-Hmac-Sha256 value from the tool above and verify FastAPI returns HTTP 200 OK.
terminalbashcurl -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.
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.
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.
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.
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:
Validate Python FastAPI and pydantic-settings .env files in your browser. Fix pydantic_core.ValidationError, nested __ delimiters, unquoted #, and DEBUG leaks.
Build a hardened Nginx reverse proxy config for Python FastAPI and Uvicorn/Gunicorn on port 8000 with --proxy-headers, SSL, WebSockets, and long timeouts.
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.
Related Webhook HMAC Verification Guides
Browse all 10 webhook guides →Shopify Base64 HMAC Webhook Verification in Laravel (Binary hash_hmac Fix)
Verify Shopify X-Shopify-Hmac-Sha256 webhooks in Laravel 11/12 using base64_encode with binary hash_hmac, $request->getContent(), and hash_equals.
Stripe Webhook Signature Verification in FastAPI (request.body() Guide)
Fix Stripe webhook signature errors in Python FastAPI. Read raw bytes with await request.body() before Pydantic parsing and compare via hmac.compare_digest.
GitHub Webhook X-Hub-Signature-256 Verification in Node.js Express
Verify GitHub X-Hub-Signature-256 HMAC-SHA256 webhooks in Express.js using raw Buffers, sha256= prefix validation, and crypto.timingSafeEqual.
ASP.NET Core 8/9 Raw Body Webhook HMAC Verification (EnableBuffering Guide)
Verify Stripe, GitHub, and Shopify HMAC-SHA256 webhooks in ASP.NET Core 8/9 using EnableBuffering(), StreamReader, and FixedTimeEquals in C#.