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

如何通过联系人组ID筛选Google People API的联系人?

解决Google People API按组ID筛选联系人的问题

我之前刚好处理过类似的需求,确实Google People API的connections.list方法没有提供直接按组ID筛选的参数,但我们可以在获取到所有联系人数据后,通过返回的memberships字段手动过滤出属于特定组的联系人。下面是具体的实现方案和修改后的代码:

核心思路

  1. 获取所有联系人:通过API的分页机制获取用户的全部联系人(因为单页最多返回200条,所以要处理分页逻辑避免遗漏)
  2. 过滤目标组联系人:检查每个联系人的memberships数组,判断是否包含目标组的contactGroupId

修改后的Node.js代码

const {google} = require('googleapis');

const getGoogleConnectionsByGroup = async (userToken, targetGroupId) => {
  const oauth2Client = new google.auth.OAuth2;
  oauth2Client.setCredentials({
    'access_token': userToken, // 来自Passport会话的用户token
  });
  const googlePeople = google.people({
    version: 'v1',
    auth: oauth2Client,
  });
  
  let allConnections = [];
  let nextPageToken = null;

  // 循环获取所有分页的联系人数据
  do {
    const params = {
      resourceName: 'people/me',
      pageSize: 200,
      sortOrder: 'LAST_MODIFIED_DESCENDING',
      personFields: ['names', 'emailAddresses', 'memberships', 'organizations'],
      pageToken: nextPageToken, // 传递分页token,获取下一页数据
    };
    const response = await googlePeople.people.connections.list(params);
    
    if (response.data.connections) {
      allConnections = [...allConnections, ...response.data.connections];
    }
    nextPageToken = response.data.nextPageToken;
  } while (nextPageToken);

  // 过滤出属于目标组的联系人
  const filteredContacts = allConnections.filter(contact => {
    // 使用可选链操作符避免空值报错,检查是否有匹配的组ID
    return contact.memberships?.some(membership => {
      return membership.contactGroupMembership?.contactGroupId === targetGroupId;
    });
  });

  return filteredContacts;
};

关键注意事项

  • 必须包含memberships字段:确保personFields参数里包含memberships,否则API返回的联系人数据中不会有组信息,过滤逻辑会失效
  • 处理分页:如果用户联系人数量超过200条,必须通过nextPageToken循环获取所有页的数据,不然会漏掉部分联系人
  • 空值安全:使用?.可选链操作符避免因某些联系人没有memberships字段而抛出错误

调用这个函数时,只需要传入用户的token和目标组ID即可:

// 示例调用
const targetGroup = 'your-target-contact-group-id';
const groupContacts = await getGoogleConnectionsByGroup(userToken, targetGroup);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 17:47:27