I am trying to create a script to upload my file to Google Drive. When I run it, it works perfectly. Here's the working code:
public function uploadToDrive()
{
$client = new Google_Client();
$client->setClientId(Mage::getStoreConfig('mtm_google/drive/client_id'));
$client->setClientSecret(Mage::getStoreConfig('mtm_google/drive/client_secret'));
$client->setRedirectUri(Mage::getStoreConfig('mtm_google/drive/redirect_uri'));
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
session_start();
if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$client->setAccessToken($_SESSION['access_token']);
}
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->setName('analysis.csv');
$file->setDescription('A test document');
$data = file_get_contents('temp.csv');
$service->files->create($file, array(
'data' => $data,
'mimeType' => 'text/csv',
'uploadType' => 'multipart'
));
echo 'SUCCESS!';
unlink('temp.csv');
} else {
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit();
}
}
This script should be executable from console, and not executed from certain URL. When I try to execute this from console, nothing happens because session variables and redirects are something it can't handle. How can I modify this script in order to be executable from console?
Simply define/set variables : $_GET, $_SESSION, ....
Those variables can be passed like an arguments from console using $argv[]
Related
Hi Im trying Google drive integration v3 in php to upload file from my web page i do not want to use picker. I have successfully done oauth and login. I can create a file in the drive but with empty data. the error i get is permission to write i have given public access to that folder. How can i solve this and write the content to that file.
My code after auth(successfull) redirect.
first.php
require_once 'google-api-php-client/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('conf/client_id.json');
//$scope='https://www.googleapis.com/auth/drive.file';
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->addScope(Google_Service_Drive::DRIVE_FILE);
$client->addScope(Google_Service_Drive::DRIVE);
$client->addScope(Google_Service_Drive::DRIVE_APPDATA);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Drive($client);
$data = file_get_contents("a.png");
// create and upload a new Google Drive file, including the data
$file = new Google_Service_Drive_DriveFile($client);
$file->setName('img_'.uniqid().'.png');
$file->setMimeType('image/png');
//$parent = new Google_ParentReference();
//$parent->setId("0B687nRLFFN08ZXg0WU9Zb3VQaEE");
//$file->setParents(array($parent));
//$file->setParents(array('setId'=>"0B687nRLFFN08ZXg0WU9Zb3VQaEE"));
$createdFile = $service->files->create($file, array(
'data' => file_get_contents("a.png"), //$data
'mimeType' => 'image/png',
'uploadType' => 'media'
));
}
else {
$redirect_uri='http://'.$_SERVER['HTTP_HOST'].'/google/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
I am trying to upload files to google drive using below code
require_once 'google-api-php-client-master/src/google/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope('https://www.googleapis.com/auth/drive');
if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
/*$drive_service = new Google_Service_Drive($client);
$files_list = $drive_service->files->listFiles(array())->getItems();
echo json_encode($files_list);*/
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->setTitle("test");
$file->setMimeType('application/vnd.google-apps.folder');
$createdFile = $service->files->insert($file, array(
'mimeType' => 'application/vnd.google-apps.folder',
'uploadType' => 'multipart'
));
echo "===".$fileId = $createdFile->id;
}
else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
and it is giving me insufficient permissions error.
Am i missing something?
I tried using Service account and it worked fine, Is Service account required to upload files using Google Drive API?
I have problem with downloading file from google drive using php api. I managed to upload file to google drive in folder and $service->files->insert returns to me File Resource which has attribute downloadUrl but when I redirect to that url, it does not work. I get 401 error. Why is this happening? What do I need to do make this work?
Here's code:
<?php
require_once 'vendor/autoload.php';
session_start();
$client_id = 'xxx';
$client_secret = 'yyy';
$redirect_uri = 'http://localhost/GoogleDrive/code.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
$authUrl = $client->createAuthUrl();
header("Location: $authUrl");
and code.php
require_once 'vendor/autoload.php';
session_start();
$client_id = 'xxx';
$client_secret = 'yyy';
$redirect_uri = 'http://localhost/GoogleDrivePayload/code.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setApprovalPrompt('force');
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['upload_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['upload_token']) && $_SESSION['upload_token']) {
$client->setAccessToken($_SESSION['upload_token']);
if ($client->isAccessTokenExpired()) {
unset($_SESSION['upload_token']);
}
}
if ($client->getAccessToken()) {
$file = new Google_Service_Drive_DriveFile();
$file->setTitle("hello.exe");
$file->setDescription("LALALALALAL");
$file->setMimeType('application/x-msdos-program');
$parent = new Google_Service_Drive_ParentReference();
$parent->setId("zzz");
$file->setParents(array($parent));
$data = file_get_contents('hello.exe');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'application/x-msdos-program',
'uploadType' => 'multipart',
"visibility" => "DEFAULT"
));
header("Location: " . $createdFile->downloadUrl);
}
downloadUrl is exactly what it says, ie. the URL your PHP app can use to fetch the file. You would almost never redirect a browser to that URL, and if you did (you probably really don't want to), you'll need append a valid access token to the URL to fix the 401.
I have applied file insertion code i.e to upload csv files to the google drive. All is working perfectly but I am getting duplicate files instead of getting one at a time. I have to upload two different files at a time but I am getting 4 files, need help in this case
This is google.php file where I have included "Google_Client.php","Google_DriveService.php" and file "insert.php" for the insertion in google drive which contain function insertFile($service, $title, $description, $parentId, $mimeType, $filename)
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'insert.php';
session_start();
$title = 'Total Likes/Reblogs';
$description = 'Total Likes/Reblogs';
$title1 = 'Total Likes/Reblogs per post';
$description1 = 'Total Likes/Reblogs per post';
$parentId = '';
$mimeType = 'text/csv';
$filename = 'total.csv';
$fileNamePerPost = 'totalPerPost.csv';
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$service = new Google_DriveService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
insertFile($service, $title, $description, $parentId, $mimeType, $filename);
insertFile($service, $title1, $description1, $parentId, $mimeType, $fileNamePerPost);
} else {
$state = mt_rand();
$client->setState($state);
echo $_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
Once OAuth 2.0 callback is handled, you need to stop executing. header(...) doesn't stop the script and inserts 2 files. Once the first execution is finished, redirection inserts the same files again.
I've nearly searched every result of the first page of google for this. But can't seem to find the answer. I'm working with a refresh_token by Google's API and receiving:
Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }
What i'm doing. First: i'm creating and storing a persistant connection to the google api:
$client = new Google_Client();
$client->setClientId('xxxxxx-s73q0pa41aq3i2kcpatmpas6e6kkp99h.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxx');
$client->setRedirectUri('http://xxxxxxxx/generaterefreshtoken.php');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->setAccessType('offline');
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if ($client->getAccessToken()) {
$jsonarray = json_decode($client->getAccessToken());
$arrGoogleAuth['access_token']=$jsonarray->access_token;
$arrGoogleAuth['refresh_token']=$jsonarray->refresh_token;
//filewrite
$myFile = "refreshtoken.conf";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $client->getAccessToken());
fclose($fh);
/*
die();
$service = new Google_DriveService($client);
$file = new Google_DriveFile();
$file->setTitle('My document.txt');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
*/
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
$auth = $client->createAuthUrl();
header("Location: $auth");
}
So basicly everything runs and the token gets stored in a textfile:
{
"access_token":"xxxxxxxxxxxxxxxN4U0ys2wy5monxs0Xh5fu5ayKL0OIENo-d1sN6g3YA",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token":"xxxxxxxxxxxxDON-l90BNUcJgnkfZWDfg",
"created":1358120143
}
When i'm trying to auth using the following code:
$client = new Google_Client();
$client->setClientId($googleDriveConfig['clientid']);
$client->setClientSecret($googleDriveConfig['clientsecret']);
$client->setRedirectUri(curPageURL);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->refreshToken(file_get_contents('../_config/refreshtoken.conf'));
$client->authenticate();
I'm getting the following error:
Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }
You'll get an "invalid_grant" error if you try to refresh when the token isn't expired.
Instead of this:
$client->refreshToken(file_get_contents('../_config/refreshtoken.conf'));
Use this:
$client->setAccessToken(file_get_contents('../_config/refreshtoken.conf'));
Once your token expires you refresh should work.
The invalid_grant means either means that the authorization code has already been used (available in $GET['code']) or the type of application configured in the Google APIs Console is invalid.
Make sure you select "Web Application" when registering your app in the Google APIs Console.
The function that worked for me is as follows
$client->setAccessType("refresh_token");
I ran into something similar and the problem for me was my system clock (inside the Docker VM where I was running the code) was not synchronized with the real time. So you are requesting a token with a created date too far in the past or future, which OAuth is rejecting.
I was tipped of by the report here.
Before Authenticate, there must be something like:
$client->grantType("refresh_token")