1. 簡介

上次更新時間:2020 年 10 月 30 日
在 Business Messages 中建立購物車!
這是系列程式碼研究室的第二個單元,旨在建構「線上購買店內取貨」使用者歷程。在許多電子商務歷程中,購物車是將使用者轉換為付費顧客的關鍵。購物車也是進一步瞭解顧客的方式,並可根據顧客的興趣提供其他商品建議。在本程式碼研究室中,我們將著重於建構購物車體驗,並將應用程式部署至 Google App Engine。
什麼是好的購物車?
購物車是成功線上購物體驗的關鍵。結果顯示,商家訊息不僅能協助潛在顧客詢問產品問題,還能促進整個購物體驗,讓顧客在對話中完成付款。

除了購物車,良好的購物體驗還包括讓使用者依類別瀏覽商品,以及讓商家推薦買家可能感興趣的其他產品。將更多商品加入購物車後,使用者可以查看整個購物車,並在結帳前移除或新增商品。
建構項目
在本程式碼研究室系列的這一節中,您將擴充在第 1 部分中為虛構公司 Bonjour Meal 建構的數位代理程式,讓使用者可以瀏覽商品目錄並將商品加入購物車。
在本程式碼研究室中,您的應用程式將
- 在 Business Messages 中顯示問題目錄
- 建議使用者可能感興趣的項目
- 查看購物車內容,並建立總價摘要

課程內容
- 如何在 Google Cloud Platform 的 App Engine 上部署網頁應用程式
- 如何使用永久儲存機制儲存購物車狀態
本程式碼研究室著重於擴充本程式碼研究室系列第 1 部分的數位代理程式。
軟硬體需求
- 已註冊並獲准用於 Business Messages 的 GCP 專案
- 如需瞭解如何
- 為 GCP 專案產生的服務帳戶 JSON 憑證檔案
- 搭載 Android 5 以上版本的裝置,或安裝 Google 地圖應用程式的 iOS 裝置
- 網頁應用程式程式設計經驗
- 網際網路連線!
2. 開始設定
本程式碼研究室假設您已建立第一個代理程式,並完成第 1 部分的程式碼研究室。因此,我們不會說明如何啟用 Business Messages 和 Business Communications API、建立服務帳戶金鑰、部署應用程式,或在 Business Communications 控制台上設定 Webhook。話雖如此,我們還是會複製範例應用程式,確保您的應用程式與我們建構的內容一致,並在 Google Cloud Platform 上啟用 Datastore 的 API,以便保存購物車相關資料。
從 GitHub 複製應用程式
在終端機中,使用下列指令將 Django Echo Bot 範例複製到專案的工作目錄:
$ git clone https://github.com/google-business-communications/bm-bonjour-meal-django-starter-code
將為服務帳戶建立的 JSON 憑證檔案複製到範例的資源資料夾,然後將憑證重新命名為「bm-agent-service-account-credentials.json」。
bm-bonjour-meal-django-starter-code/bonjourmeal-codelab/step-2/resources/bm-agent-service-account-credentials.json
啟用 Google Datastore API
在本程式碼研究室的第 1 部分,您已啟用 Business Messages API、Business Communications API 和 Cloud Build API。
在本程式碼研究室中,我們將使用 Google Datastore,因此也需要啟用這個 API:
- 在 Google Cloud 控制台中開啟 Google Datastore API。
- 確認您使用的是正確的 GCP 專案。
- 按一下「啟用」。
部署範例應用程式
在終端機中,前往範例的 step-2 目錄。
在終端機中執行下列指令,部署範例:
$ gcloud config set project PROJECT_ID*
$ gcloud app deploy
- PROJECT_ID 是您用來向 API 註冊的專案 ID。
請注意上一個指令輸出內容中已部署應用程式的網址:
Deployed service [default] to [https://PROJECT_ID.appspot.com]
您剛部署的程式碼包含一個 Web 應用程式,其中含有用來接收 Business Messages 訊息的 Webhook。其中包含我們在程式碼研究室第 1 部分中完成的所有作業。如果尚未設定,請設定 Webhook。
應用程式會回覆一些簡單的查詢,例如使用者詢問 Bonjour Meal 的營業時間。您應透過 Business Communications 控制台的「服務專員資訊」中擷取的測試網址,在行動裝置上測試這項功能。測試網址會在行動裝置上啟動 Business Messages 體驗,您可以在這裡與服務專員互動。
3. 產品目錄
商品目錄系統
在大多數情況下,您可以透過內部 API 直接整合品牌商品目錄。在其他情況下,您可能會擷取網頁內容,或建構自己的庫存追蹤系統。我們的重點不是建立商品目錄系統,而是使用簡單的靜態檔案,其中包含代理程式的圖片和產品資訊。在本節中,我們會從這個靜態檔案擷取資訊,將該資訊顯示在對話中,並允許使用者瀏覽可加入購物車的項目。
靜態目錄檔案如下所示:
bonjourmeal-codelab/step-2/resources/inventory.json
{
"food": [
{
"id":0,
"name": "Ham and cheese sandwich",
"price": "6.99",
"image_url": "https://storage.googleapis.com/bonjour-rail.appspot.com/ham-and-cheese.png",
"remaining": 8
},
{
"id":1,
"name": "Chicken veggie wrap",
"price": "9.99",
"image_url": "https://storage.googleapis.com/bonjour-rail.appspot.com/chicken-veggie-wrap.png",
"remaining": 2
},
{
"id":2,
"name": "Assorted cheese plate",
"price": "7.99",
"image_url": "https://storage.googleapis.com/bonjour-rail.appspot.com/assorted-cheese-plate.png",
"remaining": 6
},
{
"id":3,
"name": "Apple walnut salad",
"price": "12.99",
"image_url": "https://storage.googleapis.com/bonjour-rail.appspot.com/apple-walnut-salad.png",
"remaining": 1
}
]
}
現在讓 Python 應用程式讀取這個檔案!
從商品目錄讀取
這個目錄中的「inventory.json」是靜態檔案,我們需要在 views.py 中新增一些 Python 邏輯,讀取 JSON 檔案的內容,然後顯示在對話中。讓我們建立一個函式,從 JSON 檔案讀取資料,並傳回可用的產品清單。
這個函式定義可以放在 views.py 中的任何位置。
bonjourmeal-codelab/step-2/bopis/views.py
...
def get_inventory_data():
f = open(INVENTORY_FILE)
inventory = json.load(f)
return inventory
...
這應該會提供我們從商品目錄讀取資料所需的資訊。現在我們需要將這項產品資訊顯示在對話中。
顯示產品目錄
為簡化本程式碼研究室,我們提供一般產品目錄,透過單一豐富資訊卡輪播,向 Business Messages 對話顯示所有庫存項目。
如要查看產品目錄,我們將建立建議回覆,其中包含「顯示菜單」文字和 postbackData「show-product-catalog」。當使用者輕觸建議回覆,且您的網路應用程式收到 postback 資料時,我們會傳送豐富的資訊卡輪播。請在 views.py 頂端新增這個建議回覆的常數。
bonjourmeal-codelab/step-2/bopis/views.py
...
CMD_SHOW_PRODUCT_CATALOG = 'show-product-catalog'
...
接著,我們會剖析訊息並將其傳送至新函式,該函式會傳送含有產品目錄的複合式資訊卡輪轉介面。首先,請擴充 route_message 函式,在輕觸建議回覆時呼叫「send_product_catalog」函式,然後定義該函式。
在下列程式碼片段中,於 route_message 函式的 if 陳述式中新增條件,檢查 normalized_message 是否等於我們先前定義的常數 CMD_SHOW_PRODUCT_CATALOG。
bonjourmeal-codelab/step-2/bopis/views.py
...
def route_message(message, conversation_id):
'''
Routes the message received from the user to create a response.
Args:
message (str): The message text received from the user.
conversation_id (str): The unique id for this user and agent.
'''
normalized_message = message.lower()
if normalized_message == CMD_RICH_CARD:
send_rich_card(conversation_id)
elif normalized_message == CMD_CAROUSEL_CARD:
send_carousel(conversation_id)
elif normalized_message == CMD_SUGGESTIONS:
send_message_with_suggestions(conversation_id)
elif normalized_message == CMD_BUSINESS_HOURS_INQUIRY:
send_message_with_business_hours(conversation_id)
elif normalized_message == CMD_ONLINE_SHOPPING_INQUIRY:
send_online_shopping_info_message(conversation_id)
elif normalized_message == CMD_SHOW_PRODUCT_CATALOG:
send_product_catalog(conversation_id)
else:
echo_message(message, conversation_id)
...
請務必完成流程並定義 send_product_catalog。send_product_catalog 會呼叫 get_menu_carousel,,從稍早讀取的目錄檔案產生複合式資訊卡輪轉介面。
函式定義可放在 views.py 的任何位置。請注意,下列程式碼片段會使用兩個新常數,應加到檔案頂端。
bonjourmeal-codelab/step-2/bopis/views.py
...
CMD_ADD_ITEM = 'add-item'
CMD_SHOW_CART = 'show-cart'
...
def get_menu_carousel():
"""Creates a sample carousel rich card.
Returns:
A :obj: A BusinessMessagesCarouselCard object with three cards.
"""
inventory = get_inventory_data()
card_content = []
for item in inventory['food']:
card_content.append(BusinessMessagesCardContent(
title=item['name'],
description=item['price'],
suggestions=[
BusinessMessagesSuggestion(
reply=BusinessMessagesSuggestedReply(
text='Add item',
postbackData='{'+f'"action":"{CMD_ADD_ITEM}","item_name":"{item["id"]}"'+'}'))
],
media=BusinessMessagesMedia(
height=BusinessMessagesMedia.HeightValueValuesEnum.MEDIUM,
contentInfo=BusinessMessagesContentInfo(
fileUrl=item['image_url'],
forceRefresh=False))))
return BusinessMessagesCarouselCard(
cardContents=card_content,
cardWidth=BusinessMessagesCarouselCard.CardWidthValueValuesEnum.MEDIUM)
def send_product_catalog(conversation_id):
"""Sends the product catalog to the conversation_id.
Args:
conversation_id (str): The unique id for this user and agent.
"""
rich_card = BusinessMessagesRichCard(carouselCard=get_menu_carousel())
fallback_text = ''
# Construct a fallback text for devices that do not support carousels
for card_content in rich_card.carouselCard.cardContents:
fallback_text += (card_content.title + '\n\n' + card_content.description
+ '\n\n' + card_content.media.contentInfo.fileUrl
+ '\n---------------------------------------------\n\n')
message_obj = BusinessMessagesMessage(
messageId=str(uuid.uuid4().int),
representative=BOT_REPRESENTATIVE,
richCard=rich_card,
fallback=fallback_text,
suggestions=[
BusinessMessagesSuggestion(
reply=BusinessMessagesSuggestedReply(
text='See my cart',
postbackData=CMD_SHOW_CART)
),
BusinessMessagesSuggestion(
reply=BusinessMessagesSuggestedReply(
text='See the menu',
postbackData=CMD_SHOW_PRODUCT_CATALOG)
),
]
)
send_message(message_obj, conversation_id)
...
如果您檢查輪播項目建立作業,也會發現我們建立了 BusinessMessagesSuggestion 類別的執行個體。每項建議都代表使用者在輪轉介面中選取的產品。使用者輕觸建議回覆時,Business Messages 會將包含 JSON 的 postbackData 傳送至你的 Webhook,說明項目和使用者想執行的動作 (加入或從購物車移除)。在下一節中,我們會剖析類似這樣的訊息,以便實際將商品加入購物車。
完成這些變更後,請將網路應用程式部署至 Google App Engine,並試用相關功能!
$ gcloud app deploy
在行動裝置上載入對話介面後,傳送「show-product-catalog」訊息,你應該會看到產品輪轉介面,如下所示。

如果輕觸「新增項目」,除了代理會回應建議回覆中的回傳資料,實際上不會發生任何事。在下一節中,我們會使用產品目錄,並用來建構要加入項目的購物車。
您可以使用各種方式擴充剛建立的產品目錄。你可能會看到不同的飲品菜單選項或素食選項。使用輪轉介面或建議晶片,可讓使用者深入瀏覽選單選項,找到他們想要的產品組合。您可以將本程式碼研究室視為延伸練習,嘗試擴充產品目錄系統,讓使用者在菜單中分別查看飲料和食物,甚至指定素食選項。
4. 購物車
在本程式碼研究室的這一節中,我們將以先前可瀏覽產品的章節為基礎,建構購物車功能。
購物車的主要功能包括讓使用者將商品加入購物車、從購物車中移除商品、追蹤購物車中各商品的數量,以及查看購物車中的商品。
追蹤購物車狀態表示我們需要在網路應用程式中保存資料。為簡化實驗和部署作業,我們將使用 Google Cloud Platform 中的 Google Datastore 持久儲存資料。使用者與商家之間的對話 ID 不會變動,因此我們可以藉此將使用者與購物車商品建立關聯。
首先,請連線至 Google Datastore,並在看到對話 ID 時保留該 ID。
連結至 Datastore
每當對購物車執行任何互動時 (例如使用者新增或刪除項目),我們就會連線至 Google Datastore。如要進一步瞭解如何使用這個用戶端程式庫與 Google Datastore 互動,請參閱官方說明文件。
下列程式碼片段定義了更新購物車的函式。這個函式會採用下列輸入內容:conversation_id 和 message。message 包含描述使用者想採取的動作的 JSON,這已內建於顯示產品目錄的輪播介面中。這個函式會建立 Google Datastore 用戶端,並立即擷取 ShoppingCart 實體,其中金鑰為對話 ID。
將下列函式複製到 views.py 檔案。我們會在下一節中繼續擴充這項功能。
bonjourmeal-codelab/step-2/bopis/views.py
from google.oauth2 import service_account
from google.cloud import datastore
def update_shopping_cart(conversation_id, message):
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_LOCATION)
client = datastore.Client(credentials=credentials)
key = client.key('ShoppingCart', conversation_id)
entity = datastore.Entity(key=key)
result = client.get(key)
# TODO: Add logic to add and remove items from cart
entity.update(result)
client.put(entity)
讓我們擴充這項函式,將商品加入購物車。
將商品加入購物車
當使用者輕觸產品輪播介面中的「新增項目」建議動作時,postbackData 會包含 JSON,說明使用者想採取的動作。JSON 字典有兩個鍵:「action」和「item_name」,這個 JSON 字典會傳送至你的 Webhook。「item_name」欄位是與 inventory.json 中項目相關聯的專屬 ID。
從訊息剖析購物車指令和購物車項目後,我們就可以編寫條件陳述式來新增項目。這裡需要考慮的特殊情況包括:Datastore 從未見過對話 ID,或是購物車首次收到這項商品。以下是上述定義的 update_shopping_cart 功能擴充項目。這項變更會將商品新增至購物車,並由 Google Datastore 持續保存。
下列程式碼片段是新增至 views.py 的前一個函式擴充功能。您可以新增差異,或是複製程式碼片段並取代現有的 update_shopping_cart 函式版本。
bonjourmeal-codelab/step-2bopis/views.py
def update_shopping_cart(conversation_id, message):
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_LOCATION)
inventory = get_inventory_data()
cart_request = json.loads(message)
cart_cmd = cart_request["action"]
cart_item = cart_request["item_name"]
item_name = inventory['food'][int(cart_item)]['name']
client = datastore.Client(credentials=credentials)
key = client.key('ShoppingCart', conversation_id)
entity = datastore.Entity(key=key)
result = client.get(key)
if result is None:
if cart_cmd == CMD_ADD_ITEM:
entity.update({
item_name: 1
})
else:
if cart_cmd == CMD_ADD_ITEM:
if result.get(item_name) is None:
result[item_name] = 1
else:
result[item_name] = result[item_name] + 1
entity.update(result)
client.put(entity)
這個函式稍後會擴充,以支援 cart_cmd 包含 CMD_DEL_ITEM 中定義的「del-item」字串的情境。
融會貫通
請務必在 route_message 函式中新增管道,以便在收到將項目新增至購物車的訊息時呼叫 update_shopping_cart 函式。您也需要定義常數,以便使用本程式碼研究室中使用的慣例新增項目。
bonjourmeal-codelab/step-2bopis/views.py
...
CMD_DEL_ITEM = 'del-item'
...
def route_message(message, conversation_id):
'''
Routes the message received from the user to create a response.
Args:
message (str): The message text received from the user.
conversation_id (str): The unique id for this user and agent.
'''
normalized_message = message.lower()
if normalized_message == CMD_RICH_CARD:
send_rich_card(conversation_id)
elif normalized_message == CMD_CAROUSEL_CARD:
send_carousel(conversation_id)
elif normalized_message == CMD_SUGGESTIONS:
send_message_with_suggestions(conversation_id)
elif normalized_message == CMD_BUSINESS_HOURS_INQUIRY:
send_message_with_business_hours(conversation_id)
elif normalized_message == CMD_ONLINE_SHOPPING_INQUIRY:
send_online_shopping_info_message(conversation_id)
elif normalized_message == CMD_SHOW_PRODUCT_CATEGORY:
send_product_catalog(conversation_id)
elif CMD_ADD_ITEM in normalized_message or CMD_DEL_ITEM in normalized_message:
update_shopping_cart(conversation_id, message)
else:
echo_message(message, conversation_id)
...
目前我們已可將商品加入購物車。將變更部署至 Google App Engine 後,您應該就能在 GCP 控制台的 Google Datastore 資訊主頁中,看到購物車變更。請參閱下方的 Google Datastore 控制台螢幕截圖,其中有一個實體是以對話 ID 命名,後面接著與購物車中商品和商品數量的關係。

在下一節中,我們將建立列出購物車中商品的方法。購物車檢視機制應顯示購物車中的所有商品、商品數量,以及從購物車中移除商品的選項。
查看購物車中的商品
我們只能透過列出購物車中的商品,瞭解購物車的狀態,並知道可以移除哪些商品。
首先,請傳送友善訊息,例如「這是你的購物車:」,然後再傳送一則訊息,內含複合式資訊卡輪播介面,以及「移除一項」或「新增一項」的相關建議回覆。此外,豐富資訊卡輪播介面應列出購物車中儲存的商品數量。
實際進入並編寫函式之前,請注意一件事:如果購物車中只有一種商品,我們就無法將其顯示為輪播。輪播式豐富資訊卡必須包含至少兩張資訊卡。反之,如果購物車中沒有任何商品,我們希望顯示購物車為空的簡單訊息。
瞭解這點後,我們來定義名為 send_shopping_cart 的函式。這項函式會連線至 Google Datastore,並根據對話 ID 要求 ShoppingCart 實體。取得該資料後,我們會呼叫 get_inventory_data 函式,並使用複合式資訊卡輪播來回報購物車的狀態。我們也需要依名稱取得產品 ID,因此可以宣告函式來查看 Google Datastore,以判斷該值。製作輪播內容時,我們可以將建議回覆與要刪除或新增的項目 (依產品 ID) 建立關聯。下列程式碼片段會執行所有這些作業。將程式碼複製到 views.py 中的任何位置。
bonjourmeal-codelab/step-2/bopis/views.py
...
def get_id_by_product_name(product_name):
inventory = get_inventory_data()
for item in inventory['food']:
if item['name'] == product_name:
return int(item['id'])
return False
def send_shopping_cart(conversation_id):
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_LOCATION)
# Retrieve the inventory data
inventory = get_inventory_data()
# Pull the data from Google Datastore
client = datastore.Client(credentials=credentials)
key = client.key('ShoppingCart', conversation_id)
result = client.get(key)
shopping_cart_suggestions = [
BusinessMessagesSuggestion(
reply=BusinessMessagesSuggestedReply(
text='See total price', postbackData='show-cart-price')),
BusinessMessagesSuggestion(
reply=BusinessMessagesSuggestedReply(
text='Empty the cart', postbackData='empty-cart')),
BusinessMessagesSuggestion(
reply=BusinessMessagesSuggestedReply(
text='See the menu', postbackData=CMD_SHOW_PRODUCT_CATALOG)),
]
if result is None or len(result.items()) == 0:
message_obj = BusinessMessagesMessage(
messageId=str(uuid.uuid4().int),
representative=BOT_REPRESENTATIVE,
text='There are no items in your shopping cart.',
suggestions=shopping_cart_suggestions)
send_message(message_obj, conversation_id)
elif len(result.items()) == 1:
for product_name, quantity in result.items():
product_id = get_id_by_product_name(product_name)
fallback_text = ('You have one type of item in the shopping cart')
rich_card = BusinessMessagesRichCard(
standaloneCard=BusinessMessagesStandaloneCard(
cardContent=BusinessMessagesCardContent(
title=product_name,
description=f'{quantity} in cart.',
suggestions=[
BusinessMessagesSuggestion(
reply=BusinessMessagesSuggestedReply(
text='Remove one',
postbackData='{'+f'"action":"{CMD_DEL_ITEM}","item_name":"{product_id}"'+'}'))
],
media=BusinessMessagesMedia(
height=BusinessMessagesMedia.HeightValueValuesEnum.MEDIUM,
contentInfo=BusinessMessagesContentInfo(
fileUrl=inventory['food'][product_id]
['image_url'],
forceRefresh=False)))))
message_obj = BusinessMessagesMessage(
messageId=str(uuid.uuid4().int),
representative=BOT_REPRESENTATIVE,
richCard=rich_card,
suggestions=shopping_cart_suggestions,
fallback=fallback_text)
send_message(message_obj, conversation_id)
else:
cart_carousel_items = []
# Iterate through the cart and generate a carousel of items
for product_name, quantity in result.items():
product_id = get_id_by_product_name(product_name)
cart_carousel_items.append(
BusinessMessagesCardContent(
title=product_name,
description=f'{quantity} in cart.',
suggestions=[
BusinessMessagesSuggestion(
reply=BusinessMessagesSuggestedReply(
text='Remove one',
postbackData='{'+f'"action":"{CMD_DEL_ITEM}","item_name":"{product_id}"'+'}'))
],
media=BusinessMessagesMedia(
height=BusinessMessagesMedia.HeightValueValuesEnum.MEDIUM,
contentInfo=BusinessMessagesContentInfo(
fileUrl=inventory['food'][product_id]
['image_url'],
forceRefresh=False))))
rich_card = BusinessMessagesRichCard(
carouselCard=BusinessMessagesCarouselCard(
cardContents=cart_carousel_items,
cardWidth=BusinessMessagesCarouselCard.CardWidthValueValuesEnum
.MEDIUM))
fallback_text = ''
# Construct a fallback text for devices that do not support carousels
for card_content in rich_card.carouselCard.cardContents:
fallback_text += (
card_content.title + '\n\n' + card_content.description + '\n\n' +
card_content.media.contentInfo.fileUrl +
'\n---------------------------------------------\n\n')
message_obj = BusinessMessagesMessage(
messageId=str(uuid.uuid4().int),
representative=BOT_REPRESENTATIVE,
richCard=rich_card,
suggestions=shopping_cart_suggestions,
fallback=fallback_text,
)
send_message(message_obj, conversation_id)
...
請務必在 views.py 頂端定義 CMD_SHOW_CART,並在使用者傳送含有「show-cart」的訊息時呼叫 send_shopping_cart。
bonjourmeal-codelab/step-2/bopis/views.py
...
def route_message(message, conversation_id):
'''
Routes the message received from the user to create a response.
Args:
message (str): The message text received from the user.
conversation_id (str): The unique id for this user and agent.
'''
normalized_message = message.lower()
if normalized_message == CMD_RICH_CARD:
send_rich_card(conversation_id)
elif normalized_message == CMD_CAROUSEL_CARD:
send_carousel(conversation_id)
elif normalized_message == CMD_SUGGESTIONS:
send_message_with_suggestions(conversation_id)
elif normalized_message == CMD_BUSINESS_HOURS_INQUIRY:
send_message_with_business_hours(conversation_id)
elif normalized_message == CMD_ONLINE_SHOPPING_INQUIRY:
send_online_shopping_info_message(conversation_id)
elif normalized_message == CMD_SHOW_PRODUCT_CATEGORY:
send_product_catalog(conversation_id)
elif CMD_ADD_ITEM in normalized_message or CMD_DEL_ITEM in normalized_message:
update_shopping_cart(conversation_id, message)
elif normalized_message == CMD_SHOW_CART:
send_shopping_cart(conversation_id)
else:
echo_message(message, conversation_id)
...

根據我們在 send_shopping_cart 函式中導入的邏輯,當您輸入「show-cart」時,系統會顯示購物車中沒有任何商品的訊息、顯示購物車中單一商品的豐富資訊卡,或是顯示多個商品的資訊卡輪播。此外,我們還提供三種建議回覆:「查看總價」、「清空購物車」和「查看菜單」。
請嘗試部署上述程式碼變更,測試購物車是否會追蹤你加入的商品,以及你是否能從對話介面查看購物車 (如上方的螢幕截圖所示)。您可以在新增變更的 step-2 目錄中執行這項指令,部署變更。
$ gcloud app deploy
我們會在下一節中建構「查看總價」功能,然後再建構從購物車移除商品的函式。get_cart_price 函式的運作方式與「查看購物車」功能類似,會交叉參照 Datastore 中的資料和 inventory.json 檔案,計算購物車的總價。這在程式碼研究室的下一部分會派上用場,因為我們要整合付款功能。
從購物車中移除商品
最後,我們可以導入移除購物車的功能,完成購物車行為。將現有的 update_shopping_cart 函式換成下列程式碼片段。
bonjourmeal-codelab/step-2/ bopis/views.py
def update_shopping_cart(conversation_id, message):
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_LOCATION)
inventory = get_inventory_data()
cart_request = json.loads(message)
cart_cmd = cart_request["action"]
cart_item = cart_request["item_name"]
item_name = inventory['food'][int(cart_item)]['name']
client = datastore.Client(credentials=credentials)
key = client.key('ShoppingCart', conversation_id)
entity = datastore.Entity(key=key)
result = client.get(key)
if result is None:
if cart_cmd == CMD_ADD_ITEM:
entity.update({
item_name: 1
})
elif cart_cmd == CMD_DEL_ITEM:
# The user is trying to delete an item from an empty cart. Pass and skip
pass
else:
if cart_cmd == CMD_ADD_ITEM:
if result.get(item_name) is None:
result[item_name] = 1
else:
result[item_name] = result[item_name] + 1
elif cart_cmd == CMD_DEL_ITEM:
if result.get(item_name) is None:
# The user is trying to remove an item that's no in the shopping cart. Pass and skip
pass
elif result[item_name] - 1 > 0:
result[item_name] = result[item_name] - 1
else:
del result[item_name]
entity.update(result)
client.put(entity)
傳送確認訊息
使用者將商品加入購物車時,你應傳送確認訊息,告知對方你已收到要求並完成處理。這不僅有助於設定期望,還能讓對話持續進行。
讓我們擴充 update_shopping_cart 函式,向對話 ID 傳送訊息,說明項目已新增或移除,並建議使用者查看購物車或再次查看菜單。
bonjourmeal-codelab/step-2/bopis/views.py
def update_shopping_cart(conversation_id, message):
# No changes to the function, except appending the following logic
...
if cart_cmd == CMD_ADD_ITEM:
message = 'Great! You\'ve added an item to the cart.'
else:
message = 'You\'ve removed an item from the cart.'
message_obj = BusinessMessagesMessage(
messageId=str(uuid.uuid4().int),
representative=BOT_REPRESENTATIVE,
text=message,
suggestions=[
BusinessMessagesSuggestion(
reply=BusinessMessagesSuggestedReply(
text='Review shopping cart',
postbackData=CMD_SHOW_CART)
),
BusinessMessagesSuggestion(
reply=BusinessMessagesSuggestedReply(
text='See menu again',
postbackData=CMD_SHOW_PRODUCT_CATALOG)
),
])
send_message(message_obj, conversation_id)

這樣就大功告成了!提供功能齊全的購物車體驗,讓使用者新增、移除及查看購物車中的商品。
此時,如要在 Business Messages 對話中查看購物車功能,請部署應用程式,以便與服務專員互動。如要這麼做,請在 step-2 目錄中執行這項指令。
$ gcloud app deploy
5. 準備付款
為準備在下一部分與付款處理服務整合,我們需要取得購物車價格的方法。讓我們建立一個函式,透過交叉參照 Google Datastore 中的購物車資料、從商品目錄中擷取每個項目的價格,然後將價格乘以購物車中每個項目的數量,為我們擷取價格。
bonjourmeal-codelab/step-2/bopis/views.py
...
def get_cart_price(conversation_id):
# Pull the data from Google Datastore
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_LOCATION)
client = datastore.Client(credentials=credentials)
key = client.key('ShoppingCart', conversation_id)
entity = datastore.Entity(key=key)
result = client.get(key)
# Retrieve the inventory data
inventory = get_inventory_data()
# Start off with a total of 0 before adding up the total
total_price = 0
if len(result.items()) != 0:
for product_name, quantity in result.items():
total_price = total_price + float(
inventory['food'][get_id_by_product_name(product_name)]['price']) * int(quantity)
return total_price
...
最後,我們可以取用該函式,並傳送訊息給使用者。
bonjourmeal-codelab/step-2/bopis/views.py
...
def send_shopping_cart_total_price(conversation_id):
cart_price = get_cart_price(conversation_id)
message_obj = BusinessMessagesMessage(
messageId=str(uuid.uuid4().int),
representative=BOT_REPRESENTATIVE,
suggestions=[],
text=f'Your cart\'s total price is ${cart_price}.')
send_message(message_obj, conversation_id)
...
如要將所有內容整合在一起,請更新 route_message 函式和常數,以觸發上述邏輯。
bonjourmeal-codelab/step-2/bopis/views.py
...
CMD_GET_CART_PRICE = 'show-cart-price'
...
def route_message(message, conversation_id):
'''
Routes the message received from the user to create a response.
Args:
message (str): The message text received from the user.
conversation_id (str): The unique id for this user and agent.
'''
normalized_message = message.lower()
if normalized_message == CMD_RICH_CARD:
send_rich_card(conversation_id)
elif normalized_message == CMD_CAROUSEL_CARD:
send_carousel(conversation_id)
elif normalized_message == CMD_SUGGESTIONS:
send_message_with_suggestions(conversation_id)
elif normalized_message == CMD_BUSINESS_HOURS_INQUIRY:
send_message_with_business_hours(conversation_id)
elif normalized_message == CMD_ONLINE_SHOPPING_INQUIRY:
send_online_shopping_info_message(conversation_id)
elif normalized_message == CMD_SHOW_PRODUCT_CATEGORY:
send_product_catalog(conversation_id)
elif CMD_ADD_ITEM in normalized_message or CMD_DEL_ITEM in normalized_message:
update_shopping_cart(conversation_id, message)
elif normalized_message == CMD_SHOW_CART:
send_shopping_cart(conversation_id)
elif normalized_message == CMD_GET_CART_PRICE:
send_shopping_cart_total_price(conversation_id)
else:
echo_message(message, conversation_id)
...
以下幾張螢幕截圖顯示上述邏輯的成果:

在程式碼研究室的下一部分,我們準備與付款處理方整合時,會呼叫 get_cart_price 函式,將資料傳遞至付款處理方,並啟動付款流程。
同樣地,您也可以部署應用程式並與服務專員互動,在 Business Messages 對話中試用這項購物車功能。
$ gcloud app deploy
6. 恭喜
恭喜!你已在 Business Messages 中成功建構購物車體驗。
在本程式碼研究室中,我們未介紹清空整個購物車的功能。如果願意,請嘗試擴充應用程式,以完成「清空購物車」功能。解決方案位於您複製的原始碼步驟 3 中。
在後續章節中,我們會整合外部付款處理方,讓使用者能與您的品牌完成付款交易。
什麼是好的購物車?
對話中的購物車體驗與行動應用程式或實體商店並無不同。在本程式碼研究室中,我們探討了新增及移除項目,以及計算購物車價格等功能。與現實世界購物車不同的是,您可以在加入或移除商品時,隨時查看購物車中所有商品的價格。這些高價值功能可讓對話式商務體驗與眾不同!
後續步驟
準備就緒後,請參閱下列主題,瞭解如何在 Business Messages 中實現更複雜的互動:
參考文件
- SuggestedReply
- Business Messages 訊息參考文件
- RichCard 的 JSON 定義