2

Dear Stackoverflow Helper ... I need a big ask. Google Help page are very unhelpful and doesn’t explain it at all.

I have been trying to work out the Google Drive API, something they claim is easy, and yet for the last few days nothing has me more stumped.

Basically I have “underpants …?... profit” I just need that something.

So all I want to do is write a PHP script, which will be called without user interaction on my server by a cron job It calls the list of files in my Google drive Gives me the download links And I’ll sort it all out and download the latest file (to a certain criteria PDF certain file name)

require_once 'google-api-php-client/src/Google/Client.php';
require_once 'google-api-php-client/src/Google/Service/Drive.php';

$client = new Google_Client();
// Get your credentials from the console
$client->setClientId(IDHere);
$client->setClientSecret(SecretHere);
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));

$service = new Google_Service_Drive($client);

$authUrl = $client->createAuthUrl();

//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));

// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);

$GoogleDriveList = file_get_contents("https://www.googleapis.com/drive/v2/files?fields=items(id%2CdownloadUrl%2CoriginalFilename%2CcreatedDate%2CfileExtension)&key=APIKEYHERE");
echo $GoogleDriveList;

First Issue The required once is different to the samples the google gives, thus through much trial an error I have had to guess at which classes should be initialised.

I keep getting numerous errors about classes that are not activated

Fatal error: Class 'Google_Service' not found in ***\google-api-php-client\src\Google\Service\Drive.php on line 32

(Which I solved by require_once 'google-api-php-client/src/Google/Service.php';)

Fatal error: Class 'Google_Service_Resource' not found in ***\google-api-php-client\src\Google\Service\Drive.php on line 1283

(This one I don’t know where the class lives, I tried searching all the php docs in “src\Google”, but no joy, but I could have missed it.)

Second Issue I just need it OAuth to do its thing so I can call this line

$GoogleDriveList = file_get_contents("https://www.googleapis.com/drive/v2/files?fields=items(id%2CdownloadUrl%2CoriginalFilename%2CcreatedDate%2CfileExtension)&key=APIKEYHERE");

Would some please give me the code to get AuthO working

This part has to be wrong, it just doesn’t make sense to me, and it seems like user input. But after days of searching I can’t find a single automatic system. And yet the very page this code is from seem to suggest that this is the answer.

//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));

To me this looks like what I want https://developers.google.com/drive/web/auth/web-server but for the life of me I can’t find the simple things like how to initialise the getCredentials, and what parameters I have to pass to it?

I have also seen code on this URL but I am just too fried to understand it. Though it does look really promising. https://developers.google.com/accounts/docs/OAuth2WebServer#formingtheurl

Does anyone have a sample code of how to get this blast thing to work? I just need a full code sample of how the php OAuth system works. Thank you very much Sorry if it doesn't make sense but I am just fried …

pinoyyid
  • 21,499
  • 14
  • 64
  • 115
James
  • 196
  • 14
  • Have you looked at this [sample code](https://code.google.com/p/google-mail-oauth2-tools/wiki/PhpSampleCode)? – pointNclick Apr 01 '15 at 22:21
  • @pointNclick oh thats new ... I have the libraries, but didn't see the samples. That just might be it thank you! – James Apr 02 '15 at 00:23
  • 1
    See http://stackoverflow.com/questions/19766912/how-do-i-authorise-a-background-web-app-without-user-intervention-canonical?s=8|2.2577 and https://www.google.com.ph/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CBwQFjAA&url=https%3A%2F%2Fdevelopers.google.com%2Faccounts%2Fdocs%2FOAuth2WebServer&ei=nsAcVYiyHY-KuATXtIGQBQ&usg=AFQjCNFKZyBwtXHgiBDy8V7KKguVffM78g&sig2=nKIYsDpUkifZDJO7Bvxtcg&bvm=bv.89744112,d.c2E . DO NOT READ ANY OTHER PAGES UNTIL YOU'VE UNDERSTOOD THOSE TWO. – pinoyyid Apr 02 '15 at 04:08
  • @pinoyyid when someone is looking for help... general rule of thumb is that they do not understand it, that is why they are asking for help. But reading the stackoverflow link, I understand that the only way for this to work is to trick the system into leaving a token open forever. It seems that Google AuthO system has just defeated itself – James Apr 02 '15 at 14:13
  • @James It's OAuth. Apologies for the caps, it's just hard to provide emphasis in comments. If you read and understand those two pages, you will have all the knowledge you need. The Google docs are difficult to assimilate because they're so scattered and generally focus on a use case other than yours. That's why I'm focussing you towards those two. The refresh token works very well because it's secured by the app in a server and can be revoked by the user at any time. – pinoyyid Apr 02 '15 at 15:59
  • imho, the problem is exacerbated by libraries that provide ill-documented, leaky abstractions. If you read and understand those two pages, you'll see that you only need a couple of REST POSTS and an http redirect. You'll find yourself surprised at how something so simple can become so impenetrable. I've wasted weeks of my life wrangling this, which is why I'm happy to provide assistance wherever I can on SO. – pinoyyid Apr 02 '15 at 16:02

2 Answers2

0

$CLIENT_ID = 'YOUR_CLIENT_ID..ENDS.WITH.apps.googleusercontent.com';
$CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
$RefreshToken = 'YOUR_REFRESH_TOKEN';
$ReDirectURL = 'https://developers.google.com/oauthplayground'; #needs to be set, normally just set to the oauthplayground
$YOUR_API_KEY = 'YOUR_API_KEY';

$url = 'https://www.googleapis.com/oauth2/v3/token';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
curl_setopt($ch, CURLOPT_FAILONERROR, false);  
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); 

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded'
));

curl_setopt($ch, CURLOPT_POSTFIELDS,
    'client_id=' . urlencode($CLIENT_ID) . '&' .
    'client_secret=' . urlencode($CLIENT_SECRET) . '&' .
    'refresh_token=' . urlencode($RefreshToken) . '&' .
    'grant_type=refresh_token'
); 
$AuthorizationReturn = curl_exec($ch);
curl_close($ch);

$lemmings = explode('"',$AuthorizationReturn);
$accessToken = $lemmings[3];

$GoogleDriveList = file_get_contents("https://www.googleapis.com/drive/v2/files?fields=items(id%2CdownloadUrl%2CoriginalFilename%2CcreatedDate%2CfileExtension)&key=$YOUR_API_KEY&access_token=$accessToken");
$GoogleDriveList = json_decode($GoogleDriveList, true);

#The rest is dependent on your goals ... good luck and I hope I saved you the stress
#Get List of Files on your Google Drive and find the id of the file ($i being a counter through the list)
$FILE_ID = $GoogleDriveList['items'][$i]['id'];
$DownloadedFilefromGoogleDrive = file_get_contents("https://www.googleapis.com/drive/v2/files/$FILE_ID?alt=media&key=$YOUR_API_KEY");
# and save ...
James
  • 196
  • 14
  • Sorry to add, you need to read up on the links given by pinoyyid (thank you) and setting up of a Google Drive API ... and honestly google service end is like trying to navigate a mine field in an oil tanker with a blindfold – James May 01 '15 at 09:10
0

I was getting the error:

Fatal error: Class 'Google_Service_Resource' ....

Until I added this line:

require_once 'google-api-php-client/src/Google/autoload.php';

According to this issue and comment: https://stackoverflow.com/a/29620217/2911874

Community
  • 1
  • 1