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

求基于新版Sign in with Google对接Google Sheet API的读写示例

新版Sign in with Google 集成 Google Sheets API 实现读写示例

核心逻辑说明

新版Sign in with Google基于Google Identity Services (GIS),不再依赖旧的gapi.auth2。核心流程是通过GIS获取Access Token,然后用这个Token作为身份凭证,直接调用Google Sheets REST API完成读写操作。


完整代码示例

<!DOCTYPE html>
<html>
<head>
  <title>GIS + Sheets API Demo</title>
  <!-- 引入Google Identity Services脚本 -->
  <script src="https://accounts.google.com/gsi/client" async defer></script>
</head>
<body>
  <!-- 登录按钮容器 -->
  <div id="g_id_onload"
       data-client_id="你的OAuth客户端ID"
       data-context="signin"
       data-ux_mode="popup"
       data-callback="handleCredentialResponse"
       data-scopes="https://www.googleapis.com/auth/spreadsheets"
       data-auto_prompt="false">
  </div>
  <div class="g_id_signin"
       data-type="standard"
       data-shape="rectangular"
       data-theme="outline"
       data-text="signin_with"
       data-size="large"
       data-logo_alignment="left">
  </div>

  <!-- 操作按钮 -->
  <button id="readBtn" disabled>读取表格数据</button>
  <button id="writeBtn" disabled>写入表格数据</button>
  <pre id="output"></pre>

  <script>
    let accessToken = null;
    // 替换为你的测试表格ID
    const SPREADSHEET_ID = "你的Google表格ID";
    // 替换为要操作的单元格范围,比如Sheet1!A1:B2
    const RANGE = "Sheet1!A1:B2";

    // 登录回调,解析Credential获取Access Token
    function handleCredentialResponse(response) {
      // 从JWT格式的credential中解析出access_token
      const payload = JSON.parse(atob(response.credential.split('.')[1]));
      accessToken = payload.access_token;
      // 启用操作按钮
      document.getElementById('readBtn').disabled = false;
      document.getElementById('writeBtn').disabled = false;
      document.getElementById('output').textContent = "登录成功,可进行表格操作";
    }

    // 读取表格数据
    document.getElementById('readBtn').addEventListener('click', async () => {
      try {
        const response = await fetch(
          `https://sheets.googleapis.com/v4/spreadsheets/${SPREADSHEET_ID}/values/${RANGE}`,
          {
            headers: {
              'Authorization': `Bearer ${accessToken}`
            }
          }
        );
        const data = await response.json();
        document.getElementById('output').textContent = JSON.stringify(data, null, 2);
      } catch (error) {
        document.getElementById('output').textContent = `读取失败: ${error.message}`;
      }
    });

    // 写入表格数据
    document.getElementById('writeBtn').addEventListener('click', async () => {
      const values = [
        ["测试数据1", "2024-01-01"],
        ["测试数据2", "2024-01-02"]
      ];
      try {
        const response = await fetch(
          `https://sheets.googleapis.com/v4/spreadsheets/${SPREADSHEET_ID}/values/${RANGE}?valueInputOption=USER_ENTERED`,
          {
            method: 'PUT',
            headers: {
              'Authorization': `Bearer ${accessToken}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ values })
          }
        );
        const data = await response.json();
        document.getElementById('output').textContent = `写入成功: ${JSON.stringify(data, null, 2)}`;
      } catch (error) {
        document.getElementById('output').textContent = `写入失败: ${error.message}`;
      }
    });
  </script>
</body>
</html>

关键步骤说明

  1. 前置配置

    • 在谷歌云控制台启用Google Sheets API
    • 创建OAuth 2.0客户端ID,将当前页面域名添加到「已授权的JavaScript来源」
    • 调整测试表格的共享权限:如果是私人表格,需确保登录账号有读写权限;公开表格可设置为「任何有链接的人可编辑/查看」
  2. 核心代码解析

    • 通过g_id_onload配置客户端ID、请求权限(data-scopes)和登录回调
    • 登录成功后,从返回的JWT凭证中解析出Access Token
    • 调用Sheets API时,在请求头中携带Authorization: Bearer ${accessToken}完成身份验证
  3. 权限调整

    • 仅需读取表格:将data-scopes改为https://www.googleapis.com/auth/spreadsheets.readonly
    • 需要读写权限:保持https://www.googleapis.com/auth/spreadsheets即可

注意事项

  • Access Token默认有效期1小时,可通过GIS的token刷新机制自动获取新Token
  • 本地开发可使用localhost,谷歌允许该域名作为测试环境;线上部署需使用HTTPS
  • 若遇到权限错误,检查OAuth客户端ID配置、表格共享权限、请求scope是否匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:30:58