以 Google Chat 應用程式的身分進行驗證

本指南說明如何設定及使用服務帳戶,以便代表 Chat 應用程式存取 Google Chat API。首先,該工具將逐步引導您建立服務帳戶。接著,它會示範如何編寫使用服務帳戶進行 Chat API 驗證,並在 Chat 聊天室中張貼訊息的指令碼。

在非同步呼叫 Google Chat API 時,即時通訊應用程式可以使用服務帳戶進行驗證,以便執行下列作業:

  • 透過 spaces.messages.create 傳送訊息至 Google Chat,即可:
    • 在長時間執行的背景工作執行完畢時通知使用者。
    • 通知使用者伺服器已離線。
    • 要求客戶服務人員傾向提出新的客戶客服案件。
  • 使用 spaces.messages.update 將先前傳送的訊息更新為:
    • 變更進行中作業的狀態。
    • 更新工作的指派對像或截止日期。
  • 透過 spaces.members.list 列出聊天室中的使用者,以便執行下列操作:
    • 查看聊天室成員。
    • 確認聊天室成員包含團隊成員。

透過服務帳戶完成驗證後,如要取得 Chat 聊天室中的相關資料或執行動作,Chat 應用程式必須具有聊天室成員資格。舉例來說,如要列出聊天室的成員,或是在聊天室中建立訊息,則 Chat 應用程式本身必須是聊天室的成員。

如果您的 Chat 應用程式需要存取使用者資料或代表使用者執行動作,請改為以使用者身分進行驗證

如果您是網域管理員,可以授予全網域授權委派權限,授權應用程式服務帳戶存取您使用者的資料,不必要求每位使用者都提供同意。設定全網域委派後,您可以使用服務帳戶發出 API 呼叫來模擬使用者帳戶。雖然服務帳戶會用於驗證,但全網域委派會模擬使用者,因此會將使用者視為使用者驗證。任何需要使用者驗證的功能都可以使用全網域委派。

如要進一步瞭解即時通訊應用程式何時需要驗證,以及使用何種驗證類型,請參閱 Chat API 驗證與授權總覽中的必要驗證類型一節。

必要條件

如要執行本指南中的範例,您必須具備以下先決條件:

此外,您還需要下列語言特有的先決條件:

Java

  • JDK 1.7 以上版本
  • Maven 套件管理工具
  • 已初始化 Maven 專案。如要初始化新專案,請在指令列介面中執行下列指令:

    mvn archetype:generate -DgroupId=com.google.chat.app.authsample -DartifactId=auth-sample-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
    

Python

  • Python 3.6 以上版本
  • pip 套件管理工具

Node.js

  • Node.js
  • npm 套件管理工具
  • 已初始化 Node.js 專案。如要初始化新專案,請建立並切換至新資料夾,然後在指令列介面中執行下列指令:

    npm init
    

Apps Script

步驟 1:在 Google Cloud 控制台中建立服務帳戶

建立 Chat 應用程式可用來存取 Google API 的服務帳戶。

建立服務帳戶

如要建立服務帳戶,請按照下列步驟操作:

  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 >「IAM 與管理」>「服務帳戶」

    前往「Service Accounts」(服務帳戶)

  2. 按一下「建立服務帳戶」
  3. 填寫服務帳戶詳細資料,然後按一下「建立並繼續」
  4. 選用:為服務帳戶指派角色,即可授予 Google Cloud 專案資源的存取權。詳情請參閱授予、變更及撤銷資源的存取權
  5. 按一下 [繼續]。
  6. 選用:輸入可透過這個服務帳戶管理及執行動作的使用者或群組。詳情請參閱管理服務帳戶模擬功能
  7. 按一下 [完成]。記下服務帳戶的電子郵件地址。

服務帳戶會顯示在服務帳戶頁面上。接下來,為服務帳戶建立私密金鑰。

建立私密金鑰

如要為服務帳戶建立及下載私密金鑰,請按照下列步驟操作:

  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 >「IAM 與管理」>「服務帳戶」

    前往「Service Accounts」(服務帳戶)

  2. 選取您的服務帳戶。
  3. 依序按一下「金鑰」>「新增金鑰」>「建立新的金鑰」
  4. 選取「JSON」,然後按一下「Create」(建立)

    系統會產生一組新的公開/私密金鑰,並以新檔案的形式下載到您的電腦。將下載的 JSON 檔案儲存為 credentials.json 在工作目錄中。這個檔案是該金鑰的唯一副本。如要瞭解如何安全儲存金鑰,請參閱「管理服務帳戶金鑰」。

  5. 按一下「關閉」

如要進一步瞭解服務帳戶,請參閱 Google Cloud IAM 說明文件中的服務帳戶

步驟 2:安裝 Google 用戶端程式庫和其他依附元件

安裝專案所需的 Google 用戶端程式庫和其他依附元件。

Java

如要在 Maven 專案中加入 Google 用戶端程式庫和其他必要依附元件,請在專案目錄中編輯 pom.xml 檔案,並新增下列依附元件:

<dependencies>
  <!-- ... existing dependencies ... -->
  <dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-chat</artifactId>
    <version>v1-rev20230905-2.0.0</version>
  </dependency>
  <dependency>
    <groupId>com.google.auth</groupId>
    <artifactId>google-auth-library-oauth2-http</artifactId>
    <version>1.19.0</version>
  </dependency>
  <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.10.1</version>
  </dependency>
</dependencies>

Python

如果您尚未安裝 Python 適用的 Google 用戶端程式庫,請在指令列介面中執行下列指令:

pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client

Node.js

如要將 Google 用戶端程式庫新增至 Node.js 專案,請切換至專案的目錄,然後在指令列介面中執行下列指令:

npm install "@googleapis/chat"

Apps Script

這個範例使用 Apps Script 程式庫的 OAuth2 產生服務帳戶驗證的 JWT 憑證。如何在 Apps Script 專案中加入程式庫:

  1. 按一下左側的「編輯器」圖示
  2. 在左側的「Libraries」(資料庫) 旁邊,按一下「Add a Library」(新增程式庫)
  3. 輸入指令碼 ID 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
  4. 依序按一下「查詢」和「新增」

您可以使用用戶端程式庫支援的任何語言。

步驟 3:編寫使用服務帳戶向 Chat API 進行驗證的指令碼

以下程式碼使用服務帳戶向 Chat API 進行驗證,然後訊息張貼到 Chat 聊天室:

Java

  1. 在專案的目錄中開啟 src/main/java/com/google/chat/app/authsample/App.java 檔案。
  2. App.java 中的內容替換為以下程式碼:

    package com.google.chat.app.authsample;
    
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpRequestInitializer;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.services.chat.v1.HangoutsChat;
    import com.google.api.services.chat.v1.model.Message;
    import com.google.auth.http.HttpCredentialsAdapter;
    import com.google.auth.oauth2.GoogleCredentials;
    
    /**
     * Authenticates with Chat API via service account credentials,
     * then creates a Chat message.
     */
    public class App {
        // Specify required scopes.
        private static final String CHAT_SCOPE = "https://www.googleapis.com/auth/chat.bot";
    
        // Specify service account details.
        private static final String PRIVATE_KEY_RESOURCE_URI = "/credentials.json";
    
        public static void main( String[] args ) {
            try {
                // Run app.
                Message response = App.createChatMessage();
                // Print details about the created message.
                System.out.println(response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private static Message createChatMessage() throws Exception {
            // Build the Chat API client and authenticate with the service account.
            GoogleCredentials credentials = GoogleCredentials.fromStream(
                App.class.getResourceAsStream(PRIVATE_KEY_RESOURCE_URI))
                .createScoped(CHAT_SCOPE);
            HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
            HangoutsChat chatService = new HangoutsChat.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                GsonFactory.getDefaultInstance(),
                requestInitializer)
                .setApplicationName("auth-sample-app")
                .build();
    
            // The space to create the message in.
            //
            // Replace SPACE_NAME with a space name.
            // Obtain the space name from the spaces resource of Chat API,
            // or from a space's URL.
            String spaceName = "spaces/SPACE_NAME";
    
            // Create a Chat message.
            Message message = new Message().setText("Hello, world!");
            return chatService.spaces().messages().create(spaceName, message).execute();
        }
    }
    
  3. 將程式碼中的 SPACE_NAME 替換為聊天室名稱,這個名稱可從 Chat API 的 spaces.list 方法或聊天室網址取得。

  4. 在專案的目錄中建立名為 resources 的新子目錄。

  5. 確認服務帳戶的私密金鑰檔案名稱為 credentials.json,並將檔案複製到 resources 子目錄。

  6. 如要設定 Maven 在專案套件中納入私密金鑰檔案,請在專案目錄中編輯 pom.xml 檔案,並將下列設定新增至 <build> 區段:

    <build>
      <!-- ... existing configurations ... -->
      <resources>
        <resource>
          <directory>resources</directory>
        </resource>
      </resources>
    </build>
    
  7. 如要設定 Maven 在專案套件中納入依附元件,並執行應用程式的主要類別,請編輯專案目錄中的 pom.xml 檔案,並將下列設定新增至 <plugins> 區段:

    <plugins>
      <!-- ... existing configurations ... -->
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.google.chat.app.authsample.App</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
    

Python

  1. 在工作目錄中,建立名為 chat_app_auth.py 的檔案。
  2. chat_app_auth.py 中加入下列程式碼:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE_NAME with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE_NAME',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    # Prints details about the created message.
    print(result)
    
  3. 將程式碼中的 SPACE_NAME 替換為聊天室名稱,這個名稱可從 Chat API 的 spaces.list 方法或聊天室網址取得。請確認服務帳戶的私密金鑰檔案名稱為 credentials.json

Node.js

  1. 在專案的目錄中,建立名為 chat_app_auth.js 的檔案。
  2. chat_app_auth.js 中加入下列程式碼:

    const chat = require('@googleapis/chat');
    
    async function createMessage() {
      const auth = new chat.auth.GoogleAuth({
    
        // Specify service account details.
        keyFilename: 'credentials.json',
    
        // Specify required scopes.
        scopes: ['https://www.googleapis.com/auth/chat.bot']
    
      });
      const authClient = await auth.getClient();
    
      // Create the Chat API client and authenticate with the service account.
      const chatClient = await chat.chat({
        version: 'v1',
        auth: authClient
      });
    
      // Create a Chat message.
      const result = await chatClient.spaces.messages.create({
    
        // The space to create the message in.
        //
        // Replace SPACE_NAME with a space name.
        // Obtain the space name from the spaces resource of Chat API,
        // or from a space's URL.
        parent: 'spaces/SPACE_NAME',
    
        // The message to create.
        requestBody: { 'text': 'Hello, world!' }
    
      });
      return result;
    }
    
    // Execute function then print details about the created message.
    createMessage().then(console.log);
    
  3. 將程式碼中的 SPACE_NAME 替換為聊天室名稱,這個名稱可從 Chat API 的 spaces.list 方法或聊天室網址取得。請確認服務帳戶的私密金鑰檔案名稱為 credentials.json

Apps Script

  1. 在 Apps Script 編輯器中,編輯 appsscript.json 檔案並新增呼叫 API 所需的 OAuth 範圍:

      "oauthScopes": [
        "https://www.googleapis.com/auth/chat.messages.create",
        "https://www.googleapis.com/auth/script.external_request"
      ]
    
  2. 請將下列程式碼儲存在 Apps Script 專案中,命名為 ChatAppAuth.gs 的檔案:

    const CREDENTIALS = CREDENTIALS;
    
    const SCOPE = 'https://www.googleapis.com/auth/chat.bot';
    
    /**
     * Authenticates with Chat API via app credentials, then posts a message.
     */
    function createMessage() {
      const service = getService_();
      if (!service.hasAccess()) {
        console.error(service.getLastError());
        return;
      }
    
      // The space to create the message in.
      //
      // Replace SPACE_NAME with a space name.
      // Obtain the space name from the spaces resource of Chat API,
      // or from a space's URL.
      const parent = 'spaces/SPACE_NAME';
    
      // Call the Chat API to create a message.
      const result = UrlFetchApp.fetch(`https://chat.googleapis.com/v1/${parent}/messages`,
        {
          method: 'post',
          contentType: 'application/json',
          // Authenticate with the service account token.
          headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
          // The message to create.
          payload: JSON.stringify({ 'text': 'Hello, world!' })
        });
    
      // Log details about the created message.
      console.log(result.getContentText());
    }
    
    /**
     * Configures the OAuth library to authenticate with the service account.
     */
    function getService_() {
      return OAuth2.createService(CREDENTIALS.client_email)
          .setTokenUrl('https://oauth2.googleapis.com/token')
          .setPrivateKey(CREDENTIALS.private_key)
          .setIssuer(CREDENTIALS.client_email)
          .setSubject(CREDENTIALS.client_email)
          .setScope(SCOPE)
          .setPropertyStore(PropertiesService.getScriptProperties());
    }
    
  3. 將程式碼中的 CREDENTIALS 替換為 credentials.json 檔案的內容。

  4. 將程式碼中的 SPACE_NAME 替換為聊天室名稱,這個名稱可從 Chat API 的 spaces.list 方法或聊天室網址取得。

步驟 4:執行完整範例

在工作目錄中建構並執行範例:

Java

mvn compile assembly:single
java -jar target/auth-sample-app-1.0-SNAPSHOT-jar-with-dependencies.jar

Python

python3 chat_app_auth.py

Node.js

node chat_app_auth.js

Apps Script

在 Apps Script 編輯器中開啟 ChatAppAuth.gs 檔案,然後按一下「Run」

指令碼會向 Chat API 發出已驗證的要求,然後以 Chat 應用程式的形式在 Chat 聊天室中發布訊息來回應。

排解範例問題

本節說明您在嘗試執行這個範例時可能會遇到的常見問題。

你無法使用這個應用程式

執行指令碼時,您可能會收到錯誤訊息:

<HttpError 403 when requesting https://chat.googleapis.com/v1/spaces/{space}/messages?alt=json returned "You are not permitted to use this app". Details: "You are not permitted to use this app">

此錯誤訊息表示 Chat 應用程式的權限不足,無法在指定 Chat 聊天室中建立 Chat 訊息。

如要解決這項錯誤,請將 Chat 應用程式新增至指令碼中指定的 Chat 聊天室

參閱 Chat API 參考說明文件,瞭解 Chat API 的其他功能。