You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用OAuth凭据访问Google Analytics Data API?

使用OAuth凭据调用Google Analytics Data API(Node.js)

谷歌官方支持使用OAuth用户凭据(而非服务账号)直接调用Analytics Data API,以下是简便的实现方式:

1. 准备OAuth凭据

  • 登录Google Cloud控制台,创建OAuth 2.0客户端ID(根据项目类型选择「桌面应用」或「网页应用」)
  • 下载凭据JSON文件,保存为credentials.json放在项目目录下

2. 安装依赖

npm install @google-analytics/data google-auth-library

3. 完整代码实现

初始化客户端与授权流程

const { BetaAnalyticsDataClient } = require('@google-analytics/data');
const { OAuth2Client } = require('google-auth-library');
const fs = require('fs');
const path = require('path');

// 加载OAuth客户端凭据
const credentialsPath = path.join(__dirname, 'credentials.json');
const credentials = JSON.parse(fs.readFileSync(credentialsPath));
const clientConfig = credentials.installed || credentials.web; // 根据凭据类型切换

const oAuth2Client = new OAuth2Client(
  clientConfig.client_id,
  clientConfig.client_secret,
  clientConfig.redirect_uris[0]
);

// 加载已保存的令牌(首次运行跳过,先获取授权码)
const tokenPath = path.join(__dirname, 'token.json');
if (fs.existsSync(tokenPath)) {
  const token = JSON.parse(fs.readFileSync(tokenPath));
  oAuth2Client.setCredentials(token);
}

// 初始化Analytics Data客户端
const analyticsDataClient = new BetaAnalyticsDataClient({ auth: oAuth2Client });

// 首次运行:生成授权URL,引导用户授权
async function getAuthorizationUrl() {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline', // 长期授权,获取刷新令牌
    scope: ['https://www.googleapis.com/auth/analytics.readonly'], // API所需只读权限
  });
  console.log('请访问以下URL完成授权:', authUrl);
}

// 用授权码交换令牌并保存
async function exchangeCodeForToken(code) {
  const { tokens } = await oAuth2Client.getToken(code);
  oAuth2Client.setCredentials(tokens);
  fs.writeFileSync(tokenPath, JSON.stringify(tokens));
  console.log('令牌已保存,可正常调用API');
}

// 示例API调用:获取GA4报表数据
async function fetchAnalyticsReport() {
  try {
    const [response] = await analyticsDataClient.runReport({
      property: 'properties/你的GA4属性ID',
      dateRanges: [{ startDate: '7daysAgo', endDate: 'today' }],
      dimensions: [{ name: 'city' }],
      metrics: [{ name: 'activeUsers' }],
    });
    console.log('报表数据:', response);
  } catch (err) {
    console.error('API调用失败:', err);
  }
}

// 首次运行时先执行getAuthorizationUrl(),获取授权码后执行exchangeCodeForToken('授权码')
// 之后直接调用fetchAnalyticsReport()即可
// fetchAnalyticsReport();

关键说明

  • OAuth用户凭据适合需要模拟特定Google账号访问其自身GA4数据的场景,服务账号则更适合服务器端无人值守的批量数据获取
  • 最新版本的@google-analytics/data SDK原生支持传入自定义OAuth2Client实例,无需依赖临时workaround
  • 保存的token.json包含刷新令牌,可自动续期访问令牌,无需重复授权

内容的提问来源于stack exchange,提问作者Robin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 13:44:59