How to Send a WhatsApp Message Using Twilio’s Messaging API

Dalvares
2 min readNov 13, 2023

--

In this tutorial, we’ll explore how to send WhatsApp messages programmatically using Twilio’s Messaging API. Whether you’re building a chatbot, sending notifications, or creating a two-way communication system, integrating WhatsApp messaging can enhance your application’s communication capabilities. Let’s get started!

Prerequisites

To follow along, you’ll need:

  • A Twilio account (Sign up for free)
  • A Twilio phone number with WhatsApp enabled
  • Credentials (Account SID and Auth Token) from your Twilio Console
  • Your environment set up for development (Node.js will be used here)

Step 1: Setting Up Your Twilio Account for WhatsApp

First, you’ll want to set up a Twilio number to use with the WhatsApp sandbox:

  1. Go to the Twilio Console.
  2. Navigate to Programmable Messaging, then click on “Try it Out” > “Try WhatsApp”.
  3. Follow the instructions to activate the sandbox for WhatsApp by sending the given code to the sandbox number from your WhatsApp account.
npm install twilio

Step 3: Sending a WhatsApp Message

Now that you have your Twilio environment set up and the Node.js library installed, you can write the code to send a WhatsApp message. Create a new file send-whatsapp-message.js and add the following content:

// send-whatsapp-message.js
const twilio = require('twilio');

const accountSid = 'your_account_sid'; // Replace with your Twilio account SID
const authToken = 'your_auth_token'; // Replace with your Twilio Auth Token
const client = new twilio(accountSid, authToken);

client.messages.create({
to: 'whatsapp:+1234567890', // Replace with recipient's number including the international prefix
from: 'whatsapp:+14155238886', // Replace with your Twilio number
body: 'Hello, this is a message sent from Twilio WhatsApp API!'
})
.then(message => console.log(`Message sent! Message SID: ${message.sid}`))
.catch(error => console.error(error));

Make sure you use your Twilio credentials and replace the to and from numbers with your own details.

Step 4: Run Your Code

Run your Node.js application with the following command, and if everything is set up correctly, your WhatsApp message will be sent!

node send-whatsapp-message.js

Conclusion

Congratulations! You’ve now sent a WhatsApp message using Twilio’s Messaging API. From here, you can integrate this functionality into your applications, use media messages, handle incoming messages, or even link a chatbot. Twilio offers extensive documentation and SDKs in different languages to help you expand this service according to your needs.

Remember to always abide by WhatsApp’s policies and best practices when sending messages to ensure your Twilio account remains in good standing.

Happy coding!

--

--