2013-02-06 31 views
8

我想编写一个从脚本中导入网站统计数据的PHP脚本。该脚本可通过Web前端访问(用于触发导入)并驻留在本地服务器(127.0.0.1)上。从本地服务器请求Google Analytics(分析)数据

enter image description here

当我从文档理解是,有用于验证和使用核心API两种选择:

  1. API密钥 - 只授予统计
  2. 的OAuth2访问 - 充分授权

如果我正确理解OAuth2的机制,那么在我的方案中这不是一个选项,因为我无法指定回调URL。 Hacky的解决方案出现在我脑海里 - 比如建立一个从浏览器直接连接到GA的Web配置认证,然后通过JavaScript获取数据并将其提供给导入脚本 - 但我宁愿不要这样的解决方案。另外,因为触发导入过程的浏览器交互将来可能会被cron作业取代。

API键似乎正是我想要的,但来自浏览器的GET请求失败。

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密钥面对我的下一个inconveniency这是很明显,关键是唯一有效的一天。


在这一天,我的问题结束

所以是这样的:

是否有可能无需手动认证或产生每天API密钥来获取在上述情况下的数据?

+2

拿在[授权方式]好好看看(https://developers.google.com/analytics/devguides/reporting/core/v3/gdataAuthorization #common_oauth)可用。有2个应该为你工作。 ** Web服务器**和**服务帐户**。使用[Web服务器](https://developers.google.com/accounts/docs/OAuth2WebServer)方法,您仍然需要通过oAuth,但您只需要执行一次。之后,您将获得一个刷新令牌,您可以使用该令牌在需要时生成更多访问令牌,而无需再次通过oAuth流。 [服务帐户](https://developers.google.com/accou – Eduardo

+0

好吧,也许这是诀窍,但我仍然对完整的回答感兴趣,同时也提到了其他提到的点 – Raffael

回答

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文档。此外,要小心,有一个查询帽(除非你支付)

+0

阻止我使用这种方法的事情是**丧失灵活性**。如果我必须迁移到另一个GA帐户,我需要获得新的服务凭证,或者如果我必须从两个不同的帐户获取数据,我必须使用欺骗手段。最后,这只是我选择的选择! – Birla

+0

我授予这个答案的赏金,因为(至少表面上)它似乎解决我的问题比其他答案更直接。我还没有找到时间来处理这个项目。只要我确实知道如何在我的案例中完成这项工作,我将自己标记答案或写一个答案。 – Raffael

2

我认为得到这个工作,你需要使用OAuth,但有轻微的修改,以从服务器上运行它。谷歌称这种权威性方法“Using OAuth 2.0 for Web Server Applications

该网页上所描述的,你可以使用PHP客户端库来完成认证。客户端库位于here

如何使用此客户端库的一个例子例子是在同一项目上的help pages。请注意,您必须对代码进行一些修改,如注释中所述将代码存储在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>"; 
} 
+0

我没有' insert_your_oauth2_redirect_uri' – Raffael

+0

要接受这个答案,你必须解释如何处理这个问题(没有重定向URI),或者如何以及为什么我错误理解了这个URI的含义。更喜欢一个不粘贴谷歌示例代码,而是一个工作示例,如何获取一些有意义的内容,例如foo /等某些URL的访问次数 – Raffael

+1

在您的设置中,不是reqirect uri只是您的计算机的地址。在认证后重定向用户,我不认为它验证了URL,并且因为没有验证,所以你可以指定http://127.0.0.1/page_that_reads_the_auth_token。 – Avi

2

我有一个类似的设置。你不知道的是,你可以指定一个http://localhosthttp://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()实现如下:

​​

我的MySQL表有像id, title, send_to_emails, frequency, dimensions, metrics, filters, profile_id列,每个报告完整地定义从GA的产生。你可以使用你已经知道的documentation,和sandbox tester玩弄他们。

相关问题