Webhook HMAC-SHA256 Verifier · Stripe + Laravel

Stripe Webhook Signature Verification in Laravel (Raw Body & CSRF Fix)

Verify and generate Stripe + Laravel HMAC-SHA256 signatures locally using crypto.subtle. Compare raw-body vs re-serialized JSON hashes side by side and copy constant-time verification code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust payload/secret or load a test scenario2. Inspect live HMAC & diagnostics3. Copy handler code
Quick-Test Scenarios:

1. Provider, Secret & Header

Whitespace and line endings affect the HMAC digest. Edit the raw payload below to test byte-level changes.

Test Signature Generated·Stripe-Signature

Stripe-Signature: t=1795378346,v1=ed93e8400d4d139d1ca098f597ac996bca36f446138a3879ed0217e1bab1aef6

<?php
// app/Http/Controllers/StripeWebhookController.php (Laravel 11/12)
// Exclude '/webhooks/stripe' from CSRF in bootstrap/app.php:
// $middleware->validateCsrfTokens(except: ['webhooks/*']);

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class StripeWebhookController extends Controller
{
    public function __invoke(Request $request): Response
    {
        $rawBody = $request->getContent(); // Raw unparsed HTTP body bytes
        $sigHeader = (string) $request->header('Stripe-Signature', '');
        $secret = (string) config('services.stripe.webhook_secret');

        $parts = [];
        foreach (explode(',', $sigHeader) as $item) {
            [$k, $v] = array_pad(explode('=', trim($item), 2), 2, '');
            if ($k === 't') $parts['t'] = $v;
            if ($k === 'v1') $parts['v1'][] = $v;
        }

        $timestamp = $parts['t'] ?? '';
        $signatures = $parts['v1'] ?? [];

        if ($timestamp === '' || abs(time() - (int) $timestamp) > 300) {
            return response('Timestamp outside 5-minute replay window', 400);
        }

        $expected = hash_hmac('sha256', "{$timestamp}.{$rawBody}", $secret);
        $valid = collect($signatures)->contains(fn (string $sig) => hash_equals($expected, $sig));

        if (! $valid) {
            return response('Invalid Stripe signature', 400);
        }

        // Dispatch async job after verification so Stripe receives 200 OK quickly
        return response('OK', 200);
    }
}
1. Raw Body HMAC (HEX)Valid

ed93e8400d4d139d1ca098f597ac996bca36f446138a3879ed0217e1bab1aef6

Untouched raw request bytes (indentation and newlines preserved).

2. Re-Serialized JSON HMACMismatch

a317b0957a1e14c949acb466ee5f3116f7be0d63f22408fde3139691aecf083d

Digest produced if JSON middleware parses and re-encodes the body.

HMAC & Raw-Body Diagnostics

  • criticalRaw Body vs. Re-Serialized JSON Produces Two Different Signatures

    Notice in the comparison box below: hashing this exact raw payload produces a completely different HMAC than hashing JSON.stringify(JSON.parse(payload)). Never run express.json(), request.json(), or json_encode($request->all()) before verifying webhook signatures.

  • infoAlways Use Constant-Time Comparison (Never === or ==)

    Compare computed and received digests with hash_equals() (PHP/Laravel), hmac.compare_digest() (Python/FastAPI), crypto.timingSafeEqual() (Node.js/Next.js/Express), or CryptographicOperations.FixedTimeEquals() (ASP.NET Core) to prevent timing side-channel attacks.

Runs locally in your browser using window.crypto.subtle. Webhook secrets and payloads are never sent to a server.

Typical Webhook Signature Verification Error (Stripe + Laravel)

When middleware consumes the raw HTTP stream, JSON gets re-serialized before hashing, or encoding/prefixes mismatch in Stripe + Laravel, your server logs an exception matching the output below:

Server Exception / Webhook Delivery Log

Stripe\Exception\SignatureVerificationException: No signatures found matching the expected signature for payload

Raw Request Stream Handling & Replay Protection in Stripe + Laravel

Integrating Stripe webhooks into a Laravel 11 or Laravel 12 application is one of the highest-stakes backend workflows in SaaS engineering: billing upgrades, subscription renewals, and invoice failures all depend on verifying Stripe's Stripe-Signature header accurately. Yet even experienced PHP engineers routinely encounter Stripe\Exception\SignatureVerificationException or HTTP 419 Page Expired right when deploying to staging or production.

The root cause of almost every SignatureVerificationException is hashing re-serialized JSON instead of the raw HTTP request bytes. Stripe signs the literal string "{timestamp}.{raw_body}"; including every space, newline, and Unicode escape byte transmitted over TCP. Calling json_encode($request->all()) inside a Laravel controller alters formatting and key ordering, producing a completely different HMAC-SHA256 digest. In Laravel, you MUST read the untouched stream with $request->getContent().

Equally important in Laravel 11 and 12 is CSRF middleware exclusion. If you register your webhook endpoint inside routes/web.php (or any middleware group including ValidateCsrfToken), Laravel rejects Stripe's external POST request with HTTP 419 before your controller even executes. Either place webhook routes inside routes/api.php or explicitly exempt webhooks/* inside bootstrap/app.php via $middleware->validateCsrfTokens(except: ["webhooks/*"]).

Always verify the timestamp tolerance window (default 300 seconds / 5 minutes) to defeat replay attacks, compare digests with PHP's constant-time hash_equals() function rather than ===, and immediately dispatch heavy database or email work onto a Redis/MySQL Laravel queue job so Stripe receives an HTTP 200 OK within 200 milliseconds; preventing timeout retries and duplicate fulfillment.

Finally, double-check that STRIPE_WEBHOOK_SECRET in your production .env holds the endpoint-specific signing secret (starting with whsec_) from your live Stripe Dashboard rather than the temporary stripe listen CLI secret or your sk_live_ API key, and clear Laravel's config cache whenever rotating secrets.

In production Laravel billing systems, combine raw-body Stripe signature verification with a dedicated webhook_events ledger table indexed by unique stripe_event_id and processed_at columns. Logging rejected signature failures (without logging the raw secret) alongside HTTP status codes lets on-call engineers spot secret-rotation mismatches within seconds, while Laravel Horizon or Redis queue retries guarantee zero lost subscription upgrades during transient database blips.

Step-by-Step Stripe + Laravel 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.

  1. 1Exclude Webhook Routes From Laravel 11/12 CSRF Verification

    bootstrap/app.php

    Ensure external Stripe POST calls are never blocked with 419 Page Expired by either mounting them in routes/api.php or explicitly excluding webhooks/* in bootstrap/app.php.

    bootstrap/app.phpphp
    <?php
    
    use Illuminate\Foundation\Application;
    use Illuminate\Foundation\Configuration\Middleware;
    
    return Application::configure(basePath: dirname(__DIR__))
        ->withRouting(
            web: __DIR__.'/../routes/web.php',
            api: __DIR__.'/../routes/api.php',
        )
        ->withMiddleware(function (Middleware $middleware) {
            $middleware->validateCsrfTokens(except: [
                'webhooks/stripe',
            ]);
        })
        ->create();
  2. 2Verify Raw Request Bytes With $request->getContent() and Stripe SDK

    app/Http/Controllers/StripeWebhookController.php

    Pass $request->getContent() directly to Stripe\Webhook::constructEvent() (or manual hash_hmac + hash_equals) and dispatch an idempotent queued job immediately.

    app/Http/Controllers/StripeWebhookController.phpphp
    <?php
    
    namespace App\Http\Controllers;
    
    use App\Jobs\ProcessStripeEvent;
    use Illuminate\Http\Request;
    use Illuminate\Http\Response;
    use Stripe\Exception\SignatureVerificationException;
    use Stripe\Webhook;
    
    class StripeWebhookController extends Controller
    {
        public function __invoke(Request $request): Response
        {
            $rawBody = $request->getContent();
            $signature = (string) $request->header('Stripe-Signature', '');
            $secret = (string) config('services.stripe.webhook_secret');
    
            try {
                $event = Webhook::constructEvent($rawBody, $signature, $secret);
            } catch (SignatureVerificationException|\UnexpectedValueException $e) {
                return response('Invalid Stripe webhook signature', 400);
            }
    
            ProcessStripeEvent::dispatch($event->id, $event->type, $event->toArray());
    
            return response('Webhook handled', 200);
        }
    }
  3. 3Store Endpoint Secret in config/services.php for config:cache Compatibility

    config/services.php

    Never call env("STRIPE_WEBHOOK_SECRET") inside your controller; map it in config/services.php so php artisan config:cache preserves the secret in production.

    config/services.phpphp
    'stripe' => [
        'secret' => env('STRIPE_SECRET'),
        'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
    ],
  4. 4Test End-to-End Locally With Stripe CLI Before Deploying

    terminal

    Forward live test events to your local Laravel endpoint and confirm HTTP 200 OK with zero signature errors.

    terminalbash
    stripe listen --forward-to http://127.0.0.1:8000/api/webhooks/stripe
    stripe trigger checkout.session.completed

Common Stripe + Laravel Webhook Pitfalls

Avoid these three subtle production failure modes when verifying external webhook signatures.

Pitfall 1

Mixing Up Local stripe listen whsec_ Secret With Production Dashboard Secret

Every Stripe webhook endpoint has its own unique whsec_ signing secret. Leaving the temporary local CLI secret in production .env causes 100% of live webhooks to fail with SignatureVerificationException.

Pitfall 2

Using json_encode($request->all()) Instead of $request->getContent()

Re-encoding Laravel's parsed request array strips whitespace, escapes forward slashes differently, and alters float formatting; guaranteeing HMAC mismatch on every Stripe event.

Pitfall 3

Nginx 301 Trailing-Slash Redirects Turning POST Webhooks Into GET

If Stripe posts to https://api.example.com/api/webhooks/stripe and Nginx redirects to /api/webhooks/stripe/ via 301, Stripe does not follow redirects on webhooks and marks delivery as failed.

Related Tools

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:

Frequently Asked Questions

Why does Stripe return SignatureVerificationException only in production on Laravel?
Most often either php artisan config:cache made env("STRIPE_WEBHOOK_SECRET") return null (switch to config("services.stripe.webhook_secret")), or the production .env still has the local stripe listen signing secret instead of the live endpoint secret.
Should I use Laravel Cashier or a custom Stripe webhook controller?
Laravel Cashier ships with built-in VerifyWebhookSignature middleware and handles subscription lifecycle events cleanly. Use a custom controller when integrating one-off Checkout payments, Connect accounts, or non-Cashier billing schemas.
How do I make Laravel Stripe webhook processing idempotent?
Store each processed Stripe event ID ($event->id) in a unique database column (stripe_event_id) before applying credits or provisioning access. If Stripe retries the same event, skip duplicates cleanly and return HTTP 200.
Why does Stripe-Signature sometimes contain multiple v1= values?
During zero-downtime webhook secret rotation, Stripe signs payloads with both the old and new whsec_ secrets simultaneously (t=..,v1=sig1,v1=sig2). Always check whether ANY v1 token matches your expected digest via hash_equals().
Browse all 10 webhook guides →