2015-10-27 59 views
0

我首次實施Google Login API。它工作正常,但我只能檢索電子郵件地址。我嘗試了其他方法,但沒有成功。我如何獲得其他用戶詳細信息,如用戶名?使用OAuth檢索Google用戶詳細信息

include('/../src/Google/autoload.php'); 
 

 

 
     /*   * ********************************************** 
 
      ATTENTION: Fill in these values! Make sure 
 
      the redirect URI is to this page, e.g: 
 
      http://localhost:8080/user-example.php 
 
     * ********************************************** */ 
 

 
     $client_id = 'bla-bla-bla'; 
 
     $client_secret = 'bla-bla-bla'; 
 
     $redirect_uri = 'bla-bla-bla/google_login'; 
 

 

 
     /*   * ********************************************** 
 
      Make an API request on behalf of a user. In 
 
      this case we need to have a valid OAuth 2.0 
 
      token for the user, so we need to send them 
 
      through a login flow. To do this we need some 
 
      information from our API console project. 
 
     * ********************************************** */ 
 

 
     if (isset($_GET['code'])) { 
 
      $client = new Google_Client(); 
 
      $client->setClientId($client_id); 
 
      $client->setClientSecret($client_secret); 
 
      $client->setRedirectUri($redirect_uri); 
 

 
      $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile')); 
 

 
      $client->authenticate($_GET['code']); 
 
      
 
      $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; 
 
      $google_oauth = new Google_Service_Oauth2($client); 
 
      print_r($google_ouath);//give error Undefined variable: google_ouath 
 
      print_r($google_ouath->userinfo); //give error Undefined variable: google_ouath 
 
      print_r($google_ouath->userinfo>get());//give error Undefined variable: google_ouath 
 
      $google_account_email = $google_oauth->userinfo->get()->email; //works fine 
 
      //$google_account_getDisplayName = $google_ouath->userinfo->get()->DisplayName; 
 
      //$google_account_givenname = $google_ouath->userinfo->get()->givenName; 
 
      //$google_account_name = $google_ouath->userinfo->get()->name; 
 
      echo '<pre>'; 
 

 
      print_r($google_account_email); 
 

 
      echo '</pre>'; 
 
      exit;

回答

0

這是因爲在變量名拼寫錯誤在這裏:

print_r($google_ouath);//give error Undefined variable: google_ouath 
print_r($google_ouath->userinfo); //give error Undefined variable: google_ouath 
print_r($google_ouath->userinfo>get());//give error Undefined variable: google_ouath 

變量名google_ouath應該是google_oauthau應該轉換,所以就變成:

print_r($google_oauth); 
print_r($google_oauth->userinfo); 
print_r($google_oauth->userinfo>get()); 

你也應該擺脫已過時的範圍名稱:

$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile')); 

,並使用速記和ID連接兼容格式:

$client->setScopes(array('email', 'profile'));