Stripe retries webhooks, delivers them out of order, and anyone who finds your endpoint can POST to it. A handler that trusts the request or runs twice will eventually corrupt a customer's plan. Two rules fix most of it: verify the signature, and make processing idempotent.
1. Verify the signature on the raw body
Stripe signs the exact bytes it sends. Parse the JSON first and the signature check fails, so read the raw body.
@router.post("/billing/webhook", include_in_schema=False)
async def webhook(request: Request, session: AsyncSession = Depends(get_session),
settings: Settings = Depends(get_settings_dep)):
payload = await request.body()
try:
event = verify_signature(payload, request.headers.get("stripe-signature", ""),
settings.stripe_webhook_secret)
except SignatureError as e:
raise HTTPException(400, f"Invalid signature: {e}") from None
The Stripe-Signature header contains a timestamp t and one or more v1 signatures. The signed string is t + "." + payload, signed with HMAC-SHA256 using your endpoint secret. Compare in constant time, and reject timestamps older than a few minutes to block replays. The official stripe library does this for you with stripe.Webhook.construct_event.
2. Store processed event ids
Every event has a unique id. Keep a table of ids you already processed and return 200 for repeats.
class StripeEvent(Base):
__tablename__ = "stripe_events"
id: Mapped[int] = mapped_column(primary_key=True)
event_id: Mapped[str] = mapped_column(String(100), unique=True)
type: Mapped[str] = mapped_column(String(100))
processed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
event_id, etype = event.get("id", ""), event.get("type", "")
if await session.scalar(select(StripeEvent).where(StripeEvent.event_id == event_id)):
return {"received": True, "duplicate": True}
... # handle the event
session.add(StripeEvent(event_id=event_id, type=etype))
return {"received": True}
Do the work and the StripeEvent insert in the same transaction. If the handler fails, nothing is recorded and Stripe's retry processes the event again. The unique constraint is the real guard if two deliveries race.
3. Handle only what you need
For subscriptions the useful events are:
-
checkout.session.completed: link the Stripe customer and subscription ids to your organization. -
customer.subscription.createdand.updated: set the plan and status from the subscription object. -
customer.subscription.deleted: drop back to the free plan. -
invoice.payment_failed: mark the accountpast_dueand decide on a grace period.
Set the plan from the subscription events, not from the browser redirect after checkout, which the user can skip or fake.
4. Test it without a Stripe account
Sign your own test payloads with the same HMAC and post them to the endpoint. Test four cases: a valid event (200), a bad signature (400), the same event twice (second one reports duplicate), and an old timestamp (rejected).
Related
More SaaS backend plumbing (tenants, API keys, plan limits): https://extezzu.github.io/webtools/guides/fastapi-saas-backend-checklist/
Disclosure: this code comes from a commercial FastAPI starter we sell ($29, one-time): https://www.creem.io/product/prod_7LIIfd0Y6cBufZxtRTfNO9 . The snippets above stand on their own.
Top comments (0)