2014-02-18 8 views
1

Google 드라이브의 튜토리얼을 따르면 인증/액세스 토큰을 유지하기 위해 매번 인증/승인을 요청할 필요가 없도록 새로 고침 토큰을 사용해야한다고합니다 우리는 API 호출을합니다.Google 드라이브 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 호출을 수행하는 방법 ??

의견이 있으십니까 ??

감사합니다,
아니 켓

답변

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>"; 
} 

이렇게하면 클라이언트 사용자 상호 작용없이 Google 드라이브에 모든 파일이 표시됩니다.

+0

'Google_Auth_AssertionCredentials'에 문제가있어서 'Google_AssertionCredentials'에 파일 및 변경 기능이 있습니다. 하지만 지금 문제가 있습니다 :'PHP 치명적인 오류 : 75 행의 google_drive \ vendor \ google \ apiclient-services \ src \ Google \ Service \ Drive.php에서 생성자를 호출 할 수 없습니다. ' – Peter