search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

Using OAuth 2.0 to Access Google APIs with Google API PHP Client – 佛祖球球

Using OAuth 2.0 to Access Google APIs with Google API PHP Client

PHP:7.2
google/apiclient:v2.4.0

Google 提供了許多 API 給開發者使用,如果要讓使用者透過 Google APIs 存取資訊,必須先透過 OAuth 登入以後,取得 Google 配發的 Access Token 才可以使用。許多網站常見的第三方登入也是透過一樣的原理製作完成。

相關文件可以參考 Google OAuth2

Preconditions

在開始之前,必須先按照 Google 的規定,到 Google API Console 申請 Client ID。

Step 1. 建立專案
Create Project

Step 2. 開啟你需要使用到的 API
Enable API

Step 3. 建立 OAuth Client ID
Get OAuth Client ID

Step 4. 設定 OAuth page(記得把需要用的 API 加進授權範圍)
Setting OAuth page

Step 5. 將 client_secret 下載下來
Download client_secret

Web Flow of Web Server Applications

在開始之前,先說明一下 Web Application 做 Google OAuth Login 的架構:
Web Application login flow with OAuth

  • 網站發出 要求 Token 的需求
  • 將網站導到 Google 登入畫面
  • 登入成功以後,Google 會導回你的 Redirect url 並在參數代入一次性的 Authorization code
  • 使用 Authorization code 要求換取 Access Token

Basic Usage

Google API PHP Client 是 Google 提供的 SDK 之一,可以讓開發者透過 PHP 操作 Google APIs。

使用 Composer 安裝

composer require google/apiclient:"^2.0"

產生登入 URL

$client = new Google_Client();
// 代入從 API console 下載下來的 client_secret
$client->setAuthConfig('client_secret.json');

// 加入需要的權限(Google Drive API)
// 也可以使用 url,例如:https://www.googleapis.com/auth/drive.metadata.readonly
$client->addScope(['profile', Google_Service_Drive::DRIVE_METADATA_READONLY]);

// 設定 redirect URI,登入認證完成會導回此頁
$client->setRedirectUri('https://xxxx');

// 不需要透過使用者介面就可以 refresh token
$client->setAccessType('offline');
// 支援 Incremental Authorization 漸進式擴大授權範圍
$client->setIncludeGrantedScopes(true);

// 產生登入用的 URL
$authUrl = $client->createAuthUrl();
// 導至登入認證畫面
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));

Notice: 詳細授權清單可以參考 Google Scopes , SDK 提供的 Service 清單則在 Google API PHP Client Service

取得 Access Token

$client = new Google_Client();
// 代入從 API console 下載下來的 client_secret
$client->setAuthConfig('client_secret.json');

// Authorization code
$code = $_GET['code'];
$client->authenticate($code);

// 取得 Access Token
$accessToken = $client->getAccessToken();

存取 API

$client = new Google_Client();
// 代入 Access Token
$client->setAccessToken($accessToken);

// 取得使用者資訊
$oauth = new Google_Service_Oauth2($client);
$userinfoObj = $oauth->userinfo->get();

// 取得 Google Drive 檔案清單
$drive = new Google_Service_Drive($client);
$results = $drive->files->listFiles([]);

if (count($results->getFiles()) === 0) {
    echo 'No files found.';
} else {
    echo "Files:" . PHP_EOL;
    foreach ($results->getFiles() as $file) {
        echo $file->getName() . PHP_EOL;
    }
}

1 Comment

使用 Facebook, Google+ 進行網站會員認證 | hoyo 學習紀錄 · 10 月 2, 2015 at 4:50 下午

[…] [Oauth]使用 OAuth 2.0 存取 Google APIs(for Login) […]

Comments are closed.



熱門推薦

本文由 blogjohnsonluorg 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦