列出促销活动
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
用于列出促销活动信息的 Merchant API 代码示例。
Java
// Copyright 2023 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.promotions.v1;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.promotions.v1.ListPromotionsRequest;
import com.google.shopping.merchant.promotions.v1.Promotion;
import com.google.shopping.merchant.promotions.v1.PromotionsServiceClient;
import com.google.shopping.merchant.promotions.v1.PromotionsServiceClient.ListPromotionsPagedResponse;
import com.google.shopping.merchant.promotions.v1.PromotionsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to list promotions. */
public class ListPromotionsSample {
public static void listPromotions(String accountId) throws Exception {
GoogleCredentials credential = new Authenticator().authenticate();
PromotionsServiceSettings promotionsServiceSettings =
PromotionsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
try (PromotionsServiceClient promotionsServiceClient =
PromotionsServiceClient.create(promotionsServiceSettings)) {
ListPromotionsRequest request =
ListPromotionsRequest.newBuilder()
.setParent(String.format("accounts/%s", accountId))
.build();
System.out.println("Sending list promotions request:");
ListPromotionsPagedResponse response = promotionsServiceClient.listPromotions(request);
int count = 0;
// Iterates over all rows in all pages and prints the datasource in each row.
// Automatically uses the `nextPageToken` if returned to fetch all pages of data.
for (Promotion promotion : response.iterateAll()) {
System.out.println(promotion);
count++;
}
System.out.print("The following count of promotions were returned: ");
System.out.println(count);
} catch (Exception e) {
System.out.println("Failed to list promotions.");
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
listPromotions(config.getAccountId().toString());
}
}
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\Promotions\V1\ListPromotionsRequest;
use Google\Shopping\Merchant\Promotions\V1\Promotion;
use Google\Shopping\Merchant\Promotions\V1\Client\PromotionsServiceClient;
/**
* This class demonstrates how to list promotions.
*/
class ListPromotions
{
/**
* Lists promotions for the given account.
*
* @param array $config
* The configuration data used for authentication and getting the account ID.
* @return void
*/
public static function listPromotionsSample($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.
$promotionsServiceClient = new PromotionsServiceClient($options);
try {
// Creates the request.
$request = new ListPromotionsRequest([
'parent' => sprintf('accounts/%s', $config['accountId']),
]);
print "Sending list promotions request:\n";
// Makes the request.
$response = $promotionsServiceClient->listPromotions($request);
$count = 0;
// Iterates over all promotions returned in the response.
foreach ($response->iterateAllElements() as $promotion) {
print_r($promotion);
$count++;
}
printf("The following count of promotions were returned: %s\n", $count);
} catch (ApiException $e) {
printf("Failed to list promotions.\n");
print $e->getMessage();
}
}
/**
* Helper to execute the sample.
*
* @return void
*/
public function callSample(): void
{
$config = Config::generateConfig();
// Makes the call to list promotions.
self::listPromotionsSample($config);
}
}
// Run the script
$sample = new ListPromotions();
$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 for listing Promotions."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_promotions_v1 import ListPromotionsRequest
from google.shopping.merchant_promotions_v1 import PromotionsServiceClient
_ACCOUNT = configuration.Configuration().read_merchant_info()
_PARENT = f"accounts/{_ACCOUNT}"
def list_promotions():
"""Lists promotions for the given account."""
# Gets OAuth Credentials.
credentials = generate_user_credentials.main()
# Creates a client.
client = PromotionsServiceClient(credentials=credentials)
# Creates the request.
request = ListPromotionsRequest(parent=_PARENT)
# Makes the request and prints the results.
try:
print("Sending list promotions request:")
response = client.list_promotions(request=request)
count = 0
# Iterates over all returned promotions and prints them.
for promotion in response.promotions:
print(promotion)
count += 1
print(f"The following count of promotions were returned: {count}")
except RuntimeError as e:
print("Failed to list promotions.")
print(e)
if __name__ == "__main__":
list_promotions()
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-21。
[null,null,["最后更新时间 (UTC):2025-08-21。"],[[["\u003cp\u003eThis webpage provides code samples in Java, PHP, and Python demonstrating how to list promotions using the Merchant API.\u003c/p\u003e\n"],["\u003cp\u003eThe code examples showcase the use of the \u003ccode\u003eListPromotionsRequest\u003c/code\u003e to retrieve a list of promotions associated with a specific account.\u003c/p\u003e\n"],["\u003cp\u003eEach code sample iterates through the returned promotions and prints the details and count, offering a way to see all promotions for a merchant.\u003c/p\u003e\n"],["\u003cp\u003eThe Java, PHP, and Python samples include instructions for handling authentication, creating the request, and processing the response from the Promotions Service.\u003c/p\u003e\n"]]],["The provided code samples demonstrate listing promotions using the Merchant API in Java, PHP, and Python. Each sample authenticates using credentials, initializes a `PromotionsServiceClient`, and constructs a `ListPromotionsRequest` with the account ID. The client then sends the request, iterates through the `Promotion` objects in the response, and prints each `promotion` and the total count returned. The process will catch errors if any promotions are not listed.\n"],null,["# List promotions\n\nMerchant API code sample to list promotions. \n\n### Java\n\n\n // Copyright 2023 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.promotions.v1;\n import com.google.api.gax.core.FixedCredentialsProvider;\n import com.google.auth.oauth2.GoogleCredentials;\n import com.google.shopping.merchant.promotions.v1.ListPromotionsRequest;\n import com.google.shopping.merchant.promotions.v1.Promotion;\n import com.google.shopping.merchant.promotions.v1.PromotionsServiceClient;\n import com.google.shopping.merchant.promotions.v1.PromotionsServiceClient.ListPromotionsPagedResponse;\n import com.google.shopping.merchant.promotions.v1.PromotionsServiceSettings;\n import shopping.merchant.samples.utils.Authenticator;\n import shopping.merchant.samples.utils.Config;\n\n /** This class demonstrates how to list promotions. */\n public class ListPromotionsSample {\n\n public static void listPromotions(String accountId) throws Exception {\n GoogleCredentials credential = new Authenticator().authenticate();\n\n PromotionsServiceSettings promotionsServiceSettings =\n PromotionsServiceSettings.newBuilder()\n .setCredentialsProvider(FixedCredentialsProvider.create(credential))\n .build();\n\n try (PromotionsServiceClient promotionsServiceClient =\n PromotionsServiceClient.create(promotionsServiceSettings)) {\n\n ListPromotionsRequest request =\n ListPromotionsRequest.newBuilder()\n .setParent(String.format(\"accounts/%s\", accountId))\n .build();\n\n System.out.println(\"Sending list promotions request:\");\n ListPromotionsPagedResponse response = promotionsServiceClient.listPromotions(request);\n\n int count = 0;\n\n // Iterates over all rows in all pages and prints the datasource in each row.\n // Automatically uses the `nextPageToken` if returned to fetch all pages of data.\n for (Promotion promotion : response.iterateAll()) {\n System.out.println(promotion);\n count++;\n }\n System.out.print(\"The following count of promotions were returned: \");\n System.out.println(count);\n\n } catch (Exception e) {\n System.out.println(\"Failed to list promotions.\");\n System.out.println(e);\n }\n }\n\n public static void main(String[] args) throws Exception {\n Config config = Config.load();\n listPromotions(config.getAccountId().toString());\n }\n } \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/java/src/main/java/shopping/merchant/samples/promotions/v1/ListPromotionsSample.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\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\\Promotions\\V1\\ListPromotionsRequest;\n use Google\\Shopping\\Merchant\\Promotions\\V1\\Promotion;\n use Google\\Shopping\\Merchant\\Promotions\\V1\\Client\\PromotionsServiceClient;\n\n /**\n * This class demonstrates how to list promotions.\n */\n class ListPromotions\n {\n\n /**\n * Lists promotions for the given account.\n *\n * @param array $config\n * The configuration data used for authentication and getting the account ID.\n * @return void\n */\n public static function listPromotionsSample($config): void\n {\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 $promotionsServiceClient = new PromotionsServiceClient($options);\n\n try {\n // Creates the request.\n $request = new ListPromotionsRequest([\n 'parent' =\u003e sprintf('accounts/%s', $config['accountId']),\n ]);\n\n print \"Sending list promotions request:\\n\";\n\n // Makes the request.\n $response = $promotionsServiceClient-\u003elistPromotions($request);\n\n $count = 0;\n\n // Iterates over all promotions returned in the response.\n foreach ($response-\u003eiterateAllElements() as $promotion) {\n print_r($promotion);\n $count++;\n }\n printf(\"The following count of promotions were returned: %s\\n\", $count);\n } catch (ApiException $e) {\n printf(\"Failed to list promotions.\\n\");\n print $e-\u003egetMessage();\n }\n }\n\n\n /**\n * Helper to execute the sample.\n *\n * @return void\n */\n public function callSample(): void\n {\n $config = Config::generateConfig();\n\n // Makes the call to list promotions.\n self::listPromotionsSample($config);\n }\n }\n\n\n // Run the script\n $sample = new ListPromotions();\n $sample-\u003ecallSample(); \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/php/examples/promotions/v1/ListPromotionsSample.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 for listing Promotions.\"\"\"\n\n from examples.authentication import configuration\n from examples.authentication import generate_user_credentials\n from google.shopping.merchant_promotions_v1 import ListPromotionsRequest\n from google.shopping.merchant_promotions_v1 import PromotionsServiceClient\n\n _ACCOUNT = configuration.Configuration().read_merchant_info()\n _PARENT = f\"accounts/{_ACCOUNT}\"\n\n\n def list_promotions():\n \"\"\"Lists promotions for the given account.\"\"\"\n\n # Gets OAuth Credentials.\n credentials = generate_user_credentials.main()\n\n # Creates a client.\n client = PromotionsServiceClient(credentials=credentials)\n\n # Creates the request.\n request = ListPromotionsRequest(parent=_PARENT)\n\n # Makes the request and prints the results.\n try:\n print(\"Sending list promotions request:\")\n response = client.list_promotions(request=request)\n\n count = 0\n\n # Iterates over all returned promotions and prints them.\n for promotion in response.promotions:\n print(promotion)\n count += 1\n print(f\"The following count of promotions were returned: {count}\")\n\n except RuntimeError as e:\n print(\"Failed to list promotions.\")\n print(e)\n\n\n if __name__ == \"__main__\":\n list_promotions()\n\n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/python/examples/promotions/v1/list_promotions_sample.py"]]