Administra la configuración de Omnichannel

La API de Omnichannel Settings es el punto de entrada para configurar tus programas de anuncios del inventario local (LIA) y fichas locales gratuitas (FLL).

Úsala para realizar las siguientes acciones de manera programática:

  • Administrar (crear y actualizar) la configuración de Omnichannel
  • Recuperar (obtener y enumerar) la configuración de Omnichannel
  • Solicita la verificación del inventario para los comercios aptos

Para obtener más información, consulta la descripción general de los anuncios del inventario local y las fichas locales gratuitas.

Requisitos previos

Deberías tener

Crea un parámetro de configuración de varios canales

Puedes usar el método omnichannelSettings.create para crear un parámetro de configuración multicanal. El método create toma un recurso omnichannelSetting como entrada y devuelve el parámetro de configuración de varios canales creado, si se ejecuta correctamente.

Cuando crees, debes completar tanto el regionCode como el LsfType:

  • OmnichannelSetting se aplica por país. RegionCode define el país de segmentación. Una vez que lo crees, no podrás cambiarlo. RegionCode debe seguir la regla de nombres definida por el proyecto Repositorio de datos de configuración regional común (CLDR).
  • LsfType se basa en la página de tu producto. Para obtener detalles, consulta LsfType.

Para obtener más detalles, consulta Cómo cambiar la experiencia de página del producto para tus anuncios del inventario local.

No es necesario que completes todos los campos en la etapa de creación, sino que puedes configurarlos más adelante. Para actualizar un omnichannelSetting existente, consulta Actualiza un parámetro de configuración de varios canales.

A continuación, se muestra una solicitud de ejemplo si eliges MHLSF_BASIC y te inscribes en inStock:

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

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

Reemplaza lo siguiente:

  • {ACCOUNT_ID}: Es el identificador único de tu cuenta de Merchant Center.
  • {REGION_CODE}: Es un código de región según lo define el CLDR.
  • {URI}: Es un URI válido que se usa para la opinión determinada. Un URI no apto puede impedir la aprobación.

Después de que la solicitud se ejecute correctamente, deberías ver la siguiente respuesta:

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

Inscribir diferentes funciones de LIA o FLL con los campos omnichannelSetting activa revisiones manuales que suelen tardar entre un par de horas y un par de días. Te recomendamos que verifiques tus entradas para evitar tiempos de espera innecesarios debido a datos no aptos.

Para ver el parámetro de configuración de varios canales que acabas de crear o verificar el estado de las revisiones, usa accounts.omnichannelSettings.get o accounts.omnichannelSettings.list, y especifica el país.

Tipo de vidriera local (LSF)

Según la página del producto que planees usar, elige un LsfType:

Tipo de página del producto LsfType Valor enumerado
Páginas de productos con información de disponibilidad en tienda Vidriera local alojada por el comercio (básica) MHLSF_BASIC
Páginas de productos específicas de la tienda con disponibilidad y precio Vidriera local alojada por el comercio (completa) MHLSF_FULL
Páginas de productos sin disponibilidad en tienda Vidriera local alojada en Google (GHLSF) GHLSF

Si eliges los tipos de vidriera local alojada por el comerciante, también debes completar el campo de URI para, al menos, uno de los atributos inStock o pickup.

InStock

Puedes usar InStock para proporcionar más información sobre la página de tu producto.

Si eliges los tipos de LSF alojada por el comercio y especificas el campo URI en InStock, indicas que quieres publicar productos con disponibilidad en stock. Iniciaremos una revisión en función del URI proporcionado.

Si eliges el tipo GHLSF, debes proporcionar un campo InStock vacío en la solicitud. A diferencia de los tipos de LSF alojados por el comercio, para completar la incorporación, debes completar el proceso de verificación del inventario.

En esta muestra de código, se crea un omnichannelSetting con 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)

Retiro

Además de la disponibilidad en tienda, también puedes mejorar tus productos en tienda con la función de retiro, que solo es apta para los tipos de LSF alojada por el comercio.

Cuando un producto se marca para retiro, significa que un cliente puede comprarlo en línea y retirarlo en la tienda. Cuando configuras el campo Pickup, indicas tu intención de publicar productos con un ANS de retiro. Iniciaremos una revisión en función del URI proporcionado.

A continuación, se muestra una solicitud de ejemplo que crea un parámetro de configuración de omnichannel con Pickup:

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

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

En exhibición para pedido

Con la función en exhibición para pedido, puedes mostrar productos que se exhiben en tu tienda física, pero que no están disponibles para comprarse de inmediato. Por ejemplo, muebles grandes:

  • Los clientes que busquen productos similares en Google verán estos anuncios con la anotación "en la tienda" en los resultados de la búsqueda.
  • Los clientes que exploren la tienda en una página de resultados de la Búsqueda de Google verán estos productos marcados como "disponibles para pedidos".

Los usuarios pueden elegir tu anuncio del inventario local o tu ficha local gratuita para ver el artículo. Si desean comprar el artículo, pueden visitar tu tienda física, verlo y hacer un pedido con envío a domicilio o retiro en tienda.

Acerca de (Alemania, Austria y Suiza)

Si publicas anuncios en Austria y Alemania, y eliges GHLSF, debes enviar una página Acerca de.

Si publicas anuncios en Suiza, debes enviar una página "Acerca de" independientemente de LsfType.

Hasta que se verifique la URL de la página Acerca de, los comercios de GHLSF no podrán solicitar la verificación manual del inventario a Google.

Para todos los comercios de estos tres países, el servicio no habilita las funciones de FLL o LIA hasta que se apruebe tu página Acerca de.

Verificación del inventario

La verificación del inventario solo es obligatoria para los comercios de GHLSF. No se admite para los tipos MHLSF.

Antes o después de agregar los datos de productos y del inventario (ya sea con accounts.products.localInventories.insert o la interfaz de usuario de Merchant Center), debes verificar tu contacto. Proporciona un contacto de verificación del inventario (nombre y dirección de correo electrónico) con el método create o update. El contacto recibirá un correo electrónico enviado por Google y podrá verificar su estado haciendo clic en un botón del mensaje.

Una vez que lo hayas hecho, podrás solicitar la verificación del inventario. Para obtener más información, consulta Acerca de la verificación del inventario.

Puedes cambiar tu contacto durante el proceso de verificación o después de la verificación con omnichannelSetting.update.

Una vez que se completa este proceso, Google valida la exactitud de la información proporcionada.

Obtén un parámetro de configuración de varios canales

Para recuperar la configuración de omnichannelSetting en un país determinado o verificar el estado actual de tus revisiones, usa el método omnichannelSettings.get.

A continuación, se muestra una solicitud de ejemplo:

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

Reemplaza lo siguiente:

  • {ACCOUNT_ID}: Es el identificador único de tu cuenta de Merchant Center.
  • {OMNICHANNEL_SETTING}: Es el código de región de tu país de segmentación.

El estado ACTIVE indica que se aprobó la revisión.

Si el estado es FAILED, soluciona los problemas y activa una revisión nueva llamando a omnichannelSetting.update.

El campo de solo lectura LFP muestra el estado de Socio de feeds locales. Para vincular a la asociación, usa lfpProviders.linkLfpProvider.

Para obtener más información sobre cómo verificar los estados y sus significados, consulta Cómo ver el estado de un parámetro de configuración de varios canales.

Enumera la configuración de varios canales

Para recuperar toda la información de omnichannelSetting de tu cuenta, usa el método omnichannelSettings.list.

A continuación, se incluye una muestra de código:

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)

Actualiza un parámetro de configuración de varios canales

Para actualizar la configuración de un parámetro de configuración de varios canales existente, usa el método omnichannelSettings.update.

Para actualizar, debes agregar el atributo que deseas a la máscara de actualización y completar los campos correspondientes en el campo omnichannelSetting de la solicitud de actualización. Puedes actualizar cualquiera de las siguientes opciones:

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

Si un atributo no se incluye en la máscara de actualización, no se actualizará.

Si se incluye un atributo en la máscara de actualización, pero no se establece en la solicitud, se borrará.

En la siguiente muestra de código, se indica cómo actualizar el campo de verificación del inventario.

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)

Cómo solicitar la verificación del inventario

omnichannelSettings.requestInventoryVerification solo es pertinente para los comercios de GHLSF.

Antes de llamar a esta RPC, debes haber realizado lo siguiente:

  • Sube tus datos de productos y de inventario.
  • Confirma un contacto de verificación del inventario.
  • En el caso de los comercios de Alemania, Austria o Suiza, completa una revisión de la página About.

Para determinar si cumples con los requisitos, llama a omnichannelSettings.get y consulta omnichannelSetting.inventoryVerification.state. Si se muestra INACTIVE, todo está listo para llamar a 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);
  }
}

Consulta el estado de un parámetro de configuración de varios canales.

Para verificar el estado de las revisiones de incorporación de LIA, consulta ReviewState para conocer los atributos correspondientes de omnichannelSetting que devuelven los métodos omnichannelSettings.get o omnichannelSettings.list.

El campo ReviewState se aplica a todas las revisiones de incorporación, excepto al proceso de verificación del inventario, y puede tener los siguientes valores:

  • ACTIVE: Se aprueba.
  • FAILED: Se rechaza.
  • RUNNING: Todavía está en proceso de revisión.
  • ACTION_REQUIRED: Solo existe en InStock.state para los comercios de GHLSF. Significa que debes solicitar la verificación del inventario para que se publiquen los LIA.

InventoryVerification.State tiene los siguientes valores:

  • SUCCEEDED: Se aprueba.
  • INACTIVE: Todo listo para solicitar la verificación del inventario.
  • RUNNING: Está en proceso de revisión
  • SUSPENDED: No se pudo realizar la verificación del inventario demasiadas veces (por lo general, 5) y debes esperar antes de poder volver a solicitarla.
  • ACTION_REQUIRED: Debes tomar medidas adicionales antes de solicitar la verificación del inventario.

Soluciona problemas relacionados con Omnichannel Settings API

En esta sección, se describe cómo solucionar problemas habituales.

Crea un parámetro de configuración de varios canales

  • Asegúrate de configurar LsfType y RegionCode.
  • Si eliges GHLSF, proporciona un InStock vacío en la solicitud.
  • Si eliges los tipos de LSF alojados por el comercio, proporciona al menos un URI en InStock o Pickup.

Actualiza un parámetro de configuración de varios canales

El método de actualización de este recurso requiere las siguientes reglas adicionales:

  • No puedes modificar el código de región.
  • No puedes realizar actualizaciones mientras la función de LIA o FLL se esté ejecutando o se haya aprobado.
  • Cuando cambies de los tipos de LSF alojados por el comercio a GHLSF, si InStock y Pickup se configuraron anteriormente, debes incluirlos en la máscara de actualización junto con la actualización de LsfType.

Por ejemplo, si antes aplicaste MHLSF_BASIC y Pickup, y se rechazaron, puedes cambiar a GHLSF enviando una solicitud como esta:

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

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

Reemplaza lo siguiente:

  • {ACCOUNT_ID}: Es el identificador único de tu cuenta de Merchant Center.
  • {REGION_CODE}: Es un código de región según lo define CLDR.

Cómo solicitar la verificación del inventario

Si, a pesar de actualizar los feeds de productos o los feeds de inventario y confirmar el contacto, InventoryVerification.state es distinto de INACTIVE, haz lo siguiente:

  • Para los comercios de Alemania, Austria y Suiza: Asegúrate de haber completado la revisión de la página Acerca de.
  • Habrá una demora de aproximadamente 48 horas.
  • En caso de que se produzcan fallas repetidas en la verificación de inventario (más de cinco), el servicio aplica un período de inactividad de treinta días antes de permitir otra solicitud. Comunícate con el equipo de Atención al Cliente de Google si quieres solicitarlo antes.

Más información

Para obtener más detalles, consulta el Centro de ayuda de anuncios del inventario local y fichas locales gratuitas.