《Disney +》 迪士尼、Marvel、彼思、星球大戰…  PS Blog 2021年度遊戲:得獎名單   同一角色不同姿態!「鬼滅之刃 火神血風譚」竈門炭治郎(火之神神樂)參戰!   《Crash Bandicoot™ 4: It’s About Time》即將登上PS5   不容錯過!E3 2021「SQUARE ENIX PRESENTS SUMMER SHOWCASE」發表內容統整!   《Resident Evil Village》Maiden體驗版今日登陸PS5   聖劍傳說高清復刻手遊版開售!12月21日前有早鳥優惠!   日本埼玉縣將線上舉行電競祭典「eSports SAITAMA FESTA 2021」   擁抱VR生存遊戲《Song in the Smoke》的原始曠野 

使用 Google PHP SDK 來做 OAuth 登入

商業

以前要使用 Google 帳號來做網站登入,會強迫一定要使用 Google+ API,但是 Google+ 預計 2019/3/7 關閉,所以 Google+ API 也跟著關閉,於是 Google 提供最原始的登入方式來做串接,此篇就是使用 Google OAuth 的方式做登入。

使用 Google PHP SDK 來做 OAuth 登入

使用 Google 標準 OAuth 2.0 登入,首先還是要申請憑證 (Google API Console),申請憑證步驟在這邊就不細說,主要就是下面幾點:

  1. 憑證新增:「OAuth 2.0 用戶端 ID」 (其它相關資料再行填寫)
  2. 進入新增完成的「OAuth 2.0 用戶端 ID」,於頁面最上方:「下載 JSON」 (存檔:credentials.json)

JSON 拿到後,再來就可以開始寫程式囉~

Google 這個教學影片可以先參考看看:

Google OAuth 2.0 的文件:

Google OAuth PHP 的程式範例

  1. composer require google/apiclient # apt install composer,安裝 PHP 的 Google API SDK
  2. 再來程式參考可見:
    addScope(['https://www.googleapis.com/auth/userinfo.email', Google_Service_Oauth2::USERINFO_PROFILE]);
    $gclient = new Google_Client();
    $gclient->setAuthConfig('credentials.json');
    $gclient->setAccessType('offline'); // offline access
    $gclient->setIncludeGrantedScopes(true); // incremental auth
    $gclient->addScope([Google_Service_Oauth2::USERINFO_EMAIL, Google_Service_Oauth2::USERINFO_PROFILE]);
    $gclient->setRedirectUri('https://example.com/'); // 寫憑證設定:「已授權的重新導向 URI 」的網址
    
    $google_login_url = $gclient->createAuthUrl(); // 取得要點擊登入的網址
    
    // 登入後,導回來的網址會有 code 的參數
    if (isset($_GET['code']) && $gclient->authenticate($_GET['code'])) {
        $token = $gclient->getAccessToken(); // 取得 Token
        // $token data: [
        // 'access_token' => string
        // 'expires_in' => int 3600
        // 'scope' => string 'https://www.googleapis.com/auth/userinfo.email openid https://www.googleapis.com/auth/userinfo.profile' (length=102)
        // 'created' => int 1550000000
        // ];
        $gclient->setAccessToken($token); // 設定 Token
    
        $oauth = new Google_Service_Oauth2($gclient);
        $profile = $oauth->userinfo->get();
    
        $uid = $profile->id; // Primary key
        print_r($profile); // 自行取需要的內容來使用囉~
    } else {
        // 直接導向登入網址
        header('Location: ' . $google_login_url);
        exit;
    }
    ?>
  3. 想要加強 OAuth 登入的 state,可以參考此篇:Google、Facebook oAuth2 登入如何帶回傳的參數(state)

幾個常見問答:

  • 查詢 Access Token 到期時間 API
    • https://www.googleapis.com/oauth2/v1/tokeninfo?accesstoken=$token # 看 expirein (秒數)
  • 程式裡面 Access Token 預設過期時間是 3600秒
  • 需要額外資料授權(Scope),可於此網頁找參數:OAuth 2.0 Scopes for Google APIs

Google Oauth2 API 文件:

Tsung

隨機商業新聞

Micorsoft