使用PHP的Google URL Shortening API

时间:2013-03-27 19:24:21

标签: google-api google-api-php-client

现在我知道这是一个通过互联网的常见话题,特别是StackOverflow。但是我没有(或者还没有看到)是在会话中维护令牌的直接解决方案。

我正在使用Google APIs Client Library for PHP

我的查询: 我有一个index.php,我使用PHP客户端lib中的Google_Oauth2Service获取用户数据(例如名称)。用户已成功通过身份验证,一切顺利。现在我想使用URL Shortening服务,因此我有一个shorten.php,我有代码尝试获取短URL。一些如何不起作用。

的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);
....
....

在这里,我开始了会话并制作了Google_Client的对象。我已经声明了客户端ID,密码和所有其他细节。

然后我在成功验证时获取访问令牌并将其存储在Session变量中,这样当我尝试从shorten.php获取短URL(使用jQuery ajax)时,我可以使用现有令牌。

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

现在在 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);    
            ....

这是代码中断的确切行$shortURL = $url_service->url->insert($url);我成功使用Session变量获取令牌并创建了一个成功的URL Service对象。但就在我调用insert方法时,那就是它失败了。

来自 apache错误日志

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

当我在index.php和shorten.php文件上转储Google_Client变量时,这就是我得到的。

的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)
}

并且两者都是一样的,所以我假设这里有些东西不对。请帮助或指导。

1 个答案:

答案 0 :(得分:0)

您在验证时没有请求UrlShortener范围,这就是它失败的原因。 要添加范围,您可以在index.php中进行身份验证之前创建UrlshortenerService,并传递客户端的同一实例,如:

//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);
$url_service = new Google_UrlshortenerService($gClient);

或者,您可以使用setScopes覆盖自动生成的范围