Skip to content

Instantly share code, notes, and snippets.

@talkingnews
Created September 7, 2012 15:13
Show Gist options
  • Save talkingnews/3667043 to your computer and use it in GitHub Desktop.
Save talkingnews/3667043 to your computer and use it in GitHub Desktop.
Pyrocms Google URL shortener and the oAuth2 conundrum
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Plugin_Googleshort extends Plugin
{
const CLIENT_ID = 'xxxxx.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = '[email protected]';
const KEY_FILE = 'xxxxx-privatekey.p12';
function shorten()
{
require_once 'googleAPI/src/Google_Client.php';
require_once 'googleAPI/src/contrib/Google_UrlshortenerService.php';
$client = new Google_Client();
$client->setApplicationName("Short URL");
// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcache
session_start(); // of course, I can't do this because session headers have already been set
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$key = file_get_contents(Plugin_Googleshort::KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(Plugin_Googleshort::SERVICE_ACCOUNT_NAME, array(
'https://www.googleapis.com/auth/urlshortener'
), $key, 'notasecret'));
$client->setClientId(Plugin_Googleshort::CLIENT_ID)
$accessToken = $client->getAccessToken(); // nice idea, but this doesn't work of course.
$this->load->driver('Streams');
$entry_data = array('google_session' => $accessToken);
$this->streams->entries->update_entry('1', $entry_data, 'google_sessions', 'streams');
$service = new Google_UrlshortenerService($client);
$url = new Google_Url();
$url->longUrl = "http://www.bbc.co.uk/";
$short = $service->url->insert($url);
var_dump($short);
// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
//if ($client->getAccessToken()) {
// $_SESSION['token'] = $client->getAccessToken();
//}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment