如何通过 Drive API(PHP 客户端)创建公共 Google 文档

2023-12-12

这就是我到目前为止所得到的,通过结合this and this:

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

//First, build a Drive service object authorized with the service accounts
$auth = new Google_AssertionCredentials(
    DRIVE_SERVICE_ACCOUNT_EMAIL,
    array( DRIVE_SCOPE ),
    file_get_contents( DRIVE_SERVICE_ACCOUNT_KEY )
);
$client = new Google_Client();
$client->setUseObjects( true );
$client->setAssertionCredentials( $auth );
$service = new Google_DriveService( $client );

//Then, insert the file
$file = new Google_DriveFile();
$file->setTitle( 'My document' );
$file->setMimeType( 'text/plain' );
$createdFile = $service->files->insert( $file, array(
    'data' => 'Hello world!',
    'mimeType' => 'text/plain',
));

print_r( $createdFile );

它有效,这意味着它创建一个文本/纯文件并返回一个包含其元数据的数组。但是,我想要的是创建一个 Google 文档,而不是文本/纯文本。当然,我尝试将 mime 类型(两种外观)更改为“application/vnd.google-apps.document”,但得到以下结果:

致命错误:未捕获异常“Google_ServiceException”,消息为“调用 POST 时出错”https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart:/local/path/to/google-api-php-client/src/io/Google_REST.php:66 中的(400)错误请求

另外,我需要该文档可供公众访问。当我通过上述方法上传文本/纯文件,然后尝试浏览它(从与上传者不同的帐户)时,我被告知我需要权限。我仔细查看了数组$createdFile并注意到一个没有值的“共享”密钥,所以我很天真地尝试将其设置为 1:

$file->setShared( 1 );

它不起作用,而且,当我再次查看数组时,我注意到“共享”键仍然没有分配任何值。我在网上查找了任何可能对我有帮助的文档,但没有运气。有人可以帮我吗?谢谢!!


经过大量阅读和测试,我找到了问题的答案。

问题是文件的“数据”参数:Google 文档不能将纯文本作为数据(它们的数据需要包含一些标题或其他内容)。因此,通过删除“data”参数(以及“mimeType”,为什么不呢),我得到的错误就消失了。

至于权限,解决方案是先创建具有默认权限的文件,然后添加新的权限。

下面我粘贴了创建可公开访问的 Google 文档的最少代码:

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

//Build the Drive Service object authorized with your Service Account
$auth = new Google_AssertionCredentials(
    DRIVE_SERVICE_ACCOUNT_EMAIL,
    array( DRIVE_SCOPE ),
    file_get_contents( DRIVE_SERVICE_ACCOUNT_KEY )
);
$client = new Google_Client();
$client->setUseObjects( true );
$client->setAssertionCredentials( $auth );
$service = new Google_DriveService( $client );

//Create the file
$file = new Google_DriveFile();
$file->setTitle( 'Hello world!' );
$file->setMimeType( 'application/vnd.google-apps.document' );
$file = $service->files->insert( $file );

//Give everyone permission to read and write the file
$permission = new Google_Permission();
$permission->setRole( 'writer' );
$permission->setType( 'anyone' );
$permission->setValue( 'me' );
$service->permissions->insert( $file->getId(), $permission );

print_r( $file );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何通过 Drive API(PHP 客户端)创建公共 Google 文档 的相关文章

随机推荐