8

我想编写一个从 GA 导入网络统计数据的 PHP 脚本。该脚本可通过 Web 前端访问(用于触发导入)并位于本地服务器 (127.0.0.1) 上。

在此处输入图像描述

正如我从文档中了解到的那样,有两种用于验证和使用核心 API 的选项:

  1. API 密钥- 仅授予对统计信息的访问权限
  2. OAuth2 - 完全授权

如果我正确理解 OAuth2 的机制,那么在我的场景中这不是一个选项,因为我无法指定回调 URL。我想到了一些骇人听闻的解决方案——比如建立一个从浏览器直接连接到 GA 的 Web 配置文件身份验证,然后通过 JavaScript 获取数据并将其提供给导入脚本——但我宁愿避免使用这种解决方案。还因为触发导入过程的浏览器交互将来可能会被 cron 作业取代。

API 密钥似乎正是我想要的,但来自浏览器的 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]

回复:

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

URL虽然应该没问题。除了关键参数之外,它与使用http://ga-dev-tools.appspot.com/explorer/生成的参数相同(在这种情况下使用 AOuth2)。API 密钥是新的。

然后再次生成一个新的 API 密钥给我带来了下一个不便,即显然该密钥仅在一天内有效。


所以归根结底,我的问题是:

是否可以在上述场景中获取数据,而无需每天手动进行身份验证或生成 API 密钥?

4

3 回答 3

5

正如已经建议的那样,使用这个库:https ://code.google.com/p/google-api-php-client/ 但是,不要使用 oauth,而是从 api 控制台创建一个服务帐户(只需选择服务器应用程序)。这将为您提供客户端 ID、标识服务帐户的电子邮件以及保存私钥的 *.p12 文件。

然后,您必须以管理员用户身份将服务帐户(电子邮件)添加到您的分析中,以获得所需的数据。

要使用该服务:

$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);

获取一些数据:

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

有关详细信息,请查看 api 文档。另外,请注意,有查询上限(除非您付费)

于 2013-02-14T16:43:37.783 回答
2

我认为要使其正常工作,您需要使用 OAuth 但稍作修改即可从服务器运行它。Google 将此身份验证方法称为“将 OAuth 2.0 用于 Web 服务器应用程序

如该页面所述,您可以使用 PHP 客户端库来完成身份验证。客户端库位于此处

有关如何使用此客户端库的示例位于同一项目的帮助页面上。请注意,您必须对代码进行一些修改,因为注释说将令牌存储在 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>";
}
于 2013-02-08T22:50:06.470 回答
2

我有类似的设置。您没有意识到的是,您可以将http://localhostorhttp://127.0.0.1或其他任何内容指定为源和回调 URL。您需要在本地服务器上设置一些 Web 界面,为具有 GA 访问权限的用户启动 OAuth 设置。请注意,这是一次。回调处理程序必须是这样的:

注意:此处使用的库与上一个答案相同,详细代码在包装器中。

$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

保存令牌后,您必须在客户端中设置它,然后再向 GA 发出请求以获取您的分析数据。像:

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); 

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;

我的 mysql 表具有id, title, send_to_emails, frequency, dimensions, metrics, filters, profile_id完全定义从 GA 生成的每个报告的列。您可以使用文档指标和维度列表以及您已经了解的沙盒测试器来玩弄它们。

于 2013-02-10T18:35:48.280 回答