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

React基于Google Identity新授权流集成GA Embed API方案

React项目基于新版Google Identity Services集成Google Analytics Embed API落地方案

旧版gapi身份验证模块被禁用不代表GA Embed API无法使用,核心思路是把授权流程从废弃的gapi.auth2模块替换为新版Google Identity Services(GIS),拿到访问令牌后手动注入gapi鉴权上下文,即可正常使用所有GA Embed API的原生能力,无需依赖过时的第三方封装包。


前置准备

  • 在Google Cloud控制台创建OAuth 2.0 Client ID,将React项目的本地调试域名、线上生产域名加入授权来源列表,不需要开启旧版库兼容开关
  • 开通对应Analytics API权限,申请的OAuth权限范围包含https://www.googleapis.com/auth/analytics.readonly
  • 不需要安装react-use-analytics-api等基于旧gapi封装的第三方包,原生实现逻辑更稳定

具体实现步骤

1. 加载必要静态依赖

不要引入旧版platform.js鉴权库,只需要加载两个核心资源:新版GIS客户端库、gapi核心库,在React组件中通过useEffect动态加载即可,避免阻塞首屏:

import { useEffect, useState } from 'react';

export default function GADashboard() {
  const [libsLoaded, setLibsLoaded] = useState(false);
  const [authorized, setAuthorized] = useState(false);
  // 替换为自己的Client ID和GA视图ID
  const CLIENT_ID = '你的GCP OAuth Client ID';
  const GA_VIEW_ID = 'ga:你的GA数据视图ID';

  useEffect(() => {
    const loadScript = (src) => {
      return new Promise((resolve, reject) => {
        // 避免重复加载脚本
        if (document.querySelector(`script[src="${src}"]`)) {
          resolve();
          return;
        }
        const script = document.createElement('script');
        script.src = src;
        script.async = true;
        script.defer = true;
        script.onload = resolve;
        script.onerror = reject;
        document.body.appendChild(script);
      });
    };

    const initDeps = async () => {
      try {
        // 并行加载两个依赖库
        await Promise.all([
          loadScript('https://accounts.google.com/gsi/client'),
          loadScript('https://apis.google.com/js/api.js')
        ]);
        // 只加载gapi的analytics模块,不要加载auth/auth2模块
        window.gapi.load('analytics', () => {
          setLibsLoaded(true);
        });
      } catch (err) {
        console.error('GA依赖加载失败', err);
      }
    };

    initDeps();
  }, []);

2. 实现新版GIS授权流程

依赖加载完成后,初始化GIS OAuth客户端,用户授权拿到access_token后,手动注入到gapi的鉴权上下文中,绕开旧版鉴权逻辑:

const handleAuth = () => {
    if (!libsLoaded) return;
    const tokenClient = window.google.accounts.oauth2.initTokenClient({
      client_id: CLIENT_ID,
      scope: 'https://www.googleapis.com/auth/analytics.readonly',
      callback: (tokenRes) => {
        if (tokenRes.error) return;
        // 核心步骤:手动给gapi设置鉴权令牌
        window.gapi.auth.setToken({
          access_token: tokenRes.access_token,
          expires_in: tokenRes.expires_in
        });
        setAuthorized(true);
      }
    });
    // 触发授权弹窗,已授权用户可传prompt:''实现静默续签
    tokenClient.requestAccessToken({ prompt: 'consent' });
  };

3. 渲染GA数据组件

授权完成后,即可和旧版写法一致,直接调用gapi.analytics的原生API渲染图表、数据卡片、视图选择器等组件,所有接口请求会自动携带之前注入的令牌,不会触发弃用报错:

useEffect(() => {
    if (!authorized) return;
    // 示例:渲染近30天访问量趋势折线图
    const trendChart = new window.gapi.analytics.googleCharts.DataChart({
      query: {
        metrics: 'ga:sessions',
        dimensions: 'ga:date',
        'start-date': '30daysAgo',
        'end-date': 'yesterday',
        ids: GA_VIEW_ID
      },
      chart: {
        container: 'ga-trend-chart',
        type: 'LINE',
        options: { width: '100%', title: '近30天访问量趋势' }
      }
    });
    trendChart.execute();
  }, [authorized]);

  return (
    <div className="ga-dashboard">
      {!authorized && <button onClick={handleAuth}>授权Google账号查看数据</button>}
      <div id="ga-trend-chart" style={{ width: '100%', minHeight: 420 }}></div>
    </div>
  );
}

常见踩坑说明

  • 不需要配置plugin_name参数,该参数仅对2022年7月29日之前创建的旧Client ID生效,新建Client ID配置该参数仍然会触发弃用报错
  • 不要主动加载gapi的auth/auth2子模块,这两个模块是触发弃用报错的直接原因,所有鉴权逻辑交给GIS处理即可
  • 令牌过期后不需要用户重新手动授权,监听令牌过期事件后调用requestAccessToken并传入prompt:''即可静默刷新令牌
  • 如果对接GA4,只需要替换对应的权限范围、查询参数为GA4适配的格式即可,鉴权流程完全通用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 11:06:19