using a refresh token to create a new access token, then post new event into calendar

4,489 views
Skip to first unread message

Craig R

unread,
Nov 27, 2014, 10:55:58 AM11/27/14
to google-ca...@googlegroups.com
I have been working through the docs, and so far, I have managed to add a new event to my calendar, using my authorization credentials from the Google Developers Console and the code snippet here


<?php


$client
= new Google_Client();
// OAuth2 client ID and secret can be found in the Google Developers Console.
$client
->setClientId('xxxxx.apps.googleusercontent.com');
$client
->setClientSecret(xxxxx);
$client
->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client
->addScope('https://www.googleapis.com/auth/calendar');
$client
->setAccessType('offline');
$client
->setApprovalPrompt('force');


$service
= new Google_Service_Calendar($client);


$authUrl
= $client->createAuthUrl();


//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";


//$authCode = trim(fgets(STDIN));
$authCode
= '';


// Exchange authorization code for access token
$accessToken
= $client->authenticate($authCode);


$client
->setAccessToken($accessToken);


$event
= new Google_Service_Calendar_Event();
$event
->setSummary('Appointment);
$event->setLocation('
Somewhere');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('
2014-12-22T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('
2014-12-22T10:00:00.000-08:00');
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail(x...@gmail.com'
);
// ...
$attendees
= array($attendee1);
$event
->attendees = $attendees;
$createdEvent
= $service->events->insert('xx...@group.calendar.google.com', $event);


echo $createdEvent
->getId();




?>


This works, but I need to get a new OAuth2.0 access token every time.
 What I want to do is use a refresh token to automatically generate a new access token, so I can add new gcal events from my web page

If I run the following code, I can successfully regenerate a new access token using the refresh token

<?php


function getAccessToken(){
    $tokenURL
= 'https://accounts.google.com/o/oauth2/token';
    $postData
= array(
       
'client_secret'=>'xxxxx',
       
'grant_type'=>'refresh_token',
       
'refresh_token'=>'xxxxx',
       
'client_id'=>'xxxx.apps.googleusercontent.com'
   
);
 
    $ch
= curl_init();
    curl_setopt
($ch, CURLOPT_URL, $tokenURL);
 curl_setopt
($ch, CURLOPT_SSL_VERIFYPEER, false);//need this otherwise you get an ssl error
    curl_setopt
($ch, CURLOPT_POST, 1);
    curl_setopt
($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt
($ch, CURLOPT_RETURNTRANSFER, true);
    $tokenReturn
= curl_exec($ch);
    $token
= json_decode($tokenReturn);
   
//var_dump($tokenReturn);
    $accessToken
= $token->access_token;
 
   
return ($accessToken);
}
?>


This always gives me a new access token, but if I put this token into the code at the top of the page, I get an error.
Google_Auth_Exception' with message 'The OAuth 2.0 access token has expired, and a refresh token is not available

I have tried returning the access token only, the return value, the json decoded return value, but I always get an error of some sort

Can anyone point me in the right direction, or to a code snippet which will allow me to insert a new event into my calendar ? 

Thanks

Lucia Fedorova

unread,
Dec 1, 2014, 5:50:35 PM12/1/14
to google-ca...@googlegroups.com
Hi Craig,
have you tried using $client->refreshToken($refreshToken) to obtain the refresh token?
');
$attendee1->setEmail(xxx@gmail.com');

// ...
$attendees
= array($attendee1);
$event
->attendees = $attendees;

$createdEvent
= $service->events->insert('xxxxx...@group.calendar.google.com', $event);


echo $createdEvent
->getId();




?>

Craig R

unread,
Dec 2, 2014, 6:36:33 AM12/2/14
to google-ca...@googlegroups.com


On Monday, 1 December 2014 22:50:35 UTC, Lucia Fedorova wrote:
Hi Craig,
have you tried using $client->refreshToken($refreshToken) to obtain the refresh token?


I have the refresh token, the second code snippet works ok, or appears to.

If I call the function getAccessToken() as shown above

I get the response string(83) "xxxx.0ACWT0cKdibM6I9bqd1PwP62Mkyfy1Pxxxxxxxfl4qcdJ3s8xPAu82weQKtOlBqhz9pJjtUjxxxxxx" (string modified)

if i call it again i get a different token, which to me, indicates that the function is working ok,

if I then try to use the code to insert an event, using the supplied access token, I get an error,  Uncaught exception 'Google_Auth_Exception' with message 'Could not json decode the token'

If i change the getAccessToken() function to return the result of curl_exec($ch)

I get the response string(158) "{ "access_token" : "xxxx.0AAmWInp-iqiTJIEuKTM9QC5dZpEXVVQYJk8d2zeNWlOk7fvtImld6dQj0OGP09tOAvoDCYxxxxxxx", "token_type" : "Bearer", "expires_in" : 3600 }" (token modified)

If I then try to use the code to insert an event, I get Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.

Lucia Fedorova

unread,
Dec 3, 2014, 6:41:31 PM12/3/14
to google-ca...@googlegroups.com
Hi Craig,
I meant to say that $client->refreshToken($refreshToken) will refresh the token. Then you can just do $client->accessToken() to see your new access token. All heavy lifting should be done by the client library and you should be able to get rid of all the curl calls. Try taking a look at the reply here: http://stackoverflow.com/questions/18461143/refresh-token-with-google-api-client-php

Craig R

unread,
Dec 6, 2014, 2:05:21 AM12/6/14
to google-ca...@googlegroups.com
Thanks for the link

I worked out that the values returned when getting my refresh token only gave me 3 values, the 'access_token' itself, the 'token_type', and 'expires_in'.

What is also required when calling setAccessToken() is the 'refresh_token' and the 'created' value.

using the answer here https://stackoverflow.com/questions/25525471/google-oauth-2-0-refresh-token-for-web-application-with-public-access as a guide, 

I managed to pass the all of the parameters into setAccessToken()

I had the refresh token already, but I am not clear on the 'created', is it when the refresh token was created or the access token, and will this value change ?

I tried this over the last couple of days,  - i stored the 'refresh_token' and 'created' values in my database and build the string with the 'access-token', 'token-type' and 'expires_in'

Seems to work ok ;-)
 
Reply all
Reply to author
Forward
0 new messages