アクセスできるアカウントをフィルタする

accounts.list メソッドを使用すると、認証されたユーザーがアクセスできる Account リソースのリストを取得できます。filter クエリ パラメータを使用すると、次のようなさまざまな条件に基づいて結果を絞り込むことができます。

  • アカウントのプロパティ
  • 他のアカウントとの関係(高度なアカウント構造のプロバイダなど)
  • アカウントに関連付けられているサービス

これは、複数のアカウントを管理したり、特定の条件を満たす特定のアカウントを見つけたりするのに役立ちます。

次のフィールドを使用して、account レベルでフィルタできます。

  • access: ユーザーが account に対して持つアクセス権の種類でフィルタします。このフィルタでは、次の値を使用できます。
    • DIRECT: ユーザーが直接アクセスできるアカウントのみを返します。
    • INDIRECT: ユーザーが間接的にアクセスできるアカウントのみを返します。
    • ALL: ユーザーがアクセスできるすべてのアカウント(直接アクセスと間接アクセスの両方)を返します。フィルタが指定されていない場合、この動作がデフォルトになります。
  • capabilities: account リソースの capabilities でフィルタします(このフィールドはリソース自体では使用できません)。CAN_UPLOAD_PRODUCTS 機能のみがサポートされています。このフィールドは否定をサポートし、コレクション構文を使用します。
  • relationship(...): アカウントと別のアカウントの関係の種類でフィルタします。1 つのリクエストに複数の relationship(...) フィルタを含めることができます。
  • accountName: account リソースの accountName でフィルタします。

フィルタ構文の詳細については、フィルタ構文ガイドをご覧ください。

次の例では、最も一般的なクエリを作成する方法について説明します。次の例ではすべて、accounts.list メソッドを使用します。詳細については、accounts.list リファレンス ドキュメントをご覧ください。

特定のプロバイダのサブアカウントを見つける

accounts.listSubaccounts メソッドは、サブアカウントを直接一覧表示する方法を提供します。次のセクションで説明するように、フィルタリング機能を使用することもできます。高度なアカウントを管理している場合は、providerId でフィルタして、すべての子アカウントを一覧表示できます。PROVIDER_ID は、アドバンス アカウントの ID に置き換えます。

たとえば、プロバイダの ID が 123 の場合は、relationship(providerId=123) を使用します。

これは、アカウントの構造を管理するのに役立ちます。

GET https://merchantapi.googleapis.com/accounts/v1/accounts?filter=relationship(providerId%20%3D%20PROVIDER_ID)

リクエストが成功すると、200 ステータス コードと、一致するサブアカウントのリストを含むレスポンス本文が返されます。

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

商品をアップロードできないアカウントを確認する

複数のフィルタ条件を組み合わせて、より具体的な検索を行うことができます。

フィルタ accountName=*store* AND -capabilities:CAN_UPLOAD_PRODUCTS は、名前に「store」が含まれていて、商品を直接アップロードするように設定されていないすべてのアカウントを検索します。capabilities の前の - は否定演算子として機能します。これは、高度なアカウントのみを取得する場合に便利です。

GET https://merchantapi.googleapis.com/accounts/v1/accounts?filter=accountName%20%3D%20%22*store*%22%20AND%20-capabilities%3ACAN_UPLOAD_PRODUCTS

リクエストが成功すると、200 ステータス コードと、一致するアカウントのリストを含むレスポンス本文が返されます。

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

名前でアカウントを検索する

表示名が特定のパターンに一致するアカウントを検索できます。

たとえば、accountName=*store* と入力すると、名前に「store」が含まれるすべてのアカウントが検索されます。

これにより、特定のビジネス アカウントをすばやく見つけることができます。

GET https://merchantapi.googleapis.com/accounts/v1/accounts?filter=accountName%20%3D%20%22*store*%22

リクエストが成功すると、200 ステータス コードと、一致するアカウントのリストを含むレスポンス本文が返されます。

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

特定のサービスのプロバイダにリンクされているアカウントを見つける

プロバイダとの特定のサービス関係を持つアカウントを見つけることができます。たとえば、アカウントの集計でプロバイダ PROVIDER_ID に集計されたすべてのアカウントを見つけるには、フィルタ 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))

リクエストが成功すると、200 ステータス コードと、一致するアカウントのリストを含むレスポンス本文が返されます。

{
  "accounts": [
    {
      "name": "accounts/54321",
      "accountId": "54321",
      "accountName": "Aggregated Account X",
      "adultContent": false,
      "languageCode": "en",
      "timeZone": {
        "id": "America/New_York"
      }
    }
  ]
}

サービス関係の承認状態に基づいてアカウントを検索する

プロバイダとのサービス関係のステータスに基づいてアカウントをフィルタできます。たとえば、特定のプロバイダ PROVIDER_ID からのアカウント リンク リクエスト (handshakeState = "PENDING") を承認していないすべてのアカウントを検索します。

たとえば、プロバイダ ID が 123、サービスタイプが ACCOUNT_MANAGEMENT、ステータスが PENDING のアカウントを検索するには、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)

リクエストが成功すると、200 ステータス コードと、一致するアカウントのリストを含むレスポンス本文が返されます。

{
  "accounts": [
    {
      "name": "accounts/98765",
      "accountId": "98765",
      "accountName": "Managed Account Y",
      "adultContent": false,
      "languageCode": "es",
      "timeZone": {
        "id": "Europe/Madrid"
      }
    }
  ]
}

クライアント ライブラリを使用してアカウントをフィルタする

次の例は、クライアント ライブラリを使用して、アカウント名やプロバイダとの関係などの複合条件に基づいてアカウントをフィルタする方法を示しています。これらの例では、accounts.list メソッドを使用します。詳細については、accounts.list リファレンス ドキュメントをご覧ください。

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;
    let pageSize = 500;
    // Call the Accounts.list API method with a filter. Use the pageToken to iterate through
    // all pages of results.
    do {
      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>'