JavaScript 快速入門導覽課程

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

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

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

目標

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

必備條件

  • 擁有已啟用 Google 雲端硬碟的 Google 帳戶。

設定環境

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

啟用 API

使用 Google API 前,請先在 Google Cloud 專案中啟用這些 API。您可以在單一 Google Cloud 專案中啟用一或多個 API。
  • 在 Google Cloud 控制台中啟用 Google Drive API。

    啟用 API

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

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

    前往 OAuth 同意畫面

  2. 選取應用程式的使用者類型,然後按一下「Create」
  3. 填寫應用程式註冊表單,然後按一下「儲存並繼續」
  4. 目前,您可以略過新增範圍,然後按一下「儲存並繼續」。日後建立適用於 Google Workspace 機構外部的應用程式時,您必須新增並驗證應用程式需要的授權範圍。

  5. 針對使用者類型選取「外部」,請新增測試使用者:
    1. 在「測試使用者」下方,點選「新增使用者」
    2. 輸入您的電子郵件地址和任何其他授權測試使用者,然後按一下「儲存並繼續」
  6. 查看您的應用程式註冊摘要。如要變更,請按一下「編輯」。如果應用程式註冊正確無誤,請按一下「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。此屬性可識別應用程式可從哪些網域向 OAuth 2.0 伺服器傳送 API 要求。
    • 伺服器端應用程式 (Java、Python 等):在「授權的重新導向 URI」下方,按一下「新增 URI」。然後輸入端點 URI,OAuth 2.0 伺服器可將回應傳送至這個 URI。
  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 檔案中,貼上以下程式碼範例:

    drive/quickstart/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Drive API Quickstart</title>
        <meta charset="utf-8" />
      </head>
      <body>
        <p>Drive 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://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          const SCOPES = 'https://www.googleapis.com/auth/drive.metadata.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 listFiles();
            };
    
            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 metadata for first 10 files.
           */
          async function listFiles() {
            let response;
            try {
              response = await gapi.client.drive.files.list({
                'pageSize': 10,
                'fields': 'files(id, name)',
              });
            } catch (err) {
              document.getElementById('content').innerText = err.message;
              return;
            }
            const files = response.result.files;
            if (!files || files.length == 0) {
              document.getElementById('content').innerText = 'No files found.';
              return;
            }
            // Flatten to string to display
            const output = files.reduce(
                (str, file) => `${str}${file.name} (${file.id})\n`,
                'Files:\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. 在工作目錄中啟動網路伺服器:

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

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

後續步驟