Keeping Google API sessions persistent with refresh tokens
I’ve been working with Google’s Tasks API and was looking to have a way a user would only need to authenticate their account once. Google does not explain very well on how to achieve this.
With php you will need to get the api setup HERE. You then need to then setup up an authentication stream:
require_once 'src/apiClient.php'; require_once 'src/contrib/apiTasksService.php'; $client = new apiClient(); $tasksService = new apiTasksService($client);
On the callback of the user allowing your app to access their tasks, you will get an access token and more importantly here a refresh token.
$auth = $client->authenticate(); $token = $client->getAccessToken(); $refresh_token = $token['refresh_token'];
Save the refresh token to somewhere you are able to access it again whenever you’d like. After that we can use that token to get the users tasks at any moment.
$client->refresh_token($refresh_token);
























Ted Bradley said
am August 26 2012 @ 1:43 pm
This was really helpful, and allowed me to turn the jason string into a variable so I could access/save the refresh token. The thing I’m still confused by is how to then actually use the refresh token? If i just drop the code
client->refresh_token($refresh_token);
into my script i get an error. Does it need a conditional or to be applied only at a certain time? Is that the only line of code I need to have permanent access to the api without having to re-grant permission?
Ted Bradley said
am August 26 2012 @ 2:38 pm
this turned out to be more simple than i had anticipated. starting with the hello analytics api, i added the following code and it appears to be able to connect now without re-authenticating.
// begin custom code
$client->setAccessType(‘offline’);
if (isset($_SESSION['token'])) {
// echo $_SESSION['token'];
echo ”;
echo ”;
$authObj = json_decode($_SESSION['token']);
$accessToken = $authObj->access_token;
$refreshToken = $authObj->refresh_token;
$tokenType = $authObj->token_type;
$expiresIn = $authObj->expires_in;
echo ‘access_token = ‘ . $accessToken;
echo ”;
echo ‘refresh_token = ‘ . $refreshToken;
echo ”;
echo ‘token_type = ‘ . $tokenType;
echo ”;
echo ‘expires_in = ‘ . $expiresIn;
echo ”;
echo ”;
}
$refreshToken = ’1/ewPvNg6_2toqDtCaw2bdIUhgQpGF7koqLAIurSpo4Uk’;
$client->refreshToken($refreshToken);
// end custom code