Shopping Campaign Samples

The code samples below provide examples for managing Shopping campaigns using the AdWords API. Client Library.

Add product partition tree

#!/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 creates a ProductPartition tree.

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

use Data::Uniqid qw(uniqid);

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201710::AdGroupCriterionOperation;
use Google::Ads::AdWords::v201710::BiddableAdGroupCriterion;
use Google::Ads::AdWords::v201710::BiddingStrategyConfiguration;
use Google::Ads::AdWords::v201710::CpcBid;
use Google::Ads::AdWords::v201710::Criterion;
use Google::Ads::AdWords::v201710::Money;
use Google::Ads::AdWords::v201710::NegativeAdGroupCriterion;
use Google::Ads::AdWords::v201710::ProductBiddingCategory;
use Google::Ads::AdWords::v201710::ProductCanonicalCondition;
use Google::Ads::AdWords::v201710::ProductBrand;
use Google::Ads::AdWords::v201710::ProductPartition;

use Cwd qw(abs_path);

# Replace with valid values of your account.
my $ad_group_id = "INSERT_AD_GROUP_ID_HERE";

# Example main subroutine.
sub add_product_partition_tree {
  my ($client, $ad_group_id) = @_;

  my $operations = [];

  # The next temporary criterion ID to be used.
  #
  # When creating our tree we need to specify the parent-child relationships
  # between nodes. However, until a criterion has been created on the server
  # we do not have a criterionId with which to refer to it.
  #
  # Instead we can specify temporary IDs that are specific to a single mutate
  # request. Once the criteria have been created they are assigned an ID as
  # normal and the temporary ID will no longer refer to it.
  #
  # A valid temporary ID is any negative integer.
  my $next_id = -1;

  # The most trivial partition tree has only a unit node as the root:
  #   create_unit($operations, $ad_group_id, null, null, 100000);
  my $root = create_subdivision($operations, $next_id--, $ad_group_id);

  create_unit(
    $operations,
    $ad_group_id,
    $root,
    Google::Ads::AdWords::v201710::ProductCanonicalCondition->new(
      {condition => "NEW"}
    ),
    200000
  );

  create_unit(
    $operations,
    $ad_group_id,
    $root,
    Google::Ads::AdWords::v201710::ProductCanonicalCondition->new(
      {condition => "USED"}
    ),
    100000
  );

  my $other_condition =
    create_subdivision($operations, $next_id--, $ad_group_id, $root,
    Google::Ads::AdWords::v201710::ProductCanonicalCondition->new());

  create_unit($operations, $ad_group_id, $other_condition,
    Google::Ads::AdWords::v201710::ProductBrand->new({value => "CoolBrand"}),
    900000);

  create_unit($operations, $ad_group_id, $other_condition,
    Google::Ads::AdWords::v201710::ProductBrand->new({value => "CheapBrand"}),
    10000);

  my $other_brand =
    create_subdivision($operations, $next_id--, $ad_group_id, $other_condition,
    Google::Ads::AdWords::v201710::ProductBrand->new());

  # The value for the bidding category is a fixed ID for the 'Luggage & Bags'
  # category. You can retrieve IDs for categories from the ConstantDataService.
  # See the 'get_product_category_taxonomy' example for more details.
  create_unit(
    $operations,
    $ad_group_id,
    $other_brand,
    Google::Ads::AdWords::v201710::ProductBiddingCategory->new({
        type  => "BIDDING_CATEGORY_L1",
        value => -5914235892932915235
      }
    ),
    750000
  );

  create_unit(
    $operations,
    $ad_group_id,
    $other_brand,
    Google::Ads::AdWords::v201710::ProductBiddingCategory->new(
      {type => "BIDDING_CATEGORY_L1",}
    ),
    110000
  );

  my $result =
    $client->AdGroupCriterionService()->mutate({operations => $operations});

  my $children = {};
  my $root_node;
  # For each criterion, make an array containing each of its children.
  # We always create the parent before the child, so we can rely on that here.
  foreach my $ad_group_criterion (@{$result->get_value()}) {
    $children->{$ad_group_criterion->get_criterion()->get_id()} = [];

    my $parent_criterion_id =
      $ad_group_criterion->get_criterion()->get_parentCriterionId();
    if ($parent_criterion_id) {
      push $children->{$parent_criterion_id},
        $ad_group_criterion->get_criterion();
    } else {
      $root_node = $ad_group_criterion->get_criterion();
    }
  }

  # Show the tree
  display_tree($root_node, $children);

  return 1;
}

# Return a new subdivision product partition and add to the provided list
# an operation to create the partition. The parent and value fields
# should not be specified for the root node.
# operations: The list of operations to add to.
# temp_id: The temporary ID to use for the new partition.
# ad_group_id: The ID of the ad group for the new partition.
# parent: (Optional) The parent partition for the new partition.
# value: (Optional) The case value (product dimension) for the new partition.
sub create_subdivision {
  my ($operations, $temp_id, $ad_group_id, $parent, $value) = @_;
  my $division = Google::Ads::AdWords::v201710::ProductPartition->new({
      partitionType => "SUBDIVISION",
      id            => $temp_id
  });

  # The root node has neither a parent nor a value.
  if ($parent) {
    $division->set_parentCriterionId($parent->get_id());
    $division->set_caseValue($value);
  }

  my $criterion = Google::Ads::AdWords::v201710::BiddableAdGroupCriterion->new({
      adGroupId => $ad_group_id,
      criterion => $division
  });

  push $operations, create_add_operation($criterion);

  return $division;
}

# Return a new unit product partition and add to the provided list
# an operation to create the partition. The parent, value and bid_amount
# fields should not be specified for the root node.
# operations: The list of operations to add to.
# ad_group_id: The ID of the ad group for the new partition.
# parent: (Optional) The parent partition for the new partition.
# value: (Optional) The case value (product dimension) for the new partition.
# bid_amount: (Optional) The bid amount for the AdGroupCriterion.  If specified
#   then the AdGroupCriterion will be a BiddableAdGroupCriterion.
sub create_unit {
  my ($operations, $ad_group_id, $parent, $value, $bid_amount) = @_;
  my $unit = Google::Ads::AdWords::v201710::ProductPartition->new(
    {partitionType => "UNIT",});

  # The root node has neither a parent nor a value.
  if ($parent) {
    $unit->set_parentCriterionId($parent->get_id());
    $unit->set_caseValue($value);
  }

  my $criterion;
  if ($bid_amount && $bid_amount > 0) {
    my $biddingStrategyConfiguration =
      Google::Ads::AdWords::v201710::BiddingStrategyConfiguration->new({
        bids => [
          Google::Ads::AdWords::v201710::CpcBid->new({
              bid => Google::Ads::AdWords::v201710::Money->new(
                {microAmount => $bid_amount})})]});

    $criterion =
      Google::Ads::AdWords::v201710::BiddableAdGroupCriterion->new({
        biddingStrategyConfiguration => $biddingStrategyConfiguration
      });
  } else {
    $criterion = Google::Ads::AdWords::v201710::NegativeAdGroupCriterion->new();
  }

  $criterion->set_adGroupId($ad_group_id);
  $criterion->set_criterion($unit);

  push $operations, create_add_operation($criterion);

  return $unit;
}

# Return a new ADD operation for the specified ad group criterion.
# ad_group_criterion: The ad group criterion for the new operation.
sub create_add_operation {
  my ($ad_group_criterion) = @_;
  my $operation = Google::Ads::AdWords::v201710::AdGroupCriterionOperation->new(
    {
      operand  => $ad_group_criterion,
      operator => "ADD"
    });

  return $operation;
}

# Recursively display a node and each of its children.
# node: The node (Criterion) to display.
# children: Reference to a hash of each criterion ID to the array of its
#   child criteria.
# level: (Optional) The depth of node in the criteria tree.
sub display_tree {
  my ($node, $children, $level) = @_;

  # Recursively display a node and each of its children.
  $level = 0 unless $level;
  my $value = '';
  my $type  = '';

  my $node_dimension = $node->get_caseValue();
  if ($node_dimension) {
    $type = $node_dimension->get_ProductDimension__Type();
    if ($type eq 'ProductCanonicalCondition') {
      $value = $node_dimension->get_condition();
    } elsif ($type eq 'ProductBiddingCategory') {
      $value =
        $node_dimension->get_type() . "(" .
        ($node_dimension->get_value() or '') . ")";
    } elsif ($type eq 'ProductBrand') {
      $value = $node_dimension->get_value();
    } else {
      $value = $node_dimension;
    }
    $value = '' unless $value;
  }

  printf "%sid: %s, type: %s, value: %s\n", "  " x $level,
    $node->get_id(), $type, $value;
  foreach my $child_node (@{$children->{$node->get_id()}}) {
    display_tree($child_node, $children, $level + 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 => "v201710"});

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

# Call the example
add_product_partition_tree($client, $ad_group_id);

Add product scope

#!/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 restricts the products that will be included in the campaign by
# setting a ProductScope.

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

use Data::Uniqid qw(uniqid);

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201710::CampaignCriterion;
use Google::Ads::AdWords::v201710::CampaignCriterionOperation;
use Google::Ads::AdWords::v201710::ProductBiddingCategory;
use Google::Ads::AdWords::v201710::ProductBrand;
use Google::Ads::AdWords::v201710::ProductCanonicalCondition;
use Google::Ads::AdWords::v201710::ProductCustomAttribute;
use Google::Ads::AdWords::v201710::ProductOfferId;
use Google::Ads::AdWords::v201710::ProductScope;
use Google::Ads::AdWords::v201710::ProductType;

use Cwd qw(abs_path);

# Replace with valid values of your account.
my $campaign_id = "INSERT_CAMPAIGN_ID_HERE";

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

  my $product_scope = Google::Ads::AdWords::v201710::ProductScope->new({
      # This set of dimensions is for demonstration purposes only. It would be
      # extremely unlikely that you want to include so many dimensions in your
      # product scope.
      dimensions => [
        Google::Ads::AdWords::v201710::ProductBrand->new({value => "Nexus"}),
        Google::Ads::AdWords::v201710::ProductCanonicalCondition->new(
          {condition => "NEW"}
        ),
        Google::Ads::AdWords::v201710::ProductCustomAttribute->new({
            type  => "CUSTOM_ATTRIBUTE_0",
            value => "my attribute value"
          }
        ),
        Google::Ads::AdWords::v201710::ProductOfferId->new({value => "book1"}),
        Google::Ads::AdWords::v201710::ProductType->new({
            type  => "PRODUCT_TYPE_L1",
            value => "Media"
          }
        ),
        Google::Ads::AdWords::v201710::ProductType->new({
            type  => "PRODUCT_TYPE_L2",
            value => "Books"
          }
        ),
        # The value for the bidding category is a fixed ID for the
        # 'Luggage & Bags' category. You can retrieve IDs for categories from the
        # ConstantDataService. See the 'get_product_category_taxonomy' example for
        # more details.
        Google::Ads::AdWords::v201710::ProductBiddingCategory->new({
            type  => "BIDDING_CATEGORY_L1",
            value => -5914235892932915235
          })]});

  my $campaign_criterion =
    Google::Ads::AdWords::v201710::CampaignCriterion->new({
      campaignId => $campaign_id,
      criterion  => $product_scope
    });

  # Create operation.
  my $operation =
    Google::Ads::AdWords::v201710::CampaignCriterionOperation->new({
      operand  => $campaign_criterion,
      operator => "ADD"
    });

  # Make the mutate request.
  my $result =
    $client->CampaignCriterionService()->mutate({operations => [$operation]});

  # Display result.
  $campaign_criterion = $result->get_value()->[0];

  printf("Created a ProductScope criterion with ID '%s'.\n",
    $campaign_criterion->get_criterion()->get_id());

  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 => "v201710"});

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

# Call the example
add_product_scope($client, $campaign_id);

Add Shopping campaign

#!/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 adds a Shopping campaign.

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

use Data::Uniqid qw(uniqid);

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201710::AdGroup;
use Google::Ads::AdWords::v201710::AdGroupAd;
use Google::Ads::AdWords::v201710::AdGroupAdOperation;
use Google::Ads::AdWords::v201710::AdGroupCriterionOperation;
use Google::Ads::AdWords::v201710::AdGroupOperation;
use Google::Ads::AdWords::v201710::BiddableAdGroupCriterion;
use Google::Ads::AdWords::v201710::BiddingStrategyConfiguration;
use Google::Ads::AdWords::v201710::Budget;
use Google::Ads::AdWords::v201710::Campaign;
use Google::Ads::AdWords::v201710::CampaignOperation;
use Google::Ads::AdWords::v201710::CpcBid;
use Google::Ads::AdWords::v201710::ProductAd;
use Google::Ads::AdWords::v201710::ProductPartition;
use Google::Ads::AdWords::v201710::ShoppingSetting;

use Cwd qw(abs_path);

# Replace with valid values of your account.
my $budget_id   = "INSERT_BUDGET_ID_HERE";
my $merchant_id = "INSERT_MERCHANT_CENTER_ID_HERE";
# If set to true (1), a default partition will be created. If running the
# add_product_partition_tree.pl example right after this example,
# make sure this stays set to false (0).
my $create_default_partition = 0;

# Example main subroutine.
sub add_shopping_campaign {
  my ($client, $budget_id, $merchant_id, $create_default_partition) = @_;

  my $campaign = Google::Ads::AdWords::v201710::Campaign->new({
      name => "Shopping campaign #" . uniqid(),
      # The advertisingChannelType is what makes this a Shopping campaign
      advertisingChannelType => "SHOPPING",
      # Recommendation: Set the campaign to PAUSED when creating it to stop
      # the ads from immediately serving. Set to ENABLED once you've added
      # targeting and the ads are ready to serve.
      status => "PAUSED",
      # Set budget (required)
      budget =>
        Google::Ads::AdWords::v201710::Budget->new({budgetId => $budget_id}),
      # Set bidding strategy (required)
      biddingStrategyConfiguration =>
        Google::Ads::AdWords::v201710::BiddingStrategyConfiguration->new(
        {biddingStrategyType => "MANUAL_CPC"}
        ),
      # Set shopping setting (required)
      settings => [
        # All Shopping campaigns need a ShoppingSetting
        Google::Ads::AdWords::v201710::ShoppingSetting->new({
            salesCountry     => "US",
            campaignPriority => 0,
            merchantId       => $merchant_id,
            # By setting enableLocal to true (1) below, you will enable Local
            # Inventory Ads in your campaign. Set this to false (0) if you want
            # to disable this feature in your campaign.
            enableLocal => 1
          })]});

  # Create operation
  my $operation = Google::Ads::AdWords::v201710::CampaignOperation->new({
    operand  => $campaign,
    operator => "ADD"
  });

  # Make the mutate request
  my $result = $client->CampaignService()->mutate({operations => [$operation]});

  # Display result
  $campaign = $result->get_value()->[0];
  printf "Campaign name '%s' and ID %d was added.\n",
    $campaign->get_name(),
    $campaign->get_id();

  # Create ad group
  my $ad_group = Google::Ads::AdWords::v201710::AdGroup->new({
      campaignId => $campaign->get_id(),
      name       => "Ad Group #" . uniqid()});

  # Create operation
  $operation = Google::Ads::AdWords::v201710::AdGroupOperation->new({
    operand  => $ad_group,
    operator => "ADD"
  });

  # Make the mutate request
  $result = $client->AdGroupService()->mutate({operations => [$operation]});

  # Display result
  $ad_group = $result->get_value()->[0];
  printf "Ad group with name '%s' and ID %d was added.\n",
    $ad_group->get_name(),
    $ad_group->get_id();

  # Create product ad
  my $product_ad = Google::Ads::AdWords::v201710::ProductAd->new();

  # Create ad group ad
  my $ad_group_ad = Google::Ads::AdWords::v201710::AdGroupAd->new({
    adGroupId => $ad_group->get_id(),
    ad        => $product_ad
  });

  # Create operation
  $operation = Google::Ads::AdWords::v201710::AdGroupAdOperation->new({
    operand  => $ad_group_ad,
    operator => "ADD"
  });

  # Make the mutate request
  $result = $client->AdGroupAdService()->mutate({operations => [$operation]});

  # Display result
  $ad_group_ad = $result->get_value()->[0];
  printf "Product ad with ID %d was added.\n", $ad_group_ad->get_ad()->get_id();

  if ($create_default_partition) {
    # Create an ad group criterion for 'All products'.
    my $product_partition =
      Google::Ads::AdWords::v201710::ProductPartition->new({
        partitionType => 'UNIT',
        # Make sure the caseValue is null and the parentCriterionId is null.
        caseValue         => undef,
        parentCriterionId => undef
      });

    my $ad_group_criterion =
      Google::Ads::AdWords::v201710::BiddableAdGroupCriterion->new({
        adGroupId => $ad_group->get_id(),
        criterion => $product_partition,
        biddingStrategyConfiguration =>
          Google::Ads::AdWords::v201710::BiddingStrategyConfiguration->new({
            bids => [
              Google::Ads::AdWords::v201710::CpcBid->new({
                  bid => Google::Ads::AdWords::v201710::Money->new(
                    {microAmount => 500000})}
              ),
            ]})});

    # Create operation.
    $operation = Google::Ads::AdWords::v201710::AdGroupCriterionOperation->new({
      operator => "ADD",
      operand  => $ad_group_criterion
    });

    # Make the mutate request
    $result =
      $client->AdGroupCriterionService()->mutate({operations => [$operation]});

    # Display result
    $ad_group_criterion = $result->get_value()->[0];
    printf "Ad group criterion with ID %d in ad group with ID %d was added.\n",
      $ad_group_criterion->get_criterion()->get_id(),
      $ad_group_criterion->get_adGroupId();
  }

  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 => "v201710"});

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

# Call the example
add_shopping_campaign($client, $budget_id, $merchant_id,
  $create_default_partition);

Add campaign for Showcase Shopping ads

#!/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 adds a Shopping campaign for Showcase ads.

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

use Data::Uniqid qw(uniqid);

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201710::AdGroup;
use Google::Ads::AdWords::v201710::AdGroupAd;
use Google::Ads::AdWords::v201710::AdGroupAdOperation;
use Google::Ads::AdWords::v201710::AdGroupCriterionOperation;
use Google::Ads::AdWords::v201710::AdGroupOperation;
use Google::Ads::AdWords::v201710::BiddableAdGroupCriterion;
use Google::Ads::AdWords::v201710::Campaign;
use Google::Ads::AdWords::v201710::CampaignOperation;
use Google::Ads::AdWords::v201710::CpcBid;
use Google::Ads::AdWords::v201710::BiddingStrategyConfiguration;
use Google::Ads::AdWords::v201710::Budget;
use Google::Ads::AdWords::v201710::Image;
use Google::Ads::AdWords::v201710::Money;
use Google::Ads::AdWords::v201710::NegativeAdGroupCriterion;
use Google::Ads::AdWords::v201710::ProductCanonicalCondition;
use Google::Ads::AdWords::v201710::ProductPartition;
use Google::Ads::AdWords::v201710::ShoppingSetting;
use Google::Ads::AdWords::v201710::ShowcaseAd;
use Google::Ads::Common::MediaUtils;

use Cwd qw(abs_path);

# Replace with valid values of your account.
my $budget_id   = "INSERT_BUDGET_ID_HERE";
my $merchant_id = "INSERT_MERCHANT_CENTER_ID_HERE";

# Example main subroutine.
sub add_shopping_campaign_for_showcase_ads {
  my ($client, $budget_id, $merchant_id) = @_;

  my $campaign = _create_campaign($client, $budget_id, $merchant_id);
  printf "Campaign name '%s' and ID %d was added.\n",
    $campaign->get_name(),
    $campaign->get_id();

  my $ad_group = _create_ad_group($client, $campaign);
  printf "Ad group with name '%s' and ID %d was added.\n",
    $ad_group->get_name(),
    $ad_group->get_id();

  my $ad_group_ad = _create_showcase_ad($client, $ad_group);
  printf "Showcase ad with ID %d was added.\n",
    $ad_group_ad->get_ad()->get_id();

  my $ad_group_criterion =
    _create_product_partitions($client, $ad_group->get_id());
  printf "Product partition tree with %s nodes was added.\n",
    scalar @{$ad_group_criterion};

  return 1;
}

# Creates a shopping campaign.
sub _create_campaign {
  my ($client, $budget_id, $merchant_id) = @_;

  my $campaign = Google::Ads::AdWords::v201710::Campaign->new({
      name => "Shopping campaign #" . uniqid(),
      # The advertisingChannelType is what makes this a Shopping campaign
      advertisingChannelType => "SHOPPING",
      # Recommendation: Set the campaign to PAUSED when creating it to stop
      # the ads from immediately serving. Set to ENABLED once you've added
      # targeting and the ads are ready to serve.
      status => "PAUSED",
      # Set budget (required)
      budget =>
        Google::Ads::AdWords::v201710::Budget->new({budgetId => $budget_id}),
      # Set bidding strategy (required)
      biddingStrategyConfiguration =>
        Google::Ads::AdWords::v201710::BiddingStrategyConfiguration->new(
        {biddingStrategyType => "MANUAL_CPC"}
        ),
      # Set shopping setting (required)
      settings => [
        # All Shopping campaigns need a ShoppingSetting
        Google::Ads::AdWords::v201710::ShoppingSetting->new({
            salesCountry     => "US",
            campaignPriority => 0,
            merchantId       => $merchant_id,
            # By setting enableLocal to true (1) below, you will enable Local
            # Inventory Ads in your campaign. Set this to false (0) if you want
            # to disable this feature in your campaign.
            enableLocal => 1
          })]});

  # Create operation
  my $operation = Google::Ads::AdWords::v201710::CampaignOperation->new({
    operand  => $campaign,
    operator => "ADD"
  });

  # Make the mutate request
  my $result = $client->CampaignService()->mutate({operations => [$operation]});

  $campaign = $result->get_value()->[0];
  return $campaign;
}

# Creates an ad group in a Shopping campaign.
sub _create_ad_group {
  my ($client, $campaign) = @_;

  # Create ad group
  my $ad_group = Google::Ads::AdWords::v201710::AdGroup->new({
      campaignId => $campaign->get_id(),
      name       => "Ad Group #" . uniqid(),
      # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS.
      adGroupType => "SHOPPING_SHOWCASE_ADS",
      # Required: Set the ad group's bidding strategy configuration.
      # Showcase ads require either ManualCpc or EnhancedCpc in the campaign's
      # BiddingStrategyConfiguration.
      biddingStrategyConfiguration =>
        Google::Ads::AdWords::v201710::BiddingStrategyConfiguration->new({
          bids                => [
            Google::Ads::AdWords::v201710::CpcBid->new({
                bid => Google::Ads::AdWords::v201710::Money->new(
                  {microAmount => 1000000}
                ),
              }
            ),
          ]}
        ),
    });

  # Create operation
  my $operation = Google::Ads::AdWords::v201710::AdGroupOperation->new({
    operand  => $ad_group,
    operator => "ADD"
  });

  # Make the mutate request
  my $result = $client->AdGroupService()->mutate({operations => [$operation]});

  $ad_group = $result->get_value()->[0];
  return $ad_group;
}

# Creates a Showcase ad.
sub _create_showcase_ad {
  my ($client, $ad_group) = @_;

  # Create the Showcase ad.
  my $showcase_ad = Google::Ads::AdWords::v201710::ShowcaseAd->new({
    name       => "Showcase ad #" . uniqid(),
    finalUrls  => ["http://example.com/showcase"],
    displayUrl => "example.com"
  });

  # Required: Set the ad's expanded image.
  my $expanded_image = Google::Ads::AdWords::v201710::Image->new({
      mediaId => _upload_image(
        $client, "https://goo.gl/IfVlpF"
      )});
  $showcase_ad->set_expandedImage($expanded_image);

  # Optional: Set the collapsed image.
  my $collapsed_image = Google::Ads::AdWords::v201710::Image->new({
      mediaId => _upload_image(
        $client, "https://goo.gl/NqTxAE"
      )});
  $showcase_ad->set_collapsedImage($collapsed_image);

  # Create ad group ad.
  my $ad_group_ad = Google::Ads::AdWords::v201710::AdGroupAd->new({
    adGroupId => $ad_group->get_id(),
    ad        => $showcase_ad
  });

  # Create operation.
  my $operation = Google::Ads::AdWords::v201710::AdGroupAdOperation->new({
    operand  => $ad_group_ad,
    operator => "ADD"
  });

  # Make the mutate request.
  my $result =
    $client->AdGroupAdService()->mutate({operations => [$operation]});

  $ad_group_ad = $result->get_value()->[0];
  return $ad_group_ad;
}

# Uploads an image.
sub _upload_image {
  my ($client, $url) = @_;

  # Create image.
  my $image_data =
    Google::Ads::Common::MediaUtils::get_base64_data_from_url($url);
  my $image = Google::Ads::AdWords::v201710::Image->new({
    data => $image_data,
    type => "IMAGE"
  });

  # Upload image.
  $image = $client->MediaService()->upload({media => [$image]});
  return $image->get_mediaId();
}

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

# Creates the production partition tree for an ad group.
sub _create_product_partitions {
  my ($client, $ad_group_id) = @_;

  my $operations = [];
  my $next_id    = -1;

  # Make the root node a subdivision.
  my $root = _create_subdivision($operations, $next_id--, $ad_group_id);

  # Add a unit node for condition = NEW to include it.
  _create_unit(
    $operations,
    $ad_group_id,
    $root,
    Google::Ads::AdWords::v201710::ProductCanonicalCondition->new(
      {condition => "NEW"}));

  # Add a unit node for condition = USED to include it.
  _create_unit(
    $operations,
    $ad_group_id,
    $root,
    Google::Ads::AdWords::v201710::ProductCanonicalCondition->new(
      {condition => "USED"}));

  # Exclude everything else.
  _create_unit($operations, $ad_group_id, $root,
    Google::Ads::AdWords::v201710::ProductCanonicalCondition->new({}));

  my $result =
    $client->AdGroupCriterionService()->mutate({operations => $operations});
  my $ad_group_criterion = $result->get_value();
  return $ad_group_criterion;
}

# Return a new subdivision product partition and add to the provided list
# an operation to create the partition. The parent and value fields
# should not be specified for the root node.
# operations: The list of operations to add to.
# temp_id: The temporary ID to use for the new partition.
# ad_group_id: The ID of the ad group for the new partition.
# parent: (Optional) The parent partition for the new partition.
# value: (Optional) The case value (product dimension) for the new partition.
sub _create_subdivision {
  my ($operations, $temp_id, $ad_group_id, $parent, $value) = @_;
  my $division = Google::Ads::AdWords::v201710::ProductPartition->new({
    partitionType => "SUBDIVISION",
    id            => $temp_id
  });

  # The root node has neither a parent nor a value.
  if ($parent) {
    $division->set_parentCriterionId($parent->get_id());
    $division->set_caseValue($value);
  }

  my $ad_group_criterion =
    Google::Ads::AdWords::v201710::BiddableAdGroupCriterion->new({
      adGroupId => $ad_group_id,
      criterion => $division
    });

  my $operation = Google::Ads::AdWords::v201710::AdGroupCriterionOperation->new(
    {
      operand  => $ad_group_criterion,
      operator => "ADD"
    });
  push $operations, $operation;

  return $division;
}

# Return a new unit product partition and add to the provided list
# an operation to create the partition. The parent, value and bid_amount
# fields should not be specified for the root node.
# operations: The list of operations to add to.
# ad_group_id: The ID of the ad group for the new partition.
# parent: (Optional) The parent partition for the new partition.
# value: (Optional) The case value (product dimension) for the new partition.
# bid_amount: (Optional) The bid amount for the AdGroupCriterion.  If specified
#   then the AdGroupCriterion will be a BiddableAdGroupCriterion.
sub _create_unit {
  my ($operations, $ad_group_id, $parent, $value, $bid_amount) = @_;
  my $unit = Google::Ads::AdWords::v201710::ProductPartition->new(
    {partitionType => "UNIT",});

  # The root node has neither a parent nor a value.
  if ($parent) {
    $unit->set_parentCriterionId($parent->get_id());
    $unit->set_caseValue($value);
  }

  my $criterion;
  if ($bid_amount && $bid_amount > 0) {
    my $biddingStrategyConfiguration =
      Google::Ads::AdWords::v201710::BiddingStrategyConfiguration->new({
        bids => [
          Google::Ads::AdWords::v201710::CpcBid->new({
              bid => Google::Ads::AdWords::v201710::Money->new(
                {microAmount => $bid_amount})})]});

    $criterion =
      Google::Ads::AdWords::v201710::BiddableAdGroupCriterion->new(
      {biddingStrategyConfiguration => $biddingStrategyConfiguration});
  } else {
    $criterion = Google::Ads::AdWords::v201710::NegativeAdGroupCriterion->new();
  }

  $criterion->set_adGroupId($ad_group_id);
  $criterion->set_criterion($unit);

  my $operation = Google::Ads::AdWords::v201710::AdGroupCriterionOperation->new(
    {
      operand  => $criterion,
      operator => "ADD"
    });
  push $operations, $operation;

  return $unit;
}

# 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 => "v201710"});

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

# Call the example
add_shopping_campaign_for_showcase_ads($client, $budget_id, $merchant_id);

Get product category taxonomy

#!/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 fetches the set of valid ProductBiddingCategories.

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

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201710::Selector;
use Google::Ads::AdWords::v201710::Predicate;

use Cwd qw(abs_path);

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

  # Create selector.
  my $selector = Google::Ads::AdWords::v201710::Selector->new({
      fields     => ["DimensionValue", "ParentDimensionValue", "DisplayValue"],
      predicates => [
        Google::Ads::AdWords::v201710::Predicate->new({
            field    => "Country",
            operator => "IN",
            values   => ["US"]})]});

  my $results =
    $client->ConstantDataService()
    ->getProductBiddingCategoryData({selector => $selector});

  if ($results) {
    # %bidding_categories is a hash where key=dimension ID
    # and value=a hash of properties
    my %bidding_categories = ();
    my @root_categories    = ();
    foreach my $product_bidding_category_data (@{$results}) {
      my $id =
        $product_bidding_category_data->get_dimensionValue()->get_value();
      my $parent_id;
      my $name =
        $product_bidding_category_data->get_displayValue()->[0]->get_value();
      if ($product_bidding_category_data->get_parentDimensionValue()) {
        $parent_id =
          $product_bidding_category_data->get_parentDimensionValue()
          ->get_value();
      }

      if (!(exists $bidding_categories{$id})) {
        $bidding_categories{$id} = {};
      }

      my $category = $bidding_categories{$id};

      if ($parent_id) {
        if (!(exists $bidding_categories{$parent_id})) {
          $bidding_categories{$parent_id} = {};
        }
        my $parent = $bidding_categories{$parent_id};

        if (!(exists $parent->{"children"})) {
          $parent->{"children"} = [];
        }
        my $children = $parent->{"children"};
        push $children, $category;
      } else {
        push @root_categories, $category;
      }

      $category->{"id"}   = $id;
      $category->{"name"} = $name;
    }
    display_categories(\@root_categories, "");
  } else {
    print "No product bidding category data items were found.\n";
  }

  return 1;
}

sub display_categories {
  my $categories = shift;
  my $prefix     = shift;
  foreach my $category (@{$categories}) {
    printf "%s%s [%s]\n", $prefix, $category->{"name"}, $category->{"id"};
    if (exists $category->{"children"}) {
      my $category_name = $category->{"name"};
      my $children      = $category->{"children"};
      display_categories($children, "${prefix}${category_name} > ");
    }
  }
}

# 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 => "v201710"});

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

# Call the example
get_product_category_taxonomy($client);

Send feedback about...

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