使用前準備:
1. Google Cloud Platform 帳號 (一般 google 即可申請)
2. 使用網域 (這邊以 haer0248.me 當作範例)
jQuery + PHP 基本認識 (?)
首先,前往 Google Cloud Platform 建立一個專案
連結: https://console.cloud.google.com/projectcreate
上方名稱可自訂,必須為 英文字母、數字、單引號、連字號、空格或驚嘆號。
點選建立按鈕後必須等待一段時間,完成後右上方鈴鐺會通知已完成建立,並前往建立的該專案。
於左側列表點選 API 和服務 => OAuth 同意畫面
User Type 選擇【外部】
其餘查看下方圖片填寫即可,網域請填入正確網域,否則後面的 OAuth 用戶端ID 會無法成功建立。
完成後點選左側列表 API 和服務 => 憑證 => 建立憑證 => OAuth 用戶端 ID
依照下方圖片填寫即可完成:

完成後,前往 API和服務 => 憑證 查看 OAuth 2.0 用戶端 ID 部分,複製【用戶端 ID】,會長得像 xxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com
以上為 Google Cloud Platform 部分,接下為網頁端。
在 <head> 中加入
<script async defer
src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};GoogleOAuthAPI()" onreadystatechange="if (this.readyState === 'complete') this.onload()"></script>
<script>
function GoogleOAuthAPI() {
gapi.load("client:auth2", {
callback: function() {
gapi.client.init({
clientId: "<這邊插入剛剛取得的用戶端 ID>",
scope: "https://www.googleapis.com/auth/userinfo.profile"
});
}
});
}
</script>
以下部分為使用按鈕呼叫 (jQuery 判斷後顯示的 JS)
*注意,此處透過 ajax Post 到指定的 PHP 頁面進行登入,回傳資料為 data. 開頭,若需要回傳資料請繼續查看下方。
*若需要下面三項以外的資料,必須申請通過才可以取得,其他公開的請前往: https://any-api.com/googleapis_com/oauth2/docs/userinfo/oauth2_userinfo_get
<button id="google_link_btn">使用 Google 帳號登入</button>
<script>
$("button[id=google_link_btn]").click(function (){
gapi.auth2.getAuthInstance().signIn().then(
function(success) {
var profile = success.getBasicProfile();
$.ajax({
type: "POST", url: "<請填入自己的登入 POST 頁面>", dataType: "json",
data: {
googlename: profile.getName(), // 取得 Google 帳號暱稱
googleid: profile.getId(), // 取得 Google OpenID
gmail: profile.getEmail() // 取得 Google 電子郵件
},
success: function(data) {
// 請自行填寫回傳成功後要執行什麼
},
error: function(jqXHR) {
alert("出現錯誤:" + jqXHR.status);
}
})
},
function(error) {
alert("Google API出現錯誤");
}
);
});
</script>
按鈕點選後帳號已選擇回傳資料頁面:
<?php
header('Content-Type: application/json; charset=UTF-8');
if ($_SERVER['REQUEST_METHOD'] == "POST"){
$googleid = $_POST['googleid']; // 取得 Google OpenID
$googlename = $_POST['googlename']; // 取得 Google 帳號暱稱
$gmail = $_POST['gmail']; // 取得 Google 電子郵件
/*
這邊可以填寫輸入資料庫及任何判斷或記錄於 SESSION 的部分,
輸出一定要有一個 msg,否則於前端很難除錯!
*/
$msg = '登入成功';
}else{
$msg = '傳輸方式錯誤';
}
echo json_encode(array("msg" => $msg)); // 這邊就會在前端回傳 data.msg
?>
若有任何錯誤及問題,歡迎於底下留言及討論!