本指南介绍了如何设置和使用服务账号来代表 Chat 应用访问 Google Chat API。首先,本指南将引导您完成创建服务账号的步骤。然后,它演示了如何编写一个脚本,该脚本使用服务账号向 Chat API 进行身份验证,并在 Chat 聊天室中发布消息。
如果 Chat 应用通过服务账号进行身份验证,则必须是 Chat 聊天室的成员,才能获取聊天室中的数据或在聊天室中执行操作。例如,如需列出聊天室的成员或在聊天室中创建消息,Chat 应用本身必须是该聊天室的成员。唯一的例外情况是,当 Chat 应用创建具有应用身份验证的聊天室时,该应用会创建聊天室,然后自动成为成员。
支持应用授权的 Google Chat API 方法(授权范围的名称以 https://www.googleapis.com/auth/chat.app.*
开头)需要管理员一次性批准。支持使用 https://www.googleapis.com/auth/chat.bot
授权范围进行应用授权的 Google Chat API 方法不需要额外审批。https://www.googleapis.com/auth/chat.app.*
授权范围已在开发者预览版中推出。
如果您的 Chat 应用需要访问用户数据或代表用户执行操作,请改为以用户身份进行身份验证。如果您是网域管理员,则可以授予全网域授权,以授权 Chat 应用的服务账号访问您用户的数据,而无需经过每位用户的同意。如需了解详情,请参阅使用全网域授权进行身份验证和授权。
如需详细了解 Chat 应用何时需要身份验证以及应使用哪种身份验证,请参阅 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
- 一种 Google Chat 应用,可接收并响应互动事件。如需使用 HTTP 服务创建交互式 Chat 应用,请完成此快速入门。
- 将 Chat 应用添加到聊天室。如需添加 Chat 应用,请参阅 测试 Google Chat 应用的互动功能。
Python
- Python 3.6 或更高版本
- pip 软件包管理工具
- 一种 Google Chat 应用,可接收并响应互动事件。如需使用 HTTP 服务创建交互式 Chat 应用,请完成此快速入门。
- 将 Chat 应用添加到聊天室。如需添加 Chat 应用,请参阅 测试 Google Chat 应用的互动功能。
Node.js
- Node.js 14 或更高版本
- npm 软件包管理工具
-
已初始化的 Node.js 项目。如需初始化新项目,请创建并切换到新文件夹,然后在命令行界面中运行以下命令:
npm init
- 一种 Google Chat 应用,可接收并响应互动事件。如需使用 HTTP 服务创建交互式 Chat 应用,请完成此快速入门。
- 将 Chat 应用添加到聊天室。如需添加 Chat 应用,请参阅 测试 Google Chat 应用的互动功能。
Apps 脚本
- 一种 Google Chat 应用,可接收并响应互动事件。如需在 Apps 脚本中创建交互式 Chat 应用,请完成此快速入门。
- 将 Chat 应用添加到聊天室。如需添加 Chat 应用,请参阅 测试 Google Chat 应用的互动功能。
第 1 步:在 Google Cloud 控制台中创建服务账号
创建服务账号,供 Chat 应用用来访问 Google API。
创建服务账号
如需创建服务账号,请按照以下步骤操作:
Google Cloud 控制台
- 在 Google Cloud 控制台中,依次前往菜单 > IAM 和管理 > 服务账号。
- 点击创建服务账号。
- 填写服务账号详细信息,然后点击创建并继续。
- 可选:为您的服务账号分配角色,以授予对 Google Cloud 项目资源的访问权限。如需了解详情,请参阅授予、更改和撤消对资源的访问权限。
- 点击继续。
- 可选:输入可管理此服务账号并使用此服务账号执行操作的用户或群组。如需了解详情,请参阅管理服务账号模拟。
- 点击完成。记下服务账号的电子邮件地址。
gcloud CLI
- 创建服务账号:
gcloud iam service-accounts create
SERVICE_ACCOUNT_NAME
\ --display-name="SERVICE_ACCOUNT_NAME
" - 可选:为您的服务账号分配角色,以授予对 Google Cloud 项目资源的访问权限。如需了解详情,请参阅授予、更改和撤消对资源的访问权限。
该服务账号会显示在服务账号页面上。接下来,为服务账号创建私钥。
创建一个私钥
如需为服务账号创建并下载私钥,请按以下步骤操作:
- 在 Google Cloud 控制台中,依次前往菜单 > IAM 和管理 > 服务账号。
- 选择您的服务账号。
- 依次点击密钥 > 添加密钥 > 创建新密钥。
- 选择 JSON,然后点击创建。
系统会生成新的公钥/私钥对,并以新文件的形式下载到您的计算机。将下载的 JSON 文件以
credentials.json
的名称保存到工作目录中。此文件是相应密钥的唯一副本。如需了解如何安全地存储密钥,请参阅管理服务账号密钥。 - 点击关闭。
如需详细了解服务账号,请参阅 Google Cloud IAM 文档中的服务账号。
接下来,为此服务账号创建与 Google Workspace Marketplace 兼容的 OAuth 客户端。
获得管理员批准
如需使用 https://www.googleapis.com/auth/chat.bot
授权范围,无需获得管理员批准。前往第 2 步:安装 Google 客户端库和其他依赖项。
本指南中的示例使用 https://www.googleapis.com/auth/chat.bot
授权范围,因此如果您要按照示例操作,请前往第 2 步。
如需使用以 https://www.googleapis.com/auth/chat.app.*
开头的授权范围(作为开发者预览版的一部分提供),您的 Chat 应用必须获得一次性管理员批准。
如需获得管理员批准,您必须准备好 Chat 应用的服务账号,并提供以下信息:
- 与 Google Workspace Marketplace 兼容的 OAuth 客户端。
- Google Workspace Marketplace SDK 中的应用配置。
创建与 Google Workspace Marketplace 兼容的 OAuth 客户端
如需创建与 Google Workspace Marketplace 兼容的 OAuth 客户端,请按以下步骤操作:
在 Google Cloud 控制台中,依次前往菜单 > IAM 和管理 > 服务账号。
点击您为 Chat 应用创建的服务账号。
点击高级设置。
点击创建与 Google Workspace Marketplace 兼容的 OAuth 客户端。
点击继续。
系统会显示一条确认消息,表明已创建与 Google Workspace Marketplace 兼容的 OAuth 客户端。
在 Google Workspace Marketplace SDK 中配置 Chat 应用
如需在 Google Workspace Marketplace SDK 中配置 Chat 应用,请按以下步骤操作:
在 Google Cloud 控制台中,启用 Google Workspace Marketplace SDK。
在 Google Cloud 控制台中,依次前往菜单 > API 和服务 > 已启用的 API 和服务 > Google Workspace Marketplace SDK > 应用配置。
完成“应用配置”页面。您如何配置 Chat 应用取决于您的目标受众群体和其他因素。如需有关完成应用配置页面的帮助,请参阅在 Google Workspace Marketplace SDK 中配置您的应用。 在本指南中,请输入以下信息:
- 在应用显示设置下,选择不公开。
- 在安装设置下,选择个人安装 + 管理员安装。
- 在应用集成下,选择 Chat 应用。
在 OAuth 范围下,输入您的 Chat 应用使用的所有身份验证范围。
在开发者信息下方,输入您的开发者名称、开发者网站网址和开发者电子邮件地址。
点击 Save draft。
获得管理员批准
现在,您的服务账号已配置为可接收管理员审批,请从 Google Workspace 管理员处获取审批,该管理员可以按照为 Chat 应用设置授权中的步骤授予审批。
第 2 步:安装 Google 客户端库和其他依赖项
安装项目所需的 Google 客户端库和其他依赖项。
Java
如需将 Google 客户端库和其他必需的依赖项添加到 Maven 项目中,请修改项目目录中的 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
如需将 Google 客户端库添加到 Node.js 项目,请切换到项目目录,然后在命令行界面中运行以下命令:
npm install "@googleapis/chat"
Apps 脚本
此示例使用 OAuth2 for Apps 脚本库生成用于服务账号身份验证的 JWT 令牌。如需将库添加到您的 Apps 脚本项目,请执行以下操作:
- 点击左侧的编辑器图标 。
- 在左侧,点击媒体库旁边的添加媒体库图标 。
- 输入脚本 ID
1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
。 - 点击查找,然后点击添加。
此示例使用高级聊天服务来调用 Google Chat API。如需为您的 Apps 脚本项目启用该服务,请执行以下操作:
- 点击左侧的编辑器图标 。
- 在左侧,点击服务旁边的添加服务图标 。
- 选择 Google Chat API。
- 在版本中,选择 v1。
- 点击添加。
您可以使用我们的客户端库支持的任何语言。
第 3 步:编写一个使用服务账号向 Chat API 进行身份验证的脚本
以下代码使用服务账号向 Chat API 进行身份验证,然后向 Chat 聊天室发布消息:
Java
- 在项目目录中,打开
src/main/java/com/google/chat/app/authsample/App.java
文件。 将
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 using 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(); } }
在代码中,将
SPACE_NAME
替换为聊天室名称,您可以通过 Chat API 中的spaces.list
方法或从聊天室的网址获取聊天室名称。在项目目录中创建一个名为
resources
的新子目录。确保服务账号的私钥文件名为
credentials.json
,并将其复制到resources
子目录。如需配置 Maven 以将私钥文件包含在项目软件包中,请修改项目目录中的
pom.xml
文件,并将以下配置添加到<build>
部分:<build> <!-- ... existing configurations ... --> <resources> <resource> <directory>resources</directory> </resource> </resources> </build>
如需配置 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
- 在工作目录中,创建一个名为
chat_app_auth.py
的文件。 在
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. creds = 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=creds) # 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)
在代码中,将
SPACE_NAME
替换为聊天室名称,您可以通过 Chat API 中的spaces.list
方法或从聊天室的网址获取聊天室名称。确保服务账号的私钥文件名为credentials.json
。
Node.js
- 在项目目录中,创建一个名为
chat_app_auth.js
的文件。 在
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);
在代码中,将
SPACE_NAME
替换为聊天室名称,您可以通过 Chat API 中的spaces.list
方法或从聊天室的网址获取聊天室名称。确保服务账号的私钥文件名为credentials.json
。
Apps 脚本
在 Apps 脚本编辑器中,修改文件
appsscript.json
并添加必要的 OAuth 范围,以发出外部请求来获取服务账号 OAuth 令牌:"oauthScopes": [ "https://www.googleapis.com/auth/script.external_request" ]
将以下代码保存在 Apps 脚本项目中的一个名为
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 using 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()); }
在代码中,将
CREDENTIALS
替换为文件credentials.json
的内容。在代码中,将
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 脚本
在 Apps 脚本编辑器中打开文件 ChatAppAuth.gs
,然后点击运行。
您的脚本向 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 聊天室。
管理员必须授予应用执行此操作所需的 OAuth 授权范围
运行脚本时,您可能会收到以下错误消息:
<HttpError 403 when requesting https://chat.googleapis.com/v1/spaces/{space}?alt=json returned "The administrator must grant the app the required OAuth authorization scope for this action.". Details: "The administrator must grant the app the required OAuth authorization scope for this action.">
此错误消息表示 Google Workspace 管理员尚未向 Google Chat 应用授予一次性批准,以使用以名称 https://www.googleapis.com/auth/chat.app.*
开头的授权范围。
如需解决此错误,请执行以下操作:
- 请让 Google Workspace 管理员向您的 Chat 应用授予审批权限。在 Chat 应用逻辑中处理此错误时,请考虑发送一条消息,告知用户 Chat 应用需要管理员审批才能执行所请求的操作,例如:
To perform this action, I need approval. <https://support.google.com/a?p=chat-app-auth|Learn more>.
- 如果 Google Chat API 方法支持
https://www.googleapis.com/auth/chat.bot
授权范围(不需要管理员批准),请考虑改用该范围。如需查看方法支持哪些授权范围,请参阅 Google Chat API 参考文档。
相关主题
- 如需了解 Chat API 的其他功能,请查看 Chat API 参考文档。
- 如果使用以
https://www.googleapis.com/auth/chat.app.*
开头的 OAuth 授权范围,请了解管理员如何授予一次性批准。