2014-02-18 175 views
1

我跟着谷歌驅動器上的教程,它說,要堅持認證/訪問令牌,我們必須使用刷新令牌,以便我們不必要求用戶每次驗證/授權我們做一個API調用。谷歌驅動器API授權問題

代碼:

require_once 'google-api-php-client/src/Google_Client.php'; 
require_once 'google-api-php-client/src/contrib/Google_DriveService.php'; 


$client = new Google_Client(); 
// Get your credentials from the console 
$client->setClientId('client ID'); 
$client->setClientSecret('client secret'); 
$client->setRedirectUri('URL'); 

$client->setScopes(array('https://www.googleapis.com/auth/drive')); 
$client->setAccessType('offline'); 

$service = new Google_DriveService($client); 

$authUrl = $client->createAuthUrl(); 


// Exchange authorization code for access token 
$accessToken = $client->authenticate(); 

$client->setAccessToken($accessToken); 

$files = $service->files->listFiles(); 
echo "<pre>"; print_r($files); 

這給我的文件和文件夾列表中,但我每次刷新頁面,它把我帶回到谷歌授權頁面。我可以將訪問令牌保存在數據庫中,但是如何使用它並進行API調用,而無需再向用戶請求授權?

任何想法??

謝謝
Aniket

回答

0

可能,最好採用P12鍵使用服務器到服務器的身份驗證: https://developers.google.com/api-client-library/php/auth/service-accounts

您可以模擬用戶帳戶,所有文件都將通過你的服務器訪問。

$client_email = '1234567890- [email protected]'; 
$private_key = file_get_contents('MyProject.p12'); 
$user_to_impersonate = '[email protected]'; 

$private_key = file_get_contents($pkey); //notasecret 
$scopes = array('https://www.googleapis.com/auth/drive'); 
$credentials = new \Google_Auth_AssertionCredentials(
     $client_email, 
     $scopes, 
     $private_key, 
     'notasecret', // Default P12 password 
     'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type 
     $user_to_impersonate 
    ); 

$client = new \Google_Client(); 
$client->setAssertionCredentials($credentials); 
if ($client->getAuth()->isAccessTokenExpired()) { 
     $client->getAuth()->refreshTokenWithAssertion(); 
} 

$service = new \Google_Service_Drive($client); 

$files = $service->files->listFiles(); 
echo "count files=".count($files)."<br>";  

foreach($files as $item) { 
    echo "title=".$item['title']."<br>"; 
} 

這會給你沒有任何客戶端的用戶交互在您的谷歌驅動器列出的所有文件。

+0

我有'Google_Auth_AssertionCredentials'問題,但找到了文件並將其更改爲'Google_AssertionCredentials'。但現在我有問題:PHP致命錯誤:無法在第75行的google_drive \ vendor \ google \ apiclient-services \ src \ Google \ Service \ Drive.php中調用構造函數 – Peter