Building Your First WhatsApp Bot in PHP: A Beginner’s Guide to Code and Integration

Building a custom WhatsApp bot might seem daunting at first, but with clear guidance, it’s a manageable and rewarding project for developers—especially those just beginning to explore API integrations. This tutorial provides a straightforward path to s…


This content originally appeared on DEV Community and was authored by WhatsApp API for developers

Building a custom WhatsApp bot might seem daunting at first, but with clear guidance, it’s a manageable and rewarding project for developers—especially those just beginning to explore API integrations. This tutorial provides a straightforward path to setting up a WhatsApp bot in PHP, covering everything from API token setup to tailored message responses.

Designed for beginners, this guide is the perfect foundation for developing more advanced bots in the future.

Features of This WhatsApp Bot

This introductory bot is programmed to respond to incoming messages with preset text and image replies, depending on the message content. It’s a practical starting point for developers wanting to learn about API-driven interactions and automated messaging.

One standout feature: this bot operates seamlessly within WhatsApp Groups and communities, enabling you to bring automation to your WhatsApp channels with ease.

Prerequisites

To get started, make sure you have the following setup:

1. Obtain Your API Token

  1. Register on Whapi.Cloud. Whapi.Cloud provides an easy to use API gateway that is compatible with any programming language. It will allow you to integrate your website, store, app or CRM with WhatsApp without nerves.
  2. Download the ready-to-use bot source code from GitHub: https://github.com/Whapi-Cloud/whatsapp-simple-php-bot.
  3. Get your API Token to work with your WhatsApp. How to get the token is very detailed in this instruction.
  4. Save this token in /config/config.php for easy access by the bot.

2. Set Up Your Webhook URL

A webhook is a tool that enables one application to send real-time data to another. For this WhatsApp bot, the webhook URL is the designated address where WhatsApp sends incoming messages for your bot to process and reply.

To allow the bot to receive messages, you’ll need to configure a webhook URL.

This guide covers where to find this link, recommended server options, and popular solutions available. If you’re testing locally, however, a live server isn’t necessary. You can set up a tunnel to allow requests to reach your local machine.

Testing Locally: For local testing, use Ngrok to expose your server online temporarily, allowing you to simulate bot functions without needing to deploy on a live server.

Download and unzip Ngrok, then run:
./ngrok http PORT_NUMBER
Replace PORT_NUMBER with the port where your server is running.

Set Webhook URL in Dashboard: Copy the Ngrok-generated link as your webhook URL in the Whapi.Cloud dashboard. This directs incoming messages to your bot’s local server, allowing real-time interaction with WhatsApp.

Channel settings after it is connected to your number

3. Install Composer

Composer is needed to handle dependencies for this bot. Run the following commands to install Composer:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
php -r "unlink('composer-setup.php');"

4. Install Dependencies

With Composer installed, navigate to the bot’s directory and run:

php composer.phar install

5. Launch the Bot

After setting everything up, start the bot with the command:

php server.php

For a video tutorial on setup, check out our YouTube guide.

Understanding the Structure of Your WhatsApp Bot

This bot is structured with clarity and detailed comments, making it beginner-friendly and easy to navigate. Below is an overview of the primary components:

Core Modules

/src/channel.php
This module contains essential functions that manage communication between the bot and users:

  • checkHealth(): Confirms that the bot’s channel is functioning properly.
  • sendMessage(): Sends text messages to specified recipients.
  • setWebHook(): Configures the webhook automatically (optional).
  • getWebHooks(): Retrieves webhook details from the API.
  • sendLocalJPG(): Converts images from the /images/ directory to base64 and sends them as media messages.

The code snippet demonstrating sendMessage() functionality. This feature displays the “Typing” status in your WhatsApp for 5 seconds and then sends a text message after that:

public function sendMessage($to, $body): bool {
  $ch = curl_init('https://gate.whapi.cloud/messages/text');
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'Authorization: Bearer ' . $this->token,
      'Content-Type: application/json'
  ]);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
      'typing_time' => 5,
      'to' => $to,
      'body' => $body
  ]));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($ch);
  $data = json_decode($response, true);
  curl_close($ch);

  return $data['sent'] ?? false;
}

Primary Logic

/src/Whapi.php
The main logic for the bot resides here, controlling how it processes and responds to incoming messages:

  • Message Filtering: Screens out outgoing messages, ensuring only external incoming messages are handled.
  • Sender and Content Parsing: Extracts the sender’s phone number and the message text.
  • Command-Based Responses: Uses a switch statement to define responses based on specific commands or keywords received.

This structure allows for easy customization and extension, providing a solid foundation to build upon as you add new features.

// The main cycle of the bot is to check and react to the incoming message depending on the text
switch ($receivedText) {
  case 'help':
      $channel->sendMessage($senderPhone, 'Text1'); // If the bot receives the message 'help', it will send the message 'Text1'
      break;
  case 'command':
      $channel->sendMessage($senderPhone, 'Text2');
      break;
  case 'image':
      $channel->sendLocalJPG(__DIR__ . '/../public/images/example.jpeg', $senderPhone, 'Caption'); // We encode the picture in base64, so it's easier to send a media message.
      break;
  default:
      $channel->sendMessage($senderPhone, 'Unknown command'); // On an unknown team, it's best to send navigation information to help your customer navigate
      break;
}

Customizing and Expanding Your WhatsApp Bot

With the initial setup complete, you have a strong foundation to enhance your bot with new features and customizations. Here are some ways to expand its functionality and tailor it to your needs.

Add Custom Commands and Responses

Customize your bot’s behavior by adding commands within the /src/Whapi.php file. Expand the switch statement to recognize additional keywords or phrases and create unique responses, from text and images to other content types.

Send Varied Content

Go beyond basic text and images by implementing advanced messaging options available through Whapi.Cloud’s API. These include:

  • Files in multiple formats
  • Location sharing
  • Contact information cards
  • Stickers and polls
  • Product listings within messages
  • Interactive messages with buttons for user actions

Interactive Message Reactions

Make your bot more engaging by adding message reactions. Enable it to quote messages, respond with emoji reactions, mark messages as read, or show real-time typing indicators. These small interactions add a human-like element to your bot’s responses.

Automated WhatsApp Group Management

With Whapi.Cloud’s API, you can automate a range of group management tasks, turning your bot into a powerful tool for group coordination:

  • Automatically create, modify, or delete groups.
  • Access group information, including member details and total counts.
  • Manage membership by adding or removing users, assigning administrator roles, and blocking members.
  • Customize group settings like name, avatar, and permissions.
  • Generate and share group invitation links effortlessly.

For full implementation details and code examples, check out Whapi.Cloud’s detailed documentation. Each method is thoroughly explained with examples to help you unlock the full potential of your bot’s capabilities.

These enhancements make it possible to build a highly functional WhatsApp bot tailored to your unique needs, going far beyond basic message responses.

FAQs and Troubleshooting

Setting up and running a WhatsApp bot can sometimes present challenges. Here are some solutions for common issues to help keep your bot operating smoothly:

Bot Isn’t Responding to Incoming Messages

1. Confirm Your Testing Method
Make sure you’re testing from a different phone number than the one the bot uses. The bot is designed to respond only to messages from external sources, so messages from the same number won’t trigger a response.

2. Check Webhook Functionality
If the bot still isn’t responding, the webhook configuration might need attention. Here are a few steps to troubleshoot:

  • Simulate Webhook Requests: Use a tool like Webhook Request Debugger to simulate incoming requests and confirm that your bot’s webhook URL matches what the API expects.
  • Server Response Verification: Ensure your server responds with a 200 OK status, indicating that the webhook is active and receiving requests.

You can also use an endpoint tester to verify your webhook link, which sends test callbacks to simulate real incoming requests.

3. Contact Technical Support
If these steps don’t resolve the issue, reach out to our technical support team. Use the chat widget on our website or email care@whapi.cloud, and our team will assist with any webhook or bot configuration issues to get you up and running.

Conclusion

This WhatsApp bot in PHP offers an ideal entry point for beginners exploring chatbot creation and API integration. By following this guide, you’ll develop foundational skills for building more advanced bots capable of responding to various commands with text, images, and more. This project lays the groundwork for creating versatile and interactive bots that can grow in complexity as you expand your API knowledge.


This content originally appeared on DEV Community and was authored by WhatsApp API for developers


Print Share Comment Cite Upload Translate Updates
APA

WhatsApp API for developers | Sciencx (2024-11-06T08:44:45+00:00) Building Your First WhatsApp Bot in PHP: A Beginner’s Guide to Code and Integration. Retrieved from https://www.scien.cx/2024/11/06/building-your-first-whatsapp-bot-in-php-a-beginners-guide-to-code-and-integration/

MLA
" » Building Your First WhatsApp Bot in PHP: A Beginner’s Guide to Code and Integration." WhatsApp API for developers | Sciencx - Wednesday November 6, 2024, https://www.scien.cx/2024/11/06/building-your-first-whatsapp-bot-in-php-a-beginners-guide-to-code-and-integration/
HARVARD
WhatsApp API for developers | Sciencx Wednesday November 6, 2024 » Building Your First WhatsApp Bot in PHP: A Beginner’s Guide to Code and Integration., viewed ,<https://www.scien.cx/2024/11/06/building-your-first-whatsapp-bot-in-php-a-beginners-guide-to-code-and-integration/>
VANCOUVER
WhatsApp API for developers | Sciencx - » Building Your First WhatsApp Bot in PHP: A Beginner’s Guide to Code and Integration. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/11/06/building-your-first-whatsapp-bot-in-php-a-beginners-guide-to-code-and-integration/
CHICAGO
" » Building Your First WhatsApp Bot in PHP: A Beginner’s Guide to Code and Integration." WhatsApp API for developers | Sciencx - Accessed . https://www.scien.cx/2024/11/06/building-your-first-whatsapp-bot-in-php-a-beginners-guide-to-code-and-integration/
IEEE
" » Building Your First WhatsApp Bot in PHP: A Beginner’s Guide to Code and Integration." WhatsApp API for developers | Sciencx [Online]. Available: https://www.scien.cx/2024/11/06/building-your-first-whatsapp-bot-in-php-a-beginners-guide-to-code-and-integration/. [Accessed: ]
rf:citation
» Building Your First WhatsApp Bot in PHP: A Beginner’s Guide to Code and Integration | WhatsApp API for developers | Sciencx | https://www.scien.cx/2024/11/06/building-your-first-whatsapp-bot-in-php-a-beginners-guide-to-code-and-integration/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.