Как управлять настройками многоканальности

Omnichannel Settings API – это точка входа для настройки программ рекламы местного ассортимента и бесплатных местных предложений.

Используйте его, чтобы программно:

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

Подробнее о рекламе местного ассортимента и бесплатных местных предложениях…

Требования

У вас должно быть

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

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

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

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

Подробнее о том, как изменить удобство страницы товара для рекламы местного ассортимента…

На этапе создания заполнять все поля не обязательно, их можно настроить позже. Чтобы изменить существующий параметр 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"
  }
}

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

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

Тип витрины местного магазина

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

Тип страницы товара LsfType Перечисляемое значение
Страницы товаров с данными о наличии в магазинах Витрина магазина у продавца (базовая реализация) MHLSF_BASIC
Страницы товаров с данными о наличии и цене в определенном магазине Витрина магазина у продавца (полнофункциональная реализация) MHLSF_FULL
Страницы товаров без данных о наличии в магазинах Витрина магазина в Google GHLSF

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

InStock

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

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

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

В этом примере кода создается 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)

Самовывоз

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

Если товар отмечен как доступный для самовывоза, значит покупатель может приобрести его онлайн и забрать в магазине. Указав значение в поле 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 проверку ассортимента вручную.

Для всех продавцов из этих трех стран сервис не включает функции рекламы местного ассортимента и бесплатных предложений поблизости, пока страница "О компании" не будет одобрена.

Проверка ассортимента

Проверка ассортимента требуется только для продавцов с 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);
  }
}

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

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

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

  • ACTIVE – одобрено.
  • FAILED: отклонено.
  • RUNNING: ещё на рассмотрении.
  • ACTION_REQUIRED: этот атрибут существует только в InStock.state для продавцов, которые используют GHLSF. Это означает, что вам нужно запросить проверку ассортимента, чтобы показывать рекламу местного ассортимента.

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

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

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

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

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

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

Как изменить многоканальные настройки

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

  • Изменить код региона нельзя.
  • Нельзя вносить изменения, пока функция "Реклама местного ассортимента" или "Бесплатная доставка в магазин" включена или одобрена.
  • При переходе с типов 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 часов.
  • Если проверка ассортимента не пройдена более пяти раз, сервис вводит 30-дневный период ожидания, после которого можно отправить новый запрос. Если вы хотите запросить его раньше, обратитесь в службу поддержки Google.

Подробнее…

Подробнее о рекламе местного ассортимента и бесплатных местных предложениях рассказывается в Справочном центре.