node.jstwiliowhatsapp

Unable to send whatsapp templated message using Twilio


I'm using Twillio to send whatsapp messages to my customers for updates regarding services they are using, but I'm unable to send the message at all. I'm using v5.0.1 of the twilio SDK for NodeJS

What I have

My template looks like this:

Body: Hi! Your {{2}} booking has been updated!

Sample content: BMW

Button: https://[website]/view-booking?bookingId={{1}}

Type: Visit website

Text: View booking

Sample content = -wn54Cw5WO-G3QFUKHP_6dT6PEfApuiloZNoMdTuMZs%3D

These are the two things I've tried:

exports.sendSMS = async (phoneNumber) => {
  const accountSid = "";
  const authToken = "";
  const client = new twilio(accountSid, authToken);

  return await client.messages
    .create({
      contentSid: "[sid]",
      contentVariables: JSON.stringify({
        1: "BMW",
        2: "-wn54Cw5WO-G3QFUKHP_6dT6PEfApuiloZNoMdTuMZs%3D",
      }),
      from: "whatsapp:+[number]",
      to: `whatsapp:+${formatUKPhoneNumber(phoneNumber)}`,
    })
    .then((message) => {
      console.log(message);
      return message.sid;
    })
    .catch((e) => {
      console.log(`error0: ${e}`);
    });
};

The error I get with this is error0: Error: A text message body or media urls must be specified.

exports.sendSMS = async (phoneNumber) => {
  const accountSid = "";
  const authToken = "";
  const client = new twilio(accountSid, authToken);

  return await client.messages
    .create({
      body: "Hi! Your BMW booking has been updated!",
      from: "whatsapp:+[number]",
      to: `whatsapp:+${formatUKPhoneNumber(phoneNumber)}`,
    })
    .then((message) => {
      console.log(message);
      return message.sid;
    })
    .catch((e) => {
      console.log(`error0: ${e}`);
    });
};

This one doesn't return an error, but the Twillio logs say that the message has failed (below)

Twillio logs


Solution

  • You are mixing two different approaches here.

    The first one you mentioned is using the Content Template Builder. In there, you can submit another template to Meta and from then on, reference the template by ID and provide the variables to plug in. It's important that you specify a messaging service in the from or messagingServiceSid properties. This is a requirement.

    client.messages
          .create({
             contentSid: 'HXXXXXXXXX',
             from: 'MGXXXXXXXX',
             contentVariables: JSON.stringify({
               1: 'Name'
             }),
             to: 'whatsapp:+18551234567'
           })
          .then(message => console.log(message.sid));
    

    The second one is using the quite strict WhatsApp templates - appearing white spaces or encodings can turn a valid usage of a template invalid. I'd recommend the first approach, but you need to make sure you have the proper content template created first.