Help Desk
  • Getting Started
    • ๐Ÿ™ŒWelcome to Whapi.Cloud
    • ๐Ÿ’ฐPricing
    • โ˜•Partners
    • ๐Ÿš€Getting started
    • ๐Ÿ‘จโ€๐Ÿ’ปAPI Docs
      • Developer hubs
      • Swagger environment
      • Postman collection
  • Sending
    • Introduction
    • Send text message
      • Whatsapp API send message PHP
      • Whatsapp API send message Python
      • Whatsapp API send message Node JS
      • Whatsapp API send message ะก#
      • Whatsapp API send message Java
      • API integration with VB6
      • Whatsapp API send message GO (Golang)
    • Send video, audio, image, document
    • Send Group message
    • Send post to WhatsApp Channel
    • Send message with Buttons
    • Send Emoji
    • Overview of other methods for sending
      • Send Voice message
      • Send contact (vCard)
      • Send message reactions
  • Receiving
    • Introduction
    • Webhooks
      • Our webhooks (Tracked events)
      • Where to Find the Webhook URL?
      • Set the webhook link to the channel
      • Detailed webhook settings
      • How to check the webhook?
      • Incoming webhooks format
        • Incoming message
        • Sent message
        • Chats
        • Groups
        • Account and device status
        • Other
          • Presences
          • Views of stories (statuses)
          • Story (status) from your contacts
          • Calls
      • Receive messages
        • Receive WhatsApp messages using PHP
        • Receive WhatsApp messages using Node js
        • Receive WhatsApp messages using Python
    • HTTP API
      • Retrieve a Specific User's Chat History
      • Get a full-size picture in the response
      • Get order items
      • Get a profile picture of a chat or user
    • File expiration period
  • Groups
    • Send Group message
      • Mentioning all participants in a WhatsApp group
    • Get list of group members
    • Add new member to Group
  • Channels
    • Send post to WhatsApp Channel
    • Get messages from Channels
    • Get votes from polls in the Channel
  • Communities
    • Introduction
    • Create a community
    • Add a member to a community
    • Send announcement
    • Get info on community participants
    • Add a group / Exclude a group from the community
  • Account
    • Setting "Auto Download"
    • Customizable Webhook Headers
    • How to find out the IP channel
    • How to Delete a Channel
    • Add Business Info to Invoice
  • Source code
    • WhatsApp ChatBot
      • WhatsApp Python Bot
      • WhatsApp PHP Bot
      • WhatsApp Node JS Bot
      • WhatsApp Java Bot
    • WhatsApp API Google Sheets
    • WhatsApp Phone Number Checker
    • Request Distributor (Balancer)
  • FAQ
    • Chat ID. What is it and how to get it?
    • Current status of Buttons on WhatsApp
    • How to send a paragraph (line break)
    • Inactive Links in WhatsApp Messages
    • WhatsApp Text Formatting
    • Checking if the number has Whatsapp
    • Specifics of sending messages to numbers of different countries
    • Why aren't participants being added to the group?
  • Does WhatsApp API Work with the Phone Turned Off?
  • Hints
    • Android Emulators
    • Virtual Numbers for WhatsApp
    • How to use polls as buttons?
    • How to check who blocked you in Whatsapp?
    • Setting up a WhatsApp proxy
  • Integrations
    • Make.com
      • Ready-Made Scenarios
        • WhatsApp & Whisper API: Voice-to-Text Integration
        • Automated WhatsApp Group Message Forwarding in Make.com
      • Request Scenario Setup
    • Pabbly Connect
    • Google Contacts
    • DialogFlow
    • n8n
  • Tools
    • WhatsApp Number Checker
    • Automatic warm-up module
    • WhatsApp Activity Safety Meter
    • Residential Proxies from Whapi.Cloud
  • Troubleshooting
    • Couldn't Link Device โ€“ WhatsApp QR Code or Pairing Code Fails
    • Channel status โ€œSYNC_ERRORโ€
    • Not getting a READ status on webhook
    • 429 (Too Many Requests) - Soft Ban
    • โ€œWaiting for this message. This may take a whileโ€ โ€“ WhatsApp Message Error
    • Missing push notifications after connecting to API
  • Blocking
    • How to not get Banned?
    • How to do mailings without the risk of being blocked?
    • If My Number Is Banned, Can It Be Restored?
    • Unlocking Your WhatsApp Number
    • Connecting a New WhatsApp Number After a Ban: Steps and Recommendations
    • Warming Up New Phone Numbers for WhatsApp API
  • Partner Documentation
    • Introduction
    • Partner Dashboard Overview
    • Partner Program Guidelines
      • Workflow: Step-by-Step
      • Billing for Partners
      • Allocating Days to Customer Channels: Best Practices & Guide
      • Interface for channel management
    • Partner Documentation
      • Channel creation
      • Changing channel mode
      • Channel extension
      • Channel deletion
      • Getting the list of channels
      • Notices of end of days on balance
Powered by GitBook
On this page
  • Introduction
  • Setup Webhook on Whapi.Cloud
  • PHP Script
  • Conclusion

Was this helpful?

  1. Receiving
  2. Webhooks
  3. Receive messages

Receive WhatsApp messages using PHP

How to Receive WhatsApp messages using PHP and webhook

PreviousReceive messagesNextReceive WhatsApp messages using Node js

Last updated 10 months ago

Was this helpful?

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: . 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.

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.

Setup Webhook on Whapi.Cloud

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

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

  2. 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.

  3. 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!

Detailed manual about webhooks

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

to your Whapi.Cloud account and go to your Channel Dashboard.

here
Sign up
Log in
https://github.com/Whapi-Cloud/php-whatsapp-chatbot
Settings on your channel
Webhook settings