ecshop使用Google API及OAuth2.0登入授權(PHP)

來源:互聯網
上載者:User

標籤:

一、申請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;

ecshop使用Google API及OAuth2.0登入授權(PHP)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.