Sending WhatsApp Messages using PHP

Nowadays, WhatsApp has become an indispensable communication tool. It offers a seamless and instant way to connect with others. Integrating WhatsApp messaging into your PHP applications can greatly enhance user engagement and streamline communication processes.

In this article, we will explore how to send WhatsApp messages using PHP, providing you with a step-by-step guide, a working example, and a user notification form to send messages to subscribers stored in a database.

Setting Up WhatsApp Business API

To send WhatsApp messages programmatically, you need to set up a Twilio(https://www.twilio.com) account. Before performing further operation signup or sign in to your Twilio account.

Obtain the authentication credentials required to interact with the WhatsApp Business API. These credentials include a private key file, an account token, and a phone number.

Installing the Required Libraries

To interact with the WhatsApp Business API in PHP, you’ll need to install the following libraries using Composer, a dependency management tool for PHP:

Open the terminal or command prompt and navigate to your project directory. Run the following command to install the Twilio libraries:

composer require twilio/sdk

Implementing the WhatsApp Message Sending using Form

In this example, you will take a message from the user as input and whenever a user submits a form then you will send that message to some users using Whatsapp API.

Create a new file and add below code to it:

<?php
require __DIR__ . '/vendor/autoload.php';

use Twilio\Rest\Client;

$accountSid = 'YOUR_TWILIO_ACCOUNT_SID';
$authToken = 'YOUR_TWILIO_AUTH_TOKEN';

$twilioNumber = 'YOUR_TWILIO_WHATSAPP_NUMBER';

$client = new Client($accountSid, $authToken);

function sendWhatsAppMessage($to, $message, $client, $twilioNumber)
{
    $client->messages->create(
        'whatsapp:' . $to,
        [
            'from' => 'whatsapp:' . $twilioNumber,
            'body' => $message
        ]
    );
}

// Handling form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $message = $_POST['message'];

    $servername = 'YOUR_MYSQL_SERVERNAME';
    $username = 'YOUR_MYSQL_USERNAME';
    $password = 'YOUR_MYSQL_PASSWORD';
    $database = 'YOUR_MYSQL_DATABASE';

    $conn = new mysqli($servername, $username, $password, $database);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT * FROM subscribers";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $subscriber = $row['phone_number'];
            sendWhatsAppMessage($subscriber, $message, $client, $twilioNumber);
        }
        echo "WhatsApp messages sent for ". $result->num_rows ." subscribers!";
    } else {
        echo "No subscribers found";
    }
    $conn->close();
}
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Whatsapp API intregration in PHP</title>
    </head>
    <body>
        <form method="POST" action="">
            <label for="message">Message:</label><br>
            <textarea id="message" name="message" rows="4" cols="50"></textarea><br><br>
            <input type="submit" value="Send Message">
        </form>
    </body>
</html>

Above example, we will take text input from the user where a user enters a message and we will send that message to all subscribers from a database. It’s just a simple textarea and submits button,

First of all, it will create a new instance for Twilio using an account SID, auth token, and WhatsApp number. You need to replace those values with your actual configurations.

After initializing Twilio object, It will fetch all subscribers from the database. If a database doesn’t have any subscribers then it will send a print message to user.

If there is more than 1 subscriber then it will send a WhatsApp notification with the user inputted message one by one. Here, we have defined a function to send messages which accepts phone number, message, Twilio instance, and sender’s number as parameters.

It will process message request one by one and after sending messages to all subscribers it will print a message for the user.

Conclusion

In this article, we have taken examples of how to send WhatsApp messages programmatically using PHP and Twilio. Additionally, we have provided a user notification form that allows you to send messages to subscribers stored in a database.

Here, we have taken a simple example. In actual implementation, you need to ensure necessary permissions and comply with relevant laws and regulations when sending WhatsApp messages. You can even optimize performance using chunking or creating a background process for sending messages.