Receive WhatsApp messages using PHP and webhook

Introduction

In this tutorial, we will create a page to handle incoming WhatsApp message using PHP.

Dependencies

for local development purposes, a tunneling service is required. This example uses ngrok , You can download ngrok from here.

Example

This is a very simple example, with the server logging the body from the request to the log.txt file.

The body contains the complete webhook information sent from the Ultramsg API WhatsApp instance.

$data = file_get_contents("php://input");
$event = json_decode($data, true);
if(isset($event)){
	//Here, you now have event and can process them how you like e.g Add to the database or generate a response
	$file = 'log.txt';  
	$data =json_encode($event)."\n";  
	file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
}

On Server Usage

Save the above example file as test.php and upload it to your server the Webhook URL will be :

http://your-server/test.php

On Local Usage with ngrok

Save the above example file as test.php in your localhost and the URL will be :

http://localhost/test.php

Start ngrok :

ngrok http 80

After this, you should see a
*.ngrok.io URL.
for example :
https://7647-115-83-121-164.ngrok.io
replace localhost with
ngrok.io URL
the URL will be:
https://7647-115-83-121-164.ngrok.io/webhook.php

What’s next?

paste your URL in Instance settings.
You should be able to receive webhooks now and you can see them in the log.txt file.

EXAMPLE JSON RESPONSE

{
  "event_type": "message_received",
  "instanceId": "90",
  "data": {
    "id": "[email protected]_7ECAED9EB68D3474BE591443134C2E3F",
    "from": "[email protected]",
    "to": "[email protected]",
    "ack": "pending",
    "type": "chat",
    "body": "I can't send a message using php code\nCan you help me",
    "fromMe": false,
    "isForwarded": false,
    "time": 1643311467
  }
}