2013-12-23 79 views
0

我在將Google Analytics(分析)API與我的PHP網站集成時遇到問題。我試圖在我的網站上顯示數據而無需用戶登錄到Google,因此我使用的是服務帳戶方法。我也嘗試使用hello world分析代碼,這給了我同樣的錯誤。Google Analytics API PHP「OAuth客戶端被禁用」

以下是完整的錯誤消息: 刷新OAuth2令牌時出錯,消息:'{「error」:「disabled_client」,「error_description」:「OAuth客戶端被禁用。 }'

<?php 
require_once('google-api/Google_Client.php'); 
require_once('google-api/contrib/Google_AnalyticsService.php'); 

session_start(); 
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
</head> 
<body> 
<?php 
$KEY_FILE = 'path_to_key_file/123-privatekey.p12'; //KEY FILE  

$client = new Google_Client(); 
$client->setApplicationName('AppName'); //APP NAME 

$account = '[email protected]'; //FOUND IN CLIENT SERVICE EMAIL ADDRESS 



$client->setAssertionCredentials(new Google_AssertionCredentials(
    $account, 
    array('https://www.googleapis.com/auth/analytics.readonly'), 
    file_get_contents($KEY_FILE)) 
); 

$client->setClientId('123.apps.googleusercontent.com'); //CLIENT ID 
$client->setAccessType('offline_access'); // this may be unnecessary? 


if (!$client->getAccessToken() && false) { 
    $authUrl = $client->createAuthUrl(); 
    print "<a class='login' href='$authUrl'>Connect Me!</a>"; 

} else { 
    // Create analytics service object. See next step below. 
    if ($client) 
    { 
     // Create analytics service object. See next step below. 
     //$analytics = new Google_AnalyticsService($client); 
     //runDemo($analytics); 
     $ids = "ga:" . "46052980"; 
     $startDate="2013-12-12"; 
     $endDate="2013-12-20"; 
     $metrics="ga:visits"; 
     try { 
      $analytics = new Google_AnalyticsService($client); 
      $results = $analytics->data_ga->get($ids, 
          $startDate, 
           $endDate,'ga:visits'); 
      /*echo '<b>Number of visits this week:</b> '; 
      echo $results['totalsForAllResults']['ga:visits']; 
      */ 
     } catch(Exception $e) { 
      echo 'There was an error : - ' . $e->getMessage(); 
     } 


    } else { 
     echo "error"; 
     echo $key; 
    } 
} 

if ($client->getAccessToken()) { 
    $_SESSION['token'] = $client->getAccessToken(); 
    echo $_SESSION['token']; 
} 

?> 
</body> 
</html> 

回答

0

您必須立即使用OAuth2。看看sample code for PHP。請注意,您必須先在Google API控制檯中註冊您的應用以獲取客戶端ID,客戶端密鑰和API密鑰。