Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

NOTE: This article is 3 years or older so its information may no longer be relevant. Read on at your own discretion! Comments for this article have automatically been locked, refer to the FAQ for more details.
If you want to avoid prompting the user to give permission to your app every time it tries to use their Google+ account for authentication/authorisation, you probably want to use the refresh token to gain the same access.

A refresh token is retrieved the very first time the user gives permission to your app. You can then store this token on your server for later use. This is a permanent token without expiration and it will last until the user revokes it. Revocation can be done online from the Account Permissions page.

More detail of the OAuth implementation for Google+ can be found on the Using OAuth 2.0 to Access Google APIs page. This example will assume you are familiar with the protocol and have already
set up an app and configured it for use with Google+ API.

This example is written in PHP and relies on the Google APIs Client Library for PHP (version 1.1).

So lets get started with some code. I am going to assume that the client ID and the client secret are defined with two variables as follows:
 Variables
$gpclientid = 'xxx';
$gpclientsecret = 'xxx';


Now what we need to do is to generate a URL that is clicked by the user (or the user is redirected to) that will initiate the OAuth flow. When generating this URL, it's important to set the required scopes and any visible actions that will be needed by your app in the future. I also force the approval prompt in this case so that I am guaranteed to get a new token.

Last, it is critical to have a redirect URL set up back to yourself, this is the URL that the Google+ API will redirect to once the user has authorised your app. This URL must be in the list of authorised redirect URIs for your app. In this case, I use redirect to the request.php page and also set a parameter gp so that my code can know that the request came from the Google+ API. The code looks to see if the gp URL parameter was set, the 'Get Access' link is only generated if it has not.
 request.php
<?php
require_once 'google/src/Google/autoload.php';
$client = new Google_Client();
$client->setClientId($gpclientid);
$client->setClientSecret($gpclientsecret);
$client->setScopes('https://www.googleapis.com/auth/plus.login');
$client->setRequestVisibleActions('http://schema.org/AddAction');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setRedirectUri("http://localhost/request.php?gp=1");
if (!isset($_REQUEST['gp'])) {
$authUrl = $client->createAuthUrl();
echo('<a href="'. $authUrl .'">Get Access</a>');
}
...




Continuing with the same source file, the code below is run after Google has redirected back to you. The gp and code URL parameters are checked. The former is something I've defined, the latter is something that Google sends back. The code parameter is used for the final part of the OAuth flow, then we can get the refresh token and save it for later use. The save_token() method is not shown here, this method should permanently store the fetched token to your server in a secure location.
 request.php
...
if (isset($_REQUEST['gp']) && isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$refreshToken = $client->getRefreshToken();
save_token($refreshToken);
echo('Refresh token saved');
exit();
}
?>


At this point, the refresh token is available to make other calls to the Google+ API. So lets see how it's used. Another script is needed for that since the previous one only dealt with requesting and storing the token.
 test.php
<?php
require_once 'google/src/Google/autoload.php';
$gpclientid = 'xxx';
$gpclientsecret = 'xxx';
$gprefreshtoken = load_token();
$client = new Google_Client();
$client->setClientId($gpclientid);
$client->setClientSecret($gpclientsecret);
try {
$client->refreshToken($gprefreshtoken);
$client->verifyIdToken();
$plus = new Google_Service_Plus($client);
$moment_body = new Google_Service_Plus_Moment();
$moment_body->setType("http://schema.org/AddAction");
$item_scope = new Google_Service_Plus_ItemScope();
$item_scope->setUrl("https://developers.google.com/+/plugins/snippet/examples/thing");
$moment_body->setObject($item_scope);
$momentResult = $plus->moments->insert('me', 'vault', $moment_body);
echo('Successfully posted app activity to Google+');
}
catch (Exception $e) {
echo('Something went wrong: '. $e->getMessage());
}
?>



What the code above does is load the previously saved token. The load_token() method is not shown here, but should load the refresh token from a location on your server. After we have the refresh token, the refreshToken() method is called on the Google+ client to get a new access token, which is then verified. After this point a Google+ service is created by passing in the client object. Then, a simple app activity is written.

-i

Skip down to comments...
Hope you found this post useful...

...so please read on! I love writing articles that provide beneficial information, tips and examples to my readers. All information on my blog is provided free of charge and I encourage you to share it as you wish. There is a small favour I ask in return however - engage in comments below, provide feedback, and if you see mistakes let me know.

If you want to show additional support and help me pay for web hosting and domain name registration, donations, no matter how small, are always welcome!

Use of any information contained in this blog post/article is subject to this disclaimer.
 
comments powered by Disqus
Other posts you may like...