-
Notifications
You must be signed in to change notification settings - Fork 260
/
GetAccountHierarchy.php
340 lines (309 loc) · 14.9 KB
/
GetAccountHierarchy.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<?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 GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V10\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V10\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V10\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\V10\GoogleAdsServerStreamDecorator;
use Google\Ads\GoogleAds\V10\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V10\Resources\CustomerClient;
use Google\Ads\GoogleAds\V10\Services\CustomerServiceClient;
use Google\Ads\GoogleAds\V10\Services\GoogleAdsRow;
use Google\ApiCore\ApiException;
/**
* Gets the account hierarchy of the specified manager customer ID and login customer ID. If you
* don't specify them, the example will instead print the hierarchies of all accessible customer
* accounts for your authenticated Google account. Note that if the list of accessible customers
* for your authenticated Google account includes accounts within the same hierarchy, this example
* will retrieve and print the overlapping portions of the hierarchy for each accessible customer.
*/
class GetAccountHierarchy
{
// Optional: You may pass the manager customer ID on the command line or specify it here. If
// neither are set, a null value will be passed to the runExample() method, and the example
// will print the hierarchies of all accessible customer IDs.
private const MANAGER_CUSTOMER_ID = null;
// Optional: You may pass the login customer ID on the command line or specify it here if and
// only if the manager customer ID is set. If the login customer ID is set neither on the
// command line nor below, a null value will be passed to the runExample() method, and the
// example will use each accessible customer ID as the login customer ID.
private const LOGIN_CUSTOMER_ID = null;
// Stores the mapping from the root customer IDs (the ones that will be used as a start point
// for printing each hierarchy) to their `CustomerClient` objects.
private static $rootCustomerClients = [];
public static function main()
{
// Either pass the required parameters for this example on the command line, or insert them
// into the constants above.
$options = (new ArgumentParser())->parseCommandArguments([
ArgumentNames::MANAGER_CUSTOMER_ID => GetOpt::OPTIONAL_ARGUMENT,
ArgumentNames::LOGIN_CUSTOMER_ID => GetOpt::OPTIONAL_ARGUMENT
]);
$managerCustomerId =
$options[ArgumentNames::MANAGER_CUSTOMER_ID] ?: self::MANAGER_CUSTOMER_ID;
$loginCustomerId =
$options[ArgumentNames::LOGIN_CUSTOMER_ID] ?: self::LOGIN_CUSTOMER_ID;
if ($managerCustomerId xor $loginCustomerId) {
throw new \InvalidArgumentException(
'Both the manager customer ID and login customer ID must be provided together, '
. 'or they must both be null.'
);
}
// 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, $managerCustomerId, $loginCustomerId);
} 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
* @param int|null $managerCustomerId the manager customer ID
* @param int|null $loginCustomerId the login customer ID
*/
public static function runExample(
GoogleAdsClient $googleAdsClient,
?int $managerCustomerId,
?int $loginCustomerId
) {
$rootCustomerIds = [];
if (is_null($managerCustomerId)) {
// We will get the account hierarchies for all accessible customers.
$rootCustomerIds = self::getAccessibleCustomers($googleAdsClient);
} else {
// We will get only the hierarchy for the provided manager customer ID when it's
// provided.
$rootCustomerIds[] = $managerCustomerId;
}
$allHierarchies = [];
$accountsWithNoInfo = [];
// Constructs a map of account hierarchies.
foreach ($rootCustomerIds as $rootCustomerId) {
$customerClientToHierarchy =
self::createCustomerClientToHierarchy($loginCustomerId, $rootCustomerId);
if (is_null($customerClientToHierarchy)) {
$accountsWithNoInfo[] = $rootCustomerId;
} else {
$allHierarchies += $customerClientToHierarchy;
}
}
// Prints the IDs of any accounts that did not produce hierarchy information.
if (!empty($accountsWithNoInfo)) {
print
'Unable to retrieve information for the following accounts which are likely '
. 'either test accounts or accounts with setup issues. Please check the logs for '
. 'details:' . PHP_EOL;
foreach ($accountsWithNoInfo as $accountId) {
print $accountId . PHP_EOL;
}
print PHP_EOL;
}
// Prints the hierarchy information for all accounts for which there is hierarchy info
// available.
foreach ($allHierarchies as $rootCustomerId => $customerIdsToChildAccounts) {
printf(
"The hierarchy of customer ID %d is printed below:%s",
$rootCustomerId,
PHP_EOL
);
self::printAccountHierarchy(
self::$rootCustomerClients[$rootCustomerId],
$customerIdsToChildAccounts,
0
);
print PHP_EOL;
}
}
/**
* Creates a map between a customer client and each of its managers' mappings.
*
* @param int|null $loginCustomerId the login customer ID used to create the GoogleAdsClient
* @param int $rootCustomerId the ID of the customer at the root of the tree
* @return array|null a map between a customer client and each of its managers' mappings if the
* account hierarchy can be retrieved. If the account hierarchy cannot be retrieved, returns
* null
*/
private static function createCustomerClientToHierarchy(
?int $loginCustomerId,
int $rootCustomerId
): ?array {
// Creates a GoogleAdsClient with the specified login customer ID. See
// https://developers.google.com/google-ads/api/docs/concepts/call-structure#cid for more
// information.
// 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)
->withLoginCustomerId($loginCustomerId ?? $rootCustomerId)
->build();
// Creates the Google Ads Service client.
$googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
// Creates a query that retrieves all child accounts of the manager specified in search
// calls below.
$query = 'SELECT customer_client.client_customer, customer_client.level,'
. ' customer_client.manager, customer_client.descriptive_name,'
. ' customer_client.currency_code, customer_client.time_zone,'
. ' customer_client.id FROM customer_client WHERE customer_client.level <= 1';
$rootCustomerClient = null;
// Adds the root customer ID to the list of IDs to be processed.
$managerCustomerIdsToSearch = [$rootCustomerId];
// Performs a breadth-first search algorithm to build an associative array mapping
// managers to their child accounts ($customerIdsToChildAccounts).
$customerIdsToChildAccounts = [];
while (!empty($managerCustomerIdsToSearch)) {
$customerIdToSearch = array_shift($managerCustomerIdsToSearch);
// Issues a search request by specifying page size.
/** @var GoogleAdsServerStreamDecorator $stream */
$stream = $googleAdsServiceClient->searchStream(
$customerIdToSearch,
$query
);
// Iterates over all elements to get all customer clients under the specified customer's
// hierarchy.
foreach ($stream->iterateAllElements() as $googleAdsRow) {
/** @var GoogleAdsRow $googleAdsRow */
$customerClient = $googleAdsRow->getCustomerClient();
// Gets the CustomerClient object for the root customer in the tree.
if ($customerClient->getId() === $rootCustomerId) {
$rootCustomerClient = $customerClient;
self::$rootCustomerClients[$rootCustomerId] = $rootCustomerClient;
}
// The steps below map parent and children accounts. Continue here so that managers
// accounts exclude themselves from the list of their children accounts.
if ($customerClient->getId() === $customerIdToSearch) {
continue;
}
// For all level-1 (direct child) accounts that are a manager account, the above
// query will be run against them to create an associative array of managers to
// their child accounts for printing the hierarchy afterwards.
$customerIdsToChildAccounts[$customerIdToSearch][] = $customerClient;
// Checks if the child account is a manager itself so that it can later be processed
// and added to the map if it hasn't been already.
if ($customerClient->getManager()) {
// A customer can be managed by multiple managers, so to prevent visiting
// the same customer multiple times, we need to check if it's already in the
// map.
$alreadyVisited = array_key_exists(
$customerClient->getId(),
$customerIdsToChildAccounts
);
if (!$alreadyVisited && $customerClient->getLevel() === 1) {
array_push($managerCustomerIdsToSearch, $customerClient->getId());
}
}
}
}
return is_null($rootCustomerClient) ? null
: [$rootCustomerClient->getId() => $customerIdsToChildAccounts];
}
/**
* Retrieves a list of accessible customers with the provided set up credentials.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @return int[] the list of customer IDs
*/
private static function getAccessibleCustomers(GoogleAdsClient $googleAdsClient): array
{
$accessibleCustomerIds = [];
// Issues a request for listing all customers accessible by this authenticated Google
// account.
$customerServiceClient = $googleAdsClient->getCustomerServiceClient();
$accessibleCustomers = $customerServiceClient->listAccessibleCustomers();
print 'No manager customer ID is specified. The example will print the hierarchies of'
. ' all accessible customer IDs:' . PHP_EOL;
foreach ($accessibleCustomers->getResourceNames() as $customerResourceName) {
$customer = CustomerServiceClient::parseName($customerResourceName)['customer_id'];
print $customer . PHP_EOL;
$accessibleCustomerIds[] = intval($customer);
}
print PHP_EOL;
return $accessibleCustomerIds;
}
/**
* Prints the specified account's hierarchy using recursion.
*
* @param CustomerClient $customerClient the customer client whose info will be printed and
* its child accounts will be processed if it's a manager
* @param array $customerIdsToChildAccounts a map from customer IDs to child
* accounts
* @param int $depth the current depth we are printing from in the
* account hierarchy
*/
private static function printAccountHierarchy(
CustomerClient $customerClient,
array $customerIdsToChildAccounts,
int $depth
) {
if ($depth === 0) {
print 'Customer ID (Descriptive Name, Currency Code, Time Zone)' . PHP_EOL;
}
$customerId = $customerClient->getId();
print str_repeat('-', $depth * 2);
printf(
" %d ('%s', '%s', '%s')%s",
$customerId,
$customerClient->getDescriptiveName(),
$customerClient->getCurrencyCode(),
$customerClient->getTimeZone(),
PHP_EOL
);
// Recursively call this function for all child accounts of $customerClient.
if (array_key_exists($customerId, $customerIdsToChildAccounts)) {
foreach ($customerIdsToChildAccounts[$customerId] as $childAccount) {
self::printAccountHierarchy($childAccount, $customerIdsToChildAccounts, $depth + 1);
}
}
}
}
GetAccountHierarchy::main();