Twilio API — WhatsApp
Twilio is a cloud communications platform as a service company based in America. Twilio enables software developers to programmatically make and receive phone calls, send and receive text messages, and perform other communication functions through its web services APIs.
In this blog, we will be trying to understand how to work with Twilio WhatsApp API. I hope this will be as interesting as it sounds!
Let’s start by making an account on Twilio’s website. After verifying your email and phone number, add WhatsApp as the product that we are going to use and JavaScript as the preferred language in the form given.
You will be landed on a page with a prompt for creating a sandbox. We will definitely do it as we are preparing this as a testing set. Select the “agree” checkbox and click on the confirm button.
Now WhatsApp the code from the registered phone number to the WhatsApp number provided. You will see something like this -
Now test it with one-way and two-way messages by selecting a template. Now let’s start working on its integration into a website.
I hope you have NodeJs installed on your PC, if not, you can do it here. Open a terminal in a folder and execute the following command to initiate the project.
npm init
Keep tapping “Enter” until all the questions are completed. Then execute this -
npm i dotenv ejs express nodemon twilio
Now, add files and folders in this pattern to your directory.
Now, we will be adding the start command in the package.json file for our server to run on nodemon something like this —
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon index.js"},
Now run the following command on your terminal to host the website on your local server. (Server)
npm start
So, we will send messages through the website to the phone number registered in the sandbox. (P.S: you can add more numbers).
So let’s write the index.js file which consists of the endpoints of the website.
I know the code is pretty simple and easy to understand, but what about the accountSid and authToken? Get your credentials here and add it in .env file like this —
Let’s finally work on the User Interface by editing the index.ejs file —
The code consists of a form that will let you WhatsApp to the registered number. The User Interface will finally look like this here!
I hope you will fall in love with Twilio API and explore more. Feel free to ping me on LinkedIn in case you have any doubts!
Don’t forget to leave some claps if you liked this blog!