Google Analytics Reporting API v4官方JS教程因OAuth库过时失效
Universal Analytics Core Reporting API v4 前端适配GIS指南(解决旧授权库弃用问题)
遇到的问题
- 已完成Universal Analytics项目的API访问配置,通过Google官方Request Composer可正常调用API
- 使用官方原Web JS快速入门教程时,控制台提示用户身份验证/授权库将于2023年3月弃用
- 尝试通用GIS迁移指南适配时触发403错误,发现该指南仅适用于前端登录场景,不支持API访问
正确迁移步骤
找到针对OAuth2 API访问的专用GIS迁移指南后,适配完成可正常执行查询,关键步骤整理如下:
- 引入Google Identity Services库:
<script src="https://accounts.google.com/gsi/client" async defer></script> - 初始化授权客户端:
window.onload = () => { google.accounts.oauth2.initTokenClient({ client_id: '你的客户端ID', scope: 'https://www.googleapis.com/auth/analytics.readonly', callback: (tokenRes) => { if (tokenRes.error) throw tokenRes.error; // 拿到授权令牌后调用报表接口 getAnalyticsReport(tokenRes.access_token); } }); }; - 编写授权触发函数:
function authAndFetch() { google.accounts.oauth2.getToken({prompt: ''}); } - 实现报表查询逻辑:
function getAnalyticsReport(token) { fetch('https://analyticsreporting.googleapis.com/v4/reports:batchGet', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ reportRequests: [{ viewId: '你的视图ID', dateRanges: [{startDate: '7daysAgo', endDate: 'today'}], metrics: [{expression: 'ga:sessions'}] }] }) }) .then(res => res.json()) .then(data => console.log('报表数据:', data)) .catch(err => console.error('查询失败:', err)); } - 页面添加授权触发按钮:
<button onclick="authAndFetch()">授权获取数据</button>
关键注意事项
- 必须使用API访问专用的GIS迁移指南,通用前端登录迁移文档会导致403权限错误
- 确保Google Cloud Console中客户端ID已配置当前域名的授权范围
- 授权范围仅需申请
https://www.googleapis.com/auth/analytics.readonly,避免过度授权
内容的提问来源于stack exchange,提问作者Axonn
相关产品推荐
相关产品推荐

