Skip to content

Expert Answers to Your Magento, Shopify & Shopware Questions

Vendor-neutral, engineer-written explanations. Clear definitions first, then practical steps with real examples — no fluff.

Stagebit builds and maintains stores on Magento, Adobe Commerce, Shopify, Shopware, and Laravel, and this library holds the questions our own engineers get asked most often on each platform.

How do I verify and secure incoming webhooks in Laravel?

SB
Written by Stagebit Engineering Team
Updated November 2026 8 min read Verified by engineers

You verify incoming webhooks in Laravel by checking a signature that only the sender and your application can produce. You then secure the endpoint so that replayed, flooded, or slow requests cannot do damage. Because anyone can post to a public URL, never trust a request just because it reaches your route.

Quick answer

To verify incoming webhooks in Laravel, compute an HMAC of the raw body and compare it to the signature header, or use the sender’s official SDK. Serve the route over HTTPS, exclude it from CSRF protection, and ignore event IDs you have already processed. Then validate the event against your own records, rate limit the route, and return a 2xx response before processing the payload in a queued job. The spatie/laravel-webhook-client package covers signature checks, payload storage, and queuing for senders that sign the request body with HMAC.

How to verify incoming webhooks in Laravel step by step

Diagram of the steps that verify incoming webhooks in Laravel: rate limit, signature check, event validation, ID record, 2xx reply, queued job

1. Serve the webhook endpoint over HTTPS only

HTTPS protects the request in transit, while a signature proves who sent it and that the body is unaltered. You need both. Stripe, for example, requires HTTPS for live-mode webhook endpoints, as its webhook documentation explains.

Also watch for redirects. Stripe treats a 3xx response as a failed delivery, so register the final URL after any HTTP-to-HTTPS or www redirect.

2. Exclude the webhook route from CSRF protection

Webhook senders cannot send a CSRF token, so Laravel rejects their requests to any route in the web middleware group unless you exclude it.

Laravel’s CSRF documentation recommends keeping these routes outside the web middleware group. If that is impractical, add the URI to the exclusion list in bootstrap/app.php. Laravel 11 and 12 use validateCsrfTokens, and Laravel 13 uses preventRequestForgery.

// Laravel 13
$middleware->preventRequestForgery(except: [
    'webhooks/*',
]);

// Laravel 11 and 12
$middleware->validateCsrfTokens(except: [
    'webhooks/*',
]);

Older versions use the $except array in the VerifyCsrfToken middleware instead. Exclude only the webhook routes, because the exclusion does not authenticate the sender. If the sender reports a 419 response, the exclusion is missing or the URI pattern does not match.

Be careful when you test. Laravel disables the CSRF middleware in automated tests, so a missing exclusion passes your test suite and fails in production. Send a real test delivery from the sender, such as one from the Stripe CLI, before you go live.

3. Verify the webhook signature against the raw body

Read the body with $request->getContent() and compute the HMAC over those exact bytes. Decoding and re-encoding JSON can change whitespace and character escaping, so the hash no longer matches. Compare the result with hash_equals(), which runs in constant time.

// use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response;
class VerifyWebhookSignature
{
    public function handle(Request $request, Closure $next): Response
    {
        $secret = config('services.acme.webhook_secret');
        abort_if(blank($secret), 500, 'Webhook secret is not configured');

        $expected = hash_hmac('sha256', $request->getContent(), $secret);
        $received = $request->header('X-Signature', '');

        abort_unless(hash_equals($expected, $received), 401);

        return $next($request);
    }
}

The header name, the encoding (hex or base64), and any prefix such as sha256= differ by sender, so match the sender’s documentation exactly. Some senders also sign a timestamp together with the body. In that case, the string you hash includes more than the body.

4. Use the sender’s official SDK when one exists

Stripe signs the timestamp and the raw body joined by a dot, and its Stripe-Signature header carries the timestamp plus one or more signatures. A plain HMAC of the body therefore never matches. Use Stripe’s PHP library instead of the middleware above.

// composer require stripe/stripe-php
// .env: STRIPE_WEBHOOK_SECRET=whsec_...
// config/services.php: 'stripe' => ['webhook_secret' => env('STRIPE_WEBHOOK_SECRET')]
use Stripe\Webhook;
use Stripe\Exception\SignatureVerificationException;
use UnexpectedValueException;

try {
    $event = Webhook::constructEvent(
        $request->getContent(),
        $request->header('Stripe-Signature', ''),
        config('services.stripe.webhook_secret')
    );
} catch (UnexpectedValueException $e) {
    abort(400, 'Invalid webhook payload');
} catch (SignatureVerificationException $e) {
    abort(401, 'Invalid webhook signature');
}

This example handles Stripe’s snapshot events. Stripe’s newer thin event format uses a different handler in its SDKs, so check Stripe’s documentation if you register thin events.

If your application already uses Laravel Cashier, use the webhook controller and signature verification it provides instead of writing your own. Cashier’s documentation says the STRIPE_WEBHOOK_SECRET variable is what ensures incoming webhooks come from Stripe. In practice, a missing secret in production switches verification off.

Check this first if every signature fails

  • Hash $request->getContent(), and avoid a re-encoded copy of $request->all().
  • Check that you use the secret for the right environment, since Stripe, for one, issues different secrets for test and live mode.
  • Make sure no proxy, gateway, or middleware rewrites the body before it reaches your application.

5. Validate the event before acting on it

A valid signature confirms the request was signed with your secret. It does not make every field safe for your business logic. Before you change anything, check the event type, the required fields, and the data types.

if ($event->type !== 'payment_intent.succeeded') {
    return response()->noContent(); // acknowledge events you do not handle
}

$intent = $event->data->object;

abort_if(empty($intent->id) || ! isset($intent->amount), 400);

Return a 2xx response for event types you ignore, because a non-2xx response tells many senders to retry. For payments, also compare the amount, currency, status, and referenced order against your own records. Never act on a customer ID or order ID from the payload without looking it up in your database first.

Do not assume events arrive in order, either. Stripe, for example, does not guarantee delivery in the order it generated events, so fetch the current object state when order matters.

6. Reject replayed deliveries

A valid signature proves who sent a request, not that the request is new. Anyone who captures a signed request can send it again. Two checks close that gap, and they solve different problems.

  • Timestamp window: If the sender signs a timestamp, reject requests outside a tolerance of a few minutes. Stripe’s libraries default to five minutes, and a tolerance of 0 disables the check entirely, so never set it to 0.
  • Event ID: Store each delivery or event ID in a table with a unique index, and ignore IDs you have already seen. Stripe recommends tracking event IDs for this reason, since a genuine delivery can arrive more than once inside the timestamp window.
// Requires a unique index on webhook_events.event_id
// For Stripe, use $event->id instead of a header
$eventId = $request->header('X-Event-Id');
abort_if(blank($eventId), 400);

$inserted = DB::table('webhook_events')->insertOrIgnore([
    'event_id' => $eventId,
    'received_at' => now(),
]);

if ($inserted === 0) {
    return response()->noContent(); // already handled
}

Record the ID last, after the signature and event checks pass. Otherwise a request you rejected for bad data would look like a duplicate when the sender retries it. A single insert against a unique index also avoids the race that a separate check-then-insert pair creates when two copies arrive together.

Because you acknowledge the delivery before processing, your own queue retries must recover from processing failures. Stripe retries failed deliveries for up to three days in live mode, which is why the ID check matters. Configure job retries and the failed jobs table to match.

7. Rate limit and restrict the webhook endpoint

Define a named limiter, then attach it to the route with the throttle middleware.

// AppServiceProvider::boot()
RateLimiter::for('webhooks', function (Request $request) {
    return Limit::perMinute(120)->by($request->ip());
});

// routes/web.php or routes/api.php
Route::post('/webhooks/acme', AcmeWebhookController::class)
    ->middleware(['throttle:webhooks', VerifyWebhookSignature::class]);

The value 120 is an example, so size the limit from the sender’s real peak delivery rate. Otherwise you will drop genuine events. Keying on IP also fails when the sender uses only a few addresses.

The same happens behind a load balancer that has no trusted proxies configured, because every request then appears to come from one address.

Two further layers sit outside Laravel. First, cap the request body size at your web server or reverse proxy, for example with client_max_body_size in Nginx, so oversized payloads never reach PHP. Second, restrict the route by source address where the sender allows it.

Stripe, for example, publishes the IP addresses it sends webhooks from and recommends allowlisting them alongside signature verification. Keep any allowlist current, because senders can change their ranges. The signature check must still run on every request.

8. Acknowledge fast and queue the work

After the signature, validation, and event ID checks pass, call ProcessAcmeEvent::dispatch($request->getContent()) and return a 2xx response. Stripe’s documentation tells you to return the 2xx before any complex logic that could time out. Slow work such as API calls and database writes therefore belongs inside the job.

Write the job so a retry is safe. Check the current state before side effects such as sending an email or marking an invoice paid, because a queued job can run again after a partial failure.

9. Protect the secret and log safely

Webhook signing secrets are credentials. Anyone who obtains one can forge requests that pass your verification.

  • Store secrets in environment variables or a secrets manager, and read them through a config file.
  • Never commit them, expose them in frontend code or API responses, or write them to logs.
  • Use a separate secret for each sender and endpoint where the sender supports it.
  • Rotate a secret periodically, and rotate it immediately if you suspect a leak.

Some senders help with rotation. Stripe, for example, can keep the old secret active for up to seven days and sends one signature per active secret, so verification passes if any one matches. For senders that do not, accept both secrets yourself for a short window, then remove the old one.

Calling env() outside config files returns null once you cache your configuration, so map each secret in config/services.php. Logs help you investigate failed deliveries and spot attacks. However, full payloads and headers can expose customer data, so record only the following.

  • The sender, event ID, event type, and processing status.
  • The request timestamp and your response status.
  • Signature verification failures and processing errors.
Log::warning('Webhook signature verification failed.', [
    'provider' => 'stripe',
    'ip' => $request->ip(),
]);

Watch for repeated signature failures, unusual request volumes, and processing errors. They often point to an attack or a misconfigured secret before business operations suffer.

Should I use spatie/laravel-webhook-client instead of custom middleware?

The spatie/laravel-webhook-client package receives webhooks, verifies signatures, stores payloads, and runs your processing in a queued job. Its default validator computes an HMAC-SHA256 of the request body and compares it with hash_equals(). You can also swap in your own validator class when the sender signs differently.

The package adds a webhook_calls table and keeps each payload there. As a result, set a retention policy if payloads include personal data.

ConcernCustom middlewarespatie/laravel-webhook-client
Signature checkYou write it, as in step 3Default HMAC-SHA256 validator, or your own class
Payload storageNone unless you build itEach call stored in webhook_calls
Timestamp and event ID checksYou build them, as in step 6Not in the default setup; a custom webhook profile is the natural place
Best fitOne sender, a simple HMAC header, no extra tablesSeveral senders, or a stored record of every call

Recommended setup for a Laravel webhook endpoint

To verify incoming webhooks in Laravel from a single sender with an HMAC header, write the middleware from step 3 and keep the rest in your own code. It stays small and adds no tables. For Stripe, use the official library or Cashier.

Choose the package when you receive from several senders or want a stored record of every call. Whichever route you take, finish all nine steps, because a signature check alone leaves replays, floods, and slow handlers unaddressed. If you would rather have engineers build or audit the integration, see our Laravel development services.

Was this answer helpful?

Your feedback helps us improve our answers.

Still need help?

Questions about securing webhooks in Laravel?

If you're weighing how to verify and secure webhooks in your Laravel app, we're happy to walk through what you're seeing and what your options are.

Talk to Laravel Experts