Metoda accounts.list
umożliwia pobieranie listy zasobów
Account, do których
uwierzytelniony użytkownik ma dostęp. Możesz użyć parametru zapytania filter, aby zawęzić wyniki na podstawie różnych kryteriów, takich jak:
- właściwości konta,
- relacje z innymi kontami (np. dostawcy w zaawansowanej strukturze konta),
- usługi powiązane z kontami.
Może to być przydatne do zarządzania wieloma kontami lub znajdowania konkretnych kont firmowych, które spełniają określone warunki.
Aby filtrować na poziomie account, możesz użyć tych pól:
access: filtruje według typu dostępu użytkownika doaccount. Ten filtr akceptuje te wartości:DIRECT: zwraca tylko konta, do których użytkownik ma bezpośredni dostęp. Są to konta, do których użytkownik został dodany bezpośrednio.INDIRECT: zwraca tylko konta, do których użytkownik ma pośredni dostęp. Są to konta, do których użytkownik ma dostęp, mimo że nie jest użytkownikiem tego konta. Na przykład użytkownik konta zbiorczego będzie miał dostęp „INDIRECT” do konta podrzędnego tego konta zbiorczego. Podobnie użytkownicy usługi porównywania cen będą mieli pośredni dostęp do kont współpracujących z tą usługą.ALL: zwraca wszystkie konta, do których użytkownik ma dostęp (bezpośredni i pośredni). Jeśli filtr nie jest określony, jest to zachowanie domyślne.
capabilities: filtruje wedługcapabilitieszasobuaccount(pamiętaj, że to pole nie jest dostępne w samym zasobie). Obsługiwana jest tylko funkcjaCAN_UPLOAD_PRODUCTS. To pole obsługuje negację i używa składni kolekcji.relationship(...): filtruje według typu relacji konta z innym kontem. W jednym żądaniu możesz uwzględnić kilka filtrówrelationship(...).accountName: filtruje wedługaccountNamezasobuaccount.
Więcej informacji o składni filtra znajdziesz w przewodniku Składnia filtra.
Przykłady
Z tych przykładów dowiesz się, jak tworzyć najczęstsze zapytania. Wszystkie poniższe przykłady używają metody accounts.list. Więcej informacji znajdziesz w
accounts.list
dokumentacji referencyjnej.
Znajdowanie kont podrzędnych konkretnego dostawcy
Metoda
accounts.listSubaccounts
umożliwia bezpośrednie wyświetlanie listy kont podrzędnych. Możesz też użyć funkcji filtrowania opisanych w kolejnych sekcjach. Jeśli zarządzasz zaawansowanym kontem, możesz wyświetlić listę wszystkich jego kont podrzędnych, filtrując według providerId. Zastąp PROVIDER_ID identyfikatorem zaawansowanego konta.
Na przykład jeśli identyfikator dostawcy to
123, użyj relationship(providerId=123).
Jest to przydatne do zarządzania strukturą kont.
GET https://merchantapi.googleapis.com/accounts/v1/accounts?filter=relationship(providerId%20%3D%20PROVIDER_ID)
Pomyślne żądanie zwraca kod stanu 200 i treść odpowiedzi z listą pasujących kont podrzędnych:
{
"accounts": [
{
"name": "accounts/77777",
"accountId": "77777",
"accountName": "SubAccount A of Provider",
"adultContent": false,
"languageCode": "fr",
"timeZone": {
"id": "Europe/Paris"
}
},
{
"name": "accounts/88888",
"accountId": "88888",
"accountName": "SubAccount B of Provider",
"adultContent": false,
"languageCode": "de",
"timeZone": {
"id": "Europe/Berlin"
}
}
],
"nextPageToken": "XYZ123abcDEF..."
}
Znajdowanie kont, na których nie można przesyłać produktów
Możesz połączyć kilka warunków filtra, aby utworzyć bardziej szczegółowe wyszukiwania.
Filtr accountName=*store* AND -capabilities:CAN_UPLOAD_PRODUCTS znajduje wszystkie konta, które w nazwie mają „store” i nie są skonfigurowane do bezpośredniego przesyłania produktów. Znak - przed capabilities działa jako operator negacji. Może to być przydatne do pobierania tylko zaawansowanych kont.
GET https://merchantapi.googleapis.com/accounts/v1/accounts?filter=accountName%20%3D%20%22*store*%22%20AND%20-capabilities%3ACAN_UPLOAD_PRODUCTS
Pomyślne żądanie zwraca kod stanu 200 i treść odpowiedzi z listą pasujących kont:
{
"accounts": [
{
"name": "accounts/54321",
"accountId": "54321",
"accountName": "Partner Store - US",
"adultContent": false,
"languageCode": "en",
"timeZone": {
"id": "America/New_York"
}
},
{
"name": "accounts/98765",
"accountId": "98765",
"accountName": "Auxiliary Brand Store",
"adultContent": false,
"languageCode": "fr",
"timeZone": {
"id": "Europe/Paris"
}
}
],
"nextPageToken": "CDEfghIJKlmnOPQ..."
}
Znajdowanie kont według nazwy
Możesz wyszukiwać konta, których nazwa wyświetlana pasuje do określonego wzorca.
Na przykład accountName=*store* znajdzie wszystkie konta, które w nazwie mają „store”.
Ułatwia to szybkie znajdowanie konkretnych kont firmowych.
GET https://merchantapi.googleapis.com/accounts/v1/accounts?filter=accountName%20%3D%20%22*store*%22
Pomyślne żądanie zwraca kod stanu 200 i treść odpowiedzi z listą pasujących kont:
{
"accounts": [
{
"name": "accounts/12345",
"accountId": "12345",
"accountName": "My Awesome Store",
"adultContent": false,
"languageCode": "en",
"timeZone": {
"id": "America/Los_Angeles"
}
},
{
"name": "accounts/67890",
"accountId": "67890",
"accountName": "Another Store Online",
"adultContent": false,
"languageCode": "en",
"timeZone": {
"id": "Europe/London"
}
}
],
"nextPageToken": "ABSdefGHIjklMNO..."
}
Znajdowanie kont powiązanych z dostawcą w przypadku konkretnej usługi
Możesz znaleźć konta, które mają określoną relację z dostawcą.
Aby na przykład znaleźć wszystkie konta zagregowane na koncie dostawcy PROVIDER_ID na potrzeby agregacji kont, użyj filtra
relationship(providerId=PROVIDER_ID) AND
service(type="ACCOUNT_AGGREGATION").
GET https://merchantapi.googleapis.com/accounts/v1/accounts?filter=relationship(providerId%20%3D%20PROVIDER_ID%20AND%20service(type%20%3D%20%22ACCOUNT_AGGREGATION%22))
Pomyślne żądanie zwraca kod stanu 200 i treść odpowiedzi z listą pasujących kont:
{
"accounts": [
{
"name": "accounts/54321",
"accountId": "54321",
"accountName": "Aggregated Account X",
"adultContent": false,
"languageCode": "en",
"timeZone": {
"id": "America/New_York"
}
}
]
}
Znajdowanie kont na podstawie stanu zatwierdzenia relacji z usługą
Możesz filtrować konta na podstawie stanu ich relacji z dostawcą. Aby na przykład znaleźć wszystkie konta, które nie zaakceptowały prośby o połączenie konta
(handshakeState = "PENDING")od konkretnego dostawcy PROVIDER_ID.
Aby na przykład znaleźć konta, na których identyfikator dostawcy to 123, typ usługi
to ACCOUNT_MANAGEMENT, a stan to PENDING, użyj
relationship(service(handshakeState = "PENDING" AND type =
"ACCOUNT_MANAGEMENT") AND providerId = 123).
GET https://merchantapi.googleapis.com/accounts/v1/accounts?filter=relationship(service(handshakeState%20%3D%20%22PENDING%22%20AND%20type%20%3D%20%22ACCOUNT_MANAGEMENT%22)%20AND%20providerId%20%3D%20PROVIDER_ID)
Pomyślne żądanie zwraca kod stanu 200 i treść odpowiedzi z listą pasujących kont:
{
"accounts": [
{
"name": "accounts/98765",
"accountId": "98765",
"accountName": "Managed Account Y",
"adultContent": false,
"languageCode": "es",
"timeZone": {
"id": "Europe/Madrid"
}
}
]
}
Filtrowanie kont za pomocą bibliotek klienta
Z tych przykładów dowiesz się, jak używać bibliotek klienta do filtrowania kont na podstawie połączonych kryteriów, takich jak nazwa konta i relacja z dostawcą. Te przykłady używają metody accounts.list. Więcej informacji,
zobacz
accounts.list
dokumentację referencyjną.
Java
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.Account;
import com.google.shopping.merchant.accounts.v1.AccountsServiceClient;
import com.google.shopping.merchant.accounts.v1.AccountsServiceClient.ListAccountsPagedResponse;
import com.google.shopping.merchant.accounts.v1.AccountsServiceSettings;
import com.google.shopping.merchant.accounts.v1.ListAccountsRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to filter the accounts the user making the request has access to. */
public class FilterAccountsSample {
public static void filterAccounts(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.
AccountsServiceSettings accountsServiceSettings =
AccountsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
// Calls the API and catches and prints any network failures/errors.
try (AccountsServiceClient accountsServiceClient =
AccountsServiceClient.create(accountsServiceSettings)) {
// Filter for accounts with display names containing "store" and a provider with the ID "123":
String filter = "accountName = \"*store*\" AND relationship(providerId = 123)";
// Filter for all subaccounts of account "123":
// String filter2 = "relationship(providerId = 123 AND service(type =
// \"ACCOUNT_AGGREGATION\"))";
// String filter3 = "relationship(service(handshakeState = \"APPROVED\" AND type =
// \"ACCOUNT_MANAGEMENT\") AND providerId = 123)";
ListAccountsRequest request = ListAccountsRequest.newBuilder().setFilter(filter).build();
System.out.println("Sending list accounts request with filter:");
ListAccountsPagedResponse response = accountsServiceClient.listAccounts(request);
int count = 0;
// Iterates over all rows in all pages and prints the sub-account
// in each row.
// `response.iterateAll()` automatically uses the `nextPageToken` and recalls the
// request to fetch all pages of data.
for (Account account : response.iterateAll()) {
System.out.println(account);
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();
filterAccounts(config);
}
}
PHP
use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1\Client\AccountsServiceClient;
use Google\Shopping\Merchant\Accounts\V1\ListAccountsRequest;
/**
* This class demonstrates how to filter the accounts the user making the request has access to.
*/
class FilterAccounts
{
public static function filterAccounts(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.
$accountsServiceClient = new AccountsServiceClient($options);
// Calls the API and catches and prints any network failures/errors.
try {
// Filter for accounts with display names containing "store" and a provider with the ID "123":
$filter = "accountName = \"*store*\" AND relationship(providerId = 123)";
// Filter for all subaccounts of account "123":
// $filter = "relationship(providerId = 123 AND service(type = \"ACCOUNT_AGGREGATION\"))";
// $filter = "relationship(service(handshakeState = \"APPROVED\" AND type =
// \"ACCOUNT_MANAGEMENT\") AND providerId = 123)";
$request = new ListAccountsRequest(['filter' => $filter]);
print "Sending list accounts request with filter:\n";
$response = $accountsServiceClient->listAccounts($request);
$count = 0;
// Iterates over all rows in all pages and prints the sub-account
// in each row.
// `response.iterateAll()` automatically uses the `nextPageToken` and recalls the
// request to fetch all pages of data.
foreach ($response->iterateAllElements() as $account) {
print_r($account);
$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::filterAccounts($config);
}
}
$sample = new FilterAccounts();
$sample->callSample();
Python
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import AccountsServiceClient
from google.shopping.merchant_accounts_v1 import ListAccountsRequest
def filter_accounts():
"""Filters the accounts the user making the request has access to."""
# Get OAuth credentials.
credentials = generate_user_credentials.main()
# Create a client.
client = AccountsServiceClient(credentials=credentials)
# Create the filter string.
filter_string = 'accountName = "*store*" AND relationship(providerId = 123)'
# Create the request.
request = ListAccountsRequest(filter=filter_string)
# Make the request and print the response.
try:
print("Sending list accounts request with filter:")
response = client.list_accounts(request=request)
count = 0
for account in response:
print(account)
count += 1
print(f"The following count of elements were returned: {count}")
except RuntimeError as e:
print(e)
if __name__ == "__main__":
filter_accounts()
AppsScript
/**
* Filters and lists accounts for which the logged-in user has access to
*/
function filterAccounts() {
// IMPORTANT:
// Enable the Merchant API Accounts sub-API Advanced Service and call it
// "MerchantApiAccounts"
// Create the filter string.
// Documentation can be found at
// https://developers.google.com/merchant/api/guides/accounts/filter-syntax
const filter = 'accountName = "*store*" AND relationship(providerId = 123)';
try {
console.log('Sending filter Accounts request');
let pageToken;
const pageSize = 500;
// Call the Accounts.list API method with a filter. Use the pageToken to iterate through
// all pages of results.
do {
const response =
MerchantApiAccounts.Accounts.list({pageSize, pageToken, filter});
for (const account of response.accounts) {
console.log(account);
}
pageToken = response.nextPageToken;
} while (pageToken); // Exits when there is no next page token.
} catch (e) {
console.log('ERROR!');
console.log(e);
}
}
cURL
curl --location 'https://merchantapi.googleapis.com/accounts/v1/accounts?filter=accountName%20%3D%20%22*store*%22%20AND%20relationship(providerId%20%3D%20PROVIDER_ID)' \
--header 'Authorization: Bearer API_TOKEN'