AngularJS服务发送Twilio短信

时间:2016-06-04 14:56:15

标签: javascript angularjs

我一直在尝试创建可以从控制器调用的AngularJS服务,并根据应用程序中的特定事件发送短信。实施基于this,其工作原理如下:

首先,我们有服务:

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);
        }
      })

    }

  }

}

然后在控制器中进行设置:

function ConsumerBusinessProfileCtrl($scope, BusinessService) {

  $scope.sendMessage = function(to, from, body) {
    return BusinessService.twilioSMS.sendMessage(to, from, body)
  }

}

然后从视图中调用它:

<a ng-click="sendMessage('+12345678901', '+15005550006', 'Hey Jenny! Good luck on the bar exam!')">Send Message</a>

我已经使用我的accountSid,authToken和电话号码测试了jsfiddle example,它运行正常。但我的实现失败,出现401 (UNAUTHORIZED)错误。我的一部分认为这是因为$http不支持beforeSendafterSend。但我不确定?这里有人可以指导我朝正确的方向发展吗?

1 个答案:

答案 0 :(得分:1)

将$ http更改为以下内容以修复问题:

 $http({
  method: 'POST',
  url: testEndpoint,
  data: data,
  transformRequest: function(obj) {
    var str = [];
    for (var p in obj)
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    return str.join("&");
  },
  headers: {
    'Authorization': 'Basic ' + btoa(accountSid + ':' + authToken),
    'Content-Type': 'application/x-www-form-urlencoded'
  },
}).success(function(response) {
  console.log(response);
}).error(function(error) {
  console.log(error);
});
}