以 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 的服務帳戶。

建立服務帳戶

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

Google Cloud 控制台

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

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

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

gcloud CLI

  1. 建立服務帳戶:
    gcloud iam service-accounts create SERVICE_ACCOUNT_NAME \
      --display-name="SERVICE_ACCOUNT_NAME"
  2. 選用:將角色指派給服務帳戶,即可授予 Google Cloud 專案資源的存取權。詳情請參閱「授予、變更及撤銷資源的存取權」。

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

建立私密金鑰

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

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

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

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

    系統就會為您產生一組新的公開/私密金鑰,並以新檔案的形式下載至您的機器。將下載的 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

Node.js

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

npm install "@googleapis/chat"

Apps Script

這個範例使用 OAuth2 for Apps Script 程式庫,產生服務帳戶驗證所需的 JWT 憑證。如何將程式庫新增至 Apps Script 專案:

  1. 按一下左側的「編輯器」圖示
  2. 在左側的「程式庫」旁邊,按一下「新增程式庫」
  3. 輸入指令碼 ID 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
  4. 按一下「查詢」,然後點選「新增」

此範例使用進階 Chat 服務呼叫 Google Chat API。如要為 Apps Script 專案開啟服務:

  1. 按一下左側的「編輯器」圖示
  2. 在左側的「Service」旁邊,按一下「Add a service」圖示
  3. 選取「Google Chat API」
  4. 在「版本」中選取「v1」
  5. 按一下 [新增]。

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

步驟 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 apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # 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 檔案,並加入必要的 OAuth 範圍,要求外部要求取得服務帳戶 OAuth 權杖:

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

    // Specify the contents of the file credentials.json.
    const CREDENTIALS = CREDENTIALS;
    
    const SCOPE = 'https://www.googleapis.com/auth/chat.bot';
    
    // 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'
    
    /**
     * Authenticates with Chat API via app credentials, then posts a message.
     */
    function createMessageWithAppCredentials() {
      try {
        const service = getService_();
        if (!service.hasAccess()) {
          console.error(service.getLastError());
          return;
        }
    
        // Specify the message to create.
        const message = {'text': 'Hello world!'};
    
        // Call Chat API with a service account to create a message.
        const result = Chat.Spaces.Messages.create(
            message,
            PARENT,
            {},
            // Authenticate with the service account token.
            {'Authorization': 'Bearer ' + service.getAccessToken()});
    
        // Log details about the created message.
        console.log(result);
    
      } catch (err) {
        // TODO (developer) - Handle exception.
        console.log('Failed to create message with error %s', err.message);
      }
    }
    
    /**
     * 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 發出已驗證要求,而該 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 的其他功能。