Google URL Shortening API using PHP-Collection of common programming errors

Now I know this is a common topic that has been over the Internet especially StackOverflow. But what I do not have (or haven’t yet seen) is a straight solution for the token being maintained over a session.

I’m using the Google APIs Client Library for PHP .

My Query: I have one index.php where I fetch the user data (such as name) using the Google_Oauth2Service from the PHP client lib. The user is authenticated successfully and all goes well. Now I’d like to use the URL Shortening service and therefore I have a shorten.php where I have the code to try fetch the short URL. Some how this doesn’t work.

index.php

//include google api files
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_Oauth2Service.php';
require_once 'src/contrib/Google_UrlshortenerService.php';

//start session
session_start();
$gClient = new Google_Client();
$gClient->setApplicationName('Test App');
$gClient->setClientId($google_client_id);
$gClient->setClientSecret($google_client_secret);
$gClient->setRedirectUri($google_redirect_url);
$gClient->setDeveloperKey($google_developer_key);

$google_oauthV2 = new Google_Oauth2Service($gClient);
....
....

Here I have started the session and made an object of the Google_Client. I have declared the client id, secret and all other details.

Then I get the access token on successful authentication and store it in the Session variable so that when I try to fetch the short url (using jQuery ajax) from shorten.php, I can use the existing token.

$_SESSION['token'] = $gClient->getAccessToken();    
....

Now in shorten.php

session_start();
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_Oauth2Service.php';
require_once 'src/contrib/Google_UrlshortenerService.php';

$gClient = new Google_Client();
$gClient->setApplicationName('Test App');
$gClient->setClientId($google_client_id);
$gClient->setClientSecret($google_client_secret);
$gClient->setRedirectUri($google_redirect_url);
$gClient->setDeveloperKey($google_developer_key);

....
if (isset($_SESSION['token']) && $_SESSION['token']) {

    // Set the access token from the session
    $gClient->setAccessToken($_SESSION['token']);   
    $url_service = new Google_UrlshortenerService($gClient);

    // Check if a URL has been passed
    if (isset($_GET['url'])) {  
            $url = new Google_Url();
        $url->longUrl = $_GET['url'];

        $shortURL = $url_service->url->insert($url);    
            ....

This is the exact line where the code breaks $shortURL = $url_service->url->insert($url); I was successful in getting the token using the Session variable and created a successful URL Service object. But just when I call the insert method, that’s when it fails.

From the apache error logs :

husain@innovate:~/myprojects/web$ tail -1 /var/log/apache2/error.log | sed -e 's/\\n/\n/g'
[Thu Mar 28 00:42:35 2013] [error] [client 127.0.0.1] PHP Fatal error:  Uncaught exception 'Google_ServiceException' with message 'Error calling POST https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyCxfXP-xS-QYJw-7mM4SNG3EW9ryj_Oiv4: (401) Invalid Credentials' in /home/husain/myprojects/web/apps/src/io/Google_REST.php:66
Stack trace:
#0 /home/husain/myprojects/web/apps/src/io/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest))
#1 /home/husain/myprojects/web/apps/src/service/Google_ServiceResource.php(177): Google_REST::execute(Object(Google_HttpRequest))
#2 /home/husain/myprojects/web/apps/src/contrib/Google_UrlshortenerService.php(38): Google_ServiceResource->__call('insert', Array)
#3 /home/husain/myprojects/web/apps/shorten.php(44): Google_UrlServiceResource->insert(Object(Google_Url))
#4 {main}
  thrown in /home/husain/myprojects/web/apps/src/io/Google_REST.php on line 66

When I dump the Google_Client variables on the index.php and shorten.php files, this is what I get.

index.php

Google_Client Object
    (
    [scopes:protected] => Array

        (
        )

    [useObjects:protected] => 
    [services:protected] => Array
        (
            [oauth2] => Array
                (
                    [scope] => Array
                        (
                            [0] => https://www.googleapis.com/auth/userinfo.profile
                            [1] => https://www.googleapis.com/auth/userinfo.email
                        )

                )

        )

    [authenticated:Google_Client:private] => 
)

shorten.php

object(Google_Client)#1 (4) {
  ["scopes":protected]=>
  array(0) {
  }
  ["useObjects":protected]=>
  bool(false)
  ["services":protected]=>
  array(1) {
    ["urlshortener"]=>
    array(1) {
      ["scope"]=>
      string(44) "https://www.googleapis.com/auth/urlshortener"
    }
  }
  ["authenticated":"Google_Client":private]=>
  bool(false)
}

and both aint the same so I’m assuming that there is something not right here. Help or direction please.