Receive WhatsApp messages using PHP

How to Receive WhatsApp messages using PHP?

Introduction

In this tutorial, we will create a page to handle incoming WhatsApp message webhooks using php

Dependencies

for local development purposes, a tunneling service is required. This example uses ngrok

You can download ngrok here: https://ngrok.com/download

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 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 webhook.php and upload it to your server the Webhook URL will be :

http://your-server/webhook.php

On Local Usage

Save the above example file as webhook.php in your localhost and the webhook url will be :

http://localhost/webhook.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 webhook url will be:

https://7647-115-83-121-164.ngrok.io/webhook.php

What’s next?

paste your Webhook URL in Instance settings.

You should be able to receive webhooks now and you can see them in the log.txt file .

WhatsApp Chat WhatsApp Chat Hello, how can I help you ?