I'm trying to upload a file to my Google Drive using a service account. When I deploy this code, I don't want the user to give authorization, I want them to upload to my account. I'm using this via PHP, and below is where I am so far.
This code is based on the examples given by the official documentation. When I run the php script, I get no errors, and I print_r the result variable. It has multiple URLs, when I go to it with the same account I created all this with, it says I need to request permission. When I look in my Google Developers console, it says it got the request and successfully ran it.
However, the file doesn't show anywhere in my Google Drive. I'm not really sure where to see these files on the service account, and how to get this file into my Google Drive. Below is my code.
Am I missing a permission somewhere, or am I supposed to somehow connect the service account to a normal account?
DEFINE("TESTFILE", 'testfile-small.txt');
if (!file_exists(TESTFILE)) {
$fh = fopen(TESTFILE, 'w');
fseek($fh, 1024 * 1024);
fwrite($fh, "!", 1);
fclose($fh);
}
// The setup
// Authentication Credentials
$client_id = '<my client id>'; //Client ID
$service_account_name = '<my client email'; //Email Address
$key_file_location = '<path to key>'; //key.p12
// Create the client
$client = new Google_Client();
$client->setApplicationName("IEEE_File_Upload");
$service = new Google_Service_Drive($client);
// Check for token
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
// Get the key
$key = file_get_contents($key_file_location);
// Create the credentials
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/drive'),
$key
);
// Set the credentials
$client->setAssertionCredentials($cred);
// Something with tokens
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
// Actual file stuff
// Now lets try and send the metadata as well using multipart!
$file = new Google_Service_Drive_DriveFile();
$file->setTitle("Hello World!");
$result = $service->files->insert(
$file,
array(
'data' => file_get_contents(TESTFILE),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
)
);
echo "<h3>Results Of Call:</h3>";
foreach ($result as $item) {
echo $item['volumeInfo']['title'], "<br /> \n";