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

2022年能否用服务账号调用Google Sheets API?求Node.js授权示例

使用服务账号授权Google Sheets的Node.js示例

核心优势

服务账号无需手动刷新令牌,也不会出现7天过期的问题,完全适配无人值守的Discord机器人场景。

前置准备

  • 从Google Cloud控制台下载服务账号的JSON密钥文件(创建服务账号时生成)
  • 将你的Google Sheet共享给JSON密钥中client_email对应的邮箱,赋予编辑权限

替换原授权函数的完整示例

const { google } = require('googleapis');
const fs = require('fs');

/**
 * 使用服务账号创建授权客户端,并执行回调函数
 * @param {string} keyPath 服务账号JSON密钥文件路径
 * @param {function} callback 回调函数,接收授权后的客户端及额外参数
 */
function authorizeWithServiceAccount(keyPath, callback) {
  // 加载服务账号密钥,指定所需权限范围
  const auth = new google.auth.GoogleAuth({
    keyFile: keyPath,
    scopes: ['https://www.googleapis.com/auth/spreadsheets'], // 对应Google Sheets编辑权限
  });

  // 获取授权客户端
  auth.getClient().then((authClient) => {
    // 传递额外参数给回调(和你原代码的arguments逻辑一致)
    return callback(authClient, arguments[2], arguments[3]);
  }).catch((err) => {
    console.error('服务账号授权失败:', err);
  });
}

// 示例:调用授权函数并写入Google Sheet
function writeToSheet(authClient, spreadsheetId, range, values) {
  const sheets = google.sheets({ version: 'v4', auth: authClient });
  sheets.spreadsheets.values.update({
    spreadsheetId: spreadsheetId,
    range: range,
    valueInputOption: 'USER_ENTERED',
    resource: { values: values },
  }, (err, res) => {
    if (err) return console.error('写入Sheet失败:', err);
    console.log(`成功更新 ${res.data.updatedCells} 个单元格`);
  });
}

// 使用示例
const SERVICE_ACCOUNT_KEY_PATH = './service-account-key.json';
const SPREADSHEET_ID = '你的Google Sheet ID';
const RANGE = 'Sheet1!A1:B2';
const VALUES = [['Discord用户ID', '操作时间'], ['123456', new Date().toISOString()]];

// 调用授权并执行写入
authorizeWithServiceAccount(SERVICE_ACCOUNT_KEY_PATH, writeToSheet, SPREADSHEET_ID, RANGE, VALUES);

关键说明

  1. 权限范围:scopes字段需根据需求调整,https://www.googleapis.com/auth/spreadsheets涵盖读写权限,若仅需读取可改为https://www.googleapis.com/auth/spreadsheets.readonly
  2. 额外参数传递:示例保留了你原代码中传递额外参数的逻辑,通过arguments获取后续参数并传给回调
  3. 错误处理:添加了基础错误捕获,避免机器人因授权失败直接崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:15:38