google-api - 以编程方式接受服务帐户的“Google 我的商家”邀请
问题描述
我正在尝试使用服务帐户通过 Google My Business API 检索位置/评论。
到目前为止,我有:
- 在 Developers Console 中创建了一个项目
- 启用对 Google My Business API 的访问(已被 Google 批准/列入白名单)
- 使用关联的 OAuth 身份创建服务帐户
- 邀请 OAuth 身份(即服务帐户)作为“Google 我的商家”位置的管理员
当使用可从https://developers.google.com/my-business/sampleshttps://mybusiness.googleapis.com/v4/accounts/[ACCOUNT NAME]/invitations
下载的 Google 示例 .NET 客户端以编程方式列出邀请时,我能够看到邀请
但是,当我尝试通过https://mybusiness.googleapis.com/v4/accounts/[ACCOUNT NAME]/invitations/[INVITATION NAME]:accept
请求接受邀请时失败并出现 500 服务器错误。
创建MyBusinessService
实例时,我首先创建一个服务帐户凭据,例如:
ServiceAccountCredential credential;
using (Stream stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read, FileShare.Read))
{
credential = (ServiceAccountCredential)GoogleCredential
.FromStream(stream)
.CreateScoped(new [] { "https://www.googleapis.com/auth/plus.business.manage" })
.UnderlyingCredential;
}
接下来我创建一个初始化器,如:
var initializer = new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "My GMB API Client",
GZipEnabled = true,
};
最后,我创建了一个MyBusinessService
实例,例如:var service = new MyBusinessService(initializer);
我可以列出邀请:
service.Accounts
.Invitations
.List("[ACCOUNT NAME]")
.Execute()
.Invitations;
但是,尝试接受邀请失败:
service.Accounts
.Invitations
.Accept(null, "[INVITATION NAME]")
.Execute();
第一个参数null
如本文档所述,请求正文应为空。
或者是否有其他方式可以接受邀请,以使服务帐户能够检索我们所在位置的“Google 我的商家”评论?
解决方案
要作为服务器到服务器身份验证的服务帐户登录,您需要为您的服务帐户启用域范围委派。https://developers.google.com/admin-sdk/directory/v1/guides/delegation
完成此操作后,您可以通过模拟已获批准的“我的商家”经理的电子邮件地址,让您的服务帐户登录到“Google 我的商家”API。这是在 NodeJS 中,这是我使用的:
const { google } = require('googleapis'); // MAKE SURE TO USE GOOGLE API
const { default: axios } = require('axios'); //using this for api calls
const key = require('./serviceaccount.json'); // reference to your service account
const scopes = 'https://www.googleapis.com/auth/business.manage'; // can be an array of scopes
const jwt = new google.auth.JWT({
email: key.client_email,
key: key.private_key,
scopes: scopes,
subject: `impersonated@email.com`
});
async function getAxios() {
const response = await jwt.authorize() // authorize key
let token = response.access_token // dereference token
console.log(response)
await axios.get('https://mybusiness.googleapis.com/v4/accounts', {
headers: {
Authorization: `Bearer ${token}`
} // make request
})
.then((res) => { // handle response
console.log(res.data);
})
.catch((err) => { // handle error
console.log(err.response.data);
})
}
await getAxios(); // call the function
推荐阅读
- javascript - 试图分配给只读属性反应本机错误
- android - 使用 Vision API 实现自定义检测器
- python - 无法在 Django 外键字段中插入值
- c# - 对于 CosmosDB,如何将日期值转换为 YYYY-MM-DDThh:mm:ss.sssZ 格式的字符串?
- c# - C#:如何在文本框中获取 xml 值?
- python - Executor Map 不运行函数
- node.js - 通过节点快递在 MongoDB 中发送 POST 请求时验证错误说需要路径
- python - Python PIL load() 将像素图与数据作为具有 4 个值的元组
- c# - Xamarin Build Error Compilation 无法完成,因为缺少某些库类
- python - Altair:全球地图居中