PHP后端中的Google AnalyticsAPI

时间:2022-04-06 14:18:43

So I want to display GA chart in custom PHP backend. So I created APP in https://console.developers.google.com/ but I cant figure out how to access my own google analytics data withouth asking for user to login. For now I have simple code:

所以我想在自定义PHP后端显示GA图表。所以我在https://console.developers.google.com/创建了APP,但我无法弄清楚如何在不要求用户登录的情况下访问我自己的谷歌分析数据。现在我有简单的代码:

  $client = new Google_Client();
  $client->setApplicationName("App Name");
  $client->setClientId(CLIENT_ID);
  $client->setClientSecret(CLIENT_SECRET);
  $client->setDeveloperKey(APP_ID);
  $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
  $client->authenticate();
  $token = $client->getAccessToken();
  $service = new Google_Service_Analytics($client);
$optParams = array(
      'sort' => 'ga:pageviews',
      'max-results' => '5');
$results = $service->data_ga->get(
       'ga:123456',
       '2015-01-01',
       '2015-01-30',
       'ga:pagePath',
       $optParams);

print_r($results);

I guess I am doing everything wrong :), so my question would be, how to allow anyone to access my own google analytics data through PHP script?

我想我做错了:),所以我的问题是,如何允许任何人通过PHP脚本访问我自己的谷歌分析数据?

1 个解决方案

#1


If you want to access your own account, then I suggest you look into using a service account.

如果您想访问自己的帐户,我建议您考虑使用服务帐户。

Once you have created the service account on the Google Developer console, remember to go to your Google Analytics account and give the service account email address access to your Google Analytics data at the Account level. You can read about how to do that here Google Service Account PHP code ripped from that tutorial.

在Google Developer控制台上创建服务帐户后,请务必访问您的Google Analytics帐户,并在帐户级别向服务帐户电子邮件地址授予对Google Analytics数据的访问权限。您可以在此处阅读有关如何执行此操作的Google服务帐户PHP代码。

session_start();        
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';        
/************************************************   
 The following 3 values an befound in the setting   
 for the application you created on Google      
 Developers console.         Developers console.
 The Key file should be placed in a location     
 that is not accessable from the web. outside of 
 web root.       web root.

 In order to access your GA account you must    
 Add the Email address as a user at the     
 ACCOUNT Level in the GA admin.         
 ************************************************/
$client_id = 'xxx-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = 'xxx-nk421gjc2v8mlr2qnmmqaak04ntb1dbp@developer.gserviceaccount.com';   
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';     
$client = new Google_Client();      
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);    
// seproate additional scopes with a comma   
$scopes ="https://www.googleapis.com/auth/analytics.readonly";  
$cred = new Google_Auth_AssertionCredentials(    
 $Email_address,         
 array($scopes),        
 $key        
 );     
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {        
 $client->getAuth()->refreshTokenWithAssertion($cred);      
}       
$service = new Google_Service_Analytics($client);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
//calulating start date  
$date = new DateTime(date("Y-m-d"));     
$date->sub(new DateInterval('P10D'));    
//Adding Dimensions
$params = array('dimensions' => 'ga:userType'); 
// requesting the data  
$data = $service->data_ga->get("ga:78110423", $date->format('Y-m-d'), date("Y-m-d"), "ga:users,ga:sessions", $params );  
?><html>     
<?php echo $date->format('Y-m-d') . " - ".date("Y-m-d"). "\n";?>    
<table>  
<tr>     
<?php    
//Printing column headers
foreach($data->getColumnHeaders() as $header){
 print "<td>".$header['name']."</td>";      
}       
?>      
</tr>       
<?php       
//printing each row.
foreach ($data->getRows() as $row) {        
 print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";      
}    
//printing the total number of rows
?>      
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>     
</table>     
</html>  

#1


If you want to access your own account, then I suggest you look into using a service account.

如果您想访问自己的帐户,我建议您考虑使用服务帐户。

Once you have created the service account on the Google Developer console, remember to go to your Google Analytics account and give the service account email address access to your Google Analytics data at the Account level. You can read about how to do that here Google Service Account PHP code ripped from that tutorial.

在Google Developer控制台上创建服务帐户后,请务必访问您的Google Analytics帐户,并在帐户级别向服务帐户电子邮件地址授予对Google Analytics数据的访问权限。您可以在此处阅读有关如何执行此操作的Google服务帐户PHP代码。

session_start();        
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';        
/************************************************   
 The following 3 values an befound in the setting   
 for the application you created on Google      
 Developers console.         Developers console.
 The Key file should be placed in a location     
 that is not accessable from the web. outside of 
 web root.       web root.

 In order to access your GA account you must    
 Add the Email address as a user at the     
 ACCOUNT Level in the GA admin.         
 ************************************************/
$client_id = 'xxx-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = 'xxx-nk421gjc2v8mlr2qnmmqaak04ntb1dbp@developer.gserviceaccount.com';   
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';     
$client = new Google_Client();      
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);    
// seproate additional scopes with a comma   
$scopes ="https://www.googleapis.com/auth/analytics.readonly";  
$cred = new Google_Auth_AssertionCredentials(    
 $Email_address,         
 array($scopes),        
 $key        
 );     
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {        
 $client->getAuth()->refreshTokenWithAssertion($cred);      
}       
$service = new Google_Service_Analytics($client);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
//calulating start date  
$date = new DateTime(date("Y-m-d"));     
$date->sub(new DateInterval('P10D'));    
//Adding Dimensions
$params = array('dimensions' => 'ga:userType'); 
// requesting the data  
$data = $service->data_ga->get("ga:78110423", $date->format('Y-m-d'), date("Y-m-d"), "ga:users,ga:sessions", $params );  
?><html>     
<?php echo $date->format('Y-m-d') . " - ".date("Y-m-d"). "\n";?>    
<table>  
<tr>     
<?php    
//Printing column headers
foreach($data->getColumnHeaders() as $header){
 print "<td>".$header['name']."</td>";      
}       
?>      
</tr>       
<?php       
//printing each row.
foreach ($data->getRows() as $row) {        
 print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";      
}    
//printing the total number of rows
?>      
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>     
</table>     
</html>