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:
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.
1Read Raw Bytes With await request.body() Before Parsing JSON
app/routers/stripe_webhooks.pyAvoid Pydantic body parameters on webhook endpoints; inject Request and pass raw_body bytes straight into stripe.Webhook.construct_event().
app/routers/stripe_webhooks.pypythonimport 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}2Verify Manually With Standard Library hmac.compare_digest (Zero SDK)
app/utils/stripe_hmac.pyIf 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.pypythonimport 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)3Register the Webhook Router Without Trailing-Slash Redirects
app/main.pyMount the router cleanly so POST /webhooks/stripe hits the handler directly with HTTP 200 rather than a 307 redirect.
app/main.pypythonfrom fastapi import FastAPI from app.routers.stripe_webhooks import router as stripe_router app = FastAPI() app.include_router(stripe_router)4Test Live Events Against Uvicorn Port 8000
terminalRun Uvicorn and forward test events via Stripe CLI to verify 200 OK status and signature matching.
terminalbashuvicorn 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.
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.
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.
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.
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 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.
Related Webhook HMAC Verification Guides
Browse all 10 webhook guides →Shopify Base64 HMAC Webhook Verification in Python FastAPI
Fix Shopify X-Shopify-Hmac-Sha256 webhooks in Python FastAPI. Use base64.b64encode on raw digest bytes, await request.body(), and hmac.compare_digest.
Stripe Webhook Signature Verification in Laravel (Raw Body & CSRF Fix)
Fix Stripe SignatureVerificationException in Laravel 11/12 using $request->getContent(), CSRF exclusion in bootstrap/app.php, hash_equals, and async queues.
Stripe Webhook Verification in Next.js App Router (request.text() Guide)
Fix Stripe webhook signature mismatch in Next.js App Router Route Handlers. Use await request.text() instead of request.json() with timingSafeEqual.
Stripe Webhook Verification in Node.js Express (express.raw() Order Fix)
Fix Stripe webhook signature mismatch in Express.js. Mount express.raw({ type: "application/json" }) before express.json() and verify with timingSafeEqual.