使用Google Analytics API v3获取属性时返回空数组求助
问题:GA4账号调用Analytics v3 API获取属性返回空数组
已成功连接Google Analytics(GA4),本人GA账号和用于认证的服务账号均为两个GA4属性的管理员,但调用Analytics v3版本API获取属性时返回空数组,响应显示账号连接正常但属性列表为空。
运行的Node.js脚本
const { google } = require("googleapis"); const analytics = google.analytics("v3"); const credentials = require("./service-account-credentials.json"); const client = new google.auth.JWT( credentials.client_email, null, credentials.private_key, ["https://www.googleapis.com/auth/analytics.readonly"] ); client.authorize((err) => { if (err) { console.log(err); return; } //call to get account name analytics.management.accounts.list({ auth: client }, (err, result) => { if (err) { console.log(err); } else { console.log( `Google analytics connection is working and your account is: ${result.data.items[0].name}` ); //call to get properties analytics.management.webproperties.list( { auth: client, accountId: "12345678", }, (err, result) => { if (err) { console.log(err); } else { console.log( `Available properties: ${JSON.stringify(result.data.items)}` ); } } ); } }); });
输出结果
Google analytics connection is working and your account is: markusets Available properties: []
已确认账号与服务账号拥有属性管理员权限,凭证正确(认证成功并获取到账号名称),尝试多种方法获取属性仍返回空数组,寻求问题原因及解决方案。
原因分析
- Google Analytics v3 API仅适配Universal Analytics(UA)属性,不支持GA4属性。你管理的是GA4属性,因此调用v3接口的
webproperties.list无法识别到GA4属性,返回空数组。 - 账号名称能正常获取是因为账号层级的接口在v3中是通用的,但属性层级的接口只对UA属性生效。
解决方案
要获取GA4属性,需使用Google Analytics Admin API(v1版本),以下是修改后的Node.js示例代码:
const { google } = require("googleapis"); const analyticsadmin = google.analyticsadmin("v1"); const credentials = require("./service-account-credentials.json"); const client = new google.auth.JWT( credentials.client_email, null, credentials.private_key, ["https://www.googleapis.com/auth/analytics.readonly"] ); async function listGA4Properties() { try { await client.authorize(); // 获取账号列表,定位目标账号 const accountsResponse = await analyticsadmin.accounts.list({ auth: client }); const targetAccount = accountsResponse.data.accounts.find(acc => acc.name.includes("12345678")); if (!targetAccount) { console.log("未找到目标账号"); return; } // 获取该账号下的GA4属性 const propertiesResponse = await analyticsadmin.properties.list({ auth: client, filter: `parent:${targetAccount.name}` }); console.log(`Google analytics connection is working and your account is: ${targetAccount.displayName}`); console.log(`Available GA4 properties: ${JSON.stringify(propertiesResponse.data.properties)}`); } catch (err) { console.error(err); } } listGA4Properties();
注意事项:
- 确保
googleapis包版本支持Analytics Admin API,若未安装可执行npm install googleapis。 - 服务账号需拥有GA4属性的查看者或管理员权限,并已在GA4后台完成授权配置。
内容的提问来源于stack exchange,提问作者markus etschmayer
相关产品推荐
相关产品推荐

