列出用户
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
用于列出用户的 Merchant API 代码示例。
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.users.v1;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.ListUsersRequest;
import com.google.shopping.merchant.accounts.v1.User;
import com.google.shopping.merchant.accounts.v1.UserServiceClient;
import com.google.shopping.merchant.accounts.v1.UserServiceClient.ListUsersPagedResponse;
import com.google.shopping.merchant.accounts.v1.UserServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to list all the users for a given Merchant Center account. */
public class ListUsersSample {
private static String getParent(String accountId) {
return String.format("accounts/%s", accountId);
}
public static void listUsers(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.
UserServiceSettings userServiceSettings =
UserServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
// Creates parent to identify the account from which to list all users.
String parent = getParent(config.getAccountId().toString());
// Calls the API and catches and prints any network failures/errors.
try (UserServiceClient userServiceClient = UserServiceClient.create(userServiceSettings)) {
// The parent has the format: accounts/{account}
ListUsersRequest request = ListUsersRequest.newBuilder().setParent(parent).build();
System.out.println("Sending list users request:");
ListUsersPagedResponse response = userServiceClient.listUsers(request);
int count = 0;
// Iterates over all rows in all pages and prints the user
// in each row.
// `response.iterateAll()` automatically uses the `nextPageToken` and recalls the
// request to fetch all pages of data.
for (User 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();
listUsers(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.
*/
/**
* Demonstrates how to list all the users for a given Merchant Center account.
*/
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\ListUsersRequest;
use Google\Shopping\Merchant\Accounts\V1\Client\UserServiceClient;
/**
* Lists users.
*
* @param array $config The configuration data.
* @return void
*/
function listUsers($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.
$userServiceClient = new UserServiceClient($options);
// Creates parent to identify the account from which to list all users.
$parent = sprintf("accounts/%s", $config['accountId']);
// Calls the API and catches and prints any network failures/errors.
try {
$request = new ListUsersRequest(['parent' => $parent]);
print "Sending list users request:\n";
$response = $userServiceClient->listUsers($request);
$count = 0;
foreach ($response->iterateAllElements() as $element) {
print_r($element);
$count++;
}
print "The following count of elements were returned: ";
print $count . "\n";
} catch (ApiException $e) {
print $e->getMessage();
}
}
$config = Config::generateConfig();
listUsers($config);
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 users."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import ListUsersRequest
from google.shopping.merchant_accounts_v1 import UserServiceClient
_ACCOUNT = configuration.Configuration().read_merchant_info()
def get_parent(account_id):
return f"accounts/{account_id}"
def list_users():
"""Lists all the users for a given Merchant Center account."""
# Get OAuth credentials
credentials = generate_user_credentials.main()
# Create a UserServiceClient
client = UserServiceClient(credentials=credentials)
# Create parent string
parent = get_parent(_ACCOUNT)
# Create the request
request = ListUsersRequest(parent=parent)
try:
print("Sending list users request:")
response = client.list_users(request=request)
count = 0
for element in response:
print(element)
count += 1
print("The following count of elements were returned: ")
print(count)
except RuntimeError as e:
print(e)
if __name__ == "__main__":
list_users()
如未另行说明,那么本页面中的内容已根据知识共享署名 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 all users associated with a specific Merchant Center account.\u003c/p\u003e\n"],["\u003cp\u003eThe code examples utilize the Merchant API to create a \u003ccode\u003eListUsersRequest\u003c/code\u003e and retrieve a \u003ccode\u003eListUsersPagedResponse\u003c/code\u003e or equivalent response object to get users.\u003c/p\u003e\n"],["\u003cp\u003eEach code sample authenticates using OAuth credentials and configures a \u003ccode\u003eUserServiceClient\u003c/code\u003e or equivalent before making the API request.\u003c/p\u003e\n"],["\u003cp\u003eThe provided code demonstrates iterating over the API response to print and count the users retrieved from the account.\u003c/p\u003e\n"]]],["The code samples demonstrate listing all users for a Merchant Center account using the Merchant API in Java, PHP, and Python. Each sample authenticates via OAuth, creates a `UserServiceClient`, and defines the account parent. They then construct a `ListUsersRequest` and send it to the API. Finally, they iterate through the API's paged response, printing each user and the total count, handling any network or API exceptions.\n"],null,["# List users\n\nMerchant API code sample to list users. \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.users.v1;\n import com.google.api.gax.core.FixedCredentialsProvider;\n import com.google.auth.oauth2.GoogleCredentials;\n import com.google.shopping.merchant.accounts.v1.ListUsersRequest;\n import com.google.shopping.merchant.accounts.v1.User;\n import com.google.shopping.merchant.accounts.v1.UserServiceClient;\n import com.google.shopping.merchant.accounts.v1.UserServiceClient.ListUsersPagedResponse;\n import com.google.shopping.merchant.accounts.v1.UserServiceSettings;\n import shopping.merchant.samples.utils.Authenticator;\n import shopping.merchant.samples.utils.Config;\n\n /** This class demonstrates how to list all the users for a given Merchant Center account. */\n public class ListUsersSample {\n\n private static String getParent(String accountId) {\n return String.format(\"accounts/%s\", accountId);\n }\n\n public static void listUsers(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 UserServiceSettings userServiceSettings =\n UserServiceSettings.newBuilder()\n .setCredentialsProvider(FixedCredentialsProvider.create(credential))\n .build();\n\n // Creates parent to identify the account from which to list all users.\n String parent = getParent(config.getAccountId().toString());\n\n // Calls the API and catches and prints any network failures/errors.\n try (UserServiceClient userServiceClient = UserServiceClient.create(userServiceSettings)) {\n\n // The parent has the format: accounts/{account}\n ListUsersRequest request = ListUsersRequest.newBuilder().setParent(parent).build();\n\n System.out.println(\"Sending list users request:\");\n ListUsersPagedResponse response = userServiceClient.listUsers(request);\n\n int count = 0;\n\n // Iterates over all rows in all pages and prints the user\n // in each row.\n // `response.iterateAll()` automatically uses the `nextPageToken` and recalls the\n // request to fetch all pages of data.\n for (User 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 listUsers(config);\n }\n } \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/java/src/main/java/shopping/merchant/samples/accounts/users/v1/ListUsersSample.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 * Demonstrates how to list all the users for a given Merchant Center account.\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\\Accounts\\V1\\ListUsersRequest;\n use Google\\Shopping\\Merchant\\Accounts\\V1\\Client\\UserServiceClient;\n\n\n /**\n * Lists users.\n *\n * @param array $config The configuration data.\n * @return void\n */\n function listUsers($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 $userServiceClient = new UserServiceClient($options);\n\n // Creates parent to identify the account from which to list all users.\n $parent = sprintf(\"accounts/%s\", $config['accountId']);\n\n // Calls the API and catches and prints any network failures/errors.\n try {\n $request = new ListUsersRequest(['parent' =\u003e $parent]);\n\n print \"Sending list users request:\\n\";\n $response = $userServiceClient-\u003elistUsers($request);\n\n $count = 0;\n foreach ($response-\u003eiterateAllElements() as $element) {\n print_r($element);\n $count++;\n }\n print \"The following count of elements were returned: \";\n print $count . \"\\n\";\n } catch (ApiException $e) {\n print $e-\u003egetMessage();\n }\n }\n\n\n $config = Config::generateConfig();\n listUsers($config); \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/php/examples/accounts/users/v1/ListUsersSample.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 users.\"\"\"\n\n\n from examples.authentication import configuration\n from examples.authentication import generate_user_credentials\n from google.shopping.merchant_accounts_v1 import ListUsersRequest\n from google.shopping.merchant_accounts_v1 import UserServiceClient\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_users():\n \"\"\"Lists all the users for a given Merchant Center account.\"\"\"\n\n # Get OAuth credentials\n credentials = generate_user_credentials.main()\n\n # Create a UserServiceClient\n client = UserServiceClient(credentials=credentials)\n\n # Create parent string\n parent = get_parent(_ACCOUNT)\n\n # Create the request\n request = ListUsersRequest(parent=parent)\n\n try:\n print(\"Sending list users request:\")\n response = client.list_users(request=request)\n\n count = 0\n for element in response:\n print(element)\n count += 1\n\n print(\"The following count of elements were returned: \")\n print(count)\n\n except RuntimeError as e:\n print(e)\n\n\n if __name__ == \"__main__\":\n list_users()\n\n\n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/python/examples/accounts/users/v1/list_users_sample.py"]]