Android 如何在 Cordova/Phonegap 中使用 Google 登录 API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23930744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:38:10  来源:igfitidea点击:

How to use Google Login API with Cordova/Phonegap

androidcordovaoauthparse-platformgoogle-oauth

提问by Augustus Francis

I want to use "Login with Google" in my Phonegap App. I have read many articles but couldn't find out how it is done. Thanks in Advance. I tried using oAuth2 for "installed Applications" as per this URL. But then the app users have to manually copy code and paste in my app. I am using built.io Federated Login, if its relevant.

我想在我的 Phonegap 应用程序中使用“使用 Google 登录”。我已经阅读了很多文章,但无法找到它是如何完成的。提前致谢。我尝试按照此URL将 oAuth2 用于“已安装的应用程序” 。但随后应用程序用户必须手动复制代码并粘贴到我的应用程序中。如果相关,我正在使用 built.io Federated Login

回答by Nico Westerdale

Google has dropped support for the accepted answer above! After April 20th 2017 use of the In-App browser as described by @Deep Mehta will no longer be supported. If you use the accepted answer then it is going to start failing very soon.

谷歌已放弃对上述已接受答案的支持!2017 年 4 月 20 日之后,将不再支持使用 @Deep Mehta 所述的应用内浏览器。如果您使用接受的答案,那么它很快就会开始失败。

Here's Google's post about the change: https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html

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

Luckily there's a new plugin that wraps up all the funcitonality that you need to do this:

幸运的是,有一个新插件包含了您执行此操作所需的所有功能:

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

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

Here's an article on how to use it in Ionic 1 and 2 also: http://blog.ionic.io/google-oauth-changes

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

Again - DO NOT USE THE ACCEPTED ANSWER! It will fail after April 20 2017.

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

回答by Deep Mehta

add this code in one js file and include in your project. when you want to access google login api on button click call function callGoogle()rest will be done by this code. Dont forget to add your client id and Client_Secret keys. Its working fine for me. You need inappbrowser cordova plugin.

将此代码添加到一个 js 文件中并包含在您的项目中。当您想在按钮上访问谷歌登录 api 时,点击呼叫function callGoogle()休息将由此代码完成。不要忘记添加您的客户端 ID 和 Client_Secret 密钥。它对我来说工作正常。您需要 inappbrowsercordova 插件。

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

回答by ldeluca

I recommend this cordova plugin: https://www.npmjs.com/package/cordova-plugin-googleplusIt's pretty recent but I just added it to my app and it seems to do the trick!

我推荐这个cordova插件:https: //www.npmjs.com/package/cordova-plugin-googleplus它是最近的,但我刚刚将它添加到我的应用程序中,它似乎可以解决问题!

回答by Jason Washo

Another implementation that works well here: https://github.com/valenzia10/PhonegapGoogleLogin

另一个在这里运行良好的实现:https: //github.com/valenzia10/PhonegapGoogleLogin

回答by Alex

It's 2019: and Google+ API is shut down.

现在是 2019 年:Google+ API 已关闭。

Google has an article about how to authenticate using the firebase API: https://firebase.google.com/docs/auth/web/cordova

Google 有一篇关于如何使用 firebase API 进行身份验证的文章:https: //firebase.google.com/docs/auth/web/cordova