本節說明如何將具有時效性的更新庫存實體傳送給 Google。透過 Incremental Update API,您可以近乎即時地推送更新及刪除沙箱或正式環境庫存中的實體。
這項功能主要用於無法預見的更新,例如緊急關閉。一般而言,透過 Incremental Update API 提交的任何變更應該在一小時內生效的變更。如果您的變更不需要立即反映,可以改用批次擷取。漸進式更新作業會在五分鐘內處理完畢。
必要條件
導入漸進式更新前,請先完成下列事項:
- 系統會建立具備動作專案的編輯者角色的服務帳戶。詳情請參閱「建立及設定專案」。
- 系統會代管並擷取實際工作環境或沙箱的資料動態饋給。詳情請參閱「批次擷取」。
- (建議選用) 安裝 Google 用戶端程式庫,安裝時應以您選擇的語言安裝,以便呼叫 API 時使用 OAuth 2.0。下列程式碼範例使用的是這些程式庫。否則,您必須按照「使用 OAuth 2.0 存取 Google API」一文中的說明,手動處理權杖交換。
端點
在以下要求中,替換以下內容:
- PROJECT_ID:與您在建立及設定專案中建立的專案相關聯的 Google Cloud 專案 ID。
- TYPE:要在資料動態饋給中更新的物件實體類型 (
@type
屬性)。 - ENTITY_ID (僅限刪除端點):要刪除的實體 ID。請務必對實體 ID 進行網址編碼。
- DELETE_TIME (僅限刪除端點):選填欄位,表示實體在系統中刪除的時間 (預設為收到要求的時間)。時間值不得為未來的時間。透過漸進式呼叫傳送實體時,實體版本管理也會在刪除呼叫時使用
delete_time
欄位。將此值的格式設為yyyy-mm-ddTHH:mm:ssZ
更新端點
如要修改實體,請向下列端點發出 HTTP POST 要求,並加入更新內容和新增項目的酬載。在單一 API 呼叫中,您最多可以更新 1,000 個實體。
https://actions.googleapis.com/v2/apps/PROJECT_ID/entities:batchPush
舉例來說,如果您想更新 ID 為「 Delivery-provider-id」的專案中的實體,端點如下所示:
https://actions.googleapis.com/v2/apps/delivery-provider-id/entities:batchpush
刪除端點
如要刪除清查中的實體,請對下列端點發出 HTTP DELETE 要求。
https://actions.googleapis.com/v2/apps/PROJECT_ID/entities/TYPE/ENTITY_ID?entity.vertical=FOODORDERING&delete_time=DELETE_TIME
舉例來說,如要從「 Delivery-provider-id」專案中刪除 ID 為「menuSection_122」的「MenuSection」實體,您必須發出 HTTP DELETE API 呼叫:
https://actions.googleapis.com/v2/apps/delivery-provider-id/entities/MenuSection/menuSection_122?entity.vertical=FOODORDERING
沙箱環境
如要在沙箱清查中使用 Incremental Update API,請按照上方端點中的指引操作,但請向 /v2/sandbox/apps/
提出要求,而非 /v2/apps/
。
https://actions.googleapis.com/v2/sandbox/apps/PROJECT_ID/entities:batchPush
https://actions.googleapis.com/v2/sandbox/apps/PROJECT_ID/entities/TYPE/ENTITY_ID?entity.vertical=FOODORDERING&delete_time=DELETE_TIME
更新實體
每個 POST 要求都必須包含要求參數,以及 JSON 酬載,其中包含商品目錄結構定義中所列任何實體類型的結構化資料。
更新酬載
JSON 看起來應與批次動態饋給中的內容相同,但下列差異如下:
- 酬載主體大小不得超過 5 MB。與批次動態饋給類似,建議您移除空白字元,以容納更多資料。
- 信封如下:
{ "requests": [ { "entity": { "data":"ENTITY_DATA", "name": "apps/project_id>/entities/type/entity_id" }, "update_time":"UPDATE_TIMESTAMP" }, ], "vertical": "FOODORDERING" }
在上述酬載中,替換以下內容:
- ENTITY_DATA:以字串序列化的 JSON 格式實體。JSON-LD 實體必須在
data
欄位中以字串的形式傳遞。 - UPDATE_TIMESTAMP (選用):系統中實體更新的時間戳記。時間值不得為未來的時間。預設時間戳記是指 Google 收到要求的時間。透過漸進式要求傳送實體時,實體版本管理也會在新增/更新要求時使用
update_time
欄位。
範例
範例 1:更新餐廳
假設您急需更新餐廳的電話號碼,您的更新包含整個餐廳的 JSON。
請考慮採用如下所示的批次動態饋給:
{ "@type": "Restaurant", "@id": "restaurant12345", "name": "Some Restaurant", "url": "https://www.provider.com/somerestaurant", "telephone": "+16501234567", "streetAddress": "345 Spear St", "addressLocality": "San Francisco", "addressRegion": "CA", "postalCode": "94105", "addressCountry": "US", "latitude": 37.472842, "longitude": -122.217144 }
然後,HTTP POST 的漸進式更新會如下所示:
POST v2/sandbox/apps/provider-project/entities:batchPush Host: actions.googleapis.com Content-Type: application/ld+json { "requests": [ { "entity": { "name": "apps/provider-project/entities/restaurant/restaurant12345", "data": { "@type": "Restaurant", "@id": "restaurant12345", "name": "Some Restaurant", "url": "https://www.provider.com/somerestaurant", "telephone": "+16501235555", "streetAddress": "345 Spear St", "addressLocality": "San Francisco", "addressRegion": "CA", "postalCode": "94105", "addressCountry": "US", "latitude": 37.472842, "longitude": -122.217144 } } } "vertical": "FOODORDERING" }
範例 2:更新多間餐廳
如要在單一 API 呼叫中更新兩個餐廳實體,HTTP POST 要求如下所示:
POST v2/sandbox/apps/provider-project/entities:batchPush Host: actions.googleapis.com Content-Type: application/ld+json { "requests": [ { "entity": { "name": "apps/provider-project/entities/restaurant/restaurant12345", "data": { "@type": "Restaurant", "@id": "restaurant12345", "name": "Some Restaurant", "url": "https://www.provider.com/somerestaurant", "telephone": "+16501235555", "streetAddress": "345 Spear St", "addressLocality": "San Francisco", "addressRegion": "CA", "postalCode": "94105", "addressCountry": "US", "latitude": 37.472842, "longitude": -122.217144 } } }, { "entity": { "name": "apps/provider-project/entities/restaurant/restaurant123", "data": { "@type": "Restaurant", "@id": "restaurant123", "name": "Some Other Restaurant", "url": "https://www.provider.com/somerestaurant", "telephone": "+16501231235", "streetAddress": "385 Spear St", "addressLocality": "San Mateo", "addressRegion": "CA", "postalCode": "94115", "addressCountry": "US" } } } ] "vertical": "FOODORDERING" }
示例 3:更新菜單品項價格
假設您需要變更選單項目的價格,如範例 1 所示,您的更新必須包含整個頂層實體 (選單) 的 JSON,且動態饋給會使用 v1 庫存結構定義。
請考慮採用如下所示的批次動態饋給:
{ "@type": "MenuItemOffer", "@id": "menuitemoffer6680262", "sku": "offer-cola", "menuItemId": "menuitem896532", "price": 3.00, "priceCurrency": "USD" }
然後使用 POST 進行漸進式更新的方式如下:
POST v2/sandbox/apps/provider-project/entities:batchPush Host: actions.googleapis.com Content-Type: application/ld+json { "requests": [ { "entity": { "name": "apps/provider-project/entities/menuitemoffer/menuitemoffer6680262", "data": { "@type": "MenuItemOffer", "@id": "menuitemoffer6680262", "sku": "offer-cola", "menuItemId": "menuitem896532", "price": 1.00, "priceCurrency": "USD" }, "vertical": "FOODORDERING" } } ] "vertical": "FOODORDERING" }
新增實體
如要新增實體,請避免使用商品目錄更新功能。請改為按照 v2 庫存結構定義所述,使用批次動態饋給程序。
移除實體
如要移除頂層實體,請稍微修改後的端點,並在要求中使用 HTTP DELETE 而非 HTTP POST。
刪除頂層實體
假設您想刪除動態饋給中的餐廳,您還必須刪除其服務和選單。
ID 為「provider/餐廳/menu/nr」的選單實體範例端點:
DELETE v2/apps/delivery-provider-id/entities/menu/provider%2Frestaurant%2Fmenu%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
範例:餐廳實體 ID 為「https://www.provider.com/restaurant/nr」:
DELETE v2/apps/delivery-provider-id/entities/restaurant/provider%2Frestaurant%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
ID 為「https://www.provider.com/restaurant/service/nr」的服務實體範例端點:
DELETE v2/apps/delivery-provider-id/entities/service/provider%2Frestaurant%2Fservice%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
}
移除子實體
請勿使用 HTTP DELETE 來移除頂層實體 (例如選單項目) 中的子實體。請改為將子實體移除視為更新,其中子實體已從相關清單或 reverseReference 中移除。
API 回應代碼
成功呼叫不代表動態饋給有效或正確,只代表發出 API 呼叫。成功的呼叫會收到 HTTP 回應代碼 200,以及空白的回應主體:
{}
如果失敗,HTTP 回應代碼會是 200,而回應主體會指出發生錯誤的原因。
舉例來說,如果使用者將信封中的「垂直」值設為 FAKE_VERTICAL
,您會收到以下訊息:
{
"error": {
"code": 400,
"message": "Invalid value at 'entity.vertical' (TYPE_ENUM), \"FAKE_VERTICAL\"",
"status": "INVALID_ARGUMENT",
"details": [
{
"@type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "entity.vertical",
"description": "Invalid value at 'entity.vertical' (TYPE_ENUM), \"FAKE_VERTICAL\""
}
]
}
]
}
}
程式碼範例
以下為如何以各種語言使用 Incremental Update API 的範例。這些範例使用 Google 驗證程式庫,並假設使用 v1 庫存結構定義的動態饋給。如需替代解決方案,請參閱「針對伺服器對伺服器應用程式使用 OAuth 2.0」。
更新實體
Node.js
此程式碼使用 Node.js 的 Google 驗證程式庫。
const {auth} = require('google-auth-library') const request = require('request'); // The service account client secret file downloaded from the Google Cloud Console const serviceAccountJson = require('./service-account.json') // entity.json is a file that contains the entity data in json format const entity = require('./entity.json') const ENTITY_ID = 'your/entity/id' const PROJECT_ID = 'type/your-project-id' /** * Get the authorization token using a service account. */ async function getAuthToken() { let client = auth.fromJSON(serviceAccountJson) client.scopes = ['https://www.googleapis.com/auth/assistant'] const tokens = await client.authorize() return tokens.access_token; } /** * Send an incremental update to update or add an entity */ async function updateEntity(entity) { const token = await getAuthToken() request.post({ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, url: `https://actions.googleapis.com/v2/apps/${PROJECT_ID}/entities:batchPush`, body: { requests: [ { entity: { data: JSON.stringify(entity) name: `apps/${PROJECT_ID}/entities/${ENTITY_ID}` } } ], vertical: 'FOODORDERING' }, json: true }, (err, res, body) => { if (err) { return console.log(err); } console.log(`Response: ${JSON.stringify(res)}`) }) } updateEntity(entity)
Python
這個程式碼使用 Python 適用的 Google 驗證程式庫。
from google.oauth2 import service_account from google.auth.transport.requests import AuthorizedSession import json import urllib PROJECT_ID = 'your-project-id' ENTITY_ID = 'type/your/entity/id' ENDPOINT = 'https://actions.googleapis.com/v2/apps/%s/entities:batchPush' % ( PROJECT_ID) # service-account.json is the service account client secret file downloaded from the # Google Cloud Console credentials = service_account.Credentials.from_service_account_file( 'service-account.json') scoped_credentials = credentials.with_scopes( ['https://www.googleapis.com/auth/assistant']) authed_session = AuthorizedSession(scoped_credentials) # Retrieving the entity update_file = open("entity.json") #JSON file containing entity data in json format. data = update_file.read() entity = {} entity['data'] = data #entity JSON-LD serialized as string entity['name'] = 'apps/%s/entities/%s' % (PROJECT_ID, urllib.quote(ENTITY_ID, '') ) # Populating the request request = {} request['entity'] = entity requestArray = [request] # Populating the payload payload = {} payload['requests'] = requestArray payload['vertical'] = 'FOODORDERING' response = authed_session.post(ENDPOINT, json=payload) print(response.text) #if successful, will be '{}'
Java
這個程式碼使用 Java 適用的 Google 驗證程式庫。
private static final String PROJECT_ID = "your-project-id"; private static final String ENTITY_ID = "type/your-entity-id"; /** * Get the authorization token using a service account. */ private static String getAuthToken() { InputStream serviceAccountFile = Example.class.getClassLoader().getResourceAsStream("service-account.json"); ServiceAccountCredentials.Builder credentialsSimpleBuilder = ServiceAccountCredentials.fromStream(serviceAccountFile).toBuilder(); credentialsSimpleBuilder.setScopes(ImmutableList.of("https://www.googleapis.com/auth/assistant")); AccessToken accessToken = credentialsSimpleBuilder.build().refreshAccessToken(); return accessToken.getTokenValue(); } /** * Send an incremental update to update or add an entity. * @param entityId The id of the entity to update. * @param entity the json of the entity to be updated. */ public void updateEntity(String entityId, JSONObject data) { String authToken = getAuthToken(); String endpoint = String.format("https://actions.googleapis.com/v2/apps/%s/entities/:batchPush", PROJECT_ID); JSONObject entity = new JSONObject(); entity.put("data", data.toString()); entity.put("name", String.format("apps/%s/entities/%s", PROJECT_ID, URLEncoder.encode(ENTITY_ID, "UTF-8"))); JSONObject request = new JSONObject(); request.put("entity", entity); JSONArray requestArray = new JSONArray(); requestArray.put(request); JSONObject payload = new JSONObject(); payload.put("requests", requestArray); payload.put("vertical", FOODORDERING); // Execute POST request executePostRequest(endpoint, authToken, payload); }
移除實體
Node.js
此程式碼使用 Node.js 的 Google 驗證程式庫。
const {auth} = require('google-auth-library') const request = require('request'); // The service account client secret file downloaded from the Google Cloud Console const serviceAccountJson = require('./service-account.json') // entity.json is a file that contains the entity data in json format const entity = require('./entity.json') const ENTITY_ID = 'restaurant/http://www.provider.com/somerestaurant' const PROJECT_ID = 'your-project-id' /** * Get the authorization token using a service account. */ async function getAuthToken() { let client = auth.fromJSON(serviceAccountJson) client.scopes = ['https://www.googleapis.com/auth/assistant'] const tokens = await client.authorize() return tokens.access_token; } /** * Send an incremental update to delete an entity */ async function deleteEntity(entityId) { const token = await getAuthToken() request.delete({ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, url: `https://actions.googleapis.com/v2/apps/${PROJECT_ID}/entities/${encodeURIComponent(entityId)}?entity.vertical=FOODORDERING`, body: {}, json: true }, (err, res, body) => { if (err) { return console.log(err); } console.log(`Response: ${JSON.stringify(res)}`) }) } deleteEntity(ENTITY_ID)
Python
這個程式碼使用 Python 適用的 Google 驗證程式庫。
from google.oauth2 import service_account from google.auth.transport.requests import AuthorizedSession import json import urllib # Service config PROJECT_ID = 'your-project-id' ENTITY_ID = 'restaurant/http://www.provider.com/somerestaurant' DELETE_TIME = '2018-04-07T14:30:00-07:00' ENDPOINT = 'https://actions.googleapis.com/v2/apps/%s/entities/%s?entity.vertical=FOODORDERING&delete_time=%s' % ( PROJECT_ID, urllib.quote(ENTITY_ID, ''), urllib.quote(DELETE_TIME, '')) # service-account.json is the service account client secret file downloaded from the # Google Cloud Console credentials = service_account.Credentials.from_service_account_file( 'service-account.json') scoped_credentials = credentials.with_scopes( ['https://www.googleapis.com/auth/assistant']) authed_session = AuthorizedSession(scoped_credentials) response = authed_session.delete(ENDPOINT) print(response.text) #if successful, will be '{}'
Java
這個程式碼使用 Java 適用的 Google 驗證程式庫。
private static final String PROJECT_ID = "your-project-id"; private static final String ENTITY_ID = "restaurant/http://www.provider.com/somerestaurant"; /** * Get the authorization token using a service account. */ private static String getAuthToken() { InputStream serviceAccountFile = Example.class.getClassLoader().getResourceAsStream("service-account.json"); ServiceAccountCredentials.Builder credentialsSimpleBuilder = ServiceAccountCredentials.fromStream(serviceAccountFile).toBuilder(); credentialsSimpleBuilder.setScopes(ImmutableList.of("https://www.googleapis.com/auth/assistant")); AccessToken accessToken = credentialsSimpleBuilder.build().refreshAccessToken(); return accessToken.getTokenValue(); } /** * Send an incremental update to delete an entity. * @param entityId The id of the entity to delete. */ public void deleteEntity(String entityId) { String authToken = getAuthToken(); String endpoint = String.format( "https://actions.googleapis.com/v2/apps/%s/entities/%s?entity.vertical=FOODORDERING", PROJECT_ID, URLEncoder.encode(entityId, "UTF-8")); // Execute DELETE request System.out.println(executeDeleteRequest(endpoint, authToken)); }
應用情境
以下應用實例包括漸進式更新、完整動態饋給更新,以及 API 呼叫中的高層級內容:
情境 | 要更新的實體 | 說明和效果 |
---|---|---|
停用服務 | Service |
出於未預期的原因,您必須停用服務。 增量更新:更新有問題的 完整動態饋給:請務必在 Google 下次擷取實體前,將完整動態饋給中的實體更新為 |
特定商品缺貨 | MenuItemOffer |
增量更新:針對指定的 MenuItem ,傳送 inventoryLevel 設為 0 的封裝 MenuItemOffer 實體,以及所有其他資料維持不變。 |
選單項目價格異動 | MenuItemOffer |
增量更新:傳送含有 price 的封裝 MenuItemOffer 實體,並將 price 設為指定 MenuItem 的更新價格,所有其他資料則維持不變。 |
新增頂層實體 僅適用於 |
Menu 、Restaurant 、Service |
舉例來說,您必須在餐廳中新增菜單。 完整動態饋給:在資料動態饋給中加入實體,然後等待批次擷取。 |
永久刪除頂層實體 僅適用於 |
Menu 、Restaurant 、Service |
增量更新:傳送明確刪除。 完整動態饋給:請務必在 Google 下次擷取實體前,將實體從完整動態饋給中移除,否則會重新加入實體。 |
新增特定Service 的寄送區域 |
ServiceArea |
增量動態饋給:傳送有問題的 ServiceArea 實體並完整呈現其所有欄位,就像您在完整動態饋給中一樣,並在 polygon 、geoRadius 或 postalCode 中指定新的運送區域。 |
更新 Service 後抵達的預估送達時間 |
ServiceHours |
增量動態饋給:傳送與動態饋給相同的 ServiceHours ,但 leadTimeMin 會據此更新。 |
更新Service 的運送價格 |
Fee |
增量動態饋給:傳送完整提交內容「Fee 」,已更新「price 」。 |
更新Service 中的外送或外帶時段 |
ServiceHours |
增量動態饋給:傳送與動態饋給相同的 ServiceHours ,但 opens 和 closes 屬性會據此更新。 |
Service (變更最低訂單金額) |
Fee |
增量動態饋給:傳送完整的「Fee 」和「minPrice 」更新 |
永久刪除MenuItem |
Menu |
增量動態饋給:傳送與動態饋給中的相同 MenuItem ,但 parentMenuSectionId 空白。 |
批次工作和漸進式更新的處理時間服務等級目標
透過批次更新或刪除的實體,系統會在 2 小時內以最佳方式處理,而透過漸進式更新來更新的實體則會在 5 分鐘內處理。過時實體將在 7 天後刪除。
你可以傳送以下其中一種給 Google:
- 每天執行多項批次工作,讓商品目錄保持在最新狀態;或
- 每天執行一項批次工作,並採用漸進式 API,讓庫存保持在最新狀態。