refreshToken() not working in google-api-php-client - php

Am using PHP client library provided by Google. Also using web applications in Google API console. When i try to refresh my token its return "Google_AuthException' with message 'Error refreshing the OAuth2 token, message: '{
"error" : "invalid_grant" " .Please Help me how refresh my token
This in My Sample code
ini_set("memory_limit", -1);
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$client->setClientId('XXXXXXXXXXX');
$client->setClientSecret('XXXXXXXXXX');
$client->setRedirectUri('http://localhost:1134/Google%20APIs/index.php');
$client->setAccessType("offline");
$client->setApprovalPrompt("force");
$SCOPES = array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile');
$client->setScopes($SCOPES);
$drive = new Google_DriveService($client);
$token ='{"access_token":"XXXXXXXX","token_type":"Bearer","expires_in":3600,"id_token":"XXXXXXXXXXXXXXXXXXXXXXX","refresh_token":"XXX","created":1396703189}';
$client->setAccessToken($token);
if ($client->isAccessTokenExpired()) {
$client->refreshToken("1\/ccccccxxxxx");
}
if ($client->getAccessToken()) {
$user = $client->about;
$ret = retrieveAllFiles($drive);
//var_dump($ret);
} else {
$authUrl = $client->createAuthUrl();
}
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files['items']);
$pageToken = $files['nextPageToken'];
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}

Related

PHP / GMail API

I have been trying to use PHP coding for accessing my Gmail, following the documentation here: https://developers.google.com/gmail/api/quickstart/php
This worked well until this evening when I started back on it. I now get the following error:
Fatal error: Uncaught LogicException: refresh token must be passed in
or set as part of setAccessToken in
C:\Users\mcgranj\Dropbox\eBay_web\google\vendor\google\apiclient\src\Google\Client.php:258
Stack trace: #0
C:\Users\mcgranj\Dropbox\eBay_web\google\quickstart.php(71):
Google_Client->fetchAccessTokenWithRefreshToken(NULL) #1
C:\Users\mcgranj\Dropbox\eBay_web\google\quickstart.php(118):
getClient() #2 {main} thrown in
C:\Users\mcgranj\Dropbox\eBay_web\google\vendor\google\apiclient\src\Google\Client.php
on line 258
I have been troubleshooting it all night, following every suggestion I could find:
Google API Client "refresh token must be passed in or set as part of setAccessToken"
Google API PHP Refresh Token returns NULL
Google api refresh_token null and how to refresh access token
But I am still having that problem, and it is using the quick start PHP code. I am so frustrated by this. Any guidance and/or suggestions are welcome.
Here is my PHP code:
<?php
require_once __DIR__ . '/vendor/autoload.php';
date_default_timezone_set('America/Chicago');
ini_set('max_execution_time', 0); //indefinite
ini_set('memory_limit','256M'); //increase PHP memory
ini_set('display_errors', 10);
define('APPLICATION_NAME', 'Gmail API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/gmail-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
Google_Service_Gmail::GMAIL_READONLY)
));
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$newAccessToken = $client->getAccessToken();
$accessToken = array_merge($accessToken, $newAccessToken);
file_put_contents($credentialsPath, json_encode($accessToken));
}
return $client;
}
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
$client = getClient();
$service = new Google_Service_Gmail($client);
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
function listMessages($service, $user) {
$pageToken = NULL;
$messages = array();
$opt_param = array();
do {
try {
if ($pageToken) {
$opt_param['pageToken'] = $pageToken;
}
$opt_param['maxResults'] = 5; //Return only 5 messages
$opt_param['labelIds'] = 'INBOX';
$opt_param['q'] = "after:2017/07/08 FROM:shipment-tracking#amazon.com";
$messagesResponse = $service->users_messages->listUsersMessages($user, $opt_param);
if ($messagesResponse->getMessages()) {
$messages = array_merge($messages, $messagesResponse->getMessages());
$pageToken = $messagesResponse->getNextPageToken();
}
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
} while ($pageToken);
foreach ($messages as $message) {
print 'Message with ID: ' . $message->getId() . '<br/>';
$id = $message->getId();
echo "<pre>"; print_r($message); echo "</pre>";
$gmailurl = "https://www.googleapis.com/gmail/v1/users/".$user."/messages/".$id;
echo "<a href='$gmailurl' target='_blank'>".$gmailurl."</a><p>";
$messagePayload = $message->getPayload();
}
return $messages;
}
listMessages($service, $user);
?>
Based from this thread, make sure that you have called json_encode before writing the auth result to the token.json file. You can fix it by adding json_encode like: file_put_contents($credentialsPath, json_encode($accessToken));. Also, this page suggested to add $client->setAccessType('offline'); and include force prompt to return the refresh token: $client->setApprovalPrompt('force');.

php server google drive download file in background

I need form PHP level, in background without user interaction login on google drive and get files list. I found similar topic and code for question working, but is required handly login, where I need login from php in background.
In second post with code for possibly login witout user interaction, but I don't know where is bug.
My code PHP:
<?php
require_once 'vendor/autoload.php';
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_DriveService.php';
require_once 'src/auth/Google_AssertionCredentials.php';
$client_email = 'xxxxxx#xxxxxxxxxxxxx.xxx.gserviceaccount.com';
$private_key = file_get_contents('key.p12');
$user_to_impersonate = 'xxxxxxxxxxxxxxx#gmail.com';
$scopes = array('https://www.googleapis.com/auth/drive');
$credentials = new Google_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
$user_to_impersonate
);
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service = new Google_Service_Drive($client);
$files = $service->files->listFiles();
echo "count files=".count($files)."<br>";
foreach( $files as $item ) {
echo "title=".$item['title']."<br>";
}
?>
Vendor directory I get from this instruction, and other files I get from this GitHub
I had problem with function Google_Auth_AssertionCredentials, PHP hasn't file with this function. I found that file src/auth/Google_AssertionCredentials.php has similar function Google_AssertionCredentials. I included Google_AssertionCredentials.php file and changed function name.
In finally I have new error:
PHP Fatal error: Cannot call constructor in
\google_drive\vendor\google\apiclient-services\src\Google\Service\Drive.php
on line 75
I don't know what doing again. I tried many other metod for login on google drive, eg. load file list GET method with API_KEY, or via json file.
As result I want get file list, download them. edit and upload.
Any sugestions?
EDIT:
I have part sucess. I found liblary this, and them work with this code:
<?php
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
session_start();
require_once '/google-api-php-client/autoload.php';
$client_email = 'xxxx#xxxxx.iam.gserviceaccount.com';
$user_to_impersonate = 'xxxxxx#gmail.com';
$private_key = file_get_contents('key.p12');
$scopes = array('https://www.googleapis.com/auth/drive');
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer',
$user_to_impersonate
);
$client = new Google_Client();
if(isset($_SESSION['service_token'])==false && $_SESSION['service_token']=='') {
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($credentials);
}
$_SESSION['service_token'] = $client->getAccessToken();
}
if(isset($_SESSION['service_token']) && $_SESSION['service_token']) {
$client->setAccessToken($_SESSION['service_token']);
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
$_SESSION['service_token'] = $client->getAccessToken();
}
$service = new Google_Service_Drive($client);
print_r(retrieveAllFiles($service));
}
?>
And in result I have only one file [originalFilename] => Getting started, this is PDF, but I don't see this file on Gogle dirve. On google drive I uploaded file: README.md.
I'm not sure, but maybe this file is on ` 'xxxx#xxxxx.iam.gserviceaccount.com' and script not logged to 'xxxxxx#gmail.com'?

Can't get list of files from google drive using php

I am working with google drive API with PHP. Basically i create a auth credentials and stuck at a point where i want to list of google drive files. Here is my code which i try.
<?php
require_once realpath(dirname(__FILE__) . '/gac/src/Google/autoload.php');
$client = new Google_Client();
session_start();
$client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://www.my-website-name.com/drive_test');
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
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);
echo "<pre>";
$all_files = "";
$all_files = retrieveAllFiles($service);
print_r($all_files);
die;
} else {
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit();
}
/**
* Retrieve a list of File resources.
*
* #param Google_Service_Drive $service Drive API service instance.
* #return Array List of Google_Service_Drive_DriveFile resources.
*/
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
?>
I am getting output like this.
Array
(
)
Please help me to solve this issue. Thank you.
Oh yes, finally i found the issue and fix it. It's a permission issue. I just replace this code
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
With new code
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
and everythig

Google Tasks - insert task from webpage

I'm trying to add a new task from my website to the Google Tasks. I checked the Google Tasks Api docs, and this is the code what I figured out:
<?php
session_start();
require_once 'google-api-php-client-master/autoload.php';
//Google credentials
$client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
$service_account_name = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.gserviceaccount.com';
$key_file_location = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.p12';
if (!strlen($service_account_name) || !strlen($key_file_location))
echo missingServiceAccountDetailsWarning();
$client = new Google_Client();
$client->setApplicationName("Whatever the name of your app is");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/tasks'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
try {
$client->getAuth()->refreshTokenWithAssertion($cred);
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
$_SESSION['service_token'] = $client->getAccessToken();
// Set task data
$task = new Task();
$task->setTitle('New Task');
$task->setNotes('Please complete me');
$task->setDue(new TaskDateTime('2015-02-26T12:00:00.000Z'));
$result = $service->insertTasks('#default', $task);
echo $result->getId();
?>
It says me "Fatal error: Class 'Task' not found in /customers/1/b/5/xxxxxxx.xx/httpd.www/test2/test2.php on line 34".
What do I do wrong? And what else should I do to get this code work?
The doc is for stable api. If you are using master version, it has to be like this:
$task = new Google_Service_Tasks_Task();
$task->setTitle('New Task');
$task->setNotes('Please complete me');
$task->setDue(new TaskDateTime('2015-02-26T12:00:00.000Z'));
$result = $service->tasks->insert('#default', $task);
echo $result->getId();

Listing all files from Google Drive

I would like to list all the files from my Google drive to my "DriveFiles.php" file where I can display the files and its details. I am a beginner so a complete code will be helpful. Thanks.
My code:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
require_once 'google-api-php-client/src/io/Google_HttpRequest.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
// initialize a client with application credentials and required scopes.
$client = new Google_Client();
$client->setClientId('CLIENT_ID');
$client->setClientSecret('CLIENT_SECRET');
$client->setRedirectUri('REDIRECT_URI');
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setUseObjects(true);
if (isset($_GET['code']))
{
session_start();
print_r($_SESSION);
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$client->setAccessToken($_SESSION['token']);
// initialize the drive service with the client.
$services = new Google_DriveService($client);
retrieveAllFiles($services);
}
if(!$client->getAccessToken()){
$authUrl = $client->createAuthUrl();
echo '<a class="login" href="'.$authUrl.'">Login</a>';
}
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
?>
When I execute the code I get the following error:
Fatal error: Uncaught exception 'Google_Exception' with message 'Cant
add services after having authenticated' in
D:\GT_local\Public\google-api-php-client\src\Google_Client.php:115
Stack trace: #0
D:\GT_local\Public\google-api-php-client\src\contrib\Google_DriveService.php(1258):
Google_Client->addService('drive', 'v2') #1
D:\GT_local\Public\quickstart.php(55):
Google_DriveService->__construct(Object(Google_Client)) #2 {main}
thrown in
"FILE_LOCATION(C://google-api-php-client\src\Google_Client.php on line
115)"
How can I fix this.
Try starting the session in the top of the script, and try to do all authentication before you have to do any operation. Also use the most recent API so you can use this libraries:
require_once '/src/Google/autoload.php';
require_once '/src/Google/Client.php';
require_once '/src/Google/Service/Oauth2.php';
require_once '/src/Google/Service/Drive.php';

Categories