PHP使用Google Plus Oauth登錄
前陣子Google+已經(jīng)發(fā)布了OAuth的應(yīng)用程序編程接口,現(xiàn)在他們只提供用戶活動和循環(huán)數(shù)據(jù)。我已經(jīng)使用PHP通過Google+數(shù)據(jù)簡單實現(xiàn)了一個稱為用戶身份驗證的登錄系統(tǒng)。試試這幾乎就像twitter登錄系統(tǒng),我希望未來Google+會釋放更多選項。
使用Google Plus Oauth登錄
第一步
點擊這里添加或者注冊你的域名。
添加或者注冊你的域名
第二步
通過HTML文件上傳或包括META標簽來驗證您的域名所有權(quán)。
通過HTML文件上傳或包括META標簽來驗證您的域名所有權(quán)。
第三步
谷歌將會提供你OAuth用戶密鑰和秘密密鑰。
谷歌將會提供你OAuth用戶密鑰和秘密密鑰
第四步
在Oauth控制臺創(chuàng)建客戶端ID(Client ID)。
在Oauth控制臺創(chuàng)建客戶端ID(Client ID)
在Oauth控制臺創(chuàng)建客戶端ID(Client ID)
第五步
應(yīng)用的Oauth Client ID和客戶端密鑰(client secret)。
應(yīng)用的Oauth Client ID和客戶端密鑰(client secret)
下面來看一下我們的程序文件。
#p#
Config.php
在這里,你必須配置OAuth應(yīng)用密鑰和用戶密鑰。
- // OAuth2 Settings, you can get these keys at https://code.google.com/apis/console Step 6 keys
- 'oauth2_client_id' => 'App Client ID',
- 'oauth2_client_secret' => 'App Client Secret',
- 'oauth2_redirect_uri' => 'http://yoursite.com/gplus/index.php',
- // OAuth1 Settings Step 3 keys.
- 'oauth_consumer_key' => 'OAuth Consumer Key',
- 'oauth_consumer_secret' => 'OAuth Consumer Secret',
gplus_login.php
google+的登錄系統(tǒng)。
- <?php
- require_once 'src/apiClient.php';
- require_once 'src/contrib/apiPlusService.php';
- session_start ();
- $client = new apiClient ();
- $client->setApplicationName ( "9lessons Google+ Login Application" );
- $client->setScopes ( array ('https://www.googleapis.com/auth/plus.me' ) );
- $plus = new apiPlusService ( $client );
- if (isset ( $_REQUEST ['logout'] )) {
- unset ( $_SESSION ['access_token'] );
- }
- if (isset ( $_GET ['code'] )) {
- $client->authenticate ();
- $_SESSION ['access_token'] = $client->getAccessToken ();
- header ( 'Location: http://' . $_SERVER ['HTTP_HOST'] . $_SERVER ['PHP_SELF'] );
- }
- if (isset ( $_SESSION ['access_token'] )) {
- $client->setAccessToken ( $_SESSION ['access_token'] );
- }
- if ($client->getAccessToken ()) {
- $me = $plus->people->get ( 'me' );
- $_SESSION ['access_token'] = $client->getAccessToken ();
- } else
- $authUrl = $client->createAuthUrl ();
- if (isset ( $me )) {
- $_SESSION ['gplusdata'] = $me;
- header ( "location: home.php" );
- }
- if (isset ( $authUrl ))
- print "<a class='login' href='$authUrl'>Google Plus Login </a>";
- else
- print "<a class='logout' href='index.php?logout'>Logout</a>";
- ?>
home.php
這里包含了將google+的session信息插入user數(shù)據(jù)表的PHP代碼。
- <?php
- session_start();
- if (!isset($_SESSION['gplusdata'])) {
- // Redirection to home page
- header("location: index.php");
- }else{
- $me=$_SESSION['gplusdata'];
- echo "<img src='{$me['image']['url']}'/>";
- echo "Name: {$me['displayName']}";
- echo "Gplus Id: {$me['id']}";
- echo "Male: {$me['gender']}";
- echo "Relationship: {$me['relationshipStatus']}";
- echo "Location: {$me['placesLived'][0]['value']}";
- echo "Tagline: {$me['tagline']}";
- print "<a class='logout' href='index.php?logout'>Logout</a> ";
- }
- ?>
下面附上使用Google Plus Oauth登錄的示例源碼:下載點這里
原文鏈接:http://www.phpfuns.com/php/login-with-google-plus-oauth.shtml
【編輯推薦】