2015-05-29 113 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

相关问题