从Google实时API(GA4)获取当前活跃用户的数量。

huangapple go评论61阅读模式
英文:

Get a count of currently active users from Google RealTime API (GA4)

问题

我正在尝试获取当前查看我的网站的人数。随着Google Analytics即将从UA切换到GA4,我认为最好使用GA4,但文档,特别是API的文档,相当薄弱。我认为我需要查询Realtime API,但我在构建请求时遇到了困难。目前,我卡在授权步骤上,但我不确定首先是否有意义。我已经在Google Analytics中创建了一个服务帐户。

以下是我目前拼凑在一起的代码,从各种来源中获取,目前正在给我带来401错误:

<div id="active-users"></div>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta name="google-signin-client_id" content="{SERVICE_CLIENT_ID}.apps.googleusercontent.com">

<script>
  // 加载Google Analytics API客户端库
  gapi.load('client', function () {
    gapi.client.init({
      client_id: '{SERVICE_CLIENT_ID}',
      apiKey: '{API_KEY}'
    }).then(function () {
      gapi.client.request({
        path: '/v1/data/realtime:get',
        params: {
          ids: 'GA4:{PROPERTY_ID}',
          metrics: 'rt:activeUsers'
        }
      }).then(function (response) {
        var activeUsers = response.result.totalsForAllResults['rt:activeUsers'];
        document.getElementById('active-users').innerHTML = '活跃用户:' + activeUsers;
      });
    });
  });
</script>

编辑:
我正在尝试遵循此文档,这似乎相关,但我找不到如何将其转化为客户端库的信息。

英文:

I'm trying to get a count of the number of people currently viewing my site. With Google Analytics about to switch over to GA4 from UA, I figure it's best to use GA4 but the documentation--especially for the API--is pretty weak. I believe I need to query the Realtime API but I'm having trouble putting together the request to do it. Right now I'm stuck on the authorization step, but I'm not really sure any of it makes sense in the first place. I've created a service account in Google Analytics.

Here's what I have at the moment, cobbled together from a variety of sources, currently giving me a 401 error:

&lt;div id=&quot;active-users&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;https://apis.google.com/js/client.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://apis.google.com/js/platform.js&quot; async defer&gt;&lt;/script&gt;
&lt;meta name=&quot;google-signin-client_id&quot; content=&quot;{SERVICE_CLIENT_ID}.apps.googleusercontent.com&quot;&gt;

&lt;script&gt;
  // Load the Google Analytics API client library
  gapi.load(&#39;client&#39;, function () {
    gapi.client.init({
      client_id: &#39;{SERVICE_CLIENT_ID}&#39;,
      apiKey: &#39;{API_KEY}&#39;
    }).then(function () {
      gapi.client.request({
        path: &#39;/v1/data/realtime:get&#39;,
        params: {
          ids: &#39;GA4:{PROPERTY_ID}&#39;,
          metrics: &#39;rt:activeUsers&#39;
        }
      }).then(function (response) {
        var activeUsers = response.result.totalsForAllResults[&#39;rt:activeUsers&#39;];
        document.getElementById(&#39;active-users&#39;).innerHTML = &#39;Active users: &#39; + activeUsers;
      });
    });
  });
&lt;/script&gt;

EDIT:
I am trying to follow this documentation, which seems relevant, but I can't find any information on how to translate this to the Client Library

答案1

得分: 1

以下是已翻译的内容:

这是一个可工作的示例:https://polydactyl-plain-seatbelt.glitch.me/

一些建议:

  1. 有关实时API方法本身的详细信息
  2. 有关Google JS API客户端
  3. 由于其代码是公开的,无法使用服务帐户授权JS API客户端。相反,您需要创建OAuth客户端ID
英文:

Here is a working example: https://polydactyl-plain-seatbelt.glitch.me/

Some notes:

  1. Details about the realtime API method itself
  2. Details about Google JS API client
  3. It's impossible to use Service Accounts authorisation with JS API client due to it's public code source. Instead you need to create OAuth Client ID.

答案2

得分: -1

从我理解的内容来看,您遇到了API身份验证错误。假设您已经创建了Google Cloud控制台,并为您的项目启用了Google Analytics API。

尝试以下身份验证方法:

const { google } = require('googleapis');
const { BetaAnalyticsData } = require('@google-analytics/data');
const keyPath = 'service_account_key.json';

// 使用私钥进行身份验证
const auth = new google.auth.GoogleAuth({
  keyFile: keyPath,
  scopes: ['https://www.googleapis.com/auth/analytics'],
});

// 创建客户端对象
const client = new BetaAnalyticsData({
  auth: auth,
});

// 使用客户端对象进行API请求
const request = {
  property: 'properties/<YOUR-PROPERTY-ID>',
  metrics: [
    {
      name: 'activeUsers',
    },
  ],
};
client.runRealtimeReport({ request }).then((response) => {
  console.log(response.data);
});

您可以从文档中获取更多信息。

您提供的示例是基于Realtime API编写的,可以考虑以下方式:

const { BetaAnalyticsDataClient } = require('@google-analytics/data');
const keyPath = '/path/to/service_account_key.json';

// 使用私钥进行身份验证
const client = new BetaAnalyticsDataClient({
  credentials: {
    keyFilePath: keyPath,
  },
});

// 使用客户端对象进行API请求
const request = {
  property: 'properties/<YOUR-PROPERTY-ID>',
  metrics: [
    {
      name: 'activeUsers',
    },
  ],
};
client.runRealtimeReport({ request }).then((response) => {
  const activeUsers = response.data.totals[0].values[0];
  document.getElementById('active-users').innerHTML = '活跃用户:' + activeUsers;
});

<details>
<summary>英文:</summary>
From what i can understand, you are facing API authentication error. 
Assuming you&#39;ve created google cloud console, enable google analytic API for your project etc.
Try the following authentication method:
const { google } = require(&#39;googleapis&#39;);
const { BetaAnalyticsData } = require(&#39;@google-analytics/data&#39;);
const keyPath = &#39;service_account_key.json&#39;;
// Authenticate using the private key
const auth = new google.auth.GoogleAuth({
keyFile: keyPath,
scopes: [&#39;https://www.googleapis.com/auth/analytics&#39;],
});
// Create a client object
const client = new BetaAnalyticsData({
auth: auth,
});
// Make API requests using the client object
const request = {
property: &#39;properties/&lt;YOUR-PROPERTY-ID&gt;&#39;,
metrics: [
{
name: &#39;activeUsers&#39;,
},
],
};
client.runRealtimeReport({ request }).then((response) =&gt; {
console.log(response.data);
});
You can get more information from its [documentation][1].
The example you&#39;ve provided could be written considering Realtime API.
const { BetaAnalyticsDataClient } = require(&#39;@google-analytics/data&#39;);
const keyPath = &#39;/path/to/service_account_key.json&#39;;
// Authenticate using the private key
const client = new BetaAnalyticsDataClient({
credentials: {
keyFilePath: keyPath,
},
});
// Make API requests using the client object
const request = {
property: &#39;properties/&lt;YOUR-PROPERTY-ID&gt;&#39;,
metrics: [
{
name: &#39;activeUsers&#39;,
},
],
};
client.runRealtimeReport({ request }).then((response) =&gt; {
const activeUsers = response.data.totals[0].values[0];
document.getElementById(&#39;active-users&#39;).innerHTML = &#39;Active users: &#39; + activeUsers;
});
[1]: https://github.com/googleapis/google-api-nodejs-client
</details>

huangapple
  • 本文由 发表于 2023年2月14日 06:15:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定