首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GoogleAnalytics4API与认证

GoogleAnalytics4API与认证
EN

Stack Overflow用户
提问于 2022-07-05 13:09:37
回答 2查看 952关注 0票数 3

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

  • 要求用户进行身份验证。
  • 获取代码并创建访问令牌。
  • 将访问令牌传递给listManagementProfiles API以获取经过身份验证的用户的配置文件列表。
  • 根据所选择的轮廓显示分析数据。(我们使用google服务分析库)

样本代码:

代码语言:javascript
复制
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文件。
  • 这里下载google管理客户端库

GA4示例代码:

代码语言:javascript
复制
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,如果没有访问令牌,它允许获取帐户列表。我不想让每个分析帐户访问服务帐户的手动过程。

我希望我的用户认证到我的网站,然后只做基于它的rest过程。

我怎样才能做到这一点?

我还读到了一些GA4没有概要文件(视图)的内容,那么如何访问GA4中的概要文件数据呢?是否需要将帐户/属性列表向下列出以供用户选择?

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

EN

回答 2

Stack Overflow用户

发布于 2022-07-05 13:15:39

我觉得你们关系很好。你只是把oauth和服务帐户混在一起。

使用UA分析代码,您将使用/请求用户访问他们的Google分析帐户。您目前正在使用Oauth2请求用户访问“他们”的谷歌分析帐户。这些是他们控制的账户。

使用您的GA4帐户,您将连接到google管理api,尽管您目前使用的是一个服务帐户。

服务帐户必须预先授权。它们用于开发人员拥有的帐户。您需要使用Oauth2而不是服务帐户对其进行swtich处理。这样,用户就可以通过自己的帐户进行身份验证。

谷歌分析管理Oauth2

下面是一个带有Oauth2的示例。

代码语言:javascript
复制
<?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应用程序。您可能需要将其用于web工作,但您应该能够复制您的UA auth代码并将令牌转储到其中,就像我在这里展示的那样。

简单的如何集成php与谷歌分析管理api。中无耻地复制代码

票数 2
EN

Stack Overflow用户

发布于 2022-07-06 05:45:53

若要使用访问令牌获取帐户摘要,可以使用Google客户端PHP库

这是工作代码

代码语言:javascript
复制
<?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());

输出

代码语言:javascript
复制
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
                )

        )

)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72870015

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档