JavaScript 快速入門導覽課程

快速入門導覽課程說明如何設定及執行呼叫 Google Workspace API 的應用程式。

Google Workspace 快速入門導覽課程會使用 API 用戶端程式庫,處理驗證和授權流程的部分細節。建議您為自己的應用程式採用用戶端程式庫。本快速入門導覽課程採用適用於測試環境的簡易驗證方法。如果是實際工作環境,建議您先瞭解驗證與授權,再選擇適合應用程式的存取憑證

建立 JavaScript 網頁應用程式,向 Google Docs API 提出要求。

目標

  • 設定環境。
  • 設定範例。
  • 執行範例。

先備知識

  • Google 帳戶

設定環境

如要完成本快速入門導覽課程,請設定環境。

啟用 API

使用 Google API 前,您必須先在 Google Cloud 專案中啟用 API。您可以在單一 Google Cloud 專案中啟用一或多個 API。
  • 在 Google Cloud 控制台中,啟用 Google Docs API。

    啟用 API

如果您使用新的 Google Cloud 專案完成本快速入門導覽課程,請設定 OAuth 同意畫面,並將自己新增為測試使用者。如果您已經為 Cloud 專案完成這個步驟,請跳到下一部分。

  1. 在 Google Cloud 控制台中,依序前往「選單」圖示 >「API 和服務」>「OAuth 同意畫面」

    前往 OAuth 同意畫面

  2. 在「使用者類型」部分選取「內部」,然後按一下「建立」
  3. 填寫應用程式註冊表單,然後按一下「儲存並繼續」
  4. 您現在可以略過新增範圍的步驟,然後按一下「儲存並繼續」。 日後建立要在 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. 新增與應用程式相關的已授權 URI:
    • 用戶端應用程式 (JavaScript):按一下「授權的 JavaScript 來源」下方的「新增 URI」。然後輸入瀏覽器要求的 URI。可識別應用程式可以從哪些網域傳送 API 要求至 OAuth 2.0 伺服器。
    • 伺服器端應用程式 (Java、Python 等):按一下「已授權的重新導向 URI」下方的「新增 URI」。然後輸入端點 URI,讓 OAuth 2.0 伺服器傳送回應。
  6. 按一下「建立」,畫面上會顯示 OAuth 用戶端建立的畫面,其中顯示新的用戶端 ID 和用戶端密鑰。

    記下用戶端 ID。用戶端密碼不適用於網頁應用程式,

  7. 按一下「OK」(確定)。新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」之下。

請記下這些憑證,因為本快速入門導覽課程稍後會用到。

建立 API 金鑰

  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 >「API 和服務」>「憑證」>

    前往「憑證」

  2. 依序按一下「建立憑證」>「API 金鑰」
  3. 畫面上會顯示新的 API 金鑰。
    • 按一下「複製」圖示 ,即可複製 API 金鑰,以便用於應用程式的程式碼。您也可以在專案憑證的「API 金鑰」部分找到 API 金鑰。
    • 按一下「限制金鑰」,即可更新進階設定並限制 API 金鑰的使用情形。詳情請參閱「套用 API 金鑰限制」一節。

設定範例

  1. 在工作目錄中,建立名為 index.html 的檔案。
  2. index.html 檔案中,貼上下列程式碼:

    docs/quickstart/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Google Docs API Quickstart</title>
        <meta charset="utf-8" />
      </head>
      <body>
        <p>Google Docs API Quickstart</p>
    
        <!--Add buttons to initiate auth sequence and sign out-->
        <button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
        <button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
    
        <pre id="content" style="white-space: pre-wrap;"></pre>
    
        <script type="text/javascript">
          /* exported gapiLoaded */
          /* exported gisLoaded */
          /* exported handleAuthClick */
          /* exported handleSignoutClick */
    
          // TODO(developer): Set to client ID and API key from the Developer Console
          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://docs.googleapis.com/$discovery/rest?version=v1';
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          const SCOPES = 'https://www.googleapis.com/auth/documents.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 = 'visible';
            }
          }
    
          /**
           *  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 printDocTitle();
            };
    
            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';
            }
          }
    
          /**
           * Prints the title of a sample doc:
           * https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit
           */
          async function printDocTitle() {
            try {
              const response = await gapi.client.docs.documents.get({
                documentId: '195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE',
              });
              const doc = response.result;
              const output = `Document ${doc.title} successfully found.\n`;
              document.getElementById('content').innerText = output;
            } catch (err) {
              document.getElementById('content').innerText = err.message;
              return;
            }
          }
        </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. 在工作目錄中啟動網路伺服器:

    npx http-server -p 8000
    
  1. 透過瀏覽器前往 http://localhost:8000
  2. 系統會提示您授予存取權:
    1. 如果尚未登入 Google 帳戶,請在系統提示時登入。如果您登入了多個帳戶,請選取一個要用於授權的帳戶。
    2. 然後點選 [Accept]

您的 JavaScript 應用程式會執行並呼叫 Google Docs API。

後續步驟