35371

Google API Oauth php permanent access

Question:

I am using the google Calendar API. This is what I want, once you give the app the permission, I can always use the app, without the need of giving access everyday. I keep hearing that I need to save the access token or use the refresh token to do what I want to do.. Here is the thing, how do you do it? How does the code look like? I've tried saving the token in a cookie, but after an hour, the access token has expired. How do I keep the user logged in?

PS: Please give me code examples with explanations.

Here is my code (using CakePHP):

$client = new Google_Client(); $client->setApplicationName("Wanda3.0 Agenda"); $cal = new Google_CalendarService($client); 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()) { /************* Code entry *************/ }else{ /************* Not connected to google calendar code *************/ $authUrl = $client->createAuthUrl(); $returnArr = array('status' => 'false', 'message' => "<a class='login' href='$authUrl'>Connect Me!</a>"); return $returnArr; }

Answer1:

Ok, after waiting for a few days, the suggestion from Terry Seidler(comments below) made it all happen! Here is my piece of code on how to automaticly refresh the access token without autenticating each time using cookies.

(NOTICE: It's safer to save the refresh token in your database)

This is the magic (using cookies):

$client = new Google_Client(); $client->setApplicationName("Wanda3.0 Agenda"); $cal = new Google_CalendarService($client); $client->setAccessType('offline'); if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']); } //Where the magic happends if (isset($_SESSION['token'])) { //Set the new access token after authentication $client->setAccessToken($_SESSION['token']); //json decode the session token and save it in a variable as object $sessionToken = json_decode($_SESSION['token']); //Save the refresh token (object->refresh_token) into a cookie called 'token' and make last for 1 month $this->Cookie->write('token', $sessionToken->refresh_token, false, '1 month'); } //Each time you need the access token, check if there is something saved in the cookie. //If $cookie is empty, you are requested to get a new acces and refresh token by authenticating. //If $cookie is not empty, you will tell the client to refresh the token for further use, // hence get a new acces token with the help of the refresh token without authenticating.. $cookie = $this->Cookie->read('token'); if(!empty($cookie)){ $client->refreshToken($this->Cookie->read('token')); }

And thats it! IF you have any questions, feel free to leave a comment below and I will answer the best I can. Goodluck and Cheers!

Answer2:

Instead of using cookies and sessions you should save it in the database and use it.

A similar implementation for drupal site is at Google OAuth2 sandbox at <a href="http://drupal.org/sandbox/sadashiv/1857254" rel="nofollow">http://drupal.org/sandbox/sadashiv/1857254</a> This module allows you to handle the authentication from admin interface of drupal. You can then use the fetched access token from google and then use the api function of google_oauth2_account_load or google_oauth2_client_get to get the Google_Client and carry your api call.

Answer3:

Much the same as hope industries but after testing I only wanted to refresh the token when I had to. Full source just change the keys etc at the top:

require_once 'google-api-php-client/src/Google_Client.php'; require_once 'google-api-php-client/src/contrib/Google_CalendarService.php'; session_start(); $client = new Google_Client(); $client->setApplicationName("Google Calendar PHP Starter Application"); // Visit https://code.google.com/apis/console?api=calendar to generate your // client id, client secret, and to register your redirect uri. $client->setClientId('your_id'); $client->setClientSecret('your_secret'); $client->setRedirectUri("http://localhost/your_redirect.php"); $client->setDeveloperKey('your_key'); $cal = new Google_CalendarService($client); if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . $query_string); } if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']);//update token //json decode the session token and save it in a variable as object $sessionToken = json_decode($_SESSION['token']); //Save the refresh token (object->refresh_token) into a cookie called 'token' and make last for 1 month if (isset($sessionToken->refresh_token)) { //refresh token is only set after a proper authorisation $number_of_days = 30 ; $date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ; setcookie('token', $sessionToken->refresh_token, $date_of_expiry); } } else if (isset($_COOKIE["token"])) {//if we don't have a session we will grab it from the cookie $client->refreshToken($_COOKIE["token"]);//update token } if ($client->getAccessToken()) { $calList = $cal->calendarList->listCalendarList(); print "

Calendar List

<pre>" . print_r($calList, true) . "</pre>"; $_SESSION['token'] = $client->getAccessToken(); } else { $authUrl = $client->createAuthUrl(); print "<a class='login' href='$authUrl'>Select a calendar!</a>"; }

Recommend

  • How to show a decimal corretly formatted in 0.00$ format?
  • SQL Server 2008 - separating Address field
  • how to set bug tracker url in setup.py script
  • How do you convert an aspx or master page file to page and code behind?
  • Link conversion in mod rewrite .htaccess
  • Array returning indexOf rather than count of pattern
  • Bootstrap 4: Stop collapse from pushing content down
  • Servlet interface is not a javax.servlet.Servlet
  • how to handle large size of update query in mysql with laravel
  • Forcing a context switch from the userland on Linux?
  • How to read data from socket connection - android
  • How to show a specific VC , more like navigate to a stack of VC
  • Error building image: Error building rlang - not available on R 3.5.0 (Uploading shiny)
  • Adding independent aspx/asmx pages into DotNetNuke
  • Accessing the variables from a PHP Anonymous Function
  • How to repeat sections of a SQL query across UNIONs? (DRY in SQL)
  • C++ cout and enum representations
  • Losing my session variables
  • Why can't UI components be accessed from a backgroundworker?
  • Problem with Django using Apache2 (mod_wsgi), Occassionally is “unable to import from module” for no
  • XSLT foreach repeating nodes to flat
  • how do i write assembly code from c#?
  • How to make R's read_csv2() recognise the text characters properly
  • How to access culture data in globalize.js V1.0.0
  • Dynamically switching connect in Modelica
  • nonblocking BIO_do_connect blocked when there is no internet connected
  • Redux Form - Not able to type anything in input
  • Jenkins: FATAL: Could not initialize class hudson.util.ProcessTree$UnixReflection
  • Date Conversion from yyyy-mm-dd to dd-mm-yyyy
  • Get history of file changes from TFS to implement custom “blame”-behaviour of exceptions
  • With Hadoop, can I create a tasktracker on a machine that isn't running a datanode?
  • print() is showing quotation marks in results
  • CSS Linear-gradient formatting issue accross different browsers
  • Matplotlib draw Spline from multiple points
  • Proper folder structure for lots of source files
  • -fvisibility=hidden not passed by compiler for Debug builds
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?