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?οnlοad=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;

转载于:https://www.cnblogs.com/williamzeng/p/4316210.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值