google-analytics
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGoogle 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_IDGOOGLE_CLIENT_SECRET- A valid OAuth access token (refreshed as needed)
Set credentials in , , or .
.env.env.local~/.claude/.env.global需要Google OAuth凭证:
GOOGLE_CLIENT_IDGOOGLE_CLIENT_SECRET- 有效的OAuth访问令牌(按需刷新)
在、或中配置凭证。
.env.env.local~/.claude/.env.globalGetting an Access Token
获取访问令牌
bash
undefinedbash
undefinedStep 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"
-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"
-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"
-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"
-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/XXXXXXXXXbash
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/XXXXXXXXXAPI Base
API基础地址
POST https://analyticsdata.googleapis.com/v1beta/{property_id}:runReportAll 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
日期范围快捷方式
- ,
todayyesterday - ,
7daysAgo,14daysAgo,28daysAgo,30daysAgo90daysAgo - Specific dates:
2024-01-01 - Compare periods by passing two dateRanges
- 、
todayyesterday - 、
7daysAgo、14daysAgo、28daysAgo、30daysAgo90daysAgo - 具体日期:
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
实用的获客维度
| Dimension | Description |
|---|---|
| Channel grouping (Organic, Paid, Social, etc.) |
| Traffic source (google, facebook, etc.) |
| Medium (organic, cpc, referral, etc.) |
| UTM campaign name |
| First-touch attribution source |
| 维度 | 描述 |
|---|---|
| 渠道分组(自然搜索、付费推广、社交平台等) |
| 流量来源(google、facebook等) |
| 流量媒介(organic、cpc、referral等) |
| UTM营销活动名称 |
| 首次触达归因来源 |
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
核心互动指标
| Metric | What It Measures |
|---|---|
| % of sessions that were engaged (>10s, 2+ pages, or conversion) |
| Mean session length in seconds |
| Pages per session |
| % of sessions with no engagement |
| Total events fired |
| 指标 | 衡量内容 |
|---|---|
| 互动会话占比(会话时长>10秒、浏览2个以上页面或完成转化) |
| 平均会话时长(秒) |
| 每次会话浏览页面数 |
| 跳出会话占比(无任何互动的会话) |
| 触发的事件总数 |
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 with in the dimensions.
deviceCategorycountry将维度中的替换为即可。
deviceCategorycountryBy 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
undefinedGA4 API返回JSON格式数据。可使用python3或jq解析:
bash
undefinedParse 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:
- Pull traffic overview (sessions, users, page views) with period comparison
- Pull acquisition breakdown by channel
- Pull top 20 pages by page views
- Pull conversion summary by channel
- Pull device and country breakdown
Present as a structured report with tables, trends (up/down arrows), and recommendations:
undefined当被要求提供月度报告时:
- 拉取流量概览数据(会话数、用户数、页面浏览量)并进行时段对比
- 拉取按渠道划分的获客明细
- 拉取页面浏览量TOP20的页面
- 拉取按渠道划分的转化汇总
- 拉取按设备和地域划分的流量明细
以结构化报告形式呈现,包含表格、趋势(上升/下降箭头)及建议:
undefinedMonthly Analytics Report: {Property Name}
月度分析报告:{媒体资源名称}
Period: {date range} vs {previous period}
时段:{当前日期范围} vs {对比日期范围}
Traffic Summary
流量汇总
| Metric | Current | Previous | Change |
|---|---|---|---|
| Sessions | X | Y | +Z% |
| ... |
| 指标 | 当前值 | 对比值 | 变化 |
|---|---|---|---|
| 会话数 | X | Y | +Z% |
| ... |
Top Channels
核心渠道
...
...
Top Pages
热门页面
...
...
Conversion Summary
转化汇总
...
...
Recommendations
建议
- [Based on data patterns]
undefined- [基于数据模式的建议]
undefinedCommon 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