Управление настройками омниканальной сети

API настроек омниканальной сети — это точка входа для настройки ваших программ размещения объявлений о наличии товаров в местных магазинах (LIA) и бесплатных объявлений о продаже товаров в местных магазинах (FLL).

Используйте его для программного обеспечения.

  • Управление (создание и обновление) настройками омниканальной сети
  • Получение (получение и вывод списка) настроек омниканальности.
  • Запросите проверку наличия товаров у соответствующих продавцов.

Для получения дополнительной информации см. раздел «Обзор объявлений о продаже недвижимости в вашем районе и бесплатных местных объявлений» .

Предварительные требования

Вам следовало бы

Создайте многоканальную настройку.

Для создания многоканальной настройки можно использовать метод ` omnichannelSettings.create . Метод `create` принимает в качестве входных данных ресурс ` omnichannelSetting и в случае успеха возвращает созданную многоканальную настройку.

При создании необходимо заполнить поля regionCode и LsfType :

  • Параметр OmnichannelSetting применяется к каждой стране отдельно. RegionCode определяет целевую страну. После создания его изменить нельзя. RegionCode должен соответствовать правилам именования, определенным проектом Common Locale Data Repository (CLDR) .
  • LsfType определяется на основе страницы вашего товара. Подробнее см. LsfType .

Для получения более подробной информации см. раздел «Изменение внешнего вида страницы товара для объявлений о наличии товара в вашем регионе» .

Заполнять все поля на этапе создания необязательно, их можно настроить позже. Чтобы обновить существующий параметр omnichannelSetting , см. раздел «Обновление параметра omnichannelSetting» .

Вот пример запроса, если вы выберете MHLSF_BASIC и зарегистрируетесь inStock :

POST https://merchantapi.googleapis.com/accounts/v1/accounts/{ACCOUNT_ID}/omnichannelSettings

{
  "regionCode": "{REGION_CODE}",
  "lsfType: "MHLSF_BASIC",
  "inStock": {
      "uri": {URI}"
  }
}

Замените следующее:

  • {ACCOUNT_ID} : Уникальный идентификатор вашей учетной записи в Merchant Center.
  • {REGION_CODE} : Код региона, определенный CLDR.
  • {URI} : Действительный URI, используемый для данного обзора. Недопустимый URI может помешать одобрению.

После успешного выполнения запроса вы должны увидеть следующий ответ:

{
  "name": "accounts/{ACCOUNT_ID}/omnichannelSettings/{omnichannel_setting}",
  "regionCode": "{REGION_CODE}",
  "lsfType: "MHLSF_BASIC",
  "inStock": {
      "uri": "{URI}",
      "state": "RUNNING"
  }
}

Регистрация различных функций LIA/FLL с использованием полей omnichannelSetting запускает ручную проверку, которая обычно занимает от нескольких часов до нескольких дней. Мы рекомендуем дважды проверить введенные данные, чтобы избежать ненужного ожидания из-за неподходящих данных.

Чтобы просмотреть созданные вами настройки омниканального взаимодействия или проверить состояние отзывов, используйте accounts.omnichannelSettings.get или accounts.omnichannelSettings.list , указав страну.

Тип местного магазина (LSF)

В зависимости от страницы продукта, который вы планируете использовать, выберите тип LsfType :

Тип страницы товара LsfType Значение перечисления
Страницы товаров с информацией о наличии в магазинах Базовый формат местного магазина, обслуживаемого продавцом. MHLSF_BASIC
Страницы товаров, доступные в конкретном магазине, с указанием наличия и цены. Торговая площадка местного магазина, полностью занятая товарами. MHLSF_FULL
Страницы товаров, недоступных в магазинах. Локальный интернет-магазин, размещенный на платформе Google (GHLSF) GHLSF

Если вы выбираете тип локального магазина, размещенного на сервере продавца, вам также необходимо заполнить поле URI хотя бы для одного из вариантов: inStock или pickup .

В наличии

Вы можете использовать InStock, чтобы предоставить более подробную информацию о странице вашего товара.

Если вы выберете типы LSF, размещаемые продавцом, и укажете поле URI в поле InStock, вы покажете свое намерение показывать товары, имеющиеся в наличии. Мы начнем проверку на основе предоставленного URI.

Если вы выберете тип GHLSF , вам необходимо указать пустое поле InStock в запросе. В отличие от типов LSF, размещаемых продавцом, для завершения процесса подключения вам необходимо пройти процедуру проверки наличия товара .

Этот пример кода создает объект omnichannelSetting с использованием GHLSF :

Java

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.AccountName;
import com.google.shopping.merchant.accounts.v1.CreateOmnichannelSettingRequest;
import com.google.shopping.merchant.accounts.v1.InStock;
import com.google.shopping.merchant.accounts.v1.OmnichannelSetting;
import com.google.shopping.merchant.accounts.v1.OmnichannelSetting.LsfType;
import com.google.shopping.merchant.accounts.v1.OmnichannelSettingsServiceClient;
import com.google.shopping.merchant.accounts.v1.OmnichannelSettingsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/**
 * This class demonstrates how to create an omnichannel setting for a given Merchant Center account
 * in a given country
 */
public class CreateOmnichannelSettingSample {

  public static void createOmnichannelSetting(Config config, String regionCode) throws Exception {

    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    // Creates service settings using the credentials retrieved above.
    OmnichannelSettingsServiceSettings omnichannelSettingsServiceSettings =
        OmnichannelSettingsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Calls the API and catches and prints any network failures/errors.
    try (OmnichannelSettingsServiceClient omnichannelSettingsServiceClient =
        OmnichannelSettingsServiceClient.create(omnichannelSettingsServiceSettings)) {
      String accountId = config.getAccountId().toString();
      String parent = AccountName.newBuilder().setAccount(accountId).build().toString();

      // Creates an omnichannel setting with GHLSF type in the given country.
      CreateOmnichannelSettingRequest request =
          CreateOmnichannelSettingRequest.newBuilder()
              .setParent(parent)
              .setOmnichannelSetting(
                  OmnichannelSetting.newBuilder()
                      .setRegionCode(regionCode)
                      .setLsfType(LsfType.GHLSF)
                      .setInStock(InStock.getDefaultInstance())
                      .build())
              .build();

      System.out.println("Sending create omnichannel setting request:");
      OmnichannelSetting response =
          omnichannelSettingsServiceClient.createOmnichannelSetting(request);

      System.out.println("Inserted Omnichannel Setting below:");
      System.out.println(response);
    } catch (Exception e) {
      System.out.println("An error has occured: ");
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();

    // The country which you're targeting at.
    String regionCode = "{REGION_CODE}";

    createOmnichannelSetting(config, regionCode);
  }
}

PHP

use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1\Client\OmnichannelSettingsServiceClient;
use Google\Shopping\Merchant\Accounts\V1\CreateOmnichannelSettingRequest;
use Google\Shopping\Merchant\Accounts\V1\InStock;
use Google\Shopping\Merchant\Accounts\V1\OmnichannelSetting;
use Google\Shopping\Merchant\Accounts\V1\OmnichannelSetting\LsfType;

/**
 * This class demonstrates how to create an omnichannel setting for a given
 * Merchant Center account in a given country.
 */
class CreateOmnichannelSetting
{
    /**
     * Helper to create the parent string.
     *
     * @param string $accountId The merchant account ID.
     * @return string The parent string in the format `accounts/{account}`.
     */
    private static function getParent(string $accountId): string
    {
        return sprintf('accounts/%s', $accountId);
    }

    /**
     * Creates an omnichannel setting for a given Merchant Center account.
     *
     * @param array $config The configuration file for authentication.
     * @param string $regionCode The country for the omnichannel setting.
     */
    public static function createOmnichannelSettingSample(
        array $config,
        string $regionCode
    ): void {
        // Obtains OAuth credentials from the configuration file.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Creates a client.
        $omnichannelSettingsServiceClient = new OmnichannelSettingsServiceClient([
            'credentials' => $credentials
        ]);

        // Constructs the parent resource name.
        $parent = self::getParent($config['accountId']);

        // Creates the omnichannel setting with GHLSF type in the given country.
        $omnichannelSetting = new OmnichannelSetting([
            'region_code' => $regionCode,
            'lsf_type' => LsfType::GHLSF,
            'in_stock' => new InStock()
        ]);

        // Creates the request.
        $request = new CreateOmnichannelSettingRequest([
            'parent' => $parent,
            'omnichannel_setting' => $omnichannelSetting
        ]);

        // Calls the API and prints the response.
        try {
            printf("Sending create omnichannel setting request:%s", PHP_EOL);
            $response = $omnichannelSettingsServiceClient->createOmnichannelSetting($request);
            printf("Inserted Omnichannel Setting below:%s", PHP_EOL);
            print $response->serializeToJsonString(true) . PHP_EOL;
        } catch (ApiException $e) {
            printf("An error has occured: %s", $e->getMessage());
        }
    }

    /**
     * Executes the sample.
     */
    public function callSample(): void
    {
        $config = Config::generateConfig();
        // The country which you're targeting.
        $regionCode = '{REGION_CODE}';
        self::createOmnichannelSettingSample($config, $regionCode);
    }
}

// Runs the script.
$sample = new CreateOmnichannelSetting();
$sample->callSample();

Python

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import CreateOmnichannelSettingRequest
from google.shopping.merchant_accounts_v1 import InStock
from google.shopping.merchant_accounts_v1 import OmnichannelSetting
from google.shopping.merchant_accounts_v1 import OmnichannelSettingsServiceClient


def create_omnichannel_setting(account_id: str, region_code: str) -> None:
  """Creates an omnichannel setting for a given Merchant Center account.

  Args:
      account_id: The ID of the Merchant Center account.
      region_code: The country for which you're creating the setting.
  """
  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client.
  client = OmnichannelSettingsServiceClient(credentials=credentials)

  # The parent account under which to create the setting.
  parent = f"accounts/{account_id}"

  # Creates an omnichannel setting with GHLSF type in the given country.
  omnichannel_setting = OmnichannelSetting()
  omnichannel_setting.region_code = region_code
  omnichannel_setting.lsf_type = OmnichannelSetting.LsfType.GHLSF
  omnichannel_setting.in_stock = InStock()

  # Creates the request.
  request = CreateOmnichannelSettingRequest(
      parent=parent, omnichannel_setting=omnichannel_setting
  )

  # Makes the request and catches and prints any error messages.
  try:
    print("Sending create omnichannel setting request:")
    response = client.create_omnichannel_setting(request=request)
    print("Inserted Omnichannel Setting below:")
    print(response)
  except RuntimeError as e:
    print("An error has occured: ")
    print(e)


if __name__ == "__main__":
  # The ID of the account to get the omnichannel settings for.
  _ACCOUNT = configuration.Configuration().read_merchant_info()

  # The country which you're targeting.
  _REGION_CODE = "{REGION_CODE}"

  create_omnichannel_setting(_ACCOUNT, _REGION_CODE)

Подобрать

Помимо наличия товара в магазине, вы также можете расширить ассортимент товаров, доступных в магазине, с помощью функции самовывоза, которая доступна только для товаров типа LSF, размещенных продавцом.

Если товар помечен как «Самовывоз», это означает, что покупатель может приобрести его онлайн и забрать в магазине. Указав поле Pickup , вы демонстрируете свое намерение предоставлять товары с условием самовывоза. Мы начнем проверку на основе предоставленного URI.

Вот пример запроса, который создает omnichannel конфигурацию с Pickup :

POST https://merchantapi.googleapis.com/accounts/v1/accounts/{ACCOUNT_ID}/omnichannelSettings

{
  "regionCode": "{REGION_CODE}",
  "lsfType: "MHLSF_BASIC",
  "pickup": {
     "uri: "{URI}"
  }
}

Выставляется на продажу по предварительному заказу.

Функция «Выставка под заказ» позволяет демонстрировать товары, которые есть в вашем физическом магазине, но недоступны для немедленной покупки. Например, крупная мебель:

  • Покупатели, ищущие похожие товары в Google, увидят эти объявления с пометкой «в магазине» в результатах поиска.
  • Покупатели, просматривающие магазин на странице результатов поиска Google, увидят эти товары с пометкой «Доступно для заказа».

Они могут выбрать ваше местное рекламное объявление или бесплатное местное объявление, чтобы посмотреть товар. Чтобы купить товар, они могут посетить ваш физический магазин, посмотреть его, а затем заказать доставку или доставку в ваш магазин для самовывоза.

О Германии, Австрии и Швейцарии

Если вы проходите службу в Австрии или Германии и выбираете GHLSF , вам необходимо заполнить страницу «О нас» .

Если вы проходите службу в Швейцарии, вы должны предоставить страницу «О нас» независимо от LsfType .

До подтверждения URL-адреса страницы «О нас» продавцы GHLSF не могут запрашивать у Google ручную проверку наличия товаров на складе.

Для всех продавцов в этих трех странах функция FLL/LIA не будет активирована до тех пор, пока ваша страница «О нас» не получит одобрение.

Проверка инвентаризации

Проверка инвентаризации требуется только для продавцов, GHLSF . Для продавцов, использующих MHLSF она не поддерживается.

Перед добавлением данных о товарах и складских запасах (с помощью accounts.products.localInventories.insert или пользовательского интерфейса Merchant Center) или после этого необходимо подтвердить контактные данные. Укажите контактные данные для подтверждения наличия товара (имя и адрес электронной почты) с помощью метода create или update . Контакт получит электронное письмо от Google, и сможет подтвердить свой статус, нажав кнопку в сообщении.

После завершения этой процедуры вы можете запросить проверку инвентаризации . Для получения дополнительной информации см. раздел «О проверке инвентаризации» .

Вы можете изменить свои контактные данные во время процесса верификации или после верификации, используя omnichannelSetting.update .

После завершения этого процесса Google проверяет точность предоставленной информации.

Настройте многоканальную систему

Чтобы получить конфигурацию omnichannelSetting для конкретной страны или проверить текущий статус ваших отзывов, используйте метод omnichannelSettings.get .

Вот пример запроса:

GET https://merchantapi.googleapis.com/accounts/v1/accounts/{ACCOUNT_ID}/omnichannelSettings/{OMNICHANNEL_SETTING}

Замените следующее:

  • {ACCOUNT_ID} : Уникальный идентификатор вашей учетной записи в Merchant Center.
  • {OMNICHANNEL_SETTING} : Код региона вашей целевой страны

Статус ACTIVE означает, что проверка получила одобрение.

Если статус FAILED , устраните проблемы и запустите новую проверку, вызвав функцию omnichannelSetting.update .

Поле LFP (только для чтения) отображает статус вашего партнерства с локальными источниками данных. Для привязки к партнерству используйте lfpProviders.linkLfpProvider .

Для получения дополнительной информации о проверке статусов и их значениях см. раздел «Просмотр статуса многоканальной настройки» .

Список настроек омниканальной сети

Чтобы получить всю информацию omnichannelSetting для вашей учетной записи, используйте метод omnichannelSettings.list .

Вот пример кода:

Java

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.AccountName;
import com.google.shopping.merchant.accounts.v1.ListOmnichannelSettingsRequest;
import com.google.shopping.merchant.accounts.v1.OmnichannelSetting;
import com.google.shopping.merchant.accounts.v1.OmnichannelSettingsServiceClient;
import com.google.shopping.merchant.accounts.v1.OmnichannelSettingsServiceClient.ListOmnichannelSettingsPagedResponse;
import com.google.shopping.merchant.accounts.v1.OmnichannelSettingsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/**
 * This class demonstrates how to get the list of omnichannel settings for a given Merchant Center
 * account
 */
public class ListOmnichannelSettingsSample {

  public static void omnichannelSettings(Config config) throws Exception {

    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    // Creates service settings using the credentials retrieved above.
    OmnichannelSettingsServiceSettings omnichannelSettingsServiceSettings =
        OmnichannelSettingsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    String accountId = config.getAccountId().toString();
    String parent = AccountName.newBuilder().setAccount(accountId).build().toString();

    // Calls the API and catches and prints any network failures/errors.
    try (OmnichannelSettingsServiceClient omnichannelSettingsServiceClient =
        OmnichannelSettingsServiceClient.create(omnichannelSettingsServiceSettings)) {
      ListOmnichannelSettingsRequest request =
          ListOmnichannelSettingsRequest.newBuilder().setParent(parent).build();

      System.out.println("Sending list omnichannel setting request:");
      ListOmnichannelSettingsPagedResponse response =
          omnichannelSettingsServiceClient.listOmnichannelSettings(request);

      int count = 0;

      // Iterates over all the entries in the response.
      for (OmnichannelSetting omnichannelSetting : response.iterateAll()) {
        System.out.println(omnichannelSetting);
        count++;
      }
      System.out.println(String.format("The following count of elements were returned: %d", count));
    } catch (Exception e) {
      System.out.println("An error has occured: ");
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();

    omnichannelSettings(config);
  }
}

PHP

use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1\Client\OmnichannelSettingsServiceClient;
use Google\Shopping\Merchant\Accounts\V1\ListOmnichannelSettingsRequest;

/**
 * This class demonstrates how to get the list of omnichannel settings for a
 * given Merchant Center account.
 */
class ListOmnichannelSettings
{
    /**
     * Helper to create the parent string.
     *
     * @param string $accountId The merchant account ID.
     * @return string The parent string in the format `accounts/{account}`.
     */
    private static function getParent(string $accountId): string
    {
        return sprintf('accounts/%s', $accountId);
    }

    /**
     * Lists the omnichannel settings for a given Merchant Center account.
     *
     * @param array $config The configuration file for authentication.
     */
    public static function listOmnichannelSettingsSample(array $config): void
    {
        // Obtains OAuth credentials from the configuration file.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Creates a client.
        $omnichannelSettingsServiceClient = new OmnichannelSettingsServiceClient([
            'credentials' => $credentials
        ]);

        // Constructs the parent resource name.
        $parent = self::getParent($config['accountId']);

        // Creates the request.
        $request = new ListOmnichannelSettingsRequest(['parent' => $parent]);

        // Calls the API and prints the response.
        try {
            printf("Sending list omnichannel setting request:%s", PHP_EOL);
            $response = $omnichannelSettingsServiceClient->listOmnichannelSettings($request);

            $count = 0;
            // Iterates over all the omnichannel settings and prints them.
            foreach ($response->iterateAllElements() as $omnichannelSetting) {
                print $omnichannelSetting->serializeToJsonString(true) . PHP_EOL;
                $count++;
            }
            printf("The following count of elements were returned: %d%s", $count, PHP_EOL);
        } catch (ApiException $e) {
            printf("An error has occured: %s", $e->getMessage());
        }
    }

    /**
     * Executes the sample.
     */
    public function callSample(): void
    {
        $config = Config::generateConfig();
        self::listOmnichannelSettingsSample($config);
    }
}

// Runs the script.
$sample = new ListOmnichannelSettings();
$sample->callSample();

Python

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import ListOmnichannelSettingsRequest
from google.shopping.merchant_accounts_v1 import OmnichannelSettingsServiceClient


def list_omnichannel_settings(account_id: str) -> None:
  """Lists the omnichannel settings for a given Merchant Center account.

  Args:
      account_id: The ID of the Merchant Center account.
  """
  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client.
  client = OmnichannelSettingsServiceClient(credentials=credentials)

  # The parent account for which to list the settings.
  parent = f"accounts/{account_id}"

  # Creates the request.
  request = ListOmnichannelSettingsRequest(parent=parent)

  # Makes the request and catches and prints any error messages.
  try:
    print("Sending list omnichannel setting request:")
    response = client.list_omnichannel_settings(request=request)

    count = 0
    # Iterates over all the entries in the response.
    for omnichannel_setting in response:
      print(omnichannel_setting)
      count += 1
    print(f"The following count of elements were returned: {count}")
  except RuntimeError as e:
    print("An error has occured: ")
    print(e)


if __name__ == "__main__":
  # The ID of the account to get the omnichannel settings for.
  _ACCOUNT = configuration.Configuration().read_merchant_info()

  list_omnichannel_settings(_ACCOUNT)

Обновите настройки многоканальной сети.

Для обновления конфигурации существующей многоканальной настройки используйте метод omnichannelSettings.update .

Для обновления необходимо добавить нужную функцию в маску обновления и заполнить соответствующие поля в поле omnichannelSetting в запросе на обновление. Вы можете обновить любой из следующих компонентов:

  • lsfType
  • inStock
  • pickup
  • odo
  • about
  • inventoryVerification

Если атрибут не включен в маску обновления, он не будет обновлен.

Если атрибут включен в маску обновления, но не задан в запросе, он будет очищен.

Приведенный ниже пример кода демонстрирует, как обновить поле проверки инвентаризации.

Java

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.protobuf.FieldMask;
import com.google.shopping.merchant.accounts.v1.InventoryVerification;
import com.google.shopping.merchant.accounts.v1.OmnichannelSetting;
import com.google.shopping.merchant.accounts.v1.OmnichannelSettingName;
import com.google.shopping.merchant.accounts.v1.OmnichannelSettingsServiceClient;
import com.google.shopping.merchant.accounts.v1.OmnichannelSettingsServiceSettings;
import com.google.shopping.merchant.accounts.v1.UpdateOmnichannelSettingRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/**
 * This class demonstrates how to update an omnichannel setting for a given Merchant Center account
 * in a given country
 */
public class UpdateOmnichannelSettingSample {

  public static void updateOmnichannelSettings(
      Config config, String regionCode, String contact, String email) throws Exception {

    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    // Creates service settings using the credentials retrieved above.
    OmnichannelSettingsServiceSettings omnichannelSettingsServiceSettings =
        OmnichannelSettingsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Calls the API and catches and prints any network failures/errors.
    try (OmnichannelSettingsServiceClient omnichannelSettingsServiceClient =
        OmnichannelSettingsServiceClient.create(omnichannelSettingsServiceSettings)) {
      String accountId = config.getAccountId().toString();
      String name =
          OmnichannelSettingName.newBuilder()
              .setAccount(accountId)
              .setOmnichannelSetting(regionCode)
              .build()
              .toString();

      OmnichannelSetting omnichannelSetting =
          OmnichannelSetting.newBuilder()
              .setName(name)
              .setInventoryVerification(
                  InventoryVerification.newBuilder()
                      .setContact(contact)
                      .setContactEmail(email)
                      .build())
              .build();
      FieldMask fieldMask = FieldMask.newBuilder().addPaths("inventory_verification").build();
      UpdateOmnichannelSettingRequest request =
          UpdateOmnichannelSettingRequest.newBuilder()
              .setOmnichannelSetting(omnichannelSetting)
              .setUpdateMask(fieldMask)
              .build();

      System.out.println("Sending update omnichannel setting request:");
      OmnichannelSetting response =
          omnichannelSettingsServiceClient.updateOmnichannelSetting(request);

      System.out.println("Updated Omnichannel Setting below:");
      System.out.println(response);
    } catch (Exception e) {
      System.out.println("An error has occured: ");
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();

    // The country which you're targeting at.
    String regionCode = "{REGION_CODE}";
    // The name of the inventory verification contact you want to update.
    String contact = "{NAME}";
    // The address of the inventory verification email you want to update.
    String email = "{EMAIL}";

    updateOmnichannelSettings(config, regionCode, contact, email);
  }
}

PHP

use Google\ApiCore\ApiException;
use Google\Protobuf\FieldMask;
use Google\Shopping\Merchant\Accounts\V1\Client\OmnichannelSettingsServiceClient;
use Google\Shopping\Merchant\Accounts\V1\InventoryVerification;
use Google\Shopping\Merchant\Accounts\V1\OmnichannelSetting;
use Google\Shopping\Merchant\Accounts\V1\UpdateOmnichannelSettingRequest;

/**
 * This class demonstrates how to update an omnichannel setting for a given
 * Merchant Center account in a given country.
 */
class UpdateOmnichannelSetting
{
    /**
     * Helper to create the name string.
     *
     * @param string $accountId The merchant account ID.
     * @param string $regionCode The region code of the setting.
     * @return string The name string in the format
     *     `accounts/{account}/omnichannelSettings/{omnichannelSetting}`.
     */
    private static function getName(string $accountId, string $regionCode): string
    {
        return sprintf('accounts/%s/omnichannelSettings/%s', $accountId, $regionCode);
    }

    /**
     * Updates an omnichannel setting for a given Merchant Center account.
     *
     * @param array $config The configuration file for authentication.
     * @param string $regionCode The country of the omnichannel setting.
     * @param string $contact The name of the inventory verification contact.
     * @param string $email The email of the inventory verification contact.
     */
    public static function updateOmnichannelSettingSample(
        array $config,
        string $regionCode,
        string $contact,
        string $email
    ): void {
        // Obtains OAuth credentials from the configuration file.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Creates a client.
        $omnichannelSettingsServiceClient = new OmnichannelSettingsServiceClient([
            'credentials' => $credentials
        ]);

        // Constructs the resource name.
        $name = self::getName($config['accountId'], $regionCode);

        // Creates the omnichannel setting with the updated fields.
        $omnichannelSetting = new OmnichannelSetting([
            'name' => $name,
            'inventory_verification' => new InventoryVerification([
                'contact' => $contact,
                'contact_email' => $email
            ])
        ]);

        // Creates the field mask to specify which fields to update.
        $fieldMask = new FieldMask([
            'paths' => ['inventory_verification']
        ]);

        // Creates the request.
        $request = new UpdateOmnichannelSettingRequest([
            'omnichannel_setting' => $omnichannelSetting,
            'update_mask' => $fieldMask
        ]);

        // Calls the API and prints the response.
        try {
            printf("Sending update omnichannel setting request:%s", PHP_EOL);
            $response = $omnichannelSettingsServiceClient->updateOmnichannelSetting($request);
            printf("Updated Omnichannel Setting below:%s", PHP_EOL);
            print $response->serializeToJsonString(true) . PHP_EOL;
        } catch (ApiException $e) {
            printf("An error has occured: %s", $e->getMessage());
        }
    }

    /**
     * Executes the sample.
     */
    public function callSample(): void
    {
        $config = Config::generateConfig();
        // The country which you're targeting.
        $regionCode = '{REGION_CODE}';
        // The name of the inventory verification contact you want to update.
        $contact = '{NAME}';
        // The address of the inventory verification email you want to update.
        $email = '{EMAIL}';
        self::updateOmnichannelSettingSample($config, $regionCode, $contact, $email);
    }
}

// Runs the script.
$sample = new UpdateOmnichannelSetting();
$sample->callSample();

Python

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.protobuf import field_mask_pb2
from google.shopping.merchant_accounts_v1 import InventoryVerification
from google.shopping.merchant_accounts_v1 import OmnichannelSetting
from google.shopping.merchant_accounts_v1 import OmnichannelSettingsServiceClient
from google.shopping.merchant_accounts_v1 import (
    UpdateOmnichannelSettingRequest,
)


def update_omnichannel_setting(
    account_id: str, region_code: str, contact: str, email: str
) -> None:
  """Updates an omnichannel setting for a given Merchant Center account.

  Args:
      account_id: The ID of the Merchant Center account.
      region_code: The country for which you're updating the setting.
      contact: The name of the inventory verification contact.
      email: The email of the inventory verification contact.
  """
  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client.
  client = OmnichannelSettingsServiceClient(credentials=credentials)

  # The name of the omnichannel setting to update.
  name = f"accounts/{account_id}/omnichannelSettings/{region_code}"

  # Creates an omnichannel setting with the updated values.
  omnichannel_setting = OmnichannelSetting()
  omnichannel_setting.name = name
  omnichannel_setting.inventory_verification = InventoryVerification(
      contact=contact, contact_email=email
  )

  # Creates a field mask to specify which fields to update.
  field_mask = field_mask_pb2.FieldMask(paths=["inventory_verification"])

  # Creates the request.
  request = UpdateOmnichannelSettingRequest(
      omnichannel_setting=omnichannel_setting, update_mask=field_mask
  )

  # Makes the request and catches and prints any error messages.
  try:
    print("Sending update omnichannel setting request:")
    response = client.update_omnichannel_setting(request=request)
    print("Updated Omnichannel Setting below:")
    print(response)
  except RuntimeError as e:
    print("An error has occured: ")
    print(e)


if __name__ == "__main__":
  # The ID of the account to get the omnichannel settings for.
  _ACCOUNT = configuration.Configuration().read_merchant_info()

  # The country which you're targeting.
  _REGION_CODE = "{REGION_CODE}"
  # The name of the inventory verification contact you want to update.
  _CONTACT = "{NAME}"
  # The address of the inventory verification email you want to update.
  _EMAIL = "{EMAIL}"

  update_omnichannel_setting(_ACCOUNT, _REGION_CODE, _CONTACT, _EMAIL)

Запросить проверку наличия товара на складе

omnichannelSettings.requestInventoryVerification актуален только для продавцов GHLSF .

Перед вызовом этого RPC-вызова необходимо выполнить следующие действия:

  • Загрузите данные о вашей продукции и складских запасах.
  • Подтвердите контакт для проверки инвентаризации.
  • Для продавцов из Австрии, Германии или Швейцарии необходимо заполнить отзыв на странице About .

Чтобы определить, соответствуете ли вы требованиям, вызовите метод omnichannelSettings.get и проверьте значение omnichannelSetting.inventoryVerification.state . Если оно показывает INACTIVE , вы можете вызвать omnichannelSettings.requestInventoryVerification .

Java

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.OmnichannelSettingName;
import com.google.shopping.merchant.accounts.v1.OmnichannelSettingsServiceClient;
import com.google.shopping.merchant.accounts.v1.OmnichannelSettingsServiceSettings;
import com.google.shopping.merchant.accounts.v1.RequestInventoryVerificationRequest;
import com.google.shopping.merchant.accounts.v1.RequestInventoryVerificationResponse;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/**
 * This class demonstrates how to request inventory verification for a given Merchant Center account
 * in a given country
 */
public class RequestInventoryVerificationSample {

  public static void requestInventoryVerification(Config config, String regionCode)
      throws Exception {

    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    // Creates service settings using the credentials retrieved above.
    OmnichannelSettingsServiceSettings omnichannelSettingsServiceSettings =
        OmnichannelSettingsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Calls the API and catches and prints any network failures/errors.
    try (OmnichannelSettingsServiceClient omnichannelSettingsServiceClient =
        OmnichannelSettingsServiceClient.create(omnichannelSettingsServiceSettings)) {
      String accountId = config.getAccountId().toString();
      String name =
          OmnichannelSettingName.newBuilder()
              .setAccount(accountId)
              .setOmnichannelSetting(regionCode)
              .build()
              .toString();
      RequestInventoryVerificationRequest request =
          RequestInventoryVerificationRequest.newBuilder().setName(name).build();

      System.out.println("Sending request inventory verification request:");
      RequestInventoryVerificationResponse response =
          omnichannelSettingsServiceClient.requestInventoryVerification(request);

      System.out.println("Omnichannel Setting after inventory verification request below:");
      System.out.println(response);
    } catch (Exception e) {
      System.out.println("An error has occured: ");
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();

    // The country which you're targeting at.
    String regionCode = "{REGION_CODE}";

    requestInventoryVerification(config, regionCode);
  }
}

Просмотрите статус настройки многоканального взаимодействия.

Чтобы проверить статус проверки отзывов о процессе адаптации в LIA, проверьте ReviewState для соответствующих атрибутов omnichannelSetting , возвращаемых методами omnichannelSettings.get или omnichannelSettings.list .

Поле ReviewState применяется ко всем проверкам при приеме на работу, за исключением процесса инвентаризации, и может принимать следующие значения:

  • ACTIVE : Одобрено.
  • FAILED : Заявка отклонена.
  • RUNNING : Вопрос все еще находится на рассмотрении.
  • ACTION_REQUIRED : Эта опция существует только в InStock.state для продавцов GHLSF. Она означает, что вам необходимо запросить проверку наличия товара, чтобы LIA могла выполнить заказ.

InventoryVerification.State имеет следующие значения:

  • SUCCEEDED : Заявка одобрена.
  • INACTIVE : Вы готовы запросить проверку инвентаризации.
  • RUNNING : Находится на рассмотрении.
  • SUSPENDED : Вы слишком много раз (обычно 5 раз) не прошли проверку инвентаря и должны подождать, прежде чем сможете запросить ее снова.
  • ACTION_REQUIRED : Перед запросом на проверку инвентаризации необходимо выполнить дополнительные действия.

Устранение неполадок, связанных с Omnichannel Settings API

В этом разделе описывается, как устранять распространенные неполадки.

Создайте многоканальную настройку.

  • Обязательно укажите значения LsfType и RegionCode .
  • Если вы выберете GHLSF , укажите в запросе пустое InStock "В наличии".
  • Если вы выбираете типы LSF, размещаемые продавцом, укажите как минимум один URI в InStock или Pickup .

Обновите настройки многоканальной сети.

Для обновления данного ресурса требуются следующие дополнительные правила:

  • Изменить код региона невозможно.
  • Вносить обновления невозможно, пока функция LIA/FLL работает или была одобрена.
  • При переходе с типов LSF, размещаемых продавцом, на GHLSF , если ранее были настроены InStock и Pickup , необходимо включить их в маску обновления вместе с обновлением LsfType .

Например, если вы ранее применяли MHLSF_BASIC и Pickup , и они были отклонены, вы можете переключиться на GHLSF , отправив запрос следующего вида:

PATCH https://merchantapi.googleapis.com/accounts/v1/accounts/{ACCOUNT_ID}/omnichannelSettings/{REGION_CODE}?update_mask=lsf_type,in_stock,pickup

{
  "lsfType": "GHLSF",
  "inStock": {},
}

Замените следующее:

  • {ACCOUNT_ID} : Уникальный идентификатор вашей учетной записи в Merchant Center.
  • {REGION_CODE} : Код региона, определенный в CLDR.

Запросить проверку наличия товара на складе

Если, несмотря на обновление данных о товарах или складских запасах и подтверждение контакта, значение InventoryVerification.state отличается от INACTIVE :

  • Для продавцов из Австрии, Германии и Швейцарии: убедитесь, что вы завершили проверку страницы «О нас».
  • Возможна задержка примерно на 48 часов.
  • В случае повторных сбоев проверки инвентаризации (более пяти) сервис устанавливает тридцатидневный период ожидания, прежде чем разрешить повторный запрос. Для более раннего запроса обратитесь в службу поддержки Google.

Узнать больше

Для получения более подробной информации см. раздел «Объявления о наличии товаров на местном рынке и бесплатные местные объявления» в Справочном центре .