To implement WhatsApp Cloud API direct integration with Meta in a Laravel backend with a React frontend, follow these concrete steps using the official Meta documentation and the guide at DevOpsSchool.com:
Prerequisites
Create a Meta Business and Developer account.
Verify your business and get a WhatsApp Business Account (WABA).
Add your phone number, verify, and save the Phone Number ID and WABA ID.
Generate a permanent access token using a system user. Store this token securely in Laravel’s .env file (never expose it to the client).
Set Up WhatsApp Webhooks
Create an HTTPS endpoint (e.g., /api/whatsapp/webhook) in Laravel:
// routes/api.php
Route::post('whatsapp/webhook', [WhatsAppController::class, 'webhook']);
Route::get('whatsapp/webhook', [WhatsAppController::class,
'verifyWebhook']);
In WhatsAppController, handle webhook verification and echo back hub.challenge during GET requests. Process incoming messages/events in POST requests.
Send Messages via Graph API
Use Laravel’s HTTP client (Http::withToken(...)->post(...)) to call the Cloud API:
public function sendMessage($to, $messageText) {
$url = "https://graph.facebook.com/v19.0/" . config('whatsapp.phone_id') . "/messages";
$response = Http::withToken(config('whatsapp.access_token'))
->post($url, [
"messaging_product" => "whatsapp",
"to" => $to,
"type" => "text",
"text" => ["body" => $messageText]
]);
return $response->json();
}
Store metadata (message ID, delivery/read status) and retry on failures as needed.
Message Templates
Create and approve templates in WhatsApp Manager or via API.
Store template info in your database (template name, category, language, status).
Compliance
Users must opt in before messaging; store consent info in your database.
Frontend (React)
Collect WhatsApp Opt-Ins
Build a UI in React where users can submit their WhatsApp number.
Add terms for consent and opt-in tracking.
Integrate With Laravel API
On user actions (e.g., submit form, request OTP), POST the number and message type to Laravel’s backend API (e.g., /api/send-whatsapp).
Laravel processes and sends the WhatsApp message using the Cloud API, then responds with status or delivery info.
// Example React API call
await fetch('/api/send-whatsapp', {
method: 'POST',
body: JSON.stringify({ phone: '+919999999999', message: 'OTP: 123456' }),
headers: { 'Content-Type': 'application/json' }
});
Display delivery/read status in the frontend (polling or webhook-driven).
Webhook & Message Flow
User submits number in React front-end.
React sends request to Laravel API.
Laravel stores user consent, calls WhatsApp Cloud API to send the message.
Meta pushes delivery status/events to your webhook (Laravel); update DB and notify UI as needed.
Top comments (0)