We all use WhatsApp in our daily life to send text messages to one another. We can send WhatsApp messages using the Twilio API in NodeJS using the following approach.
Features of Twilio:
- Widely used module for sending text messages.
- Supports various languages.
- Can be also used to send programmable voice messages.
Step 1: Creating a Twilio Account
Create a Twilio account and go to the WhatsApp Sandbox section, you can find the WhatsApp Sandbox section over here.
Step 2: Linking your WhatsApp number
Send a message defined by Twilio from your WhatsApp number to +14155238886 to set up the Twilio Sandbox.
The code mentioned in the below image is join movement-limited
Once the sandbox is successfully set up, we get a success message as shown in the below image.
Step 3: Setting up our files.
To setup our project, we first need to add a package.json file that keeps track of our dependencies. The package.json file is initialized using the following command.
npm init --y
Note: The –y tag makes yes as the default answer for all the questions.
Step 4: Installing the Twilio module.
Once our number is successfully linked, we can start sending WhatsApp messages. But first, we need to install the Twilio module. You can learn more about the Twilio module here. We can install the Twilio module using the following command.
npm i twilio
Step 5: Creating a file
Create a file with .js extension in the same npm repository. We can run the file using the following command.
Step 6: Importing the Twilio module.
To use the Twilio, we must import it. We can import the Twilio module using the following command.
const twilio = require('twilio')
Step 7: Getting the auth token and id from our Twilio account.
We get the auth token and id when we have successfully linked our WhatsApp number. To find your own auth token and id, go to the one-way messaging section of WhatsApp on the Twilio website.
Step 8: Sending the WhatsApp message.
The below code is used to send WhatsApp messages from the Twilio Sandbox.
Step 9: Execution
Make sure you are in the same directory in which the file is created. Execute the above code using the following command.
Note: Here the file name provided is twilio.js.
Upon successful execution, we get a message in the console as shown in the below image.
The WhatsApp messages are received as shown in the below image.