Google Ads API is returning to beta status. Please read our blog post for more details.

列出帐号

通过使用 CustomerService 中的 ListAccessibleCustomers 方法,您可以列出自己可访问的客户。不过,有必要了解一下此类请求会返回哪些客户。

在 Google Ads API 中,有少数请求不仅不要求您在请求中指定客户 ID,而且还会忽略任何已提供的 login-customer-id,列出可访问的客户就是此类请求之一。

生成的客户列表取决于您的 OAuth 凭据。该请求会返回一个列表,其中会列出您可以根据当前凭据直接采取操作的所有帐号。它不一定包括帐号层次结构中的所有帐号,只会包括已通过帐号中的管理员权限或其他权限添加了身份验证成功用户的帐号。

假设您是用户 A,同时是上图两个层次结构中 M1C3 的管理员。如果您要调用 Google Ads API(例如调用 GoogleAdsService),则可以访问帐号 M1C1C2C3 的信息。不过,调用 CustomerService.ListAccessibleCustomers 将仅返回 M1C3,因为只有这两个帐号是用户 A 可以直接访问的帐号。

以下示例代码说明了如何使用 ListAccessibleCustomers 方法:

Java

private void runExample(GoogleAdsClient client) {
  // Optional: Change credentials to use a different refresh token, to retrieve customers
  //           available for a specific user.
  //
  // UserCredentials credentials =
  //     UserCredentials.newBuilder()
  //         .setClientId("INSERT_OAUTH_CLIENT_ID")
  //         .setClientSecret("INSERT_OAUTH_CLIENT_SECRET")
  //         .setRefreshToken("INSERT_REFRESH_TOKEN")
  //         .build();
  //
  // client = client.toBuilder().setCredentials(credentials).build();

  try (CustomerServiceClient customerService =
      client.getLatestVersion().createCustomerServiceClient()) {
    ListAccessibleCustomersResponse response =
        customerService.listAccessibleCustomers(
            ListAccessibleCustomersRequest.newBuilder().build());

    System.out.printf("Total results: %d%n", response.getResourceNamesCount());

    for (String customerResourceName : response.getResourceNamesList()) {
      System.out.printf("Customer resource name: %s%n", customerResourceName);
    }
  }
}

C#

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

using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V1.Errors;
using Google.Ads.GoogleAds.V1.Services;

using System;

namespace Google.Ads.GoogleAds.Examples.V1
{
    /// <summary>
    /// This code example lists the resource names for the customers that the authenticating user
    /// has access to. This example may can be used to display a list of customer IDs that can be
    /// selected by the user for setting the login-customer-id in a subsequent call. See
    /// https://developers.google.com/google-ads/api/docs/concepts/call-structure#login-customer-id
    /// to learn more about the login-customer-id header.
    /// </summary>
    public class ListAccessibleCustomers : ExampleBase
    {
        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            ListAccessibleCustomers codeExample = new ListAccessibleCustomers();

            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient());
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example lists the resource names for the customers that the " +
                    "authenticating user has access to. This example may be used to display a " +
                    "list of customer IDs that can be selected by the user for setting the " +
                    "login-customer-id in a subsequent call. See "+
                    "https://developers.google.com/google-ads/api/docs/concepts/call-structure#login-customer-id "+
                    "to learn more about the login-customer-id header.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        public void Run(GoogleAdsClient client)
        {
            // Get the CustomerService.
            CustomerServiceClient customerService = client.GetService(Services.V1.CustomerService);

            try
            {
                // Retrieve the list of customer resources.
                string[] customerResourceNames = customerService.ListAccessibleCustomers();

                // Display the result.
                foreach (string customerResourceName in customerResourceNames)
                {
                    Console.WriteLine(
                        $"Found customer with resource name = '{customerResourceName}'.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
            }
        }
    }
}

PHP

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

namespace Google\Ads\GoogleAds\Examples\AccountManagement;

require __DIR__ . '/../../vendor/autoload.php';

use Google\Ads\GoogleAds\Lib\V1\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V1\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V1\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\V1\Errors\GoogleAdsError;
use Google\ApiCore\ApiException;

/**
 * This example lists the resource names for the customers that the authenticating user has access
 * to.
 *
 * The customer IDs retrieved from the resource names can be used to set
 * the login-customer-id configuration. For more information see this
 * documentation:
 * https://developers.google.com/google-ads/api/docs/concepts/call-structure#login-customer-id
 */
class ListAccessibleCustomers
{
    const PAGE_SIZE = 1000;

    public static function main()
    {
        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample($googleAdsClient);
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     */
    public static function runExample(GoogleAdsClient $googleAdsClient)
    {
        $customerServiceClient = $googleAdsClient->getCustomerServiceClient();

        // Issues a request for listing all accessible customers.
        $accessibleCustomers = $customerServiceClient->listAccessibleCustomers();
        print 'Total results: ' . count($accessibleCustomers) . PHP_EOL;

        // Iterates over all accessible customers' resource names and prints them.
        foreach ($accessibleCustomers->getResourceNames() as $resourceName) {
            /** @var string $resourceName */
            printf("Customer resource name: '%s'%s", $resourceName, PHP_EOL);
        }
    }
}

ListAccessibleCustomers::main();

Python

def main(client):
    customer_service = client.get_service('CustomerService', version='v1')

    try:
        accessible_customers = customer_service.list_accessible_customers()
        result_total = len(accessible_customers.resource_names)
        print('Total results: %i' % result_total)

        resource_names = accessible_customers.resource_names
        for resource_name in resource_names:
            print('Customer resource name: "%s"' % resource_name)
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)

Ruby

def list_accessible_customers()
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  customer_service = client.service(:Customer)
  accessible_customers =
      customer_service.list_accessible_customers().resource_names

  accessible_customers.each do |resource_name|
    puts "Customer resource name: #{resource_name}"
  end
end