Search code examples
twiliowhatsapptwilio-apitwilio-node

Why can't I programmatically send a templated WhatsApp message using Twilio?


My code:

const client = require('twilio')(accountSid, authToken);
const issueResolution = 'Hi Malcolm, were we able to solve the issue that you were facing?';

client.messages
      .create({
         from: senderNumber, 
         body: issueResolution,
         to: receiverNumber,
       })
      .then(message => {
        console.log(JSON.stringify(message , null, 2));
      });

The body of the message conforms to the "sample_issue_resolution" WhatsApp template shown in the Twilio web console (at https://console.twilio.com/us1/develop/sms/senders/whatsapp-templates).

I can successfully use the above code to send a message to a number which has opted in to my Twilio WhatsApp sandbox. If I try to send a message to another number which has not opted in to the sandbox, there's no error message, but the message is never received. I get the same results when I use one of my custom approved templates. What could be going wrong / how can I debug this?


Solution

  • I'd assume that this message is not matching any of your templates. There could be multiple reasons, such as a different whitespace character or a typo that differentiates both strings.

    The Message Log should tell you why a message couldn't be delivered.

    Update November 2023: The Content Template Builder is now live. With that you can refer to template IDs via the API call and fill in placeholders. This way, you don't need to ensure the strings match.

    // Download the helper library from https://www.twilio.com/docs/node/install
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    const accountSid = process.env.TWILIO_ACCOUNT_SID;
    const authToken = process.env.TWILIO_AUTH_TOKEN;
    const client = require('twilio')(accountSid, authToken);
    
    client.messages
          .create({
             contentSid: 'HXXXXXXXXX',
             from: 'MGXXXXXXXX',
             contentVariables: JSON.stringify({
               1: 'Name'
             }),
             to: 'whatsapp:+18551234567'
           })
          .then(message => console.log(message.sid));