问题描述
因为 Google 正在弃用 Google 联系人 API,而是建议我们使用 Google People API 添加/创建/删除联系人。我能够创建、获取 Google 联系人,示例代码如下:
const { google } = require("googleapis")
const path = require("path")
const keyFile = path.join(__dirname,"serviceAccCredentials.json")
const scopes = [
"https://www.googleapis.com/auth/contacts","https://www.googleapis.com/auth/contacts.readonly"
]
function log(arg) {
console.log(JSON.stringify(arg,null,4))
}
const run = async () => {
try {
const { people,contactGroups } = google.people({
version: "v1",auth: await google.auth.getClient({
keyFile,scopes
})
})
const createContact = await people.createContact(
{
requestBody: {
names: [
{
givenname: "Yacov 3",familyName: "110$"
}
],"memberships": [
{
"contactGroupMembership": {
contactGroupId: 'myContacts'
// "contactGroupResourceName": "contactGroups/myContacts"
}
}
]
}
}
)
log(createContact.data)
const afterResponse = await people.connections.list({
resourceName: "people/me",personFields: "names",})
log(afterResponse.data)
} catch (e) {
console.log(e)
}
}
run()
问题是我在 Google 通讯录下看不到使用服务帐户创建的通讯录。通常,服务帐户是为 G-suit 用户创建的,在 G-suit 域范围的委派设置下,我还添加了具有范围的项目 ID。服务帐户中还启用了 People API。
此外,在 Google's official documentation 的操场区域,当我尝试创建 Google 联系人时,它起作用了。来自 API 资源管理器/游乐场的请求如下所示
const createContact = await people.createContact({
"personFields": "names","sources": [
"READ_SOURCE_TYPE_CONTACT"
],"prettyPrint": true,"alt": "json","resource": {
"names": [
{
"givenname": "test 2","familyName": "playground"
}
],"memberships": [
{
"contactGroupMembership": {
"contactGroupResourceName": "contactGroups/myContacts"
}
}
]
}
})
奇怪的是,contactGroupResourceName
、personFields
、sources
、alt
、prettyPrint
等所有这些属性都不存在。
谁能告诉我这是怎么回事。 PS:我不能也不想使用 OAuth2,因为应用程序将是服务器到服务器的通信,不会涉及任何人的同意。谢谢
解决方法
问题:
您可能已为您的服务帐户启用了全域委派,但您并未使用它来冒充普通用户。
域范围委派的目的是让服务帐户代表域中的任何用户进行操作,但为此,您必须指定您希望服务帐户模拟哪个用户。
否则,服务帐户将访问自己的资源(通讯录、云端硬盘、日历等),而不是常规帐户的资源。因此,如果您使用普通帐户访问通讯录 UI,您将看不到已创建的联系人,因为联系人不是为此帐户创建的。
解决方案:
您需要模拟要为其创建联系人的帐户。
为了做到这一点,由于您使用的是 Node 的 getClient(),您应该指定要模拟的帐户的电子邮件地址,如图所示 here:
auth.subject = "email-address-to-impersonate";
更新:
在这种情况下,您可以执行以下操作:
let auth = await google.auth.getClient({
keyFile,scopes
});
auth.subject = "email-address-to-impersonate";
const { people,contactGroups } = google.people({
version: "v1",auth: auth
})