Liệt kê khu vực
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Mã mẫu Merchant API để liệt kê các khu vực.
Java
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package shopping.merchant.samples.accounts.regions.v1;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.ListRegionsRequest;
import com.google.shopping.merchant.accounts.v1.Region;
import com.google.shopping.merchant.accounts.v1.RegionsServiceClient;
import com.google.shopping.merchant.accounts.v1.RegionsServiceClient.ListRegionsPagedResponse;
import com.google.shopping.merchant.accounts.v1.RegionsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to list all the regions for a given Merchant Center account. */
public class ListRegionsSample {
private static String getParent(String accountId) {
return String.format("accounts/%s", accountId);
}
public static void listRegions(Config config) 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 the account from which to list all regions.
String parent = getParent(config.getAccountId().toString());
// Calls the API and catches and prints any network failures/errors.
try (RegionsServiceClient regionsServiceClient =
RegionsServiceClient.create(regionsServiceSettings)) {
// The parent has the format: accounts/{account}
ListRegionsRequest request = ListRegionsRequest.newBuilder().setParent(parent).build();
System.out.println("Sending list regions request:");
ListRegionsPagedResponse response = regionsServiceClient.listRegions(request);
int count = 0;
// Iterates over all rows in all pages and prints the region
// in each row.
// `response.iterateAll()` automatically uses the `nextPageToken` and recalls the
// request to fetch all pages of data.
for (Region 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();
listRegions(config);
}
}
PHP
<?php
/**
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once __DIR__ . '/../../../../vendor/autoload.php';
require_once __DIR__ . '/../../../Authentication/Authentication.php';
require_once __DIR__ . '/../../../Authentication/Config.php';
use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1\Client\RegionsServiceClient;
use Google\Shopping\Merchant\Accounts\V1\ListRegionsRequest;
/**
* This class demonstrates how to list all the regions for a given Merchant Center account.
*/
class ListRegionsSample
{
private static function getParent(string $accountId): string
{
return sprintf("accounts/%s", $accountId);
}
public static function listRegionsSample(array $config): 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.
$regionsServiceClient = new RegionsServiceClient($options);
// Creates parent to identify the account from which to list all regions.
$parent = self::getParent($config['accountId']);
try {
$request = new ListRegionsRequest([
'parent' => $parent
]);
print "Sending list regions request:\n";
$response = $regionsServiceClient->listRegions($request);
$count = 0;
foreach ($response->iterateAllElements() as $element) {
print $element->getName() . PHP_EOL;
$count++;
}
print "The following count of elements were returned: ";
print $count . PHP_EOL;
} catch (ApiException $e) {
print $e->getMessage();
}
}
public function callSample(): void
{
$config = Config::generateConfig();
self::listRegionsSample($config);
}
}
$sample = new ListRegionsSample();
$sample->callSample();
Python
# -*- coding: utf-8 -*-
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A module to list all the Regions for a given Merchant Center account."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import ListRegionsRequest
from google.shopping.merchant_accounts_v1 import RegionsServiceClient
_ACCOUNT = configuration.Configuration().read_merchant_info()
def get_parent(account_id):
return f"accounts/{account_id}"
def list_regions():
"""Lists all the regions for a given Merchant Center account."""
# Gets OAuth Credentials.
credentials = generate_user_credentials.main()
# Creates a client.
client = RegionsServiceClient(credentials=credentials)
# Creates parent to identify the account from which to list all regions.
parent = get_parent(_ACCOUNT)
# Creates the request.
request = ListRegionsRequest(parent=parent)
# Makes the request and catches and prints any error messages.
try:
response = client.list_regions(request=request)
count = 0
print("Sending list regions request:")
for element in response:
print(element)
count += 1
print(f"The following count of elements were returned: {count}")
except RuntimeError as e:
print("List region request failed!")
print(e)
if __name__ == "__main__":
list_regions()
Trừ phi có lưu ý khác, nội dung của trang này được cấp phép theo Giấy phép ghi nhận tác giả 4.0 của Creative Commons và các mẫu mã lập trình được cấp phép theo Giấy phép Apache 2.0. Để biết thông tin chi tiết, vui lòng tham khảo Chính sách trang web của Google Developers. Java là nhãn hiệu đã đăng ký của Oracle và/hoặc các đơn vị liên kết với Oracle.
Cập nhật lần gần đây nhất: 2025-08-21 UTC.
[null,null,["Cập nhật lần gần đây nhất: 2025-08-21 UTC."],[[["\u003cp\u003eThis code sample demonstrates how to list all regions associated with a specific Merchant Center account using the Merchant API.\u003c/p\u003e\n"],["\u003cp\u003eThe Java and Python examples both utilize OAuth 2.0 for authentication to access the Merchant API and create service clients.\u003c/p\u003e\n"],["\u003cp\u003eBoth code samples format the account identifier correctly, so as to produce the parent identifier required for the API request.\u003c/p\u003e\n"],["\u003cp\u003eThe examples make the API call by using the \u003ccode\u003eListRegionsRequest\u003c/code\u003e, which takes the parent ID as an argument, and outputs the response to the console.\u003c/p\u003e\n"],["\u003cp\u003eThe code iterates through the paged response, prints each region, and tallies the total number of regions found for the provided account.\u003c/p\u003e\n"]]],[],null,["# List regions\n\nMerchant API code sample to list regions. \n\n### Java\n\n // Copyright 2024 Google LLC\n //\n // Licensed under the Apache License, Version 2.0 (the \"License\");\n // you may not use this file except in compliance with the License.\n // You may obtain a copy of the License at\n //\n // https://www.apache.org/licenses/LICENSE-2.0\n //\n // Unless required by applicable law or agreed to in writing, software\n // distributed under the License is distributed on an \"AS IS\" BASIS,\n // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n // See the License for the specific language governing permissions and\n // limitations under the License.\n\n package shopping.merchant.samples.accounts.regions.v1;\n import com.google.api.gax.core.FixedCredentialsProvider;\n import com.google.auth.oauth2.GoogleCredentials;\n import com.google.shopping.merchant.accounts.v1.ListRegionsRequest;\n import com.google.shopping.merchant.accounts.v1.Region;\n import com.google.shopping.merchant.accounts.v1.RegionsServiceClient;\n import com.google.shopping.merchant.accounts.v1.RegionsServiceClient.ListRegionsPagedResponse;\n import com.google.shopping.merchant.accounts.v1.RegionsServiceSettings;\n import shopping.merchant.samples.utils.Authenticator;\n import shopping.merchant.samples.utils.Config;\n\n /** This class demonstrates how to list all the regions for a given Merchant Center account. */\n public class ListRegionsSample {\n\n private static String getParent(String accountId) {\n return String.format(\"accounts/%s\", accountId);\n }\n\n public static void listRegions(Config config) throws Exception {\n\n // Obtains OAuth token based on the user's configuration.\n GoogleCredentials credential = new Authenticator().authenticate();\n\n // Creates service settings using the credentials retrieved above.\n RegionsServiceSettings regionsServiceSettings =\n RegionsServiceSettings.newBuilder()\n .setCredentialsProvider(FixedCredentialsProvider.create(credential))\n .build();\n\n // Creates parent to identify the account from which to list all regions.\n String parent = getParent(config.getAccountId().toString());\n\n // Calls the API and catches and prints any network failures/errors.\n try (RegionsServiceClient regionsServiceClient =\n RegionsServiceClient.create(regionsServiceSettings)) {\n\n // The parent has the format: accounts/{account}\n ListRegionsRequest request = ListRegionsRequest.newBuilder().setParent(parent).build();\n\n System.out.println(\"Sending list regions request:\");\n ListRegionsPagedResponse response = regionsServiceClient.listRegions(request);\n\n int count = 0;\n\n // Iterates over all rows in all pages and prints the region\n // in each row.\n // `response.iterateAll()` automatically uses the `nextPageToken` and recalls the\n // request to fetch all pages of data.\n for (Region element : response.iterateAll()) {\n System.out.println(element);\n count++;\n }\n System.out.print(\"The following count of elements were returned: \");\n System.out.println(count);\n } catch (Exception e) {\n System.out.println(e);\n }\n }\n\n public static void main(String[] args) throws Exception {\n Config config = Config.load();\n\n listRegions(config);\n }\n } \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/java/src/main/java/shopping/merchant/samples/accounts/regions/v1/ListRegionsSample.java\n\n### PHP\n\n \u003c?php\n /**\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n require_once __DIR__ . '/../../../../vendor/autoload.php';\n require_once __DIR__ . '/../../../Authentication/Authentication.php';\n require_once __DIR__ . '/../../../Authentication/Config.php';\n use Google\\ApiCore\\ApiException;\n use Google\\Shopping\\Merchant\\Accounts\\V1\\Client\\RegionsServiceClient;\n use Google\\Shopping\\Merchant\\Accounts\\V1\\ListRegionsRequest;\n\n /**\n * This class demonstrates how to list all the regions for a given Merchant Center account.\n */\n class ListRegionsSample\n {\n\n private static function getParent(string $accountId): string\n {\n return sprintf(\"accounts/%s\", $accountId);\n }\n\n public static function listRegionsSample(array $config): void\n {\n // Gets the OAuth credentials to make the request.\n $credentials = Authentication::useServiceAccountOrTokenFile();\n\n // Creates options config containing credentials for the client to use.\n $options = ['credentials' =\u003e $credentials];\n\n // Creates a client.\n $regionsServiceClient = new RegionsServiceClient($options);\n\n // Creates parent to identify the account from which to list all regions.\n $parent = self::getParent($config['accountId']);\n\n try {\n $request = new ListRegionsRequest([\n 'parent' =\u003e $parent\n ]);\n\n print \"Sending list regions request:\\n\";\n $response = $regionsServiceClient-\u003elistRegions($request);\n\n $count = 0;\n foreach ($response-\u003eiterateAllElements() as $element) {\n print $element-\u003egetName() . PHP_EOL;\n $count++;\n }\n print \"The following count of elements were returned: \";\n print $count . PHP_EOL;\n\n } catch (ApiException $e) {\n print $e-\u003egetMessage();\n }\n }\n\n public function callSample(): void\n {\n $config = Config::generateConfig();\n self::listRegionsSample($config);\n }\n }\n\n $sample = new ListRegionsSample();\n $sample-\u003ecallSample(); \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/php/examples/accounts/regions/v1/ListRegionsSample.php\n\n### Python\n\n # -*- coding: utf-8 -*-\n # Copyright 2024 Google LLC\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # http://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \"\"\"A module to list all the Regions for a given Merchant Center account.\"\"\"\n\n from examples.authentication import configuration\n from examples.authentication import generate_user_credentials\n from google.shopping.merchant_accounts_v1 import ListRegionsRequest\n from google.shopping.merchant_accounts_v1 import RegionsServiceClient\n\n _ACCOUNT = configuration.Configuration().read_merchant_info()\n\n\n def get_parent(account_id):\n return f\"accounts/{account_id}\"\n\n\n def list_regions():\n \"\"\"Lists all the regions for a given Merchant Center account.\"\"\"\n\n # Gets OAuth Credentials.\n credentials = generate_user_credentials.main()\n\n # Creates a client.\n client = RegionsServiceClient(credentials=credentials)\n\n # Creates parent to identify the account from which to list all regions.\n parent = get_parent(_ACCOUNT)\n\n # Creates the request.\n request = ListRegionsRequest(parent=parent)\n\n # Makes the request and catches and prints any error messages.\n try:\n response = client.list_regions(request=request)\n count = 0\n print(\"Sending list regions request:\")\n for element in response:\n print(element)\n count += 1\n print(f\"The following count of elements were returned: {count}\")\n\n except RuntimeError as e:\n print(\"List region request failed!\")\n print(e)\n\n\n if __name__ == \"__main__\":\n list_regions()\n\n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/python/examples/accounts/regions/v1/list_regions_sample.py"]]