我的网站已经有了通用的分析,我们正在通过认证用户在仪表板上显示不同的分析配置文件数据。因为每个用户都可以访问不同的分析配置文件。所以我们在UA中遵循的步骤是,
样本代码:
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示例代码:
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的哪个端点提供这些数据?还有其他我需要使用的库吗?
发布于 2022-07-05 13:15:39
我觉得你们关系很好。你只是把oauth和服务帐户混在一起。
使用UA分析代码,您将使用/请求用户访问他们的Google分析帐户。您目前正在使用Oauth2请求用户访问“他们”的谷歌分析帐户。这些是他们控制的账户。
使用您的GA4帐户,您将连接到google管理api,尽管您目前使用的是一个服务帐户。
服务帐户必须预先授权。它们用于开发人员拥有的帐户。您需要使用Oauth2而不是服务帐户对其进行swtich处理。这样,用户就可以通过自己的帐户进行身份验证。
谷歌分析管理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应用程序。您可能需要将其用于web工作,但您应该能够复制您的UA auth代码并将令牌转储到其中,就像我在这里展示的那样。
从简单的如何集成php与谷歌分析管理api。中无耻地复制代码
发布于 2022-07-06 05:45:53
若要使用访问令牌获取帐户摘要,可以使用Google客户端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
)
)
)https://stackoverflow.com/questions/72870015
复制相似问题