After some experimentation, I have developed an AngularJS service that can be utilized by the controller to send text messages triggered by specific events in the application. The core of this implementation is based on this solution, and here is how it operates:
To begin with, let's take a look at the service itself:
function BusinessService($http) {
this.twilioSMS = {
sendMessage: function(to, from, body) {
var accountSid = 'xxx';
var authToken = 'xxx';
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 data = {
To: to,
From: from,
Body: body
};
$http({
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);
}
})
}
}
}
Next, we need to configure it in the controller:
function ConsumerBusinessProfileCtrl($scope, BusinessService) {
$scope.sendMessage = function(to, from, body) {
return BusinessService.twilioSMS.sendMessage(to, from, body)
}
}
Lastly, we invoke it from the view:
<a ng-click="sendMessage('+12345678901', '+15005550006', 'Hey Jenny! Good luck on the bar exam!')">Send Message</a>
I have successfully tested the jsfiddle demo using my own credentials and phone numbers, and it functions perfectly. However, when implementing it, I encounter a 401 (UNAUTHORIZED)
error. I suspect that this issue may arise because $http
does not support beforeSend
or afterSend
. Can someone assist me in resolving this dilemma?