OAuth を使用すると、エージェントはユーザー ID を確認し、会話内の安全な方法でパーソナライズされた情報を提供できます。信頼できる OAuth プロバイダにユーザーがログインするようにすることで、エージェントはユーザーデータにアクセスでき、自動化によって素早く回答できるようになり、人間のエージェントにとって時間を節約できます。
ビジネス メッセージは、OAuth 2.0 をサポートし、認証リクエストの提案によって、ユーザーがエージェント用に構成した OAuth プロバイダにログインするように求めます。ユーザーがログインに成功すると、メッセージとして認証コードがエージェントに返されます。
OAuth プロバイダから認証コードを取得したら、それらの API と統合して、ユーザー ID 情報を必要とする会話フローをサポートできます。操作するサービスごとに利用規約が異なることにご注意ください。
エージェントの OAuth を構成する
エージェントの認証リクエストの提案を有効にするには、まず OAuth を構成する必要があります。
OAuth 構成を指定するには、Business Communications API を使用して PATCH リクエストを送信し、エージェントの endpointUrl
フィールドを更新します。
エンドポイント URL を指定したら、エージェントのリダイレクト URI を保存し、OAuth プロバイダの情報でリダイレクト URI を更新する必要があります。
Prerequisites
次のものが必要です。
- OAuth 2.0 仕様に準拠する OAuth プロバイダ
- 開発マシン上の GCP プロジェクトのサービス アカウント キーのパス
エージェント
name
(例: 「ブランド/12345/エージェント/67890」)エージェントの
name
がわからない場合は、ブランドのすべてのエージェントを一覧表示するをご覧ください。ユーザーが OAuth プロバイダにログインするためのエンドポイント URL
更新リクエストを送信する
エージェントを更新するには、次のコマンドを実行します。変数は、前提条件で特定した値に置き換えます。
curl -X PATCH \ "https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=businessMessagesAgent.authorizationConfig" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \ -d "{ 'businessMessagesAgent': { 'authorizationConfig': { 'endpointUrl': 'ENDPOINT_URL', }, }, }"
リダイレクト URI を更新する
エージェント用に OAuth を構成したので、OAuth プロバイダに 4 つのリダイレクト URI を追加する必要があります。
https://business.google.com/callback
https://business.google.com/callback?
https://business.google.com/message?az-intent-type=1
https://business.google.com/message?az-intent-type=1&
OAuth プロバイダ情報にはすべてのリダイレクト URL を含める必要があります。
リダイレクト URI を更新するプロセスは、OAuth プロバイダによって異なります。手順については、OAuth プロバイダにお問い合わせください。
エージェントで OAuth を構成したので、認証リクエストの提案を使用してユーザーの認証を行うことができます。
ユーザーを認証する
エージェントの OAuth を構成すると、認証リクエストの提案を使用してユーザーにログインを促すことができます。
Prerequisites
次のものが必要です。
- 開発マシン上の GCP プロジェクトのサービス アカウント キーのパス
エージェント
name
(例: 「ブランド/12345/エージェント/67890」)エージェントの
name
がわからない場合は、ブランドのすべてのエージェントを一覧表示するをご覧ください。OAuth プロバイダのクライアント ID
OAuth プロバイダによるコード チャレンジの要件
OAuth プロバイダのスコープ
認証リクエストの提案を送信する
ユーザーを認証するには、
- OAuth リクエストのコード検証ツールとコード チャレンジ文字列を生成します。 要件とオプションについては、OAuth プロバイダにお問い合わせください。
- 認証リクエストの提案を含むメッセージを送信します。
cURL
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This code sends a text message to the user with an authentication request suggestion # that allows the user to authenticate with OAuth. It also has a fallback text. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#authentication-request-suggestion # Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to # Make sure a service account key file exists at ./service_account_key.json # Replace the __CLIENT_ID__ # Replace the __CODE_CHALLENGE__ # Replace the __SCOPE__ curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-messages" \ -H "$(oauth2l header --json ./service_account_key.json businessmessages)" \ -d "{ 'messageId': '$(uuidgen)', 'text': 'Sign in to continue the conversation.', 'fallback': 'Visit support.growingtreebank.com to continue.', 'suggestions': [ { 'authenticationRequest': { 'oauth': { 'clientId': '__CLIENT_ID__', 'codeChallenge': '__CODE_CHALLENGE__', 'scopes': [ '__SCOPE__', ], }, }, }, ], 'representative': { 'avatarImage': 'https://developers.google.com/identity/images/g-logo.png', 'displayName': 'Chatbot', 'representativeType': 'BOT' } }"
Node.js
/** * This code sends a text message to the user with an authentication request suggestion * that allows the user to authenticate with OAuth. It also has a fallback text. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#authentication-request-suggestion * * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js * Business Messages client library. */ /** * Before continuing, learn more about the prerequisites for authenticating * with OAuth at: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/oauth?hl=en * * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const CONVERSATION_ID = 'EDIT_HERE'; const OAUTH_CLIENT_ID = 'EDIT_HERE'; const OAUTH_CODE_CHALLENGE = 'EDIT_HERE'; const OAUTH_SCOPE = 'EDIT_HERE'; const businessmessages = require('businessmessages'); const uuidv4 = require('uuid').v4; const {google} = require('googleapis'); // Initialize the Business Messages API const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); // Set the scope that we need for the Business Messages API const scopes = [ 'https://www.googleapis.com/auth/businessmessages', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); /** * Posts a message to the Business Messages API along with an authentication request. * * @param {string} conversationId The unique id for this user and agent. * @param {string} representativeType A value of BOT or HUMAN. */ async function sendMessage(conversationId, representativeType) { const authClient = await initCredentials(); if (authClient) { // Create the payload for sending a message along with an authentication request const apiParams = { auth: authClient, parent: 'conversations/' + conversationId, resource: { messageId: uuidv4(), representative: { representativeType: representativeType, }, fallback: 'Visit support.growingtreebank.com to continue.', text: 'Sign in to continue the conversation.', suggestions: [ { authenticationRequest: { oauth: { clientId: OAUTH_CLIENT_ID, codeChallenge: OAUTH_CODE_CHALLENGE, scopes: [OAUTH_SCOPE] } } }, ], }, }; // Call the message create function using the // Business Messages client library bmApi.conversations.messages.create(apiParams, {auth: authClient}, (err, response) => { console.log(err); console.log(response); }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } sendMessage(CONVERSATION_ID, 'BOT');
Python
"""Sends a text message to the user with an authentication request suggestion. It allows the user to authenticate with OAuth and has a fallback text. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#authentication-request-suggestion This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ import uuid from businessmessages import businessmessages_v1_client as bm_client from businessmessages.businessmessages_v1_messages import BusinessMessagesAuthenticationRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesAuthenticationRequestOauth from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion from oauth2client.service_account import ServiceAccountCredentials # Before continuing, learn more about the prerequisites for authenticating # with OAuth at: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/oauth?hl=en # Edit the values below: path_to_service_account_key = './service_account_key.json' conversation_id = 'EDIT_HERE' oauth_client_id = 'EDIT_HERE' oauth_code_challenge = 'EDIT_HERE' oauth_scope = 'EDIT_HERE' credentials = ServiceAccountCredentials.from_json_keyfile_name( path_to_service_account_key, scopes=['https://www.googleapis.com/auth/businessmessages']) client = bm_client.BusinessmessagesV1(credentials=credentials) representative_type_as_string = 'BOT' if representative_type_as_string == 'BOT': representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT else: representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN # Create a text message with an authentication request message = BusinessMessagesMessage( messageId=str(uuid.uuid4().int), representative=BusinessMessagesRepresentative( representativeType=representative_type ), text='Sign in to continue the conversation.', fallback='Visit support.growingtreebank.com to continue.', suggestions=[ BusinessMessagesSuggestion( authenticationRequest=BusinessMessagesAuthenticationRequest( oauth=BusinessMessagesAuthenticationRequestOauth( clientId=oauth_client_id, codeChallenge=oauth_code_challenge, scopes=[oauth_scope]) ) ), ] ) # Create the message request create_request = BusinessmessagesConversationsMessagesCreateRequest( businessMessagesMessage=message, parent='conversations/' + conversation_id) # Send the message bm_client.BusinessmessagesV1.ConversationsMessagesService( client=client).Create(request=create_request)
- ユーザーが候補をタップして正常にログインすると、エージェントの Webhook にメッセージが受信されます。
authenticationResponse.code
フィールドから認証コードを取得します。
メッセージを受信したら、認証プロバイダと認証ベンダーを OAuth プロバイダからのアクセス トークンと交換できます。アクセストークンを使用してユーザーデータにアクセスできます。
コードサンプルを含む認証の会話例については、ユーザーを認証するをご覧ください。