Sending WhatsApp Notifications with Templates: Initiate Messages with Node.js

February 19, 2021
Written by
Reviewed by
Diane Phan
Twilion

whatsapp_notifications.png

To initiate a conversation with your user using WhatsApp, one of the following two conditions must apply:

WhatsApp message templates are message formats that have been pre-approved by WhatsApp. These pre-approved message formats can leave space for “dynamic content”, or customizations, that are relevant to your recipient, like specific appointment times, receipt totals, etc.

Once a user has opted in and agreed to receive communications from you via WhatsApp, you’re allowed to send them notifications using message templates whenever you want to. These message templates have strict requirements that disallow marketing, promotional, or subscription type content.

A message template with a clear purpose, however, can help you initiate two-way conversation with your user. Once your user has replied, a 24-hour window opens in which you’re allowed to send them free form messages and engage with them in real time.

Prerequisites

You’ll need to following tools or technologies to make the most of this tutorial:

  • A free Twilio account (if you sign up with this link, we’ll both get $10 in Twilio credit when you upgrade your account)
  • A WhatsApp account associated with your phone number

Connect to the Twilio Sandbox for WhatsApp

To create and submit a template of your own design, you’ll need to make a request to use WhatsApp in production with your Twilio phone number.

Luckily, the Twilio Sandbox for WhatsApp lets you test out Twilio’s WhatsApp API features using a shared, universal number without having to wait for your Twilio number to be approved by WhatsApp.

You can activate the WhatsApp sandbox by visiting the WhatsApp section of your Twilio Console. After checking the box to activate the sandbox, you’ll be asked to send a specific code message from your WhatsApp number to the provided universal WhatsApp number. After completing this connection, you’ll see this success screen:

WhatsApp Sandbox connection success screen

Design your Message Template

Before creating your notification message template, make sure it falls into one of the approved categories. It can take a couple of business days for WhatsApp to approve your template, so to save time, do your best to make sure it adheres to the guidelines before you submit it.

See tips on how to perfect your template.

The sandbox has three pre-approved message templates that you can reference. You can see them all if you click the Next: Send a One-Way Message button at the bottom of the success screen on the Twilio Console shown above.

This will take you to the templates section of the sandbox. Click on Appointment Reminders. Once you click on it, you’ll see a line that says:

Your appointment is coming up on {{1}} at {{2}}

This line is showing the message template for Appointment Reminders that’s been pre-approved for use in the sandbox.

Placeholders and dynamic content

The {{1}} and {{2}} seen in this template might look strange, but don’t worry, this syntax is how you denote placeholder values that allow you to customize any individual message sent with a given template. These placeholder values let you craft standardized message formats that can be approved by WhatsApp for general use, but also allow each individual message to be tailored to its recipient.

For the purposes of this tutorial, you’ll create some dummy data that can be used to customize this template when you send a message with it. A date will go in the place of {{1}}, and a time will go in the place of {{2}}.

For example, a message crafted with this template might read: “Your appointment is coming up on July 21 at 3PM”. In the next section you’ll write some code that demonstrates how you can make use of this same template to send an actual message.  

Submit the message template for approval

To submit a message template for approval, visit the WhatsApp message template section of the Twilio Console. Until your account has been approved for production WhatsApp use, you’ll be unable to submit a template.

Learn how to submit a template after account approval.

Send a Notification Using the Message Template

With your template ready, switch gears, and open your terminal or command prompt window.

Create a new directory called whatsapp-template and change into it:

mkdir whatsapp-template
cd whatsapp-template

Initiate a new Node.js app, install the  and create a file called index.js:

npm init -y
npm install twilio
touch index.js

Open your new index.js file in your favorite text editor. Copy and paste the following code into this file, taking care to replace the placeholder values for variables accountSID and authToken with your actual Account SID and Auth Token. These values can be found on the main dashboard of your Twilio Console:

const accountSid = 'YOUR_ACCOUNT_SID'; 
const authToken = 'YOUR_AUTH_TOKEN'; 
const client = require('twilio')(accountSid, authToken);

In a real production app, you would never store your credentials directly inside your application in this manner. Typically, you would use a .env file and load these credentials into your app using a package such as dotenv.

Below this code, copy and paste the following dummy appointment data:

const appointmentDetails = [
  {
    date: 'July 21',
    time: '2PM'
  },
  {
    date: 'Aug 21',
    time: '3PM'
  }
]

The appointmentDetails variable is holding an array with two objects, each with a date key and a time key.

As you loop over the array in the next step, the value for each date key will take the place of the {{1}} placeholder that WhatsApp understands to be dynamic content. Likewise, the value for each time key will fill in for the {{2}} placeholder.

Below this array, add the following code:

appointmentDetails.forEach(async appt => {
  message = await client.messages.create({ 
              body: `Your appointment is coming up on ${appt.date} at ${appt.time}`, 
              from: 'whatsapp:+14155238886',       
              to: 'whatsapp:+YOUR_WHATSAPP_NUMBER' 
            }); 
  console.log(message.sid)
});

This newly added code loops over the array of appointment details, and for each appointment, sends a message to your WhatsApp number using the pre-approved message template.

On line 3, you can see the templated message you derived in the previous section.

On line 5, highlighted, you’ll need to replace the placeholder with your personal WhatsApp number.

Save your file and head back to your terminal. Run the following command:

node index.js

This will run your code. In WhatsApp, you will receive two messages. One will say “Your appointment is coming up on July 21 at 2PM” and the other will say “Your appointment is coming up on Aug 21 at 3PM”.

In your terminal, you’ll see the SID of the two messages that were sent.

Next Steps

Test out your new JavaScript and WhatsApp skills by trying out another tutorial, like using location data in WhatsApp to find nearby healthy restaurants. Have fun, and let me know on Twitter what projects you’re building!

Ashley is a JavaScript Editor for the Twilio blog. To work with her and bring your technical stories to Twilio, find her at @ahl389 on Twitter. If you can’t find her there, she’s probably on a patio somewhere having a cup of coffee (or glass of wine, depending on the time).