google-api-php-client icon indicating copy to clipboard operation
google-api-php-client copied to clipboard

Is it possible to upload files to my own Google Drive using this SDK?

Open ghost opened this issue 10 years ago • 29 comments

Need to upload files on my PC to my own Google Drive (NOT to an end user's Google Drive) using PHP. Is this possible using this SDK? If so, how?

ghost avatar Jan 12 '16 19:01 ghost

Yes you could use this library to accomplish this - just download Service Account Credentials and set the file path with $client->setAuthConfig.

However, Wouldn't you be better off using the Drive desktop client for that?

bshaffer avatar Jan 12 '16 19:01 bshaffer

@bshaffer Thank you for your reply. Yes, I tried with Service account, however, its not giving me the same results as I have in my Google Drive. You can check the results here

And here is what I actually have in my Google Drive

Would you please explain why this happens?

ghost avatar Jan 12 '16 21:01 ghost

@bshaffer Here is the source code I've written:

<?php
include_once __DIR__ . '/vendor/autoload.php';

$client = new Google_Client();

$credentialsFile = __DIR__ . '/credentials/service_account.json';

if (!file_exists($credentialsFile)) {
    throw new RuntimeException('Service account credentials Not Found!');
}

$client->setAuthConfig($credentialsFile);
$client->setApplicationName("Service Account Example");
$client->setScopes(Google_Service_Drive::DRIVE);

$service = new Google_Service_Drive($client);

$files = $service->files->listFiles();

print '<pre>';

foreach ($files as $file) {
    print_r($file);
    print PHP_EOL . '--------------' . PHP_EOL;
}

print '</pre>';

ghost avatar Jan 12 '16 21:01 ghost

What results are you getting? It's probably because you need to set the subject. Try doing the following:

$client->setSubject('[email protected]');

I am surprised the API isn't just throwing an error. Is the response coming back with an empty array for files?

bshaffer avatar Jan 12 '16 21:01 bshaffer

Not an empty array... It contains only one file.

ghost avatar Jan 12 '16 21:01 ghost

@bshaffer I got an exception when I do that. Please help me correct the issue. https://googledrive-sunlean.c9users.io/

ghost avatar Jan 12 '16 21:01 ghost

@bshaffer it looks like using the setSubject() method is treated as an impersonation and that's the cause of the error. Does this mean every service account has its own google drive instance that is independent of the owner (Me)?

ghost avatar Jan 12 '16 22:01 ghost

@bshaffer After getting rid of the setSubject() line, I tried to insert some files and it worked just fine. it's just working on a mysterious drive :) I want it to work on MY OWN drive. Is this one of the issues that the latest SDK has? Maybe I might have to check out an older SDK.

ghost avatar Jan 12 '16 22:01 ghost

@bshaffer As long as I am using a @gmail.com account, I don't need to create a Google App account in order to do this, do I?

ghost avatar Jan 12 '16 23:01 ghost

I'm not sure why you're seeing different files - I was under the impression it was impossible to upload to drive without a user context.

We are doing something here that might be useful. We set accessType to offline, and once the user authorizes, it comes back with a refresh token that gets automatically refreshed each time.

// create an authorized client
$client = new Google_Client();
$client->setClientId($clientId);
$client->setClientSecret($clientSecret);

// create file cache for storing the access token and refresh token
$cache = new Google_Cache_File(sys_get_temp_dir().'/google-api-php-client-tests');

// make sure we have a token
if (!$token = $cache->get('access_token')) {
  $client->setRedirectUri("urn:ietf:wg:oauth:2.0:oob");
  $client->setConfig('access_type', 'offline');
  $authUrl = $client->createAuthUrl();

  echo "\nPlease enter the auth code:\n";
  ob_flush();
  `open '$authUrl'`;
  $authCode = trim(fgets(STDIN));

  $token = $client->fetchAccessTokenWithAuthCode($authCode);
  if (!isset($token['access_token'])) {
    exit('failed!');
  }
  $cache->set('access_token', $token);
}

$client->setAccessToken($token);

bshaffer avatar Jan 12 '16 23:01 bshaffer

@bshaffer I actually referred to this example that exists in the SDK.

https://github.com/google/google-api-php-client/blob/master/examples/service-account.php

For oAuth server-to-server interaction, I referred to this:

https://developers.google.com/api-client-library/php/auth/service-accounts

Probably the example is not for the right case?

ghost avatar Jan 13 '16 16:01 ghost

The second link there is referring to version 1 of this library, and has changed according to the Upgrading document in version 2. I suggest you stick with the first example.

We'll be moving the docs to version 2 very soon.

bshaffer avatar Jan 13 '16 18:01 bshaffer

@bshaffer I know that, but the example should work for my case. Can you give me sample code that do the job for me? I need it done ASAP... I know this is out of your interest/service but I'd like to ask you to for me :) I was not able to get the API to work for my case or to find any examples on the Internet that works with Google Drive. I have to use the service account because it shouldn't be asking me to log in.

ghost avatar Jan 13 '16 18:01 ghost

I have already provided several code samples that will accomplish this task. In addition, there is this example that exists as part of the repository which accomplishes what you are trying to do.

bshaffer avatar Jan 13 '16 18:01 bshaffer

@bshaffer This is not using service accounts. I wrote the code that combines the 2 examples (service account and file uploading) as you can see. As this reference says, I thought service accounts should work against my own google drive. Instead, it works against another mysterious google drive space that's independent of my drive and owned by that service account, which makes it impossible to access the files with my own google account. Is that a problem with the PHP SDK? Should I try version 1 or other SDK in other languages?

ghost avatar Jan 13 '16 18:01 ghost

You have two options:

1. Create an "installed application" and use a refresh token

This is what I outlined in my code sample above. This does not use a service account, but instead uses an Oauth "installed app" which fetches the access token with a refresh token indefinitely

2. Create a "service account" and from your USER account, authorize the client so it shows up here

this is trickier, as you will need to create an OAuth Client just to authorize your user

go to API Manager > Credentials > New Credentials > OAuth Client ID and then select other as the client type. screen shot 2016-01-13 at 11 59 46 am

Now download those credentials (below, client_secret_xxx.json) and use them like this:

$client->setAuthConfig('/path/to/client_secret_xxx.json');
$client->addScope("https://www.googleapis.com/auth/drive");
$client->setRedirectUri("urn:ietf:wg:oauth:2.0:oob"); // this is so you can grab the code in the browser
header('Location: '. $client->createAuthUrl());exit;

now you can copy the code and exchange it for an access token like this:

$client->fetchAccessTokenWithAuthCode($code);

It is not enough for you to authorize the client in the browser, you must also have the client request an access token to complete the authorization.

After all this, you will see the client show up under your authorized clients:

screen shot 2016-01-13 at 11 59 03 am

NEXT, you can switch back to your service account credentials and set the subject as the user who has authorized the app:

$client->setAuthConfig('/path/to/service-account-credentials.json');
$client->addScope("https://www.googleapis.com/auth/drive");
$client->setSubject('[email protected]');

// continue to upload with Drive forever and ever...

bshaffer avatar Jan 13 '16 20:01 bshaffer

@bshaffer Thanks a lot for your detailed explanation! :+1: It allowed me to refactor an old Adapter for laravel piece by piece.

Gummibeer avatar Jan 21 '16 20:01 Gummibeer

@bshaffer Now it says 'Requested client not authorized', even though I just pushed accept and copied the code and put it in the fetch function!

AndreyNazarchuk avatar May 07 '16 04:05 AndreyNazarchuk

@AndreyNazarchuk does the authorized application show up in your authorized applications? If not, I assume the access token was not fetched as expected.

bshaffer avatar May 07 '16 06:05 bshaffer

@bshaffer It did once, then after that I cant get it to show up again.

AndreyNazarchuk avatar May 07 '16 18:05 AndreyNazarchuk