Updated on November 4, 2026
To use the official WhatsApp Business API with PHP and Laravel you need two pieces: a service that POSTs to the /<PHONE_NUMBER_ID>/messages endpoint using Laravel’s HTTP client and a Bearer token, and a webhook route that answers Meta’s GET verification, validates the X-Hub-Signature-256 header and returns 200 fast, leaving the actual processing to a queue. This tutorial builds both from scratch, with complete code.
The code targets Laravel 13 (the version of the official docs on November 4, 2026) and Meta’s Cloud API. At the end, we show what changes if you use Vectalk.
What you’ll build
Customer on WhatsApp
│ message
▼
Meta (Cloud API) ──POST + X-Hub-Signature-256──▶ /api/webhook/whatsapp
│ validate signature
│ return 200
▼
queue (jobs)
│ dedupe by wamid
▼
ProcessWhatsAppWebhook
│ reply
▼
WhatsAppService ──POST /messages──▶ Meta
Files we’ll create or edit:
| File | Purpose |
|---|---|
.env and config/services.php | Credentials and base URL |
app/Services/WhatsAppService.php | Sending messages with retries |
routes/api.php | Webhook GET and POST routes |
app/Http/Middleware/VerifyWhatsAppSignature.php | HMAC validation |
app/Http/Controllers/WhatsAppWebhookController.php | Verification and intake |
app/Jobs/ProcessWhatsAppWebhook.php | Queued processing |
Prerequisites
- A Meta app with the WhatsApp product, a phone number registered on the Cloud API, and an access token. For production, use a system user token (see permanent access token).
- The app’s Phone Number ID and App Secret. Both are in your Meta app dashboard.
- A Laravel project with a database configured (the queue will use the
databasedriver, the default for new apps). - A public HTTPS URL for the webhook. In development, use a tunnel such as ngrok (test the webhook locally).
If you’re still deciding between integrating directly with Meta or going through a provider, start with the official WhatsApp API guide.
Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →
1. Configuration
In .env:
WHATSAPP_BASE_URL=https://graph.facebook.com/v26.0
WHATSAPP_PHONE_NUMBER_ID=106540352242922
WHATSAPP_TOKEN=EAAJB...
WHATSAPP_APP_SECRET=your_app_secret
WHATSAPP_VERIFY_TOKEN=a_long_random_string
QUEUE_CONNECTION=database
In config/services.php, add:
'whatsapp' => [
'base_url' => env('WHATSAPP_BASE_URL', 'https://graph.facebook.com/v26.0'),
'phone_number_id' => env('WHATSAPP_PHONE_NUMBER_ID'),
'token' => env('WHATSAPP_TOKEN'),
'app_secret' => env('WHATSAPP_APP_SECRET'),
'verify_token' => env('WHATSAPP_VERIFY_TOKEN'),
],
Always read config('services.whatsapp.*') in your code, never env() directly. According to the configuration docs, once the config is cached the .env file isn’t loaded, and env() only returns system-level variables.
2. A sending service with retries
Laravel ships an HTTP client built on Guzzle. The methods used below (withToken, acceptJson, timeout, retry, throw) are in the HTTP Client docs.
<?php
namespace App\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Throwable;
class WhatsAppService
{
private function client(): PendingRequest
{
$cfg = config('services.whatsapp');
return Http::baseUrl($cfg['base_url'])
->withToken($cfg['token'])
->acceptJson()
->timeout(15)
->retry(3, fn (int $attempt) => $attempt * 1000, function (Throwable $e, PendingRequest $request) {
// Retry only on network errors, 429 (rate limit) and 5xx.
if ($e instanceof ConnectionException) {
return true;
}
return $e instanceof RequestException
&& ($e->response->status() === 429 || $e->response->serverError());
});
}
public function send(array $payload): array
{
$phoneId = config('services.whatsapp.phone_number_id');
return $this->client()
->post("/{$phoneId}/messages", ['messaging_product' => 'whatsapp'] + $payload)
->throw()
->json();
}
public function sendText(string $to, string $body, ?string $replyTo = null): array
{
$payload = ['to' => $to, 'type' => 'text', 'text' => ['body' => $body]];
if ($replyTo) {
$payload['context'] = ['message_id' => $replyTo];
}
return $this->send($payload);
}
public function sendTemplate(string $to, string $name, string $lang, array $bodyParams = []): array
{
$components = [];
if ($bodyParams) {
$components[] = [
'type' => 'body',
'parameters' => array_map(fn ($v) => ['type' => 'text', 'text' => (string) $v], $bodyParams),
];
}
return $this->send([
'to' => $to,
'type' => 'template',
'template' => ['name' => $name, 'language' => ['code' => $lang], 'components' => $components],
]);
}
public function markAsRead(string $messageId, bool $typing = false): array
{
$payload = ['status' => 'read', 'message_id' => $messageId];
if ($typing) {
$payload['typing_indicator'] = ['type' => 'text'];
}
return $this->send($payload);
}
}
Key points:
- Retry only where it helps. 400-level errors (bad parameter, missing template) won’t improve on a second try. Retrying only 429 and 5xx avoids duplicate messages caused by logic errors.
- Growing backoff. The second argument to
retryis a closure returning the wait in milliseconds (1 s, 2 s…). At high volume, tune it to your number’s throughput (error 131056 signals a rate limit). throw()turns 4xx/5xx into aRequestException, with Meta’s response available in$e->response->json()for logging.
To test sending from Tinker:
app(\App\Services\WhatsAppService::class)
->sendTemplate('16505551234', 'hello_world', 'en_US');
Outside the 24-hour window, only approved templates are delivered, and the first contact with a customer must always be a template. The JSON for templates with variables, media and buttons is in how to send a template message via the API.
3. Webhook routes
Enable API routes (this command creates routes/api.php):
php artisan install:api
According to the Laravel routing docs, routes in routes/api.php are stateless, get the /api prefix and belong to the api middleware group, without the CSRF protection of the web group. That’s exactly what a webhook needs.
<?php
use App\Http\Controllers\WhatsAppWebhookController;
use App\Http\Middleware\VerifyWhatsAppSignature;
use Illuminate\Support\Facades\Route;
Route::get('/webhook/whatsapp', [WhatsAppWebhookController::class, 'verify']);
Route::post('/webhook/whatsapp', [WhatsAppWebhookController::class, 'receive'])
->middleware(VerifyWhatsAppSignature::class);
The final URL is https://your-domain.com/api/webhook/whatsapp.
4. GET verification (hub.challenge)
When you configure the webhook in the app dashboard, Meta sends a GET with hub.mode=subscribe, hub.challenge and hub.verify_token. If the token matches, you return 200 with the hub.challenge value; otherwise, anything other than 200 (Create a webhook endpoint).
Here’s the PHP gotcha: the PHP manual states that dots in incoming variable names are converted to underscores. So hub.mode arrives as hub_mode.
<?php
namespace App\Http\Controllers;
use App\Jobs\ProcessWhatsAppWebhook;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class WhatsAppWebhookController extends Controller
{
public function verify(Request $request): Response
{
// PHP turns "hub.mode" into "hub_mode"
$mode = $request->query('hub_mode');
$token = $request->query('hub_verify_token');
$challenge = $request->query('hub_challenge');
if ($mode === 'subscribe' && hash_equals((string) config('services.whatsapp.verify_token'), (string) $token)) {
return response((string) $challenge, 200)->header('Content-Type', 'text/plain');
}
return response('forbidden', 403);
}
public function receive(Request $request): Response
{
ProcessWhatsAppWebhook::dispatch($request->json()->all());
return response('', 200);
}
}
The receive method doesn’t process anything: it queues the payload and responds. Responding quickly is what prevents retries and event backlogs.
5. Validating X-Hub-Signature-256
Every POST from Meta carries an X-Hub-Signature-256: sha256=<hash> header. The hash is an HMAC-SHA256 of the raw request body, keyed with your App Secret. You recompute it and compare; if it doesn’t match, reject the request.
php artisan make:middleware VerifyWhatsAppSignature
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class VerifyWhatsAppSignature
{
public function handle(Request $request, Closure $next): Response
{
$secret = (string) config('services.whatsapp.app_secret');
$header = (string) $request->header('X-Hub-Signature-256', '');
// Use the raw body: re-serializing the JSON changes bytes and breaks the hash.
$expected = 'sha256=' . hash_hmac('sha256', $request->getContent(), $secret);
if ($secret === '' || ! hash_equals($expected, $header)) {
abort(401, 'invalid signature');
}
return $next($request);
}
}
Three common mistakes:
- Computing the HMAC over
json_encode($request->all())instead ofgetContent(). Any difference in whitespace, key order or slash escaping changes the hash. - Using
==instead ofhash_equals, which compares in constant time. - Using the access token as the key. The key is the App Secret of the app that signs the webhooks.
The same steps in other languages are in how to validate the webhook signature.
6. Processing job with deduplication
Meta retries a failed POST immediately, then a few more times with decreasing frequency for up to 7 days, and asks your server to handle duplicates. Events may also arrive batched, with up to 1,000 updates per request. That’s why the job walks every entry and dedupes on the message id (the wamid).
php artisan make:job ProcessWhatsAppWebhook
<?php
namespace App\Jobs;
use App\Services\WhatsAppService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
#[Tries(5)]
class ProcessWhatsAppWebhook implements ShouldQueue
{
use Queueable;
public function __construct(public array $payload) {}
public function handle(WhatsAppService $wa): void
{
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) {
// Cache::add is atomic: only the first delivery gets through.
if (! Cache::add('wa:msg:' . $msg['id'], 1, 60 * 60 * 24 * 7)) {
continue;
}
$this->handleMessage($wa, $msg);
}
foreach ($value['statuses'] ?? [] as $status) {
Log::info('whatsapp.status', [
'id' => $status['id'],
'status' => $status['status'],
'errors' => $status['errors'] ?? null,
]);
}
}
}
}
private function handleMessage(WhatsAppService $wa, array $msg): void
{
$wa->markAsRead($msg['id'], typing: true);
$reply = match ($msg['type']) {
'text' => 'Got it: "' . mb_substr($msg['text']['body'], 0, 200) . '". We\'ll help you shortly.',
'image', 'document' => 'File received, thanks!',
default => 'Message received.',
};
$wa->sendText($msg['from'], $reply, replyTo: $msg['id']);
}
}
Details:
Cache::addonly writes if the key doesn’t exist and, per the cache docs, it’s atomic. We keep the key for 7 days, matching Meta’s retry window. In production, prefer storing thewamidin the database with a unique index, alongside the raw payload.- Statuses (
sent,delivered,read,failed) arrive in the samemessagesfield, in thestatusesarray. They can arrive out of order; treat each as an independent event (message status webhooks). - The
#[Tries(5)]attribute sets how many times the job is attempted, per the queues docs. If a reply fails after the message was marked as processed, it won’t be retried; if that matters, moveCache::addafter the send or use a table with state.
Run the worker:
php artisan queue:work --tries=3 --timeout=30
In production, keep the worker under a process supervisor.
The full architecture (queues, retries, status ordering and raw payload storage) is covered in WhatsApp API integration architecture.
7. Test locally
GET verification:
curl "http://localhost:8000/api/webhook/whatsapp?hub.mode=subscribe&hub.verify_token=a_long_random_string&hub.challenge=12345"
The response should be just 12345.
A signed POST, simulating Meta:
BODY='{"object":"whatsapp_business_account","entry":[{"id":"0","changes":[{"field":"messages","value":{"messages":[{"from":"16505551234","id":"wamid.TEST1","timestamp":"1762250400","type":"text","text":{"body":"hi"}}]}}]}]}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "your_app_secret" | sed 's/^.* //')
curl -X POST http://localhost:8000/api/webhook/whatsapp \
-H "Content-Type: application/json" \
-H "X-Hub-Signature-256: sha256=$SIG" \
-d "$BODY"
With the tunnel running, set the public URL and verify token in App Dashboard > WhatsApp > Configuration and subscribe to the messages field. If nothing arrives, check the field subscription, the public URL and the worker logs.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Meta says the callback URL couldn’t be verified | Reading hub.challenge instead of hub_challenge, or returning HTML | Use hub_* and return plain text with status 200 |
| 419 on POST | Route defined in routes/web.php (CSRF) | Move it to routes/api.php |
| 401 on every POST | HMAC computed over re-serialized JSON or with the wrong key | Use getContent() and the App Secret |
| Messages answered twice | No dedup by wamid | Use Cache::add or a unique index |
| Slow webhook that gets retried | Processing inside the controller | Dispatch the job and return 200 |
env() returns null in production | Cached config | Read from config('services.whatsapp') |
How to do this with Vectalk
Vectalk is a proxy for the official Cloud API: payloads are identical. To reuse the same WhatsAppService:
- Set
WHATSAPP_BASE_URLtohttps://apis.vectalk.com.br/apiand use the token generated under Settings → API Tokens in the dashboard (authentication, in Portuguese). - Sending goes to
POST /messages(no Phone Number ID in the URL). With an instance token the number is resolved automatically; with an organization token, includephone_number_idin the body. Adjust thepost()line in the service. - The webhook is registered via the API (register webhook) with
instance_id,urlandname, and receives Meta’s own payload. The webhooks docs ask for a200within 20 seconds; otherwise the event is retried.
Vectalk’s documentation doesn’t describe a GET verification with hub.challenge or a signature header on forwarded events. In that setup, protect the route with a hard-to-guess secret in the URL path and confirm the details with support. Deduplication by wamid is still required. Create your account to try it.
Frequently asked questions
Do I need a WhatsApp PHP package?
No. Laravel’s HTTP client handles sending, and the webhook is a regular route. Third-party packages can help, but they add a dependency that has to keep up with Graph API versions.
Does this work in plain PHP, without Laravel?
Yes. The logic is the same: curl or Guzzle for the POST, hash_hmac('sha256', file_get_contents('php://input'), $secret) for the signature, and $_GET['hub_challenge'] for verification.
Why use a queue if processing is fast?
Because webhook response time doesn’t depend only on your code: a slow call to the API, the database or an AI model can delay the response. With a queue, the 200 goes out immediately and processing can be retried without losing the event.
Which Graph API version should I use?
Use a supported version and pin it in your config. Meta’s documentation examples use v26.0 as of this date. Upgrade deliberately, testing first.
Can one webhook handle several phone numbers?
Yes. The payload includes metadata.phone_number_id, which identifies the number that received the message. Use it to route events and to pick the right token when replying.
Official sources consulted on November 4, 2026: Create a webhook endpoint (Meta), Webhooks overview (Meta), Typing indicators (Meta), Laravel: Configuration, Laravel: Routing, Laravel: HTTP Client, Laravel: Queues, Laravel: Cache, PHP: Variables From External Sources, Vectalk: Webhooks, Vectalk: Authentication.
Try the official WhatsApp API today
Create your account, generate a token and send your first message with the quick-start guide. Same payloads and webhooks as Meta's Cloud API.
