热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在Cordova/Phonegap中使用GoogleLoginAPI-HowtouseGoogleLoginAPIwithCordova/Phonegap

IwanttouseLoginwithGoogleinmyPhonegapApp.Ihavereadmanyarticlesbutcouldntfindou

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应用程序中使用“Login with Google”。我读了很多文章但却无法知道它是如何完成的。提前致谢。我尝试按照此URL使用oAuth2作为“已安装的应用程序”。但随后应用用户必须手动并粘贴到我的应用中。我正在使用built.io联合登录,如果它相关。

4 个解决方案

#1


32  

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按钮点击通话功能调用谷歌()休息将由此代码完成。别忘了添加您的客户端ID和Client_Secret密钥。它对我来说很好。你需要inappbrowser cordova插件。

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

#2


20  

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

以下是Google关于此更改的帖子: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-googleplus and 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和I中使用它的文章:http://blog.ionic.io/google-oauth-changes

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

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

#3


3  

I recommend this cordova plugin: https://www.npmjs.com/package/cordova-plugin-googleplus It'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这是最近的,但我刚刚将它添加到我的应用程序,它似乎做了伎俩!

#4


0  

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

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


推荐阅读
  • 在Kubernetes上部署JupyterHub的步骤和实验依赖
    本文介绍了在Kubernetes上部署JupyterHub的步骤和实验所需的依赖,包括安装Docker和K8s,使用kubeadm进行安装,以及更新下载的镜像等。 ... [详细]
  • 在Docker中,将主机目录挂载到容器中作为volume使用时,常常会遇到文件权限问题。这是因为容器内外的UID不同所导致的。本文介绍了解决这个问题的方法,包括使用gosu和suexec工具以及在Dockerfile中配置volume的权限。通过这些方法,可以避免在使用Docker时出现无写权限的情况。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • Python实现变声器功能(萝莉音御姐音)的方法及步骤
    本文介绍了使用Python实现变声器功能(萝莉音御姐音)的方法及步骤。首先登录百度AL开发平台,选择语音合成,创建应用并填写应用信息,获取Appid、API Key和Secret Key。然后安装pythonsdk,可以通过pip install baidu-aip或python setup.py install进行安装。最后,书写代码实现变声器功能,使用AipSpeech库进行语音合成,可以设置音量等参数。 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 拥抱Android Design Support Library新变化(导航视图、悬浮ActionBar)
    转载请注明明桑AndroidAndroid5.0Loollipop作为Android最重要的版本之一,为我们带来了全新的界面风格和设计语言。看起来很受欢迎࿰ ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • Go GUIlxn/walk 学习3.菜单栏和工具栏的具体实现
    本文介绍了使用Go语言的GUI库lxn/walk实现菜单栏和工具栏的具体方法,包括消息窗口的产生、文件放置动作响应和提示框的应用。部分代码来自上一篇博客和lxn/walk官方示例。文章提供了学习GUI开发的实际案例和代码示例。 ... [详细]
author-avatar
Naive
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有