google-analytics

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Google Analytics (GA4)

Google Analytics (GA4)

Pull reports and insights from GA4 using the Google Analytics Data API.
通过Google Analytics Data API从GA4拉取报告和洞察信息。

Prerequisites

前提条件

Requires Google OAuth credentials:
  • GOOGLE_CLIENT_ID
  • GOOGLE_CLIENT_SECRET
  • A valid OAuth access token (refreshed as needed)
Set credentials in
.env
,
.env.local
, or
~/.claude/.env.global
.
需要Google OAuth凭证:
  • GOOGLE_CLIENT_ID
  • GOOGLE_CLIENT_SECRET
  • 有效的OAuth访问令牌(按需刷新)
.env
.env.local
~/.claude/.env.global
中配置凭证。

Getting an Access Token

获取访问令牌

bash
undefined
bash
undefined

Step 1: Get authorization code (user must visit this URL in browser)

Step 1: Get authorization code (user must visit this URL in browser)

Step 2: Exchange code for tokens

Step 2: Exchange code for tokens

curl -s -X POST "https://oauth2.googleapis.com/token"
-d "code={AUTH_CODE}"
-d "client_id=${GOOGLE_CLIENT_ID}"
-d "client_secret=${GOOGLE_CLIENT_SECRET}"
-d "redirect_uri=urn:ietf:wg:oauth:2.0:oob"
-d "grant_type=authorization_code"
curl -s -X POST "https://oauth2.googleapis.com/token"
-d "code={AUTH_CODE}"
-d "client_id=${GOOGLE_CLIENT_ID}"
-d "client_secret=${GOOGLE_CLIENT_SECRET}"
-d "redirect_uri=urn:ietf:wg:oauth:2.0:oob"
-d "grant_type=authorization_code"

Step 3: Refresh an expired token

Step 3: Refresh an expired token

curl -s -X POST "https://oauth2.googleapis.com/token"
-d "refresh_token={REFRESH_TOKEN}"
-d "client_id=${GOOGLE_CLIENT_ID}"
-d "client_secret=${GOOGLE_CLIENT_SECRET}"
-d "grant_type=refresh_token"

Store the refresh token securely. The access token expires after 1 hour.
curl -s -X POST "https://oauth2.googleapis.com/token"
-d "refresh_token={REFRESH_TOKEN}"
-d "client_id=${GOOGLE_CLIENT_ID}"
-d "client_secret=${GOOGLE_CLIENT_SECRET}"
-d "grant_type=refresh_token"

安全存储刷新令牌。访问令牌1小时后过期。

Finding Your GA4 Property ID

查找你的GA4媒体资源ID

bash
curl -s -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  "https://analyticsadmin.googleapis.com/v1beta/accountSummaries" \
  | python3 -c "
import json, sys
data = json.load(sys.stdin)
for acct in data.get('accountSummaries', []):
    for prop in acct.get('propertySummaries', []):
        print(f\"{prop['property']}  |  {prop.get('displayName','')}  |  Account: {acct.get('displayName','')}\")
"
The property ID format is
properties/XXXXXXXXX
.

bash
curl -s -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  "https://analyticsadmin.googleapis.com/v1beta/accountSummaries" \
  | python3 -c "
import json, sys
data = json.load(sys.stdin)
for acct in data.get('accountSummaries', []):
    for prop in acct.get('propertySummaries', []):
        print(f\"{prop['property']}  |  {prop.get('displayName','')}  |  Account: {acct.get('displayName','')}\")
"
媒体资源ID格式为
properties/XXXXXXXXX

API Base

API基础地址

POST https://analyticsdata.googleapis.com/v1beta/{property_id}:runReport
All report requests use POST with a JSON body. Always include
Authorization: Bearer {ACCESS_TOKEN}
.

POST https://analyticsdata.googleapis.com/v1beta/{property_id}:runReport
所有报告请求均使用POST方法并携带JSON请求体。请求头中必须包含
Authorization: Bearer {ACCESS_TOKEN}

1. Traffic Overview Report

1. 流量概览报告

Get sessions, users, page views, and engagement rate over a date range.
获取指定日期范围内的会话数、用户数、页面浏览量及互动率。

Example curl

示例curl请求

bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "metrics": [
      {"name": "sessions"},
      {"name": "totalUsers"},
      {"name": "newUsers"},
      {"name": "screenPageViews"},
      {"name": "engagementRate"},
      {"name": "averageSessionDuration"},
      {"name": "bounceRate"}
    ]
  }'
bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "metrics": [
      {"name": "sessions"},
      {"name": "totalUsers"},
      {"name": "newUsers"},
      {"name": "screenPageViews"},
      {"name": "engagementRate"},
      {"name": "averageSessionDuration"},
      {"name": "bounceRate"}
    ]
  }'

Date Range Shortcuts

日期范围快捷方式

  • today
    ,
    yesterday
  • 7daysAgo
    ,
    14daysAgo
    ,
    28daysAgo
    ,
    30daysAgo
    ,
    90daysAgo
  • Specific dates:
    2024-01-01
  • Compare periods by passing two dateRanges

  • today
    yesterday
  • 7daysAgo
    14daysAgo
    28daysAgo
    30daysAgo
    90daysAgo
  • 具体日期:
    2024-01-01
  • 通过传入两个dateRanges参数对比不同时段

2. User Acquisition Report

2. 用户获客报告

See where users come from (channels, sources, campaigns).
bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [
      {"name": "sessionDefaultChannelGroup"}
    ],
    "metrics": [
      {"name": "sessions"},
      {"name": "totalUsers"},
      {"name": "engagementRate"},
      {"name": "conversions"}
    ],
    "orderBys": [{"metric": {"metricName": "sessions"}, "desc": true}],
    "limit": 20
  }'
查看用户来源渠道、流量来源及营销活动。
bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [
      {"name": "sessionDefaultChannelGroup"}
    ],
    "metrics": [
      {"name": "sessions"},
      {"name": "totalUsers"},
      {"name": "engagementRate"},
      {"name": "conversions"}
    ],
    "orderBys": [{"metric": {"metricName": "sessions"}, "desc": true}],
    "limit": 20
  }'

Useful Acquisition Dimensions

实用的获客维度

DimensionDescription
sessionDefaultChannelGroup
Channel grouping (Organic, Paid, Social, etc.)
sessionSource
Traffic source (google, facebook, etc.)
sessionMedium
Medium (organic, cpc, referral, etc.)
sessionCampaignName
UTM campaign name
firstUserSource
First-touch attribution source

维度描述
sessionDefaultChannelGroup
渠道分组(自然搜索、付费推广、社交平台等)
sessionSource
流量来源(google、facebook等)
sessionMedium
流量媒介(organic、cpc、referral等)
sessionCampaignName
UTM营销活动名称
firstUserSource
首次触达归因来源

3. Top Pages Report

3. 热门页面报告

Find the highest-traffic pages on the site.
bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [
      {"name": "pagePath"}
    ],
    "metrics": [
      {"name": "screenPageViews"},
      {"name": "totalUsers"},
      {"name": "engagementRate"},
      {"name": "averageSessionDuration"}
    ],
    "orderBys": [{"metric": {"metricName": "screenPageViews"}, "desc": true}],
    "limit": 25
  }'

找出网站中流量最高的页面。
bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [
      {"name": "pagePath"}
    ],
    "metrics": [
      {"name": "screenPageViews"},
      {"name": "totalUsers"},
      {"name": "engagementRate"},
      {"name": "averageSessionDuration"}
    ],
    "orderBys": [{"metric": {"metricName": "screenPageViews"}, "desc": true}],
    "limit": 25
  }'

4. Engagement Metrics

4. 互动指标

Understand how users interact with your content.
bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [
      {"name": "pagePath"}
    ],
    "metrics": [
      {"name": "engagedSessions"},
      {"name": "engagementRate"},
      {"name": "averageSessionDuration"},
      {"name": "screenPageViewsPerSession"},
      {"name": "eventCount"}
    ],
    "orderBys": [{"metric": {"metricName": "engagedSessions"}, "desc": true}],
    "limit": 20
  }'
了解用户与内容的互动方式。
bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [
      {"name": "pagePath"}
    ],
    "metrics": [
      {"name": "engagedSessions"},
      {"name": "engagementRate"},
      {"name": "averageSessionDuration"},
      {"name": "screenPageViewsPerSession"},
      {"name": "eventCount"}
    ],
    "orderBys": [{"metric": {"metricName": "engagedSessions"}, "desc": true}],
    "limit": 20
  }'

Key Engagement Metrics

核心互动指标

MetricWhat It Measures
engagementRate
% of sessions that were engaged (>10s, 2+ pages, or conversion)
averageSessionDuration
Mean session length in seconds
screenPageViewsPerSession
Pages per session
bounceRate
% of sessions with no engagement
eventCount
Total events fired

指标衡量内容
engagementRate
互动会话占比(会话时长>10秒、浏览2个以上页面或完成转化)
averageSessionDuration
平均会话时长(秒)
screenPageViewsPerSession
每次会话浏览页面数
bounceRate
跳出会话占比(无任何互动的会话)
eventCount
触发的事件总数

5. Conversion Tracking

5. 转化追踪

Report on conversion events (purchases, signups, etc.).
bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [
      {"name": "eventName"}
    ],
    "metrics": [
      {"name": "eventCount"},
      {"name": "totalUsers"},
      {"name": "eventValue"}
    ],
    "dimensionFilter": {
      "filter": {
        "fieldName": "eventName",
        "inListFilter": {
          "values": ["purchase", "sign_up", "generate_lead", "begin_checkout"]
        }
      }
    }
  }'
报告转化事件(购买、注册等)。
bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [
      {"name": "eventName"}
    ],
    "metrics": [
      {"name": "eventCount"},
      {"name": "totalUsers"},
      {"name": "eventValue"}
    ],
    "dimensionFilter": {
      "filter": {
        "fieldName": "eventName",
        "inListFilter": {
          "values": ["purchase", "sign_up", "generate_lead", "begin_checkout"]
        }
      }
    }
  }'

Conversion by Channel

按渠道划分的转化情况

bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [
      {"name": "sessionDefaultChannelGroup"}
    ],
    "metrics": [
      {"name": "sessions"},
      {"name": "conversions"},
      {"name": "totalRevenue"}
    ],
    "orderBys": [{"metric": {"metricName": "conversions"}, "desc": true}]
  }'

bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [
      {"name": "sessionDefaultChannelGroup"}
    ],
    "metrics": [
      {"name": "sessions"},
      {"name": "conversions"},
      {"name": "totalRevenue"}
    ],
    "orderBys": [{"metric": {"metricName": "conversions"}, "desc": true}]
  }'

6. Audience Segments

6. 受众细分

Break down traffic by device, geography, and demographics.
按设备、地域和人口统计信息拆分流量数据。

By Device Category

按设备类型

bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [{"name": "deviceCategory"}],
    "metrics": [
      {"name": "sessions"},
      {"name": "totalUsers"},
      {"name": "engagementRate"},
      {"name": "conversions"}
    ]
  }'
bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [{"name": "deviceCategory"}],
    "metrics": [
      {"name": "sessions"},
      {"name": "totalUsers"},
      {"name": "engagementRate"},
      {"name": "conversions"}
    ]
  }'

By Country

按国家

Replace
deviceCategory
with
country
in the dimensions.
将维度中的
deviceCategory
替换为
country
即可。

By Landing Page + Source

按着陆页+来源

bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [
      {"name": "landingPage"},
      {"name": "sessionSource"}
    ],
    "metrics": [
      {"name": "sessions"},
      {"name": "engagementRate"},
      {"name": "conversions"}
    ],
    "orderBys": [{"metric": {"metricName": "sessions"}, "desc": true}],
    "limit": 30
  }'

bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
    "dimensions": [
      {"name": "landingPage"},
      {"name": "sessionSource"}
    ],
    "metrics": [
      {"name": "sessions"},
      {"name": "engagementRate"},
      {"name": "conversions"}
    ],
    "orderBys": [{"metric": {"metricName": "sessions"}, "desc": true}],
    "limit": 30
  }'

7. Period Comparison

7. 时段对比

Compare two time periods to identify trends.
bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [
      {"startDate": "30daysAgo", "endDate": "today", "name": "current"},
      {"startDate": "60daysAgo", "endDate": "31daysAgo", "name": "previous"}
    ],
    "metrics": [
      {"name": "sessions"},
      {"name": "totalUsers"},
      {"name": "conversions"},
      {"name": "engagementRate"}
    ]
  }'

对比两个时段的数据以识别趋势。
bash
curl -s -X POST \
  "https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport" \
  -H "Authorization: Bearer ${GA_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "dateRanges": [
      {"startDate": "30daysAgo", "endDate": "today", "name": "current"},
      {"startDate": "60daysAgo", "endDate": "31daysAgo", "name": "previous"}
    ],
    "metrics": [
      {"name": "sessions"},
      {"name": "totalUsers"},
      {"name": "conversions"},
      {"name": "engagementRate"}
    ]
  }'

Response Parsing

响应解析

GA4 API returns JSON. Parse with python3 or jq:
bash
undefined
GA4 API返回JSON格式数据。可使用python3或jq解析:
bash
undefined

Parse report into a table

Parse report into a table

curl -s -X POST "..." | python3 -c " import json, sys data = json.load(sys.stdin) headers = [h['name'] for h in data.get('dimensionHeaders',[])] + [m['name'] for m in data.get('metricHeaders',[])] print(' | '.join(headers)) print('-' * (len(headers) * 20)) for row in data.get('rows', []): dims = [d['value'] for d in row.get('dimensionValues',[])] mets = [m['value'] for m in row.get('metricValues',[])] print(' | '.join(dims + mets)) "

---
curl -s -X POST "..." | python3 -c " import json, sys data = json.load(sys.stdin) headers = [h['name'] for h in data.get('dimensionHeaders',[])] + [m['name'] for m in data.get('metricHeaders',[])] print(' | '.join(headers)) print('-' * (len(headers) * 20)) for row in data.get('rows', []): dims = [d['value'] for d in row.get('dimensionValues',[])] mets = [m['value'] for m in row.get('metricValues',[])] print(' | '.join(dims + mets)) "

---

Workflow: Monthly Analytics Report

工作流:月度分析报告

When asked for a monthly report:
  1. Pull traffic overview (sessions, users, page views) with period comparison
  2. Pull acquisition breakdown by channel
  3. Pull top 20 pages by page views
  4. Pull conversion summary by channel
  5. Pull device and country breakdown
Present as a structured report with tables, trends (up/down arrows), and recommendations:
undefined
当被要求提供月度报告时:
  1. 拉取流量概览数据(会话数、用户数、页面浏览量)并进行时段对比
  2. 拉取按渠道划分的获客明细
  3. 拉取页面浏览量TOP20的页面
  4. 拉取按渠道划分的转化汇总
  5. 拉取按设备和地域划分的流量明细
以结构化报告形式呈现,包含表格、趋势(上升/下降箭头)及建议:
undefined

Monthly Analytics Report: {Property Name}

月度分析报告:{媒体资源名称}

Period: {date range} vs {previous period}

时段:{当前日期范围} vs {对比日期范围}

Traffic Summary

流量汇总

MetricCurrentPreviousChange
SessionsXY+Z%
...
指标当前值对比值变化
会话数XY+Z%
...

Top Channels

核心渠道

...
...

Top Pages

热门页面

...
...

Conversion Summary

转化汇总

...
...

Recommendations

建议

  • [Based on data patterns]
undefined
  • [基于数据模式的建议]
undefined

Common Issues

常见问题

  • 403 Forbidden: User lacks access to the GA4 property
  • Empty rows: No data for the requested date range or filters
  • Quota exceeded: GA4 API has daily quotas; reduce date ranges or batch requests
  • Property not found: Verify the property ID format (
    properties/XXXXXXXXX
    )
  • 403 禁止访问:用户无GA4媒体资源访问权限
  • 空行:请求的日期范围或筛选条件下无数据
  • 配额超限:GA4 API有每日配额限制;缩小日期范围或批量处理请求
  • 媒体资源未找到:验证媒体资源ID格式是否正确(
    properties/XXXXXXXXX