WhatsApp· 5 min read

Receive WhatsApp webhooks in Laravel


Receive WhatsApp Cloud API webhooks in Laravel by registering a GET and a POST in a route file under the api middleware group. CSRF never applies there. The GET reads hub_mode, hub_verify_token and hub_challenge, with underscores, because PHP rewrites the dots. The POST hashes $request->getContent(), compares with hash_equals, dispatches a queued job and returns 200. Five files in a fresh Laravel 13 app are enough.

Start from a fresh Laravel 13 app

Laravel 13 was released on March 17th, 2026, and “requires a minimum PHP version of 8.3” (Laravel 13 release notes, accessed 2026-11-04). A new app uses SQLite by default, and the installer creates database/database.sqlite and runs the migrations (Laravel installation, accessed 2026-11-04). Those migrations include the jobs table for the queue and the cache table used for dedupe below.

composer global require laravel/installer
laravel new whatsapp-webhooks
cd whatsapp-webhooks
php artisan make:job ProcessWhatsAppWebhook

You’ll edit bootstrap/app.php, config/services.php and .env, create routes/webhooks.php by hand, and replace the generated job class.

Keep the routes out of the web group

Routes in routes/web.php get the web middleware group, “which provides features like session state and CSRF protection” (Laravel routing, accessed 2026-11-04). Meta’s POST carries no CSRF token, so a webhook there fails. The api group contains only SubstituteBindings (Laravel middleware, accessed 2026-11-04). The routing docs show how to load an extra route file with it through the then: callback. Replace the withRouting call in bootstrap/app.php:

// bootstrap/app.php (excerpt): add this import at the top
use Illuminate\Support\Facades\Route;

// ...and replace the ->withRouting(...) call
->withRouting(
    web: __DIR__.'/../routes/web.php',
    commands: __DIR__.'/../routes/console.php',
    health: '/up',
    then: function () {
        Route::middleware('api')
            ->prefix('webhooks')
            ->name('webhooks.')
            ->group(base_path('routes/webhooks.php'));
    },
)

Every route in routes/webhooks.php now lives under /webhooks/, with no session and no CSRF check. php artisan install:api would also give you a stateless file, but it installs Sanctum, which this endpoint doesn’t need.

If your webhook has to stay in web.php, exclude it instead. In Laravel 13 the middleware is PreventRequestForgery, and you pass the URIs to $middleware->preventRequestForgery(except: [...]) inside withMiddleware (Laravel CSRF, accessed 2026-11-04). Laravel 12 calls the same method validateCsrfTokens (Laravel 12 CSRF, accessed 2026-11-04). The Laravel 13 docs add that “the CSRF middleware is automatically disabled for all routes when running tests”. A feature test can pass while production answers Meta with a 419.

Add the secrets to the config

Laravel’s docs say to call env only from config files, because after config:cache “the env function will only return external, system level environment variables” (Laravel configuration, accessed 2026-11-04). Add a whatsapp entry to the array in config/services.php:

// config/services.php (excerpt): inside the returned array
'whatsapp' => [
    'app_secret' => env('WHATSAPP_APP_SECRET'),
    'verify_token' => env('WHATSAPP_VERIFY_TOKEN'),
],
# .env
WHATSAPP_APP_SECRET=APP_SECRET
WHATSAPP_VERIFY_TOKEN=VERIFY_TOKEN

The route file

<?php
// routes/webhooks.php

use App\Jobs\ProcessWhatsAppWebhook;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/whatsapp', function (Request $request) {
    $expected = config('services.whatsapp.verify_token');
    $challenge = $request->query('hub_challenge'); // PHP turns hub.challenge into hub_challenge

    if (is_string($expected) && $expected !== ''
        && $request->query('hub_mode') === 'subscribe'
        && $request->query('hub_verify_token') === $expected
        && is_string($challenge)) {
        return response($challenge, 200)->header('Content-Type', 'text/plain');
    }

    return response('', 403);
});

Route::post('/whatsapp', function (Request $request) {
    $secret = config('services.whatsapp.app_secret');
    if (!is_string($secret) || $secret === '') {
        abort(500, 'WHATSAPP_APP_SECRET is not set');
    }

    $raw = $request->getContent(); // the exact bytes Meta signed
    $header = $request->header('X-Hub-Signature-256');
    if (!is_string($header) || !str_starts_with($header, 'sha256=')) {
        return response('', 401);
    }
    $expected = hash_hmac('sha256', $raw, $secret);
    if (!hash_equals($expected, substr($header, 7))) { // user-supplied value goes second
        return response('', 401);
    }

    $payload = json_decode($raw, true);
    if (!is_array($payload)) {
        return response('', 400);
    }

    ProcessWhatsAppWebhook::dispatch($payload);

    return response('', 200);
});

In the App Dashboard, set the callback URL to https://YOUR_DOMAIN/webhooks/whatsapp, enter the verify token and subscribe to messages. Meta requires a valid certificate, and “Self-signed certificates are not supported” (Meta create a webhook endpoint, accessed 2026-11-04).

Read hub_mode, not hub.mode

php.net states that “Dots and spaces in variable names are converted to underscores” (PHP external variables, accessed 2026-11-04). Meta sends hub.mode, and the query bag holds hub_mode. Laravel’s query() also reads a dot as array nesting, so query('hub.mode') looks for a nested key that isn’t there (Laravel requests, accessed 2026-11-04). The conversion rule covers PHP-FPM and php artisan serve. If you run Laravel Octane, confirm how your server builds the query string before relying on it.

The challenge goes back as text/plain. Meta asks only for a 200 with the hub.challenge value and names no content type, so plain text is the safe choice. The Express guide covers the rest of Meta’s verification rules.

Hash the raw body

Laravel’s Request extends Symfony’s, and Symfony’s getContent() “Returns the request body content”, read from php://input (Symfony Request.php, accessed 2026-11-04). Hash those bytes. json_encode($request->all()) produces different bytes, with escaped slashes and \uXXXX sequences, and the check fails on real messages. The signature verification guide shows the failure with accents and emoji.

hash_hmac with the default $binary = false “outputs lowercase hexits”, the same format as the header after sha256= (hash_hmac, accessed 2026-11-04). For hash_equals, php.net says “It is important to provide the user-supplied string as the second parameter” (hash_equals, accessed 2026-11-04). A missing header comes back as null (Laravel requests, accessed 2026-11-04), which the is_string guard catches before hash_equals sees it.

Queue the job and return 200

Meta’s throughput page asks you to size your webhook server for a median latency of 250 ms or less. It re-delivers failed webhooks “for up to 7 days” (Meta throughput, accessed 2026-11-04). The route therefore does no work beyond the signature check. “In new Laravel applications, the database connection is defined as the default queue” (Laravel queues, accessed 2026-11-04). dispatch() therefore writes a row to jobs and the response leaves at once.

The job row survives a crash, unlike work run in the request process. Laravel’s deferred connection runs a job “after the HTTP response has been sent” but in the same process, and dispatchSync runs it before the response. Neither fits this route. Webhook queue architecture covers the design beyond one app.

The job: senders and dedupe

<?php
// app/Jobs/ProcessWhatsAppWebhook.php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

#[Tries(4)]
#[Backoff([1, 5, 10])]
class ProcessWhatsAppWebhook implements ShouldQueue
{
    use Queueable;

    private const DEDUPE_SECONDS = 8 * 24 * 60 * 60; // longer than Meta's 7-day retry window

    public function __construct(public array $payload)
    {
    }

    public function handle(): void
    {
        if (($this->payload['object'] ?? null) !== 'whatsapp_business_account') {
            return;
        }
        foreach ($this->payload['entry'] ?? [] as $entry) {
            foreach ($entry['changes'] ?? [] as $change) {
                if (($change['field'] ?? null) !== 'messages') {
                    continue;
                }
                $value = $change['value'] ?? [];
                foreach ($value['messages'] ?? [] as $msg) {
                    $this->once("msg:{$msg['id']}", function () use ($msg) {
                        $sender = $msg['from'] ?? $msg['from_user_id'] ?? 'unknown';
                        $type = $msg['type'] ?? 'unknown';
                        $text = $type === 'text' ? ($msg['text']['body'] ?? '') : "[$type]";
                        Log::info("message {$msg['id']} from {$sender}: {$text}");
                    });
                }
                foreach ($value['statuses'] ?? [] as $st) {
                    $this->once("status:{$st['id']}:{$st['status']}", function () use ($st) {
                        $recipient = $st['recipient_id'] ?? $st['recipient_user_id'] ?? 'unknown';
                        Log::info("status {$st['status']} for {$st['id']} to {$recipient}");
                        if ($st['status'] === 'failed') {
                            Log::warning('send failed', ['errors' => $st['errors'] ?? []]);
                        }
                    });
                }
            }
        }
    }

    private function once(string $key, callable $work): void
    {
        if (!Cache::add($key, true, self::DEDUPE_SECONDS)) {
            return; // already handled
        }
        try {
            $work();
        } catch (\Throwable $e) {
            Cache::forget($key); // let the retry handle this item again
            throw $e;
        }
    }
}

Cache::add stores the key only if it’s absent, returns true when it did, and “is an atomic operation” (Laravel cache, accessed 2026-11-04). The default cache driver is database, so keys outlive a restart. Two deliveries of the same message ID race for one key, and only one wins. If your code throws, once() releases the key, so the job’s retry processes that item again. Releasing the key on failure is this post’s design. If the worker process dies mid-item, the key stays and that item is skipped, which is one more reason for a unique index. The 8-day TTL is this post’s choice. A unique index in your own table is the durable version. ShouldBeUnique doesn’t help here, because it blocks duplicates only “until the existing job has completed processing”.

The sender comes from from, with from_user_id as the fallback. Meta’s business-scoped user ID page says from “Will be omitted if the phone number cannot be included”, and from_user_id holds the BSUID (Meta business-scoped user IDs, accessed 2026-11-04). Statuses use recipient_id with recipient_user_id as the fallback. Business-scoped user IDs covers what that means for a contact table keyed on phone numbers. The rest of the envelope is in the webhook payload reference.

#[Tries(4)] allows four attempts, and #[Backoff([1, 5, 10])] spaces the three retries 1, 5 and 10 seconds apart. Jobs that still fail land in failed_jobs, and php artisan queue:failed lists them. In production, keep queue:work running under a process monitor such as Supervisor, as the queue docs describe.

Test it locally

Run the server and a worker in two terminals. composer run dev starts both plus Vite.

php artisan serve
php artisan queue:work

Export the same values you put in .env, then check the GET. Keep the dots in the URL; PHP converts them on arrival. It should print 123:

export WHATSAPP_APP_SECRET="APP_SECRET" WHATSAPP_VERIFY_TOKEN="VERIFY_TOKEN"
curl "http://localhost:8000/webhooks/whatsapp?hub.mode=subscribe&hub.verify_token=$WHATSAPP_VERIFY_TOKEN&hub.challenge=123"

Then sign Meta’s text webhook sample, compacted to one line, and post it:

cat > sample.json <<'EOF'
{"object":"whatsapp_business_account","entry":[{"id":"102290129340398","changes":[{"value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"15550783881","phone_number_id":"106540352242922"},"contacts":[{"profile":{"name":"Sheena Nelson"},"wa_id":"16505551234"}],"messages":[{"from":"16505551234","id":"wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=","timestamp":"1749416383","type":"text","text":{"body":"Does it come in another color?"}}]},"field":"messages"}]}]}
EOF
SIG=$(openssl dgst -sha256 -hmac "$WHATSAPP_APP_SECRET" sample.json | awk '{print $NF}')
curl -i -X POST http://localhost:8000/webhooks/whatsapp \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  --data-binary @sample.json

The first run returns 200, the worker picks up the job and the message line appears in your log. A second run also returns 200 and logs nothing, because the cache already holds msg: plus that ID. Change one character in sample.json without re-signing and the route returns 401. To reach a public URL from your laptop, see local webhook testing with ngrok. Reply from PHP with the PHP send script.

Z-API Omni team