Lọc tài khoản bạn có thể truy cập

Phương thức accounts.list cho phép bạn truy xuất danh sách các tài nguyên Account mà người dùng đã xác thực có thể truy cập. Bạn có thể sử dụng tham số truy vấn filter để thu hẹp kết quả dựa trên nhiều tiêu chí, chẳng hạn như:

  • Thuộc tính tài khoản
  • Mối quan hệ với các tài khoản khác (chẳng hạn như nhà cung cấp trong cấu trúc tài khoản nâng cao)
  • Các dịch vụ được liên kết với tài khoản

Điều này có thể hữu ích khi bạn quản lý nhiều tài khoản hoặc tìm các tài khoản doanh nghiệp cụ thể đáp ứng một số điều kiện nhất định.

Bạn có thể sử dụng các trường sau để lọc ở cấp account:

  • access: Lọc theo loại quyền truy cập mà người dùng có đối với account. Bộ lọc này chấp nhận các giá trị sau:
    • DIRECT: Chỉ trả về những tài khoản mà người dùng có quyền truy cập trực tiếp.
    • INDIRECT: Chỉ trả về những tài khoản mà người dùng có quyền truy cập gián tiếp.
    • ALL: Trả về tất cả tài khoản mà người dùng có quyền truy cập (cả trực tiếp và gián tiếp). Đây là hành vi mặc định nếu bạn không chỉ định bộ lọc.
  • capabilities: Lọc theo capabilities của tài nguyên account (lưu ý rằng trường này không có trên chính tài nguyên). Chỉ hỗ trợ chức năng CAN_UPLOAD_PRODUCTS. Trường này hỗ trợ phủ định và sử dụng cú pháp tập hợp.
  • relationship(...): Lọc theo loại mối quan hệ mà tài khoản có với một tài khoản khác. Bạn có thể thêm nhiều bộ lọc relationship(...) vào một yêu cầu.
  • accountName: Lọc theo accountName của tài nguyên account.

Để biết thêm thông tin chi tiết về cú pháp bộ lọc, hãy xem hướng dẫn về Cú pháp bộ lọc.

Ví dụ

Các ví dụ sau đây giải thích cách tạo các truy vấn phổ biến nhất. Tất cả các ví dụ sau đây đều sử dụng phương thức accounts.list. Để biết thêm thông tin, hãy xem tài liệu tham khảo về accounts.list.

Tìm tài khoản phụ của một nhà cung cấp cụ thể

Phương thức accounts.listSubaccounts cung cấp một cách trực tiếp để liệt kê các tài khoản phụ. Bạn cũng có thể sử dụng các chức năng lọc như mô tả trong các phần sau. Nếu quản lý một tài khoản nâng cao, bạn có thể liệt kê tất cả tài khoản phụ của tài khoản đó bằng cách lọc theo providerId. Thay thế PROVIDER_ID bằng mã nhận dạng tài khoản nâng cao của bạn.

Ví dụ: sử dụng relationship(providerId=123) nếu mã nhận dạng của nhà cung cấp là 123.

Điều này hữu ích cho việc quản lý cấu trúc tài khoản của bạn.

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

Yêu cầu thành công sẽ trả về mã trạng thái 200 và một nội dung phản hồi có danh sách các tài khoản phụ phù hợp:

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

Tìm những tài khoản không thể tải sản phẩm lên

Bạn có thể kết hợp nhiều điều kiện lọc để tìm kiếm cụ thể hơn.

Bộ lọc accountName=*store* AND -capabilities:CAN_UPLOAD_PRODUCTS tìm tất cả tài khoản có "cửa hàng" trong tên nhưng không được định cấu hình để tải trực tiếp sản phẩm lên. - trước capabilities đóng vai trò là toán tử phủ định. Điều này có thể hữu ích khi bạn chỉ muốn truy xuất các tài khoản nâng cao.

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

Yêu cầu thành công sẽ trả về mã trạng thái 200 và một nội dung phản hồi có danh sách các tài khoản phù hợp:

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

Tìm tài khoản theo tên

Bạn có thể tìm kiếm những tài khoản có tên hiển thị khớp với một mẫu cụ thể.

Ví dụ: accountName=*store* sẽ tìm tất cả tài khoản có từ "cửa hàng" trong tên.

Điều này giúp bạn nhanh chóng tìm thấy các tài khoản doanh nghiệp cụ thể.

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

Yêu cầu thành công sẽ trả về mã trạng thái 200 và một nội dung phản hồi có danh sách các tài khoản phù hợp:

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

Tìm tài khoản được liên kết với một nhà cung cấp cho một dịch vụ cụ thể

Bạn có thể tìm thấy những tài khoản có mối quan hệ dịch vụ cụ thể với một nhà cung cấp. Ví dụ: để tìm tất cả tài khoản được tổng hợp trong nhà cung cấp PROVIDER_ID cho tính năng tổng hợp tài khoản, hãy sử dụng bộ lọc 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))

Yêu cầu thành công sẽ trả về mã trạng thái 200 và một nội dung phản hồi có danh sách các tài khoản phù hợp:

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

Tìm tài khoản dựa trên trạng thái phê duyệt mối quan hệ dịch vụ

Bạn có thể lọc tài khoản dựa trên trạng thái mối quan hệ dịch vụ của tài khoản với một nhà cung cấp. Ví dụ: để tìm tất cả tài khoản chưa chấp nhận yêu cầu liên kết tài khoản (handshakeState = "PENDING") từ một nhà cung cấp cụ thể PROVIDER_ID.

Ví dụ: để tìm những tài khoản có mã nhận dạng nhà cung cấp là 123, loại dịch vụ là ACCOUNT_MANAGEMENT và trạng thái là PENDING, hãy sử dụng 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)

Yêu cầu thành công sẽ trả về mã trạng thái 200 và một nội dung phản hồi có danh sách các tài khoản phù hợp:

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

Lọc tài khoản bằng thư viện ứng dụng

Các ví dụ sau đây minh hoạ cách sử dụng thư viện ứng dụng để lọc tài khoản dựa trên các tiêu chí kết hợp, chẳng hạn như tên tài khoản và mối quan hệ với một nhà cung cấp. Các ví dụ này sử dụng phương thức accounts.list. Để biết thêm thông tin, hãy xem tài liệu tham khảo về 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>'