Добавьте региональную информацию к онлайн-продуктам

Вы можете использовать API Merchant Inventories, чтобы указать, что информация о вашем продукте зависит от региона. Например, вы можете продавать разные продукты в разных местах или устанавливать разные цены на одни и те же продукты в зависимости от того, где они куплены.

Дополнительную информацию см. в разделе «Доступность и цены в регионах» .

Региональная информация предназначена для продуктов, которые вы продаете через Интернет. Подробную информацию о товарах в магазине см. в разделе Добавление информации о магазине к местным продуктам.

Вот шаги для добавления региональной информации в ваши онлайн-продукты:

Создание регионов

Прежде чем вы сможете добавить региональную информацию к товару, вам необходимо настроить регионы для своей учетной записи продавца. Вы можете использовать ресурс Content API for Shopping для создания новых regions .

Пример кода и дополнительную информацию об управлении регионами см. в руководстве по регионам.

Убедитесь, что у вас есть онлайн-продукты

Вы можете использовать Content API for Shopping, чтобы фильтровать продукты под вашей учетной записью по channel и проверять наличие существующих онлайн-продуктов. Интернет-продукты должны иметь online ценность для своего channel .

Если вам нужно добавить онлайн-продукты в свою учетную запись, используйте Content API for Shopping, чтобы вставить новые продукты , или создайте фид .

Вставьте региональную информацию

После того как в вашем аккаунте продавца появятся онлайн-продукты, вы можете добавить региональную информацию, такую ​​как region , price и availability .

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

Джава

  public static void insertRegionalInventory(Config config, String productId, String regionId)
      throws Exception {
    GoogleCredentials credential = new Authenticator().authenticate();

    RegionalInventoryServiceSettings regionalInventoryServiceSettings =
        RegionalInventoryServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    String parent = getParent(config.getMerchantId().toString(), productId);

    try (RegionalInventoryServiceClient regionalInventoryServiceClient =
        RegionalInventoryServiceClient.create(regionalInventoryServiceSettings)) {

      Price price = Price.newBuilder().setAmountMicros(33_450_000).setCurrencyCode("USD").build();

      InsertRegionalInventoryRequest request =
          InsertRegionalInventoryRequest.newBuilder()
              .setParent(parent)
              .setRegionalInventory(
                  RegionalInventory.newBuilder()
                      .setAvailability("out of stock")
                      .setRegion(regionId)
                      .setPrice(price)
                      .build())
              .build();

      System.out.println("Sending insert RegionalInventory request");
      RegionalInventory response = regionalInventoryServiceClient.insertRegionalInventory(request);
      System.out.println("Inserted RegionalInventory Name below");
      System.out.println(response.getName());
    } catch (Exception e) {
      System.out.println(e);
    }
  }

КУЛЬ

  curl --location
  'https://merchantapi.googleapis.com/inventories/v1beta/accounts/987654321/products/en~US~12345/regionalInventories:insert' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: Bearer <API_TOKEN>' \
  --data '{
     "region": "123456",
     "price": {
         "amountMicros": "33450000",
         "currencyCode": "USD"
     },
     "availability": "out of stock"
  }'

PHP

class InsertRegionalInventory
{
    // ENSURE you fill in the merchant account and product ID for the sample to
    // work.
    private const PARENT = 'accounts/[INSERT_ACCOUNT_HERE]/products/[INSERT_PRODUCT_HERE]';
    // ENSURE you fill in region ID for the sample to work.
    private const REGIONAL_INVENTORY_REGION = 'INSERT_REGION_HERE';

    /**
     * Inserts a regional inventory underneath the parent product.
     *
     * @param string $parent The account and product where this inventory will be inserted.
     *     Format: `accounts/{account}/products/{product}`
     * @param string $regionalInventoryRegion
     *     ID of the region for this
     *     `RegionalInventory` resource. See the [Regional availability and
     *     pricing](https://support.google.com/merchants/answer/9698880) for more details.
     */
    public function insertRegionalInventorySample(string $parent, string $regionalInventoryRegion): void
    {
        // Gets the OAuth credentials to make the request.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Creates options config containing credentials for the client to use.
        $options = ['credentials' => $credentials];

        // Creates a client.
        $regionalInventoryServiceClient = new RegionalInventoryServiceClient($options);

        // Creates a price object.
        $price = new Price(
            [
                'currency_code' => "USD",
                'amount_micros' => 33450000,
            ]
        );

        // Creates a new regional inventory object.
        $regionalInventory = (new RegionalInventory())
            ->setRegion($regionalInventoryRegion)
            ->setAvailability("in stock")
            ->setPrice($price);

        // Calls the API and catches and prints any network failures/errors.
        try {
            /** @var RegionalInventory $response */
            $response = $regionalInventoryServiceClient->insertRegionalInventory(
                $parent,
                $regionalInventory
            );
            printf('Response data: %s%s', $response->serializeToJsonString(), PHP_EOL);
        } catch (ApiException $ex) {
            printf('Call failed with message: %s%s', $ex->getMessage(), PHP_EOL);
        }
    }

    /**
     * Helper to execute the sample.
     */
    public function callSample(): void
    {
        // Makes the call to insert the regional inventory to the parent product
        // for the given region.
        $this->insertRegionalInventorySample($this::PARENT, $this::REGIONAL_INVENTORY_REGION);
    }

}

Питон

from examples.authentication import generate_user_credentials
from google.shopping import merchant_inventories_v1beta

# ENSURE you fill in the merchant account and product ID for the sample to
# work.
_ACCOUNT = "INSERT_ACCOUNT_HERE"
_PRODUCT = "INSERT_PRODUCT_HERE"
_PARENT = f"accounts/{_ACCOUNT}/products/{_PRODUCT}"
# ENSURE you fill in region ID for the sample to work.
_REGION = "INSERT_REGION_HERE"


def insert_regional_inventory():
  """Inserts a `RegionalInventory` to a given product.

  Replaces the full `RegionalInventory` resource if an entry with the same
  `region` already exists for the product.

  It might take up to 30 minutes for the new or updated `RegionalInventory`
  resource to appear in products.
  """

  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client.
  client = merchant_inventories_v1beta.RegionalInventoryServiceClient(
      credentials=credentials)

  # Creates a regional inventory and populate its attributes.
  regional_inventory = merchant_inventories_v1beta.RegionalInventory()
  regional_inventory.region = _REGION
  regional_inventory.availability = "in stock"
  regional_inventory.price = {
      "currency_code": "USD",
      "amount_micros": 33450000,
  }

  # Creates the request.
  request = merchant_inventories_v1beta.InsertRegionalInventoryRequest(
      parent=_PARENT,
      regional_inventory=regional_inventory,
  )

  # Makes the request and catch and print any error messages.
  try:
    response = client.insert_regional_inventory(request=request)

    print("Insert successful")
    print(response)
  except Exception as e:
    print("Insert failed")
    print(e)

Этот вызов возвращает точно те же значения, которые вы отправляете, и может не полностью представлять окончательные данные инвентаризации.

Прежде чем новый RegionalInventory появится в продукте, может пройти до 30 минут.

Дополнительные способы добавления информации о региональном ассортименте см. в разделе «Фиды регионального ассортимента» в конце статьи «Создание фида» .

Подпишитесь на бесплатные объявления в Google

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