액세스 권한이 있는 계정 필터링

accounts.list 메서드를 사용하면 인증된 사용자가 액세스할 수 있는 Account 리소스 목록을 가져올 수 있습니다. filter 쿼리 매개변수를 사용하여 다음과 같은 다양한 기준에 따라 결과를 좁힐 수 있습니다.

  • 계정 속성
  • 다른 계정과의 관계 (예: 고급 계정 구조의 제공업체)
  • 계정과 연결된 서비스

이 기능은 여러 계정을 관리하거나 특정 조건을 충족하는 특정 비즈니스 계정을 찾는 데 유용합니다.

다음 필드를 사용하여 account 수준에서 필터링할 수 있습니다.

  • access: 사용자가 account에 대해 보유한 액세스 권한 유형을 기준으로 필터링합니다. 이 필터는 다음 값을 허용합니다.
    • DIRECT: 사용자가 직접 액세스할 수 있는 계정만 반환합니다.
    • INDIRECT: 사용자가 간접적으로 액세스할 수 있는 계정만 반환합니다.
    • ALL: 사용자가 액세스할 수 있는 모든 계정 (직접 및 간접)을 반환합니다. 필터를 지정하지 않으면 이 동작이 기본값입니다.
  • capabilities: account 리소스의 capabilities를 기준으로 필터링합니다(이 필드는 리소스 자체에서 사용할 수 없음). CAN_UPLOAD_PRODUCTS 기능만 지원됩니다. 이 필드는 부정을 지원하며 컬렉션 구문을 사용합니다.
  • relationship(...): 계정과 다른 계정 간의 관계 유형을 기준으로 필터링합니다. 하나의 요청에 여러 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 참고 문서를 확인하세요.

자바

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>'