Search code examples
javascriptnode.jstwiliotwilio-apizapier

Zapier to Twilio to generate Dynamic SMS body


I would like to use Zapier to send an SMS via Twilio with a dynamic body containing different affiliate referral link to an app every time I get a new subscriber to my mailchimp mailing list.

I have two separate bits of code that do what I am looking for but, due to the limitations of installing modules within the code automation in Zapier and my lack of experience in programming i dont know how to bring the two together in a Zapier code Zap.

This is the code I can use to send an SMS with Twilio and works fine independently:

const accountSid = '<twilioAcctSid>';
const authToken = '<twilioAuthToken>';
const client = require('twilio')(accountSid, authToken);

client.messages
  .create({from: '<twilPhoneNo>', body: '<affiliateRefLink>', to: '<subscriberPhoneNo>' })
  .then(message => console.log(message.sid))
  .done();

This is the code I have used elsewhere to randomly select one of my affiliate links and I would like include a random link in the body of the SMS to the new subscriber.

const refCodes = ['link1',
                'link2',
                'link3'];

function getCode()
{
    let randomNum = Math.floor((Math.random() * refCodes.length));
    let baseSite = "#url_";
    let newLink = baseSite + refCodes[randomNum];
    document.getElementById('#url').href = newLink;
    document.getElementById('#url').innerHTML = newLink;

}

Any help would be sincerely appreciated!

Toes.


Solution

  • Thanks @philnash for your support, I was able to solve this with the code below!

      exports.handler = function(context, event, callback) {
      const appCodes = ['code1', 'code2', 'code3', 'code4']
      var smsBody = refCode ();
      var subNum = event.primaryPhone || 'There is no subscriber number'; // primaryPhone sent via HTTP post to twilio function
    
    function refCode () {
        return appCodes[Math.floor((Math.random() * appCodes.length))];
    };
    
      context.getTwilioClient().messages.create({
        to: `${subNum}`, // parameters & values recieved from HTTP POST are available within the twilio functions "event" context
        from: '+1444555666',
        body: `Get the App: ${smsBody}`
      }).then(msg => {
        callback(null, msg.sid);
      }).catch(err => callback(err));
    }