If you're still on v201609, please migrate to a newer version before October 2, 2017.

Account Management Samples

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

Create new account under an AdWords manager

#!/usr/bin/perl -w
#
# 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.
#
# This example illustrates how to create an account. By default, this account
# will only be visible via the parent AdWords manager account.

use strict;

use lib "../../../lib";
use utf8;

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201708::ManagedCustomer;
use Google::Ads::AdWords::v201708::ManagedCustomerOperation;

use Cwd qw(abs_path);
use Data::Uniqid qw(uniqid);

# Example main subroutine.
sub create_account {
  my $client = shift;

  # Create an account object with a currencyCode and a dateTimeZone
  # See https://developers.google.com/adwords/api/docs/appendix/currencycodes
  # and https://developers.google.com/adwords/api/docs/appendix/timezones
  my $account = Google::Ads::AdWords::v201708::ManagedCustomer->new({
      name         => "Managed Account #" . uniqid(),
      currencyCode => "USD",
      dateTimeZone => "America/New_York",
  });

  # Create the operation
  my $operation = Google::Ads::AdWords::v201708::ManagedCustomerOperation->new({
      operator => "ADD",
      operand  => $account
  });

  # Perform the operation. It is possible to create multiple accounts with one
  # request by sending multiple operations.
  my $response =
    $client->ManagedCustomerService->mutate({operations => [$operation],});

  if ($response) {
    my $new_account = $response->get_value();
    print "Account with customer ID ", $new_account->get_customerId(),
      " was created.\n";
  } else {
    print "No account was created.\n";
  }

  return 1;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Log SOAP XML request, response and API errors.
Google::Ads::AdWords::Logging::enable_all_logging();

# Get AdWords Client, credentials will be read from ~/adwords.properties.
my $client = Google::Ads::AdWords::Client->new({version => "v201708"});

# By default examples are set to die on any server returned fault.
$client->set_die_on_faults(1);

# Call the example
create_account($client);


Get all account changes during the past 24 hours

#!/usr/bin/perl -w
#
# 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.
#
# This example gets all account changes that happened within the last 24 hours,
# for all your campaigns.

use strict;
use lib "../../../lib";
use utf8;

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201708::CustomerSyncSelector;
use Google::Ads::AdWords::v201708::DateTimeRange;
use Google::Ads::AdWords::v201708::Selector;

use Cwd qw(abs_path);

sub get_formatted_list ($);

# Example main subroutine.
sub get_account_changes {
  my $client = shift;

  # A date range of last 24 hours.
  my ($sec, $min, $hour, $mday, $mon, $year) = localtime(time - (60 * 60 * 24));
  my $min_date_time = sprintf(
    "%d%02d%02d %02d%02d%02d",
    ($year + 1900),
    ($mon + 1),
    $mday, $hour, $min, $sec
  );
  ($sec, $min, $hour, $mday, $mon, $year) = localtime(time);
  my $max_date_time = sprintf(
    "%d%02d%02d %02d%02d%02d",
    ($year + 1900),
    ($mon + 1),
    $mday, $hour, $min, $sec
  );

  # Get a list of all campaign ids.
  my @campaign_ids = ();
  my $campaigns    = $client->CampaignService()->get({
      serviceSelector =>
        Google::Ads::AdWords::v201708::Selector->new({fields => ["Id"]})});
  if ($campaigns->get_entries()) {
    foreach my $campaign (@{$campaigns->get_entries()}) {
      push @campaign_ids, $campaign->get_id();
    }
  }

  # Create date time range.
  my $date_time_range = Google::Ads::AdWords::v201708::DateTimeRange->new({
      min => $min_date_time,
      max => $max_date_time
  });

  # Create selector.
  my $selector = Google::Ads::AdWords::v201708::CustomerSyncSelector->new({
      dateTimeRange => $date_time_range,
      campaignIds   => \@campaign_ids
  });

  # Get all account changes for campaign.
  my $account_changes =
    $client->CustomerSyncService()->get({selector => $selector});

  # Display changes.
  if ($account_changes && $account_changes->get_changedCampaigns()) {
    printf "Displaying changes up to: %s\n",
      $account_changes->get_lastChangeTimestamp();
    foreach my $campaign_changes (@{$account_changes->get_changedCampaigns()}) {
      printf "Campaign with id \"%d\" was changed:\n",
        $campaign_changes->get_campaignId();
      printf "\tCampaign changed status: %s\n",
        $campaign_changes->get_campaignChangeStatus();
      if ($campaign_changes->get_campaignChangeStatus() ne "NEW") {
        printf "\tAdded campaign criteria: %s\n",
          get_formatted_list($campaign_changes->get_addedCampaignCriteria());
        printf "\tRemoved campaign criteria: %s\n",
          get_formatted_list($campaign_changes->get_removedCampaignCriteria());

        if ($campaign_changes->get_changedAdGroups()) {
          foreach
            my $ad_group_changes (@{$campaign_changes->get_changedAdGroups()})
          {
            printf "\tAd group with id \"%d\" was changed:\n",
              $ad_group_changes->get_adGroupId();
            printf "\t\tAd group changed status: %s\n",
              $ad_group_changes->get_adGroupChangeStatus();
            if ($ad_group_changes->get_adGroupChangeStatus() ne "NEW") {
              printf "\t\tAds changed: %s\n",
                get_formatted_list($ad_group_changes->get_changedAds());
              printf "\t\tCriteria changed: %s\n",
                get_formatted_list($ad_group_changes->get_changedCriteria());
              printf "\t\tCriteria removed: %s\n",
                get_formatted_list($ad_group_changes->get_removedCriteria());
            }
          }
        }
      }
      print "\n";
    }
  } else {
    print "No account changes were found.\n";
  }

  return 1;
}

sub get_formatted_list ($) {
  my $list = $_[0];
  if (!$list) {
    return "{ }";
  }
  return "{ " . join(", ", @{$list}) . " }";
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Log SOAP XML request, response and API errors.
Google::Ads::AdWords::Logging::enable_all_logging();

# Get AdWords Client, credentials will be read from ~/adwords.properties.
my $client = Google::Ads::AdWords::Client->new({version => "v201708"});

# By default examples are set to die on any server returned fault.
$client->set_die_on_faults(1);

# Call the example
get_account_changes($client);

Get the account hierarchy under the current account

#!/usr/bin/perl -w
#
# 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.
#
# This example gets the account hierarchy under the current account.
#
# Note: This example won't work if your token is not approved and you are only
# targeting test accounts. See
# https://developers.google.com/adwords/api/docs/test-accounts

use strict;
use lib "../../../lib";
use utf8;

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201708::Paging;
use Google::Ads::AdWords::v201708::Selector;

use Cwd qw(abs_path);

use constant PAGE_SIZE => 500;

sub display_customers_tree;

# Example main subroutine.
sub get_account_hierarchy {
  my $client = shift;

  # Create selector.
  my $paging = Google::Ads::AdWords::v201708::Paging->new({
      startIndex    => 0,
      numberResults => PAGE_SIZE
  });
  my $selector = Google::Ads::AdWords::v201708::Selector->new({
      fields => ["Name", "CustomerId"],
      paging => $paging
  });

  my $page;
  my $customers = {};
  my $root_account;
  my $child_links  = {};
  my $parent_links = {};
  do {
    # Get account graph.
    $page =
      $client->ManagedCustomerService()->get({serviceSelector => $selector});

    # Display accounts graph.
    if ($page->get_entries()) {
      # Create map from customerId to parent and child links.
      if ($page->get_links()) {
        foreach my $link (@{$page->get_links()}) {
          if (!$child_links->{$link->get_managerCustomerId()}) {
            $child_links->{$link->get_managerCustomerId()} = [];
          }
          push @{$child_links->{$link->get_managerCustomerId()}}, $link;
          if (!$parent_links->{$link->get_clientCustomerId()}) {
            $parent_links->{$link->get_clientCustomerId()} = [];
          }
          push @{$parent_links->{$link->get_clientCustomerId()}}, $link;
        }
      }
      # Create map from customerID to account, and find root account.
      foreach my $customer (@{$page->get_entries()}) {
        $customers->{$customer->get_customerId()} = $customer;
        if (!$parent_links->{$customer->get_customerId()}) {
          $root_account = $customer;
        }
      }
    }
    $paging->set_startIndex($paging->get_startIndex() + PAGE_SIZE);
  } while ($paging->get_startIndex() < $page->get_totalNumEntries());

  # Display customers tree.
  print "CustomerId, Name\n";
  display_customers_tree($root_account, undef, $customers, $child_links, 0);

  return 1;
}

# Displays an account tree, starting at the account and link provided, and
# recursing to all child accounts.
sub display_customers_tree {
  my ($customer, $link, $customers, $links, $depth) = @_;
  print "-" x ($depth * 2);
  print " ";
  print $customer->get_customerId();
  print ", " .
    ($customer->get_name() ne "" ? $customer->get_name() : "(no name)");
  print "\n";
  if ($links->{$customer->get_customerId()}) {
    foreach my $child_link (@{$links->{$customer->get_customerId()}}) {
      my $child_account = $customers->{$child_link->get_clientCustomerId()};
      display_customers_tree($child_account, $child_link, $customers, $links,
        $depth + 1);
    }
  }
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Log SOAP XML request, response and API errors.
Google::Ads::AdWords::Logging::enable_all_logging();

# Get AdWords Client, credentials will be read from ~/adwords.properties.
my $client = Google::Ads::AdWords::Client->new({version => "v201708"});

# By default examples are set to die on any server returned fault.
$client->set_die_on_faults(1);

# Call the example
get_account_hierarchy($client);

Send feedback about...

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