使用PHP的OAuth Google Analytics身份验证


OAuth Google Analytics Authentication with PHP

我正试图让OAuth与Google Analytics合作,但我运气不佳。我的代码如下:

require_once('common.inc.php');
$consumerKey = "my.url.net";
$consumerSecret = "nzZ....TX";
$sig_method = "HMAC-SHA1";
$oauth_token = $token ? new OAuthToken($token, $token_secret) : NULL;
$token_endpoint = '/accounts/OAuthGetRequestToken';
$scope = 'https://www.google.com/analytics/feeds/';
$callback_url = "http://my.url.net/pete/oauth/";
$privKey = NULL;
$params = array('scope' => $scope, 'oauth_callback' => $callback_url);
$url = $token_endpoint . '?scope=' . urlencode($scope);
$consumer = new OAuthConsumer($consumerKey, $consumerSecret);
$req = OAuthRequest::from_consumer_and_token($consumer, $oauth_token, 'GET',
                                             $url, $params);
//$req->sign_request($sig_method, $consumer, $oauth_token, NULL);
echo "<PRE>";
print_r($req);
// Fill response
echo json_encode(array(
    'html_link' => '',
    'base_string' =>  $req->get_signature_base_string(),
    'response' => send_signed_request('GET', $url, array($req->to_header())),
    'authorization_header' => $req->to_header()
));

所以当这个代码运行时,它会打印出以下内容:

OAuthRequest Object
(
    [parameters:OAuthRequest:private] => Array
        (
            [oauth_version] => 1.0
            [oauth_nonce] => 5f....11
            [oauth_timestamp] => 1306433873
            [oauth_consumer_key] => my.url.net
            [scope] => https://www.google.com/analytics/feeds/
            [oauth_callback] => http://my.url.net/pete/oauth/
        )
    [http_method:OAuthRequest:private] => GET
    [http_url:OAuthRequest:private] => /accounts/OAuthGetRequestToken?scope=https%3A%2F%2Fwww.google.com%2Fanalytics%2Ffeeds%2F
    [base_string] => 
)

当我取消注释此行时:

//$req->sign_request($sig_method, $consumer, $oauth_token, NULL);

脚本加载失败,显示服务器错误。我做错了什么?任何建议都会有帮助,谢谢!

感谢您的评论Mark,这实际上是因为我的"$sig_method"变量实际上只是一个包含"HMAC…"的字符串,而它实际上需要是一个名为的对象

$sig_method = new OAuthSignatureMethod_HMAC_SHA1();

希望这对将来的人有所帮助!