GData API with OAuth2 in PHP

Or: how to access Picasa nowadays

We have been giving users of our website builder the possibility to connect their Picasa albums to their own website. To accomplish that we used the GData API with AuthSub authentication. Zend's GData library made this easy for us.

However recently AuthSub support has been dropped by Google, making OAuth2 authentication mandatory. Zend's GData component does not support this and there seems to be no PHP libraries that does the job of talking with the GData API using OAauth2 in general!

Most new Google APIs use a new API style different from the GData one. Google does actively support this API with a PHP client of its own: google-api-php-client. Too bad Picasa isn't a supported service!

Borrowing the OAuth implementation

Luckily, we can use the OAuth2 part of this library to get us up to speed.

Examples on the GitHub page are shown on how to do this. The crucial step is to set the scope to https://picasaweb.google.com/data/. Notice that I also request an offline tokken. This way we can also use the API while the user is away.

$client->setAccessType('offline');
$client->setScopes('https://picasaweb.google.com/data/');

We should end up with a key like:

{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"expires_in":3600,
"token_type": "bearer",
"scope":null,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
}

We can now extract the access_token and directly use that in API calls to Picasa. A fiddle showing a request to Picasa's API V2 using this token is given by:

file_get_contents('https://picasaweb.google.com/data/feed/api/user/default?v=2&access_token=2YotnFZFEjr1zCsicMWpAA'); // XML response

Refreshing a token

When a request is send using the new google-api, the library renews the access_token when it is expired in the background. This is necessary to keep doing API requests on behalf of the user after the initial token has expired.

As we do not use the library when making API requests we need to do this ourselves. This turns out to be easy. This code should be used before making an API request.

if ($client->isAccessTokenExpired()) {
$token = json_decode($oauthJsonResponse, true);
$client->refreshToken($token['refresh_token']);
// Save new $client->getAccessToken()
}
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.