Skip to content

Instantly share code, notes, and snippets.

@philsturgeon
Created November 23, 2011 14:58
Show Gist options
  • Save philsturgeon/1388885 to your computer and use it in GitHub Desktop.
Save philsturgeon/1388885 to your computer and use it in GitHub Desktop.
Google analytics OAuth 2 + Refresh Tokens
<?php
class Controller_Metrics extends Controller {
public function action_index()
{
if ( ! Auth::check())
{
exit('not logged in');
}
list($driver, $id) = Auth::get_user_id();
$user = Model_User::find($id);
// Find the authentication we want to work with
$auth = Model_Authentication::find_by_provider_and_user_id('google', $user->id);
// Lets do some stuff with google!
\Config::load('ninjauth', true);
$client = \OAuth2\Provider::forge('google', \Config::get('ninjauth.providers.google'));
for ($i = 0; $i < 2; $i++)
{
try
{
$url = 'https://www.google.com/analytics/feeds/accounts/default';
$request = Request::forge($url, 'curl');
$request->set_params(array(
'access_token' => $auth->access_token,
'alt' => 'json'
));
$request = $request->execute();
}
// Request fail, let's see what type!
catch (RequestException $e)
{
switch ($request->response()->status)
{
// Unauthorized
case 401:
// Are they unathorised because their token is out of date?
if ($auth->expires <= time())
{
// Let's try and refresh the token!
try
{
$token = $client->access($auth->refresh_token, array(
'grant_type' => 'refresh_token',
));
}
// Aww man?!
catch (RequestException $e)
{
// Bitch and fail
Debug::dump($request->response());
exit('oh fuck it1');
}
// Update this authentication
$auth->access_token = $token->access_token;
$auth->expires = $token->expires;
$auth->refresh_token = $token->refresh_token;
$auth->save();
// Back to the start
continue;
}
break;
}
}
// No exception was throw so carry on
break;
}
$json = json_decode($request->response()->body(), true);
$accounts = \Arr::get($json, 'feed.entry');
Debug::dump($accounts);
//
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment