2015-05-29 118 views
0

我已經在服務類型憑證在谷歌控制檯中創建項目。我已經下載P12密鑰文件,然後寫示例代碼插入文件來測試它:如何從項目中瀏覽文件谷歌驅動器

<?php 
require_once 'google-api-php-client/src/Google_Client.php'; 
require_once 'google-api-php-client/src/contrib/Google_DriveService.php'; 
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php"; 

$scopes = array('https://www.googleapis.com/auth/drive'); 
$accountEmail = 'SECRET'; 
$accountP12FilePath = './key.p12'; 


$key = file_get_contents($accountP12FilePath); 
$auth = new Google_AssertionCredentials($accountEmail, $scopes, $key); 
$client = new Google_Client(); 
$client->setUseObjects(true); 
$client->setAssertionCredentials($auth); 
$service = new Google_DriveService($client); 

$file = new Google_DriveFile(); 
$file->setTitle('Test Title'); 
$file->setDescription('test description'); 
$parent = new Google_ParentReference(); 
$file->setParents(array($parent)); 


$createdFile = $service->files->insert($file, array(
    'data' => 'test data', 
    'mimeType' => 'text/plain' 
)); 

var_dump($createdFile); 
?> 

它轉儲Google_DriveFile對象有許多的URL。其中一些,如'downloadUrl',返回401未授權錯誤。當我嘗試'alternateLink'時,它顯示帶有我需要訪問的信息的Google驅動器頁面,以及請求訪問和切換帳戶的按鈕。

它還表示我當前登錄了我的帳戶,這是用來創建項目的工具,並且可以在Google控制檯頁面的項目的權限頁面上看到。

如何訪問屬於我在腳本中使用的項目的驅動器?

回答

0

終於找到解決方案,它丟失了文件權限。值得注意的是,將權限對象傳遞給$ file對象(插入前)不起作用。我不得不通過傳遞已創建的文件名和權限對象到$服務 - > permissions-> insert方法,就像是插入權限:

$permission = new Google_Permission(); 
$permission->setValue('[email protected]'); 
$permission->setType('user'); 
$permission->setRole('writer'); 
$service->permissions->insert($createdFile->getId(), $permission); 

不過我是不是能夠真正編輯該文件。當我打開文件的URL

$createdFile->getAlternateLink(); 

然後,我不得不重新打開該文件與谷歌文檔。該文件複製到我的個人帳戶,然後我只能編輯一個文件的副本,而不是基本文件本身。

我不知道是否有辦法讓這些文件真正可編輯,但我搬到了Dropbox,因爲谷歌驅動API和它的文檔SUX

相關問題