JavaScript 快速入门

创建一个向 Gmail API 发出请求的 JavaScript Web 应用。

快速入门介绍了如何设置和运行调用 Google Workspace API 的应用。本快速入门使用适合测试环境的简化身份验证方法。对于生产环境,我们建议您先了解身份验证和授权,然后再选择适合您应用的访问凭据。

本快速入门使用 Google Workspace 推荐的 API 客户端库来处理身份验证和授权流程的一些细节。

目标

  • 设置环境。
  • 设置示例。
  • 运行示例。

前提条件

  • 已启用 Gmail 的 Google 账号。

设置环境

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

启用 API

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

    启用 API

配置 OAuth 权限请求页面

如果您使用新的 Google Cloud 云项目完成本快速入门,请配置 OAuth 权限请求页面。如果您已为 Cloud 项目完成此步骤,请跳至下一部分。

  1. 在 Google API 控制台中,依次点击“菜单” > Google Auth 平台 > 品牌塑造。

    前往“品牌塑造”

  2. 如果您已配置 Google Auth Platform,则可以在品牌、受众群体和数据访问中配置以下 OAuth 权限请求页面设置。如果您看到一条消息,提示尚未配置 Google Auth Platform,请点击开始使用:
    1. 在应用信息下的应用名称中,输入应用的名称。
    2. 在用户支持邮箱中,选择一个支持邮箱,供用户在遇到同意情况相关问题时与您联系。
    3. 点击下一步。
    4. 在受众群体下,选择内部。
    5. 点击下一步。
    6. 在联系信息下,输入一个邮箱,以便您接收有关项目变更的通知。
    7. 点击下一步。
    8. 在完成下,查看 Google API 服务用户数据政策,如果您同意,请选择我同意 Google API 服务:用户数据政策。
    9. 点击继续。
    10. 点击创建。
  3. 目前,您可以跳过添加范围。 未来,如果您创建的应用要在 Google Workspace 组织外部使用,则必须将用户类型更改为外部。然后,添加应用所需的授权范围。如需了解详情,请参阅完整的配置 OAuth 同意指南。

为 Web 应用授权凭据

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

    前往“客户”页面

  2. 点击创建客户端。
  3. 依次点击应用类型 > Web 应用。
  4. 在名称字段中,输入凭证的名称。此名称仅在 Google Cloud 控制台中显示。
  5. 添加与您的应用相关的已获授权的 URI:
    • 客户端应用 (JavaScript) - 在已获授权的 JavaScript 来源下,点击添加 URI。然后,输入要用于浏览器请求的 URI。这会标识您的应用可以从中向 OAuth 2.0 服务器发送 API 请求的网域。
    • 服务器端应用(Java、Python 等)- 在已获授权的重定向 URI 下,点击添加 URI。然后,输入 OAuth 2.0 服务器可以向其发送响应的端点 URI。
  6. 可选:如果您的应用是代表用户执行操作的 AI 智能体,请选择将此客户端用于 AI 赋能的智能体。如果您的应用同时支持 AI 智能体工作流和标准用户功能,请为二者分别创建独立的 OAuth 客户端。创建客户端后,您将无法更改此设置。
  7. 点击创建。

    新创建的凭证会显示在 OAuth 2.0 客户端 ID 下。

    请注意,Web 应用不使用客户端密钥。

  8. 保存客户端 ID,以便在本快速入门的后续步骤中使用。

创建 API 密钥

  1. 在 Google Cloud 控制台中,依次点击“菜单” > API 和服务 > 凭证。

    进入“凭据”页面

  2. 点击创建凭据 > API 密钥。
  3. 系统会显示您的新 API 密钥。
    • 点击“复制”图标 ,复制 API 密钥,以便在应用代码中使用。您还可以在项目的凭证的“API 密钥”部分找到 API 密钥。
    • 为防止未经授权的使用,我们建议您限制 API 密钥可用于哪些位置和 API。如需了解详情,请参阅添加 API 限制。

设置示例

  1. 在工作目录中,创建一个名为 index.html 的文件。
  2. 在 index.html 文件中,粘贴以下示例代码:

    gmail/quickstart/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Gmail API Quickstart</title>
        <meta charset="utf>-8&<quot;> /
    <  /h>ead
     < >body
        pGmail API <Qu>icksta<rt/p
    
        !--Add buttons to initiate auth sequence and >sign <out--
        button id="authorize_button" onclick>="ha<ndleAut>hClic<k()"Authorize/button
        button id="signout_but>ton"<; oncli>ck=&qu<ot;handleSignoutClick()"Sign Out/button
    
     ><   p>re id=<"content" style=&qu>ot;white-space: pre-wrap;"/pre
    
        script type="text/javascript"
          /* exported gapiLoaded */
          /* exported gisLoaded */
          /* exported handleAuthClick */
          /* exported handleSignoutClick */
    
          // TODO(developer): S<et to client I>D and API key from the Dev<eloper Conso>le
          const CLIENT_ID = 'YOUR_CLIENT_ID';
          const API_KEY = 'YOUR_API_KEY';
    
          // Discovery doc URL for APIs used by the quickstart
          const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest';
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          const SCOPES = 'https://www.googleapis.com/auth/gmail.readonly';
    
          let tokenClient;
          let gapiInited = false;
          let gisInited = false;
    
          document.getElementById('authorize_button').style.visibility = 'hidden';
          document.getElementById('signout_button').style.visibility = 'hidden';
    
          /**
           * Callback after api.js is loaded.
           */
          function gapiLoaded() {
            gapi.load('client', initializeGapiClient);
          }
    
          /**
           * Callback after the API client is loaded. Loads the
           * discovery doc to initialize the API.
           */
          async function initializeGapiClient() {
            await gapi.client.init({
              apiKey: API_KEY,
              discoveryDocs: [DISCOVERY_DOC],
            });
            gapiInited = true;
            maybeEnableButtons();
          }
    
          /**
           * Callback after Google Identity Services are loaded.
           */
          function gisLoaded() {
            tokenClient = google.accounts.oauth2.initTokenClient({
              client_id: CLIENT_ID,
              scope: SCOPES,
              callback: '', // defined later
            });
            gisInited = true;
            maybeEnableButtons&&();
          }
    
          /**
           * Enables user interaction after all libraries are loaded.
           */
          function maybeEnableButtons() {
            if (gapiInited  gisInited) {
              document.getElementById('authorize_button').style.visibility = 'vis>ible';
            }
          }
    
          /**
           *  Sign in the user upon button click.
           */
          function handleAuthClick() {
            tokenClient.callback = async (resp) = {
              if (resp.error !== undefined) {
                throw (resp);
              }
              document.getElementById('signout_button').style.visibility = 'visible';
              document.getElementById('authorize_button').innerText = 'Refresh';
              await listLabels();
            };
    
            if (gapi.client.getToken() === null) {
              // Prompt the user to select a Google Account and ask for consent to share their data
              // when establishing a new session.
              tokenClient.requestAccessToken({prompt: 'consent'});
            } else {
              // Skip display of account chooser and consent dialog for an existing session.
              tokenClient.requestAccessToken({prompt: ''});
            }
          }
    
          /**
           *  Sign out the user upon button click.
           */
          function handleSignoutClick() {
            const token = gapi.client.getToken();
            if (token !== null) {
              google.accounts.oauth2.revoke(token.access_token);
              gapi.client.setToken('');
              document.getElementById('content').innerText = '';
              document.getElementById('authorize_button').innerText = 'Authorize';
              document.getElementById('signout_button').style.visibility = 'hidden';
            }
          }
    
          /**
           * Print all Labels in the authorized user's inbox. If no labels
           * are found an appropriate message is printed.
           */
          async function listLabels() {
            let response;
            try {
              response = await gapi.client.gmail.users.labels.list({
                'userId': 'me',
              });
            } catch (err) {
              document.getElementById('content').innerText = err.message;
              return;
       >     }
            const labels = response.result.labels;
            if (!labels || labels.length == 0) {
              document.getElemen<tById(&>#39;c<ontent').innerText = 'No labels found.';
              return;
            }><
          >  // <Flatten to string to display
            const output = labels.reduce(
                (str,>< label)> = <`${st>r<}${la>bel.name}\n`,
                'Labels:\n');
            document.getElementById('content').innerText = output;
          }
        /script
        script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"/script
        script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"/script
      /body
    /html

    替换以下内容:

运行示例

  1. 在工作目录中,安装 http-server 软件包:

    npm install http-server
    
  2. 在工作目录中,启动 Web 服务器:

    npx http-server -p 8000
    
  1. 在浏览器中,前往 http://localhost:8000。
  2. 您会看到一个提示,要求您授予访问权限:
    1. 如果您尚未登录 Google 账号,请在系统提示时登录。如果您登录了多个账号,请选择一个账号用于授权。
    2. 点击接受。

您的 JavaScript 应用会运行并调用 Gmail API。

后续步骤