原神1.2版本更新:龍脊雪山凜冽來襲   旅行食鬼 PAC-MAN GEO   想被這樣的吸血鬼吸血阿…!DOAXVV的萬聖節新穿搭「ブラッディ・キッス」登場!   成為《Marvel’s Spider-Man: Miles Morales》中的Superstar超級英雄   和風幻想RPG-陰陽師Onmyoji與熊本熊合作活動第3彈開始了!   用《ASTRO’s PLAYROOM》發揮DualSense無線控制器的力量   Ghost of Tsushima: Legends(奇譚模式)將於2020年秋季登陸PS4!   Nifty Games 宣布 Peter Moore 加入董事局 

使用 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)

幾個常見問答:

Google Oauth2 API 文件:

相關文章