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

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

我从 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。

那么我如何在其中实现登录过程(无需访问 google 站点)?

我试过下面的代码...

$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 需要身份验证。听起来您想访问自己的数据而不是其他用户拥有的数据。为此,您需要创建一个 service account.

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

该示例使用了 Boooks API。您可以通过执行以下操作将其更改为 Google Analytics API

$service = new Google_Service_Books($client);

改为

$service = new Google_Service_Analytics($client);

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

其他注意事项:

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

关于php - 如何在 php 中获取谷歌分析实时 activeUsers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23632814/

相关文章:

google-api - 获取 Google 日历 API 限制

google-api - 从数据源中修补或删除权重 - 删除其他应用程序插入的数据

javascript - AJAX 不会重新加载页面

php - 在 PHP 中存储上次运行的脚本

c# - 您在哪里可以找到 GoogleOAuth2AuthenticationOptions?

oauth-2.0 - 对于 B2B 企业 REST API,在 oAuth2 中请求访问 token 是否会使之前授予该客户端 ID 的访问 token 失效?

google-api - Google Drive API不够文件权限错误

php - 将简单的 php 函数变成变量

PHP 从数据库中提取数据时将所有非英文字符替换为 null

php - 如何使用来自 discord oauth2 登录的访问 token 来获取用户信息