mcpField
G
google-analytics

google-analytics

github.com/openclaudia营销与增长722524 次安装1 天前更新
代码仓库

关于 google-analytics

通过 Google Analytics Data API 获取 GA4 报告的 Claude skill,面向需要分析流量、获客、互动、转化和受众细分的分析人员。

主要功能

  1. 01流量与互动报告
  2. 02按渠道和来源分析获客
  3. 03热门页面报告
  4. 04转化事件分析
  5. 05设备与地区细分
  6. 06时间段对比

适用场景

  1. 01整理月度分析报告
  2. 02比较不同时段的流量
  3. 03识别主要获客渠道
  4. 04检查页面互动和转化

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/openclaudia/openclaudia-skills --skill google-analytics

安装后在 Claude Code 中输入/google-analytics确认已加载。

详细介绍

Google Analytics (GA4)

使用 Google Analytics Data API 从 GA4 获取报告和洞察。

前提条件

需要 Google OAuth 凭据:

  • GOOGLE_CLIENT_ID
  • GOOGLE_CLIENT_SECRET
  • 有效的 OAuth 访问令牌(需要时刷新)

在 .env、.env.local 或 ~/.claude/.env.global 中设置凭据。

获取访问令牌
# Step 1: Get authorization code (user must visit this URL in browser)
echo "https://accounts.google.com/o/oauth2/v2/auth?client_id=${GOOGLE_CLIENT_ID}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code&access_type=offline"

# 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"

# 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"

请妥善保管刷新令牌。访问令牌会在 1 小时后过期。

查找 GA4 属性 ID
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 基础地址

POST https://analyticsdata.googleapis.com/v1beta/{property_id}:runReport

所有报告请求都使用 POST,并附带 JSON 请求体。务必包含 Authorization: Bearer {ACCESS_TOKEN}。


1. 流量概览报告

获取某个日期范围内的会话数、用户数、页面浏览量和互动率。

curl 示例
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"}
    ]
  }'
日期范围快捷方式
  • today、yesterday
  • 7daysAgo、14daysAgo、28daysAgo、30daysAgo、90daysAgo
  • 特定日期:2024-01-01
  • 传入两个 dateRanges 即可比较不同时间段

2. 用户获取报告

查看用户的来源(渠道、来源、广告系列)。

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
  }'
常用的用户获取维度
维度说明
sessionDefaultChannelGroup渠道分组(自然流量、付费流量、社交媒体等)
sessionSource流量来源(google、facebook 等)
sessionMedium媒介(自然流量、cpc、引荐等)
sessionCampaignNameUTM 广告系列名称
firstUserSource首次触点归因来源

3. 热门页面报告

找出网站流量最高的页面。

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. 互动指标

了解用户如何与内容互动。

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
  }'
关键互动指标
指标衡量内容
engagementRate有互动的会话所占百分比(>10 秒、浏览 2 个以上页面或发生转化)
averageSessionDuration平均会话时长(秒)
screenPageViewsPerSession每个会话的页面数
bounceRate没有互动的会话所占百分比
eventCount触发的事件总数

5. 转化跟踪

查看转化事件(购买、注册等)的报告。

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"]
        }
      }
    }
  }'
按渠道划分的转化
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. 受众细分

按设备、地理位置和人口统计信息细分流量。

按设备类别划分
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"}
    ]
  }'
按国家/地区划分

将维度中的 deviceCategory 替换为 country。

按着陆页 + 来源划分
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. 时间段比较

比较两个时间段,以发现趋势。

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"}
    ]
  }'

响应解析

GA4 API 返回 JSON。使用 python3 或 jq 进行解析:

# 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))
"

工作流:月度分析报告

收到月度报告请求时:

  1. 获取流量概览(会话数、用户数、页面浏览量),并比较不同时间段
  2. 获取按渠道划分的用户获取情况
  3. 获取按页面浏览量排序的前 20 个页面
  4. 获取按渠道划分的转化摘要
  5. 获取按设备和国家/地区划分的数据

以结构化报告的形式呈现,包含表格、趋势(向上/向下箭头)和建议:

## Monthly Analytics Report: {Property Name}
### Period: {date range} vs {previous period}

### Traffic Summary
| Metric | Current | Previous | Change |
|--------|---------|----------|--------|
| Sessions | X | Y | +Z% |
| ...

### Top Channels
...

### Top Pages
...

### Conversion Summary
...

### Recommendations
- [Based on data patterns]

常见问题

  • 403 Forbidden:用户无权访问此 GA4 属性
  • 空行:请求的日期范围或筛选条件没有数据
  • 超出配额:GA4 API 有每日配额;请缩短日期范围或分批发送请求
  • 找不到属性:请确认属性 ID 的格式正确(properties/XXXXXXXXX)

评论

支持 Markdown