v2 漸進式商品目錄更新

,瞭解如何調查及移除這項存取權。

本節說明如何傳送具時效性的商品目錄更新 實體上傳至 Google。Incremental Update API 可讓您推送更新及刪除 就能大幅提升作業效率

這項功能主要是供您無法預見的更新 例如緊急關閉。通常透過 漸進式更新 API 應在以下時間以內推出: 1 小時。如果不需要立即反映變更,您可以 批次擷取。 漸進式更新會在五分鐘內處理完畢。

必要條件

實作漸進式更新前,請務必先完成以下事項:

  1. 系統會建立具有 Actions 專案的編輯者角色的服務帳戶。 詳情請參閱: 建立及設定專案
  2. 系統會代管及擷取實際工作環境或沙箱資料動態饋給。 詳情請參閱: 批次擷取
  3. (建議選用) 安裝 Google 用戶端程式庫 並在呼叫 也能使用 Google Cloud CLI 或 Compute Engine API以下提供的程式碼範例使用了這些程式庫。否則, 必須手動處理權杖交換,如使用 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

例如,要刪除「MenuSection」ID 為「menuSection_122」的實體當中的「delivery-provider-id」就必須對以下程式碼發出 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:更新餐廳

假設您急需更新餐廳的電話號碼,您的 update 會包含整間餐廳的 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 所示,您的 update 必須包含整個頂層實體 (選單) 的 JSON,而 動態饋給會採用第 1 版商品目錄架構。

假設批次動態饋給如下所示:

{
  "@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"
}
敬上

新增實體

如要新增實體,請避免使用商品目錄更新項目。建議改用批次動態饋給 第 2 版商品目錄架構中所述的程序。

移除實體

如要移除頂層實體,請使用稍微修改的端點。 並在要求中使用 HTTP DELETE,而不是 HTTP POST。

刪除頂層實體

舉例來說,當你想刪除動態饋給中的餐廳時,您必須 也會一併刪除其服務和選單。

選單實體 (ID 為) 的範例端點 "provider/restaurant/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 為 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,而回應主體 代表出了問題

舉例來說,如果使用者將「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 Update API 語言。這些範例使用 Google Auth 程式庫,並假設動態饋給為 第 1 版商品目錄架構如要瞭解替代解決方案,請參閱 針對伺服器對伺服器應用程式使用 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

您必須基於未預期的原因停用服務。

增量更新:Service 方法是將 isDisabled 屬性設為 true。 但不要變更其他屬性

完整動態饋給:請務必更新完整動態饋給中的實體 必須將「isDisabled」設為「true」,才能 下一次由 Google 擷取,否則系統將重新啟用該實體。

特定產品缺貨中 MenuItemOffer 增量更新:傳送封裝的 MenuItemOffer 就指定類別而言,inventoryLevel 設為 0 的實體 MenuItem,所有其他資料則維持不變。
菜單品項價格異動 MenuItemOffer 增量更新:傳送封裝的 MenuItemOffer price 設定為指定的更新價格 MenuItem,所有其他資料則維持不變。

新增頂層實體

僅適用於 Menu 類型的實體, RestaurantService

MenuRestaurantService

舉例來說,您需要為餐廳新增菜單,

完整動態饋給:在資料動態饋給中加入實體,然後等待批次擷取。

永久刪除頂層實體

僅適用於 Menu 類型的實體, RestaurantService

MenuRestaurantService

增量更新:傳送 「明確刪除」

完整動態饋給:請務必在 下一次 Google 擷取,否則會重新加入該實體。

新增特定Service的送貨區域 ServiceArea 漸進式動態饋給:傳送相關的 ServiceArea 實體和所有 欄位完整保留,就像您平常在完整動態饋給內一樣,並新增了運送區域 polygongeoRadiuspostalCode 內指定。
更新Service後的預計送達時間 ServiceHours 漸進式動態饋給:傳送與活動相同的 ServiceHours 動態饋給,但 leadTimeMin 除外 。
更新Service的配送價格 Fee 漸進式動態饋給:Fee 傳送完整提交資料, 已更新「price」。
更新Service的外送或外帶時段 ServiceHours 漸進式動態饋給:傳送與活動相同的 ServiceHours 動態饋給 (openscloses 屬性除外) 。
Service (變更最低訂單金額) Fee 漸進式動態饋給:以下列方式傳送完整的「Fee」: minPrice 已更新
永久刪除MenuItem Menu 漸進式動態饋給:傳送與活動相同的 MenuItemparentMenuSectionId 空白

批次工作和漸進式更新處理時間的服務等級目標

透過批次更新或刪除的實體,系統會在 2 個日期內處理該實體 處於最佳作業模式的時數,而透過漸進式更新對實體進行更新時 短短 5 分鐘內就能完成過時實體會在 7 天後刪除。

您可以向 Google 傳送以下資訊:

  • 每天執行多項批次工作,讓商品目錄資料保持在最新狀態。
  • 每天一項批次工作和漸進式 API,讓商品目錄資料保持最新狀態。