WhatsApp official API in Laravel: send and webhook

Integrate the official WhatsApp API into Laravel via CRPRO Hub: the Http client with a token, a webhook with CSRF excluded, hash_equals signatures and a queue.

In Laravel, the connection to CRPRO Hub fits in three pieces: a service that uses the Http facade to send, a webhook route that checks the signature, and a job that processes the event outside the request cycle. The Hub's PHP guide covers the framework-free base; here are the points that only show up in Laravel, like CSRF protection, the raw body and Http::fake in tests.

Where to keep the key and the secret

Short answer: in .env, read by config/services.php. The API key (hub_pk_...) and the webhook secret (whsec_...) never go in code or in the repository.

Create the API key in the Hub dashboard with the messages:send and webhooks:write scopes and copy the value right away: it is shown only once (authentication). The whsec_ secret is also shown once, in the POST /api/v1/webhooks response. If you lose either, rotate it; there is no way to recover it.

// config/services.php 'crprohub' => [ 'key' => env('CRPRO_API_KEY'), 'webhook_secret' => env('CRPRO_WEBHOOK_SECRET'), ],

How to send a message with the Http facade

Short answer: Http::withToken() builds Authorization: Bearer, withHeaders() adds the Idempotency-Key and post() sends the JSON. The Hub answers 202, and throw() turns any 4xx or 5xx into an exception.

  • withToken() adds the token to the Authorization header, as Laravel's HTTP client documentation describes.
  • withHeaders() takes an array of headers; it is where the Idempotency-Key goes, mandatory on send.
  • timeout() sets the maximum wait in seconds. Without it, a Hub outage holds your worker; connectTimeout() limits only the connection.
  • post() with an array sends the body; to needs the country code, digits only.
  • json('data.message_id') reads the returned id using dot notation.
<?php namespace App\Services; use Illuminate\Support\Facades\Http; class CrproHub { public function enviarTexto(string $canal, string $para, string $texto, string $chave): string { $resposta = Http::withToken(config('services.crprohub.key')) ->withHeaders(['Idempotency-Key' => $chave]) ->acceptJson() ->timeout(10) ->post("https://crprohub.com/api/v1/channels/{$canal}/messages", [ 'to' => $para, 'type' => 'text', 'text' => ['body' => $texto], ]); $resposta->throw(); // 4xx e 5xx viram exceção return $resposta->json('data.message_id'); // a resposta é 202: aceita, não entregue } }

The Idempotency-Key should be stable per logical message, for example the notification or received event id. That way a job retry returns the original response instead of sending another message. If the same key comes back with a different body, the Hub answers 409 IDEMPOTENCY_KEY_REUSED. The limits are 60 messages per minute per channel and 120 requests per minute per organization and credential. The client's retry() method exists and accepts a condition callback; use it only for 429 and 5xx, always with the same key.

How to receive the webhook and exclude CSRF

Short answer: create a POST route, exclude it from CSRF verification, read the body with $request->getContent(), check the HMAC with hash_equals and answer 2xx. Without the CSRF exclusion, Laravel rejects the Hub call, which has no session token.

Laravel's documentation explains the case: webhook routes should live outside the web middleware group or be listed in validateCsrfTokens(except: [...]) in bootstrap/app.php. The example uses the second form. The Hub signs timestamp.delivery_id.body with HMAC SHA-256, so the body must be exactly the received bytes; that is why getContent(), and not json_encode of the already parsed array.

// routes/web.php use App\Http\Controllers\CrproWebhookController; Route::post('/webhooks/crprohub', [CrproWebhookController::class, 'receber']); // bootstrap/app.php ->withMiddleware(function (Middleware $middleware): void { $middleware->validateCsrfTokens(except: ['webhooks/crprohub']); })curl -X POST https://crprohub.com/api/v1/webhooks \ -H "Authorization: Bearer hub_pk_EXEMPLO_NAO_REAL" \ -H "Content-Type: application/json" \ -d '{"name":"Recebimento","url":"https://your-app.com/webhooks/crprohub","event_types":["message.received"]}'<?php namespace App\Http\Controllers; use App\Jobs\ProcessarEventoCrpro; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; class CrproWebhookController extends Controller { public function receber(Request $request) { $raw = $request->getContent(); // bytes exatos, antes de qualquer parse $assinado = $request->header('X-Hub-Timestamp').'.'.$request->header('X-Hub-Delivery-Id').'.'.$raw; $esperado = hash_hmac('sha256', $assinado, config('services.crprohub.webhook_secret')); $recebido = str_replace('sha256=', '', (string) $request->header('X-Hub-Signature-256')); if (! hash_equals($esperado, $recebido)) { abort(401); } $evento = json_decode($raw, true); // O id do corpo se repete na retentativa e no replay. if (Cache::add('crprohub:evento:'.$evento['id'], 1, now()->addDay())) { ProcessarEventoCrpro::dispatch($evento); } return response()->json(['ok' => true]); // 2xx rápido } }{ "id": "6f1f0f6a-3b2c-4d1e-9a8b-0c1d2e3f4a5b", "event": "message.received", "channel_id": "9f6a9c1e-2f3d-4a5b-8c7d-1e2f3a4b5c6d", "occurred_at": "2026-08-21T12:00:00.000Z", "data": { "message_id": "wamid.EXEMPLO123", "from": "5521999999999", "type": "text", "text": "Oi, ainda tem em estoque?" } }
hash_equals compares in constant time. Never use === or == on the signature: a plain comparison leaks timing per byte position.

Queue, duplicates and a fast response

Short answer: the controller only validates, records the event id and dispatches a job. The Hub expects a 2xx within 10 seconds; anything slow (database, AI model, another API) goes to the queue.

On failure, the Hub resends up to nine times over about four days; after 20 consecutive failures it pauses the endpoint, and reactivation is a PATCH on /api/v1/webhooks/{id} with {"status":"active"}. The example's Cache::add writes the key only if it does not exist, which discards repeats of the same id. There is a catch: if the job fails after the id is marked, the Hub's retry will be discarded. To avoid it, mark the id as done at the end of the job, and in the controller only check existence.

SituationController responseEffect on the Hub
Invalid signature401Counts as a failure and retries
Repeated event200, nothing dispatchedDelivery complete
New event200, job dispatchedDelivery complete
Unhandled exception500Retries, then pauses after 20

To diagnose deliveries that do not arrive, see the webhooks page.

How to test without calling the Hub

Short answer: use Http::fake() to simulate the 202 response and Http::assertSent() to check the header. No test in your suite needs a real key or network.

Http::fake([ 'crprohub.com/*' => Http::response(['data' => ['message_id' => 'wamid.X', 'status' => 'accepted']], 202), ]); app(CrproHub::class)->enviarTexto('CANAL', '5521999999999', 'Olá', 'chave-1'); Http::assertSent(fn ($req) => $req->hasHeader('Idempotency-Key', 'chave-1'));

Laravel's documentation describes Http::fake for simulated responses and Http::preventStrayRequests() to fail if any call escapes the simulation. For the webhook, build a body, compute the signature with the same formula as the controller and send it with $this->postJson, passing the body as a single string. Test two cases: a correct signature and a swapped one. For a real call without risk, use a test channel and the POST /api/v1/webhooks/{id}/test endpoint, limited to 10 per hour per endpoint. The quickstart shows the first call end to end.

Frequently asked questions

Do I need a package to integrate Laravel with CRPRO Hub?

No. The Http facade, which wraps Guzzle, and a webhook route are enough. This article does not depend on any Hub package.

Why does the webhook return 419 in Laravel?

Because the route went through the web group's CSRF check. Exclude the URI with validateCsrfTokens(except: [...]) in bootstrap/app.php or register the route outside the web group, as Laravel's documentation indicates.

Can I use $request->all() to check the signature?

No. The signature covers the exact body bytes; re-serializing the parsed array can change spacing and order. Use $request->getContent().

How do I avoid sending the same message twice if the job retries?

Use an Idempotency-Key that is stable per logical message. The same key with the same body returns the original response; with a different body, the Hub answers 409.

Fontes

Documentação oficial da Meta, conferida em 31 de outubro de 2026.