Region w Merchant API to region geograficzny, którego możesz używać jako celu związanego z zasobem accounts.products.regionalInventories. Regiony możesz definiować jako zbiory kodów pocztowych lub, w niektórych krajach, za pomocą predefiniowanych geotargetów. Więcej informacji znajdziesz w artykule Konfigurowanie
regionów.
Merchant API udostępnia punkty końcowe operacji wsadowych 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 zarządzających regionalną dostępnością i cenami na dużą skalę, które zwiększa wydajność i upraszcza integrację.
Przegląd
Interfejs Batch API umożliwia wykonywanie tych czynności za pomocą powiązanych metod:
- Tworzenie wielu regionów w jednym żądaniu:
regions:batchCreate - Usuwanie wielu regionów naraz:
regions:batchDelete - Jednoczesne aktualizowanie wielu regionów:
regions:batchUpdate
Wymagania wstępne
Wszystkie żądania wsadowe wymagają do uwierzytelnienia 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 BatchCreateRegions.
Żądanie
Skonstruuj adres URL żądania w ten sposób:
POST
https://merchantapi.googleapis.com/accounts/v1/accounts/{ACCOUNT_ID}/regions:batchCreate
Treść żądania zawiera listę requests, gdzie każdy obiekt określa a
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ź
Pomyślne żądanie 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
}
]
}
Poniższy przykład pokazuje, jak utworzyć wiele 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.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 użyć BatchUpdateRegions do zaktualizowania displayName i postalCodeArea w 2 istniejących regionach. Aby zaktualizować docelowy region, musisz podać region.name.
Żądanie
Skonstruuj 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ć dane region do zaktualizowania. Pole region.name musi zawierać identyfikator regionu do zaktualizowania, np. „98005”. Określ zasób jako name zamiast
accounts/{ACCOUNT_ID}/regions/name. Dołączenie updateMask w celu wskazania pól 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ź
Pomyślne żądanie 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ąć wiele regionów w ramach jednego wywołania.
Żądanie
Ten przykład pokazuje, jak użyć BatchDeleteRegions do usunięcia 2 regionów w ramach jednego wywołania.
POST
https://merchantapi.googleapis.com/accounts/v1/accounts/{ACCOUNT_ID}/regions:batchDelete
Treść żądania zawiera listę requests, gdzie każdy obiekt 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ąć wiele 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 operacja w ramach partii nie powiedzie się (np. nie uda się utworzyć regionu), cała partia nie powiedzie się i żadne zmiany nie zostaną wprowadzone. Interfejs API zwróci błąd z informacjami o przyczynie niepowodzenia.
- Limity operacji zbiorczych: każde żądanie zbiorcze może zawierać maksymalnie 100 operacji na regionach.
- Limity: te punkty końcowe używają 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 pułapek 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 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 nie więcej niż 100 operacji.
Wymagane pole jest puste
Ten błąd występuje, gdy brakuje wymaganego pola. Komunikat o błędzie określa brakujący parametr.
Komunikaty o błędach są następujące:
- W przypadku
batchCreate:[regionId] Required parameter: regionId - W przypadku
batchUpdate:[region.name] Required field not provided. - W przypadku
batchDelete:[name] Required parameter: name
Aby rozwiązać ten problem, sprawdź, czy wszystkie wymagane pola są obecne w każdej operacji. Na przykład każdy wpis w żądaniu batchUpdate musi zawierać 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”
Błąd występuje, jeśli próbujesz utworzyć region z regionId, który już istnieje.
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 ramach partii i nie kolidują z istniejącymi regionami.
„Znaleziono zduplikowaną wartość w polu region.name lub regionId”
Błąd występuje, jeśli próbujesz utworzyć lub zaktualizować wiele regionów o tym samym identyfikatorze w ramach jednego żądania zbiorczego.
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 jednego żądania zbiorczego.
„Nie znaleziono elementu”
Jeśli podczas korzystania z batchUpdate jakikolwiek region określony w żądaniu nie istnieje, cała partia nie powiedzie się i zostanie zwrócony błąd 404 NOT_FOUND. Różni się to od batchDelete, które w przypadku nieistniejących regionów kończy się powodzeniem.
"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 próbujesz zaktualizować, istnieją.