the following code runs through well, but some times reports "Invalid token". It happens, when I have foreign website in my ID list. But when I log in with email/password pair, it runs well till the end. Any idea what is wrong?
Cheers:
Bob
<?php
/*
API ACCESS PANEL:
https://code.google.com/apis/console/
*/
session_start(); #the includes are as follows, using also gapi.class.php
require_once 'src/apiClient.php';
require_once 'src/contrib/apiAnalyticsService.php';
ini_set('display_errors', '1');
$client = new apiClient();
$client->setApplicationName("Google Analytics PHP Starter Application");
/*
Visit https://code.google.com/apis/console?api=analytics to generate your client id, client secret, and to register your redirect uri.
*/
$client->setClientId('');# MUST SET UP!
$client->setClientSecret('');# MUST SET UP!
$client->setRedirectUri('http://localhost/analytics/chart_server.php');# MUST SET UP!
$client->setDeveloperKey('');# MUST SET UP!
// requestReportData first parameter, an Analytics Profil ID must defined here:
$ga_profile_id='';# MUST SET UP!
//////////////////////////////////////////////////////////////////////////////
$service = new apiAnalyticsService($client);
// logout
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
exit;
}
// get the tooken from Google, store into the session, call back this script with header-location
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
exit;
}
// if we got token in the session-ben, passing to $client (this is the OAuth client)
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// if the token valid, then we have access:
if ($client->getAccessToken()){
#$props = $service->management_webproperties->listManagementWebproperties("~all");
/*
print "Web Properties " . print_r($props, true);
*/
print("auth OK");//ok
print_r($client->getAccessToken()); // print out for test
$_SESSION['token'] = $client->getAccessToken();// stor eback to the session
} else { // Authorize with OAuth cause we have no valid access token
#https://www.google.com/analytics/feeds/
#https://www.googleapis.com/auth/analytics.readonly
$scope="https://www.google.com/analytics/feeds/"; // we'd like to access this
$authUrl = $client->createAuthUrl($scope);
header("Location: ".$authUrl); /* Redirect browser */
# print "<a class='login' href='$authUrl'>Connect Me!</a>";
exit;
}
// test printout, OAuth account object:
$accounts = $service->management_accounts->listManagementAccounts();
print "List of accounts" . print_r($accounts, true) .;
//////////////////////////////////////////////////////////////////////////////////////////////
// Here is the Google Analytics API call, and the "TOKEN INVALID 401" error message //
//////////////////////////////////////////////////////////////////////////////////////////////
require 'gapi.class.php';
$ga = new gapi(null,null,$_SESSION['token']); // access token instead of mail, password pair
#$token=$ga->getAuthToken();# $_SESSION['token']
// http://code.google.com/p/gapi-google-analytics-php-interface/wiki/GAPIDocumentation
// requestReportData($report_id, $dimensions, $metrics, $sort_metric=null, $filter=null, $start_date=null, $end_date=null, $start_index=1, $max_results=30)
$dimensions=array('browser','date');// x coord
$metrics=array('visits','pageLoadTime','uniquePageviews'); // y coord
$sort_metric="-date"; #descending order
$filter = '';
$startDate = '2012-04-01';
$endDate = '2012-04-12';
$start_index=1;
$max_results=50;
#$ga->requestReportData($accProfiles[$profileNum]->getProfileId(),$dimensions,$metrics,$sort_metric,$filter, $start_date, $end_date, $start_index, $max_results );
$ga->requestReportData($ga_profile_id, $dimensions, $metrics, $sort_metric, $filter, $startDate, $endDate, $start_index, $max_results );
$results=$ga->getResults();
// test:
echo "Google Analytics data ";print_r($results);
#echo "#####".$ga->getMetrics();
// Set the JSON header
//header("Content-type: text/json");
#echo json_encode( array($dim, $met1, $met2, $met3 ) );
?>
Just forget the gapi.class.php. It is slow, and works only with USR/PSW.
The apiAnalyticsService is also slow, but works with tokens well.
Try changing your scope from this:
$scope="https://www.google.com/analytics/feeds/";
to this:
$scope="https://www.googleapis.com/auth/analytics.readonly";
Related
<?php
session_start();
require_once realpath(dirname(__FILE__) . '/Google/src/Google/autoload.php');
/************************************************
ATTENTION: Fill in these values! Make sure
the redirect URI is to this page, e.g:
http://localhost:8080/user-example.php
************************************************/
$client_id = 'xxxxx-1l76cd2vi4ik5oqm5s20nj965riu4hum.apps.googleusercontent.com';
$client_secret = 'secret';
$redirect_uri = 'http://www.audit.polydevs.co.uk/oauth2callback.php?login';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes('email');
/************************************************
If we're logging out we just need to clear our
local access token in this case
************************************************/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
header("Location: login.php");
}
if (isset($_REQUEST['logoutInvalid'])) {
unset($_SESSION['access_token']);
header("Location: login.php?invalid");
}
/************************************************
If we have a code back from the OAuth 2.0 flow,
we need to exchange that with the authenticate()
function. We store the resultant access token
bundle in the session, and redirect to ourself.
************************************************/
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
/************************************************
If we have an access token, we can make
requests, else we generate an authentication URL.
************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
/************************************************
If we're signed in we can go ahead and retrieve
the ID token, which is part of the bundle of
data that is exchange in the authenticate step
- we only need to do a network call if we have
to retrieve the Google certificate to verify it,
and that can be cached.
************************************************/
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
$token_data = $client->verifyIdToken()->getAttributes();
}
if($client->isAccessTokenExpired()) {
echo 'Access Token Expired'; // Debug
$client->authenticate;
$newAccessToken = json_decode($client->getAccessToken());
$client->refreshToken($newAccessToken->refresh_token);
}
if (strpos($client_id, "googleusercontent") == false) {
echo missingClientSecretsWarning();
exit;
}
if (isset($_REQUEST['login'])) {
if (isset($authUrl)) {
header('Location:'.$authUrl);
} else {
require_once('func/connect.php');
$query = "SELECT * FROM users WHERE email = ?";
$stmt = $db->prepare($query);
$stmt->bindValue(1, $token_data['payload']['email']);
$stmt->execute();
$count = $stmt->rowCount();
if ($count > 0) {
header('Location: index.php');
} else {
$plus = new Google_Service_Plus( $client );
$me = $plus->people->get('me');
$query = "INSERT INTO users (name,email,role) VALUES(?,?,?)";
$stmt = $db->prepare($query);
$stmt->bindValue(1, $me['displayName']);
$stmt->bindValue(2, $token_data['payload']['email']);
$stmt->bindValue(3, 'regular');
$stmt->execute();
header('Location: index.php');
}
}
}
Specifically here
if($client->isAccessTokenExpired()) {
echo 'Access Token Expired'; // Debug
$client->authenticate;
$newAccessToken = json_decode($client->getAccessToken());
$client->refreshToken($newAccessToken->refresh_token);
}
Once my token expires, I cannot logout nor access any of the webpages as they require to have a valid token..
nor can i login, as that requires it too!
Or alternatively, can I just disable it!
EDIT
I'm very sorry, I'm tired and assuming everyone knows what I'm talking about.. The issue is that when the access token expires, I can either unset the $_SESSION['access_token'] and force relogging in ( major problem ) or have a way of just refreshing / disabling the token/expire so it won't impede on any ongoing processes for the user.
I would recommend reading a basic guide about OAuth so you can get the general idea.
Basically the server and the client go through a series of steps to prove that they are who they say they are. Once this has been completed the server will issue a short lived access_token and a refresh_token.
You can then use this access_token in all Api requests. However this access_token has a limited lifetime. When it expires you must give the refresh_token to the server and it will issue another access_token
To do this with the Google Api PHP library you use this code
//$client is the GApi Client
if($client->isAccessTokenExpired()) {
echo 'Access Token Expired'; // Debug
$client->refreshToken('your_refresh_token');
}
Using code below I successfully received a token and using this token also get user detail, but when I try to post/insert moment in user wall I see the following error message
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https:--www.googleapis.com/plus/v1/people/me/moments/vault: (401) Unauthorized' in $_SESSION['access_token_gp']
I got user token when user login using my site in login page I ask for below permission
$client->addScope("email");
$client->addScope("https://www.googleapis.com/auth/plus.stream.write");
$client->addScope("https://www.googleapis.com/auth/plus.login");
If I print_r($tokenInfo); you will see all scope which I ask at login time.
The full code:
session_start();
require_once realpath(dirname(__FILE__) . '/google-api-php-client-master/autoload.php');
$client_id = 'my_client_id';
$client_secret = 'my_secret_key';
$redirect_uri = 'my_redirect_url';
// code to post in google plus start here //
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
if (isset($_SESSION['access_token_gp'])) {
// Verify the token
$token = json_decode($_SESSION['access_token_gp']);
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.$token->access_token;
$req = new Google_Http_Request($reqUrl);
$tokenInfo = get_object_vars(json_decode($client->getAuth()->authenticatedRequest($req)->getResponseBody()));
if($tokenInfo['expires_in'] <= 0){
$client->authenticate($_SESSION['access_token_gp']);
$_SESSION['access_token_gp'] = $client->getAccessToken();
} else {
$client->setAccessToken($_SESSION['access_token_gp']);
}
$plusservicemoment = new Google_Service_Plus_Moment();
$plusservicemoment->setType("http://schemas.google.com/AddActivity");
$plusService = new Google_Service_Plus($client);
$item_scope = new Google_Service_Plus_ItemScope();
$item_scope->setId($tokenInfo['user_id']);
$item_scope->setType("http://schemas.google.com/AddActivity");
$item_scope->setName("The madexme Platform");
$item_scope->setDescription("A page that describes just how madexme is work!");
//$item_scope->setImage("full image path here");
$plusservicemoment->setTarget($item_scope);
$result = $plusService->moments->insert('me','vault',$plusservicemoment);
//print_r($result);
}
// code to post in google plus end here //
Make sure you have the latest client lib from GitHub. There is something wrong with your Oauth2 connection. This code is partially converted from my Google Google Calendar API tutorial. I don't have the power to test it right now. But this should be close. I will test it tonight.
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Plus.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("AIzaSyBBH88dIQPjcl5nIG-n1mmuQ12J7HThDBE");
$client->setClientId('2046123799103-i6cjd1hkjntu5bkdkjj5cdnpcu4iju8p.apps.googleusercontent.com');
$client->setClientSecret('6s4YOx3upyJhtwnetovfK40e');
$client->setRedirectUri('http://localhost/google-api-php-client-samples/Calendar/oauth2Pure.php');
$client->setAccessType('offline'); // Gets us our refreshtoken
$client->setScopes(array(https://www.googleapis.com/auth/plus.login'));
//For loging out.
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$service = new Google_Service_Plus($client);
$moment = new Google_Moment();
$moment->setType('http://schemas.google.com/AddActivity');
$itemScope = new Google_ItemScope();
$itemScope->setUrl('https://developers.google.com/+/plugins/snippet/examples/thing');
$moment->setTarget($itemScope);
$plus->moments->insert('me', 'vault', $moment);
?>
Again I hope you understand that this is not going to show up on the users Google+ page / timeline.
I'm want to get google+ posts via PHP, but google requires my login via browser.
It's possible provide the account's authentication via PHP, allowing me to get the posts without login every time I want to get the posts?
The code is:
<?php
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_PlusService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('clientid');
$client->setClientSecret('clientsecret');
$client->setRedirectUri('http://localhost/OLA/google+/simple.php/b.html');
$client->setDeveloperKey('apikey');
$plus = new Google_PlusService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) { // login stuff <-------
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die("The session state did not match.");
}
$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 ($client->getAccessToken()) {
//$me = $plus->people->get('me');
//print "Your Profile: <pre>" . print_r($me, true) . "</pre>";
$params = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $params);
//print "Your Activities: <pre>" . print_r($activities, true) . "</pre>";
$params = array(
'orderBy' => 'recent',
'maxResults' => '20'//20
);
$q = "tag";
$results = $plus->activities->search($q, $params);
//code ....
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
// This is the part that logs me in via browser <------
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
Yep, just call as you would and use the simple API access key - you can retrieve public information, but you will have to supply to long numeric ID for the user you're retrieving posts for rather than using the string 'me'. Take a look at the latest version of the library as well: https://github.com/google/google-api-php-client as well. You need to setup your client as you were doing, with an API key from a project which has the Google+ enabled on https://developers.google.com/console
$client = new Google_Client();
$client->setApplicationName("Post Fetcher");
$client->setDeveloperKey('PUT_YOUR_API_KEY_HERE_OR_IT_WONT_WORK');
$plus = new Google_Service_Plus($client);
$activities = $this->plus->activities
->listActivities("118051310819094153327", "public");
I'm currently working with the Google Calendar API.
I retrieve a list of EVENTS from the user's calendar, but at the moment the account of the user is given in my code.
I wan't to make this variable (It should retrieve EVENTS from the account you select).
This is my code:
<?php
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_CalendarService.php';
$client = new Google_Client();
$client->setApplicationName('Tryout for Google Calendar');
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('myid');
$client->setClientSecret('mysecret');
$client->setRedirectUri('http://localhost/gcal/done.php');
$client->setDeveloperKey('mykey');
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$minCheck = date(DATE_ATOM);
$eventList = $cal->events->listEvents("phpkay#gmail.com", array('singleEvents' => 'true', 'timeMin' => $minCheck));
print "<h1>Calendar List</h1><pre>" . print_r($eventList, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
This is the part where I set the useraccount, namely: "phpkay#gmail.com"
$eventList = $cal->events->listEvents("phpkay#gmail.com", array('singleEvents' => 'true', 'timeMin' => $minCheck));
How can I retrieve the selected useraccount (the user gets a screen where he can select one of the Google accounts he owns to use for this APP) and use this instead of the set "phpkay#gmail.com"-account?
Sorry if my question is unclear, I have no clue how to phrase this in another way.
You can do this with the OAuth 2.0 API. Just include:
https://developers.google.com/admin-sdk/directory/v1/reference/users
in your list of OAuth scopes and then make an authenticated GET request to:
https://www.googleapis.com/oauth2/v2/userinfo
this will return the email address of the authenticated user. You can try this out in the Google API Explorer
I followed again THIS TUTORIAL to upload a file on Google Drive with php, directly from my REMOTE SERVER: so I have created new API Project from Google API Console, enabled Drive API service, requested OAuth Client ID and Client Secret, wrote them in a script, then upload it together with Google APIs Client Library for PHP folder to this http://www.MYSERVER.com/script1.php, to retrieve Auth code:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('XXX'); // HERE I WRITE MY Client ID
$drive->setClientSecret('XXX'); // HERE I WRITE MY Client Secret
$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);
?>
When I visit http://www.MYSERVER.com/script1.php I allow authorization and get the Auth code that I can write in a second script. Then I upload it to http://www.MYSERVER.com/script2.php, who looks like:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('X'); // HERE I WRITE MY Client ID
$drive->setClientSecret('X'); // HERE I WRITE MY Client Secret
$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']= 'X/XXX'; // HERE I WRITE AUTH CODE RETRIEVED AFTER RUNNING REMOTE script.php
file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test Drive');
$doc->setDescription('Document');
$doc->setMimeType('text/plain');
$content = file_get_contents('drive.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
?>
Well, now the file drive.txt is uploaded on my Google Drive and structure of token.json file is a sort of:
{"access_token":"XXX","token_type":"Bearer","expires_in":3600,"refresh_token":"YYY","created":1365505148}
Now, as you can imagine I can call script2.php and upload file until a certain time. Finally, the point is: I don't want the token to expire, I don't want to allow authorization each time it expire (recalling script1.php): I need to call the script2.php periodically during the day, to upload my file automatically, without user interaction. So, what's the best way to automatically refresh the token forever in this context? Do I need another script? Can I add some code to script2.php? or modify the token.json file? And where can I read the time remaining before the token expire? Thanks!
You don't have to periodically ask for an access token. If you have a refresh_token, PHP client will automatically acquire a new access token for you.
In order to retrieve an refresh_token, you need to set access_type to "offline" and ask for offline access permissions:
$drive->setAccessType('offline');
Once you get a code,
$_GET['code']= 'X/XXX';
$drive->authenticate();
// persist refresh token encrypted
$refreshToken = $drive->getAccessToken()["refreshToken"];
For future requests, make sure that refreshed token is always set:
$tokens = $drive->getAccessToken();
$tokens["refreshToken"] = $refreshToken;
$drive->setAccessToken(tokens);
If you want a force access token refresh, you can do it by calling refreshToken:
$drive->refreshToken($refreshToken);
Beware, refresh_token will be returned only on the first $drive->authenticate(), you need to permanently store it. In order to get a new refresh_token, you need to revoke your existing token and start auth process again.
Offline access is explained in detail on Google's OAuth 2.0 documentation.
After messing a lot I got this to work. I am using one file/script to get the offline token and then a class to do stuff with the api:
require_once 'src/Google/autoload.php'; // load library
session_start();
$client = new Google_Client();
// Get your credentials from the console
$client->setApplicationName("Get Token");
$client->setClientId('...');
$client->setClientSecret('...');
$client->setRedirectUri('...'); // self redirect
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
$client->setAccessType("offline");
$client->setApprovalPrompt('force');
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$client->getAccessToken(["refreshToken"]);
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
return;
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
?>
<!doctype html>
<html>
<head><meta charset="utf-8"></head>
<body>
<header><h1>Get Token</h1></header>
<?php
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
$token = json_decode($_SESSION['token']);
echo "Access Token = " . $token->access_token . '<br/>';
echo "Refresh Token = " . $token->refresh_token . '<br/>';
echo "Token type = " . $token->token_type . '<br/>';
echo "Expires in = " . $token->expires_in . '<br/>';
echo "Created = " . $token->created . '<br/>';
echo "<a class='logout' href='?logout'>Logout</a>";
file_put_contents("token.txt",$token->refresh_token); // saving access token to file for future use
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
</body>
</html>
You can load refresh token from file and use it as necessary for offline access:
class gdrive{
function __construct(){
require_once 'src/Google/autoload.php';
$this->client = new Google_Client();
}
function initialize(){
echo "initializing class\n";
$client = $this->client;
// credentials from google console
$client->setClientId('...');
$client->setClientSecret('...');
$client->setRedirectUri('...');
$refreshToken = file_get_contents(__DIR__ . "/token.txt"); // load previously saved token
$client->refreshToken($refreshToken);
$tokens = $client->getAccessToken();
$client->setAccessToken($tokens);
$this->doSomething(); // go do something with the api
}
}
More here: https://github.com/yannisg/Google-Drive-Uploader-PHP