google-analytics - 带身份验证的 Google Analytics 4 API

标签 google-analytics google-analytics-api google-api-php-client google-analytics-4

我的网站已经有了通用分析,我们通过对用户进行身份验证在我们的仪表板上显示不同的分析配置文件数据。因为每个用户都可以访问不同的分析配置文件。所以我们在 UA 中遵循的步骤是,

  • 要求用户进行身份验证。
  • 获取授权码并创建访问 token 。
  • 将访问 token 传递给 listManagementProfiles API 以获取经过身份验证的用户的配置文件列表。
  • 根据选定的配置文件,我们显示分析数据。 (我们使用谷歌服务分析库)

示例代码:

if (!class_exists('Google_Client')) {
    require_once '/lib/google-api-php-client-master/src/Google/Client.php';
    require_once '/lib/google-api-php-client-master/src/Google/Service/Analytics.php';
}

$this->client = new Google_Client();
$this->client->setApprovalPrompt('force');
$this->client->setAccessType('offline');
$this->client->setClientId('************');
$this->client->setClientSecret('*************');
$this->client->setRedirectUri('*****************');
$this->client->setScopes('https://www.googleapis.com/auth/analytics');
$this->client->setDeveloperKey('*************************');

$this->service = new Google_Service_Analytics($this->client);
$accessToken = $this->client->authenticate($authCode);
if ($accessToken) {
   $this->client->setAccessToken($accessToken);
        return true;
} else {
   return false;
}

        

我卡在哪里了?

  • 我已查看 GA4 文档并按照文档中提供的步骤进行操作。我已经在我的一个 Google 帐户中为 GA4 创建了帐户/属性。
  • 然后我从谷歌控制台启用了分析服务。
  • 创建服务帐户。
  • 已下载 JSON 文件。
  • here 下载了谷歌管理客户端库

GA4示例代码:

require 'vendor/autoload.php';

use Google\Analytics\Admin\V1alpha\AnalyticsAdminServiceClient;
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;

putenv('GOOGLE_APPLICATION_CREDENTIALS=config.json');

$client = new AnalyticsAdminServiceClient();

$accounts = $client->listAccountSummaries();

但这不需要 access_token 并且没有访问 token ,它允许获取帐户列表。我不希望手动为每个分析帐户授予对服务帐户的访问权限。

我希望我的用户对我的网站进行身份验证,然后仅根据它执行其余过程。

我怎样才能做到这一点?

我还看到一些东西说 GA4 没有配置文件( View ),那么我如何访问 GA4 中的配置文件数据?我是否需要将帐户/属性列表列出来供用户选择?

我需要网站上的推荐、自然搜索、用户和 session 数据。 GA4 的哪个端点提供此数据? 我需要使用任何其他库吗?

最佳答案

我觉得你很接近。您只是在混合使用 oauth 和服务帐户。

通过您的 UA 分析代码,您正在使用 Google 分析报告 API/Google 分析管理 API 来请求用户访问他们的 Google 分析帐户。您当前正在使用 Oauth2 请求用户访问“他们的”谷歌分析帐户。这些是他们控制的帐户。

虽然您当前使用的是服务帐户,但您可以通过 GA4 帐户连接到 Google Analytics 管理 API。

服务帐户必须预先授权。它们旨在与开发者拥有的帐户一起使用。您需要切换它以使用 Oauth2 而不是服务帐户。这样,用户将通过自己的帐户进行身份验证。

Google 分析管理员 Oauth2

这是 Oauth2 的示例。

<?php

// composer composer require google/analytics-admin

require 'vendor/autoload.php';
use Google\Client;

use Google\Analytics\Admin\V1alpha\AnalyticsAdminServiceClient;

putenv('GOOGLE_APPLICATION_CREDENTIALS=C:\YouTube\dev\credentials.json');  // Installed app credentials.

$credentials =  getenv('GOOGLE_APPLICATION_CREDENTIALS');

$myfile = file_get_contents($credentials, "r") ;

$clientObj = json_decode($myfile);

$client = getClient();

$tokenResponse = $client->getAccessToken();

print_r($tokenResponse);
print_r($tokenResponse["access_token"]);


$service = new AnalyticsAdminServiceClient( [
    'credentials' => Google\ApiCore\CredentialsWrapper::build( [
        'scopes'  => [
            'https://www.googleapis.com/auth/analytics',
            'openid',
            'https://www.googleapis.com/auth/analytics.readonly',
        ],
        'keyFile' => [
            'type'          => 'authorized_user',
            'client_id'     => $clientObj->installed->client_id,
            'client_secret' => $clientObj->installed->client_secret,
            'refresh_token' => $tokenResponse["refresh_token"]
        ],
    ] ),
] );

$accounts = $service->listAccounts();

foreach ($accounts as $account) {
    print 'Found account: ' . $account->getName() . PHP_EOL;
}


function getClient()
{
    $client = new Client();
    $client->setApplicationName('Google analytics admin beta Oauth2');
    $client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
    $client->setAuthConfig(getenv('GOOGLE_APPLICATION_CREDENTIALS'));
    $client->setAccessType('offline');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'tokenAdmin.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

请注意,这是一个控制台应用程序,而不是网络应用程序。您可能需要调整它才能使用 web,但您应该能够复制您的 UA 授权代码并按照我在此处显示的那样转储 token 。

代码无耻地复制自Simple How to Integrate php with Google analytics admin api.

关于google-analytics - 带身份验证的 Google Analytics 4 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72870015/

相关文章:

php - 如何在 Google 分析中测量 Greasemonkey 下载量

javascript - 无需身份验证即可从 javascript 访问 Google Analytics API 数据

google-analytics - 如何使用 Google Analytics Core Reporting API 获取原始用户计时数据

javascript - 如何在您的开发环境中捕获 'ga is not defined'

javascript - 谷歌分析嵌入 api 取消授权

php - 如何使用 google-php-api-client 设置 Google Play `inAppUpdatePriority`

javascript - 用于跟踪单个页面的 2 个域的 Google Analytics 代码

google-analytics - 如何在 Google Analytics 报告中将 www 域与非 www 域合并

php - 如何在 YouTube 上上传大文件

php - Google Analytics PHP API - 获取用户电子邮件