Ява
// 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.
package com.google.ads.googleads.examples.accountmanagement;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v17.errors.GoogleAdsError;
import com.google.ads.googleads.v17.errors.GoogleAdsException;
import com.google.ads.googleads.v17.services.CustomerServiceClient;
import com.google.ads.googleads.v17.services.ListAccessibleCustomersRequest;
import com.google.ads.googleads.v17.services.ListAccessibleCustomersResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Retrieves the accounts available for a particular OAuth token. This is often useful when managing
* new accounts. After completing OAuth for a user, set the credentials on GoogleAdsClient to the
* user's refresh token, then call ListAccessibleCustomers to retrieve the customer IDs accessible
* by the user.
*/
public class ListAccessibleCustomers {
public static void main(String[] args) {
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
try {
new ListAccessibleCustomers().runExample(googleAdsClient);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
System.exit(1);
}
}
/**
* Runs the example.
*
* @param client the GoogleAdsClient instance to use.
*/
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);
}
}
}
}
С#
// 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
//
// 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 CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V17.Errors;
using Google.Ads.GoogleAds.V17.Services;
using System;
using System.Collections.Generic;
namespace Google.Ads.GoogleAds.Examples.V17
{
/// <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#cid
/// to learn more about the login-customer-id header.
/// </summary>
public class ListAccessibleCustomers : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="ListAccessibleCustomers"/> example.
/// </summary>
public class Options : OptionsBase
{
}
/// <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)
{
Options options = ExampleUtilities.ParseCommandLine<Options>(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 =>
"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.V17.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}");
throw;
}
}
}
}
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\V17\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V17\Services\ListAccessibleCustomersRequest;
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#cid
*/
class ListAccessibleCustomers
{
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
);
}
exit(1);
} catch (ApiException $apiException) {
printf(
"ApiException was thrown with message '%s'.%s",
$apiException->getMessage(),
PHP_EOL
);
exit(1);
}
}
/**
* 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(new ListAccessibleCustomersRequest());
print 'Total results: ' . count($accessibleCustomers->getResourceNames()) . 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();
Питон
#!/usr/bin/env python
# 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
#
# 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.
"""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#cid
"""
import sys
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
def main(client):
customer_service = client.get_service("CustomerService")
accessible_customers = customer_service.list_accessible_customers()
result_total = len(accessible_customers.resource_names)
print(f"Total results: {result_total}")
resource_names = accessible_customers.resource_names
for resource_name in resource_names:
print(f'Customer resource name: "{resource_name}"')
if __name__ == "__main__":
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
googleads_client = GoogleAdsClient.load_from_storage(version="v17")
try:
main(googleads_client)
except GoogleAdsException as ex:
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:'
)
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")
sys.exit(1)
Руби
#!/usr/bin/env ruby
# Encoding: utf-8
#
# 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
#
# 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.
#
# 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#cid
require 'optparse'
require 'google/ads/google_ads'
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
accessible_customers = client.service.customer.list_accessible_customers().resource_names
accessible_customers.each do |resource_name|
puts "Customer resource name: #{resource_name}"
end
end
if __FILE__ == $0
PAGE_SIZE = 1000
begin
list_accessible_customers()
rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
e.failure.errors.each do |error|
STDERR.printf("Error with message: %s\n", error.message)
if error.location
error.location.field_path_elements.each do |field_path_element|
STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
end
end
error.error_code.to_h.each do |k, v|
next if v == :UNSPECIFIED
STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
end
end
raise
end
end
Перл
#!/usr/bin/perl -w
#
# 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
#
# 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.
#
# 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
use strict;
use warnings;
use utf8;
use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Getopt::Long qw(:config auto_help);
use Cwd qw(abs_path);
sub list_accessible_customers {
my ($api_client) = @_;
my $list_accessible_customers_response =
$api_client->CustomerService()->list_accessible_customers();
printf "Total results: %d.\n",
scalar @{$list_accessible_customers_response->{resourceNames}};
foreach
my $resource_name (@{$list_accessible_customers_response->{resourceNames}})
{
printf "Customer resource name: '%s'.\n", $resource_name;
}
return 1;
}
# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
return 1;
}
# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();
# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);
# Parameters passed on the command line will override any parameters set in code.
GetOptions();
# Call the example.
list_accessible_customers($api_client);
=pod
=head1 NAME
list_accessible_customers
=head1 DESCRIPTION
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
=head1 SYNOPSIS
list_accessible_customers.pl [options]
-help Show the help message.
=cut