Webhook HMAC-SHA256 Verifier · Stripe + FastAPI

Stripe Webhook Signature Verification in FastAPI (request.body() Guide)

Verify and generate Stripe + 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·Stripe-Signature

Stripe-Signature: t=1795378346,v1=f44b8a1064864dbeebd8b41cdad13a6526e6988a6038b16551466d94fed14bd3

# 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/stripe")
async def handle_stripe_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")

    sig_header = request.headers.get("stripe-signature", "")
    parts = dict(item.split("=", 1) for item in sig_header.split(",") if "=" in item)
    timestamp = parts.get("t", "")
    v1_sig = parts.get("v1", "")

    if not timestamp or abs(int(time.time()) - int(timestamp)) > 300:
        raise HTTPException(status_code=400, detail="Webhook timestamp outside tolerance")

    signed_payload = f"{timestamp}.".encode("utf-8") + raw_body
    expected = hmac.new(secret, signed_payload, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, v1_sig):
        raise HTTPException(status_code=400, detail="Invalid Stripe signature")

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

f44b8a1064864dbeebd8b41cdad13a6526e6988a6038b16551466d94fed14bd3

Untouched raw request bytes (indentation and newlines preserved).

2. Re-Serialized JSON HMACMismatch

d4db3d9068dd15cb4019ca1947e732a5cca99b64fd574532aee384f5256218ac

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 (Stripe + FastAPI)

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

Server Exception / Webhook Delivery Log

stripe.error.SignatureVerificationError: No signatures found matching the expected signature for payload

Raw Request Stream Handling & Replay Protection in Stripe + FastAPI

FastAPI's automatic Pydantic request-body deserialization is a huge productivity win for REST endpoints; but it is the #1 cause of broken Stripe webhooks in Python backends. If you declare a webhook route like async def stripe_webhook(payload: dict) or async def stripe_webhook(event: StripeEvent), FastAPI parses the JSON into a Python dict before your function runs, making it impossible to recover the exact raw byte stream Stripe signed.

To verify Stripe signatures reliably in FastAPI, inject Starlette's raw Request object (request: Request) without a Pydantic body parameter and read raw_body: bytes = await request.body(). Passing raw_body directly to stripe.Webhook.construct_event(payload=raw_body, sig_header=sig_header, secret=webhook_secret); or computing hashlib.sha256 HMAC over f"{timestamp}.".encode() + raw_body with hmac.compare_digest(); guarantees exact byte-level parity.

Be mindful of FastAPI's 307 trailing-slash redirect behavior when mounting webhook routers. If Stripe posts to https://api.example.com/webhooks/stripe while your FastAPI router declares @router.post("/webhooks/stripe/"), FastAPI responds with a 307 Temporary Redirect that Stripe treats as a failed delivery. Always match the exact URL path with no trailing-slash discrepancy.

To prevent Stripe timeouts under load, offload database syncing, invoice PDF generation, or onboarding emails to FastAPI BackgroundTasks (for lightweight tasks) or a Celery + Redis worker (for durable retries) and return {"received": True} with HTTP 200 immediately after verifying the signature.

Test your exact raw JSON vs. re-serialized Python json.dumps() digest behavior using the live browser Web Crypto verifier above before pushing your FastAPI webhook endpoint to staging or production.

For high-reliability Python FastAPI billing pipelines behind Nginx and Uvicorn, pair raw-body signature verification with structured logging of event.id, event.type, and verification latency while keeping STRIPE_WEBHOOK_SECRET wrapped in Pydantic SecretStr. Using a durable Redis + Celery worker for subscription fulfillment guarantees FastAPI replies HTTP 200 to Stripe in milliseconds even when downstream ERP or email providers experience latency spikes.

Step-by-Step Stripe + 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. 1Read Raw Bytes With await request.body() Before Parsing JSON

    app/routers/stripe_webhooks.py

    Avoid Pydantic body parameters on webhook endpoints; inject Request and pass raw_body bytes straight into stripe.Webhook.construct_event().

    app/routers/stripe_webhooks.pypython
    import os
    import stripe
    from fastapi import APIRouter, BackgroundTasks, Header, HTTPException, Request
    
    router = APIRouter(prefix="/webhooks", tags=["webhooks"])
    
    def process_subscription_event(event_id: str, event_type: str, data: dict):
        # Idempotent DB update or Celery task dispatch
        pass
    
    @router.post("/stripe")
    async def stripe_webhook(
        request: Request,
        background_tasks: BackgroundTasks,
        stripe_signature: str | None = Header(default=None, alias="Stripe-Signature"),
    ):
        raw_body: bytes = await request.body()
        webhook_secret = os.environ["STRIPE_WEBHOOK_SECRET"]
    
        if not stripe_signature:
            raise HTTPException(status_code=400, detail="Missing Stripe-Signature header")
    
        try:
            event = stripe.Webhook.construct_event(
                payload=raw_body,
                sig_header=stripe_signature,
                secret=webhook_secret,
            )
        except (ValueError, stripe.error.SignatureVerificationError) as exc:
            raise HTTPException(status_code=400, detail=f"Invalid signature: {exc}")
    
        background_tasks.add_task(
            process_subscription_event,
            event["id"],
            event["type"],
            event["data"]["object"],
        )
        return {"received": True}
  2. 2Verify Manually With Standard Library hmac.compare_digest (Zero SDK)

    app/utils/stripe_hmac.py

    If you prefer verifying Stripe signatures without importing the Stripe SDK, use Python's hashlib, hmac, and hmac.compare_digest() with a 300-second timestamp check.

    app/utils/stripe_hmac.pypython
    import hashlib
    import hmac
    import time
    
    def verify_stripe_raw(raw_body: bytes, sig_header: str, secret: str, tolerance: int = 300) -> bool:
        timestamp = ""
        v1_sigs: list[str] = []
        for part in sig_header.split(","):
            if "=" not in part:
                continue
            k, v = part.strip().split("=", 1)
            if k == "t":
                timestamp = v
            elif k == "v1":
                v1_sigs.append(v)
    
        if not timestamp or abs(int(time.time()) - int(timestamp)) > tolerance:
            return False
    
        signed = f"{timestamp}.".encode("utf-8") + raw_body
        expected = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest()
        return any(hmac.compare_digest(expected, sig) for sig in v1_sigs)
  3. 3Register the Webhook Router Without Trailing-Slash Redirects

    app/main.py

    Mount the router cleanly so POST /webhooks/stripe hits the handler directly with HTTP 200 rather than a 307 redirect.

    app/main.pypython
    from fastapi import FastAPI
    from app.routers.stripe_webhooks import router as stripe_router
    
    app = FastAPI()
    app.include_router(stripe_router)
  4. 4Test Live Events Against Uvicorn Port 8000

    terminal

    Run Uvicorn and forward test events via Stripe CLI to verify 200 OK status and signature matching.

    terminalbash
    uvicorn app.main:app --reload --port 8000
    stripe listen --forward-to http://127.0.0.1:8000/webhooks/stripe

Common Stripe + FastAPI Webhook Pitfalls

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

Pitfall 1

Using payload: dict or BaseModel Parameter on the Webhook Route

Declaring payload: dict forces FastAPI to parse JSON first, and calling json.dumps(payload) produces spaces/escapes that differ from Stripe's raw bytes; breaking HMAC verification.

Pitfall 2

Custom Starlette BaseHTTPMiddleware Consuming request.body() Early

Logging or auditing middleware built on Starlette BaseHTTPMiddleware that awaits request.body() can stall or alter stream reads on downstream endpoints. Keep webhook routes lean or use pure ASGI middleware.

Pitfall 3

Trailing Slash 307 Redirects Rejecting Stripe Deliveries

If Stripe sends POST /webhooks/stripe and FastAPI redirects to /webhooks/stripe/ via 307, Stripe marks the delivery failed. Always match your exact path string in both FastAPI and Stripe Dashboard.

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 await request.body() return bytes instead of str in FastAPI?
HMAC operates over raw bytes. Passing raw_body bytes directly to hmac.new(.., raw_body, hashlib.sha256) or stripe.Webhook.construct_event() avoids accidental UTF-8 decoding or line-ending normalization.
Can I call await request.json() AFTER await request.body() in FastAPI?
Yes. Starlette caches the body bytes on the Request instance after await request.body(), or even better, simply parse json.loads(raw_body) once signature verification succeeds.
Should I use BackgroundTasks or Celery for FastAPI Stripe webhooks?
BackgroundTasks is fine for quick non-critical operations, but if your FastAPI container restarts mid-task, BackgroundTasks jobs are lost. For billing and fulfillment, enqueue durable Celery or Dramatiq tasks backed by Redis.
Why does hmac.compare_digest() matter over == in Python?
Standard == exits on the first mismatched byte, leaking timing information over thousands of requests. hmac.compare_digest() runs in constant time and prevents timing side-channel attacks.
Browse all 10 webhook guides →