我使用以下控制器从Google帐户导入联系人。我在gmail登录后获得了授权码。但是无法通过将授权代码发布到网址“https://accounts.google.com/o/oauth2/token”来获取访问权限。我没有得到任何回应。
angular.module('app',['ngRoute','angular-google-gapi'])
.config(['$routeProvider',function($routeProvider){
$routeProvider
.when('/log-in', {
template: '<button ng-click="logInCtrl.onLogInButtonClick()">Log In</button>',
controller: 'LogInController',
controllerAs: 'logInCtrl'
}).otherwise({
redirectTo:'/log-in'
});
}])
.controller('LogInController',function($scope,$http,GAuth,GApi){
var self = this;
var client_id = clientid;
var client_secret =clientsecretkey;
var redirect_uri ='http://localhost/myapp/oauth2callback';
var grant_type='authorization_code';
var apiKey= myapikey;
var scopes = 'https://www.googleapis.com/auth/userinfo.email https://www.google.com/m8/feeds/contacts/default/full';//to be able to reference to it in a callback, you could use $scope instead
$scope.email = '';
gapi.load('auth2', function() {//load in the auth2 api's, without it gapi.auth2 will be undefined
gapi.auth2.init(
{
client_id: clientid
}
);
var GoogleAuth = gapi.auth2.getAuthInstance();//get's a GoogleAuth instance with your client-id, needs to be called after gapi.auth2.init
self.onLogInButtonClick=function(){//add a function to the controller so ng-click can bind to it
GAuth.login().then(function(user){
$scope.email = user.email;
},function(response){
console.log(error);});
GoogleAuth.grantOfflineAccess({'redirect_uri': 'postmessage'}).then($scope.signInCallback);
};
});
$scope.signInCallback = function(result){
var code = result['code'];
var data = {
code : result['code'],
client_id: clientid,
client_secret:clientsecret,
redirect_uri:'http://localhost/myapp/oauth2callback',
grant_type:'authorization_code'
};
$http.post('https://accounts.google.com/o/oauth2/token',data,{headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}}).then(
function(response){
// success callback
console.log(response);
},
function(response){
// failure call back
console.log(1);
}
);
}
}).run(['GAuth', 'GApi', 'GData', '$rootScope','$http',function(GAuth, GApi, GData, $rootScope,$http) {
// Sends this header with any AJAX request
$http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
// Send this header only in post requests. Specifies you are sending a JSON object
$http.defaults.headers.post['dataType'] = 'json'
$rootScope.gdata = GData;
var CLIENT = clientid;
var BASE = 'https://myGoogleAppEngine.appspot.com/_ah/api';
GApi.load('http://localhost','v1',BASE);
// GApi.load('calendar','v3'); // for google api (https://developers.google.com/apis-explorer/)
GApi.load('contacts', 'v3');
GApi.load('plus','v1',BASE);
GAuth.setClient(CLIENT);
GAuth.setScope("https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.login");
}]);