Skip to main content

What Are Webhooks? How They Work and How They Automate Your Business

In this article

A webhook is a message one system sends to another the moment something happens. Technically it is an HTTP POST to a web address you have given the other system, with the details of the event as JSON in the body. Instead of your website asking Stripe every few seconds whether a payment has gone through, Stripe tells your website when it has. That reversal, from asking to being told, is the whole idea, and it is what lets a business run a chain of actions with nobody in the loop.

Our own UK Name Change service is a plain example. A customer fills in a form and pays through Stripe. Stripe sends a webhook to the site saying the payment succeeded. The site generates the legally formatted deed poll automatically, ready for us to print and post. More than 160,000 names have been changed that way. The parts that make it dependable are not the happy path but the three things this guide spends most of its time on: signatures, retries and idempotency.

How a webhook works

  1. You give the sending system a URL on your site, for example /webhooks/stripe/, and choose which events you want to hear about.
  2. Something happens: a payment succeeds, a subscription renews, an invoice is paid in Xero, a parcel is scanned.
  3. The sender POSTs a JSON document to your URL. It carries an event id, an event type, a timestamp and the data: the order, the customer, the amount.
  4. Your site checks the message is genuine, records it, and replies with a success code straight away.
  5. Your site then does the work: marks the order paid, generates the document, sends the email.
  6. If your site did not reply with success, the sender tries again later, usually several times over hours or days.

A typical event body, trimmed, looks like this:

{
  "id": "evt_1QbX8s2eZvKYlo2C",
  "type": "payment_intent.succeeded",
  "created": 1760602860,
  "data": {
    "object": {
      "id": "pi_3QbX8r2eZvKYlo2C",
      "amount": 4500,
      "currency": "gbp",
      "metadata": {"order_id": "10482"}
    }
  }
}

The metadata is the useful trick. When your site creates the payment it attaches your own order number, so when the event comes back you know exactly which record to update.

Compared with polling

The alternative is polling: your server asks the other system "anything new?" on a timer. Polling is simple and sometimes right, for example when a provider offers no webhooks, but it has two costs. The delay is the length of the timer, so a two-minute poll means a customer waits up to two minutes for a receipt. And most polls return nothing, which wastes your server's time and uses up the provider's rate limit. A webhook arrives within seconds of the event and costs nothing until something happens.

The same trade-off exists inside the browser, where it is the difference between refreshing a page and a live connection; WebSockets versus HTTP polling covers that side.

Three webhooks most businesses already depend on

Payment succeeded

When a customer pays on your site the money moves on Stripe's servers, not yours, so the only reliable way to know it worked is Stripe's payment_intent.succeeded or checkout.session.completed event. The handler marks the order paid, kicks off fulfilment and sends the receipt. Do not do any of that from the page the customer is sent back to after paying; they can close the tab before it loads. A booking system has the same rule, which is why a custom booking app confirms from the webhook, not the redirect.

New enquiry, straight to the team

Webhooks go out as well as in. When someone submits a quote form, your site can POST to Slack's incoming webhook URL so a message appears in the sales channel within a second. It can also POST to your CRM so the lead is created with the form data attached. Nobody checks an inbox, and nobody retypes anything.

Subscription payment failed

A renewal fails because a card has expired. The invoice.payment_failed event arrives, your app pauses access or starts a grace period, and an email asks for a new card. Stripe retries the charge on its own schedule and sends another event when it succeeds, at which point access is restored. The subscription state in your database is driven entirely by these events, which is the pattern described in running subscription e-commerce properly.

Signatures: proving the message is genuine

Your webhook URL is public. Anyone who guesses it can POST a fake "payment succeeded" event, and a naive handler would ship the order. Every serious provider therefore signs each message.

Stripe takes a secret it shares with you when you register the endpoint and computes an HMAC-SHA256 of the timestamp and the raw body. It sends the result in a Stripe-Signature header. Your handler recomputes the signature from the raw bytes it received and compares the two. If they differ, or if the timestamp is more than a few minutes old (which blocks a replayed copy of a real message), the request is rejected with a 400 and nothing happens.

Two details catch people out. The signature is computed over the raw request body, so any framework setting that parses or re-encodes JSON before you see it will break verification. And the endpoint must be exempt from Django's CSRF protection, because Stripe is not a browser and has no CSRF token; the signature does the job CSRF would have done.

Retries: why your handler will be called twice

If your server is down, slow, or replies with anything other than a success code, the sender assumes the message was lost. It sends it again, with growing gaps between attempts, for hours or days. That is good: a deploy or an outage does not lose you an order. It also means two things your code has to be built for.

First, reply fast. Verify the signature, write the event to your database, hand the real work to a background job, and return 200 within a second or two. A handler that generates a PDF and sends an email before replying will time out under load, which triggers a retry, which generates a second PDF.

Second, expect duplicates and out-of-order delivery. A retry of a message you did process arrives as if new. A later event can arrive before an earlier one. Your handler cannot assume it has seen each event once, in order.

Idempotency: doing it once however many times you are told

An idempotent handler produces the same result whether it runs once or five times for the same event. The simplest way to get there is to store every event id in a table with a unique constraint, and only act when the insert succeeds:

@csrf_exempt
@require_POST
def stripe_webhook(request):
    try:
        event = stripe.Webhook.construct_event(
            request.body,
            request.headers["Stripe-Signature"],
            settings.STRIPE_WEBHOOK_SECRET,
        )
    except (ValueError, stripe.SignatureVerificationError):
        return HttpResponseBadRequest()

    _, created = WebhookEvent.objects.get_or_create(
        event_id=event["id"], defaults={"payload": event}
    )
    if created:
        handle_stripe_event.delay(event["id"])
    return HttpResponse(status=200)

The background job then does the work in a database transaction. The work itself is written so that repeating it is harmless. That means "set the order to paid" rather than "add the payment to the total", and "send the receipt if it has not been sent" rather than "send the receipt".

The unique constraint stops two copies of the same event being recorded. Together, that is what lets UK Name Change say that no order is missed and none is charged or emailed twice. The same discipline applies to API calls your site makes to other systems, where an idempotency key does the equivalent job in the other direction.

Sending your own webhooks

If you run a platform, your customers will eventually want to be told when things happen in it, and you become the sender. The rules are the mirror image of the ones above:

  • Let each customer register a URL and choose events.
  • Sign every message with a secret unique to that endpoint.
  • Retry failures with increasing delays and stop after a sensible limit.
  • Keep a log of every attempt that the customer can see.
  • Never send anything you would not want in their server logs.

On our web platform builds outbound webhooks are a later stage, after the core product and its own inbound integrations are in use.

Questions people ask

What is the difference between a webhook and an API?

An API answers when your system asks. A webhook is the other system telling you something happened, without being asked. Most integrations use both: your site calls the API to start something and receives a webhook when it finishes.

Are webhooks secure?

They are when the message is signed and the handler verifies the signature and timestamp before doing anything. An unsigned webhook endpoint that trusts whatever it receives is a way for a stranger to mark their own order as paid.

What happens if my server is down when a webhook is sent?

The sender keeps retrying, usually for hours or days, until it gets a success reply. As long as your handler is idempotent, the delayed delivery is processed once and nothing is lost.

Can I use webhooks without a developer?

For simple cases, yes: tools such as Zapier and Make can receive a webhook and pass the data on. They are fine for "form to spreadsheet". For anything that moves money or changes an order, you want signatures, retries and idempotency handled in code you control.

How we handle this on our own builds

Every webhook endpoint we ship verifies the signature, records the event id under a unique constraint, and replies within a second. It does the real work in a background job that is safe to repeat. Every provider's test events are run against the handler before launch. Stripe's command-line tool forwards real test events to a local machine, so the handler is exercised before it ever reaches staging.

After launch, the failure mode of a webhook is silence: nothing arrives, nothing breaks visibly, and you find out when a customer asks where their order is. So we log every event received, alert when a feed that normally delivers several events an hour goes quiet, and check the provider's dashboard for failed deliveries after every deploy. None of it is glamorous, and it is the difference between automation you can forget about and automation that needs watching.