Stripe webhooks are how your application learns about billing events it did not initiate. Renewals succeed or fail, customers cancel in the billing portal, disputes arrive weeks later. If your webhook endpoint accepts unverified requests, anyone who finds the URL can tell your system that an invoice was paid. If it processes events carelessly, retries and out-of-order delivery slowly push your database out of sync with what customers actually pay for.
This is the pattern I use in Django for webhooks that are both secure and reliable.
How Stripe signs webhook events
Every webhook request includes a Stripe-Signature header containing a timestamp (t=) and one or more signatures (v1=). Stripe computes the signature as an HMAC-SHA256 of the string "{timestamp}.{raw_request_body}", keyed with your endpoint’s signing secret (the value that starts with whsec_).
To verify a request, you recompute that HMAC over the exact bytes you received and compare the results in constant time. You also check that the timestamp is recent, which protects against replayed requests. The official stripe Python library does all of this in one call, so there is no reason to hand-roll it.
The key detail is in the definition: the signature covers the raw body. If you verify anything else, such as request.POST, a parsed and re-serialised JSON dict, or a body a proxy has modified, verification fails, as it should.
The webhook view
A plain Django view gives you direct access to the raw bytes in request.body:
# billing/views.py
import json
import stripe
from django.conf import settings
from django.db import transaction
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .models import StripeEvent
from .tasks import process_stripe_event
@csrf_exempt
@require_POST
def stripe_webhook(request):
payload = request.body # raw bytes: exactly what Stripe signed
signature = request.headers.get("Stripe-Signature", "")
try:
event = stripe.Webhook.construct_event(
payload, signature, settings.STRIPE_WEBHOOK_SECRET
)
except ValueError:
return HttpResponse(status=400) # body is not valid JSON
except stripe.SignatureVerificationError:
return HttpResponse(status=400) # signature or timestamp check failed
with transaction.atomic():
record, created = StripeEvent.objects.get_or_create(
event_id=event["id"],
defaults={"type": event["type"], "payload": json.loads(payload)},
)
if created:
transaction.on_commit(lambda: process_stripe_event.delay(record.pk))
return HttpResponse(status=200)
A few deliberate choices here:
csrf_exempt: Stripe cannot send a CSRF token. The signature check is the authentication for this endpoint.- Verification happens first. Nothing is parsed, stored or acted on until the signature is valid.
- The endpoint does almost no work. It verifies, records and enqueues, then returns
200. Stripe treats slow or failing responses as delivery failures and retries them. transaction.on_commitmakes sure the background task is only queued once the event row is actually committed.
If your project uses Django REST Framework, keep this endpoint as a plain Django view. DRF’s request parsing can consume or transform the body before you get to verify it.
Store every event exactly once
Stripe guarantees at-least-once delivery, so the same event can arrive twice. A unique constraint on the event ID turns duplicates into a no-op:
# billing/models.py
from django.db import models
class StripeEvent(models.Model):
event_id = models.CharField(max_length=255, unique=True)
type = models.CharField(max_length=255)
payload = models.JSONField()
received_at = models.DateTimeField(auto_now_add=True)
processed_at = models.DateTimeField(null=True, blank=True)
class Meta:
indexes = [models.Index(fields=["type", "processed_at"])]
This table also gives you an audit trail of every billing event your system has seen. That is invaluable when a customer asks why their access changed.
Process in the background, idempotently
The background task does the real work. The most robust approach is to treat the event as a notification that something changed and fetch the current state from Stripe, rather than applying the event’s snapshot as a delta. Events can arrive out of order, so a customer.subscription.updated from two minutes ago must not overwrite a newer state.
# billing/tasks.py
import stripe
from celery import shared_task
from django.utils import timezone
from .models import StripeEvent
from .services import sync_subscription
SUBSCRIPTION_EVENTS = {
"customer.subscription.created",
"customer.subscription.updated",
"customer.subscription.deleted",
}
@shared_task(bind=True, max_retries=5, default_retry_delay=30)
def process_stripe_event(self, record_id):
record = StripeEvent.objects.get(pk=record_id)
if record.processed_at:
return # already handled
obj = record.payload["data"]["object"]
try:
if record.type in SUBSCRIPTION_EVENTS:
subscription = stripe.Subscription.retrieve(obj["id"])
sync_subscription(subscription) # idempotent: writes the latest state
elif record.type == "invoice.payment_failed":
subscription_id = obj.get("subscription")
if subscription_id:
sync_subscription(stripe.Subscription.retrieve(subscription_id))
except stripe.StripeError as exc:
raise self.retry(exc=exc)
record.processed_at = timezone.now()
record.save(update_fields=["processed_at"])
sync_subscription should write the subscription’s status, price and current period into your own tables and derive entitlements from that state. Because it always writes the latest state, running it twice is harmless.
Add a periodic task that re-queues events still unprocessed after a few minutes. Then a worker crash or a broker outage cannot silently drop a billing event.
Testing locally with the Stripe CLI
The Stripe CLI forwards real, signed test events to your machine:
stripe listen --forward-to localhost:8000/webhooks/stripe/
# prints a signing secret (whsec_...) for this session; put it in STRIPE_WEBHOOK_SECRET
stripe trigger customer.subscription.created
Remember that the CLI’s signing secret differs from the secret of the endpoint you register in the Dashboard. Using the wrong one is the most common cause of SignatureVerificationError.
Checklist
- Verify the signature on the raw body before anything else
- Use the correct signing secret per environment and endpoint
- Exempt only this view from CSRF
- Record event IDs with a unique constraint
- Return
200quickly and process in the background - Sync the latest state from Stripe instead of trusting event order
- Re-queue events that were never processed
- Keep the server clock in sync (NTP), because timestamp tolerance depends on it
Webhooks are where most billing bugs hide, and this pattern removes the usual ones. If you are building subscription or usage-based billing and want a second pair of eyes, see my Stripe integration service.