How to Use Twilio's WhatsApp API in CakePHP

March 27, 2024
Written by
Popoola Temitope
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

How to Use Twilio's WhatsApp API in CakePHP

With a large number of people using WhatsApp every day, Twilio's WhatsApp Business API allows businesses to communicate with their customers via WhatsApp. This can involve creating a WhatsApp support bot, sending authentication OTPs, and providing automated product previews via WhatsApp.

In this tutorial, we will explore how to send a customized message via WhatsApp to users using Twilio's WhatsApp Business API in a CakePHP application.

Requirements

To follow along with this tutorial, you will need to have the following:

Create a new CakePHP application

To scaffold a new CakePHP project using Composer, you need to run the command below on your terminal.

composer create-project --prefer-dist cakephp/app:~5.0 whatsapp_message

When prompted with "Set Folder Permissions? (Default to Y) [Y, n]?", answer with "Y" to complete the project installation.

Next, you need to run the command below to navigate the terminal to the project's working directory and start the application development server.

cd whatsapp_message
bin/cake server

Once the application server starts running, open http://localhost:8765 in your browser to access the application's default welcome page as shown in the screenshot below.

CakePHP default welcome page

To continue, you need to open the project in your preferred code editor.

Install the Twilio PHP Helper Library

Twilio's PHP helper library allows us to utilize Twilio's WhatsApp Business API in a CakePHP application relatively trivally. Run the command below in a new terminal window or tab to install it using Composer.

composer require twilio/sdk

Retrieve your Twilio API access tokens

You will need your Twilio Account SID and Auth Token to connect to Twilio with the PHP Helper Library. To retrieve them, log in to your Twilio Console dashboard, where you'll find them in the Account Info panel, as shown in the screenshot below.

Twilio Access Token

Store the Twilio access tokens as environment variables

After retrieving your Twilio access tokens, you need to ensure that they are stored securely in your project using environment variables.

The .env file is used for securely storing sensitive data. To use the .env file, you need to make a copy of the config/.env.example file and rename it to .env using the command below.

cp config/.env.example config/.env

Next, from the project's root directory, navigate to the config folder and open the .env file. Then add the following variables to it.

TWILIO_ACCOUNT_SID="<twilio_account_sid>"
TWILIO_AUTH_TOKEN="<twilio_auth_token>"

Then, replace TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN with your corresponding Twilio access token values.

Now, for the application to automatically load the environment variables, open the bootstrap.php file and uncomment the following lines.

if (!env('APP_NAME') && file_exists(CONFIG . '.env')) {
    $dotenv = new \josegonzalez\Dotenv\Loader([CONFIG . '.env']);
    $dotenv->parse()
        ->putenv()
        ->toEnv()
        ->toServer();
}

Set up the WhatsApp number

Now, let’s set up the Twilio Sandbox WhatsApp number. To do that, From your Twilio Console dashboard menu, navigate to Explore Products > Messaging > Try it out > Send a WhatsApp message option, as shown in the screenshot below.

Twilio WhatsApp dashboard

Next, follow the instructions to connect to the WhatsApp Sandbox, which you can see an example of in the screenshot above.

Joining Twilio WhatsApp number

Now, copy your Twilio number from the Twilio WhatsApp Sandbox's From field and add it to the .env file without the prefix whatsapp: as follows:

TWILIO_NUMBER="<twilio_whatsapp_number>"

In the code above, replace <twilio_whatsapp_number> with the WhatsApp number displayed on the Twilio WhatsApp Sandbox page.

Add the ability to send a WhatsApp message

Let’s create a SendWhatsAppMessage class that will connect the application to the applicable Twilio endpoint, which sends messages via WhatsApp to users. To do so, inside the src folder, create a new folder named Services. Inside the Services folder, create a file named TwilioService .php. Then, add the following code to the new file.

<?php
declare(strict_types=1);

namespace App\Services;

use Twilio\Rest\Client;

class TwilioService
{
    public function sendWhatsAppMessage($to, $message)
    {
        $accountSid = env('TWILIO_ACCOUNT_SID');
        $authToken = env('TWILIO_AUTH_TOKEN');
        $twilioNumber = env('TWILIO_NUMBER');
        $client = new Client($accountSid, $authToken);
        $message=  $client->messages->create(
                "whatsapp:$to",
                [
                    'from' => "whatsapp:$twilioNumber",
                    'body' =>"{$message}",
                ]
            );
            return $message->status;
    }
}

In the code above,

  • The sendWhatsAppMessage() method accepts two parameters: $to, representing the recipient's WhatsApp number, and $message the content to be sent.
  • The Twilio access tokens are retrieved from the relevant environment variables, and a Twilio client instance is instantiated with them.
  • The $client->messages->create() method is invoked, passing the recipient's WhatsApp number, Twilio number, and the message to be sent.

Create the controller

Now, let's create the application controller to handle the application logic. To create the controller, run the command below:

bin/cake bake controller WhatsAppMessage --no-actions

Running the above command will automatically generate the WhatsAppMessageController.php file inside the src/Controller folder. Open the WhatsAppMessageController.php file and replace its code with the following:

<?php
declare(strict_types=1);

namespace App\Controller;

use App\Services\TwilioService;

class WhatsAppMessageController extends AppController
{
    public function index()
    {
        $twilioService = new TwilioService();
        If ($this->request->is('post')) {
            $to = $this->request->getData('to');
            $message = $this->request->getData('message');
            $response = $twilioService->sendWhatsAppMessage($to, $message);
            if ($response == "failed" || $response=="undelivered") {
                $this->Flash->error('Failed to send WhatsApp message. Please try again later.');
            } else {
                $this->Flash->success('WhatsApp message initiated successfully. Message status: ' . $response . '.');
                
            }
        }
    }
}

In the code above:

  • $this->request->is("post") is used to check whether the form has been submitted.
  • Then the recipient's number and the message content are obtained from the form fields using $this->request->getData(). These details are then passed to the sendWhatsAppMessage() method to send the WhatsApp message.

Create the template

To create the application, navigate to the templates folder from the application's root directory and create a folder named WhatsAppMessage. Inside the folder, create a file named index.php and add the following code to it.

<?= $this->Form->create() ?>
<?= $this->Form->control('to', ['label' => 'Recipient WhatsApp Number']) ?>
<?= $this->Form->control('message', ['label' => 'Message']) ?>
<?= $this->Form->button('Send WhatsApp Message') ?>
<?= $this->Form->end() ?>

Add a route to the routing table

Now, navigate to the config folder and open routes.php. Locate $routes->scope() and add the following code before $builder->fallbacks().

$builder->connect('/WhatsAppMessage', ['controller' => 'WhatsAppMessage', 'action' => 'sendMessage', 'How to send WhatsApp message']);

Test the application

To test the application, open http://localhost:8765/whats-app-message in your browser. Enter the recipient's WhatsApp number and the message to send. Then, click the "Send WhatsApp Message" button to send it, as shown in the GIF image below:

There may be a delay in the delivery of the message depending on its status. Click here for more information.

Now, you should receive a message on your WhatsApp number, as shown in the screenshot below.

That's how you use Twilio's WhatsApp API in CakePHP

Twilio's WhatsApp Business API provides a powerful solution for businesses to engage with their users through WhatsApp. This tutorial demonstrates how to use Twilio's WhatsApp API in a CakePHP application to send customized messages to users.

Popoola Temitope is a mobile developer and a technical writer who loves writing about frontend technologies. He can be reached on LinkedIn.