Listing all files from Google Drive - php

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';

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');.

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

I couldn't connect to Google calender api using v3 php client library

I couldn't connect able to display events,insert events by using php client library.
This is the error i got.
I am using v3 version of client library
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/calendar/v3/calendars/primary?key=****************: (401) Login Required' in /var/www/html/google-api-php-client1/src/Google/Http/REST.php:79
Stack trace:
#0 /var/www/html/google-api-php-client1/src/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 /var/www/html/google-api-php-client1/src/Google/Client.php(503): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /var/www/html/google-api-php-client1/src/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 /var/www/html/google-api-php-client1/src/Google/Service/Calendar.php(1269): Google_Service_Resource->call('get', Array, 'Google_Service_...')
#4 /var/www/html/simple.php(27): Google_Service_Calendar_Calendars_Resource->get('primary') #5 {main} thrown in /var/www/html/google-api-php-client1/src/Google/Http/REST.php on line 79
since you are getting 401 login required error so you need to set setAccessToken.visit here Error with Google Calendar API - 401 Login required when adding a calendar event
may be you need to issue refreshToken() using the original authenticated access code that contains a refresh token.
// example
$google_client->refreshToken($token->refresh_token);
and use 'setDeveloperKey'. it works.you can see this:https://code.google.com/p/google-api-php-client/issues/detail?id=218
Finally solved problem.
This is the perfect example to get list of events of calender.
<?php
// ...
ini_set('display_errors', 1);
error_reporting(E_ALL);
set_include_path('google-api-php-client1/src');
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
//
$client = new Google_Client();
//print_r($client);exit;
//$client->setUseObjects(true);
$client->setApplicationName("your-app-name");
$client->setClientId("CLIENT id");
$client->setClientSecret('CLIENT SECRET');
$client->setDeveloperKey('DEVELOPER KEY');
$client->setRedirectUri('your url mostly localhost');
$client->setScopes(array(
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly',
));
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
//print_r($_SESSION['token']);exit;
//header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
if (isset($_SESSION['token'])) {
//echo 'innn';exit;
$client->setAccessToken($_SESSION['token']);
//echo 'innn';exit;
}
}
if ($client->getAccessToken()) {
//echo 'innn';exit;
$service = new Google_Service_Calendar($client);
//echo '<pre>'; print_r($service);exit;
//$calendar = $service->calendars->get('primary');
//echo $calendar->getSummary();
$events = $service->events->listEvents('primary');
while(true) {
foreach ($events->getItems() as $event) {
echo $event->getSummary();
}
$pageToken = $events->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$events = $service->events->listEvents('primary', $optParams);
} else {
break;
}
}
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
Script to add event.
Actual problem is Google Calendar version 3 not matching with its documentation.
So I checked Calender.php for all available classes.
$event = new Google_Service_Calendar_Event();
$event->setSummary('Interview');
$event->setLocation('Hell');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2014-09-04T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2014-09-04T11:00:00.000-07:00');
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail('email#abc.com');
// ...
$attendees = array($attendee1,
// ...
);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('primary', $event);
echo $createdEvent->getId();

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

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;
}

Google Admin SDK in PHP

I am using the following code to retrieve the list of users associated with my google apps account.
There is no problem with authentication but when the redirection made this error is appearing.
index.php
<?php
require_once 'test_user/src/Google_Client.php';
require_once 'test_user/src/contrib/Google_PlusService.php';
require_once 'test_user/src/contrib/Google_Oauth2Service.php';
require_once 'test_user/src/contrib/Google_DirectoryService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("ApplicationName");
//*********** Replace with Your API Credentials **************
$client->setClientId('****');
$client->setClientSecret('****');
$client->setRedirectUri('****');
$client->setDeveloperKey('****');
//************************************************************
$client->setScopes(array('https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/admin.directory.user.readonly'));
$plus = new Google_PlusService($client);
$oauth2 = new Google_Oauth2Service($client); // Call the OAuth2 class for get email address
$adminService = new Google_DirectoryService($client); // Call directory API
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_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())
{
$user = $oauth2->userinfo->get();
$me = $plus->people->get('me');
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
//$users = $adminService->users->get($email);
$list_users = $adminService->users->listUsers();
print '<h2>Response Result:</h2><pre>' . print_r($list_users, true) . '</pre>';
$_SESSION['access_token'] = $client->getAccessToken();
}
else
{
$authUrl = $client->createAuthUrl();
header("location:$authUrl");
}
?>
error i'm getting:
Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling
GET https://www.googleapis.com/admin/directory/v1/users?
key=AIzaSyBp0yBFCCosu113tbNbw7yAIjIt1ndFFIs: (400) Bad Request' in
/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php:66 Stack trace: #0
/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php(36):
Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1
/var/www/vhosts/vx44.com/httpdocs/test_user/src/service/Google_ServiceResource.php(186):
Google_REST::execute(Object(Google_HttpRequest)) #2
/var/www/vhosts/vx44.com/httpdocs/test_user/src/contrib/Google_DirectoryService.php(695):
Google_ServiceResource->__call('list', Array) #3
/var/www/vhosts/vx44.com/httpdocs/test_user/test_user.php(52):
Google_UsersServiceResource->listUsers('nelson302.com') #4 {main} thrown in/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php on line 66
Note that i've enabled Admin SDK on Google APIs Console.
What am i doing wrong here? thank you for helping
Try replacing:
$list_users = $adminService->users->listUsers();
with:
$adminOptParams = array('customer' => 'my_customer');
$list_users = $adminService->users->listUsers($adminOptParams);
this is explained in the Admin SDK Developer's Guide.

Categories