Google Analytics(Analytics)4具有身份验证的API

发布于 2025-02-13 07:06:05 字数 2102 浏览 3 评论 0 原文

我的网站已经具有通用分析,我们正在通过对用户进行认证在仪表板上显示不同的分析资料数据。因为每个用户都可以访问不同的分析资料。因此,我们在UA中遵循的步骤是,

  • 请用户进行身份验证。
  • 获取验证代码并创建一个访问令牌。
  • 将访问令牌传递给ListManagementProfiles API,以获取身份验证用户的配置文件列表。
  • 基于所选配置文件,我们显示分析数据。 (我们使用Google Service Analytics库)

示例代码:

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的帐户/属性。
  • 然后,我从Google控制台启用了分析服务。
  • 创建的服务帐户。
  • 下载的JSON文件。

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并且没有访问令牌,它允许获取帐户列表。我不希望为每个分析帐户提供访问服务帐户的手动过程。

我希望我的用户能够验证我的网站,然后仅根据它进行休息过程。

我该如何实现?

我还阅读了GA4没有配置文件(视图)的东西,那么我如何访问GA4中的配置文件数据?我是否需要向用户列出帐户/属性列表以进行选择?

我需要网站上的推荐,有机搜索,用户和会话数据。 GA4的哪个端点提供此数据? 我还需要使用其他库吗?

My website already has universal analytics and we are displaying different analytics profile data on our dashboard by authenticating users. Because each user will have access to a different analytics profile. So the steps we follow in UA are,

  • Ask the user to authenticate.
  • Get auth code and create an access token.
  • Passing access token to listManagementProfiles API to get the list of profiles for the authenticated user.
  • Based on the selected profile we display the analytics data. (we use google service analytics library)

sample code:

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;
}

        

Where I'm stuck?

  • I've checked for the GA4 documentation and followed the steps provided in the doc. I have created the account/property for GA4 in one of my google accounts.
  • I then enabled the analytics service from google console.
  • Created service account.
  • Downloaded JSON file.
  • Downloaded the google admin client library from here

GA4 sample code:

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

But this does not require the access_token and without an access token, it allows to fetch the accounts lists. I don't want the manual process of giving access to the service account for each analytics account.

I want my user to authenticate to my website and then only do the rest process based on it.

How can I achieve that?

I also read something that GA4 does not have profiles(views), then how can I access the profile data in GA4? do I need to list down the accounts/properties list to the user for selection?

I need the referral, organic search, users, and session data on my website. What endpoint of GA4 provides this data?
Any other library do I need to use?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒解孤独 2025-02-20 07:06:05

我认为你很亲密。您只是在混合OAuth和服务帐户。

使用UA Analytics代码,您正在使用Google Analytics(Analytics)报告API / Google Analytics Management API请求用户访问其Google Analytics(分析)帐户。您当前正在使用OAuth2请求访问用户以访问“他们的” Google Analytics(分析)帐户。这些是他们控制的帐户。

使用GA4帐户,您正在连接到Google Analytics(Analytics)Admin API,尽管您当前正在使用服务帐户。

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

Google Analytics(Analytics)Admin Admin 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;
}

请注意,这是一个控制台应用,而不是网络应用程序。您可能必须对其进行Tweek进行处理才能使用Web,但是您应该能够复制UA auth Code并将令牌转储到我这里所示。

代码无耻地从

I think you are close. You are just mixing oauth and service account.

With your UA analytics code you are using the Google analytics reporting api / google analytics management api to request access of the user to access their Google analytics accounts. You are currently using Oauth2 to request access of a user to access "their" google analytics accounts. These are accounts that they control.

With your GA4 accounts you are connecting to the google analytics admin api though you are currently using a service account.

Service accounts must be pre authorized. They are intended for use with accounts that the developer owns. You need to swtich it to use Oauth2 and not a service account. This way the users will be authenticated to their own account.

Google analytics admin Oauth2

Here is a sample with 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;
}

Note this is a console app, not a web app. You may have to tweek it to work with web but you should just be able to copy your UA auth code and dump the tokens in as i have shown here.

Code shamelessly copied from Simple How to Integrate php with Google analytics admin api.

伴我心暖 2025-02-20 07:06:05

要使用访问令牌获取帐户摘要,您可以使用 google apis client for php

这是工作代码

<?php
require_once 'vendor/autoload.php';

use Google\Client;
use Google\Service\GoogleAnalyticsAdmin;

$access_token = 'ya29.xxxxxxx';

// Init Google Client and Set Access Token
$client = new Client();
$client->setAccessToken($access_token);

// GA Admin Service
$service = new GoogleAnalyticsAdmin($client);

// Fetch Account Summaries
$summary = $service->accountSummaries->listAccountSummaries();

// Output
print_r($summary->toSimpleObject());

输出

stdClass Object
(
    [accountSummaries] => Array
        (
            [0] => stdClass Object
                (
                    [account] => accounts/XXXXXXX
                    [displayName] => XXXXXXX
                    [name] => accountSummaries/XXXXXXX
                    [propertySummaries] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [displayName] => XXXXXXX GA4 Property
                                    [parent] => accounts/XXXXXXX
                                    [property] => properties/XXXXXXX
                                    [propertyType] => PROPERTY_TYPE_ORDINARY
                                )

                        )

                )

            [1] => stdClass Object
                (
                    [account] => accounts/XXXXXX
                    [displayName] => XXXXXXX accounts
                    [name] => accountSummaries/XXXXXX
                )

        )

)

To fetch Account Summaries using Access Token, you can use Google APIs Client Library for PHP

Here is the working code

<?php
require_once 'vendor/autoload.php';

use Google\Client;
use Google\Service\GoogleAnalyticsAdmin;

$access_token = 'ya29.xxxxxxx';

// Init Google Client and Set Access Token
$client = new Client();
$client->setAccessToken($access_token);

// GA Admin Service
$service = new GoogleAnalyticsAdmin($client);

// Fetch Account Summaries
$summary = $service->accountSummaries->listAccountSummaries();

// Output
print_r($summary->toSimpleObject());

Output

stdClass Object
(
    [accountSummaries] => Array
        (
            [0] => stdClass Object
                (
                    [account] => accounts/XXXXXXX
                    [displayName] => XXXXXXX
                    [name] => accountSummaries/XXXXXXX
                    [propertySummaries] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [displayName] => XXXXXXX GA4 Property
                                    [parent] => accounts/XXXXXXX
                                    [property] => properties/XXXXXXX
                                    [propertyType] => PROPERTY_TYPE_ORDINARY
                                )

                        )

                )

            [1] => stdClass Object
                (
                    [account] => accounts/XXXXXX
                    [displayName] => XXXXXXX accounts
                    [name] => accountSummaries/XXXXXX
                )

        )

)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文