英文:
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:
<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>
// Load the Google Analytics API client library
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 = 'Active users: ' + activeUsers;
});
});
});
</script>
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/
一些建议:
- 有关实时API方法本身的详细信息
- 有关Google JS API客户端
- 由于其代码是公开的,无法使用服务帐户授权JS API客户端。相反,您需要创建OAuth客户端ID。
英文:
Here is a working example: https://polydactyl-plain-seatbelt.glitch.me/
Some notes:
- Details about the realtime API method itself
- Details about Google JS API client
- 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've created google cloud console, enable google analytic API for your project etc.
Try the following authentication method:
const { google } = require('googleapis');
const { BetaAnalyticsData } = require('@google-analytics/data');
const keyPath = 'service_account_key.json';
// Authenticate using the private key
const auth = new google.auth.GoogleAuth({
keyFile: keyPath,
scopes: ['https://www.googleapis.com/auth/analytics'],
});
// Create a client object
const client = new BetaAnalyticsData({
auth: auth,
});
// Make API requests using the client object
const request = {
property: 'properties/<YOUR-PROPERTY-ID>',
metrics: [
{
name: 'activeUsers',
},
],
};
client.runRealtimeReport({ request }).then((response) => {
console.log(response.data);
});
You can get more information from its [documentation][1].
The example you've provided could be written considering Realtime API.
const { BetaAnalyticsDataClient } = require('@google-analytics/data');
const keyPath = '/path/to/service_account_key.json';
// Authenticate using the private key
const client = new BetaAnalyticsDataClient({
credentials: {
keyFilePath: keyPath,
},
});
// Make API requests using the client object
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 = 'Active users: ' + activeUsers;
});
[1]: https://github.com/googleapis/google-api-nodejs-client
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论