Receive WhatsApp messages using PHP

How to Receive WhatsApp messages using PHP and webhook

Welcome to this tutorial, where we will guide you through the process of receiving WhatsApp messages using PHP and a Webhook. This is an incredibly valuable tool for businesses looking to automate their customer interactions on WhatsApp. Let's get started!

By the way, we have the source code of a great PHP chatbot: https://github.com/Whapi-Cloud/php-whatsapp-chatbot. It can handle incoming messages, try it!

Introduction

Webhooks are HTTP callbacks that receive data when a certain event occurs, making them perfect for receiving messages in real-time. In this guide, we will create a simple PHP script that will serve as our Webhook to receive incoming messages.

Detailed manual about webhooks here

Requirements

  1. PHP: You will need PHP installed on your server or local machine. This tutorial will use PHP 7.4, but the code should work with other versions.

  2. cURL extension: This PHP extension is used to make HTTP requests. Make sure you have this extension enabled.

  3. Whapi.Cloud account: To interact with WhatsApp, we will use the Whapi.Cloud service. Sign up for an account if you haven't done so already.

Setup Webhook on Whapi.Cloud

Before we start coding, you will need to set up a Webhook URL on Whapi.Cloud.

  1. Log in to your Whapi.Cloud account and go to your Channel Dashboard.

  2. Click on 'Settings', then 'Webhook'.

  3. Here, you can specify the URL where Whapi.Cloud should send the incoming messages. The URL should point to the PHP script we will create in the next step.

  4. Save your changes.

When messages arrive, you can process them to generate automatic responses, log them in databases, or even forward them to other platforms.

PHP Script

When a new message arrives, Whapi.Cloud can forward it to your webhookURL. This URL should point to a PHP script on your server. The incoming data will be in JSON format.

Sample Message Format

{
  "messages": [
    {
      "id": "IINCYddajIbJxaBbi0gwXQ-gOUSdTZG3w",
      "from_me": false,
      "type": "text",
      "chat_id": "15055913687@s.whatsapp.net",
      "timestamp": 1696502988,
      "text": {
        "body": "Hello"
      },
      "from_name": "Alexander"
    }
  ]
}

Sample PHP Script to Process the Message:

Create a PHP file named webhook.php in the root directory of your project. Below is the code for the webhook:

<?php
// Assuming you're using POST method for your webhook
$data = file_get_contents('php://input');
$json_data = json_decode($data, true);

if(isset($json_data['messages']) && is_array($json_data['messages'])) {
    foreach ($json_data['messages'] as $message) {
        $chat_id = str_replace('@s.whatsapp.net', '', $message['chat_id']);
        $text = $message['text']['body'];
        
        // Process the message
        handleIncomingMessage($chat_id, $text);
    }
}

function handleIncomingMessage($from, $message) {
    // TODO: Implement your logic here
    // For example: Save message to a database, send an email notification, etc.
    
    // Example: Send a thank you reply (you will need to use Whapi.Cloud API to actually send a message)
    if($message == 'Hello') {
        echo "Thank you for reaching out, " . $from;
        // Here, you could use the Whapi.Cloud API to send a reply. Read more in https://whapi.readme.io/reference/sendmessagetext
    }
    
    // Log message (just an example)
    file_put_contents('messages.log', "$from: $message\n", FILE_APPEND);
}

?>

The provided PHP script processes incoming WhatsApp messages forwarded by the Whapi.Cloud service to a specified webhook URL. Upon receiving a message, the script extracts the sender's phone number (chat_id) and the message content (text). Depending on the message content, it can generate predefined responses, log the message to a file, or be extended to save messages to a database, send email notifications, and more.

Extending the Script:

  1. Database Logging: Use the PHP Data Objects (PDO) extension to connect to your database and store the incoming messages.

  2. Email Forwarding: Integrate with PHPMailer or the built-in mail() function to forward messages to an email address.

  3. Automatic Responses: Set up predefined responses based on the incoming message's content.

  4. Integration with Other Systems: You can forward the message to CRM systems, ticketing systems, or any other platform your business uses.

Conclusion

That's it! You've now set up a PHP webhook to receive incoming WhatsApp messages. This powerful tool can significantly streamline your communication process, especially when handling high volumes of customer inquiries.

Feel free to experiment with your new setup and explore the possibilities. And if you encounter any issues or have any questions, don't hesitate to get in touch. We're always here to help!

Last updated