使用 OAuth 進行驗證

OAuth 可讓代理程式驗證使用者並提供身分識別資訊 以安全的方式討論對話中的資訊藉由鼓勵使用者登入 可信任的 OAuth 供應商可存取使用者資料, 自動回答問題,為真人服務專員節省時間。

Business Messages 支援 OAuth 2.0 使用 驗證要求 建議, 會提示使用者登入您為代理程式設定的 OAuth 供應商。 使用者成功登入後,Business Messages 就會獲得授權 將程式碼以訊息的形式傳回代理程式

取得 OAuth 供應商提供的授權碼後, 與自己的 API 整合,並支援需要使用者的對話流程 身分資訊請注意,您與每項服務互動的方式都有 自己的使用條款

設定代理程式的 OAuth

如要啟用代理程式的驗證要求建議功能,您必須 請先設定 OAuth

如要指定 OAuth 設定,請發出 PATCH 要求 企業通訊部門 API 更新代理程式的「endpointUrl」欄位。

指定端點網址後,您需要儲存應用程式的重新導向 URI 並更新 OAuth 供應商資訊中的重新導向 URI。

必要條件

您需要下列項目:

  • 遵循 OAuth 2.0 規格的 OAuth 供應商
  • 開發機器上 GCP 專案服務帳戶金鑰的路徑
  • 代理程式 name (例如「brands/12345/agents/67890」)

    如果您不知道代理程式的 name,請參閱列出 品牌

  • 使用者登入 OAuth 提供者的端點網址

傳送更新要求

如要更新代理程式,請執行下列指令。將變數替換為值 已確認在必要條件中提供的資訊。

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 之後,您必須新增四個重新導向 URI 傳送至 OAuth 供應商:

  • 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 供應商資訊中納入所有重新導向網址。

更新重新導向 URI 的程序會因 OAuth 供應商而異。請參閱 OAuth 供應商操作說明。

為代理程式設定 OAuth 後,您可以進行驗證 使用者驗證要求 建議

驗證使用者

為代理程式設定 OAuth 後,您可以提示使用者透過 驗證要求 建議

必要條件

您需要下列項目:

  • 開發機器上 GCP 專案服務帳戶金鑰的路徑
  • 代理程式 name (例如「brands/12345/agents/67890」)

    如果您不知道代理程式的 name,請參閱列出 品牌

  • OAuth 供應商提供的用戶端 ID

  • OAuth 供應商提供的程式碼驗證要求

  • OAuth 供應商的範圍

傳送驗證要求建議

驗證要求建議

如要驗證使用者

  1. 為 OAuth 要求產生程式碼驗證器和程式碼驗證字串。 請向 OAuth 供應商洽詢需求條件和選項。
  2. 傳送含有驗證要求建議的訊息。

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)
  1. 當使用者輕觸建議並成功登入時,您 收到 訊息傳送從 「authenticationResponse.code」欄位。

收到訊息後,你可以交換授權碼和代碼 OAuth 供應商提供的存取權杖驗證器。您可以存取使用者資料 取得憑證

如需驗證的範例對話 (包括程式碼範例),請參閱 驗證 使用者