php – 使用 Google Api 登入並取得個人資料

先介紹編碼,申請 API 方式緊接在後。

編碼

參考。這裡使用 composer 自動引入 google/apiclient 介紹。請按照 0 1 2 3 看流程喔!當然可以拆成多頁 PHP,就不用 if … elseif … 啦。

<?php 
session_start();
require_once 'vendor/autoload.php';

// 0) 設定 client 端的 id, secret
$client = new Google_Client;
$client->setClientId("你的 id");
$client->setClientSecret("你的 secret");

// 2) 使用者認證後,可取得 access_token 
if (isset($_GET['code'])) 
{
    $client->setRedirectUri("http://domain/test.php");
    $result = $client->authenticate($_GET['code']);

    if (isset($result['error'])) 
    {
        die($result['error_description']);
    }

    $_SESSION['google']['access_token'] = $result;
    header("Location:http://domain/test.php?action=profile");
}

// 3) 使用 id_token 取得使用者資料。另有 setAccessToken()、getAccessToken() 可以設定與取得 token
elseif ($_GET['action'] == "profile")
{
    $profile = $client->verifyIdToken($_SESSION['google']['access_token']['id_token']);
    print_r($profile); //使用者個人資料
}

// 1) 前往 Google 登入網址,請求用戶授權
else 
{
    $client->revokeToken();
    session_destroy();

    // 添加授權範圍,參考 https://developers.google.com/identity/protocols/googlescopes
    $client->addScope(['https://www.googleapis.com/auth/userinfo.profile']);
    $client->setRedirectUri("http://domain/test.php");
    $url = $client->createAuthUrl();
    header("Location:{$url}");
}

授權範圍可以這麼寫

$client->addScope(['https://www.googleapis.com/auth/userinfo.profile']);

或是使用這種寫法

$this->client->addScope([Google_Service_Oauth2::USERINFO_PROFILE]);

 

 

安裝

參考,使用 Google API Client Libraries 提供的 PHP 版本套件登入,並使用 composer 下載

"require": {
  "google/apiclient": "^2.0"
}

或是 Github 。此處範例以 composer 為介紹。

取得 ID 與 Secret

前往這裡,在左上角建立專案

輸入專案名稱

一開始平臺中沒有 API,所以我們選擇一個要使用的 API

我們挑選 Google+ API

 

然後啟用這項服務

 

啟用憑證

輸入需要的資料

選擇網路應用程式,並填寫重新導向的 URI。這非常重要,因為要告知 API 當認證完畢以後,要回到哪個網頁。下方介紹使用非框架的寫法,所以只有一張 test.php。

可以看到 ID 與密鑰

忘記的時候點選右邊的筆也能查看

申請文以後,就可以開始寫編碼

Comments

  1. Feeey个人博客
    2017-01-28 - 20:25

    进来转转,博主新年快乐。

  2. Feeey个人博客
    2017-02-11 - 07:59

    以后会常来逛逛,博客很棒。

發表迴響