A API Omnichannel Settings é o ponto de entrada para configurar os programas de anúncios de inventário local (LIA, na sigla em inglês) e listagens locais sem custo financeiro (FLL, na sigla em inglês).
Use-a para programar
- Gerenciar (criar e atualizar) as configurações omnichannel
- Buscar (receber e listar) as configurações omnichannel
- Pedir a verificação de inventário para comerciantes qualificados
Para mais informações, consulte Visão geral dos anúncios de inventário local e das listagens locais sem custo financeiro.
Pré-requisitos
Você precisa ter
uma conta do Merchant Center
um Perfil da Empresa. Se você não tiver um, crie um. Consulte Inscrever-se em um Perfil da Empresa.
Um link entre o Perfil da Empresa e a conta do Merchant Center. Para criar o link, use a interface do usuário do Merchant Center ou a API Merchant (consulte Vincular um Perfil da Empresa no Google).
Criar uma configuração omnichannel
Use o método omnichannelSettings.create para criar uma configuração omnichannel. O método "create" usa um recurso omnichannelSetting como entrada e retorna a configuração omnichannel criada, se for bem-sucedida.
Ao criar, preencha regionCode e
LsfType:
- A configuração omnichannel é feita por país.
RegionCodedefine o país segmentado. Depois de criado, não é possível mudar.RegionCodedeve seguir a regra de nomenclatura definida pelo Common Locale Data Repository (CLDR) projeto. LsfTypeé baseado na página do produto. Para mais detalhes, consulteLsfType.
Para mais detalhes, consulte Mudar a experiência na página do produto para seus anúncios de inventário local.
Não é necessário preencher todos os campos na fase de criação, mas é possível configurá-los mais tarde. Para atualizar um omnichannelSetting, consulte
Atualizar uma configuração omnichannel.
Confira um exemplo de solicitação se você escolher MHLSF_BASIC e inscrever inStock:
POST https://merchantapi.googleapis.com/accounts/v1/accounts/{ACCOUNT_ID}/omnichannelSettings
{
"regionCode": "{REGION_CODE}",
"lsfType: "MHLSF_BASIC",
"inStock": {
"uri": {URI}"
}
}
Substitua:
{ACCOUNT_ID}: o identificador exclusivo da sua conta do Merchant Center{REGION_CODE}: um código de região conforme definido pelo CLDR{URI}: um URI válido usado para a revisão. Um URI inelegível pode impedir a aprovação.
Depois que a solicitação for executada, você vai receber a seguinte resposta:
{
"name": "accounts/{ACCOUNT_ID}/omnichannelSettings/{omnichannel_setting}",
"regionCode": "{REGION_CODE}",
"lsfType: "MHLSF_BASIC",
"inStock": {
"uri": "{URI}",
"state": "RUNNING"
}
}
A inscrição em diferentes recursos de LIA/FLL usando campos omnichannelSetting aciona análises manuais que geralmente levam de algumas horas a alguns dias. Recomendamos verificar suas entradas para evitar tempo de espera desnecessário devido a dados inelegíveis.
Para conferir a configuração omnichannel recém-criada ou verificar o estado das análises, use accounts.omnichannelSettings.get ou accounts.omnichannelSettings.list, especificando o país.
Tipo de vitrine local (LSF, na sigla em inglês)
Com base na página do produto que você planeja usar, escolha um LsfType:
| Tipo de página do produto | LsfType | Valor de tipo enumerado |
|---|---|---|
| Páginas de produtos com disponibilidade na loja | Vitrine local hospedada pelo comerciante (versão básica) | MHLSF_BASIC |
| Páginas de produtos específicas da loja com disponibilidade e preço | Vitrine local hospedada pelo comerciante (versão completa) | MHLSF_FULL |
| Páginas de produtos sem disponibilidade na loja | Vitrine local hospedada pelo Google (GHLSF, na sigla em inglês) | GHLSF |
Se você escolher os tipos de vitrine local hospedada pelo comerciante, também precisará preencher o campo URI para pelo menos um de inStock ou pickup.
InStock
Você pode usar "InStock" para fornecer mais informações sobre a página do produto.
Se você escolher os tipos de LSF hospedados pelo comerciante e especificar o campo URI em "InStock", estará mostrando sua intenção de veicular produtos com disponibilidade em estoque. Vamos iniciar uma análise com base no URI fornecido.
Se você escolher o tipo GHLSF, precisará fornecer um campo InStock vazio na solicitação. Ao contrário dos tipos de LSF hospedados pelo comerciante, para concluir a integração, você precisa
concluir o processo de verificação de inventário.
Este exemplo de código cria um omnichannelSetting com 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)
Retirada
Além da disponibilidade na loja, você também pode aprimorar seus produtos com o recurso de retirada, que só está disponível para tipos de LSF hospedados pelo comerciante.
Quando um produto é marcado para retirada, significa que um cliente pode comprá-lo on-line e retirá-lo na loja. Ao definir o campo Pickup, você está mostrando sua intenção de veicular produtos com uma opção de retirada. Vamos iniciar uma análise com base no URI fornecido.
Confira um exemplo de solicitação que cria uma configuração omnichannel com Pickup:
POST https://merchantapi.googleapis.com/accounts/v1/accounts/{ACCOUNT_ID}/omnichannelSettings
{
"regionCode": "{REGION_CODE}",
"lsfType: "MHLSF_BASIC",
"pickup": {
"uri: "{URI}"
}
}
Em mostruário sem pronta entrega
Com o Em mostruário sem pronta entrega recurso, você pode mostrar os produtos que são exibidos na loja física, mas não estão disponíveis para compra imediata. Por exemplo, móveis grandes:
- Esses anúncios vão aparecer com a nota "na loja" nos resultados da pesquisa para os clientes que procurarem produtos semelhantes no Google.
- Quem estiver procurando a loja em uma página de resultados da pesquisa do Google vai ver esses produtos marcados como "Disponível para encomenda".
As pessoas podem escolher seu anúncio de inventário local ou listagem local sem custo financeiro para conferir o item. Para comprar, elas podem visitar a loja física, ver o item e fazer a encomenda para ser entregue em determinado endereço ou retirada na loja.
Sobre (Alemanha, Áustria e Suíça)
Se você estiver veiculando anúncios na Áustria e na Alemanha e escolher GHLSF, envie uma
página "Sobre".
Se você estiver veiculando anúncios na Suíça, envie uma página "Sobre", independentemente de LsfType.
Até que o URL da página "Sobre" seja verificado, os comerciantes de GHLSF não poderão pedir a verificação de inventário manual do Google.
Para todos os comerciantes desses três países, o serviço não ativa os recursos de FLL/LIA até que a página "Sobre" seja aprovada.
Verificação de inventário
A verificação de inventário só é necessária para comerciantes de GHLSF. Ela não é compatível com os tipos MHLSF.
Antes ou depois de adicionar dados de produtos e de inventário (usando accounts.products.localInventories.insert ou a interface do usuário do Merchant Center), você precisa verificar seu contato. Forneça um contato de verificação de inventário (nome e endereço de e-mail) usando o método create ou update. O contato vai receber um e-mail enviado pelo Google e a capacidade de verificar o status clicando em um botão na mensagem.
Depois de concluir esse processo, você pode pedir a verificação de inventário. Para mais informações, consulte Sobre a verificação de inventário.
Você pode mudar seu contato durante o processo de verificação ou depois da verificação usando omnichannelSetting.update.
Após a conclusão desse processo, o Google valida a precisão das informações fornecidas.
Receber uma configuração omnichannel
Para recuperar a configuração omnichannelSetting em um determinado país ou verificar
o status atual das suas análises, use o método omnichannelSettings.get.
Veja um exemplo de solicitação:
GET https://merchantapi.googleapis.com/accounts/v1/accounts/{ACCOUNT_ID}/omnichannelSettings/{OMNICHANNEL_SETTING}
Substitua:
{ACCOUNT_ID}: o identificador exclusivo da sua conta do Merchant Center{OMNICHANNEL_SETTING}: o código de região do país segmentado
O status ACTIVE indica que a análise foi aprovada.
Se o status for FAILED, resolva os problemas e acione uma nova análise chamando omnichannelSetting.update.
O campo somente leitura LFP mostra o status da sua parceria de feeds locais. Para vincular à parceria, use lfpProviders.linkLfpProvider.
Para mais informações sobre como verificar os status e os significados deles, consulte Conferir o status de uma configuração omnichannel.
Listar configurações omnichannel
Para recuperar todas as informações de omnichannelSetting da sua conta, use o
omnichannelSettings.list método.
Confira um exemplo 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)
Atualizar uma configuração omnichannel
Para atualizar a configuração de uma configuração omnichannel, use o método omnichannelSettings.update.
Para atualizar, adicione o recurso desejado à máscara de atualização e preencha os campos correspondentes no campo omnichannelSetting na solicitação de atualização.
Você pode atualizar qualquer um dos seguintes itens:
lsfTypeinStockpickupodoaboutinventoryVerification
Se um atributo não estiver incluído na máscara de atualização, ele não será atualizado.
Se um atributo estiver incluído na máscara de atualização, mas não estiver definido na solicitação, ele será limpo.
O exemplo de código a seguir demonstra como atualizar o campo de verificação de inventário.
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)
Pedir a verificação de inventário
omnichannelSettings.requestInventoryVerification só é relevante para comerciantes de GHLSF.
Antes de chamar esse RPC, você precisa ter feito o seguinte:
- Fazer upload dos dados de produtos e de inventário.
- Verificar um contato de verificação de inventário.
- Para comerciantes na Áustria, Alemanha ou Suíça, concluir uma
Aboutanálise da página.
Para determinar sua qualificação, chame omnichannelSettings.get e verifique omnichannelSetting.inventoryVerification.state. Se ele mostrar INACTIVE, você poderá chamar 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);
}
}
Conferir o status de uma configuração omnichannel.
Para verificar o status de análise das análises de integração de LIA, confira ReviewState
para os atributos correspondentes de omnichannelSetting retornados pelos
omnichannelSettings.get ou omnichannelSettings.list métodos.
O campo ReviewState se aplica a todas as análises de integração, exceto o processo de verificação de inventário, e pode ter os seguintes valores:
ACTIVE: foi aprovado.FAILED: foi rejeitado.RUNNING: ainda está em revisão.ACTION_REQUIRED: só existe noInStock.statepara comerciantes de GHLSF. Isso significa que você precisa pedir a verificação de inventário para que o LIA seja veiculado.
InventoryVerification.State tem os seguintes valores:
SUCCEEDED: foi aprovado.INACTIVE: você está pronto para pedir a verificação de inventário.RUNNING: está em revisãoSUSPENDED: você falhou na verificação de inventário muitas vezes (geralmente 5) e precisa esperar antes de poder pedir novamente.ACTION_REQUIRED: você precisa realizar outras ações antes de pedir a verificação de inventário.
Resolver problemas relacionados à Omnichannel Settings API
Esta seção descreve como resolver problemas comuns.
Criar uma configuração omnichannel
- Defina
LsfTypeeRegionCode. - Se você escolher
GHLSF, forneça umInStockvazio na solicitação. - Se você escolher os tipos de LSF hospedados pelo comerciante, forneça pelo menos um URI em
InStockouPickup.
Atualizar uma configuração omnichannel
O método de atualização desse recurso exige as seguintes regras adicionais:
- Não é possível modificar o código da região.
- Não é possível fazer atualizações enquanto o recurso LIA/FLL estiver em execução ou tiver sido aprovado.
- Ao mudar de tipos de LSF hospedados pelo comerciante para
GHLSF, seInStockePickupforam configurados anteriormente, você precisa incluí-los na máscara de atualização junto com a atualizaçãoLsfType.
Por exemplo, se você aplicou MHLSF_BASIC e Pickup antes e eles foram rejeitados, é possível mudar para GHLSF enviando uma solicitação 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": {},
}
Substitua:
{ACCOUNT_ID}: o identificador exclusivo da sua conta do Merchant Center{REGION_CODE}: um código de região conforme definido pelo CLDR
Pedir a verificação de inventário
Se, apesar de atualizar os feeds de produtos ou inventário e confirmar o contato, InventoryVerification.state for diferente de INACTIVE:
- Para comerciantes na Áustria, Alemanha e Suíça: confira se você concluiu uma análise da página "Sobre".
- Haverá um atraso de cerca de 48 horas.
- Em caso de falhas repetidas na verificação de inventário (mais de cinco), o serviço impõe um período de espera de 30 dias antes de permitir outra solicitação. Entre em contato com o suporte do Google se quiser pedir antes.
Saiba mais
Para mais detalhes, consulte a Central de Ajuda dos anúncios de inventário local e das listagens locais sem custo financeiro.