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

Google账号OAuth2认证后拉取GMB账户返回Unauthorized错误如何修复

问题修复方案

1. 基础语法错误修复

首先修复两处明显的低级逻辑错误:

  • fetchGoogleMyBusinessAccounts方法中axios.get是异步方法,你漏加了await关键字,导致拿到的是Promise对象而非实际响应结果
  • OAuth回调逻辑中重复声明了oauth2Client变量,删掉第二次重复初始化的代码即可

2. 授权凭证绑定逻辑修复

你没有给OAuth2客户端绑定获取到的授权凭证,直接取存储的access_token发起请求容易出现授权上下文不匹配的问题,修改fetchGoogleMyBusinessAccounts逻辑如下:

async fetchGoogleMyBusinessAccounts() { 
  const oauth2Client = initOAuth2Client();
  const tokens = fetchTokenFromDatabase(); // 取出完整的tokens对象,不要仅取access_token
  oauth2Client.setCredentials(tokens); // 给客户端绑定授权凭证

  console.log(`Fetching GMB Accounts`);
  const accountsUrls = `https://mybusinessaccountmanagement.googleapis.com/v1/accounts`;
  try {
      const response = await axios.get(accountsUrls, {
          headers: {
              Authorization: `Bearer ${(await oauth2Client.getAccessToken()).token}`
          }
      });
      const data = response.data;
      console.log(`GMB Accounts response = ${JSON.stringify(data, null, 2)}`);
  } catch (e) {
      console.log('Error retrieving GMB Accounts:Full error below:');
      console.log(e.response?.data || e); // 打印接口返回的具体错误信息,方便进一步定位
  }
}

3. 权限与服务开通校验

  • 确认你的Google Cloud项目已经开通了My Business Account Management API,未开通对应API的情况下就算授权完成也会返回401错误
  • 确认你完成授权的Google账号确实拥有对应商家账号的管理权限,无权限的账号授权后也无法拉取商家列表
  • 检查存储的access_token是否过期,默认有效期为1小时,过期后需要用refresh_token换发新的有效access_token再发起请求

4. 授权作用域校验

你当前使用的https://www.googleapis.com/auth/business.manage是正确的GMB管理权限,不需要额外新增其他作用域,确认用户授权时确实勾选了该权限的同意选项,没有取消对应权限的授权。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:09:01