首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Cordova/Phonegap中使用

如何在Cordova/Phonegap中使用
EN

Stack Overflow用户
提问于 2014-05-29 10:04:09
回答 5查看 48.1K关注 0票数 32

我想在我的Phonegap应用程序中使用“使用Google登录”。我读过很多文章,但都找不出是怎么写的。提前谢谢。我尝试使用oAuth2作为“已安装的应用程序”,就像这个URL一样。但是,应用程序用户必须手动复制代码并粘贴到我的应用程序中。我使用的是built.io 联邦登录,如果相关的话。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2017-03-15 16:03:26

谷歌已经放弃了对上面接受的答案的支持!2017年4月20日之后,将不再支持@Deep所描述的应用程序内浏览器的使用。如果你使用公认的答案,那么它很快就会失败。

以下是谷歌关于这一变化的帖子:https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html

幸运的是,有一个新插件封装了您需要这样做的所有功能:

https://github.com/EddyVerbruggen/cordova-plugin-googleplus与NPM https://www.npmjs.com/package/cordova-plugin-googleplus

这里有一篇关于如何在Ionic 1和2中使用它的文章--也是:http://blog.ionic.io/google-oauth-changes

再说一遍-不要使用接受的答案!它将在2017年4月20日之后失败。

票数 43
EN

Stack Overflow用户

发布于 2014-05-29 10:37:57

将此代码添加到一个js文件中并包括在您的项目中。当您想要访问google时,单击“调用function callGoogle() rest”将由此代码完成。不要忘记添加您的客户端id和Client_Secret密钥。对我来说很好。你需要inappbrowser cordova插件。

代码语言:javascript
复制
var googleapi = {
    authorize: function(options) {
        var deferred = $.Deferred();
         //Build the OAuth consent page URL
        var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
            client_id: options.client_id,
            redirect_uri: options.redirect_uri,
            response_type: 'code',
            scope: options.scope
        });

        //Open the OAuth consent page in the InAppBrowser
        var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no');

        //The recommendation is to use the redirect_uri "urn:ietf:wg:oauth:2.0:oob"
        //which sets the authorization code in the browser's title. However, we can't
        //access the title of the InAppBrowser.
        //
        //Instead, we pass a bogus redirect_uri of "http://localhost", which means the
        //authorization code will get set in the url. We can access the url in the
        //loadstart and loadstop events. So if we bind the loadstart event, we can
        //find the authorization code and close the InAppBrowser after the user
        //has granted us access to their data.
        $(authWindow).on('loadstart', function(e) {
            var url = e.originalEvent.url;
            var code = /\?code=(.+)$/.exec(url);
            var error = /\?error=(.+)$/.exec(url);

            if (code || error) {
                //Always close the browser when match is found
                authWindow.close();
            }

            if (code) {
                //Exchange the authorization code for an access token
                $.post('https://accounts.google.com/o/oauth2/token', {
                    code: code[1],
                    client_id: options.client_id,
                    client_secret: options.client_secret,
                    redirect_uri: options.redirect_uri,
                    grant_type: 'authorization_code'
                }).done(function(data) {
                    deferred.resolve(data);

                    $("#loginStatus").html('Name: ' + data.given_name);
                }).fail(function(response) {
                    deferred.reject(response.responseJSON);
                });
            } else if (error) {
                //The user denied access to the app
                deferred.reject({
                    error: error[1]
                });
            }
        });

        return deferred.promise();
    }
};
var accessToken;
var UserData = null;

function callGoogle() {

    //  alert('starting');
    googleapi.authorize({
        client_id: 'client_id',
        client_secret: 'Client_Secret',
        redirect_uri: 'http://localhost',
        scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
    }).done(function(data) {
        accessToken = data.access_token;
        // alert(accessToken);
        // $loginStatus.html('Access Token: ' + data.access_token);
        console.log(data.access_token);
        console.log(JSON.stringify(data));
        getDataProfile();

    });

}

// This function gets data of user.
function getDataProfile() {
    var term = null;
    //  alert("getting user data="+accessToken);
    $.ajax({
        url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
        type: 'GET',
        data: term,
        dataType: 'json',
        error: function(jqXHR, text_status, strError) {},
        success: function(data) {
            var item;

            console.log(JSON.stringify(data));
            // Save the userprofile data in your localStorage.
            localStorage.gmailLogin = "true";
            localStorage.gmailID = data.id;
            localStorage.gmailEmail = data.email;
            localStorage.gmailFirstName = data.given_name;
            localStorage.gmailLastName = data.family_name;
            localStorage.gmailProfilePicture = data.picture;
            localStorage.gmailGender = data.gender;
        }
    });
    disconnectUser();
}

function disconnectUser() {
    var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' + accessToken;

    // Perform an asynchronous GET request.
    $.ajax({
        type: 'GET',
        url: revokeUrl,
        async: false,
        contentType: "application/json",
        dataType: 'jsonp',
        success: function(nullResponse) {
            // Do something now that user is disconnected
            // The response is always undefined.
            accessToken = null;
            console.log(JSON.stringify(nullResponse));
            console.log("-----signed out..!!----" + accessToken);
        },
        error: function(e) {
            // Handle the error
            // console.log(e);
            // You could point users to manually disconnect if unsuccessful
            // https://plus.google.com/apps
        }
    });
}
票数 31
EN

Stack Overflow用户

发布于 2016-12-29 04:24:17

我推荐这个cordova插件:https://www.npmjs.com/package/cordova-plugin-googleplus,它是最近才出现的,但我只是把它添加到我的应用程序中,它看起来很管用!

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23930744

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档