{"id":3054,"date":"2014-03-15T03:26:51","date_gmt":"2014-03-15T03:26:51","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/03\/15\/google-url-shortening-api-using-php-collection-of-common-programming-errors-2\/"},"modified":"2014-03-15T03:26:51","modified_gmt":"2014-03-15T03:26:51","slug":"google-url-shortening-api-using-php-collection-of-common-programming-errors-2","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/03\/15\/google-url-shortening-api-using-php-collection-of-common-programming-errors-2\/","title":{"rendered":"Google URL Shortening API using PHP-Collection of common programming errors"},"content":{"rendered":"<p>Now I know this is a common topic that has been over the Internet especially StackOverflow. But what I do not have (or haven&#8217;t yet seen) is a straight solution for the token being maintained over a session.<\/p>\n<p>I&#8217;m using the Google APIs Client Library for PHP .<\/p>\n<p><strong>My Query:<\/strong> 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&#8217;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&#8217;t work.<\/p>\n<p><strong>index.php<\/strong><\/p>\n<pre><code>\/\/include google api files\nrequire_once 'src\/Google_Client.php';\nrequire_once 'src\/contrib\/Google_Oauth2Service.php';\nrequire_once 'src\/contrib\/Google_UrlshortenerService.php';\n\n\/\/start session\nsession_start();\n$gClient = new Google_Client();\n$gClient-&gt;setApplicationName('Test App');\n$gClient-&gt;setClientId($google_client_id);\n$gClient-&gt;setClientSecret($google_client_secret);\n$gClient-&gt;setRedirectUri($google_redirect_url);\n$gClient-&gt;setDeveloperKey($google_developer_key);\n\n$google_oauthV2 = new Google_Oauth2Service($gClient);\n....\n....\n<\/code><\/pre>\n<p>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.<\/p>\n<p>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.<\/p>\n<pre><code>$_SESSION['token'] = $gClient-&gt;getAccessToken();    \n....\n<\/code><\/pre>\n<p>Now in <strong>shorten.php<\/strong><\/p>\n<pre><code>session_start();\nrequire_once 'src\/Google_Client.php';\nrequire_once 'src\/contrib\/Google_Oauth2Service.php';\nrequire_once 'src\/contrib\/Google_UrlshortenerService.php';\n\n$gClient = new Google_Client();\n$gClient-&gt;setApplicationName('Test App');\n$gClient-&gt;setClientId($google_client_id);\n$gClient-&gt;setClientSecret($google_client_secret);\n$gClient-&gt;setRedirectUri($google_redirect_url);\n$gClient-&gt;setDeveloperKey($google_developer_key);\n\n....\nif (isset($_SESSION['token']) &amp;&amp; $_SESSION['token']) {\n\n    \/\/ Set the access token from the session\n    $gClient-&gt;setAccessToken($_SESSION['token']);   \n    $url_service = new Google_UrlshortenerService($gClient);\n\n    \/\/ Check if a URL has been passed\n    if (isset($_GET['url'])) {  \n            $url = new Google_Url();\n        $url-&gt;longUrl = $_GET['url'];\n\n        $shortURL = $url_service-&gt;url-&gt;insert($url);    \n            ....\n<\/code><\/pre>\n<p>This is the exact line where the code breaks <code>$shortURL = $url_service-&gt;url-&gt;insert($url);<\/code> 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&#8217;s when it fails.<\/p>\n<p>From the <strong>apache error logs<\/strong> :<\/p>\n<pre><code>husain@innovate:~\/myprojects\/web$ tail -1 \/var\/log\/apache2\/error.log | sed -e 's\/\\\\n\/\\n\/g'\n[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\nStack trace:\n#0 \/home\/husain\/myprojects\/web\/apps\/src\/io\/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest))\n#1 \/home\/husain\/myprojects\/web\/apps\/src\/service\/Google_ServiceResource.php(177): Google_REST::execute(Object(Google_HttpRequest))\n#2 \/home\/husain\/myprojects\/web\/apps\/src\/contrib\/Google_UrlshortenerService.php(38): Google_ServiceResource-&gt;__call('insert', Array)\n#3 \/home\/husain\/myprojects\/web\/apps\/shorten.php(44): Google_UrlServiceResource-&gt;insert(Object(Google_Url))\n#4 {main}\n  thrown in \/home\/husain\/myprojects\/web\/apps\/src\/io\/Google_REST.php on line 66\n<\/code><\/pre>\n<p>When I dump the Google_Client variables on the index.php and shorten.php files, this is what I get.<\/p>\n<p><strong>index.php<\/strong><\/p>\n<pre><code>Google_Client Object\n    (\n    [scopes:protected] =&gt; Array\n\n        (\n        )\n\n    [useObjects:protected] =&gt; \n    [services:protected] =&gt; Array\n        (\n            [oauth2] =&gt; Array\n                (\n                    [scope] =&gt; Array\n                        (\n                            [0] =&gt; https:\/\/www.googleapis.com\/auth\/userinfo.profile\n                            [1] =&gt; https:\/\/www.googleapis.com\/auth\/userinfo.email\n                        )\n\n                )\n\n        )\n\n    [authenticated:Google_Client:private] =&gt; \n)\n<\/code><\/pre>\n<p><strong>shorten.php<\/strong><\/p>\n<pre><code>object(Google_Client)#1 (4) {\n  [\"scopes\":protected]=&gt;\n  array(0) {\n  }\n  [\"useObjects\":protected]=&gt;\n  bool(false)\n  [\"services\":protected]=&gt;\n  array(1) {\n    [\"urlshortener\"]=&gt;\n    array(1) {\n      [\"scope\"]=&gt;\n      string(44) \"https:\/\/www.googleapis.com\/auth\/urlshortener\"\n    }\n  }\n  [\"authenticated\":\"Google_Client\":private]=&gt;\n  bool(false)\n}\n<\/code><\/pre>\n<p>and both aint the same so I&#8217;m assuming that there is something not right here. Help or direction please.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Now I know this is a common topic that has been over the Internet especially StackOverflow. But what I do not have (or haven&#8217;t yet seen) is a straight solution for the token being maintained over a session. I&#8217;m using the Google APIs Client Library for PHP . My Query: I have one index.php where [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-3054","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/3054","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=3054"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/3054\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=3054"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=3054"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=3054"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}