ecshop使用Google API及OAuth2.0登录授权(PHP)

一、申请clientID

https://console.developers.google.com/project

二、开启Google+ API权限

https://console.developers.google.com/project/gentle-charmer-848/apiui/api

三、添加同意画面

四、建立新的用户端ID(一个域名对应一个ID)

五、显示页面js登录按钮

案例地址:https://developers.google.com/+/web/signin/

参考代码:
                <button id="customBtn" class="customGPlusSignIn"><b><img src="images/btn_red_32.png" width="32" height="32"/></b>Log in with Google</button>
                <script type="text/javascript">
                function render() {
                    gapi.signin.render(‘customBtn‘, {
                      ‘callback‘: ‘signinCallback‘,
                      ‘approvalprompt‘:‘force‘,
                      ‘clientid‘: ‘779557060237-b9fqq4gnr5qchdij2j8h5h13ujla52fj.apps.googleusercontent.com‘,
                      ‘cookiepolicy‘: ‘http://www.5dlj.com‘,
                      ‘requestvisibleactions‘: ‘http://schemas.google.com/AddActivity‘,
                      ‘scope‘: ‘https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email‘
                });}
                function signinCallback(authResult) {
                  if (authResult[‘access_token‘]) {
                        gapi.client.load("oauth2","v2",function(){
                            var request=gapi.client.oauth2.userinfo.get();
                            request.execute(function(obj){
                                if(obj["email"] == ""){
                                    alert(‘Email is empty!‘);
                                }
                            });
                        });
                    window.location.href="google_login.php?access_token="+authResult[‘access_token‘];
                  } else if (authResult[‘error‘]) {
                    authResult[‘error‘];
                  }
                }
                !function() {
                    var po = document.createElement(‘script‘);
                    po.type = ‘text/javascript‘; po.async = true;
                    po.src = ‘https://apis.google.com/js/client:plusone.js?onload=render‘;
                    var s = document.getElementsByTagName(‘script‘)[0];
                    s.parentNode.insertBefore(po, s);
                }();
                </script>

六、google_login.php返回结果处理

<?php
define(‘IN_ECS‘, true);
require(dirname(__FILE__) . ‘/includes/init.php‘);

if(isset($_REQUEST[‘access_token‘])) {
    $access_token = $_REQUEST[‘access_token‘];
    $url = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=".$access_token;

$user_gg = json_decode(file_get_contents($url),true);
    $gg_email = compile_str($user_gg[‘email‘]);
    $gg_id    = $user_gg[‘id‘];
    $gg_name  = compile_str($user_gg[‘name‘]);
    $picture  = $user_gg[‘picture‘] == ‘https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg‘ ? ‘‘ : compile_str($user_gg[‘picture‘]); //头像
    $gender   = 0;
    if($user_gg[‘gender‘] == ‘male‘)//性别
    {
        $gender = 1;
    }
    elseif($user_gg[‘gender‘] == ‘female‘)
    {
        $gender = 2;
    }

$locale   = compile_str($user_gg[‘locale‘]); //国家
    $verified_email  = $user_gg[‘verified_email‘]; //邮箱是否验证
    if(empty($gg_email))
    {
        show_message("Your Google email is empty!", ‘‘, ‘user.php‘, ‘warning‘);
    }
    
    $sql = "select * from ".$GLOBALS[‘ecs‘]->table("users")." where email=‘".$gg_email.
    "‘ or user_name=‘".$gg_email."‘ order by user_id desc limit 1";
    $user_info = $GLOBALS[‘db‘]->getRow($sql);
    $record = array();
    if(!empty($user_info)) //gg邮箱已注册或者登陆过
    {
        $user_name = $user_info[‘user_name‘];
        $user->set_session($user_name);
        $user->set_cookie($user_name, null);
        update_user_info();
        recalculate_price();
        
        if(empty($user_info[‘gg_id‘]) || empty($user_info[‘nick_name‘]) || empty($user_info[‘user_image‘]) || empty($user_info[‘sex‘]))
        {
            $record[‘is_validated‘] = 1;
            empty($user_info[‘gg_id‘]) ? $record[‘gg_id‘] = $gg_id : ‘‘;
            empty($user_info[‘gg_name‘]) ? $record[‘gg_name‘] = $gg_name : ‘‘;
            empty($user_info[‘nick_name‘]) ? $record[‘nick_name‘] = $gg_name : ‘‘;
            empty($user_info[‘user_image‘]) ? $record[‘user_image‘] = get_picture($picture) : ‘‘;
            empty($user_info[‘sex‘]) ? $record[‘sex‘] = $gender : ‘‘;
            $db->autoExecute($ecs->table(‘users‘), $record, ‘UPDATE‘, "user_id = ‘$user_info[user_id]‘");
        }
    }
    else //GG邮箱未注册或者未登陆过,自动注册
    {
        $password = generate_word();
        include_once(ROOT_PATH."includes/lib_passport.php");
        include_once(ROOT_PATH.‘includes/lib_transaction.php‘);
        $other = array();
        if(register($gg_email, $password, $gg_email,$other))
        {
            $record[‘gg_id‘]      = $gg_id;
            $record[‘gg_name‘]    = $gg_name;
            $record[‘nick_name‘]  = $gg_name;
            $record[‘user_image‘] = get_picture($picture);
            $record[‘sex‘]        = $gender;
            $record[‘reg_type‘]   = 3;
            $record[‘is_validated‘]= 1;
            $db->autoExecute($ecs->table(‘users‘), $record, ‘UPDATE‘, "user_id = ‘$_SESSION[user_id]‘");
            /* 发送注册成功邮件*/
            $tpl = get_mail_template(‘pp_login‘);
            $expired_date =local_date("Y-m-d", gmtime()+864000);
            $smarty->assign(‘expired_date‘, $expired_date);
            $smarty->assign(‘password‘, $password);
            $smarty->assign(‘username‘, $gg_email);
            $content = $GLOBALS[‘smarty‘]->fetch(‘str:‘ . $tpl[‘template_content‘]);
            send_mail($gg_email, $gg_email,$tpl[‘template_subject‘],$content,$tpl[‘is_html‘]);
            log_account_change($_SESSION[‘user_id‘], 0, 0, 0, 50, ‘Get 50 M points from Google register.‘, ACT_OTHER);
        }
        else
        {
            show_message("Your Google email register error!", ‘‘, ‘user.php‘, ‘warning‘);
        }
    }
    $_SESSION[‘back_act‘] = $_SESSION[‘back_act‘] ? $_SESSION[‘back_act‘] : "./index.html";
    ecs_header("Location:".$_SESSION[‘back_act‘]."\n");
}
else
{
    die(‘Illegal Access!‘);
}
//获取远程头像图片
function get_picture($picture){
    if($picture)
    {
        $data = file_get_contents($picture); // 读文件内容
        $filename =  DATA_DIR . ‘/u_image/‘.local_date(‘ymdHis‘,gmtime()).‘_‘.rand(10,99).substr($picture,-4,4); //得到时间戳
        $fp = @fopen(ROOT_PATH . $filename,"w"); //以写方式打开文件
        @fwrite($fp,$data);
        fclose($fp);
    }
    else
    {
        $filename = ‘‘;    
    }
    return $filename;
}
?>
七、添加新字段的sql语句

ALTER TABLE `ecs_users` ADD `gg_name` varchar(60) NOT NULL;
ALTER TABLE `ecs_users` ADD `gg_id` varchar(60) NOT NULL;
ALTER TABLE `ecs_users` ADD `nick_name` varchar(60) NOT NULL;
ALTER TABLE `ecs_users` ADD `user_image` varchar(60) NOT NULL;

时间: 2024-08-09 23:12:54

ecshop使用Google API及OAuth2.0登录授权(PHP)的相关文章

google API 使用Client Login 登录授权

今天要使用google api来获取google analytics 的数据,所以必须要用到google 的登录授权. Google的服务认证体系包含了多种认证授权的方式,如AuthSub授权认证服务.OAUTH授权认证服务与ClientLogin授权认证服务等.具体大家可以参考 : http://blog.csdn.net/hereweare2009/article/details/4002537 http://blog.zhourunsheng.com/2011/07/%E8%84%9A%E

***微信公众平台开发: 获取用户基本信息+OAuth2.0网页授权

本文介绍如何获得微信公众平台关注用户的基本信息,包括昵称.头像.性别.国家.省份.城市.语言.本文的方法将囊括订阅号和服务号以及自定义菜单各种场景,无论是否有高级接口权限,都有办法来获得用户基本信息,而无需模拟登录. 在本文中,特别要注意的是有两个不同的Access Token,他们产生的方式不一样,一种是使用AppID和AppSecret获取的access_token,一种是OAuth2.0授权中产生的access_token,方倍工作室分别称为全局Access Token和授权Access

Force.com微信开发系列(七)OAuth2.0网页授权

OAuth是一个开放协议,允许用户让第三方应用以安全且标准的方式获取该用户在某一网站上存储的私密资源(如用户个人信息.照片.视频.联系人列表),而无须将用户名和密码提供给第三方应用.本文将详细介绍OAuth协议以及在微信里的具体实现. OAuth2.0协议介绍 OAuth2.0是OAuth协议的下一版本,但不向后兼容OAuth 1.0. OAuth 2.0关注客户端开发者的简易性,同时为Web应用,桌面应用和手机,和起居室设备提供专门的认证流程. OAuth2.0允许用户提供一个令牌,而不是用户

使用Owin中间件搭建OAuth2.0认证授权服务器

前言 这里主要总结下本人最近半个月关于搭建OAuth2.0服务器工作的经验.至于为何需要OAuth2.0.为何是Owin.什么是Owin等问题,不再赘述.我假定读者是使用Asp.Net,并需要搭建OAuth2.0服务器,对于涉及的Asp.Net Identity(Claims Based Authentication).Owin.OAuth2.0等知识点已有基本了解.若不了解,请先参考以下文章: MVC5 - ASP.NET Identity登录原理 - Claims-based认证和OWIN

微信公众平台oauth2.0网页授权

本篇文章你将学到:在自己做的微信网站里,利用oauth2.0网页授权接口获取用户的信息(openid,姓名,性别,地区,头像等).如大转盘等游戏记录哪个微信用户获得什么奖品.H5等小游戏需要把分数与对应用户捆绑在一起等网页应用. 微信公众平台oauth2.0网页授权能干什么 它是在自己做的网站中不用用户登录来获取微信用户相关信息的,进而实现相关业务. 说明与注意 1.网页授权分为两种, 一种为只获取openid  (基本授权 snsapi_base) 一种为获取用户全部信息 (高级授权 snsa

微信公众平台开发(71)OAuth2.0网页授权

微信公众平台开发 OAuth2.0网页授权认证 网页授权获取用户基本信息 作者:方倍工作室 微信公众平台最近新推出微信认证,认证后可以获得高级接口权限,其中一个是OAuth2.0网页授权,很多朋友在使用这个的时候失败了或者无法理解其内容,希望我出个教程详细讲解一下,于是便有了这篇文章. 一.什么是OAuth2.0 官方网站:http://oauth.net/   http://oauth.net/2/ 权威定义:OAuth is An open protocol to allow secure

微信OAuth2.0网页授权接口

微信OAuth2.0网页授权接口 微信OAuth2.0网页授权接口的thinkphp实现版本号.主要实现了oauth网页受权,以及部分其它接口. 用法 为什么用OAuth2.0受权? 通过OAuth2.0受权的网页将会获取到打开者的微信信息.甚至包含微信昵称.头像等实用的数据,开发人员们能够凭此设计出很多其它更丰富的页面应用,比方近期一直非常火爆的红包类活动.除此之外还有个额外的优点,就是能够控制页面在非微信浏览器中无法打开,能够降低代码被人窥窃的风险. 那么红包类活动是怎样使用OAuth2.0

(转)微信公众平台开发 OAuth2.0网页授权

微信公众平台开发 OAuth2.0网页授权认证 网页授权获取用户基本信息 作者:方倍工作室 微信公众平台最近新推出微信认证,认证后可以获得高级接口权限,其中一个是OAuth2.0网页授权,很多朋友在使用这个的时候失败了或者无法理解其内容,希望我出个教程详细讲解一下,于是便有了这篇文章. 一.什么是OAuth2.0 官方网站:http://oauth.net/   http://oauth.net/2/ 权威定义:OAuth is An open protocol to allow secure

Spring Cloud云架构 - SSO单点登录之OAuth2.0登录认证(1)

今天我们对OAuth2.0的整合方式做一下笔记,首先我从网上找了一些关于OAuth2.0的一些基础知识点,帮助大家回顾一下知识点: 一.oauth中的角色 client:调用资源服务器API的应用 Oauth 2.0 Provider:包括Authorization Server和Resource Server (1)Authorization Server:认证服务器,进行认证和授权 (2)Resource Server:资源服务器,保护受保护的资源user:资源的拥有者 二.下面详细介绍一下