带有Google Analytics API的OAuth报告无效令牌


OAuth with Google Analytics API reports invalid token

以下代码运行良好,但有时报告"无效令牌"。当我的ID列表中有外国网站时,就会发生这种情况。但是当我使用电子邮件/密码对登录时,它运行良好直到最后。知道出了什么问题吗?

干杯:

鲍勃

<?php  
/*  
API ACCESS PANEL:  
https://code.google.com/apis/console/  
*/  
session_start();  #the includes are as follows, using also gapi.class.php  
require_once 'src/apiClient.php';  
require_once 'src/contrib/apiAnalyticsService.php';  
ini_set('display_errors', '1');  
$client = new apiClient();  
$client->setApplicationName("Google Analytics PHP Starter Application");  
/*  
Visit https://code.google.com/apis/console?api=analytics to generate your client id, client secret, and to register your redirect uri.  
*/  
$client->setClientId('');# MUST SET UP!  
$client->setClientSecret('');# MUST SET UP!  
$client->setRedirectUri('http://localhost/analytics/chart_server.php');# MUST SET UP!  
$client->setDeveloperKey('');# MUST SET UP!  
 // requestReportData first parameter, an Analytics Profil ID must defined here:  
$ga_profile_id='';# MUST SET UP!  
//////////////////////////////////////////////////////////////////////////////  
$service = new apiAnalyticsService($client);  
// logout  
if (isset($_GET['logout'])) {  
    unset($_SESSION['token']);  
    exit;  
}  
// get the tooken from Google, store into the session, call back this script with header-location  
if (isset($_GET['code'])) {  
    $client->authenticate();  
    $_SESSION['token'] = $client->getAccessToken();  
    header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);  
    exit;  
}  
// if we got token in the session-ben, passing to $client (this is the OAuth client)  
if (isset($_SESSION['token'])) {  
    $client->setAccessToken($_SESSION['token']);  
}  
// if the token valid, then we have access:  
if ($client->getAccessToken()){  
    #$props = $service->management_webproperties->listManagementWebproperties("~all");  
    /*  
    print "Web Properties " . print_r($props, true);  
    */  
    print("auth OK");//ok  
    print_r($client->getAccessToken()); // print out for test  
    $_SESSION['token'] = $client->getAccessToken();// stor eback to the session  
} else { // Authorize with OAuth cause we have no valid access token  
    #https://www.google.com/analytics/feeds/  
    #https://www.googleapis.com/auth/analytics.readonly  
    $scope="https://www.google.com/analytics/feeds/"; // we'd like to access this  
    $authUrl = $client->createAuthUrl($scope);  
    header("Location: ".$authUrl); /* Redirect browser */  
    #  print "<a class='login' href='$authUrl'>Connect Me!</a>";  
    exit;  
}  
// test printout, OAuth account object:  
$accounts = $service->management_accounts->listManagementAccounts();  
print "List of accounts" . print_r($accounts, true) .;  

//////////////////////////////////////////////////////////////////////////////////////////////  
// Here is the Google Analytics API call, and the "TOKEN INVALID 401" error message         //  
//////////////////////////////////////////////////////////////////////////////////////////////  
require 'gapi.class.php';  
$ga = new gapi(null,null,$_SESSION['token']); // access token instead of mail, password pair  
#$token=$ga->getAuthToken();# $_SESSION['token']  

// http://code.google.com/p/gapi-google-analytics-php-interface/wiki/GAPIDocumentation  
// requestReportData($report_id, $dimensions, $metrics, $sort_metric=null, $filter=null, $start_date=null, $end_date=null, $start_index=1, $max_results=30)  
$dimensions=array('browser','date');// x coord  
$metrics=array('visits','pageLoadTime','uniquePageviews'); // y coord  
$sort_metric="-date"; #descending order  
$filter = '';  
$startDate = '2012-04-01';  
$endDate = '2012-04-12';  
$start_index=1;  
$max_results=50;  
#$ga->requestReportData($accProfiles[$profileNum]->getProfileId(),$dimensions,$metrics,$sort_metric,$filter, $start_date, $end_date, $start_index, $max_results );  
$ga->requestReportData($ga_profile_id, $dimensions, $metrics, $sort_metric, $filter, $startDate, $endDate, $start_index, $max_results );  
$results=$ga->getResults();  
// test:  
echo "Google Analytics data ";print_r($results);  
#echo "#####".$ga->getMetrics();  
// Set the JSON header  
//header("Content-type: text/json");  
#echo json_encode( array($dim, $met1, $met2, $met3 ) );  

?>  

忘记gapi.class.php。它很慢,并且仅适用于USR/PSW。apiAnalyticsService也很慢,但可以很好地处理令牌。

尝试从下面更改范围:

$scope="https://www.google.com/analytics/feeds/";

对此:

$scope="https://www.googleapis.com/auth/analytics.readonly";