How to create a public Google Doc through the Drive API (PHP client)

二次信任 提交于 2019-11-30 10:27:54

After much reading and testing, I found the answer to my question.

The problem was the 'data' parameter of the file: the Google Docs cannot have plain text as data (their data needs to include some headers or something). So by deleting the 'data' parameter (and the 'mimeType' too, why not), the error I got disappeared.

As to the permissions, the solution was to first create the file with the default permissions, and then add a new one.

Below I paste the minimal code to create a publicly accessible Google Doc:

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

I have implemented this as a plugin in the Moodle LMS system, here is the source code, which includes a PHP class that implement creating and setting proper permissions to the docs. https://github.com/nadavkav/moodle-mod_googledrive

The actual relevant class is here: https://github.com/nadavkav/moodle-mod_googledrive/blob/master/classes/googledrive.php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!