2017-02-07 14 views
3

我一直在做谷歌認證教程,以更好地瞭解如何使用谷歌登入API和我最近收到此錯誤:致命錯誤:調用一個成員函數的getAttributes()的陣列

Fatal error: Call to a member function getAttributes() on array. 

它每當我嘗試:

$this->client->verifyIdToken()->getAttributes(); 

getPayload()函數。我不知道爲什麼會發生這種情況。我的配置是Windows 10,我正在使用WAMP服務器來運行此應用程序。任何幫助,將不勝感激。

<?php class GoogleAuth { 
private $db; 
private $client; 
public function __construct(Google_Client $googleClient) 
{ 
    $this->client = $googleClient; 
    $this->client->setClientId('234sfsdfasdfasdf3223jgfhjghsdsdfge3.apps.googleusercontent.com'); 
    $this->client->setClientSecret('fD5g4-B6e5dCDGASefsd-'); 
    $this->client->setRedirectUri('http://localhost:9080/GoogleSigninTutorial/index.php'); 
    $this->client->setScopes('email'); 
} 

public function checkToken() 
{ 
    if(isset($_SESSION['access_token']) && !empty($_SESSION['access_token'])) 
    { 
    $this->client->setAccessToken($_SESSION['access_token']); 
    } 
    else 
    { 
    return $this->client->createAuthUrl(); 
    } 
    return ''; 
} 

public function login() 
{ 
    if(isset($_GET['code'])) 
    { 
    $this->client->authenticate($_GET['code']); 
    $_SESSION['access_token'] = $this->client->getAccessToken(); 
    return true; 
    } 
    return false; 
} 

public function logout() 
{ 
    unset($_SESSION['access_token']); 
} 

public function getPayload() 
{ 
    return $this->client->verifyIdToken()->getAttributes(); 
} 
} 
?> 

回答

5

我有同樣的問題。 從我似乎明白了,

$attributes = $this->client->verifyIdToken()->getAttributes(); 

是訪問應該返回的谷歌帳戶信息的陣列過時的方式(即在運行此行之後,$屬性,預計將與所有的數組對應令牌谷歌帳戶的信息。)

試試這個

$this->client->verifyIdToken(); 

看來,在最新的API(到目前爲止),這條線本身返回與預期信息的數組(這是爲什麼呢當你添加->getAttributes()時,你會得到一個錯誤,因爲這個函數在數組上調用時是無效的。) 因此,只需運行上面的這一行來生成數組,並將其放入回顯中,如果你想查看這些值,如

echo '<pre>', print_r($attributes), '</pre>'; 

如果你沒有看到任何陣列顯示,這可能是因爲你有一個 header('Location: url') 的地方,在執行該回波之後重定向到另一個URL地址,所以它永遠不會顯示。 (或A die

您也可以直接通過做

$this->client->verifyIdToken()['email']; 
$this->client->verifyIdToken()['name']; 
//so on 

希望這可以幫助訪問特定的屬性,如emailnamegiven_namefamily_name

+1

謝謝!爲我節省了時間!只是一件事,當設置範圍指定你想要什麼...檢查這裏... http://stackoverflow.com/questions/14007560/get-userinfo-from-google-oauth-2-0-php-api – Albeis

+0

好點Albeis!另外,您可以在這裏找到所有範圍https://developers.google.com/identity/protocols/googlescopes只需使用Ctrl + F(Cmd + F)在您需要的範圍內查找特定關鍵字確定它被稱爲。 – user

相關問題