Google Analytics(分析)V4客户端访问我们的应用

发布于 2025-02-12 00:49:48 字数 1246 浏览 3 评论 0原文

我们在PHP中有一个Web应用程序,对于我们的客户,我们已经准备好连接到Google Analytics(分析)UA。我使用“ google/apiclient”:“^2.0”,它可以使用我们的客户在管理中单击按钮,然后运行一个遵循代码:

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

我从 https://console.cloud.google.com/ - > OAuth 2.0客户端ID

然后将客户端重定向到Google登录,并允许在我们的应用程序的GA数据中加速。然后将代码重新定向,生成访问令牌。有了这个令牌,我可以获取他的GA UA数据,并将其显示给我们管理中的图表。它的工作原理,但是现在我得到了GA UA将会结束的信息,我需要为UA V4创建相同的程序。但是在给GA V4的文档中,我发现的内容: https://develoveler.google.google。 com/ananalytics/devguides/reporting/data/v1 不是信息如何为我们的客户处理它。只有授权过度服务帐户,我必须履行自己的凭据。凭证。也就是说,要通过OAuth 2.0客户端ID将其重定向到Google,并允许访问我们的应用程序以读取其数据。有可能吗?

谢谢您的帮助,很抱歉我的英语不好

We have a web application in PHP, for our clients we have prepared connect to google analytics UA. I use "google/apiclient": "^2.0", it works that our clients click on button in our administration and then is runned a followed code:

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

The credentials i get from https://console.cloud.google.com/ -> OAuth 2.0 Client IDs

then the client is redirected to google where he log in, and allow acces to his GA data for our app. then is redirected back with code is generated access token. With this token i can get his GA UA data and show it to graphs in our administration. It works allright, but now i get information that GA UA will be end, and i need to create the same proces for UA V4. But in documentation to GA V4 what i found: https://developers.google.com/analytics/devguides/reporting/data/v1
Is not information how to process it for our clients. There is only authorisation over service account, that i must donwload my own credentials.json to service account but it allow me only acces to my private account, but i need it to work the same as before, so for other clients without having to upload credentials.json. That is, to be redirected to google via OAuth 2.0 Client IDs and allow access to our application to read their data. Is it even possible?

Thank you for help, and sorry for my bad english

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

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

发布评论

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

评论(2

马蹄踏│碎落叶 2025-02-19 00:49:48

这应该让您开始。我将Google API PHP客户端库中的OAuth2方法组合在一起,并将其应用于新库。

它不是最佳的,但可以起作用。下面的代码用于安装应用程序而不是Web。它不会主持工作。

<?php


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

use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;

putenv('GOOGLE_APPLICATION_CREDENTIALS=C:\YouTube\dev\credentials.json');  // Installed / native / desktop Client credetinals.

$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 BetaAnalyticsDataClient( [
    '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"]
        ],
    ] ),
] );

$response = $service->runReport([
    'property' => 'properties/[YOUR_PROPERTY_ID]'
]);

foreach ($response->getRows() as $row) {
    foreach ($row->getDimensionValues() as $dimensionValue) {
        print 'Dimension Value: ' . $dimensionValue->getValue() . PHP_EOL;
    }
}


function getClient()
{
    $client = new Client();
    $client->setApplicationName('Google analytics data beta Oauth2');
    $client->setScopes('https://www.googleapis.com/auth/analytics');
    $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 = 'token.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;
}

This should give you a start. I am combining the OAuth2 methods from the Google API php client library and applying them to the new library.

Its not optimal but it works. Code below is for installed application not web. Its not going to work hosted.

<?php


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

use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;

putenv('GOOGLE_APPLICATION_CREDENTIALS=C:\YouTube\dev\credentials.json');  // Installed / native / desktop Client credetinals.

$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 BetaAnalyticsDataClient( [
    '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"]
        ],
    ] ),
] );

$response = $service->runReport([
    'property' => 'properties/[YOUR_PROPERTY_ID]'
]);

foreach ($response->getRows() as $row) {
    foreach ($row->getDimensionValues() as $dimensionValue) {
        print 'Dimension Value: ' . $dimensionValue->getValue() . PHP_EOL;
    }
}


function getClient()
{
    $client = new Client();
    $client->setApplicationName('Google analytics data beta Oauth2');
    $client->setScopes('https://www.googleapis.com/auth/analytics');
    $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 = 'token.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;
}
乜一 2025-02-19 00:49:48

并且请如何获取列表属性的列表流,我有一个代码来获取GA4属性:

$this->SetGa4ClientAdmin();
$accounts = $this->ga4_admin->listAccounts();
$this->data['accounts_v4'] = array();

foreach ($accounts as $account) {
  $this->data['accounts_v4'][$account->getName()] = array('name' => $account->getDisplayName(), 'childrens' => array());
  try {
    $properties = $this->ga4_admin->ListProperties('parent:' . $account->getName());
    foreach ($properties AS $property) {
      $this->data['accounts_v4'][$account->getName()]['childrens'][$property->getName()] = $property->getDisplayName();
    }
  } catch (Exception $ex) {
    die("error: " . $ex->getMessage());
  }
}

在每个属性中,我需要获得GA4流的测量ID。

我需要得到这个

And please how to get list streams of listed properties, I have a code to get GA4 properties:

$this->SetGa4ClientAdmin();
$accounts = $this->ga4_admin->listAccounts();
$this->data['accounts_v4'] = array();

foreach ($accounts as $account) {
  $this->data['accounts_v4'][$account->getName()] = array('name' => $account->getDisplayName(), 'childrens' => array());
  try {
    $properties = $this->ga4_admin->ListProperties('parent:' . $account->getName());
    foreach ($properties AS $property) {
      $this->data['accounts_v4'][$account->getName()]['childrens'][$property->getName()] = $property->getDisplayName();
    }
  } catch (Exception $ex) {
    die("error: " . $ex->getMessage());
  }
}

At every property I need to get measurement ID of GA4 streams.

I need to get this

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