【问题标题】:How to fetch google analytics realtime activeUsers in php?如何在 php 中获取谷歌分析实时 activeUsers?
【发布时间】:2014-12-22 21:20:26
【问题描述】:

我从 https://github.com/google/google-api-php-client 并尝试了下面的代码...

$client->setApplicationName("Analytics");
$client->setDeveloperKey("key");
$service = new Google_Service_Analytics($client);

$optParams = array(
    'dimensions' => 'rt:medium');

try {
  $results = $service->data_realtime->get(
      'ga:profileid',
      'rt:activeUsers',
      $optParams);
  // Success.
} catch (apiServiceException $e) {
  // Handle API service exceptions.
  $error = $e->getMessage();
}
print_r($results);

显示错误(401)需要登录'

当我尝试来自https://console.developers.google.com/project/apps~rational-photon-578/apiui/api/analytics/method/analytics.data.realtime.get的电话时

我获得了所需的实时用户所属的 profileid。

那么我该如何实现登录过程(无需访问谷歌网站)?

我试过下面的代码...

$client_id              = 'xxxxxxxxxxxxxxx';
$service_account_name   = 'xxxxxxxxxxxxxxxx@developer.gserviceaccount.com';
$key_file_location      = 'location of .p12 keyfile';

$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");

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

$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/analytics'),
$key
);

$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
} 

$_SESSION['service_token'] = $client->getAccessToken();
echo $_SESSION['service_token'];
$service = new Google_Service_Analytics($client);


$optParams = array(
'dimensions' => 'rt:medium');


try {
$results = $service->data_realtime->get(
  'ga:profileid',
  'rt:activeUsers',
  $optParams);
// Success.
} catch (apiServiceException $e) {
// Handle API service exceptions.
$error = $e->getMessage();
}
print_r($results);

我在这里获取 access_token 和详细信息...但分析数据获取失败,因为错误“权限不足”

当我使用提到的配置文件 ID 从谷歌控制台进行测试时,我得到了结果。

【问题讨论】:

    标签: php oauth-2.0 google-api google-oauth google-analytics-api


    【解决方案1】:

    访问 Google Analytics API 需要身份验证。听起来您想访问自己的数据,而不是其他用户拥有的数据。为此,您需要创建一个service account.

    您正在使用的 Github 上的 php 客户端库,有一个使用服务帐户的示例,您可以找到它service-account.php

    该示例使用 Books API。您可以通过执行以下操作将其更改为 Google 分析 API

    $service = new Google_Service_Books($client);
    

    改成

    $service = new Google_Service_Analytics($client);
    

    如果您有任何问题,请告诉我,我会看看能否给您一个完整的示例,使用 Google Analytics(分析)和服务帐户。

    给其他人的注意事项:

    在提出这个问题时,实时 API 仍处于测试阶段,您必须请求访问。通常需要 24 小时才能访问。

    【讨论】:

    • 嘿,谢谢你的回答.. 它真的帮了很多忙 :) 现在我收到一个错误“权限不足”,无法访问实时用户。我试过下面的代码code $optParams = array('dimensions' => 'rt:medium');尝试 { $results = $service->data_realtime->get('ga:123123123', 'rt:activeUsers', $optParams); // 成功。 } catch (apiServiceException $e) { // 处理 API 服务异常。 $error = $e->getMessage(); } code
    • Realtime api 仍处于测试阶段,您必须请求访问。谷歌它我现在无法访问 PC。通常需要 24 小时才能获得访问权限。
    • 我将电子邮件地址(从服务帐户获取)添加到分析用户帐户并授予权限。所以需要 24 小时才能访问该电子邮件地址?
    • 实际上,我认为您的 Google 帐户是您用来在 Google 应用程序控制台中制作应用程序的帐户,但我不确定。
    • 我尝试了两个电子邮件地址.. 但没有运气。如果谷歌服务有任何访问延迟,将等待一段时间
    【解决方案2】:

    我已使用以下 php 代码成功地将我的 GA 帐户中的当前数据显示到我的网站:

    <?php
    
    //Cloning Google API's
    //git clone https://github.com/google/google-api-php-client.git
    
    //Setting include_path in PHP.ini
    //include_path = ".:/usr/local's/lib/php:/path/to/google-api-php-client/src"
    
    //Alternatively, you can set the same ini directive dynamically in your code.
    $lib_path = $_SERVER['DOCUMENT_ROOT'] . '/path/relative/to/DOCUMENT_ROOT/';
    set_include_path(get_include_path() . PATH_SEPARATOR . $lib_path . 'google-api-php-client/src');
    
    require_once 'Google/Client.php';
    require_once 'Google/Service/Analytics.php';
    
    $keyfile = 'path/relative/to/DOCUMENT_ROOT/xxxxxxxxxxxxxxxx.p12'; // keyfile location   
    $gaEmail = 'xxxxxxxxxxxxxxxx@developer.gserviceaccount.com'; // email you added to GA
    $gaAuth = 'https://www.googleapis.com/auth/analytics.readonly';
    
    // Create Client Object
    $client = new Google_Client();
    $client->setApplicationName('Google_Analytics'); // name of your app
    $client->setClientId('xxxxxxxxxxxxxxxx.apps.googleusercontent.com'); // from API console
    $client->setAssertionCredentials(new Google_Auth_AssertionCredentials($gaEmail, array($gaAuth), file_get_contents($keyfile)));
    
    /* Sample Grabbing Analytics data
    $service = new Google_Service_Analytics($client);
    var_dump($service->management_accounts->listManagementAccounts());
    $response = $service->data_ga->get(
        'ga:87364223', // profile id
        '2014-09-01', // start date
        '2014-09-10', // end date
        'ga:uniquePageviews',
        array(
            'dimensions' => 'ga:pagePath',
            'sort' => '-ga:uniquePageviews',
            'filters' => 'ga:pagePath=~/[a-zA-Z0-9-]+/[a-zA-Z0-9-]+', // http://localhost/browse/style/3#showmoreexample url regex filter
            'max-results' => '25'
        )
    );
    var_dump($response);
    */
    
    // Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
    $profile_id = 'ga:xxxxxxxx';
    $start = 'yesterday';
    $end = 'today';
    
    try {
        $service = new Google_Service_Analytics($client);
        $results = $service->data_ga->get($profile_id, $start, $end, 'ga:visits');
        echo $results['totalsForAllResults']['ga:visits'];
    } 
    catch(Exception $e) {
        echo 'There was an error : - ' . $e->getMessage();
    }
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多