Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refresh token with google api client php

Tags:

php

google-api

My pain with google api continues...

I'm able to use a script to use a refresh token - automatically refresh and keep my access to a calender alive. I can interact with the calendar and all is good.

I now want to move on to using the google api client for php and I had this working yesterday whilst my token was valid but now this has expired I can't work out how to use the refresh token to get a new token and to keep authenticating once it expires in the future.

I've found a number of references and tried these - here's my test script so far based on the simple.php example:

<?php
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_CalendarService.php';
session_start();

$client = new Google_Client();
$client->setAccessType('offline');
$client->setApplicationName("Downs Golfmanager");


// Visit https://code.google.com/apis/console?api=calendar to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('XXXXXX.apps.googleusercontent.com');
$client->setClientSecret('XXXXXX');
$client->setRedirectUri('XXXXXX');
$client->setDeveloperKey('XXXXXX');
$client->refreshToken('X/XXXXX');


$client->setUseObjects(true);
$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->isAccessTokenExpired()) {
    /
    echo 'Access Token Expired'; // Debug
    //$client->refreshToken($refreshToken);
}

if ($client->getAccessToken()) {

    $event = new Google_Event();

    $event->setSummary('Appointment');
    $event->setLocation('Somewhere');

    $start = new Google_EventDateTime();
    $start->setDateTime('2013-08-28T14:00:00.000+01:00');
    $event->setStart($start);

    $end = new Google_EventDateTime();
    $end->setDateTime('2013-08-28T15:25:00.000+01:00');
    $event->setEnd($end);

    $createdEvent = $cal->events->insert('[email protected]', $event);

    //echo "<pre>" . print_r($createdEvent, true) . "</pre>";
    echo $createdEvent->getId();


    //test pulling events
    $events = $cal->events->listEvents('[email protected]');

    while(true) {
      foreach ($events->getItems() as $event) {
        echo $event->getSummary();
      }
      $pageToken = $events->getNextPageToken();
      if ($pageToken) {
        $optParams = array(
            'pageToken' => $pageToken,
            'timeMin'=>'2013-08-26T00:00:00+01:00',
            'timeMax'=>'2013-08-31T00:00:00+01:00'
            );
        $events = $cal->events->listEvents('[email protected]', $optParams);
      } else {
        break;
      }
    }
    //print "<h1>Events List</h1><pre>" . print_r($events, true) . "</pre>";



  $calList = $cal->calendarList->listCalendarList();
  print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>";


$_SESSION['token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
  print "<a class='login' href='$authUrl'>Connect Me!</a>";
}

As with my previous posts I'm not clear what should be going on here. My token has expired - I have the refresh token. what changes to my code do I need to automatically refresh authorisation each time I access.

Edit: The error code is: The OAuth 2.0 access token has expired, and a refresh token is not available

I've commented out a couple of additional lines above which I'd included in my attempts to solve just to try and avoid confusing further

Thank you

like image 571
Ray Avatar asked Aug 27 '13 08:08

Ray


People also ask

How can I get Google API access token in PHP?

To obtain this access token, we must redirect the user on a page hosted by Google so that the user can log on (to the Google site, not to our own) and authorize our application to access the desired service (Google Calendar in our example).

How do I use API refresh token?

To use the refresh token, make a POST request to the service's token endpoint with grant_type=refresh_token , and include the refresh token as well as the client credentials if required.

How do I refresh my authentication token?

To refresh your access token as well as an ID token, you send a token request with a grant_type of refresh_token . Be sure to include the openid scope when you want to refresh the ID token. If the refresh token is valid, then you get back a new access and the refresh token.


1 Answers

OK - Based on a couple of posts I've fixed the problem of getting the refresh token to get a new access token. I used this code before I started to attempt any access:

if($client->isAccessTokenExpired()) {
    echo 'Access Token Expired'; // Debug
    $client->refreshToken('X/XXXXXX');
}

Where the blanked out part in refreshToken is my refresh token. I hard coded the key into the code.

This is probably not the correct solution as I've seen references to storing the key in a database, so presumably I could store the current access token in a db with the refresh token and pull these form the db as and when required to save hard coding them?

Hopefully this method I've used will work again after it expires - fingers crossed!

like image 165
Ray Avatar answered Oct 22 '22 12:10

Ray