1. https://console.developers.google.com
创建一个project ;
需要的三个参数:
clientId,clientSecret,REDIRECT URIS;

在 APIs&auth --> Credentials---->右侧中的 oAuth 点击Create new Client ID 出现下面的图片:


2.添加插件
cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser.git
3.app.js

var requestToken = "";
var accessToken = "";
var clientId = "你的clientID";
var clientSecret = "你的 clientSecret";
 
var exampleApp = angular.module('example', ['ionic'])
    .config(function($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('login', {
                url: '/login',
                templateUrl: 'templates/login.html',
                controller: 'LoginController'
            })
            .state('secure', {
                url: '/secure',
                templateUrl: 'templates/secure.html',
                controller: 'SecureController'
            });
        $urlRouterProvider.otherwise('/login');
    });
 
 
exampleApp.controller('LoginController', function($scope, $http, $location) {
 
    $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
 
    $scope.login = function() {
        var ref = window.open('https://accounts.google.com/o/oauth2/auth?client_id=' + clientId + '&redirect_uri=http://debicoffe.com/oauth2callback&scope=https://www.googleapis.com/auth/urlshortener&approval_prompt=force&response_type=code&access_type=offline', '_blank', 'location=no');
        ref.addEventListener('loadstart', function(event) { 
            if((event.url).startsWith("http://debicoffe.com/oauth2callback")) {
                requestToken = (event.url).split("code=")[1];
                $http({method: "post", url: "https://accounts.google.com/o/oauth2/token", data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=http://debicoffe.com/oauth2callback" + "&grant_type=authorization_code" + "&code=" + requestToken })
                    .success(function(data) {
                      console.log(data.token_type);
                      console.log(data.expires_in);
                      console.log(data.refresh_token);
                        accessToken = data.access_token;
                        $location.path("/secure");
                    })
                    .error(function(data, status) {
                        alert("ERROR: " + data);
                    });
                ref.close();
            }
        });
    }
 
    if (typeof String.prototype.startsWith != 'function') {
        String.prototype.startsWith = function (str){
            return this.indexOf(str) == 0;
        };
    }
    
});
 
exampleApp.controller('SecureController', function($scope, $http) {
 
    $scope.accessToken = accessToken;
    
});

 

改成你的回调地址;

posted on 2014-11-11 15:30  ทดสอบ  阅读(816)  评论(0)    收藏  举报