Build the future of communications.
Start building for free

PHP + Twilio + Whatsapp: Would You Like to Play a Game?

PHP Twilio WhatsApp

There are 1.5 billion people using WhatsApp's end to end encrypted messaging platform to communicate. Many of those people prefer WhatsApp to SMS and other messaging platforms. It's currently the most popular messaging app in the world.

Twilio is adding options to the same API calls you use to send and receive SMS messages with Twilio, so you can now reach those users the way they prefer: on WhatsApp.

Using the Twilio API Sandbox for WhatsApp in your Twilio console, you can experiment with this new channel for connecting your software to the world.

Here are a few ways you can play with the Twilio API Sandbox for WhatsApp using PHP.

Before Getting Started

To code along with this post, you'll want:

Setting Up Your Project

First we'll create a new directory for our project, then create and save a file named composer.json with this content:

{
  "require": {
    "php": ">=7.1.0",
    "twilio/sdk": "^5.21",
    "vlucas/phpdotenv": "^2.5"
  }
}

With these instructions we are letting Composer know that this project requires PHP version 7.1 or greater, the Twilio SDK for PHP, and the vlucas/phpdotenv project which we will use to store information we don't want to save in a public repo (more on this later). From inside our new project directory, we'll run the following command to have composer follow these instructions:

composer install

screenshot of console having run composer install on the provided composer.json

Setting Up the Twilio API Sandbox for WhatsApp

Currently, only approved business accounts are cleared by WhatsApp for access through the Twilio API, but we can use the Twilio API Sandbox for WhatsApp to start experimenting.

Before we get started we'll need to do a bit of setup. We'll head over to the Sandbox in our Twilio console which is located under the Programmable SMS menu.  To activate our sandbox we'll select one of the Sandbox numbers, click to agree to WhatsApp terms, and click "Activate Sandbox". In the next section we find a couple of options for linking our personal WhatsApp account to the Sandbox.

Once our personal WhatsApp account is linked we can play around using the template forms in the Sandbox, but we're going to create a couple of PHP scripts to interact with the Twilio API for WhatsApp.  We'll want to come back to this page later to add our app's ngrok URL to the "Connect the Sandbox to your App" section, so we'll leave it open for now.

Sending a Template Message

There are two ways to send an outgoing WhatsApp message through the Sandbox. Either we can reply when our WhatsApp number messages us, or we can send out a message that matches one of the available templates.

For our first experiment we will be sending a message to our WhatsApp number using a template message. We don't need to use the forms in the console as long as the Body of our message matches one of the template with the {{}} replaced with real data.

In our project directory we'll create a new file, sendMessage.php, with the following content:

<?php

require_once './vendor/autoload.php';

use Twilio\Rest\Client;

$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();

// Your Account Sid and Auth Token from twilio.com/console
$sid    = getenv("TWILIO_ACCOUNT_SID");
$token  = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

The $dotenv lines here load the vlucas/phpdotenv package so we can put information we don't want to share into a .env file to be loaded into our code using the getenv calls.

Here's what our .env file looks like for our project:

TWILIO_ACCOUNT_SID="REPLACE WITH YOUR ACCOUNT SID"
TWILIO_AUTH_TOKEN="REPLACE WITH YOUR AUTH TOKEN"
TWILIO_WHATSAPP_NUMBER="+14155238886"
MY_WHATSAPP_NUMBER="+REPLACE WITH YOUR WHATSAPP NUMBER"

The value we probably won't need to change is the TWILIO_WHATSAPP_NUMBER as there are only a few options, but if we select a different Sandbox number we will need to replace that here as well.

The rest of our sendMessage.php code above pulls in our TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN from our .env file and uses that information to create a new instance of the Twilio Rest Client connected to our Twilio account.

Next we'll add the rest of the code that we need to actually send out our message in sendMessage.php:

<?php
//...
$codes = ["chocolate", "vanilla", "strawberry", "mint-chocolate-chip", "cookies-n-cream"];

$message = $twilio->messages
   ->create("whatsapp:".getenv("MY_WHATSAPP_NUMBER"),
       [
           "body" => "Your ice-cream code is ".$codes[rand(0,4)],
           "from" => "whatsapp:".getenv("TWILIO_WHATSAPP_NUMBER")
       ]
   );

print($message->sid);

We're using the template message "Your {{1}} code is {{2}}." We have to match the template exactly or we will get an error when we send out our message, but we also want to replace the {{1}} and {{2}} so we've had a little fun with it.

Notice that the code we're using to send our message is nearly identical to the code we'd use to send an SMS using the Twilio API except for prepending whatsapp: to our numbers.

Our print command at the end is just so we can see evidence of a successfully sent message when we run our command:

php sendMessage.php

Once we've run that command we can take a look at our WhatsApp to see the message.

screenshot of WhatsApp having received generated message: "Your ice-cream code is mint-chocolate-chip"

Interactive Messages

That was fun! But let's break out of our template constraints with an interactive script. Our WhatsApp account will need to initiate the interaction, but after that our script will be free to respond with any text we like.

We'll create a new file in our project directory, receiveMessage.php, with the following content:

<?php
require_once './vendor/autoload.php';

use Twilio\Twiml;

$response = new Twiml;
$guess = $_REQUEST['Body'];
$pick = rand(1,5);

if (!in_array($guess, [1,2,3,4,5])) {
   $response->message("Hiya! I'm thinking of a number between 1 and 5 - try to guess it!");
} elseif ($guess == $pick) {
   $response->message("Yes! You guessed it!");
} else {
   $response->message("Nope, it was actually $pick - Pick a new number to play again!");
}

print $response;

Here we don't need to bring in our account data. We are replying to a message so the Twilio API already knows which account its interacting with.

The message we receive will be in the $_REQUEST["Body"] which we use to determine the right response. If we don't receive a number between 1 and 5 then we reply with a message letting the sender know how to play. Otherwise we can inform the sender whether or not they guessed our number correctly.

The print statement at the end of this script is important. The reply will not be sent if we forget to include that.

To receive a message through the Twilio API our script will need to be accessible through a public URL. That's why we have ngrok setup! We'll launch ngrok for our project:

ngrok http 80

We should see output in our console which looks something like this:

screenshot of running ngrok instance

Then we'll copy the generated URL and paste that into the "Connect the Sandbox to Your App" form we left open in our console earlier, specifically into the field labeled "A message comes in".  We need to append "/receiveMessage.php" to the URL and then save.

screenshot of WhatsApp sandbox configuration inside the Twilio console. The field "A MESSAGE COMES IN" has been filled with the url "http://92832de0.ngrok.io/receiveMessage.php"

We're ready to play!

screentshot of WhatsApp interaction. Sent message: "Hello Twilio API for WhatsApp!", Received message: "Hiya! I&#39;m thinking of a number between 1 and 5 - try to guess it!", Sent Message: "5", Received Message: "Yes! You guessed it!"

Success!

We've now used the Twilio API for WhatsApp to send a template notification and to create a programmatic chat interaction with our personal WhatsApp account in PHP.

You can continue to experiment with WhatsApp using the different templates available in the console Sandbox. Check out the official documentation where you will also find notes on features coming soon!  

You can also look for inspiration in some of the fun projects team humans have put together like combining WhatsApp with Flex, using Twilio and WhatsApp to create an npm search bot, or creating Emoji translations with the Twilio API for WhatsApp and Node.js.

There's so much fun to be had and I can't wait to see what you build!

Be sure to come say hi if we end up at a tech conference together, and you can always find me where I live: here on the internet.

Authors
Sign up and start building
Not ready yet? Talk to an expert.