Part 1: If you don't have time to read
This example of the bot implementation touches in detail on the most frequently used functionality. This will allow you to adapt the source code to your tasks and needs, or take it as a basis for creating any other integration. We have left comments near each function to make it easier for you to understand the code. In the source code of the bot you will find the following functionality:
- Respond to an unfamiliar command, this could be an instruction or your welcome message;
- Send regular message;
- Send image;
- Send file;
- Send video
- Send contact (vCard);
- Send product;
- Create new group, send an invitation and send message to the group;
- Receive and reading incoming messages;
For the bot to work, it is NOT REQUIRED that the phone is turned on or online. Connect the number and test the integration comfortably!
And if you need any help, just write to us in the support chat on any page of the site.
And if you need any help, just write to us in the support chat on any page of the site.
Why should you create a WhatsApp Chatbot?
In today's world, WhatsApp isn't just the leading instant messaging platform with billions of users, but also an integral tool for business. Automating messenger functions offers a range of strategic advantages: from instant customer support to effective marketing and feedback collection. In light of this, creating a bot for WhatsApp becomes a key step in optimizing business processes and establishing direct contact with your audience.
In this guide, we will provide step-by-step instructions on creating a bot for WhatsApp in PHP. You will learn:
- How to work with the WhatsApp API;
- Understand the nuances of creating chatbots in PHP;
- Automate and enhance interactions with your clients;
Preparing for the start - What you will need
Before we delve into the practical aspect of creating a bot for WhatsApp in PHP, ensure you have all the necessary tools and resources.
- Whapi.Cloud Account. To work with the WhatsApp API, you'll need an account on Whapi.Cloud. This provider offers developers methods to automate WhatsApp and API documentation. Currently, Whapi.Cloud is the most functional and stable provider providing affordable access to the WhatsApp API. After registering, you'll receive a free channel with a unique API token key, allowing your PHP application/integration to interact with the messenger.
- Server with PHP or local development. If you decide to test your bot locally and want it to interact with WhatsApp via a Webhook, tools like ngrok can be used. This application creates secure tunnels to your local server, giving temporary public URLs you can use for testing. To have the server invoke our script when new messages are received, we need to specify the WebHook URL in the channel settings. We will discuss this in detail further on.
Working with WhatsApp API via Whapi.Cloud
Register and go to your channel's page. By registering for the first time, you will receive 5 days of full API access, which will be sufficient to test all methods from the API. If this is not enough, contact the service support through the web chat widget, and they will remove the restrictions for comfortable testing.
The next step will be connecting your WhatsApp number. Don't worry, you can disconnect at any time, but this is necessary to check your implementation. So, go to your personal panel, find your first channel named Default Channel and click on it. As the first step, you will see a QR code and a brief instruction. Open WhatsApp on your mobile device, go to Settings -> Linked Devices -> Connect Device -> Scan QR Code.




During the connection, at steps two and three, you will have the opportunity to set up your channel. Name the channel for convenience (by the way, our API will immediately determine whether you use the standard or business version of the app with extended functions). Then, the webhook settings and other parameters of your choice will be available. However, these actions can be done later and you can skip this step.
After activating the channel in the limits information section, find your API token. This token is critically important for authentication when accessing the API. Typically, it's passed in the request headers as a Bearer Token or as a parameter, depending on how you access the API.
The Whapi.Cloud API provides a wide range of methods to interact with WhatsApp, truly allowing you to automate the messenger's key capabilities and functions. On the channel page, you can study and try out all the available methods. For convenience in development, you are provided with a specialized hub for developers, where each function comes with code examples and the ability to test on-site, displaying results and server responses.
This greatly simplifies and speeds up the integration process, you'll love it! One of the advantages of Whapi.Cloud is its simplicity and speed of connection, allowing you to start interacting with WhatsApp in just a few minutes.
After activating the channel in the limits information section, find your API token. This token is critically important for authentication when accessing the API. Typically, it's passed in the request headers as a Bearer Token or as a parameter, depending on how you access the API.
The Whapi.Cloud API provides a wide range of methods to interact with WhatsApp, truly allowing you to automate the messenger's key capabilities and functions. On the channel page, you can study and try out all the available methods. For convenience in development, you are provided with a specialized hub for developers, where each function comes with code examples and the ability to test on-site, displaying results and server responses.
This greatly simplifies and speeds up the integration process, you'll love it! One of the advantages of Whapi.Cloud is its simplicity and speed of connection, allowing you to start interacting with WhatsApp in just a few minutes.
What is Webhook and how do I set it up?
Your WhatsApp bot and our API gateway need to communicate, so when something changes in one system, the other system knows about it. For example, tracking message status changes, such as "sent", "delivered", and "read".
This is where the Webhook comes in! A configured Webhook allows your server to instantly know about specific events. Based on your settings, you can receive notifications about messages, their current status, channel status, phone, missed calls, and so on. The main difference of Whapi.Cloud is its flexibility in setting up and managing webhooks. You can set multiple different hooks for any event. And various additional options, like Auto Download or Webhook Mode, will make your work easier.
We've explored all the nuances of working with webhooks in more detail in our knowledge base: View article about webhooks


Navigate to the configuration of your channel using the button in the upper right corner. At the very beginning, you will see the webhooks section. Provide the URL of your server to receive notifications. If needed, add additional webhooks, choose the Mode and the working mode of the hook. When a message comes to you, a POST request with message information is sent to the URL you specified. This allows your bot to analyze incoming messages and respond accordingly. Webhooks can be set up either through the interface in the personal cabinet or programmatically via the API (method /Update channel settings/). How to work with incoming information and process it will be discussed later.
Creating the basis of a bot in PHP
Send and Receive message
First, let's define the structure of your project. Install Composer (if you haven't already), Initialize the project with "composer init", install dependencies and autoloader generation. You will have a vendor folder with the autoloader. Now you can plug the Composer autoloader at the beginning of your index.php file. After these basic steps, your project will be ready for further development.
Let's create the root directory public: this is where the main executable (e.g. index.php), config.php (for storing configurations, such as your API key) and the "files" folder (for storing files you will send) will be located.
Let me remind you that the entire source code of this project can be downloaded from GitHub: https://github.com/Whapi-Cloud/php-whatsapp-chatbot
config.php
return [
// API endpoint URL
"apiUrl" => "https://gate.whapi.cloud",
// API token from your channel
"token" => "YOUR CHANNEL TOKEN",
// The ID of the group to which we will send the message. Use to find out the ID: https://whapi.readme.io/reference/getgroups
"group" => '120363167596599603@g.us',
// The ID of the product we will send for the example. Create a product in your WhatsApp and find out the product ID: https://whapi.readme.io/reference/getproducts
"product" => '6559353560856703',
// Bot`s URL. Webhook Link to your server. At ( {server link}/messages ), when POST is requested, processing occurs in index.php
"botUrl" => "https://yoursite.com/messages"
];
index.php
require '../vendor/autoload.php';
use GuzzleHttp\Client;
use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;
// Don't forget to put your token in config.php
$config = require './config.php';
$app = new App();
$client = new Client([
'base_uri' => $config['apiUrl']
]);
// Commands for example bot
const COMMANDS = [
'TEXT' => 'Simple text message',
'IMAGE' => 'Send image',
'DOCUMENT' => 'Send document',
'VIDEO' => 'Send video',
'CONTACT' => 'Send contact',
'PRODUCT' => 'Send product',
'GROUP_CREATE' => 'Create group',
'GROUP_TEXT' => 'Simple text message for the group',
'GROUPS_IDS' => 'Get the id\'s of your three groups'
];
// Url files for example
const FILES = [
'IMAGE' => './files/file_example_JPG_100kB.jpg',
'DOCUMENT' => './files/file-example_PDF_500_kB.pdf',
'VIDEO' => './files/file_example_MP4_480_1_5MG.mp4',
'VCARD' => './files/sample-vcard.txt'
];
function sendWhapiRequest($endpoint, $params = [], $method = 'POST')
{
global $config, $client;
$url = $config['apiUrl'] . '/' . $endpoint;
$options = [
'headers' => [
'Authorization' => 'Bearer ' . $config['token'],
],
];
if ($params && count($params) > 0) {
if ($method === 'GET') {
$url .= '?' . http_build_query($params);
} else {
if(isset($params['media'])){
$options['multipart'] = toFormData($params);
}else{
$options['headers']['Content-Type'] = 'application/json';
$options['body'] = json_encode($params);
}
}
}
echo '$options: ' . print_r($options, true);
$response = $client->request($method, $url, $options);
$json = json_decode($response->getBody()->getContents(), true);
echo 'Whapi response: ' . print_r($json, true);
return $json;
}
function toFormData($params)
{
$multipart = [];
foreach ($params as $name => $contents) {
$multipart[] = ['name' => $name, 'contents' => $contents];
}
return $multipart;
}
// Call this function if you want to setup a webhook through the API. In this example it is not called: you will need to go to the channel settings in your personal cabinet and set the webhook link like {link to your server}/messages
function setHook()
{
global $config;
if ($config['botUrl']) {
sendWhapiRequest('settings', [
'webhooks' => [
[
'url' => $config['botUrl'],
'events' => [
[
'type' => 'message',
'method' => 'post'
]
],
'mode' => 'body'
]
]
], 'PATCH');
}
}
$app->get('/', function (Request $request, Response $response) {
return $response->write('Bot is running');
});
$app->post('/messages', function (Request $request, Response $response) use ($config) {
$data = json_decode($request->getBody(), true);
$messages = $data['messages'] ?? [];
foreach ($messages as $message) {
if ($message['from_me']) {
continue;
}
$sender = ['to' => $message['chat_id']];
$endpoint = 'messages/text';
$textBody = trim($message['text']['body'] ?? '');
$commandIndex = is_numeric($textBody) ? (int)$textBody - 1 : null;
$commands = array_keys(COMMANDS);
$command = $commands[$commandIndex] ?? null;
switch ($command) {
case 'TEXT':
$sender['body'] = 'Simple text message';
break;
case 'IMAGE':
$sender['caption'] = 'Text under the photo.';
$sender['media'] = fopen(FILES['IMAGE'], 'r');
$endpoint = 'messages/image';
break;
case 'DOCUMENT':
$sender['caption'] = 'Text under the document.';
$sender['media'] = fopen(FILES['DOCUMENT'], 'r');
$endpoint = 'messages/document';
break;
case 'VIDEO':
$sender['caption'] = 'Text under the video.';
$sender['media'] = fopen(FILES['VIDEO'], 'r');
$endpoint = 'messages/video';
break;
case 'CONTACT':
$sender['name'] = 'Whapi Test';
$sender['vcard'] = file_get_contents(FILES['VCARD']);
$endpoint = 'messages/contact';
break;
case 'PRODUCT':
// Replace with your product ID
$endpoint = "business/products/{$config['product']}";
break;
case 'GROUP_CREATE':
$groupSettings = [
'subject' => 'Whapi.Cloud Test',
'participants' => [$message['from']]
];
$groupResponse = sendWhapiRequest('groups', $groupSettings, 'POST');
$sender['body'] = $groupResponse['group_id'] ? "Group created. Group id: {$groupResponse['group_id']}" : 'Error';
$endpoint = 'messages/text';
break;
case 'GROUP_TEXT':
$sender['to'] = $config['group'];
$sender['body'] = 'Simple text message for the group';
break;
case 'GROUPS_IDS':
$groupsResponse = sendWhapiRequest('groups', ['count' => 3], 'GET');
if (!empty($groupsResponse['groups'])) {
$groupIds = array_map(function ($group, $i) {
return ($i + 1) . ". {$group['id']} - {$group['name']}";
}, $groupsResponse['groups'], array_keys($groupsResponse['groups']));
$sender['body'] = implode(",\n ", $groupIds);
} else {
$sender['body'] = 'No groups';
}
break;
default:
$sender['body'] = "Hi. Send me a number from the list. Don't forget to change the actual data in the code! \n\n" .
implode("\n", array_map(function ($text) {
static $i = 0;
$i++;
return ($i) . ". $text";
}, COMMANDS, array_keys(COMMANDS)));
break;
}
try {
sendWhapiRequest($endpoint, $sender);
} catch (\Exception $e) {
error_log($e->getMessage());
return $response->withStatus(500)->write('Error: ' . $e->getMessage());
}
}
return $response->withStatus(200)->write('Ok');
});
$app->run();
This simple bot will respond to unfamiliar commands with a menu message, as well as react with certain actions to specific commands.
Since the responses are in JSON format, this gives great scope for developing your bot. This can include details such as the time and delivery status of the message or the status of the user (online or offline), allowing your bot to optimize customer interactions. Our documentation and Developer Hub provide full details on the response structure and expected parameters for each request. All details and parameters are described in the documentation. Use the weightb functionality to make your bot even more efficient.
Advanced features
In our detailed documentation, you will find step-by-step instructions and usage examples of methods that allow sending diverse content, from files of any format, locations, and contacts to stickers, polls, and products in a message. Moreover, you can interact with messages by quoting them, reacting through emojis, marking as read, attaching or simulating real-time typing when replying.
Automating groups in WhatsApp via Whapi.Cloud offers extensive capabilities. With the API, you can effortlessly create, edit, or delete groups automatically, obtain information about groups and group members (numbers, names, overall count), manage members, define administrator roles, adjust group parameters (avatars, name, settings), create invitations via links, block members, and much more. All available methods are detailed in the Whapi.Cloud documentation.


With such an expansive array of capabilities at your disposal, crafting a bot tailored to any level of complexity and purpose becomes a breeze. Seamlessly integrate your PHP-based bot into any platform, be it a website, app, CRM, ERP system, and beyond.
Send media-image message
Sending a media-image message through a WhatsApp bot enhances user engagement, provides a more dynamic and interactive experience, and allows businesses to showcase products or convey messages visually, creating a richer communication channel compared to text alone. Here's how to send a picture via Whatsapp API with PHP:
const BASE_URL = 'https://gate.whapi.cloud/';
$token = 'bg3FeZJ6jWGw32g03PRnoNkKO7k03GtX'; // Your API token
$data = array (
'media' => 'https://upload.wikimedia.org/wikipedia/commons/b/ba/Leonardo_self.jpg',
'to' => '1234567891@s.whatsapp.net',
'mime_type' => 'jpg',
'caption' => 'Leonardo Self'
);
$data_json = json_encode($data);
$url = BASE_URL . 'messages/image';
$options = array(
'http' => array(
'method' => 'POST',
'header' => array(
'Authorization: Bearer '.$token,
'Content-Type: application/json',
'Accept: application/json'
),
'content' => $data_json
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
echo $response;
Send file via WhatsApp API
Sending files through a WhatsApp bot streamlines information sharing, offers a secure and instant way to distribute important documents, and enhances user experience by providing more versatile communication options beyond text and images. Here's how to send a file via Whatsapp API with PHP:
const BASE_URL = 'https://gate.whapi.cloud/';// Ensure that the PHP allow_url_fopen setting is enabled, as file_get_contents requires it for URL handling.
$token = 'bg3FeZJ6jWGw32g03PRnoNkKO7k03GtX'; // Your API token
$data = array (
'to' => '1234567891@s.whatsapp.net',
'media' => 'data:application/octet-stream;name=site.webmanifest;base64,ewogICAgIm5hbWUiOiAiIiwKICAgICJzaG9ydF9uYW1lIjogIiIsCiAgICAiaWNvbnMiOiBbCiAgICAgICAgewogICAgICAgICAgICAic3JjIjogIi9hbmRyb2lkLWNocm9tZS0xOTJ4MTkyLnBuZyIsCiAgICAgICAgICAgICJzaXplcyI6ICIxOTJ4MTkyIiwKICAgICAgICAgICAgInR5cGUiOiAiaW1hZ2UvcG5nIgogICAgICAgIH0KICAgIF0sCiAgICAidGhlbWVfY29sb3IiOiAiI2ZmZmZmZiIsCiAgICAiYmFja2dyb3VuZF9jb2xvciI6ICIjZmZmZmZmIiwKICAgICJkaXNwbGF5IjogInN0YW5kYWxvbmUiCn0K',
'filename' => 'webmanifest',
'caption' => "It's my file",
'view_once' => true
);
$data_json = json_encode($data);
$url = BASE_URL . 'messages/document';
$options = array(
'http' => array(
'method' => 'POST',
'header' => array(
'Authorization: Bearer '.$token,
'Content-Type: application/json',
'Accept: application/json'
),
'content' => $data_json
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
echo $response;
Conclusion and recommendations
Building a WhatsApp bot using PHP and leveraging the Whapi.Cloud service for API integration simplifies the complexities associated with messaging platforms. As we've demonstrated throughout this guide, the process can be broken down into manageable steps that even those new to PHP or API integrations can understand and implement.
This bot is designed with a "plug-and-play" philosophy. To get started is straightforward. Firstly, all you need to do is register on our service. We offer a free trial, enabling you to test out all the functionalities before making a purchasing decision. Once registered, upload the bot code to your server. By following the instructions provided in this article, your bot will be up and running in no time.
Remember, should you encounter any questions or challenges along the way, our support team is always on hand to assist. We value every user and are committed to ensuring your experience with our API is as seamless and efficient as possible.