This guide explains how to handle webhook responses when you receive inbound messages or interactions from your users on your WhatsApp number. The following use cases are covered in the code snippets below:
To get started, you need a Plivo account — sign up with your work email address if you don’t have one already. If this is your first time using Plivo APIs, follow our instructions to set up a PHP development environment.
You must have an onboarded WhatsApp account to receive inbound messages. If a number is listed as connected, it can receive inbound messages.
Change to the project directory and run this command to create a Laravel controller for inbound messages.
$ php artisan make:controller WhatsappController
This command generates a controller named WhatsappController in the app/http/controllers/ directory. Edit the app/http/controllers/WhatsappController.php file and paste this code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class WhatsappController extends Controller
{
public function receiveWhatsapp(Request $request)
{
$data = json_decode($request->getContent(), true);
$fromNumber = $data['From'];
$toNumber = $data['To'];
$contentType = $data['ContentType'];
switch ($contentType) {
case 'text':
echo "Text Message - From: $fromNumber, To: $toNumber, Text: {$data['Body']}";
break;
case 'media':
echo "Media Message - From: $fromNumber, To: $toNumber, URL: {$data['Media0']}, Caption: {$data['Body']}";
break;
case 'button':
echo "Button Message - From: $fromNumber, To: $toNumber, Text: {$data['Button']['Text']}, Payload: {$data['Button']['Payload']}";
break;
case 'interactive':
if ($data['Interactive']['Type'] == 'button_reply') {
echo "Interactive Button - From: $fromNumber, To: $toNumber, ID: {$data['Interactive']['ButtonReply']['Id']}, Title: {$data['Interactive']['ButtonReply']['Title']}";
} elseif ($data['Interactive']['Type'] == 'list_reply') {
echo "Interactive List - From: $fromNumber, To: $toNumber, ID: {$data['Interactive']['ListReply']['Id']}, Title: {$data['Interactive']['ListReply']['Title']}, Description: {$data['Interactive']['ListReply']['Description']}";
}
break;
case 'location':
echo "Location - From: $fromNumber, To: $toNumber, Latitude: {$data['Location']['Latitude']}, Longitude: {$data['Location']['Longitude']}, Name: {$data['Location']['Name']}, Address: {$data['Location']['Address']}";
break;
}
http_response_code(200);
echo 'Message Received';
}
}
Add or update a webhook URL from this link to a WhatsApp Business Account. Once you’ve done this, you should be able to receive inbound messages.
Send a WhatsApp message to the Plivo number you specified using WhatsApp application.