Reputation: 1178
Everyone I need to upload file to Google Drive via the API, I did exactly what it is mention https://developers.google.com/drive/quickstart-php.
I had generated the access token and saved it in the file, the problem is that it only works for the first time and next time it gives error
OAuth2 token, message: '{ "error" : "invalid_grant" }
We only need to upload files to Google drive (our own account) after getting from the users by form.
I had tried scripts from many tutorial but it didn't seem to work. I had also tried with offline access permission but still no luck.
Update: Here it the code that I use to generate access token
require_once APP_PATH.'_includes/google_drive/Google_Client.php';
require_once APP_PATH.'_includes/google_drive/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('xxxxxxxxxxxxxxxx');
$drive->setClientSecret('xxxxxxxxxxxxxxx');
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$url = $drive->createAuthUrl();
$authorizationCode = trim(fgets(STDIN));
$token = $drive->authenticate($authorizationCode);
And then I used this code $drive = new Google_Client();
$drive->setClientId('xxxxxxxxxxx');
$drive->setClientSecret('xxxxxxxxxxxxxxx');
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$_GET['code']= '4/axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test Document');
$doc->setDescription('Test description');
$doc->setMimeType('text/plain');
$content = file_get_contents('document.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
it works good and but when I run the page again it says
Fatal error: Uncaught exception 'Google_AuthException' with message 'Error fetching OAuth2 access token, message: 'invalid_grant'' in ...Google_OAuth2.php on line 115
any help is appreciated.
Upvotes: 4
Views: 7379
Reputation: 1178
Based on @BurcuDogan's comment, commenting out authenticate method resolved the issue.
//file_put_contents('token.json', $drive->authenticate());
Upvotes: 1