首页 > 解决方案 > 使用服务帐户进行 Google Sheets Api 授权

问题描述

我正在使用googleapis库 v44.0.0。当我尝试登录时,出现错误。

Google Sheets API 之前未在项目 33120758 中使用或已禁用。通过访问https://console.developers.google.com/apis/api/sheets.googleapis.com/overview?project=33120758启用它,然后重试。如果您最近启用了此 API,请等待几分钟让该操作传播到我们的系统并重试。

我在同一个项目上使用 google-auth-library 版本 ^ 0.10.0。而这个错误不是。

const { google } = require("googleapis");
// ...
const JwtClient = new google.auth.JWT(
  client_email, 
  null, 
  private_key, 
  ["https://www.googleapis.com/auth/spreadsheets"]
);
await JwtClient.authorize();
google.options({ auth: JwtClient });

// ...
const client = google.sheets({ version: "v4" });
const data = await client.spreadsheets.get({ spreadsheetId: myId});

标签: node.jsgoogle-sheets-api

解决方案


  • 您想将 Sheets API 与服务帐户一起使用。
  • 您想使用 googleapis 和 Node.js 来实现这一点。

如果我的理解是正确的,那么这个修改呢?

修改后的脚本:

从:
await JwtClient.authorize();
google.options({ auth: JwtClient });

// ...
const client = google.sheets({ version: "v4" });
const data = await client.spreadsheets.get({ spreadsheetId: myId});
至:
const client = google.sheets({ version: "v4", "auth": JwtClient });
const data = await client.spreadsheets.get({ spreadsheetId: myId});
console.log(data.data)

笔记:

  • 如果您想从您自己的 Google Drive 上的电子表格中检索数据,请与服务帐户的电子邮件共享电子表格。这样,可以从服务帐户中检索电子表格。请注意这一点。

在我的环境中,我可以确认修改后的脚本有效。但如果这不能解决您的问题,我深表歉意。


推荐阅读