v2 增量库存更新

<ph type="x-smartling-placeholder">

本部分介绍如何发送商品目录的有时效性更新 实体提供给 Google。借助增量更新 API,您可以推送更新和删除 您的沙盒或正式版广告资源中的实体。

此功能主要用于您无法预见的更新, 例如紧急封闭通常,通过 增量更新 API 应于以下时间之内生效 一个小时。如果您的更改不需要立即体现,您可以使用 批量提取。 增量更新的处理时间不超过五分钟。

前提条件

在实现增量更新之前,必须满足以下要求:

  1. 系统会创建一个具有 Actions 项目的 Editor 角色的服务账号。 有关详情,请参阅 创建并设置项目
  2. 托管和提取生产或沙盒数据 Feed。 有关详情,请参阅 批量注入
  3. (可选,但建议执行)安装 Google 客户端库 以便在调用 API。下面提供的代码示例使用这些库。否则 需要按照使用 OAuth 2.0 访问 Google API 中的说明手动处理令牌交换。

端点

在以下请求中,替换以下内容:

  • PROJECT_ID:与您的项目关联的 Google Cloud 项目 ID 在创建和设置项目中创建的列表。
  • TYPE:实体类型(@type 属性) 您要更新的数据 Feed 中对象的 ID。
  • 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

沙盒环境

要在沙盒广告资源中使用增量更新 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 应该和批量 Feed 中一样, 以下差异:

  • 载荷正文的大小不得超过 5 MB。与批处理作业相似, Feed,我们建议您删除空白,以适应更多数据。
  • 信封如下所示:
{
  "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。

假设批量 Feed 如下所示:

{
  "@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,并且 Feed 使用 v1 产品目录架构。

假设批量 Feed 如下所示:

{
  "@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。

删除顶级实体

假设您想删除 Feed 中的餐馆。您必须 也会删除它的服务和菜单

具有 ID 的菜单实体的示例端点 &quot;provider/restaurant/menu/nr&quot;:

DELETE v2/apps/delivery-provider-id/entities/menu/provider%2Frestaurant%2Fmenu%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com

具有 ID 的餐馆实体的示例端点 &quot;https://www.provider.com/restaurant/nr&quot;:

DELETE v2/apps/delivery-provider-id/entities/restaurant/provider%2Frestaurant%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com

具有 ID 的服务实体的示例端点 &quot;https://www.provider.com/restaurant/service/nr&quot;:

DELETE v2/apps/delivery-provider-id/entities/service/provider%2Frestaurant%2Fservice%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
}

移除子实体

请勿使用 HTTP DELETE 移除顶级实体中的子实体,例如 菜单项。相反,将子实体的移除 更新为顶级实体,其中子实体已从 相关列表或 reverseReference

API 响应代码

调用成功并不意味着 Feed 有效或正确,只是表示 已完成 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\""
          }
        ]
      }
    ]
  }
}

代码示例

下面是一些示例,介绍了如何在各种环境中使用增量更新 API 语言。这些示例使用 Google Auth 库,并假设 Feed 使用 v1 广告资源架构如需了解替代解决方案,请参阅 针对“服务器到服务器”应用使用 OAuth 2.0

更新实体

Node.js

此代码使用适用于 Node.js 的 Google auth 库

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 auth 库

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 auth 库

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 auth 库

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));
}

使用场景

以下是增量更新、完整 Feed 更新、 以及 API 调用中的较高级别内容:

场景 要更新的实体 说明和效果
停用服务 Service

由于不可预见的原因,您需要停用服务。

增量更新:在以下位置更新 Service 实体: 只需将问题的 isDisabled 属性设置为 true 即可, 但其他属性保持不变

完整 Feed:请务必根据完整 Feed 更新实体 将isDisabled设为true,然后再 下次提取时,该实体将被重新启用。

特定商品缺货 MenuItemOffer 增量更新:发送封装 MenuItemOffer 具有 inventoryLevel 设置为 0 的实体。 MenuItem,所有其他数据保持不变。
菜单项价格变动 MenuItemOffer 增量更新:发送封装 MenuItemOfferprice 设置为指定 MenuItem,所有其他数据保持不变。

添加新的顶级实体

仅适用于 Menu 类型的实体, RestaurantService

MenuRestaurantService

例如,您需要向餐厅添加新菜单。

完整 Feed:在数据 Feed 中添加实体,并等待批量提取。

永久删除顶级实体

仅适用于 Menu 类型的实体, RestaurantService

MenuRestaurantService

增量更新:将 显式删除

完整 Feed:务必先从完整 Feed 中移除实体,然后再 下次提取时,系统将重新添加该实体。

在特定Service添加新的送货区域 ServiceArea 增量更新型 Feed:将相关 ServiceArea 实体及其所有 字段保持不变,就像您在完整 Feed 中一样,同时具有新的送货区域 在 polygongeoRadiuspostalCode 内指定。
更新预计送达时间(Service ServiceHours 增量 Feed:发送 ServiceHours 与 Feed,但其 leadTimeMin 已更新 。
更新Service的运费 Fee 增量供稿:发送完整递送Fee, “price”已更新。
更新Service的送货或外卖时间 ServiceHours 增量 Feed:发送 ServiceHours 与 Feed,但其 openscloses 属性已更新 。
Service(更改最低订单金额) Fee 增量更新 Feed:发送完整的 FeeminPrice 已更新
永久删除 MenuItem Menu 增量 Feed:发送 MenuItem 与 但 parentMenuSectionId 为空。

批量作业和增量更新处理时间的 SLO

批量更新或删除的实体将在 2 分钟内进行处理 小时,而通过增量更新更新的实体将得到处理 5 分钟后开始。系统会在 7 天后删除过时实体。

您可向 Google 发送以下信息:

  • 每天多个批量作业,确保您的商品目录处于最新状态;或
  • 每天一个批量作业和增量 API,让您的商品目录保持最新状态。