这就是我到目前为止所得到的,通过结合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 );
它不起作用,而且,当我再次查看数组时,我注意到“共享”键仍然没有分配任何值。我在网上查找了任何可能对我有帮助的文档,但没有运气。有人可以帮我吗?谢谢!!