简体   繁体   English

从本地服务器请求Google Analytics数据

[英]request Google Analytics data from a local server

I want to write a PHP script that imports web stats data from GA. 我想编写一个从GA导入Web统计数据的PHP脚本。 The script is accessible through a web front end (for triggering the import) and resides on a local server (127.0.0.1). 该脚本可通过Web前端访问(用于触发导入)并驻留在本地服务器(127.0.0.1)上。

在此输入图像描述

As I understood from the documentation is that there are two options for authenticating and using the core API: 我从文档中了解到,验证和使用核心API有两种选择:

  1. API key - grants only access to statistics API密钥 - 仅授予对统计信息的访问权限
  2. OAuth2 - full authorization OAuth2 - 完全授权

If I understand the mechanics of OAuth2 correctly then this is not an option in my scenario because I cannot specify a callback URL. 如果我正确理解OAuth2的机制,那么在我的场景中这不是一个选项,因为我无法指定回调URL。 Hacky solutions come to my mind - like establishing a web profile authentication directly connecting to GA from the browser and then fetching the data by JavaScript and feeding it to the import script - but I would prefer to refrain from such solutions. 我想到了Hacky解决方案 - 比如建立一个从浏览器直接连接到GA的Web配置文件身份验证,然后通过JavaScript获取数据并将其提供给导入脚本 - 但我宁愿避免使用这些解决方案。 Also because the browser interaction triggering the import process might be substituted with a cron job in the future. 另外,因为将来可能会使用cron作业替换触发导入过程的浏览器交互。

The API key seems to be exactly what I want but the GET request from the browser fails. API密钥似乎正是我想要的,但来自浏览器的GET请求失败。

GET request: GET请求:

https://www.googleapis.com/analytics/v3/data/ga
  ?ids=ga:[profile ID]
  &start-date=2013-01-01&end-date=2013-01-05
  &metrics=ga:visits
  &key=[the API key]

Response: 响应:

{
  error: {
  errors: [
    {
      domain: "global",
      reason: "required",
      message: "Login Required",
      locationType: "header",
      location: "Authorization"
    }
  ],
  code: 401,
  message: "Login Required"
  }
}

The URL though should be fine. 虽然URL应该没问题。 Except for the key parameter it is the same as the one generated with http://ga-dev-tools.appspot.com/explorer/ which is also working (AOuth2 is used in that case). 除了关键参数外,它与http://ga-dev-tools.appspot.com/explorer/生成的关键参数相同,它也有效(在这种情况下使用AOuth2)。 The API key is fresh. API密钥是新鲜的。

Then again generating a new API key confronts me with the next inconveniency which is that apparently the key is only valid for a day. 然后再次生成一个新的API密钥使我面临下一个不便之处,即显然密钥仅在一天内有效。


So at the end of the day my question is this: 所以在一天结束时我的问题是:

Is it possible to fetch data in the above described scenario without having to authenticate manually or generate API keys on a daily basis? 是否可以在上述方案中获取数据,而无需每天手动进行身份验证或生成API密钥?

As already suggested, use this library: https://code.google.com/p/google-api-php-client/ but, instead of using oauth, create a service account from the api console (just select server application). 如上所述,请使用此库: https//code.google.com/p/google-api-php-client/但不是使用oauth,而是从api控制台创建服务帐户 (只需选择服务器应用程序)。 This will provide you with a client id, an email that identify the service account, and *.p12 file holding the private key. 这将为您提供客户端ID,标识服务帐户的电子邮件以及包含私钥的* .p12文件。

You then have to add the service account (the email) to your analytics as an admin user in order to get the data you need. 然后,您必须以管理员用户身份将服务帐户(电子邮件)添加到分析中,以便获取所需的数据。

To use the service: 要使用该服务:

$client = new Google_Client();
$client->setApplicationName('test');

$client->setAssertionCredentials(
    new Google_AssertionCredentials(
        EMAIL,
        array('https://www.googleapis.com/auth/analytics.readonly'),
        file_get_contents(PRIVATE_KEY_FILEPATH)
    )
);
$client->setClientId(CLIENT_ID);
$client->setAccessType('offline_access');

$analytics = new Google_AnalyticsService($client);

To get some data: 要获得一些数据:

$analytics->data_ga->get(PROFILE_ID, $date_from, $date_to, $metrics, $optParams)

For the details check api docs. 有关详细信息,请查看api文档。 Also, be careful, there is a query cap (unless you pay) 另外,要小心,有一个查询上限(除非你支付)

I think to get this working, you need to use OAuth but with a slight modification to run it from server. 我认为要实现这一点,您需要使用OAuth,但需要稍加修改才能从服务器运行它。 Google calls this auth method " Using OAuth 2.0 for Web Server Applications " Google将此auth方法称为“ 将OAuth 2.0用于Web服务器应用程序

As described on that page, you can use a PHP client library to get the authentication done. 如该页面所述,您可以使用PHP客户端库来完成身份验证。 The client library is located here . 客户端库位于此处

An example example on how to use this client library are on the same project's help pages . 有关如何使用此客户端库的示例示例位于同一项目的帮助页面上 Note that you'll have to make some modifications to the code as the comments say to store the token in db and to refresh it regularly. 请注意,您必须对代码进行一些修改,因为注释表示将令牌存储在db中并定期刷新它。

<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';

// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();

$client = new Google_Client();
$client->setApplicationName('Google+ PHP Starter Application');
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('insert_your_oauth2_client_id');
$client->setClientSecret('insert_your_oauth2_client_secret');
$client->setRedirectUri('insert_your_oauth2_redirect_uri');
$client->setDeveloperKey('insert_your_simple_api_key');
$plus = new Google_PlusService($client);

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {
  $activities = $plus->activities->listActivities('me', 'public');
  print 'Your Activities: <pre>' . print_r($activities, true) . '</pre>';

  // We're not done yet. Remember to update the cached access token.
  // Remember to replace $_SESSION with a real database or memcached.
  $_SESSION['token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
  print "<a href='$authUrl'>Connect Me!</a>";
}

I have a similar setup. 我有类似的设置。 The thing that you don't realize is that you can specify a http://localhost or http://127.0.0.1 or anything else as an origin and callback URL. 您没有意识到的是您可以指定http://localhosthttp://127.0.0.1或其他任何内容作为源和回调URL。 You need to setup some web interface on your local server that initiates an OAuth setup for the user with the GA access. 您需要在本地服务器上设置一些Web界面,以便为具有GA访问权限的用户启动OAuth设置。 Note that this is one time. 请注意,这是一次。 The callback handler must be something like this: 回调处理程序必须是这样的:

Note: The libraries used here are the same as the previous answer, the detailed code is in the wrapper. 注意:此处使用的库与上一个答案相同,详细代码在包装器中。

$redirect = 'http://' . $_SERVER['HTTP_HOST'] . '/content/business-intelligence';
if (isset($_GET['code'])) {
    require_once 'GAPI.php';
    $client = GAPI::init(); //create client instance of Google_Client
    $client->authenticate(); //convert auth code to access token
    $token = $client->getAccessToken();
    $retVal = CF_GAPI::persistToken($token); //save token
    if($retVal)
        $redirect .= "?new_token";
    else
        $redirect .= "?bad_token";
}
header('Location: ' . $redirect); //redirect to bi index

Once you have saved the token saved, you must set it in the client before making requests to GA to get your analytics data. 保存已保存的令牌后,必须先将其设置在客户端中,然后再向GA请求获取分析数据。 Like: 喜欢:

try {
    $token = GAPI::readToken(); //read from persistent storage
} catch (Exception $e) {
    $token = FALSE;
}

if($token == FALSE) {
    $logger->crit("Token not set before running cron!");
    echo "Error: Token not set before running cron!";
    exit;
}

$client = GAPI::init(); //instance of Google_Client
$client->setAccessToken($token); 

The GAPI::init() is implemented as follows: GAPI::init()实现如下:

$client = new Google_Client();
$client->setApplicationName(self::APP_NAME);

$client->setClientId(self::CLIENT_ID);
$client->setClientSecret(self::CLIENT_SECRET);
$client->setRedirectUri(self::REDIRECT_URI);
$client->setDeveloperKey(self::DEVELOPER_KEY);

//to specify that the token is stored offline
$client->setAccessType('offline');

//all results will be objects
$client->setUseObjects(true);

//tell that this app will RO from Analytics
$client->setScopes('https://www.googleapis.com/auth/analytics.readonly');

return $client;

My mysql table has columns like id, title, send_to_emails, frequency, dimensions, metrics, filters, profile_id which completely define each report to the generated from GA. 我的mysql表包含id, title, send_to_emails, frequency, dimensions, metrics, filters, profile_id ,它们完全定义了从GA生成的每个报告。 You can play around with them using the documentation , list of metrics & dimensions and the sandbox tester that you already know about. 您可以使用文档指标和维度列表以及您已经了解的沙箱测试器来解决这些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM