Flow of a Stripe webhook: verify, store, then reply

Handling Stripe Webhooks Without Losing a Payment

A payment that succeeds on Stripe but never reaches your database is the worst kind of bug. The customer paid, the order is still pending, and nobody gets an error. Webhooks are how Stripe tells your app what happened, so the handler has to be correct even when things go wrong.

Verify the signature first

Anyone can send a POST request to your webhook URL. Before you trust the body, check the Stripe-Signature header with your endpoint secret. The SDK does this in constructEvent(), and it also checks that the request is recent.

use Stripe\Webhook;
use Stripe\Exception\SignatureVerificationException;

public function __invoke(Request $request)
{
    try {
        $event = Webhook::constructEvent(
            $request->getContent(),
            $request->header('Stripe-Signature'),
            config('services.stripe.webhook_secret')
        );
    } catch (\UnexpectedValueException | SignatureVerificationException $e) {
        return response('Invalid', 400);
    }

    // continue below
}
Flow of a Stripe webhook: verify, store, then reply
Verify, check for a duplicate, queue the work, then reply with 200.

Reply fast and do the work later

Stripe expects a 2xx response within a few seconds. If you send the email, call a third-party API and update three tables before you reply, you risk a timeout. Stripe then retries the event, and now you have to deal with duplicates. The fix is to move the slow part into a queued job.

public function __invoke(Request $request)
{
    // ... verify the signature first (see above)

    if (WebhookEvent::where('stripe_id', $event->id)->exists()) {
        return response()->json(['ok' => true]); // already handled
    }

    ProcessStripeEvent::dispatch($event->id, $event->type, $event->data->toArray());

    return response()->json(['ok' => true]);
}

Make the handler idempotent

Stripe retries failed deliveries for up to three days, so the same event can arrive more than once. Store every event id in a table with a unique index. A second insert with the same id fails, and the job never runs twice.

Schema::create('webhook_events', function (Blueprint $table) {
    $table->id();
    $table->string('stripe_id')->unique();
    $table->string('type');
    $table->timestamp('processed_at')->nullable();
    $table->timestamps();
});
Code for an idempotency table with a unique stripe_id
The unique index on stripe_id is the real guard. The check in the controller just avoids extra work.

Test it on your machine

The Stripe CLI forwards real test events to your local app, so you can see the whole flow end to end without a deployed server.

stripe listen --forward-to http://localhost/stripe/webhook
stripe trigger invoice.paid

What to log

  • The event id and type, on every request, before any work starts.
  • The result of the job, including the reason when it fails. This is the first place I look when a customer says they paid.
  • Events you receive but do not handle. Log them as a warning, so new event types do not disappear silently.

The rule I keep to is simple: the webhook controller only verifies, records and dispatches. Everything else happens in a job that you can retry, inspect and run again.

Thanks for reading

Previous
Next
Umer
Mughal
</>
available now for work