本節說明如何將動態饋給的時效性更新傳送給 Google。Incremental Updates API 可讓您以近乎即時的方式更新及刪除動態饋給中的實體。
這項功能主要適用於無法預見的更新 (例如緊急關閉通知)。根據規則,凡是透過 Incremental Updates API 提交的變更,都必須能在一週內的上線。如果不需要立即反映變更,您可以改用批次更新。漸進式更新作業不到五分鐘就能處理。
設定
如要實作漸進式更新,請執行下列步驟:
- 按照建立及設定專案一文中的步驟建立專案。
- 按照設定服務帳戶一文中的步驟建立服務帳戶。請注意,您必須是專案的「擁有者」角色,才能新增服務帳戶的「編輯者」角色
- (建議但建議使用) 以您選擇的語言安裝 Google 用戶端程式庫,以便在呼叫 API 時輕鬆使用 OAuth 2.0。下列程式碼範例使用此程式庫。否則,您必須按照使用 OAuth 2.0 存取 Google API 中所述,手動處理權杖交換作業。
端點
如要通知 Google 可用的更新,請對 Incremental Updates API 發出 HTTP POST 要求,並納入更新和新增項目的酬載。您使用的廣告空間結構定義會決定您要向哪個端點傳送要求:
v2 廣告空間
https://actions.googleapis.com/v2/apps/PROJECT_ID/entities/TYPE/ENTITY_ID:push
v1 廣告空間
https://actions.googleapis.com/v2/apps/PROJECT_ID/entities/ENTITY_ID:push
如要移除實體,請透過對應的值區結構定義發出 HTTP DELETE 要求:
v2 廣告空間
https://actions.googleapis.com/v2/apps/PROJECT_ID/entities/TYPE/ENTITY_ID?entity.vertical=FOODORDERING&delete_time=DELETE_TIME
v1 廣告空間
https://actions.googleapis.com/v2/apps/PROJECT_ID/entities/ENTITY_ID?entity.vertical=FOODORDERING&delete_time=DELETE_TIME
在上述要求中,替換下列內容:
- PROJECT_ID:與建立及設定專案中建立的專案相關聯的 Google Cloud 專案 ID。
- TYPE (僅限 v2 商品目錄結構定義):您要更新資料動態饋給中的物件實體類型 (
@type
屬性)。 - ENTITY_ID:酬載中包含的實體 ID。請務必對實體 ID 進行網址編碼。
- DELETE_TIME (僅限刪除端點):選填欄位,代表系統在系統上刪除實體的時間 (預設為收到要求的時間)。時間值不得在未來。透過漸進式呼叫傳送實體時,實體版本管理也會在刪除呼叫的情況下使用
delete_time
欄位。請將這個值的格式設為yyyy-mm-ddTHH:mm:ssZ
舉例來說,假設您的專案 ID 為「quot;delivery-provider-id」,而該版本會使用 v2 商品目錄結構定義。你想變更餐廳實體類型為「MenuSection&」的餐廳、「menuSection_122」實體 ID。更新資料的端點如下:
https://actions.googleapis.com/v2/apps/delivery-provider-id/entities/MenuSection/menuSection_122:push
如要移除同一個實體,您必須發出以下 HTTP DELETE API 呼叫:
https://actions.googleapis.com/v2/apps/delivery-provider-id/entities/MenuSection/menuSection_122?entity.vertical=FOODORDERING
沙箱要求
針對沙箱要求,請按照上述端點中的指示,但向 /v2/sandbox/apps/
而非 /v2/apps/
發出要求。舉例來說,對 v2 廣告空間結構定義的沙箱刪除要求結構如下:
https://actions.googleapis.com/v2/sandbox/apps/PROJECT_ID/entities/TYPE/ENTITY_ID?entity.vertical=FOODORDERING&delete_time=DELETE_TIME
更新與新增項目
每日批次動態饋給也應包含透過這個 API 提交的任何變更。否則,批次更新就會覆寫漸進式變更。
酬載
每個 POST 要求都必須包含要求參數,以及包含商品目錄結構定義中任何實體類型的結構化資料的 JSON 酬載。
JSON 應與批次動態饋給中的結果相同,但有以下差異:
- 酬載主體的大小不得超過 5 MB。與批次動態饋給類似,我們建議您刪除空白字元以容納更多資料。
- 信封如下:
{ "entity": { "data":"ENTITY_DATA", "vertical":"FOODORDERING" }, "update_time":"UPDATE_TIMESTAMP" }
在上述酬載中,替換以下內容:
- 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/apps/provider-project/entities/Restaurant/restaurant12345:push Host: actions.googleapis.com Content-Type: application/ld+json { "entity": { "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:更新菜單品項的價格
假設你需要變更選單項目的價格。與範例 1 相同,您的更新必須包含整個頂層實體 (選單) 的 JSON,而動態饋給會使用 v1 庫存結構定義。
批次批次動態饋給應如下所示:
{ "@type": "MenuItemOffer", "@id": "menuitemoffer6680262", "sku": "offer-cola", "menuItemId": "menuitem896532", "price": 3.00, "priceCurrency": "USD" }
然後,透過 POST 的漸進式更新如下:
POST v2/apps/provider-project/entities/MenuItemOffer/menuitemoffer6680262:push Host: actions.googleapis.com Content-Type: application/ld+json { "entity": { "data": { "@type": "MenuItemOffer", "@id": "menuitemoffer6680262", "sku": "offer-cola", "menuItemId": "menuitem896532", "price": 1.00, "priceCurrency": "USD" }, "vertical": "FOODORDERING" } }
新增實體
如要新增實體,請避免使用商品目錄更新資料。請改用第 2 版商品目錄結構定義所述的批次動態饋給程序。
移除實體
如要移除頂層實體,請使用稍微修改的端點,並在要求中使用 HTTP DELETE 而非 HTTP POST。
請勿使用 HTTP DELETE 移除頂層實體中的子實體,例如選單中的選單項目。請改為將移除子實體視為頂層實體更新,再從相關的清單或參數中移除子實體。
範例 1:刪除頂層實體
假設您想在使用 v1 庫存結構定義的動態饋給中刪除餐廳,此外,您也必須刪除這些服務及其選單。
適用於 ID 為 https://www.provider.com/restaurant/menu/nr"
DELETE v2/apps/delivery-provider-id/entities/https%3A%2F%2Fwww.provider.com%2Frestaurant%2Fmenu%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
ID 為 https://www.provider.com/restaurant/nr" 的餐廳實體範例端點:
DELETE v2/apps/delivery-provider-id/entities/https%3A%2F%2Fwww.provider.com%2Frestaurant%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
服務 ID 為「https://www.provider.com/restaurant/service/nr"」的服務實體範例端點:
DELETE v2/apps/delivery-provider-id/entities/https%3A%2F%2Fwww.provider.com%2Frestaurant%2Fservice%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
}
範例 2:移除子實體
如要將頂層實體從頂層實體中移除,您可以傳送頂層實體,並將子實體從對應的欄位中移除。以下範例假設動態饋給使用 v1 商品目錄結構定義。
舉例來說,如要移除服務範圍,請更新服務,並將服務範圍從 areaServed
清單中移除。
POST v2/apps/delivery-provider-id/entities/https%3A%2F%2Fwww.provider.com%2Frestaurant%2Fservice%2Fnr:push
Host: actions.googleapis.com
Content-Type: application/ld+json
{
"entity": {
// Note: "data" is not serialized as a string in our example for readability.
"data": {
"@type": "Service",
"provider": {
"@type": "Restaurant",
"@id": "https://www.provider.com/restaurant/nr"
},
"areaServed": [
{
"@type": "GeoCircle",
"geoMidpoint": {
"@type": "GeoCoordinates",
"latitude": "42.362757",
"longitude": "-71.087109"
},
"geoRadius": "10000"
}
// area2 is removed.
]
...
},
"vertical": "FOODORDERING"
}
}
API 回應代碼
成功呼叫並不代表動態饋給有效或正確,只代表 API 呼叫已建立。成功的呼叫會收到 HTTP 回應代碼 200 和空白回應主體:
{}
失敗時,HTTP 回應代碼不會為 200,且回應主體會指出發生錯誤的原因。
舉例來說,如果使用者將信封中的「vertical」值設為 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 Updates 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 = '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 update or add an entity */ async function updateEntity(entityId, 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/${encodeURIComponent(entityId)}:push`, body: { entity: { data: JSON.stringify(entity), vertical: 'FOODORDERING', } }, json: true }, (err, res, body) => { if (err) { return console.log(err); } console.log(`Response: ${JSON.stringify(res)}`) }) } updateEntity(ENTITY_ID, 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 = 'restaurant/http://www.provider.com/somerestaurant' ENDPOINT = 'https://actions.googleapis.com/v2/apps/%s/entities/%s:push' % ( PROJECT_ID, urllib.quote(ENTITY_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() # Populating the entity with wrapper entity = {} entity['data'] = data #entity JSON-LD serialized as string entity['vertical'] = 'FOODORDERING' request = {} request['entity'] = entity response = authed_session.post(ENDPOINT, json=request) 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 = "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 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 entity) { String authToken = getAuthToken(); String endpoint = String.format( "https://actions.googleapis.com/v2/apps/%s/entities/%s:push", PROJECT_ID, URLEncoder.encode(entityId, "UTF-8")); JSONObject data = new JSONObject(); data.put("data", entity.toString()); data.put("vertical", "FOODORDERING"); JSONObject jsonBody = new JSONObject(); jsonBody.put("entity", data); // Execute POST request executePostRequest(endpoint, authToken, jsonBody); }
移除實體
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 呼叫中高階內容的內容:
情境 | 頂層實體 | 說明與效果 |
---|---|---|
停用服務 | DisabledService |
您正因不明原因而停用服務。 漸進式更新:傳送有爭議的 完整動態饋給:在 Google 下次擷取前,請務必更新完整動態饋給中的實體,並將 |
特定商品缺貨中 | Menu |
遞增更新:針對指定的 MenuItem 傳送封裝為 offer.inventoryLevel 的封裝實體 Menu ,且其他資料維持不變。 |
菜單商品價格異動 | Menu |
漸進式更新:傳送 offer.price 實體封裝,並將 offer.price 實體設為給定 MenuItem 的更新價格,所有其他資料則維持不變。 |
新增頂層實體 僅適用於 |
Service 年取得Menu Restaurant 學位 |
舉例來說,你必須在餐廳中新增菜單。 漸進式更新:傳送新的選單實體,以及其欄位 |
永久刪除頂層實體 僅適用於 |
Service 年取得Menu Restaurant 學位 |
漸進式更新:傳送明確刪除。 完整動態饋給:在 Google 下次擷取前,請先從完整動態饋給中移除實體,否則這個實體就會重新加入。 |
在特定 Service 中新增運送區域 |
Service |
漸進式動態饋給:傳送爭議的 Service 實體,確保所有欄位都完整不變,就像一般在完整動態饋給中一樣,並以 Service 的 areaServed 中指定新放送區域。 |
更新Service 的預估送達時間 |
Service |
漸進式動態饋給:傳送 Service 與動態饋給中相同,但其 hoursAvailable.deliveryHours 會隨之更新。 |
更新Service 的價格 |
Service |
漸進式動態饋給:完整傳送 Service 並更新 offers.priceSpecification.price 。 |
更新「Service 」的外送或外帶時段 |
Service |
漸進式動態饋給:傳送 Service 與動態饋給中相同,但其 hoursAvailable 會隨之更新。 |
Service (變更最低訂單金額) |
Service |
漸進式動態饋給:傳送完整的 Service 並更新 Service.offers.priceSpecification.eligibleTransactionVolume |
永久刪除「MenuItem 」 |
Menu |
漸進式動態饋給:以與動態饋給中相同的方式傳送 Menu ,但會將這個 MenuItem 從 hasMenuItems 清單中移除。 |
批次工作處理時間和漸進式更新作業的服務水準協議
採用批次或漸進式更新作業的實體,會在 1 到 2 天內處理完畢。透過批次更新或刪除實體的實體,會在 2 小時內處理完畢;而透過漸進式更新方式更新的實體則會在 5 分鐘內處理。過時實體會在 7 天後刪除。
你可以傳送下列資料給 Google:
- 每天可執行多項批次工作,確保商品目錄符合現況,或是
- 每天一次一個批次工作,並搭配漸進式 API 讓廣告空間保持最新狀態。