標籤:
一、申請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)