Zarządzanie grupowaniem regionów

Region Merchant API to region geograficzny, którego możesz używać jako celu powiązanego z zasobem accounts.products.regionalInventories. Regiony możesz definiować jako zbiory kodów pocztowych lub, w niektórych krajach, za pomocą wstępnie zdefiniowanych geotargetów. Więcej informacji znajdziesz w artykule Konfigurowanie regionów.

Interfejs Merchant API udostępnia punkty końcowe do zarządzania regionami, które umożliwiają tworzenie, aktualizowanie i usuwanie maksymalnie 100 regionów w ramach jednego wywołania interfejsu API. Jest to idealne rozwiązanie dla sprzedawców, którzy zarządzają regionalną dostępnością i cenami na dużą skalę, ponieważ zwiększa wydajność i upraszcza integrację.

Przegląd

Interfejs Batch API umożliwia wykonywanie tych czynności za pomocą powiązanych metod:

  • Utwórz kilka regionów w jednym żądaniu: regions:batchCreate
  • Usuwanie wielu regionów jednocześnie: regions:batchDelete
  • Aktualizowanie wielu regionów jednocześnie: regions:batchUpdate

Wymagania wstępne

Wszystkie żądania zbiorcze wymagają do uwierzytelniania roli użytkownika ADMIN.

Tworzenie wielu regionów

Ten przykład pokazuje, jak utworzyć 2 nowe regiony – jeden zdefiniowany przez kody pocztowe, a drugi przez kierowanie geograficzne – w ramach jednego wywołania funkcji BatchCreateRegions.

Żądanie

Utwórz adres URL żądania w ten sposób:

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

Treść żądania zawiera listę obiektów requests, z których każdy określa regionId i dane region do utworzenia.

{
  "requests": [
    {
      "regionId": "seattle-area-98340",
      "region": {
        "displayName": "Seattle Region",
        "postalCodeArea": {
          "regionCode": "US",
          "postalCodes": [
            {
              "begin": "98340"
            }
          ]
        }
      }
    },
    {
      "regionId": "co-de-states",
      "region": {
        "displayName": "Colorado and Delaware",
        "geoTargetArea": {
          "geotargetCriteriaIds": [
            "21138",
            "21141"
          ]
        }
      }
    }
  ]
}

Odpowiedź

Żądanie zakończone pomyślnie zwraca listę nowych obiektów region.

{
  "regions": [
    {
      "name": "accounts/{ACCOUNT_ID}/regions/seattle-area-98340",
      "displayName": "Seattle Region",
      "postalCodeArea": {
        "regionCode": "US",
        "postalCodes": [
          {
            "begin": "98340"
          }
        ]
      },
      "regionalInventoryEligible": true,
      "shippingEligible": true
    },
    {
      "name": "accounts/{ACCOUNT_ID}/regions/co-de-states",
      "displayName": "Colorado and Delaware",
      "geotargetArea": {
        "geotargetCriteriaIds": [
          "21138",
          "21141"
        ]
      },
      "regionalInventoryEligible": false,
      "shippingEligible": false
    }
  ]
}

Ten przykład pokazuje, jak utworzyć kilka regionów w żądaniu zbiorczym:

Java

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.BatchCreateRegionsRequest;
import com.google.shopping.merchant.accounts.v1.BatchCreateRegionsResponse;
import com.google.shopping.merchant.accounts.v1.CreateRegionRequest;
import com.google.shopping.merchant.accounts.v1.Region;
import com.google.shopping.merchant.accounts.v1.Region.PostalCodeArea;
import com.google.shopping.merchant.accounts.v1.Region.PostalCodeArea.PostalCodeRange;
import com.google.shopping.merchant.accounts.v1.RegionsServiceClient;
import com.google.shopping.merchant.accounts.v1.RegionsServiceSettings;
import java.util.ArrayList;
import java.util.List;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to create multiple regions for a Merchant Center account. */
public class BatchCreateRegionsSample {

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

  public static void batchCreateRegions(Config config, List<String> regionIds) throws Exception {

    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    // Creates service settings using the credentials retrieved above.
    RegionsServiceSettings regionsServiceSettings =
        RegionsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Creates parent to identify where to insert the regions.
    String parent = getParent(config.getAccountId().toString());

    // Calls the API and catches and prints any network failures/errors.
    try (RegionsServiceClient regionsServiceClient =
        RegionsServiceClient.create(regionsServiceSettings)) {

      List<CreateRegionRequest> requests = new ArrayList<>();
      for (String regionId : regionIds) {
        requests.add(
            CreateRegionRequest.newBuilder()
                .setParent(parent)
                .setRegionId(regionId)
                .setRegion(
                    Region.newBuilder()
                        .setDisplayName("Region " + regionId)
                        .setPostalCodeArea(
                            PostalCodeArea.newBuilder()
                                .setRegionCode("US")
                                .addPostalCodes(
                                    PostalCodeRange.newBuilder()
                                        .setBegin("10001")
                                        .setEnd("10282")
                                        .build())
                                .build())
                        .build())
                .build());
      }

      BatchCreateRegionsRequest request =
          BatchCreateRegionsRequest.newBuilder().setParent(parent).addAllRequests(requests).build();

      System.out.println("Sending Batch Create Regions request");
      BatchCreateRegionsResponse response = regionsServiceClient.batchCreateRegions(request);
      System.out.println("Inserted Regions Names below");
      // The last part of the region name will be the ID of the region.
      // Format: `accounts/{account}/region/{region}`
      response.getRegionsList().forEach(region -> System.out.println(region.getName()));

    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // The unique IDs of the regions to create.
    List<String> regionIds = new ArrayList<>();
    regionIds.add("REGION_1");
    regionIds.add("REGION_2");
    regionIds.add("REGION_3");
    regionIds.add("REGION_4");
    regionIds.add("REGION_5");

    batchCreateRegions(config, regionIds);
  }
}

Aktualizowanie wielu regionów

Ten przykład pokazuje, jak za pomocą pola BatchUpdateRegions zaktualizować wartości displayNamepostalCodeArea w przypadku 2 dotychczasowych regionów. Aby zaktualizować region docelowy, musisz podać region.name.

Żądanie

Utwórz adres URL żądania w ten sposób:

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

Treść żądania zawiera listę requests. Każdy obiekt musi określać regiondane do zaktualizowania. Pole region.name musi zawierać identyfikator regionu do zaktualizowania, np. „98005”. Określ zasób jako name, a nie accounts/{ACCOUNT_ID}/regions/name. Dodanie znaku updateMask, aby wskazać pola do zmiany, jest opcjonalne.

{
  "requests": [
    {
      "region": {
        "name": "98005",
        "displayName": "Seattle Updated Region",
        "postalCodeArea": {
          "regionCode": "US",
          "postalCodes": [
            {
              "begin": "98330"
            }
          ]
        }
      },
      "updateMask": "displayName,postalCodeArea"
    },
    {
      "region": {
        "name": "07086",
        "displayName": "NewYork Updated Region",
        "postalCodeArea": {
          "regionCode": "US",
          "postalCodes": [
            {
              "begin": "11*"
            }
          ]
        }
      },
      "updateMask": "displayName,postalCodeArea"
    }
  ]
}

Odpowiedź

Żądanie zakończone pomyślnie zwraca listę zaktualizowanych obiektów region.

{
  "regions": [
    {
      "name": "accounts/{ACCOUNT_ID}/regions/98005",
      "displayName": "Seattle Updated Region",
      "postalCodeArea": {
        "regionCode": "US",
        "postalCodes": [
          {
            "begin": "98330"
          }
        ]
      },
      "regionalInventoryEligible": true,
      "shippingEligible": true
    },
    {
      "name": "accounts/{ACCOUNT_ID}/regions/07086",
      "displayName": "NewYork Updated Region",
      "postalCodeArea": {
        "regionCode": "US",
        "postalCodes": [
          {
            "begin": "11*"
          }
        ]
      },
      "regionalInventoryEligible": true,
      "shippingEligible": true
    }
  ]
}

Poniższy przykład pokazuje, jak zaktualizować wiele regionów w żądaniu wsadowym:

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.BatchUpdateRegionsRequest;
import com.google.shopping.merchant.accounts.v1.BatchUpdateRegionsResponse;
import com.google.shopping.merchant.accounts.v1.Region;
import com.google.shopping.merchant.accounts.v1.RegionsServiceClient;
import com.google.shopping.merchant.accounts.v1.RegionsServiceSettings;
import com.google.shopping.merchant.accounts.v1.UpdateRegionRequest;
import java.util.ArrayList;
import java.util.List;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to update multiple regions for a Merchant Center account. */
public class BatchUpdateRegionsSample {

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

  private static String getRegionName(String accountId, String regionId) {
    return String.format("accounts/%s/regions/%s", accountId, regionId);
  }

  public static void batchUpdateRegions(Config config, List<String> regionIds) throws Exception {

    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    // Creates service settings using the credentials retrieved above.
    RegionsServiceSettings regionsServiceSettings =
        RegionsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Creates parent to identify where to update the regions.
    String parent = getParent(config.getAccountId().toString());
    String accountId = config.getAccountId().toString();

    // Calls the API and catches and prints any network failures/errors.
    try (RegionsServiceClient regionsServiceClient =
        RegionsServiceClient.create(regionsServiceSettings)) {

      List<UpdateRegionRequest> requests = new ArrayList<>();
      for (String regionId : regionIds) {
        requests.add(
            UpdateRegionRequest.newBuilder()
                .setRegion(
                    Region.newBuilder()
                        .setName(getRegionName(accountId, regionId))
                        .setDisplayName("Updated Region " + regionId)
                        .build())
                .setUpdateMask(FieldMask.newBuilder().addPaths("display_name").build())
                .build());
      }

      BatchUpdateRegionsRequest request =
          BatchUpdateRegionsRequest.newBuilder().setParent(parent).addAllRequests(requests).build();

      System.out.println("Sending Batch Update Regions request");
      BatchUpdateRegionsResponse response = regionsServiceClient.batchUpdateRegions(request);
      System.out.println("Updated Regions Names below");
      // The last part of the region name will be the ID of the region.
      // Format: `accounts/{account}/region/{region}`
      response.getRegionsList().forEach(region -> System.out.println(region.getName()));

    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // The unique IDs of the regions to update.
    List<String> regionIds = new ArrayList<>();
    regionIds.add("REGION_1");
    regionIds.add("REGION_2");
    regionIds.add("REGION_3");
    regionIds.add("REGION_4");
    regionIds.add("REGION_5");

    batchUpdateRegions(config, regionIds);
  }
}

Usuwanie wielu regionów

Możesz usunąć kilka regionów w jednym wywołaniu.

Żądanie

Ten przykład pokazuje, jak za pomocą polecenia BatchDeleteRegions usunąć 2 regiony w ramach jednego wywołania.

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

Treść żądania zawiera listę obiektów requests, z których każdy określa name (bez "accounts/{ACCOUNT_ID}/regions/") regionu do usunięcia.

{
  "requests":
   [
    {
      "name": "98005"
    },
    {
      "name": "07086"
    }
   ]
}

Odpowiedź

Pomyślne żądanie zwraca pustą treść odpowiedzi, co oznacza, że określone regiony zostały usunięte (lub nie istniały).

{}

Poniższy przykład pokazuje, jak usunąć kilka regionów w żądaniu wsadowym:

Java

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.BatchDeleteRegionsRequest;
import com.google.shopping.merchant.accounts.v1.DeleteRegionRequest;
import com.google.shopping.merchant.accounts.v1.RegionsServiceClient;
import com.google.shopping.merchant.accounts.v1.RegionsServiceSettings;
import java.util.ArrayList;
import java.util.List;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to delete multiple regions for a Merchant Center account. */
public class BatchDeleteRegionsSample {

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

  private static String getRegionName(String accountId, String regionId) {
    return String.format("accounts/%s/regions/%s", accountId, regionId);
  }

  public static void batchDeleteRegions(Config config, List<String> regionIds) throws Exception {

    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    // Creates service settings using the credentials retrieved above.
    RegionsServiceSettings regionsServiceSettings =
        RegionsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Creates parent to identify where to delete the regions.
    String parent = getParent(config.getAccountId().toString());
    String accountId = config.getAccountId().toString();

    // Calls the API and catches and prints any network failures/errors.
    try (RegionsServiceClient regionsServiceClient =
        RegionsServiceClient.create(regionsServiceSettings)) {

      List<DeleteRegionRequest> requests = new ArrayList<>();
      for (String regionId : regionIds) {
        requests.add(
            DeleteRegionRequest.newBuilder().setName(getRegionName(accountId, regionId)).build());
      }

      BatchDeleteRegionsRequest request =
          BatchDeleteRegionsRequest.newBuilder().setParent(parent).addAllRequests(requests).build();

      System.out.println("Sending Batch Delete Regions request");
      regionsServiceClient.batchDeleteRegions(request);
      System.out.println("Regions deleted successfully");

    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // The unique IDs of the regions to delete.
    List<String> regionIds = new ArrayList<>();
    regionIds.add("REGION_1");
    regionIds.add("REGION_2");
    regionIds.add("REGION_3");
    regionIds.add("REGION_4");
    regionIds.add("REGION_5");

    batchDeleteRegions(config, regionIds);
  }
}

Ograniczenia

Zanim zaczniesz, pamiętaj o tych zasadach:

  • Operacje niepodzielne: żądania wsadowe są niepodzielne. Jeśli jakakolwiek pojedyncza operacja w ramach partii zakończy się niepowodzeniem (np. nie uda się utworzyć regionu), cała partia zakończy się niepowodzeniem i nie zostaną wprowadzone żadne zmiany. Interfejs API zwróci błąd z informacją o przyczynie niepowodzenia.
  • Limity żądań zbiorczych: każde żądanie zbiorcze może zawierać maksymalnie 100 operacji w regionie.
  • Limity: te punkty końcowe korzystają z tych samych grup limitów co ich odpowiedniki z pojedynczą operacją (regions.create, regions.delete, regions.update).

Typowe błędy i problemy

Oto kilka typowych problemów i ich rozwiązań.

„Liczba żądań w partii jest zbyt duża”

Ten błąd występuje, jeśli liczba operacji w tablicy żądań przekracza limit wynoszący 100.

"error":
  {
    "code": 400,
    "message": "The number of requests in a batch is too large.",
    "status": "INVALID_ARGUMENT"
  }

Aby rozwiązać ten problem, podziel operacje na kilka żądań wsadowych zawierających maksymalnie 100 operacji.

Wymagane pole jest puste

Ten błąd występuje, gdy brakuje wymaganego pola. Komunikat o błędzie zawiera informację o brakującym parametrze.

Komunikaty o błędach:

  • batchCreate za [regionId] Required parameter: regionId
  • batchUpdate za [region.name] Required field not provided.
  • batchDelete za [name] Required parameter: name

Aby rozwiązać ten problem, sprawdź, czy w każdej operacji występują wszystkie wymagane pola. Na przykład każde żądanie batchUpdate musi zawierać element region.name. Wysłanie tego żądania spowoduje błąd:

{
  "requests":
  [
    {
      "region":
        {
          "displayName": "An update without a region name"
        },
        "updateMask": "displayName"
    }
  ]
}

„Region o podanym identyfikatorze już istnieje”

Jeśli spróbujesz utworzyć region z regionId, który już istnieje, wystąpi błąd.

Komunikat o błędzie to [regionId] Region with specified id already exists..

Aby rozwiązać ten problem, sprawdź, czy wszystkie wartości regionId są unikalne w partii i nie kolidują z istniejącymi regionami.

„Zduplikowana wartość w polu region.name lub regionId”

Jeśli w ramach jednego żądania zbiorczego spróbujesz utworzyć lub zaktualizować wiele regionów o tym samym identyfikatorze, wystąpi błąd.

Komunikat o błędzie to Duplicate value found for field {fieldName} in this batch request with value {duplicated_value}..

Aby rozwiązać ten problem, sprawdź, czy wszystkie wartości regionId (w przypadku batchCreate) lub region.name (w przypadku batchUpdate) są unikalne w ramach pojedynczego żądania zbiorczego.

„Nie znaleziono elementu”

Jeśli używasz batchUpdate, a którykolwiek region określony w żądaniu nie istnieje, cały pakiet zakończy się niepowodzeniem z błędem 404 NOT_FOUND. Różni się to od batchDelete, który zwraca wartość true w przypadku nieistniejących regionów.

"error": {
    "code": 404,
    "message": "item not found",
    "status": "NOT_FOUND"
}

Aby rozwiązać ten problem, przed wysłaniem żądania sprawdź, czy wszystkie regiony, które chcesz zaktualizować, istnieją.