2015年5月3日 星期日

Google API登入

Google 登入API 筆記

需先至 https://console.developers.google.com/
註冊帳號,
並於API驗證,建立以下資訊
1.用戶端ID:
2.電子郵件地址:
3.用戶端密碼:
4.重新導向URL:
5.授權的JavaScript

建立金鑰:Api key




下載google-api-php-client 使用的API並解壓縮放在目錄下
在申請完各項驗證之後,
即可以開始實作引入:



1.使用者授權登入: OAuth 2.0  PHP API

https://developers.google.com/api-client-library/php/start/get_started      相關說明

使用googleAPI中的 Google_Oauth2Service 取得使用者資料 程式碼如下
setApplicationName("Test Google+");

//參數設定,google console 設定API的資料

$client->setClientId('google設定的ID');
$client->setClientSecret(google設定的Secret'');
$client->setRedirectUri('google設定的導向網址');
$client->setDeveloperKey('google設定的Key');
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));

$google_user = new Google_Oauth2Service($client);  //將設定檔案傳入使用Oauth2

if (isset($_REQUEST['logout']))    //確認是否有收到logout 清除session
{   
    unset($_SESSION['access_token']);
}

if (isset($_GET['code'])) //收到google Oauth2 授權傳入的code  進行後續調用資料
{             
    $client->authenticate($_GET['code']);
    $_SESSION['access_token'] = $client->getAccessToken();
    header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if (isset($_SESSION['access_token']))   //進行後client token設定
{
    $client->setAccessToken($_SESSION['access_token']);
}


if ($client->getAccessToken())      //如果存在 getAccessToken()  代表Oauth2成功,進行使用者資料存取
{
    $userinfo = $google_user->userinfo;  
    print_r($userinfo->get());      // Google_Oauth2Service 提供的方法 截取資料

} 
else 
{
    $authUrl = $client->createAuthUrl();        //存在Authurl導致
}
?>







Google 登入 使用者資料

Connect Me!
"; } else { print "Logout"; } ?>

沒有留言:

張貼留言