Google OAuth Api 簡單教學 – 飯糰 Blog
Google OAuth Api 簡單教學

使用前準備:
1. Google Cloud Platform 帳號 (一般 google 即可申請)
2. 使用網域 (這邊以 haer0248.me 當作範例)
3. composer require google/apiclient:^2.12.1
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> 中加入

<meta name="google-signin-client_id" content="<填入用戶端 ID>">

在要登入的頁面中加入

<div id="my-signin"></div>

<script>
function successLogin(googleUser){
  var profile = googleUser.getBasicProfile();
  var id_token = googleUser.getAuthResponse().id_token;

  $.ajax({
  type: "POST", url: "user.php", dataType: "json",
    data: {
      id_token: id_token,
      googleid: profile.getId()
    },
    success: function(data) {
      alert(data.message);
    },
    error: function(jqXHR) {
      $("button[id=google_link_btn]").html(`<i class="fab fa-google"></i> 重新連結`);
    }
  })
}

function onFailure(error) {
  console.log(error);
  $("button[id=google_link_btn]").html(`<i class="fab fa-google"></i> 重新連結`);
}

function onLoad() {
  gapi.signin2.render("my-signin", {
    "scope": "profile email",
    "width": 240,
    "height": 50,
    "longtitle": true,
    "theme": "dark",
    "onsuccess": successLogin,
    "onfailure": onFailure
  });
}
</script>

以下部分為使用按鈕呼叫 (jQuery 判斷後顯示的 JS)
*注意,此處透過 ajax Post 到指定的 PHP 頁面進行登入,回傳資料為 data. 開頭,若需要回傳資料請繼續查看下方。
*若需要下面三項以外的資料,必須申請通過才可以取得,其他公開的請前往: https://any-api.com/googleapis_com/oauth2/docs/userinfo/oauth2_userinfo_get

按鈕點選後帳號已選擇回傳資料頁面:

<?php
header('Content-Type: application/json; charset=UTF-8');

require_once '../ajax/vendor/autoload.php';

$return = Array();
if ($_SERVER['REQUEST_METHOD'] == "POST"){  
    /* 
    *  這邊可以填寫輸入資料庫及任何判斷或記錄於 SESSION 的部分,
    *  輸出一定要有一個資料,否則於前端很難除錯!
    */
    $client  = new Google_Client(['client_id' => '<填入用戶端 ID>']);
    $payload = $client->verifyIdToken($_POST['id_token']);
    
    if ($payload) { // 驗證使用者是否存在
        $return['message'] = '登入成功';
    } else {
        $return['message'] = '登入失敗';
    }
  
}else{
    $return['message'] = '傳輸方式錯誤';
}

echo json_encode($return); // 這邊就會在前端回傳 data.message

若有任何錯誤及問題,歡迎於底下留言及討論!

一位普通、快爆肝的大學生,目前就讀桃園某大學資訊工程系。

感謝您的閱讀😽

若您對本篇文章有任何建議或回饋,點擊下方圖片加入我的 Discord 伺服器來討論!

?