列表配额

用于列出配额的商家 API 代码示例

// 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.

package shopping.merchant.samples.quota.v1beta;

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.quota.v1beta.ListQuotaGroupsRequest;
import com.google.shopping.merchant.quota.v1beta.QuotaGroup;
import com.google.shopping.merchant.quota.v1beta.QuotaServiceClient;
import com.google.shopping.merchant.quota.v1beta.QuotaServiceClient.ListQuotaGroupsPagedResponse;
import com.google.shopping.merchant.quota.v1beta.QuotaServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to list quota for a given Merchant Center account. */
public class ListQuotaSample {

  public static void listQuotas(String accountId) throws Exception {
    GoogleCredentials credential = new Authenticator().authenticate();

    QuotaServiceSettings quotasServiceSettings =
        QuotaServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    try (QuotaServiceClient quotaServiceClient = QuotaServiceClient.create(quotasServiceSettings)) {

      ListQuotaGroupsRequest request =
          ListQuotaGroupsRequest.newBuilder()
              .setParent(String.format("accounts/%s", accountId))
              .build();

      System.out.println("Sending list quotas request:");
      ListQuotaGroupsPagedResponse response = quotaServiceClient.listQuotaGroups(request);

      int count = 0;

      // Iterates over all rows in all pages and prints the quota group in each row.
      // Automatically uses the `nextPageToken` if returned to fetch all pages of data.
      for (QuotaGroup quota : response.iterateAll()) {
        System.out.println(quota);
        count++;
      }
      System.out.print("The following count of quota were returned: ");
      System.out.println(count);

    } catch (Exception e) {
      System.out.println("Failed to list quota.");
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    listQuotas(config.getAccountId().toString());
  }
}

<?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.
 */

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\Quota\V1beta\Client\QuotaServiceClient;
use Google\Shopping\Merchant\Quota\V1beta\ListQuotaGroupsRequest;

/**
 * This class demonstrates how to list quota for a given Merchant Center account.
 */
class ListQuotaSample
{

    /**
     * A helper function to create the parent string.
     *
     * @param string $accountId
     *      The account that owns the quota.
     *
     * @return string The parent has the format: `accounts/{account_id}`
     */
    private static function getParent(string $accountId): string
    {
        return sprintf("accounts/%s", $accountId);
    }


    /**
     * Lists quotas for a given Merchant Center account.
     *
     * @param string $accountId
     *      The Merchant Center account ID.
     * @throws ApiException
     */
    public static function listQuotas(string $accountId): 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.
        $quotaServiceClient = new QuotaServiceClient($options);

        // Creates the parent resource name.
        $parent = self::getParent($accountId);

        // Creates the request.
        $request = new ListQuotaGroupsRequest(['parent' => $parent]);

        print "Sending list quotas request:\n";

        // Calls the API and catches and prints any network failures/errors.
        try {
            $response = $quotaServiceClient->listQuotaGroups($request);

            $count = 0;

            // Iterates over all rows in all pages and prints the quota group in each row.
            foreach ($response->iterateAllElements() as $quota) {
                print_r($quota);
                $count++;
            }
            print "The following count of quota were returned: ";
            print $count . "\n";
        } catch (ApiException $e) {
            print "Failed to list quota.\n";
            print $e->getMessage() . "\n";
        }
    }

    /**
     * Helper to execute the sample.
     * @throws ApiException
     */
    public function callSample(): void
    {
        $config = Config::generateConfig();
        self::listQuotas($config['accountId']);
    }
}

// Run the script
$sample = new ListQuotaSample();
$sample->callSample();


# -*- coding: utf-8 -*-
# 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
#
#     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 quota for a given Merchant Center account."""

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping import merchant_quota_v1beta

_ACCOUNT = configuration.Configuration().read_merchant_info()
_PARENT = f"accounts/{_ACCOUNT}"


def list_quotas():
  """This class demonstrates how to list quota for a given Merchant Center account."""

  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client.
  client = merchant_quota_v1beta.QuotaServiceClient(credentials=credentials)

  # Creates the request.
  request = merchant_quota_v1beta.ListQuotaGroupsRequest(parent=_PARENT)

  print("Sending list quotas request:")
  # Makes the request.
  response = client.list_quota_groups(request=request)

  count = 0

  # Iterates over all rows in all pages and prints the quota group in each row.
  # Automatically uses the `next_page_token` if returned to fetch all pages of
  # data.
  for quota in response:
    print(quota)
    count += 1
  print("The following count of quota were returned: ")
  print(count)


if __name__ == "__main__":
  list_quotas()