This is what I've got so far, by combining 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 );
It works, meaning that it creates a text/plain file and returns me an array with its metadata. However, what I want is to create a Google Document, not a text/plain. I tried of course changing the mime type (both appearances) to "application/vnd.google-apps.document", but got the following:
Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling POST https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart: (400) Bad Request' in /local/path/to/google-api-php-client/src/io/Google_REST.php:66
Also, I need the document to be publicly accessible. When I upload a text/plain file through the above method, and then try to browse to it (from an account different of the uploader's), I'm told that I need permission. I took a closer look at the array in $createdFile
and noticed a 'shared' key with no value, so quite naively I tried setting it to 1 with:
$file->setShared( 1 );
It didn't work, and also, when I looked again at the array, I noticed that the 'shared' key had still no value assigned to it. I looked online for any documentation that may help me, but no luck. Anyone can help me out? Thanks!!