如何通过Node.js获取Google Business账户下全部关联账户及地点?
解决Google Business Profile API获取全部账户/地点的问题
问题概述
拥有Google Business账户,通过Node.js应用使用服务账户密钥认证后,仅能获取1个账户信息且存在未授权问题,无法获取所有者邮箱关联的全部账户及地点。当前代码仅实现了获取access token,需要扩展以获取完整数据。
解决步骤
1. 配置域范围委派(仅适用于Google Workspace账户)
服务账户本身没有关联的Google Business Profile数据,必须通过域范围委派模拟所有者邮箱身份访问数据:
- 登录Google Workspace管理控制台,进入「安全」→「API控制」→「域范围委派」
- 添加服务账户的
client_email,并授权https://www.googleapis.com/auth/business.manage这个权限范围 - 保存配置,确保服务账户已获得模拟指定用户的权限
2. 模拟所有者用户身份认证
创建JWT客户端时,必须指定subject参数为所有者的邮箱地址,这样服务账户才能以该用户身份访问其关联的所有Google Business账户。
3. 调用API获取账户及地点
先调用accounts.list接口获取所有关联账户,再遍历每个账户调用accounts.locations.list获取对应地点。
完整代码示例
const { google } = require('googleapis'); const key = require("./serviceAccountJson.json"); const express = require('express'); const app = express(); // 替换为实际的账户所有者邮箱 const OWNER_EMAIL = 'your-owner-email@example.com'; app.get('/get-all-locations', async (req, res) => { try { // 初始化JWT客户端,指定模拟的用户身份 const jwtClient = new google.auth.JWT( key.client_email, null, key.private_key, ['https://www.googleapis.com/auth/business.manage'], OWNER_EMAIL // 关键:指定要模拟的用户邮箱 ); // 完成认证 await jwtClient.authorize(); // 初始化Google Business Profile API客户端 const businessProfile = google.mybusinessbusinessinformation({ version: 'v1', auth: jwtClient }); // 1. 获取所有关联的账户 const accountsResponse = await businessProfile.accounts.list(); const accounts = accountsResponse.data.accounts; if (!accounts || accounts.length === 0) { return res.send({ message: '未找到关联的Google Business账户' }); } // 2. 遍历账户,获取每个账户下的地点 const allLocations = []; for (const account of accounts) { const locationsResponse = await businessProfile.accounts.locations.list({ parent: account.name // 账户的资源名称,格式为accounts/{accountId} }); const locations = locationsResponse.data.locations || []; allLocations.push({ accountId: account.name.split('/')[1], accountName: account.displayName, locations: locations.map(loc => ({ locationId: loc.name.split('/')[1], locationName: loc.title, address: loc.address?.formattedAddress })) }); } res.send({ totalAccounts: accounts.length, totalLocations: allLocations.flatMap(item => item.locations).length, data: allLocations }); } catch (error) { console.error('请求失败:', error); res.status(500).send({ error: error.message, details: error.response?.data || '无额外详情' }); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`服务器运行在端口 ${PORT}`); });
关键注意事项
- 如果使用的是个人Google账户而非Google Workspace账户,域范围委派不可用,需改用OAuth 2.0授权码流程获取用户授权
- 确保服务账户已被添加为Google Business账户的管理员(在Google Business Profile后台添加服务账户邮箱为管理员)
- 确认API已在Google Cloud控制台中启用:搜索「Google Business Profile API」并启用
内容的提问来源于stack exchange,提问作者EIT Mobility
相关产品推荐
相关产品推荐

