如何从服务器端后台服务访问Google AnalyticsAPI? [英] How to access Google Analytics API from a serverside background service?

查看:197
本文介绍了如何从服务器端后台服务访问Google AnalyticsAPI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过背景cron作业将谷歌分析数据导入到自己的数据库中,无需用户每次验证。

如何通过用户互动获取Google Analytics(分析)OAuth访问令牌正如我以前所问。使用OAuth将不起作用,因为它需要用户交互。根据 Google Analytics API参考 OAuth以及Access令牌可用于在每个会话库上访问一次页面的统计信息。然而,我正在寻找一种持久的方式来在后台服务中实现此功能。



如何在没有用户身份验证的情况下访问Google Analytics或获取无效的访问令牌? / p>

解决方案

假设有问题的帐户是您自己的,您可以通过服务帐户。请确保您将帐户级别的服务帐户电子邮件地址读取权限授予Google分析帐户,并且可以读取您的数据。

 <?php 
session_start();
require_once'Google / Client.php';
require_once'Google / Service / Analytics.php';

/ ***************************************** *******
您在Google
开发者控制台上创建的应用程序的设置
中会出现以下3个值。
密钥文件应放置在
的位置,该位置不能从网站访问。在
web根目录之外。

为了访问您的GA帐户,您必须
在GA管理员的
ACCOUNT级别以用户身份添加电子邮件地址。
********************************************** ** /
$ client_id ='1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$ Email_address ='1046123799103-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);

//使用逗号分隔其他作用域
$ 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();

//计算开始日期
$ date = new DateTime(date(Y-m-d));
$ date-> sub(new DateInterval('P10D'));

//添加尺寸
$ params = array('dimensions'=>'ga:userType');
//请求数据
$ data = $ service-> data_ga-> get(ga:78110423,$ date-> format('Ym-d'),date( Ymd),ga:users,ga:sessions,$ params);


?>< html>
<?php echo $ date->格式('Y-m-d')。 - .date(Y-m-d)。 \\\
;?>
< table>
< tr>
<?php
//打印列标题
foreach($ data-> getColumnHeaders()as $ header){
print< td>。$ header [ '名称']。 < / TD> 中;
}
?>
< / tr>
<?php
//打印每一行。
foreach($ data-> getRows()as $ row){
print< tr>< td>。$ row [0]。< / td>< td> ;。$行[1]。 < / TD>< TD> 中。$行[2]。 < / TD>< / TR> 中;
}

//打印总行数
?>
< tr>< td colspan =2>返回的行<?php print $ data-> getTotalResults();?> < / TD>< / TR>
< / table>
< / html>
<?php

?>

源自教程的代码



如果这不是您的帐户,那么您可以使用正常的Oauth2方法,请求用户进行身份验证你一旦使用刷新令牌就可以访问数据。使用上一个问题中的代码。


I'd like to pull in data from google analytics into an own database through an background cron job without the user having to authenticate every time.

I do know how to get an Google Analytics OAuth Access Token with user interaction as I asked previously. Using OAuth won't work, since it requires user interaction. According to Google Analytics API Reference OAuth as well as an Access Token can be used to access the stats of an page once on a per session base. However I'm looking for an persistent way to implement this in an background service.

How can I access google analytics without user authentication or get an none expireing access token?

解决方案

Assuming the account in question is your own you can us a service account. Make sure that you give the service account email address read access at the Account level to the Google analytics account and it will be able to read your data.

<?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.
  The Key file should be placed in a location
  that is not accessable from the web. outside of 
  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 = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-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>
<?php

?>

code ripped from tutorial Google Service Account with PHP

If this is not your account then you can use the normal Oauth2 method ask the use to authenticate you once then using the refresh token you will be able to access the data. Using the code from your previous question.

这篇关于如何从服务器端后台服务访问Google AnalyticsAPI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆