← Back to all files

03 — WhatsApp Integration

Depends on: 02-database.md Produces: Config, route, middleware, controller, sending service, Blade widget Verify with: Meta's webhook verification succeeds; a test message creates a whatsapp_messages row


1. Config

Never call env() outside a config file. After php artisan config:cache, env() returns null everywhere else — this catches people out constantly.

config/services.php — add:

'whatsapp' => [
    'app_secret'      => env('WHATSAPP_APP_SECRET'),
    'verify_token'    => env('WHATSAPP_VERIFY_TOKEN'),
    'access_token'    => env('WHATSAPP_ACCESS_TOKEN'),
    'phone_number_id' => env('WHATSAPP_PHONE_NUMBER_ID'),
    'business_number' => env('WHATSAPP_BUSINESS_NUMBER'),  // for the widget link
    'graph_version'   => env('WHATSAPP_GRAPH_VERSION', 'v21.0'),
],

'claude' => [
    'api_key'    => env('ANTHROPIC_API_KEY'),
    'model'      => env('ANTHROPIC_MODEL', 'claude-sonnet-4-6'),
    'max_tokens' => (int) env('ANTHROPIC_MAX_TOKENS', 1024),
],

.env:

WHATSAPP_APP_SECRET=
WHATSAPP_VERIFY_TOKEN=pick-any-random-string-you-like
WHATSAPP_ACCESS_TOKEN=
WHATSAPP_PHONE_NUMBER_ID=
WHATSAPP_BUSINESS_NUMBER=8801XXXXXXXXX
ANTHROPIC_API_KEY=

WHATSAPP_VERIFY_TOKEN is a string you invent. You type the same value into Meta's dashboard, and Meta echoes it back during setup so each side knows the other is real.


2. Route

routes/web.php

use App\Http\Controllers\WhatsAppWebhookController;

Route::prefix('webhooks/whatsapp')->group(function () {
    Route::get('/', [WhatsAppWebhookController::class, 'verify']);

    Route::post('/', [WhatsAppWebhookController::class, 'handle'])
        ->middleware('whatsapp.signature')
        ->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class]);
});

CSRF must be off. Meta has no CSRF token; the HMAC signature is the authentication.


3. Signature verification

Every POST from Meta carries X-Hub-Signature-256, an HMAC of the request body using your app secret. Verify it before touching anything, or anyone who finds your URL can make your bot say things and place orders.

app/Http/Middleware/VerifyWhatsAppSignature.php

<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class VerifyWhatsAppSignature
{
    public function handle(Request $request, Closure $next): Response
    {
        $header = $request->header('X-Hub-Signature-256');
        $secret = config('services.whatsapp.app_secret');

        if (! $header || ! $secret) {
            Log::warning('WhatsApp webhook: missing signature or secret');

            return response('', 403);
        }

        // Meta signs the RAW body. Using $request->all() and re-encoding
        // produces different bytes and the check will always fail.
        $expected = 'sha256=' . hash_hmac('sha256', $request->getContent(), $secret);

        // hash_equals, not ===, to avoid timing attacks.
        if (! hash_equals($expected, $header)) {
            Log::warning('WhatsApp webhook: signature mismatch', ['ip' => $request->ip()]);

            return response('', 403);
        }

        return $next($request);
    }
}

Register in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'whatsapp.signature' => \App\Http\Middleware\VerifyWhatsAppSignature::class,
    ]);
})

The two details people get wrong: use getContent() not all(), and use hash_equals not ===.


4. The controller

Two jobs: answer Meta's setup handshake, and accept messages fast.

app/Http/Controllers/WhatsAppWebhookController.php

<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Jobs\HandleIncomingMessage;
use App\Models\WhatsAppMessage;
use App\Models\WhatsAppSession;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

class WhatsAppWebhookController extends Controller
{
    /**
     * Meta calls this once when you set up the webhook.
     * Echo the challenge back as PLAIN TEXT — JSON is rejected.
     */
    public function verify(Request $request): Response
    {
        $mode      = $request->query('hub_mode');
        $token     = $request->query('hub_verify_token');
        $challenge = $request->query('hub_challenge');

        if ($mode === 'subscribe' && hash_equals(config('services.whatsapp.verify_token'), (string) $token)) {
            return response((string) $challenge, 200)
                ->header('Content-Type', 'text/plain');
        }

        return response('', 403);
    }

    /**
     * Always return 200 quickly. Meta retries on anything else, and
     * repeated failures can get your webhook disabled.
     */
    public function handle(Request $request): Response
    {
        $value = data_get($request->all(), 'entry.0.changes.0.value', []);

        // Status events (sent/delivered/read) outnumber real messages
        // about 3 to 1. Handle them inline — never queue a job for them.
        if (isset($value['statuses'])) {
            $this->recordStatuses($value['statuses']);

            return response('', 200);
        }

        if (! isset($value['messages'][0])) {
            return response('', 200);   // something we don't handle
        }

        $message = $value['messages'][0];
        $contact = $value['contacts'][0] ?? [];

        $session = WhatsAppSession::firstOrCreate(
            ['phone_number' => $message['from']],
            ['profile_name' => data_get($contact, 'profile.name')],
        );

        // Text only for now.
        if (($message['type'] ?? null) !== 'text') {
            $this->replyUnsupported($session);

            return response('', 200);
        }

        // --- Deduplication ---
        // wamid is unique in the database. If this throws, we've seen
        // this message before (a Meta retry) and must not process it again.
        try {
            $stored = WhatsAppMessage::create([
                'whatsapp_session_id' => $session->id,
                'wamid'               => $message['id'],
                'role'                => 'user',
                'direction'           => 'inbound',
                'body'                => $message['text']['body'],
            ]);
        } catch (\Illuminate\Database\UniqueConstraintViolationException) {
            Log::info('Duplicate webhook ignored', ['wamid' => $message['id']]);

            return response('', 200);
        }

        $session->update(['last_inbound_at' => now()]);

        HandleIncomingMessage::dispatch($session->id, $stored->id);

        return response('', 200);
    }

    private function recordStatuses(array $statuses): void
    {
        foreach ($statuses as $status) {
            WhatsAppMessage::where('wamid', $status['id'])
                ->update(['status' => $status['status']]);
        }
    }

    private function replyUnsupported(WhatsAppSession $session): void
    {
        app(\App\Services\WhatsAppService::class)->sendText(
            $session->phone_number,
            "Sorry, I can only read text messages. Could you type what you're looking for?"
        );
    }
}

Why dedup lives here, not in the job

If you checked for duplicates inside the job, two simultaneous deliveries would both pass the controller and both enqueue. Inserting first means the duplicate is rejected before a job exists.

A database unique index rather than a cache check, because a cache can be flushed or evicted — and the failure mode of a missed duplicate is a duplicate order.


5. Sending messages

app/Services/WhatsAppService.php

<?php

declare(strict_types=1);

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class WhatsAppService
{
    public function sendText(string $to, string $body): ?string
    {
        $version = config('services.whatsapp.graph_version');
        $phoneId = config('services.whatsapp.phone_number_id');

        $response = Http::withToken(config('services.whatsapp.access_token'))
            ->timeout(10)
            ->connectTimeout(5)
            ->retry(
                times: 3,
                sleepMilliseconds: 500,
                // Only retry network errors and server errors.
                // A 400 means our payload is wrong — retrying just repeats it.
                when: fn ($e) => $e instanceof \Illuminate\Http\Client\ConnectionException
                    || ($e instanceof \Illuminate\Http\Client\RequestException && $e->response->serverError()),
                throw: false,
            )
            ->post("https://graph.facebook.com/{$version}/{$phoneId}/messages", [
                'messaging_product' => 'whatsapp',
                'to'                => $to,
                'type'              => 'text',
                'text'              => ['body' => $body, 'preview_url' => false],
            ]);

        if ($response->failed()) {
            Log::error('WhatsApp send failed', [
                'status' => $response->status(),
                'body'   => $response->json(),
            ]);

            return null;
        }

        return data_get($response->json(), 'messages.0.id');   // the outbound wamid
    }
}

Errors you will actually hit

Status / code Meaning What to do
401 Access token expired Regenerate it. Test tokens expire in 24h.
400 code 131047 Outside the 24-hour window Don't retry. You can't send.
400 code 131026 Number isn't on WhatsApp Mark the session inactive
429 Rate limited Wait and requeue
5xx Meta's problem The retry handles it

The 24-hour window will confuse you at least once: you can reply freely within 24 hours of the customer's last message, and outside that you need a pre-approved template. Since this bot only replies, it stays inside the window naturally.


6. Storefront widget

resources/views/components/whatsapp-widget.blade.php

@props([
    'productName' => null,
    'sku' => null,
    'categoryName' => null,
])

@php
    $number = config('services.whatsapp.business_number');

    $message = match (true) {
        filled($productName) && filled($sku) => "Hi, I'm looking at {$productName} (SKU: {$sku}).",
        filled($productName)                 => "Hi, I'm looking at {$productName}.",
        filled($categoryName)                => "Hi, I'm browsing {$categoryName}.",
        default                              => "Hi, I'd like some help shopping.",
    };

    $link = 'https://wa.me/' . $number . '?text=' . rawurlencode($message);

    $label = filled($productName)
        ? "Chat with us on WhatsApp about {$productName} (opens WhatsApp)"
        : 'Chat with us on WhatsApp (opens WhatsApp)';
@endphp

@if (filled($number))
<div
    x-data="{ shown: false, expanded: false }"
    x-init="setTimeout(() => shown = true, 200)"
    x-cloak
    class="fixed bottom-5 right-5 z-40"
>
    <a
        href="{{ $link }}"
        target="_blank"
        rel="noopener noreferrer"
        aria-label="{{ $label }}"
        x-show="shown"
        x-transition.opacity.duration.300ms
        @mouseenter="expanded = true"
        @mouseleave="expanded = false"
        @focus="expanded = true"
        @blur="expanded = false"
        class="flex items-center gap-2 rounded-full bg-[#25D366] px-4 py-3
               text-white shadow-lg transition
               hover:bg-[#1ebe5d]
               focus-visible:outline focus-visible:outline-2
               focus-visible:outline-offset-2 focus-visible:outline-gray-900"
        style="min-width:48px; min-height:48px;"
    >
        <svg aria-hidden="true" focusable="false" width="24" height="24"
             viewBox="0 0 24 24" fill="currentColor">
            <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51l-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.872.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884a9.82 9.82 0 016.993 2.898 9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.889 9.884"/>
        </svg>

        <span x-show="expanded" x-transition class="text-sm font-medium whitespace-nowrap">
            Chat with us
        </span>
    </a>
</div>
@endif

Usage:

<x-whatsapp-widget :product-name="$product->name" :sku="$product->sku" />
<x-whatsapp-widget :category-name="$category->name" />
<x-whatsapp-widget />

Notes

The link is built in PHP, not Alpine. rawurlencode in PHP handles Bengali text and # in SKUs correctly. Building the URL in JavaScript invites encoding bugs.

It's a real <a href>. It works with JavaScript disabled. Alpine only animates it.

@focus as well as @mouseenter. Keyboard users never trigger hover. Expanding only on hover makes the label invisible to them.

aria-hidden="true" on the SVG so a screen reader reads the label once, not twice.

Renders nothing if business_number is empty. A missing env var should produce no button, not a broken link to wa.me/.

The pre-filled message is untrusted. The customer can edit it before sending. The bot re-looks-up any SKU rather than trusting the text.


7. Local setup

# 1. Expose your local server
ngrok http 8000
# -> https://abc123.ngrok-free.app

# 2. In Meta dashboard > WhatsApp > Configuration:
#    Callback URL:  https://abc123.ngrok-free.app/webhooks/whatsapp
#    Verify token:  (your WHATSAPP_VERIFY_TOKEN)
#    Click Verify and Save -> hits your GET endpoint

# 3. Subscribe to the "messages" field

# 4. Run the queue worker (nothing happens without this)
php artisan queue:work

# 5. Message your test number from a phone you added as a recipient

Common problems:

Symptom Cause
Verification fails Returning JSON instead of plain text, or token mismatch
403 on every POST Signature check using all() instead of getContent()
Message saved, no reply Queue worker not running
401 when sending Test access token expired — they last 24 hours
ngrok URL stopped working Free ngrok changes the URL on restart; re-save it in Meta

8. Checklist