sms bounty

JavaScript

/*
curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Messages.json' \
--data-urlencode 'To=+16518675309'  \
--data-urlencode 'From=+14158141829'  \
--data-urlencode 'Body=Hey Jenny! Good luck on the bar exam!'  \
-d 'MediaUrl=http://farm2.static.flickr.com/1075/1404618563_3ed9a44a3a.jpg' \
-u AC5ef872f6da5a21de157d80997a64bd33:[AuthToken]
*/

// Twilio module

var TwilioSMS = (function($) {

  var accountSid = 'AC84870a5c1d7c16dbbe14588684d47cef';
  var authToken = '67be49d179375d9881ea458f9a8b5da1';

  var testEndpoint = 'https://api.twilio.com/2010-04-01/Accounts/' + accountSid + '/SMS/Messages.json';
  var liveEndpoint = 'https://api.twilio.com/2010-04-01/Accounts/' + accountSid + '/Messages.json';

  var sendMessage = function(to, from, body, successCallback, failCallback) {
    var data = {
      To: to,
      From: from,
      Body: body
    };

    $.ajax({
      method: 'POST',
      url: testEndpoint,
      data: data,
      dataType: 'json',
      contentType: 'application/x-www-form-urlencoded', // !
      beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization",
          "Basic " + btoa(accountSid + ":" + authToken) // !
        );
      },
      success: function(data) {
        console.log("Got response: %o", data);

        if (typeof successCallback == 'function')
          successCallback(data);
      },
      error: function(jqXHR, textStatus, errorThrown) {
        console.log("Request failed: " + textStatus + ", " + errorThrown);

        if (typeof failCallback == 'function')
          failCallback(jqXHR, textStatus, errorThrown);
      }
    });
  }

  return {
    sendMessage: sendMessage
  };

})(jQuery);


// USAGE

TwilioSMS.sendMessage(
  '+12345678901',
  '+ 863 431 1930', // Twilio allowed test number
  'Hey Jenny! Good luck on the bar exam!',

  function ok() {
    console.log("Message sent!");
  },
  function fail() {
    console.log("Failed to send your message!");
  }
);