Maintenez les informations sur vos magasins à jour

Vous pouvez utiliser la sous-API Inventories pour tenir à jour les informations en magasin concernant vos produits locaux. Cela inclut la mise à jour de price et availability, ainsi que la suppression des magasins dans lesquels un produit n'est plus vendu.

Si vous êtes un fournisseur tiers, vous pouvez utiliser la sous-API Inventories pour créer une interface permettant à vos entreprises de mettre à jour la disponibilité en magasin de leurs produits.

Mettre à jour le prix et la disponibilité par magasin

Utilisez localInventories.insert pour mettre à jour les informations en magasin d'un produit.

Cet appel remplace la ressource LocalInventory complète. Veillez donc à inclure tous les champs. Pour obtenir un exemple de code et en savoir plus, consultez Ajouter des informations en magasin aux produits locaux.

Afficher vos magasins existants

Cette section explique comment afficher les magasins associés à un produit ou à un compte.

Par produit

Utilisez localInventories.list pour lister tous les inventaires locaux associés à un product spécifique de votre compte. Cet appel renvoie des ressources LocalInventory complètes. Utilisez l'attribut store_code pour identifier chaque magasin.

Voici un exemple permettant de lister les stocks locaux d'un produit :

Java

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.inventories.v1.ListLocalInventoriesRequest;
import com.google.shopping.merchant.inventories.v1.LocalInventory;
import com.google.shopping.merchant.inventories.v1.LocalInventoryServiceClient;
import com.google.shopping.merchant.inventories.v1.LocalInventoryServiceClient.ListLocalInventoriesPagedResponse;
import com.google.shopping.merchant.inventories.v1.LocalInventoryServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to list all the Local inventories on a given product */
public class ListLocalInventoriesSample {

  private static String getParent(String accountId, String productId) {
    return String.format("accounts/%s/products/%s", accountId, productId);
  }

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

    LocalInventoryServiceSettings localInventoryServiceSettings =
        LocalInventoryServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

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

    try (LocalInventoryServiceClient localInventoryServiceClient =
        LocalInventoryServiceClient.create(localInventoryServiceSettings)) {

      //  The parent product has the format: accounts/{account}/products/{product}
      ListLocalInventoriesRequest request =
          ListLocalInventoriesRequest.newBuilder().setParent(parent).build();

      System.out.println("Sending list Local inventory request:");
      ListLocalInventoriesPagedResponse response =
          localInventoryServiceClient.listLocalInventories(request);

      int count = 0;

      // Iterates over all rows in all pages and prints the Local inventory
      // in each row.
      for (LocalInventory element : response.iterateAll()) {
        System.out.println(element);
        count++;
      }
      System.out.print("The following count of elements were returned: ");
      System.out.println(count);
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // An ID assigned to a product by Google. In the format
    // channel:contentLanguage:feedLabel:offerId
    String productId = "local:en:label:1111111111";
    listLocalInventories(config, productId);
  }
}

cURL

  curl --location
  'https://merchantapi.googleapis.com/inventories/v1/accounts/987654321/products/en~US~12345/localInventories' \
  --header 'Authorization: Bearer <API_TOKEN>'

PHP

use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Shopping\Merchant\Inventories\V1\LocalInventory;
use Google\Shopping\Merchant\Inventories\V1\Client\LocalInventoryServiceClient;
use Google\Shopping\Merchant\Inventories\V1\ListLocalInventoriesRequest;

/**
 * Class to list the `LocalInventory` resources for the given product in your
 * merchant account. The response might contain fewer items than specified by
 * `pageSize`. If `pageToken` was returned in previous request, it can be
 * used to obtain additional results.
 *
 * `LocalInventory` resources are listed per product for a given account.
 */

class ListLocalInventories
{

    // 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]';

    /**
     * Lists all the local inventories of a given product.
     *
     * @param string $parent The `name` of the parent product to list `LocalInventory`
     *     resources for.
     *     Format: `accounts/{account}/products/{product}`
     */
    function listLocalInventoriesSample(string $parent): 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.
        $localInventoryServiceClient = new LocalInventoryServiceClient($options);

        // Prepare the request message.
        $request = (new ListLocalInventoriesRequest())
            ->setParent($parent);

        // Calls the API and catches and prints any network failures/errors.
        try {
            // Page size is set to the default value. If you are returned more
            // responses than your page size, this code will automatically
            // re-call the service with the `pageToken` until all responses
            // are returned.
            $parameters = ['pageSize' => 25000];

            /** @var PagedListResponse $response */
            $response =
                $localInventoryServiceClient->listLocalInventories($request, $parameters);

            /** @var LocalInventory $element */
            foreach ($response as $element) {
                printf('LocalInventory data: %s%s', $element->serializeToJsonString(), PHP_EOL);
            }
        } catch (ApiException $ex) {
            printf('Call failed with message: %s%s', $ex->getMessage(), PHP_EOL);
        }
    }

    // Helper to execute the sample.
    function callSample(): void
    {
        // Lists all the local inventories of the parent product.
        $this->listLocalInventoriesSample($this::PARENT);
    }
}


$sample = new ListLocalInventories();
$sample->callSample();

Python

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping import merchant_inventories_v1

# ENSURE you fill in the product ID for the sample to
# work.
_ACCOUNT = configuration.Configuration().read_merchant_info()
_PRODUCT = "[INSERT_PRODUCT_HERE]"
_PARENT = f"accounts/{_ACCOUNT}/products/{_PRODUCT}"


def list_local_inventories():
  """Lists the `LocalInventory` resources for the given product.

  The response might contain fewer items than specified by
  `pageSize`. If `pageToken` was returned in previous request, it can be
  used to obtain additional results.

  `LocalInventory` resources are listed per product for a given account.
  """

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

  # Creates a client.
  client = merchant_inventories_v1.LocalInventoryServiceClient(
      credentials=credentials)

  # Creates the request.
  # Page size is set to the default value.
  request = merchant_inventories_v1.ListLocalInventoriesRequest(
      parent=_PARENT,
      page_size=25000
  )

  try:
    # Makes the request and catch and print any error messages.
    # If you are returned more responses than your page size, this code
    # will automatically re-call the service with the `pageToken` until all
    # responses are returned.
    page_result = client.list_local_inventories(request=request)

    # Print the response.
    for response in page_result:
      print(response)

  except RuntimeError as e:
    print("List failed")
    print(e)


if __name__ == "__main__":
  list_local_inventories()

Par compte

Vous pouvez afficher tous les magasins associés à votre compte dans votre fiche d'établissement ou avec l'API Google My Business. Vous ne pouvez pas utiliser l'API Merchant pour afficher ou gérer les magasins au niveau du compte, car ces informations proviennent de votre fiche d'établissement.

Supprimer des magasins

Découvrez comment supprimer les magasins dans lesquels vous ne vendez plus de produits.

Depuis les produits

Si un produit n'est plus vendu dans un magasin spécifique, vous devez supprimer l'entrée d'inventaire en magasin pour ce magasin. Vous pouvez utiliser localInventories.delete pour supprimer une entrée d'inventaire en magasin spécifique d'un produit.

Voici un exemple permettant de supprimer une entrée d'inventaire en magasin d'un produit :

Java

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.inventories.v1.DeleteLocalInventoryRequest;
import com.google.shopping.merchant.inventories.v1.LocalInventoryName;
import com.google.shopping.merchant.inventories.v1.LocalInventoryServiceClient;
import com.google.shopping.merchant.inventories.v1.LocalInventoryServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to delete a Local inventory for a given product */
public class DeleteLocalInventorySample {

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

    LocalInventoryServiceSettings localInventoryServiceSettings =
        LocalInventoryServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    String name =
        LocalInventoryName.newBuilder()
            .setAccount(config.getAccountId().toString())
            .setProduct(productId)
            .setStoreCode(storeCode)
            .build()
            .toString();

    try (LocalInventoryServiceClient localInventoryServiceClient =
        LocalInventoryServiceClient.create(localInventoryServiceSettings)) {
      DeleteLocalInventoryRequest request =
          DeleteLocalInventoryRequest.newBuilder().setName(name).build();

      System.out.println("Sending deleteLocalInventory request");
      localInventoryServiceClient.deleteLocalInventory(request); // no response returned on success
      System.out.println(
          "Delete successful, note that it may take up to 30 minutes for the delete to update in"
              + " the system.");
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // An ID assigned to a product by Google. In the format
    // channel:contentLanguage:feedLabel:offerId
    String productId = "local:en:label:1111111111";
    // The ID uniquely identifying each region.
    String storeCode = "EXAMPLE";

    deleteLocalInventory(config, productId, storeCode);
  }
}

cURL

  curl --location --request DELETE
  'https://merchantapi.googleapis.com/inventories/v1/accounts/987654321/products/en~US~12345/localInventories/123456' \
  --header 'Authorization: Bearer <API_TOKEN>'

PHP

use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Inventories\V1\Client\LocalInventoryServiceClient;
use Google\Shopping\Merchant\Inventories\V1\DeleteLocalInventoryRequest;

/**
 * Deletes the specified `LocalInventory` resource from the given product
 * in your merchant account.  It might take up to an hour for the
 * `LocalInventory` to be deleted from the specific product.
 * Once you have received a successful delete response, wait for that
 * period before attempting a delete again.
 */

class DeleteLocalInventory
{

    // ENSURE you fill in the merchant account, product, and region ID for the
    // sample to work.
    private const ACCOUNT = 'INSERT_ACCOUNT_ID_HERE';
    private const PRODUCT = 'INSERT_PRODUCT_ID_HERE';
    private const STORE_CODE = 'INSERT_STORE_CODE_HERE';

    /**
     * Deletes a specific local inventory of a given product.
     *
     * @param string $formattedName The name of the `LocalInventory` resource
     * to delete.
     *     Format: `accounts/{account}/products/{product}/localInventories/{store_code}`
     *     Please see {@see LocalInventoryServiceClient::localInventoryName()}
     *     for help formatting this field.
     */
    function deleteLocalInventorySample(string $formattedName): 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.
         $localInventoryServiceClient = new LocalInventoryServiceClient($options);

        // Prepare the request message.
        $request = (new DeleteLocalInventoryRequest())
            ->setName($formattedName);

         // Calls the API and catches and prints any network failures/errors.
         try {
             $localInventoryServiceClient->deleteLocalInventory($request);
             print 'Delete call completed successfully.' . PHP_EOL;
         } catch (ApiException $ex) {
             printf('Call failed with message: %s%s', $ex->getMessage(), PHP_EOL);
         }
    }

    /**
     * Helper to execute the sample.
     */
    function callSample(): void
    {
        // These variables are defined at the top of the file.
        $formattedName = LocalInventoryServiceClient::localInventoryName(
            $this::ACCOUNT,
            $this::PRODUCT,
            $this::STORE_CODE
        );

        // Deletes the specific local inventory of the parent product.
        $this->deleteLocalInventorySample($formattedName);
    }
}


$sample = new DeleteLocalInventory();
$sample->callSample();

Python

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping import merchant_inventories_v1

# ENSURE you fill in the product ID and store code
# for the sample to work.
_ACCOUNT = configuration.Configuration().read_merchant_info()
_PRODUCT = "[INSERT_PRODUCT_HERE]"
_STORE_CODE = "[INSERT_STORE_CODE_HERE]"
_NAME = (f"accounts/{_ACCOUNT}/products/{_PRODUCT}/localInventories/"
         f"{_STORE_CODE}")


def delete_local_inventory():
  """Deletes the specified `LocalInventory` resource from the given product.

  It might take up to an hour for the `LocalInventory` to be deleted
  from the specific product. Once you have received a successful delete
  response, wait for that period before attempting a delete again.
  """

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

  # Creates a client.
  client = merchant_inventories_v1.LocalInventoryServiceClient(
      credentials=credentials)

  # Creates the request.
  request = merchant_inventories_v1.DeleteLocalInventoryRequest(name=_NAME)

  # Makes the request and catch and print any error messages.
  try:
    client.delete_local_inventory(request=request)
    print("Delete successful")
  except RuntimeError as e:
    print("Delete failed")
    print(e)


if __name__ == "__main__":
  delete_local_inventory()

Cet appel supprime les informations uniquement pour le magasin et le produit spécifiés.

Depuis les comptes

Vous pouvez supprimer de votre compte les magasins dans lesquels vous ne vendez plus vos produits en les supprimant de votre fiche d'établissement. Pour en savoir plus, consultez Fermer ou supprimer un établissement.