管理區域批次處理

Merchant API 區域代表地理區域,可做為與 accounts.products.regionalInventories 資源相關的指定目標。您可以將區域定義為郵遞區號的集合,或在某些國家/地區使用預先定義的指定地理區域。詳情請參閱「設定區域」。

Merchant API 提供批次端點,可用於管理區域,讓你在單一 API 呼叫中建立、更新和刪除最多 100 個區域。這項功能適合大規模管理區域供應情形和價格 (RAAP) 的商家,可提升效率並簡化整合程序。

總覽

Batch API 可讓您透過相關方法完成下列作業:

  • 在單一要求中建立多個區域:regions:batchCreate
  • 一次刪除多個區域:regions:batchDelete
  • 同時更新多個區域:regions:batchUpdate

必要條件

所有批次要求都必須由管理員使用者角色進行驗證。

建立多個區域

以下範例說明如何透過單次呼叫 BatchCreateRegions,建立兩個新區域,一個以郵遞區號定義,另一個以指定地理區域定義。

要求

請按照下列方式建構要求網址:

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

要求主體包含 requests 清單,其中每個物件都會指定要建立的 regionId 和 region 資料。

{
  "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"
          ]
        }
      }
    }
  ]
}

回應

如果要求成功,系統會傳回新的 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
    }
  ]
}

以下範例說明如何在批次要求中建立多個區域:

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);
  }
}

更新多個區域

以下範例說明如何使用 BatchUpdateRegions 更新兩個現有區域的 displayName 和 postalCodeArea。您必須提供 region.name,才能更新指定區域。

要求

請按照下列方式建構要求網址:

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

要求主體包含 requests 清單。每個物件都必須指定要更新的 region 資料。region.name 欄位必須包含要更新的區域 ID,例如「98005」。請將資源指定為 name,而非 accounts/{ACCOUNT_ID}/regions/name。您可以選擇是否加入 updateMask,指出要變更的欄位。

{
  "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"
    }
  ]
}

回應

如果要求成功,系統會傳回更新後的 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
    }
  ]
}

以下範例說明如何在批次要求中更新多個區域:

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);
  }
}

刪除多個區域

您可以在單一呼叫中刪除多個區域。

要求

以下範例說明如何使用 BatchDeleteRegions,在單一呼叫中刪除兩個區域。

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

要求主體包含 requests 清單,其中每個物件都會指定要刪除區域的 name (不含 "accounts/{ACCOUNT_ID}/regions/")。

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

回應

如果要求成功,系統會傳回空白的回應主體,表示指定的區域已刪除 (或不存在)。

{}

以下範例說明如何在批次要求中刪除多個區域:

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);
  }
}

限制

開始前,請留意下列規則:

  • 不可分割作業:批次要求不可分割。如果批次作業中有任何一項作業失敗 (例如無法建立某個區域),整個批次作業就會失敗,不會進行任何變更。API 會傳回錯誤,詳述失敗原因。
  • 批次限制:每個批次要求最多可包含 100 項區域作業。
  • 配額:這些端點使用的配額群組,與單一作業對應項目 (regions.create、regions.delete、regions.update) 相同。

常見錯誤和問題

以下列舉幾個常見問題和解決方法。

「批次中的要求數量過多」

如果要求陣列中的作業數量超過 100 項,就會發生這項錯誤。

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

如要修正這個問題,請將作業拆分為多個批次要求,每個要求最多 100 項。

未填寫必填欄位

如果缺少必填欄位,就會發生這個錯誤。錯誤訊息會指出缺少的參數。

錯誤訊息如下:

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

如要修正這個問題,請確認每項作業都包含所有必要欄位。舉例來說,batchUpdate 要求中的每個項目都必須包含 region.name。發布下列要求會導致錯誤:

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

「已有指定 ID 的區域」

如果嘗試建立的區域與現有regionId相同,就會發生錯誤。

錯誤訊息為 [regionId] Region with specified id already exists.。

如要修正這個問題,請確認批次中的所有 regionId 值都是不重複的值,且與現有區域不衝突。

「找到重複的 region.name 或 regionId 欄位值」

如果在單一批次要求中,嘗試建立或更新多個 ID 相同的區域,就會發生錯誤。

錯誤訊息為 Duplicate value found for field {fieldName} in this batch request with value {duplicated_value}.。

如要修正這個問題,請確認單一批次要求中的所有 regionId (batchCreate) 或 region.name (batchUpdate) 值都不重複。

「找不到項目」

使用 batchUpdate 時,如果要求中指定的任何區域不存在,整個批次就會失敗,並傳回 404 NOT_FOUND 錯誤。這與 batchDelete 不同,後者在區域不存在時會成功。

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

如要修正這個問題,請先確認您嘗試更新的所有區域都存在,再傳送要求。