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

如何在Google People API的NodeJS SDK中使用有效OAuth2访问令牌

在Google People Node.js SDK中传递访问令牌的方法

你有两种可靠的方式来传递已获取的访问令牌:

1. 初始化People客户端时通过auth参数传入

根据类型定义,people构造函数的options.auth字段支持直接传入字符串类型的访问令牌。这种方式会为整个客户端实例设置全局认证,后续所有API调用都会自动使用该令牌。

示例代码:

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

// 替换为你的实际访问令牌
const accessToken = 'YOUR_VALID_ACCESS_TOKEN';

// 初始化People客户端并传入访问令牌
const peopleClient = google.people({
  version: 'v1',
  auth: accessToken
});

// 调用API获取用户手机号
async function fetchUserPhoneNumber() {
  try {
    const response = await peopleClient.people.get({
      resourceName: 'people/me',
      personFields: 'phoneNumbers'
    });
    console.log('用户手机号列表:', response.data.phoneNumbers);
  } catch (error) {
    console.error('获取用户信息失败:', error.message);
  }
}

fetchUserPhoneNumber();

2. 调用单个API方法时通过access_token参数传入

在调用具体的API方法(比如people.get)时,可以直接在参数中添加access_token字段,将令牌传递给单次请求。这种方式适合需要为不同请求使用不同令牌的场景。

示例代码:

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

const peopleClient = google.people({ version: 'v1' });

// 替换为你的实际访问令牌
const accessToken = 'YOUR_VALID_ACCESS_TOKEN';

// 调用API时传入访问令牌
async function fetchUserPhoneNumber() {
  try {
    const response = await peopleClient.people.get({
      resourceName: 'people/me',
      personFields: 'phoneNumbers',
      access_token: accessToken
    });
    console.log('用户手机号列表:', response.data.phoneNumbers);
  } catch (error) {
    console.error('获取用户信息失败:', error.message);
  }
}

fetchUserPhoneNumber();

两种方式都能满足你创建账户时获取用户手机号的需求,可根据后续是否有更多API调用场景选择:全局设置更适合复用令牌,单次传入则更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:20:29