Twilio is a communications platform that allows developers to programmatically make and receive phone calls, send and receive text messages, and perform other communication functions such as WhatsApp messaging using their web service APIs.

If you wish to send an SMS when a specific event in your mobile app occurs, you can write a KScript method to do this, that you can call from your mobile app or use as an action in an Automation.

Ingredients

This recipe assumes that you have KScripts enabled for your app and that you have a Twilio account.

Recipe

Expand "Backend" in the left hand menu, select "API" and then click the "KScript" button. Create a new method called something like _sms_ and include the following JavaScript function:

function sendSMS(from, to, body) {
    var client = K.http.createClient('https://api.twilio.com');
    var ACCOUNT_SID = 'YOUR_TWILIO_ACCOUNT_SID';
    var AUTH_TOKEN = 'YOUR_TWILIO_AUTH_TOKEN';

    var headers = {
        'Authorization' : 'Basic ' + base64_encode(ACCOUNT_SID + ":" + AUTH_TOKEN)
    };

    var data =  {
        "From" : from,
        "To" : to,
        "Body" : body
    };

    var result = client.post('/2010-04-01/Accounts/' + ACCOUNT_SID + '/Messages', data, headers);

    if (failed(result)) {
        K.log(result.error);
    }
    else if (result.isError()) {
        K.log(result.getBody());
    }

    return result;
}

You can then include your _sms_ helper method and call the sendSMS() function from any scripts that need to send a sms. To try it out, create another Kscript method called something like sendSMS, add input parameters(strings) for the to number and body and then paste in the following code:

include("_sms_");
var FROM_NUMBER = 'YOUR_TWILIO_NUMBER';

K.log(sendSMS(FROM_NUMBER, K.params.to, K.params.body));

You can now test your new method and use as an action in an Automation.

If your Twilio account is in trial mode, then you can only send messages to verified phone numbers such as the number you provided during the signup process. Also, the FROM_NUMBER must be a number or short code purchased via Twilio.

If you are using our Backend feature, you can also call this method from your mobile app or, if you wish to send a recurring SMS (for example a digest of recent activity), this can be scheduled to run once per hour or day.

Further reading

A full reference guide to the Twilio SMS API can be found on the Twilio website.