google-analytics

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Google Analytics

Google Analytics

Architecture

架构

ga4
is a standalone Python CLI that wraps three GA4 APIs:
  • Data API (v1beta + v1alpha) —
    ga4 data …
    — reporting, realtime, metadata, funnels, audience exports
  • Admin API (v1beta + v1alpha) —
    ga4 admin …
    — accounts, properties, streams, key events, custom dims/metrics, measurement secrets, links, audiences, access bindings, annotations
  • Measurement Protocol
    ga4 mp …
    — event ingestion (send + validate against debug endpoint)
All commands emit JSON to stdout with
indent=2
. Errors go to stderr as plain text with exit 1. Destructive operations require
--yes/-y
on the CLI; the skill adds an additional user-confirmation layer (see Destructive operations below).
Auth is OAuth-user-only via
ga4 auth login --client-secret <Desktop-OAuth-client.json>
. The CLI owns its own state at
~/.config/skills/ga4/
(not under the skill's path —
ga4
is usable outside this skill).
ga4
是一个独立的Python CLI工具,封装了三个GA4 API:
  • Data API(v1beta + v1alpha)——
    ga4 data …
    ——报表、实时数据、元数据、漏斗、受众导出
  • Admin API(v1beta + v1alpha)——
    ga4 admin …
    ——账号、媒体资源、数据流、关键事件、自定义维度/指标、测量密钥、链接、受众、访问绑定、注释
  • Measurement Protocol——
    ga4 mp …
    ——事件采集(发送+通过调试端点验证)
所有命令会将JSON格式的输出发送至标准输出,缩进为2。错误信息以纯文本形式发送至标准错误输出,退出码为1。破坏性操作需要在CLI中添加
--yes/-y
参数;本技能还额外增加了用户确认环节(详见下方破坏性操作部分)。
认证仅支持通过
ga4 auth login --client-secret <Desktop-OAuth-client.json>
进行OAuth用户认证。CLI的状态信息存储在
~/.config/skills/ga4/
目录下(不在技能路径下——
ga4
可在本技能之外独立使用)。

Before First Use

首次使用前准备

  1. Install
    uv sync --project /abs/path/to/skills/google-analytics
  2. Create an OAuth Desktop client in GCPhttps://console.cloud.google.com/apis/credentials → Create Credentials → OAuth client ID → Desktop app → download the JSON. ADC (
    gcloud auth application-default login
    ) is deliberately not supported — Google is phasing out analytics scopes on the default gcloud client ID.
  3. Auth
    ga4 auth login --client-secret /path/to/downloaded.json
    . A browser opens for consent. On a headless machine, open an SSH tunnel first:
    ssh -L 8086:localhost:8086 <this-host>
    and open the printed URL on a machine with a browser. Scopes default to readonly + edit + manage-users; override with
    --scope
    (repeatable) for provision / user-deletion.
  4. Grant GA access — in GA Admin → Access Management, add the Google account you just authed with as Viewer (reads) or Editor/Administrator (writes, user management). See
    references/setup.md
    for click-path.
  5. Default property (optional, recommended) —
    ga4 config set-property 123456789
    .
  6. Verify
    ga4 doctor
    should be all-green.
  1. 安装
    uv sync --project /abs/path/to/skills/google-analytics
  2. 在GCP中创建OAuth桌面客户端https://console.cloud.google.com/apis/credentials → 创建凭据 → OAuth客户端ID → 桌面应用 → 下载JSON文件。ADC(
    gcloud auth application-default login
    )未被支持——Google正逐步淘汰默认gcloud客户端ID的分析权限范围。
  3. 认证
    ga4 auth login --client-secret /path/to/downloaded.json
    。会打开浏览器进行授权。在无头机器上,需先建立SSH隧道:
    ssh -L 8086:localhost:8086 <this-host>
    ,然后在有浏览器的机器上打开打印出的URL。默认权限范围为只读+编辑+用户管理;如需资源配置/用户删除,可通过
    --scope
    参数(可重复使用)覆盖默认范围。
  4. 授予GA访问权限 — 在GA管理后台 → 访问管理中,将刚完成认证的Google账号添加为查看者(只读)或编辑者/管理员(可写入、管理用户)。点击路径详情可查看
    references/setup.md
  5. 默认媒体资源(可选,推荐设置) —
    ga4 config set-property 123456789
  6. 验证
    ga4 doctor
    应显示全绿状态。

Canonical invocation

标准调用方式

bash
uv run --project /path/to/skills/google-analytics ga4 <command> [args]
For brevity, examples below use
ga4
directly. When running from outside the skill directory, always use the full
uv run --project <abs-path>
form.
bash
uv run --project /path/to/skills/google-analytics ga4 <command> [args]
为简洁起见,以下示例直接使用
ga4
。在技能目录外运行时,请始终使用完整的
uv run --project <abs-path>
格式。

Destructive operations

破坏性操作

Before running any
delete
or
archive
subcommand, show the user the exact command (including target resource name) and ask for confirmation in conversation. Only pass
--yes/-y
after an affirmative answer in the current turn. Never chain multiple destructive ops without re-confirming each one.
The CLI's
--yes
flag is a non-interactive guardrail. The skill's job is to make sure a human explicitly agrees before a
properties delete
,
key-events delete
,
custom-dimensions archive
,
custom-metrics archive
,
audiences archive
,
access-bindings delete
,
access-bindings batch-delete
,
annotations delete
,
data-streams delete
,
measurement-secrets delete
,
links firebase-delete
,
links ads-delete
,
links bigquery-delete
,
properties submit-user-deletion
, or
accounts delete
is executed. If the user is in a hurry, still ask — a single clear confirmation is cheap compared to clobbering a production property.
在运行任何
delete
archive
子命令前,需向用户展示精确的命令(包括目标资源名称)并请求对话确认。仅在当前对话中得到肯定答复后,才可添加
--yes/-y
参数。切勿在未逐一确认的情况下链式执行多个破坏性操作。
CLI的
--yes
标志是非交互式防护机制。本技能的职责是确保在执行
properties delete
key-events delete
custom-dimensions archive
custom-metrics archive
audiences archive
access-bindings delete
access-bindings batch-delete
annotations delete
data-streams delete
measurement-secrets delete
links firebase-delete
links ads-delete
links bigquery-delete
properties submit-user-deletion
accounts delete
前,得到人类用户的明确同意。即使用户赶时间,也需进行确认——一次清晰的确认相比破坏生产环境媒体资源的代价要小得多。

Command index

命令索引

ga4 auth
,
ga4 config
,
ga4 doctor

ga4 auth
ga4 config
ga4 doctor

CommandPurposeMin scope
ga4 auth login --client-secret <path>
OAuth Desktop flown/a
ga4 auth status
Report OAuth credential statusn/a
ga4 auth whoami
Scopes and expiry on the current tokenreadonly
ga4 auth logout
Remove OAuth credentialsn/a
ga4 config set-property <id>
Persist default property (stored as
properties/<id>
)
n/a
ga4 config get default-property
Read defaultn/a
ga4 config show
Dump all confign/a
ga4 doctor
Health check (config, OAuth credentials, scopes, Admin API ping)readonly
Property ids accept either
123456789
or
properties/123456789
.
命令用途最低权限范围
ga4 auth login --client-secret <path>
OAuth桌面授权流程n/a
ga4 auth status
报告OAuth凭证状态n/a
ga4 auth whoami
当前令牌的权限范围和过期时间readonly
ga4 auth logout
删除OAuth凭证n/a
ga4 config set-property <id>
持久化默认媒体资源(存储格式为
properties/<id>
n/a
ga4 config get default-property
读取默认媒体资源n/a
ga4 config show
导出所有配置n/a
ga4 doctor
健康检查(配置、OAuth凭证、权限范围、Admin API连通性)readonly
媒体资源ID支持
123456789
properties/123456789
两种格式。

ga4 data
— Data API

ga4 data
— Data API

CommandPurposeMin scope
ga4 data run-report -p <id> -d <dims> -m <metrics> -s <start> -e <end>
Standard reportreadonly
ga4 data run-pivot-report -p <id> --request-json @body.json
Pivot reportreadonly
ga4 data batch-run-reports -p <id> --requests-json @bodies.json
Up to 5 reports in one callreadonly
ga4 data batch-run-pivot-reports -p <id> --requests-json @bodies.json
Up to 5 pivot reportsreadonly
ga4 data run-realtime-report -p <id> -d <dims> -m <metrics>
Last 30 (or 60 for GA360) minutesreadonly
ga4 data run-funnel-report -p <id> --request-json @funnel.json
Funnel analysis. Alpha.readonly
ga4 data check-compatibility -p <id> -d <dims> -m <metrics>
Validate dim+metric comboreadonly
ga4 data get-metadata -p <id>
Dimensions + metrics catalog for the property (pass
properties/0
for universal)
readonly
ga4 data audience-exports create --audience <name> -d <dims>
Create audience exportreadonly
ga4 data audience-exports get <name>
/
list
/
query <name>
Audience export lifecyclereadonly
Common
run-report
flags:
--dimension-filter-json
,
--metric-filter-json
,
--order-by-json
,
--metric-aggregation
,
--cohort-spec-json
,
--comparisons-json
,
--limit
,
--offset
,
--currency-code
,
--keep-empty-rows
,
--return-property-quota
,
--request-json
(full body override).
Filter/order/cohort JSON can be inline (
--dimension-filter-json '{"filter":...}'
) or a file (
--dimension-filter-json @/tmp/f.json
). See
references/data-api.md
for the filter grammar.
命令用途最低权限范围
ga4 data run-report -p <id> -d <dims> -m <metrics> -s <start> -e <end>
标准报表readonly
ga4 data run-pivot-report -p <id> --request-json @body.json
透视报表readonly
ga4 data batch-run-reports -p <id> --requests-json @bodies.json
单次调用最多生成5个报表readonly
ga4 data batch-run-pivot-reports -p <id> --requests-json @bodies.json
单次调用最多生成5个透视报表readonly
ga4 data run-realtime-report -p <id> -d <dims> -m <metrics>
最近30分钟(GA360为60分钟)的实时数据readonly
ga4 data run-funnel-report -p <id> --request-json @funnel.json
漏斗分析。Alpha版本readonly
ga4 data check-compatibility -p <id> -d <dims> -m <metrics>
验证维度+指标组合的兼容性readonly
ga4 data get-metadata -p <id>
获取媒体资源的维度+指标目录(传入
properties/0
获取通用目录)
readonly
ga4 data audience-exports create --audience <name> -d <dims>
创建受众导出任务readonly
ga4 data audience-exports get <name>
/
list
/
query <name>
受众导出任务生命周期管理readonly
run-report
常用参数:
--dimension-filter-json
--metric-filter-json
--order-by-json
--metric-aggregation
--cohort-spec-json
--comparisons-json
--limit
--offset
--currency-code
--keep-empty-rows
--return-property-quota
--request-json
(完整请求体覆盖)。
过滤/排序/同期群JSON可以是内联格式(
--dimension-filter-json '{"filter":...}'
)或文件路径(
--dimension-filter-json @/tmp/f.json
)。过滤语法详情请查看
references/data-api.md

ga4 admin accounts
— Accounts

ga4 admin accounts
— 账号管理

CommandPurposeMin scope
accounts list
/
get <id>
/
summaries-list
Read accountsreadonly
accounts update <id> --display-name …
Renameedit
accounts delete <id> --yes
Soft-deleteedit
accounts search-change-history <id>
Audit trailreadonly
accounts run-access-report <id> -d <dims> -m <metrics>
Who-accessed-what auditreadonly
accounts get-data-sharing-settings <id>
Read sharing settingsreadonly
accounts provision-ticket --display-name … --redirect-uri …
New-account provisioning ticketedit
命令用途最低权限范围
accounts list
/
get <id>
/
summaries-list
读取账号信息readonly
accounts update <id> --display-name …
修改账号名称edit
accounts delete <id> --yes
软删除账号edit
accounts search-change-history <id>
审计追踪readonly
accounts run-access-report <id> -d <dims> -m <metrics>
访问行为审计(谁访问了什么)readonly
accounts get-data-sharing-settings <id>
读取数据共享设置readonly
accounts provision-ticket --display-name … --redirect-uri …
新账号配置工单edit

ga4 admin properties
— Properties

ga4 admin properties
— 媒体资源管理

CommandPurposeMin scope
properties list --account <id>
/
get -p <id>
Read propertiesreadonly
properties create --parent <account> --display-name … --time-zone …
Createedit
properties update -p <id> --display-name …
Update (or
--body-json
+
--update-mask
)
edit
properties delete -p <id> --yes
Soft-deleteedit
properties get-data-retention -p <id>
/
update-data-retention …
Retention settingsedit
properties get-attribution-settings -p <id>
/
update…
Attribution model. Alpha.edit
properties get-signals-settings -p <id>
/
update…
Google Signals. Alpha.edit
properties run-access-report -p <id> …
Access audit at property scopereadonly
properties search-change-history -p <id>
Change historyreadonly
properties acknowledge-user-data -p <id> --acknowledgement …
Prereq for Measurement Protocol secretsedit
properties submit-user-deletion -p <id> --user-id …
GDPR deletion. Alpha. Irreversible.user.deletion
命令用途最低权限范围
properties list --account <id>
/
get -p <id>
读取媒体资源信息readonly
properties create --parent <account> --display-name … --time-zone …
创建媒体资源edit
properties update -p <id> --display-name …
更新媒体资源(或使用
--body-json
+
--update-mask
edit
properties delete -p <id> --yes
软删除媒体资源edit
properties get-data-retention -p <id>
/
update-data-retention …
数据保留设置edit
properties get-attribution-settings -p <id>
/
update…
归因模型。Alpha版本edit
properties get-signals-settings -p <id>
/
update…
Google Signals设置。Alpha版本edit
properties run-access-report -p <id> …
媒体资源级别的访问审计readonly
properties search-change-history -p <id>
变更历史readonly
properties acknowledge-user-data -p <id> --acknowledgement …
Measurement Protocol密钥的前置要求edit
properties submit-user-deletion -p <id> --user-id …
GDPR用户数据删除。Alpha版本。不可撤销。user.deletion

ga4 admin data-streams
,
measurement-secrets

ga4 admin data-streams
measurement-secrets

CommandPurposeMin scope
data-streams list -p <id>
/
get -p <id> <stream>
Read streamsreadonly
data-streams create -p <id> --type WEB_DATA_STREAM --display-name … --uri …
Create web streamedit
data-streams create --type ANDROID_APP_DATA_STREAM --package-name …
Androidedit
data-streams create --type IOS_APP_DATA_STREAM --bundle-id …
iOSedit
data-streams update -p <id> <stream> --display-name …
Renameedit
data-streams delete -p <id> <stream> --yes
Deleteedit
data-streams get-global-site-tag -p <id> <stream>
gtag snippet. Alpha.readonly
data-streams get-enhanced-measurement -p <id> <stream>
/
update…
EM settings. Alpha.edit
data-streams get-data-redaction -p <id> <stream>
/
update…
PII redaction. Alpha.edit
measurement-secrets list -p <id> <stream>
/
get
,
create --display-name …
,
update
,
delete
MP secrets CRUD (requires
acknowledge-user-data
first)
edit
命令用途最低权限范围
data-streams list -p <id>
/
get -p <id> <stream>
读取数据流信息readonly
data-streams create -p <id> --type WEB_DATA_STREAM --display-name … --uri …
创建网页数据流edit
data-streams create --type ANDROID_APP_DATA_STREAM --package-name …
创建Android应用数据流edit
data-streams create --type IOS_APP_DATA_STREAM --bundle-id …
创建iOS应用数据流edit
data-streams update -p <id> <stream> --display-name …
修改数据流名称edit
data-streams delete -p <id> <stream> --yes
删除数据流edit
data-streams get-global-site-tag -p <id> <stream>
gtag代码片段。Alpha版本readonly
data-streams get-enhanced-measurement -p <id> <stream>
/
update…
增强型测量设置。Alpha版本edit
data-streams get-data-redaction -p <id> <stream>
/
update…
PII脱敏设置。Alpha版本edit
measurement-secrets list -p <id> <stream>
/
get
,
create --display-name …
,
update
,
delete
MP密钥增删改查(需先完成
acknowledge-user-data
操作)
edit

ga4 admin key-events
,
custom-dimensions
,
custom-metrics

ga4 admin key-events
custom-dimensions
custom-metrics

CommandPurposeMin scope
key-events list -p <id>
/
get
/
create --event-name … --counting-method …
/
update
/
delete --yes
Conversion events (replaces
conversionEvents
)
edit
custom-dimensions list -p <id>
/
get
/
create --parameter-name … --display-name … --scope EVENT
/
update
/
archive --yes
Custom dimsedit
custom-metrics list -p <id>
/
get
/
create --parameter-name … --measurement-unit …
/
update
/
archive --yes
Custom metricsedit
命令用途最低权限范围
key-events list -p <id>
/
get
/
create --event-name … --counting-method …
/
update
/
delete --yes
转化事件管理(替代
conversionEvents
edit
custom-dimensions list -p <id>
/
get
/
create --parameter-name … --display-name … --scope EVENT
/
update
/
archive --yes
自定义维度管理edit
custom-metrics list -p <id>
/
get
/
create --parameter-name … --measurement-unit …
/
update
/
archive --yes
自定义指标管理edit

ga4 admin links
— Third-party links

ga4 admin links
— 第三方链接管理

CommandPurposeMin scope
links firebase-list -p <id>
/
firebase-create --firebase-project projects/…
/
firebase-delete <id> --yes
Firebase linksedit
links ads-list -p <id>
/
ads-create --customer-id …
/
ads-update
/
ads-delete <id> --yes
Google Ads linksedit
links bigquery-list -p <id>
/
bigquery-get
/
bigquery-create --project projects/… [--daily-export …]
/
bigquery-update
/
bigquery-delete <id> --yes
BigQuery links. Alpha.edit
命令用途最低权限范围
links firebase-list -p <id>
/
firebase-create --firebase-project projects/…
/
firebase-delete <id> --yes
Firebase链接管理edit
links ads-list -p <id>
/
ads-create --customer-id …
/
ads-update
/
ads-delete <id> --yes
Google Ads链接管理edit
links bigquery-list -p <id>
/
bigquery-get
/
bigquery-create --project projects/… [--daily-export …]
/
bigquery-update
/
bigquery-delete <id> --yes
BigQuery链接管理。Alpha版本edit

ga4 admin audiences
,
access-bindings
,
annotations
— all alpha

ga4 admin audiences
access-bindings
annotations
— 均为Alpha版本

CommandPurposeMin scope
audiences list -p <id>
/
get
/
create --body-json @audience.json
/
archive --yes
Audiences. Alpha.edit
access-bindings list --account <id>
(or
--property
) /
get
/
create --user <email> -r predefinedRoles/admin
/
update
/
delete --yes
Per-user roles. Alpha.manage.users
access-bindings batch-{create,get,update,delete} --bindings-json @list.json
Batch operations. Alpha.manage.users
annotations list -p <id>
/
get
/
create --title … --annotation-date YYYY-MM-DD
(or
--start-date/--end-date
) /
update
/
delete --yes
Reporting-data annotations. Alpha.edit
Alpha endpoints may change shape without notice; keep an eye on
google-analytics-admin
release notes if you script against them.
命令用途最低权限范围
audiences list -p <id>
/
get
/
create --body-json @audience.json
/
archive --yes
受众管理。Alpha版本edit
access-bindings list --account <id>
(或
--property
) /
get
/
create --user <email> -r predefinedRoles/admin
/
update
/
delete --yes
按用户分配角色。Alpha版本manage.users
access-bindings batch-{create,get,update,delete} --bindings-json @list.json
批量操作。Alpha版本manage.users
annotations list -p <id>
/
get
/
create --title … --annotation-date YYYY-MM-DD
(或
--start-date/--end-date
) /
update
/
delete --yes
报表数据注释管理。Alpha版本edit
Alpha版本端点的格式可能会无预告变更;如果通过脚本调用这些端点,请关注
google-analytics-admin
的发布说明。

ga4 mp
— Measurement Protocol

ga4 mp
— Measurement Protocol

CommandPurpose
ga4 mp send --measurement-id G-XXX --api-secret … --events-json @events.json
Fire-and-forget send to
/mp/collect
ga4 mp validate --measurement-id G-XXX --api-secret … --events-json @events.json
Debug endpoint — returns per-event validation findings
Single-event shortcut:
--event-name purchase --event-params '{"value":12.34,"currency":"USD"}'
. For Firebase/app streams, replace
--measurement-id
with
--firebase-app-id
.
--endpoint eu
routes through the EU regional endpoint.
MP limits (enforced locally before sending): 25 events/request, 40-char event names, 25 params/event. See
references/admin-api.md
for full limits including param value length.
命令用途
ga4 mp send --measurement-id G-XXX --api-secret … --events-json @events.json
无回调发送事件至
/mp/collect
ga4 mp validate --measurement-id G-XXX --api-secret … --events-json @events.json
通过调试端点验证——返回每个事件的验证结果
单事件快捷方式:
--event-name purchase --event-params '{"value":12.34,"currency":"USD"}'
。对于Firebase/应用数据流,将
--measurement-id
替换为
--firebase-app-id
--endpoint eu
参数可将请求路由至欧盟区域端点。
MP限制(发送前本地校验):每个请求最多25个事件,事件名称最多40字符,每个事件最多25个参数。完整限制(包括参数值长度)请查看
references/admin-api.md

Writing reports

报表编写示例

bash
undefined
bash
undefined

Last 7 days of active users by country

过去7天按国家统计的活跃用户数

ga4 data run-report -p 123456789 -d country -m activeUsers -s 7daysAgo -e today
ga4 data run-report -p 123456789 -d country -m activeUsers -s 7daysAgo -e today

Week-over-week comparison with two date ranges via request JSON

通过请求JSON实现周环比对比(两个日期范围)

cat <<'EOF' > /tmp/wow.json { "dimensions": [{"name": "deviceCategory"}], "metrics": [{"name": "engagementRate"}, {"name": "sessions"}], "date_ranges": [ {"start_date": "7daysAgo", "end_date": "yesterday", "name": "this_week"}, {"start_date": "14daysAgo", "end_date": "8daysAgo", "name": "last_week"} ] } EOF ga4 data run-report -p 123456789 --request-json @/tmp/wow.json
cat <<'EOF' > /tmp/wow.json { "dimensions": [{"name": "deviceCategory"}], "metrics": [{"name": "engagementRate"}, {"name": "sessions"}], "date_ranges": [ {"start_date": "7daysAgo", "end_date": "yesterday", "name": "this_week"}, {"start_date": "14daysAgo", "end_date": "8daysAgo", "name": "last_week"} ] } EOF ga4 data run-report -p 123456789 --request-json @/tmp/wow.json

Filter: only mobile, only pages matching /blog/*

过滤条件:仅移动端,仅路径匹配/blog/*的页面

cat <<'EOF' > /tmp/filter.json {"andGroup": {"expressions": [ {"filter": {"fieldName": "deviceCategory", "stringFilter": {"value": "mobile"}}}, {"filter": {"fieldName": "pagePath", "stringFilter": {"matchType": "BEGINS_WITH", "value": "/blog/"}}} ]}} EOF ga4 data run-report -p 123456789 -d pagePath -m sessions -s 7daysAgo -e today
--dimension-filter-json @/tmp/filter.json

For deep filter grammar (AND/OR/NOT, string/numeric/between/in-list filter types), the valid metric-aggregation set, cohort specs, and the "quota token" math, read `references/data-api.md`.
cat <<'EOF' > /tmp/filter.json {"andGroup": {"expressions": [ {"filter": {"fieldName": "deviceCategory", "stringFilter": {"value": "mobile"}}}, {"filter": {"fieldName": "pagePath", "stringFilter": {"matchType": "BEGINS_WITH", "value": "/blog/"}}} ]}} EOF ga4 data run-report -p 123456789 -d pagePath -m sessions -s 7daysAgo -e today
--dimension-filter-json @/tmp/filter.json

关于复杂过滤语法(AND/OR/NOT、字符串/数值/范围/列表过滤类型)、有效的指标聚合集合、同期群规则以及“配额令牌”计算,请阅读`references/data-api.md`。

Admin safety

管理安全注意事项

  • Always
    list
    /
    get
    first
    before
    update
    /
    delete
    /
    archive
    . Validate you're targeting the right resource.
  • Use
    search-change-history
    to audit recent changes before making new ones, and to find who made the last change to a resource.
  • Alpha endpoints may change shape. If you get an unexpected schema error, check the
    google-analytics-admin
    package version and the alpha changelog.
  • update_mask
    — most admin updates require a field mask. The CLI auto-computes it from flag-based updates, but for
    --body-json
    updates you must pass
    --update-mask
    explicitly.
  • Scopes — the CLI requests the union of scopes its commands need. If a command 403s with "insufficient permissions", re-auth with a broader scope (see Before First Use).
  • 更新/删除/归档前务必先执行list/get。确认目标资源正确无误。
  • 使用search-change-history:在进行新变更前审计最近的更改记录,查看谁最后修改了该资源。
  • Alpha版本端点格式可能变更。如果遇到意外的架构错误,请检查
    google-analytics-admin
    包版本和Alpha版本更新日志。
  • update_mask:大多数管理更新需要字段掩码。CLI会根据参数自动计算掩码,但使用
    --body-json
    更新时,必须显式传入
    --update-mask
    参数。
  • 权限范围:CLI会请求其所有命令所需的权限范围集合。如果命令返回403“权限不足”错误,请使用更广泛的权限范围重新认证(详见首次使用前准备)。

Funnel / audience / access patterns

漏斗/受众/访问模式

  • Funnels (
    run-funnel-report
    )
    are built as an array of steps, each with a filter expression. The response has two sub-reports — funnel table and funnel visualization. See
    references/data-api.md
    for step-design patterns (sequential vs. any-order steps, breakdown dimensions, continuous vs. direct).
  • Audiences (
    audiences create
    ) have a deeply nested schema (filter clauses, scopes, sequences). Build the JSON separately and pass
    --body-json @audience.json
    . Start from an existing audience (
    audiences get
    ) to see the shape.
  • Access bindings use
    predefinedRoles/*
    role names. Common:
    predefinedRoles/no-cost-data
    ,
    predefinedRoles/read-and-analyze
    ,
    predefinedRoles/editor
    ,
    predefinedRoles/admin
    . Changes at account scope apply to all properties.
  • 漏斗(run-funnel-report):由一系列步骤组成,每个步骤带有过滤表达式。响应包含两个子报表——漏斗表格和漏斗可视化。步骤设计模式(顺序/任意顺序步骤、细分维度、连续/直接转化)请查看
    references/data-api.md
  • 受众(audiences create):具有深度嵌套的架构(过滤规则、范围、序列)。请单独构建JSON文件,然后通过
    --body-json @audience.json
    传入。可从现有受众(
    audiences get
    )获取格式模板。
  • 访问绑定:使用
    predefinedRoles/*
    角色名称。常用角色:
    predefinedRoles/no-cost-data
    predefinedRoles/read-and-analyze
    predefinedRoles/editor
    predefinedRoles/admin
    。账号级别的变更会应用到所有媒体资源。

Interpreting output

输出解读

Engagement benchmarks, attribution model differences, funnel drop-off heuristics, audience sequence vs. condition patterns, realtime reporting caveats, and BigQuery long-term-storage tradeoffs are all in
references/playbook.md
. Read it before drawing conclusions about whether numbers are "good" — GA4's sampling and attribution defaults differ meaningfully from UA and from other analytics tools.
互动基准、归因模型差异、漏斗流失分析、受众序列与条件模式、实时报表注意事项以及BigQuery长期存储权衡等内容均收录于
references/playbook.md
。在判断数据是否“良好”前,请先阅读该文档——GA4的抽样和归因默认设置与UA及其他分析工具存在显著差异。

Troubleshooting

故障排查

  • "No credentials. Run: ga4 auth login …" — Exactly what it says. Get a Desktop OAuth client JSON from GCP and log in.
  • "Permission denied" — The Google account you auth'd with doesn't have GA access. Grant Viewer/Editor in GA Admin → Access Management. Verify with
    ga4 admin accounts summaries-list
    .
  • "Quota exhausted" — Pass
    --return-property-quota
    on a report to see live consumption. Data API tokens reset hourly/daily. GA360 gets 10x limits.
  • "insufficient_scope" — The stored token was obtained with fewer scopes than this command needs. Re-run
    ga4 auth login --client-secret <path> --scope <extra-scope>
    (repeatable) to include them.
  • "No property id" — Pass
    --property/-p
    , set
    GA_PROPERTY_ID
    , or
    ga4 config set-property <id>
    .
  • Alpha schema changed — Pin
    google-analytics-admin
    and
    google-analytics-data
    in
    pyproject.toml
    , then
    uv sync
    .
  • Realtime report is empty — The realtime window is only the last 30 minutes (60 for GA360). If there's genuinely no active traffic, the report will be empty; this is correct.
  • MP send returned 2xx but the event didn't appear
    mp send
    always returns 2xx regardless of validity. Use
    mp validate
    first to check for rejection reasons.
  • “No credentials. Run: ga4 auth login …” — 字面意思,需从GCP获取桌面OAuth客户端JSON文件并完成登录。
  • “Permission denied” — 完成认证的Google账号没有GA访问权限。在GA管理后台 → 访问管理中授予查看者/编辑者权限。可通过
    ga4 admin accounts summaries-list
    验证。
  • “Quota exhausted” — 在报表命令中添加
    --return-property-quota
    参数查看实时配额消耗情况。Data API令牌每小时/每日重置。GA360的配额是普通版本的10倍。
  • “insufficient_scope” — 存储的令牌权限范围不足以执行当前命令。重新运行
    ga4 auth login --client-secret <path> --scope <extra-scope>
    (可重复添加)以包含所需权限。
  • “No property id” — 传入
    --property/-p
    参数、设置
    GA_PROPERTY_ID
    环境变量或执行
    ga4 config set-property <id>
    设置默认媒体资源。
  • Alpha版本架构变更 — 在
    pyproject.toml
    中固定
    google-analytics-admin
    google-analytics-data
    的版本,然后执行
    uv sync
  • 实时报表为空 — 实时数据窗口仅包含最近30分钟(GA360为60分钟)。如果确实没有活跃流量,报表为空是正常现象。
  • MP发送返回2xx但事件未显示
    mp send
    无论事件是否有效都会返回2xx。请先使用
    mp validate
    检查拒绝原因。

Configuration files

配置文件

  • ~/.config/skills/ga4/config.json
    — default property and other CLI settings
  • ~/.config/skills/ga4/credentials.json
    — OAuth user creds (written by
    ga4 auth login
    )
  • Override the config dir with
    GA4_CONFIG_DIR=/path/to/dir
  • ~/.config/skills/ga4/config.json
    — 默认媒体资源及其他CLI设置
  • ~/.config/skills/ga4/credentials.json
    — OAuth用户凭证(由
    ga4 auth login
    生成)
  • 可通过
    GA4_CONFIG_DIR=/path/to/dir
    覆盖配置目录

Migrating from earlier versions

从旧版本迁移

If upgrading from a build that stored config at
~/.config/ga4/
, run
ga4 config migrate --apply
to move the credentials and config to the new location.
ga4 auth status
emits a
deprecation_warning
until the migration runs.
如果从配置存储在
~/.config/ga4/
的版本升级,请执行
ga4 config migrate --apply
将凭证和配置迁移到新目录。在完成迁移前,
ga4 auth status
会输出
deprecation_warning
警告。