Account Management Samples

The code samples below provide examples of common account management functions using the AdWords API. Client Library.

Accept an invitation for linking to a manager account

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * 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.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AccountManagement;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\mcm\CustomerService;
use Google\AdsApi\AdWords\v201705\mcm\ServiceLink;
use Google\AdsApi\AdWords\v201705\mcm\ServiceLinkLinkStatus;
use Google\AdsApi\AdWords\v201705\mcm\ServiceLinkOperation;
use Google\AdsApi\AdWords\v201705\mcm\ServiceType;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example accepts a pending invitation to link your AdWords account to a
 * Google Merchant Center account.
 */
class AcceptServiceLink {

  const SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $serviceLinkId) {
    $customerService = $adWordsServices->get($session, CustomerService::class);

    // Create service link.
    $serviceLink = new ServiceLink();
    $serviceLink->setServiceLinkId($serviceLinkId);
    $serviceLink->setServiceType(ServiceType::MERCHANT_CENTER);
    $serviceLink->setLinkStatus(ServiceLinkLinkStatus::ACTIVE);

    // Create a service link operation and add it to the list.
    $operations = [];
    $operation = new ServiceLinkOperation();
    $operation->setOperator(Operator::SET);
    $operation->setOperand($serviceLink);
    $operations[] = $operation;

    // Accept service links on the server and print out some information about
    // accepted service links.
    $serviceLinks = $customerService->mutateServiceLinks($operations);
    foreach ($serviceLinks as $serviceLink) {
      printf(
          "Service link with service link ID %d and type '%s' updated to status"
              . ": %s.\n",
          $serviceLink->getServiceLinkId(),
          $serviceLink->getServiceType(),
          $serviceLink->getLinkStatus()
      );
    }
  }

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

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(
        new AdWordsServices(), $session, intval(self::SERVICE_LINK_ID));
  }
}

AcceptServiceLink::main();

Create new account under an AdWords manager

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * 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.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AccountManagement;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\mcm\ManagedCustomerService;
use Google\AdsApi\AdWords\v201705\mcm\ManagedCustomer;
use Google\AdsApi\AdWords\v201705\mcm\ManagedCustomerOperation;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example creates a new account under an AdWords manager account. Note:
 * this example must be run using the credentials of an AdWords manager account,
 * and by default the new account will only be accessible via the parent AdWords
 * manager account.
 */
class CreateAccount {

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $managedCustomerService =
        $adWordsServices->get($session, ManagedCustomerService::class);

    // Create a managed customer.
    $customer = new ManagedCustomer();
    $customer->setName('Account #' . uniqid());
    $customer->setCurrencyCode('EUR');
    $customer->setDateTimeZone('Europe/London');

    // Create a managed customer operation and add it to the list.
    $operations = [];
    $operation = new ManagedCustomerOperation();
    $operation->setOperator(Operator::ADD);
    $operation->setOperand($customer);
    $operations[] = $operation;

    // Create a managed customer on the server and print out some information
    // about it.
    $customer = $managedCustomerService->mutate($operations)->getValue()[0];
    printf("Account with customer ID %d was created.\n",
        $customer->getCustomerId());
  }

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

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    // You can use withClientCustomerId() of AdWordsSessionBuilder to specify
    // your manager account ID under which you want to create an account.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(new AdWordsServices(), $session);
  }
}

CreateAccount::main();

Old

<?php
/**
 * This example creates a new account under an AdWords manager account. Note:
 * this example must be run using the credentials of an AdWords manager account,
 * and by default the new account will only be accessible via the parent AdWords
 * manager account.
 *
 * PHP version 5
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * 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.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

// Include the initialization file
require_once dirname(dirname(__FILE__)) . '/init.php';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 */
function CreateAccountExample(AdWordsUser $user) {
  // Get the service, which loads the required classes.
  $managedCustomerService =
      $user->GetService('ManagedCustomerService', ADWORDS_VERSION);

  // Create customer.
  $customer = new ManagedCustomer();
  $customer->name = 'Account #' . uniqid();
  $customer->currencyCode = 'EUR';
  $customer->dateTimeZone = 'Europe/London';

  // Create operation.
  $operation = new ManagedCustomerOperation();
  $operation->operator = 'ADD';
  $operation->operand = $customer;

  $operations = array($operation);

  // Make the mutate request.
  $result = $managedCustomerService->mutate($operations);

  // Display result.
  $customer = $result->value[0];
  printf("Account with customer ID '%s' was created.\n",
      $customer->customerId);
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Run the example.
  CreateAccountExample($user);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Get all account changes during the past 24 hours

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * 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.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AccountManagement;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\ch\ChangeStatus;
use Google\AdsApi\AdWords\v201705\ch\CustomerSyncSelector;
use Google\AdsApi\AdWords\v201705\ch\CustomerSyncService;
use Google\AdsApi\AdWords\v201705\cm\CampaignService;
use Google\AdsApi\AdWords\v201705\cm\DateTimeRange;
use Google\AdsApi\AdWords\v201705\cm\Paging;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets the changes in the account during the last 24 hours.
 * Note: this example must be run using the credentials of an ad-serving
 * account.
 */
class GetAccountChanges {

  const PAGE_LIMIT = 500;

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $campaignService = $adWordsServices->get($session, CampaignService::class);
    $customerSyncService =
        $adWordsServices->get($session, CustomerSyncService::class);

    // Create selector.
    $selector = new Selector();
    $selector->setFields(['Id']);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

    // Get an array of all campaign IDs.
    $campaignIds = [];
    do {
      $page = $campaignService->get($selector);

      if ($page->getEntries() !== null) {
        $totalNumEntries = $page->getTotalNumEntries();
        foreach ($page->getEntries() as $campaign) {
          $campaignIds[] = $campaign->getId();
        }
      }

      // Advance the paging index.
      $selector->getPaging()->setStartIndex(
          $selector->getPaging()->getStartIndex() + self::PAGE_LIMIT);
    } while ($selector->getPaging()->getStartIndex() < $totalNumEntries);

    // Set the date time range, from 24 hours ago until now.
    $dateTimeRange = new DateTimeRange();
    $dateTimeRange->setMin(date('Ymd his', strtotime('-1 day')));
    $dateTimeRange->setMax(date('Ymd his'));

    // Create selector.
    $selector = new CustomerSyncSelector();
    $selector->setDateTimeRange($dateTimeRange);
    $selector->setCampaignIds($campaignIds);

    // Retrieve the account changes from the server.
    $accountChanges = $customerSyncService->get($selector);

    // Print out some information related to the account changes.
    if ($accountChanges !== null) {
      printf("Most recent change: %s\n",
          $accountChanges->getLastChangeTimestamp());
      if ($accountChanges->getChangedCampaigns() !== null) {
        foreach ($accountChanges->getChangedCampaigns()
            as $campaignChangeData) {
          printf(
              "Campaign with ID %d has change status '%s'.\n",
              $campaignChangeData->getCampaignId(),
              $campaignChangeData->getCampaignChangeStatus()
          );
          if ($campaignChangeData->getCampaignChangeStatus()
              !== ChangeStatus::NEW_VALUE) {
            printf("\tAdded campaign criteria: %s\n",
                self::flatten($campaignChangeData->getAddedCampaignCriteria()));
            printf(
                "\tRemoved campaign criteria: %s\n",
                self::flatten($campaignChangeData->getRemovedCampaignCriteria())
            );
            if ($campaignChangeData->getChangedAdGroups() !== null) {
              foreach($campaignChangeData->getChangedAdGroups()
                  as $adGroupChangeData) {
                printf(
                    "\tAd Group with ID %d has change status '%s'.\n",
                    $adGroupChangeData->getAdGroupId(),
                    $adGroupChangeData->getAdGroupChangeStatus()
                );
                if ($adGroupChangeData->getAdGroupChangeStatus()
                    !== ChangeStatus::NEW_VALUE) {
                  printf("\t\tChanged ads: %s\n",
                      self::flatten($adGroupChangeData->getChangedAds()));
                  printf("\t\tChanged criteria: %s\n",
                      self::flatten($adGroupChangeData->getChangedCriteria()));
                  printf("\t\tRemoved criteria: %s\n",
                      self::flatten($adGroupChangeData->getRemovedCriteria()));
                }
              }
            }
          }
        }
      }
    } else {
      print "No changes were found.\n";
    }
  }

  /**
   * Flatten an array to a comma-separated string or empty string if the array
   * is null.
   *
   * @param array|null $array the array to be flattened
   * @return string the comma-separated string or empty string
   */
  private static function flatten($array) {
    return ($array === null) ? '' : implode(', ', $array);
  }

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

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(new AdWordsServices(), $session);
  }
}

GetAccountChanges::main();

Old

<?php
/**
 * This example gets the changes in the account during the last 24 hours.
 * Note: this example must be run using the credentials of an ad-serving
 * account.
 *
 * PHP version 5
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * 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.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

// Include the initialization file
require_once dirname(dirname(__FILE__)) . '/init.php';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 */
function GetAccountChangesExample(AdWordsUser $user) {
  // Get the service, which loads the required classes.
  $campaignService = $user->GetService('CampaignService', ADWORDS_VERSION);
  $customerSyncService = $user->GetService('CustomerSyncService', ADWORDS_VERSION);

  // Get an array of all campaign ids.
  $campaignIds = array();
  $selector = new Selector();
  $selector->fields = array('Id');
  $selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
  do {
    $page = $campaignService->get($selector);
    if (isset($page->entries)) {
      foreach ($page->entries as $campaign) {
        $campaignIds[] = $campaign->id;
      }
    }
    $selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
  } while ($page->totalNumEntries > $selector->paging->startIndex);

  // Set the date time range, from 24 hours ago until now.
  $dateTimeRange = new DateTimeRange();
  $dateTimeRange->min = date('Ymd his', strtotime('-1 day'));
  $dateTimeRange->max = date('Ymd his');

  // Create selector.
  $selector = new CustomerSyncSelector();
  $selector->dateTimeRange = $dateTimeRange;
  $selector->campaignIds = $campaignIds;

  // Make the get request.
  $accountChanges = $customerSyncService->get($selector);

  // Display results.
  if (isset($accountChanges)) {
    printf("Most recent change: %s\n", $accountChanges->lastChangeTimestamp);
    if (isset($accountChanges->changedCampaigns)) {
      foreach ($accountChanges->changedCampaigns as $campaignChangeData) {
        printf("Campaign with id '%.0f' has change status '%s'.\n",
            $campaignChangeData->campaignId,
            $campaignChangeData->campaignChangeStatus);
        if ($campaignChangeData->campaignChangeStatus != 'NEW') {
          printf("\tAdded campaign criteria: %s\n",
              ArrayToString($campaignChangeData->addedCampaignCriteria));
          printf("\tRemoved campaign criteria: %s\n",
              ArrayToString($campaignChangeData->removedCampaignCriteria));
          if (isset($campaignChangeData->changedAdGroups)) {
            foreach($campaignChangeData->changedAdGroups as
                $adGroupChangeData) {
              printf("\tAd Group with id '%.0f' has change status '%s'.\n",
                  $adGroupChangeData->adGroupId,
                  $adGroupChangeData->adGroupChangeStatus);
              if ($adGroupChangeData->adGroupChangeStatus != 'NEW') {
                printf("\t\tChanged ads: %s\n",
                    ArrayToString($adGroupChangeData->changedAds));
                printf("\t\tChanged criteria: %s\n",
                    ArrayToString($adGroupChangeData->changedCriteria));
                printf("\t\tRemoved criteria: %s\n",
                    ArrayToString($adGroupChangeData->removedCriteria));
              }
            }
          }
        }
      }
    }
  } else {
    print "No changes were found.\n";
  }
}

/**
 * Converts an array of values to a comma-separated string.
 * @param array $array an array of values that can be converted to a string
 * @return string a comma-separated string of the values
 */
function ArrayToString($array) {
  if (!isset($array)) {
    return '';
  } else {
    return implode(', ', $array);
  }
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Run the example.
  GetAccountChangesExample($user);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Get the account hierarchy under the current account

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * 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.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AccountManagement;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\OrderBy;
use Google\AdsApi\AdWords\v201705\cm\Paging;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\AdWords\v201705\cm\SortOrder;
use Google\AdsApi\AdWords\v201705\mcm\ManagedCustomerService;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets the account hierarchy under the current account.
 */
class GetAccountHierarchy {

  const PAGE_LIMIT = 500;

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $managedCustomerService = $adWordsServices->get(
        $session, ManagedCustomerService::class);

    // Create selector.
    $selector = new Selector();
    $selector->setFields(['CustomerId', 'Name']);
    $selector->setOrdering([new OrderBy('CustomerId', SortOrder::ASCENDING)]);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

    // Maps from customer IDs to accounts and links.
    $customerIdsToAccounts = [];
    $customerIdsToChildLinks = [];
    $customerIdsToParentLinks = [];

    $totalNumEntries = 0;
    do {
      // Make the get request.
      $page = $managedCustomerService->get($selector);

      // Create links between manager and clients.
      if ($page->getEntries() !== null) {
        $totalNumEntries = $page->getTotalNumEntries();
        if ($page->getLinks() !== null) {
          foreach ($page->getLinks() as $link) {
            $customerIdsToChildLinks[$link->getManagerCustomerId()][] = $link;
            $customerIdsToParentLinks[$link->getClientCustomerId()] = $link;
          }
        }
        foreach ($page->getEntries() as $account) {
          $customerIdsToAccounts[$account->getCustomerId()] = $account;
        }
      }

      // Advance the paging index.
      $selector->getPaging()->setStartIndex(
          $selector->getPaging()->getStartIndex() + self::PAGE_LIMIT);
    } while ($selector->getPaging()->getStartIndex() < $totalNumEntries);

    // Find the root account.
    $rootAccount = null;
    foreach ($customerIdsToAccounts as $account) {
      if (!array_key_exists($account->getCustomerId(),
          $customerIdsToParentLinks)) {
        $rootAccount = $account;
        break;
      }
    }

    if ($rootAccount !== null) {
      // Display results.
      self::printAccountHierarchy(
          $rootAccount, $customerIdsToAccounts, $customerIdsToChildLinks);
    } else {
      printf("No accounts were found.\n");
    }
  }

  /**
   * Prints the specified account's hierarchy using recursion.
   *
   * @param ManagedCustomer $account the account to print
   * @param array $customerIdsToAccounts a map from customer IDs to accounts
   * @param array $customerIdsToChildLinks a map from customer IDs to child
   *     links
   * @param int|null $depth the current depth we are printing from in the
   *     account hierarchy; i.e., how far we've recursed
   */
  private static function printAccountHierarchy($account,
      $customerIdsToAccounts, $customerIdsToChildLinks, $depth = null) {
    if ($depth === null) {
      print "(Customer ID, Account Name)\n";
      self::printAccountHierarchy(
          $account, $customerIdsToAccounts, $customerIdsToChildLinks, 0);
      return;
    }

    print str_repeat('-', $depth * 2);
    $customerId = $account->getCustomerId();
    printf("%s, %s\n", $customerId, $account->getName());

    if (array_key_exists($customerId, $customerIdsToChildLinks)) {
      foreach ($customerIdsToChildLinks[$customerId] as $childLink) {
        $childAccount =
            $customerIdsToAccounts[$childLink->getClientCustomerId()];
        self::printAccountHierarchy($childAccount, $customerIdsToAccounts,
            $customerIdsToChildLinks, $depth + 1);
      }
    }
  }

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

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(new AdWordsServices(), $session);
  }
}

GetAccountHierarchy::main();

Old

<?php
/**
 * This example gets the account hierarchy under the current account. Note: this
 * example must be run using the credentials of an AdWords manager account.
 *
 * PHP version 5
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * 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.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

// Include the initialization file
require_once dirname(dirname(__FILE__)) . '/init.php';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 */
function GetAccountHierarchyExample(AdWordsUser $user) {
  // Get the service, which loads the required classes.
  $managedCustomerService =
      $user->GetService('ManagedCustomerService', ADWORDS_VERSION);

  // Create selector.
  $selector = new Selector();
  // Specify the fields to retrieve.
  $selector->fields = array('CustomerId',  'Name');
  $selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);

  // Create map from customerID to account.
  $accounts = array();
  // Create map from customerId to parent and child links.
  $childLinks = array();
  $parentLinks = array();
  do {
    // Make the get request.
    $graph = $managedCustomerService->get($selector);

    // Create links between manager and clients.
    if (isset($graph->entries)) {
      if (isset($graph->links)) {
        foreach ($graph->links as $link) {
          $childLinks[$link->managerCustomerId][] = $link;
          $parentLinks[$link->clientCustomerId] = $link;
        }
      }
      foreach ($graph->entries as $account) {
        $accounts[$account->customerId] = $account;
      }
    }
    $selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
  } while ($selector->paging->startIndex < $graph->totalNumEntries);

  $rootAccount = null;
  foreach ($accounts as $account) {
    if (!array_key_exists($account->customerId, $parentLinks)) {
      $rootAccount = $account;
      break;
    }
  }

  if ($rootAccount !== null) {
    // Display account tree.
    print "(Customer Id, Account Name)\n";
    DisplayAccountTree($rootAccount, $accounts, $childLinks, 0);
  } else {
    printf("No accounts were found.\n");
  }
}

/**
 * Displays an account tree, starting at the account provided, and recursing to
 * all child accounts.
 * @param ManagedCustomer $account the account to display
 * @param array $accounts a map from customerId to account
 * @param array $links a map from customerId to child links
 * @param int $depth the depth of the current account in the tree
 */
function DisplayAccountTree($account, $accounts, $links, $depth) {
  print str_repeat('-', $depth * 2);
  printf("%s, %s\n", $account->customerId, $account->name);
  if (array_key_exists($account->customerId, $links)) {
    foreach ($links[$account->customerId] as $childLink) {
      $childAccount = $accounts[$childLink->clientCustomerId];
      DisplayAccountTree($childAccount, $accounts, $links, $depth + 1);
    }
  }
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Run the example.
  GetAccountHierarchyExample($user);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.