How to Create a WhatsApp Survey Using Twilio and CakePHP
Time to read: 6 minutes
How to Create a WhatsApp Survey Using Twilio and CakePHP
A survey is a research method used to collect data from a predefined group of respondents to gain insights into various topics of interest. Collecting surveys through WhatsApp can be an efficient and easy way to gather feedback from people, particularly when the target respondents are already using the platform.
In this tutorial, you will learn how to create a WhatsApp survey application using Twilio and CakePHP to efficiently collect survey responses from users.
Prerequisites
To complete this tutorial, ensure that you have the following:
- PHP 8.3 or higher installed
- Composer installed globally
- Access to a MySQL database
- A Twilio account (free or paid). Create an account if you are new to Twilio.
- Ngrok installed on your computer and an Ngrok account
Create a new CakePHP project
Let’s scaffold a new CakePHP application using Composer. To do this, open your terminal, navigate to the directory where you want to scaffold the project, and run the command below.
The command above will prompt you to set folder permissions. Enter ' Y' to confirm.
Connect to a database
To interact with a MySQL database, you need to add the database connection details to the application's configuration file. To do this, open the project in your preferred code editor or IDE, navigate to the config folder, and open the app_local.php file.
Inside the app_local.php file, locate the default subsection of the Datasources section. This subsection contains the database connection details. Replace the host, username, password, and database name with your actual database values, as exemplified in the screenshot below.
Next, create a new database named survey
in your MySQL database.
Create the database tables
Let's create the questions and answers database tables by generating the migration files for the two tables using CakePHP's migration features. To do that, run the following commands.
The command above will generate three migration files: _Questions.php, _Answers.php, and _Contact.php, which will be located in the config/Migrations folder.
Now, let’s define the tables' schema and properties. To do this, navigate to the config/Migrations folder and open the migration file that ends with _Contact.php. Then update the body of the change()
function with the following code.
Now, to define the schema for the "Questions" table, open the migration file ending in _Questions.php and add the following code to the change()
function.
Next, open the second generated file that ends with _Answers.php and add the following code to the change()
function.
With the updates made, run the command below to execute the database migrations.
Create the application model and entity
To allow the application's controller to easily interact with the database tables, you need to create CakePHP models and entities for each table. You can do this by running the following commands.
Set up the application's environment variables
Now, let's create environment variables for the application's API keys. To do this, run the command below.
Then navigate to the config folder, open the .env file, and add the following at the end of the file.
To load the environment variables into the application, open the bootstrap.php file inside the config folder and uncomment the following lines of code.
Retrieve your Twilio API credentials
Next, let's retrieve the Twilio API credentials and add them to the environment variables. Log in to your Twilio console dashboard, and under the Account Info section, you'll find your Twilio Account SID and Auth Token, as shown in the screenshot below.
Now, replace the <actual_account_sid>
and <actual_auth_token>
placeholders in .env with your Twilio Account SID and Auth Token that you just copied.
Set up your Twilio WhatsApp Sandbox and retrieve your number
Let's connect to the Twilio WhatsApp sandbox. To do this, go back to your Twilio Console dashboard, and from the side menu navigate to Explore Products > Messaging > Try it Out > Send a WhatsApp Message, as shown in the screenshot below.
From the WhatsApp Sandbox page:
- Copy the Twilio WhatsApp number and replace the
<twilio_whatsapp_number>
placeholder in .env - Send the displayed join message to the Twilio WhatsApp number via WhatsApp, as shown in the screenshot above
Install Twilio's PHP Helper Library
To enable easy interaction with the Twilio WhatsApp API, let’s install the Twilio PHP Helper Library using the command below in a new terminal tab or session.
Create the survey controller
Let's create a controller to manage the application logic, such as adding new survey questions, processing incoming survey answers, and viewing collected data. To do this, run the command below in your terminal to create a controller named SurveyController
.
The command above will generate a SurveyController.php file inside the src/Controller folder. Open the controller file and update it with the following code.
In the code above:
- The
invite()
method is used to send survey invitations to users' WhatsApp numbers - The
processResponse()
method handles incoming WhatsApp messages containing user responses to survey questions and stores them in the database - The
addQuestion()
method adds new survey questions to the database - The
viewStatistics()
method retrieves all collected data, making it available to the admin for analysis
Create the application's templates
Let’s create templates for the application to handle the invite()
, addQuestion()
, and viewStatistics()
methods. To do this, navigate to the templates folder and create a new folder named Survey. Then, inside the Survey folder, create a file named invite.php and add the following code:
Then, in the same directory, create a file named add_question.php and add the following code to it:
Now, create a file named view_statistics.php in the same directory as the previous two and add the following code to it:
Configure the router
Now, let’s add the invite
, processResponse
, addQuestion
, and viewStatistics
routes to the application. From the application's root folder, navigate to the config folder and open the routes.php file. Inside the file, locate $routes->scope()
and add the following code before $builder->fallbacks()
.
Next, let’s disable CSRF protection for the /api/process-response
API endpoint. To do this, open the Application.php file inside the src folder and update the middleware()
function to match the following definition.
Now, let’s start the development server by running the command below.
Configure Twilio’s WhatsApp webhook
Next, let’s make the application accessible on the internet using ngrok, which will allow Twilio webhooks to send WhatsApp responses to your application for processing. To do that, open another terminal tab or session and run the command below.
The command above will generate a Forwarding URL, as shown in the screenshot below.
Now, back in your Twilio Console, on the Try WhatsApp page, click on Sandbox Settings and configure the Sandbox as follows.
- In the When a message comes in field, paste the ngrok Forwarding URL and append /api/process-response to the end of it
- Set the Method field to POST
Next, click Save to apply the Sandbox configuration, as shown in the screenshot below.
Test that the application works as expected
To Test the application open the ngrok Forwarding URL in your browser. The CakePHP default page should appear, as shown in the screenshot below.
Let's store the survey questions in the database. Open <ngrok Forwarding URL>/survey/add-question
in your browser, replace the <ngrok Forwarding URL>
placeholder with the ngrok Forwarding URL, and add your survey question as shown in the screenshot below.
After setting up all the survey questions, the next step is to invite users to participate. Open <Forwarding-URL>/survey/invite
and enter the user's mobile/cell number in E.164 format to send an invitation, as shown in the screenshot below.
On WhatsApp, reply with 'YES' to start the survey, and then answer the questions as shown in the screenshot below.
To view the collected responses, open <Forwarding-URL>/survey/statistics
in your browser. You will see the statistics for the collected survey responses, as shown in the screenshot below.
That’s how to create a WhatsApp survey using Twilio and CakePHP
Creating a WhatsApp survey application is an effective way to gather valuable feedback from your audience. In this tutorial, you learned how to build a WhatsApp survey application using Twilio and CakePHP to efficiently collect feedback from users.
Popoola Temitope is a mobile developer and a technical writer who loves writing about frontend technologies. He can be reached on LinkedIn.
The investigation icon in the tutorial's main image was created by Dewi Sari on Flaticon.
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.