Node.js 版快速入门

快速入门介绍了如何设置和运行调用 Google Workspace API 的应用。

Google Workspace 快速入门使用 API 客户端库来处理身份验证和授权流程的某些详细信息。我们建议您为自己的应用使用客户端库。本快速入门使用适用于测试环境的简化身份验证方法。对于生产环境,我们建议您先了解身份验证和授权,然后再选择适合您应用的访问凭据

创建一个向 People API 发出请求的 Node.js 命令行应用。

目标

  • 设置环境。
  • 安装客户端库。
  • 设置示例。
  • 运行示例。

前提条件

如需运行本快速入门,您需要满足以下前提条件:

设置您的环境

如需完成本快速入门,请设置您的环境。

启用 API

在使用 Google API 之前,您需要在 Google Cloud 项目中启用它们。您可以在单个 Google Cloud 项目中启用一个或多个 API。
  • 在 Google Cloud 控制台中,启用 People API。

    启用 API

如果您要使用新的 Google Cloud 项目完成本快速入门,请配置 OAuth 权限请求页面,并将您自己添加为测试用户。如果您已为自己的 Cloud 项目完成此步骤,请跳到下一部分。

  1. 在 Google Cloud 控制台中,依次点击“菜单”图标 > API 和服务 > OAuth 同意屏幕

    转到 OAuth 同意屏幕

  2. 对于用户类型,选择内部,然后点击创建
  3. 填写应用注册表单,然后点击保存并继续
  4. 目前,您可以跳过添加范围的步骤,点击 Save and Continue(保存并继续)。 将来,当您创建要在 Google Workspace 组织外部使用的应用时,必须将用户类型更改为外部,然后添加您的应用所需的授权范围。

  5. 查看您的应用注册摘要。如要进行更改,请点击修改。如果应用注册看起来正常,请点击 Back to Dashboard

为桌面应用授权凭据

如需在您的应用中对最终用户进行身份验证并访问用户数据,您需要创建一个或多个 OAuth 2.0 客户端 ID。客户端 ID 用于向 Google 的 OAuth 服务器标识单个应用。如果您的应用在多个平台上运行,则必须为每个平台创建单独的客户端 ID。
  1. 在 Google Cloud 控制台中,依次点击“菜单”图标 > API 和服务 > 凭据

    进入“凭据”页面

  2. 依次点击创建凭据 > OAuth 客户端 ID
  3. 依次点击应用类型 > 桌面应用
  4. 名称字段中,输入凭据的名称。此名称只会显示在 Google Cloud 控制台中。
  5. 点击创建。系统会显示 OAuth 客户端已创建屏幕,其中显示了您的新客户端 ID 和客户端密钥。
  6. 点击 OK。新创建的凭据会显示在 OAuth 2.0 客户端 ID 下方。
  7. 将下载的 JSON 文件另存为 credentials.json,然后将该文件移动到工作目录。

安装客户端库

  • 使用 npm 安装库:

    npm install googleapis@105 @google-cloud/local-auth@2.1.0 --save
    

设置示例

  1. 在您的工作目录中,创建一个名为 index.js 的文件。

  2. 在文件中粘贴以下代码:

    people/quickstart/index.js
    const fs = require('fs').promises;
    const path = require('path');
    const process = require('process');
    const {authenticate} = require('@google-cloud/local-auth');
    const {google} = require('googleapis');
    
    // If modifying these scopes, delete token.json.
    const SCOPES = ['https://www.googleapis.com/auth/contacts.readonly'];
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    const TOKEN_PATH = path.join(process.cwd(), 'token.json');
    const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');
    
    /**
     * Reads previously authorized credentials from the save file.
     *
     * @return {Promise<OAuth2Client|null>}
     */
    async function loadSavedCredentialsIfExist() {
      try {
        const content = await fs.readFile(TOKEN_PATH);
        const credentials = JSON.parse(content);
        return google.auth.fromJSON(credentials);
      } catch (err) {
        return null;
      }
    }
    
    /**
     * Serializes credentials to a file compatible with GoogleAuth.fromJSON.
     *
     * @param {OAuth2Client} client
     * @return {Promise<void>}
     */
    async function saveCredentials(client) {
      const content = await fs.readFile(CREDENTIALS_PATH);
      const keys = JSON.parse(content);
      const key = keys.installed || keys.web;
      const payload = JSON.stringify({
        type: 'authorized_user',
        client_id: key.client_id,
        client_secret: key.client_secret,
        refresh_token: client.credentials.refresh_token,
      });
      await fs.writeFile(TOKEN_PATH, payload);
    }
    
    /**
     * Load or request or authorization to call APIs.
     *
     */
    async function authorize() {
      let client = await loadSavedCredentialsIfExist();
      if (client) {
        return client;
      }
      client = await authenticate({
        scopes: SCOPES,
        keyfilePath: CREDENTIALS_PATH,
      });
      if (client.credentials) {
        await saveCredentials(client);
      }
      return client;
    }
    
    /**
     * Print the display name if available for 10 connections.
     *
     * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
     */
    async function listConnectionNames(auth) {
      const service = google.people({version: 'v1', auth});
      const res = await service.people.connections.list({
        resourceName: 'people/me',
        pageSize: 10,
        personFields: 'names,emailAddresses',
      });
      const connections = res.data.connections;
      if (!connections || connections.length === 0) {
        console.log('No connections found.');
        return;
      }
      console.log('Connections:');
      connections.forEach((person) => {
        if (person.names && person.names.length > 0) {
          console.log(person.names[0].displayName);
        } else {
          console.log('No display name found for connection.');
        }
      });
    }
    
    authorize().then(listConnectionNames).catch(console.error);
    

运行示例

  1. 在您的工作目录中,运行示例:

    node .
    
  1. 首次运行示例时,系统会提示您授予访问权限:
    1. 如果您尚未登录 Google 帐号,请在系统提示时登录。如果您已登录多个帐号,请选择一个帐号用于授权。
    2. 点击接受

    您的 Nodejs 应用运行并调用 People API。

    授权信息存储在文件系统中,因此当您下次运行示例代码时,系统不会提示您授权。

后续步骤