如何获取谷歌分析实时activeUsers在php



我从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)Login Required'

当我尝试从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。

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

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

这个例子使用了books API。您可以通过执行以下操作将其更改为Google analytics API

$service = new Google_Service_Books($client);

改为

$service = new Google_Service_Analytics($client);

如果你有任何问题让我知道,我会看看如果我不能给你一个完整的例子使用谷歌分析与服务帐户。

其他注释:

在这个问题的时候,实时API仍处于测试阶段,你必须请求访问。通常需要24小时才能进入。

我已经成功地显示当前数据从我的GA帐户到我的网站与下面的php代码:

<?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();
}
?>

相关内容

  • 没有找到相关文章

最新更新