Passing dynamic content into the body of batch notifications using Twillio's Notify API

Viewed 252

I'm utilizing Twillio's Notify API to send batch notifications to users. That part is pretty simple in Node.js:

async function sendPaymentScheduledMessage(numbers) {
    const bindings = numbers.map(number => {
      return JSON.stringify({ binding_type: 'sms', address: number });
    });

    return await service.notifications.create({
      body: `The payment of your balance is scheduled for this Friday.`,
      toBinding: bindings,
    });
  }

Now, I would like to pass user-specific content (first name, amount, account number etc.) into those messages. The API docs mention the possibility of passing a data object, but are unclear (in my opinion) on how to make that happen exactly. I imagine it would be something similar to the extent of:

async function sendPaymentScheduledMessage(users) {
    const bindings = users.map(user => {
      return JSON.stringify({ binding_type: 'sms',
                              address: user.number, 
                              data: { 'name': user.name 
                                      'amount': user.amount
                                    }
                            });
      });

    return await service.notifications.create({
      body: `Dear *name*, payment of *amount* is scheduled for this Friday.`,
      toBinding: bindings,
    });
  }

But so far I haven't been able to figure out the correct structure. If anyone has made this happen, I'd be grateful to know.

1 Answers

The ToBinding attributes only contain binding_type and address.

data is reserved for custom key-value pairs of the notification's payload. This works for FCM, GCM and APNS but not for SMS.

If you want to customise the body text just use regular JavaScript string interpolation, e.g.:

return await service.notifications.create({
  body: `Dear ${name}, payment of ${amount} is scheduled for this Friday.`,
  toBinding: bindings,
});

If you need to customise this for each user then you need to call service.notifications.create multiple times.

Related