Advanced Operations Samples

The code samples below provide examples of common advanced operations using the AdWords API. Client Library.

Add an ad customizer

<?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\v201708\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\AdCustomizerFeed;
use Google\AdsApi\AdWords\v201708\cm\AdCustomizerFeedAttribute;
use Google\AdsApi\AdWords\v201708\cm\AdCustomizerFeedAttributeType;
use Google\AdsApi\AdWords\v201708\cm\AdCustomizerFeedOperation;
use Google\AdsApi\AdWords\v201708\cm\AdCustomizerFeedService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201708\cm\ExpandedTextAd;
use Google\AdsApi\AdWords\v201708\cm\FeedItem;
use Google\AdsApi\AdWords\v201708\cm\FeedItemAdGroupTargeting;
use Google\AdsApi\AdWords\v201708\cm\FeedItemAttributeValue;
use Google\AdsApi\AdWords\v201708\cm\FeedItemOperation;
use Google\AdsApi\AdWords\v201708\cm\FeedItemService;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds an ad customizer feed and associates it with the customer.
 * Then it adds an ad that uses the feed to populate dynamic data.
 */
class AddAdCustomizer {

  const AD_GROUP_ID_1 = 'INSERT_AD_GROUP_ID_HERE';
  const AD_GROUP_ID_2 = 'INSERT_AD_GROUP_ID_HERE';
  const FEED_NAME = 'INSERT_FEED_NAME_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, array $adGroupIds, $feedName) {
    // Create a customizer feed. One feed per account can be used for all ads.
    $adCustomizerFeed =
        self::createCustomizerFeed($adWordsServices, $session, $feedName);

    // Add feed items containing the values we'd like to place in ads.
    self::createCustomizerFeedItems(
        $adWordsServices, $session, $adCustomizerFeed, $adGroupIds);

    // Create ads with customizations.
    self::createAdsWithCustomizations(
        $adWordsServices, $session, $adGroupIds, $feedName);
  }

  /**
   * Creates a new feed for AdCustomizerFeed.
   *
   * @param AdWordsServices $adWordsServices the AdWords services
   * @param AdWordsSession $session the AdWords session
   * @param string $feedName the name of feed to be created
   * @return AdCustomizerFeed the ad customizer feed
   */
  private static function createCustomizerFeed(AdWordsServices $adWordsServices,
      AdWordsSession $session, $feedName) {
    $adCustomizerFeedService =
        $adWordsServices->get($session, AdCustomizerFeedService::class);

    $nameAttribute = new AdCustomizerFeedAttribute();
    $nameAttribute->setName('Name');
    $nameAttribute->setType(AdCustomizerFeedAttributeType::STRING);

    $priceAttribute = new AdCustomizerFeedAttribute();
    $priceAttribute->setName('Price');
    $priceAttribute->setType(AdCustomizerFeedAttributeType::STRING);

    $dateAttribute = new AdCustomizerFeedAttribute();
    $dateAttribute->setName('Date');
    $dateAttribute->setType(AdCustomizerFeedAttributeType::DATE_TIME);

    $customizerFeed = new AdCustomizerFeed();
    $customizerFeed->setFeedName($feedName);
    $customizerFeed->setFeedAttributes(
        [$nameAttribute, $priceAttribute, $dateAttribute]);

    $feedOperation = new AdCustomizerFeedOperation();
    $feedOperation->setOperand($customizerFeed);
    $feedOperation->setOperator(Operator::ADD);
    $operations = [$feedOperation];

    $result = $adCustomizerFeedService->mutate($operations);
    $addedFeed = $result->getValue()[0];

    printf("Created ad customizer feed with ID %d and name '%s'.\n",
        $addedFeed->getFeedId(), $addedFeed->getFeedName());

    return $addedFeed;
  }

  /**
   * Creates feed items with the values to use in ad customizations for each ad
   * group.
   *
   * @param AdWordsServices $adWordsServices the AdWords services
   * @param AdWordsSession $session the AdWords session
   * @param AdCustomizerFeed $adCustomizerFeed the ad customizer feed
   * @param int[] $adGroupIds the ad group IDs to add the ad customizer
   */
  private static function createCustomizerFeedItems(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      AdCustomizerFeed $adCustomizerFeed,
      array $adGroupIds
  ) {
    $feedItemService = $adWordsServices->get($session, FeedItemService::class);

    $operations = [];

    $marsDate = mktime(0, 0, 0, date('m'), 1, date('Y'));
    $venusDate = mktime(0, 0, 0, date('m'), 15, date('Y'));

    // Create multiple feed item operations and add them to the operations list.
    $operations[] = self::createFeedItemAddOperation('Mars', '$1234.56',
        date('Ymd His', $marsDate), $adGroupIds[0], $adCustomizerFeed);
    $operations[] = self::createFeedItemAddOperation('Venus', '$1450.00',
        date('Ymd His', $venusDate), $adGroupIds[1], $adCustomizerFeed);

    $result = $feedItemService->mutate($operations);

    foreach ($result->getValue() as $feedItem) {
      printf("FeedItem with ID %d was added.\n", $feedItem->getFeedItemId());
    }
  }

  /**
   * Creates a feed item operation that will create a feed item with the
   * specified values and ad group target when sent to FeedItemService.mutate.
   *
   * @param string $name the value for the name attribute of the feed item
   * @param string $price the value for the price attribute of the feed item
   * @param string $date the value for the date attribute of the feed item
   * @param string $adGroupId the ID of the ad group to target with the feed
   *     item
   * @param AdCustomizerFeed $adCustomizerFeed the customizer feed
   * @return FeedItemOperation the feed item operation
   */
  private static function createFeedItemAddOperation($name, $price, $date,
      $adGroupId, AdCustomizerFeed $adCustomizerFeed) {
    $nameAttributeValue = new FeedItemAttributeValue();
    $nameAttributeValue->setFeedAttributeId(
        $adCustomizerFeed->getFeedAttributes()[0]->getId());
    $nameAttributeValue->setStringValue($name);

    $priceAttributeValue = new FeedItemAttributeValue();
    $priceAttributeValue->setFeedAttributeId(
        $adCustomizerFeed->getFeedAttributes()[1]->getId());
    $priceAttributeValue->setStringValue($price);

    $dateAttributeValue = new FeedItemAttributeValue();
    $dateAttributeValue->setFeedAttributeId(
        $adCustomizerFeed->getFeedAttributes()[2]->getId());
    $dateAttributeValue->setStringValue($date);

    $item = new FeedItem();
    $item->setFeedId($adCustomizerFeed->getFeedId());
    $item->setAttributeValues(
        [$nameAttributeValue, $priceAttributeValue, $dateAttributeValue]);

    $adGroupTargeting = new FeedItemAdGroupTargeting();
    $adGroupTargeting->setTargetingAdGroupId($adGroupId);
    $item->setAdGroupTargeting($adGroupTargeting);

    $operation = new FeedItemOperation();
    $operation->setOperand($item);
    $operation->setOperator('ADD');

    return $operation;
  }

  /**
   * Creates expanded text ads that use ad customizations for the specified
   * ad group IDs.
   *
   * @param AdWordsServices $adWordsServices the AdWords services
   * @param AdWordsSession $session the AdWords session
   * @param int[] $adGroupIds the ad group IDs to add the ad customizer
   * @param string $feedName the name of feed to be created
   */
  private static function createAdsWithCustomizations(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      array $adGroupIds,
      $feedName
  ) {
    $adGroupAdService =
        $adWordsServices->get($session, AdGroupAdService::class);
    $operations = [];

    // Create an expanded text ad that uses ad customization.
    $expandedTextAd = new ExpandedTextAd();
    $expandedTextAd->setHeadlinePart1(
        sprintf('Luxury Cruise to {=%s.Name}', $feedName));
    $expandedTextAd->setHeadlinePart2(
        sprintf('Only {=%s.Price}', $feedName));
    $expandedTextAd->setDescription(
        sprintf('Offer ends in {=countdown(%s.Date)}!', $feedName));
    $expandedTextAd->setFinalUrls(['http://www.example.com']);

    $adGroupAd = new AdGroupAd();
    $adGroupAd->setAdGroupId($adGroupIds[0]);
    $adGroupAd->setAd($expandedTextAd);

    $operation = new AdGroupAdOperation();
    $operation->setOperand($adGroupAd);
    $operation->setOperator(Operator::ADD);
    $operations[] = $operation;

    // Create another expanded text ad with the same properties as the first
    // one for another ad group.
    // This is done to prevent PHP SoapClient from making a reference
    // to this object in the generated XML payload, which is not recognized by
    // AdWords API.
    $expandedTextAd2 = new ExpandedTextAd();
    $expandedTextAd2->setHeadlinePart1(
        sprintf('Luxury Cruise to {=%s.Name}', $feedName));
    $expandedTextAd2->setHeadlinePart2(
        sprintf('Only {=%s.Price}', $feedName));
    $expandedTextAd2->setDescription(
        sprintf('Offer ends in {=countdown(%s.Date)}!', $feedName));
    $expandedTextAd2->setFinalUrls(['http://www.example.com']);

    $adGroupAd = new AdGroupAd();
    $adGroupAd->setAdGroupId($adGroupIds[1]);
    $adGroupAd->setAd($expandedTextAd2);

    $operation = new AdGroupAdOperation();
    $operation->setOperand($adGroupAd);
    $operation->setOperator(Operator::ADD);
    $operations[] = $operation;

    $result = $adGroupAdService->mutate($operations);

    foreach ($result->getValue() as $adGroupAd) {
      printf("Expanded text ad with ID %d and status '%s' was added.\n",
          $adGroupAd->getAd()->getId(), $adGroupAd->getStatus());
    }
  }

  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::AD_GROUP_ID_1), intval(self::AD_GROUP_ID_2)],
        self::FEED_NAME
    );
  }
}

AddAdCustomizer::main();

Add an ad group bid modifier

<?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\v201708\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\AdGroupBidModifier;
use Google\AdsApi\AdWords\v201708\cm\AdGroupBidModifierOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupBidModifierService;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\AdWords\v201708\cm\Platform;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This code example illustrates how to add ad group level mobile bid modifier
 * override for a campaign.
 */
class AddAdGroupBidModifier {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
  const BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $adGroupId, $bidModifier) {
    $adGroupBidModifierService =
        $adWordsServices->get($session, AdGroupBidModifierService::class);

    $operations = [];

    // Mobile criterion ID.
    $criterionId = 30001;
    // Prepare to add an ad group level override.
    $adGroupBidModifier = new AdGroupBidModifier();
    $adGroupBidModifier->setAdGroupId($adGroupId);
    $adGroupBidModifier->setCriterion(new Platform());
    $adGroupBidModifier->getCriterion()->setId($criterionId);
    $adGroupBidModifier->setBidModifier($bidModifier);

    $operation = new AdGroupBidModifierOperation();

    // Create an ad group bid modifier operation and add it to the list.
    $operation->setOperator(Operator::ADD);
    $operation->setOperand($adGroupBidModifier);
    $operations[] = $operation;

    // Create the ad group bid modifier on the server and print out some
    // information for each created ad group criterion.
    $result = $adGroupBidModifierService->mutate($operations);
    foreach ($result->getValue() as $adGroupBidModifier) {
      printf(
          "Ad group ID %d, criterion ID %d was updated with "
              . "ad group level modifier: %s\n",
          $adGroupBidModifier->getAdGroupId(),
          $adGroupBidModifier->getCriterion()->getId(),
          $adGroupBidModifier->getBidModifier()
      );
    }
  }

  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::AD_GROUP_ID),
        floatval(self::BID_MODIFIER)
    );
  }
}

AddAdGroupBidModifier::main();

Add a click-to-download ad

<?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\v201708\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201708\cm\Image;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\AdWords\v201708\cm\TemplateAd;
use Google\AdsApi\AdWords\v201708\cm\TemplateElement;
use Google\AdsApi\AdWords\v201708\cm\TemplateElementField;
use Google\AdsApi\AdWords\v201708\cm\TemplateElementFieldType;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This code example creates a click-to-download ad, also known as an
 * app promotion ad to a given ad group. To list ad groups, run
 * GetAdGroups.php.
 */
class AddClickToDownloadAd {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

    // Optionally specify a landscape image. The image needs to be in a BASE64
    // encoded form. Here we download a demo image and encode it for this ad.
    $imageData = file_get_contents('http://goo.gl/9JmyKk');

    $operations = [];
    // Create a template ad.
    $clickToDownloadAppAd = new TemplateAd();
    $clickToDownloadAppAd->setName('Ad for demo game');
    // 353 represents app install ad. See
    // https://developers.google.com/adwords/api/docs/appendix/templateads
    // for details.
    $clickToDownloadAppAd->setTemplateId(353);
    $clickToDownloadAppAd->setFinalUrls(
        ['http://play.google.com/store/apps/details?id=com.example.demogame']);
    $clickToDownloadAppAd->setDisplayUrl('play.google.com');

    // Create the template elements for the ad. You can refer to
    // https://developers.google.com/adwords/api/docs/appendix/templateads
    // for the list of avaliable template fields.
    $headline = new TemplateElementField();
    $headline->setName('headline');
    $headline->setFieldText('Enjoy your drive in Mars');
    $headline->setType(TemplateElementFieldType::TEXT);

    $description1 = new TemplateElementField();
    $description1->setName('description1');
    $description1->setFieldText('Realistic physics simulation');
    $description1->setType(TemplateElementFieldType::TEXT);

    $description2 = new TemplateElementField();
    $description2->setName('description2');
    $description2->setFieldText('Race against players online');
    $description2->setType(TemplateElementFieldType::TEXT);

    $appId = new TemplateElementField();
    $appId->setName('appId');
    $appId->setFieldText('com.example.demogame');
    $appId->setType(TemplateElementFieldType::TEXT);

    $appStore = new TemplateElementField();
    $appStore->setName('appStore');
    $appStore->setFieldText('2');
    $appStore->setType(TemplateElementFieldType::ENUM);

    $landscapeImage = new TemplateElementField();
    $landscapeImage->setName('landscapeImage');
    $image = new Image();
    $image->setData($imageData);
    $landscapeImage->setFieldMedia($image);
    $landscapeImage->setType(TemplateElementFieldType::IMAGE);

    $adData = new TemplateElement();
    $adData->setUniqueName('adData');
    $adData->setFields([$headline, $description1, $description2, $appId,
        $appStore, $landscapeImage]);

    $clickToDownloadAppAd->setTemplateElements([$adData]);

    // Create ad group ad.
    $adGroupAd = new AdGroupAd();
    $adGroupAd->setAdGroupId($adGroupId);
    $adGroupAd->setAd($clickToDownloadAppAd);
    // Optional: Set additional settings.
    $adGroupAd->setStatus(AdGroupAdStatus::PAUSED);

    // Create ad group ad operation and add it to the list.
    $operation = new AdGroupAdOperation();
    $operation->setOperand($adGroupAd);
    $operation->setOperator(Operator::ADD);
    $operations[] = $operation;

    // Create the ad group ad on the server and print out some information
    // about it.
    $result = $adGroupAdService->mutate($operations);
    foreach ($result->getValue() as $adGroupAd) {
      printf(
          "New click-to-download ad with ID %d and URL '%s' was created.\n",
          $adGroupAd->getAd()->getId(),
          $adGroupAd->getAd()->getFinalUrls()[0]
      );
    }
  }

  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::AD_GROUP_ID));
  }
}

AddClickToDownloadAd::main();

Add a page feed specifying URLs for a DSA campaign

<?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\v201708\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201708\cm\AttributeFieldMapping;
use Google\AdsApi\AdWords\v201708\cm\BiddableAdGroupCriterion;
use Google\AdsApi\AdWords\v201708\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201708\cm\Campaign;
use Google\AdsApi\AdWords\v201708\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201708\cm\CampaignService;
use Google\AdsApi\AdWords\v201708\cm\CpcBid;
use Google\AdsApi\AdWords\v201708\cm\DynamicSearchAdsSetting;
use Google\AdsApi\AdWords\v201708\cm\Feed;
use Google\AdsApi\AdWords\v201708\cm\FeedAttribute;
use Google\AdsApi\AdWords\v201708\cm\FeedAttributeType;
use Google\AdsApi\AdWords\v201708\cm\FeedItem;
use Google\AdsApi\AdWords\v201708\cm\FeedItemAttributeValue;
use Google\AdsApi\AdWords\v201708\cm\FeedItemOperation;
use Google\AdsApi\AdWords\v201708\cm\FeedItemService;
use Google\AdsApi\AdWords\v201708\cm\FeedMapping;
use Google\AdsApi\AdWords\v201708\cm\FeedMappingOperation;
use Google\AdsApi\AdWords\v201708\cm\FeedMappingService;
use Google\AdsApi\AdWords\v201708\cm\FeedOperation;
use Google\AdsApi\AdWords\v201708\cm\FeedOrigin;
use Google\AdsApi\AdWords\v201708\cm\FeedService;
use Google\AdsApi\AdWords\v201708\cm\Money;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\AdWords\v201708\cm\PageFeed;
use Google\AdsApi\AdWords\v201708\cm\Predicate;
use Google\AdsApi\AdWords\v201708\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201708\cm\Selector;
use Google\AdsApi\AdWords\v201708\cm\Webpage;
use Google\AdsApi\AdWords\v201708\cm\WebpageCondition;
use Google\AdsApi\AdWords\v201708\cm\WebpageConditionOperand;
use Google\AdsApi\AdWords\v201708\cm\WebpageParameter;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use InvalidArgumentException;

/**
 * This code example adds a page feed to specify precisely which URLs to use
 * with your Dynamic Search Ads campaign. To create a Dynamic Search Ads
 * campaign, run AddDynamicSearchAdsCampaign.php. To get campaigns, run
 * GetCampaigns.php.
 */
class AddDynamicPageFeed {

  const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

  // The criterion type to be used for DSA page feeds. DSA page feeds use
  // criterionType field instead of the placeholderType field unlike most other
  // feed types.
  const DSA_PAGE_FEED_CRITERION_TYPE = 61;

  // ID that corresponds to the page URLs.
  const DSA_PAGE_URLS_FIELD_ID = 1;

  // ID that corresponds to the labels.
  const DSA_LABEL_FIELD_ID = 2;

  public static function runExample(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      $campaignId,
      $adGroupId
  ) {
    $dsaPageUrlLabel = 'discounts';

    // Get the page feed details. This code example creates a new feed, but you
    // can fetch and re-use an existing feed.
    $feedDetails = self::createFeed($adWordsServices, $session);
    self::createFeedMapping($adWordsServices, $session, $feedDetails);
    self::createFeedItems(
        $adWordsServices, $session, $feedDetails, $dsaPageUrlLabel);

    // Associate the page feed with the campaign.
    self::updateCampaignDsaSetting(
        $adWordsServices, $session, $campaignId, $feedDetails);

    // Optional: Target web pages matching the feed's label in the ad group.
    self::addDsaTargeting(
        $adWordsServices, $session, $adGroupId, $dsaPageUrlLabel);

    printf("Dynamic page feed setup is complete for campaign ID %d.\n",
        $campaignId);
  }

  /**
   * Creates the feed for DSA page URLs.
   */
  private static function createFeed(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $feedService = $adWordsServices->get($session, FeedService::class);

    // Create feed attributes.
    $urlAttribute = new FeedAttribute();
    $urlAttribute->setType(FeedAttributeType::URL_LIST);
    $urlAttribute->setName('Page URL');

    $labelAttribute = new FeedAttribute();
    $labelAttribute->setType(FeedAttributeType::STRING_LIST);
    $labelAttribute->setName('Label');

    // Create the feed.
    $dsaPageFeed = new Feed();
    $dsaPageFeed->setName('DSA Feed #' . uniqid());
    $dsaPageFeed->setAttributes([$urlAttribute, $labelAttribute]);
    $dsaPageFeed->setOrigin(FeedOrigin::USER);

    // Create the feed operation and add it on the server.
    $operation = new FeedOperation();
    $operation->setOperator(Operator::ADD);
    $operation->setOperand($dsaPageFeed);
    $result = $feedService->mutate([$operation]);

    // Holds the feeds metadata.
    $feedDetails = new DSAFeedDetails();

    $savedFeed = $result->getValue()[0];
    $feedDetails->feedId = $savedFeed->getId();

    $savedAttributes = $savedFeed->getAttributes();
    $feedDetails->urlAttributeId = $savedAttributes[0]->getId();
    $feedDetails->labelAttributeId = $savedAttributes[1]->getId();

    // Print out some information about the created feed.
    printf(
        "Feed with name '%s', ID %d with urlAttributeId %d and "
            . "labelAttributeId %d was created.\n",
        $savedFeed->getName(),
        $feedDetails->feedId,
        $feedDetails->urlAttributeId,
        $feedDetails->labelAttributeId
    );

    return $feedDetails;
  }

  /**
   * Creates the feed mapping for the DSA page feeds.
   */
  private static function createFeedMapping(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      DSAFeedDetails $feedDetails
  ) {
    $feedMappingService =
        $adWordsServices->get($session, FeedMappingService::class);

    // Map the feed attribute IDs to the field ID constants.
    $urlFieldMapping = new AttributeFieldMapping();
    $urlFieldMapping->setFeedAttributeId(
        $feedDetails->urlAttributeId);
    $urlFieldMapping->setFieldId(self::DSA_PAGE_URLS_FIELD_ID);
    $labelFieldMapping = new AttributeFieldMapping();
    $labelFieldMapping->setFeedAttributeId(
        $feedDetails->labelAttributeId);
    $labelFieldMapping->setFieldId(self::DSA_LABEL_FIELD_ID);

    // Create the feed mapping and feed mapping operation.
    $feedMapping = new FeedMapping();
    $feedMapping->setCriterionType(self::DSA_PAGE_FEED_CRITERION_TYPE);
    $feedMapping->setFeedId($feedDetails->feedId);
    $feedMapping->setAttributeFieldMappings(
        [$urlFieldMapping, $labelFieldMapping]);

    $operation = new FeedMappingOperation();
    $operation->setOperand($feedMapping);
    $operation->setOperator(Operator::ADD);

    // Create the feed mapping operation on the server and print out some
    // information.
    $result = $feedMappingService->mutate([$operation]);
    $feedMapping = $result->getValue()[0];
    printf(
        "Feed mapping with ID %d and criterion type %d was saved for "
            .  "feed with ID %d.\n",
        $feedMapping->getFeedMappingId(),
        $feedMapping->getCriterionType(),
        $feedMapping->getFeedId()
    );
  }

  /**
   * Creates the page URLs in the DSA page feed.
   */
  private static function createFeedItems(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      DSAFeedDetails $feedDetails,
      $labelName
  ) {
    $feedItemService = $adWordsServices->get($session, FeedItemService::class);

    // Create operations to add feed items.
    $rentalCars = self::createDsaUrlAddOperation(
        $feedDetails,
        'http://www.example.com/discounts/rental-cars',
        $labelName
    );
    $hotelDeals = self::createDsaUrlAddOperation(
        $feedDetails,
        'http://www.example.com/discounts/hotel-deals',
        $labelName
    );
    $flightDeals = self::createDsaUrlAddOperation(
        $feedDetails,
        'http://www.example.com/discounts/flight-deals',
        $labelName
    );

    // Add feed item operations on the server and print out some information.
    $result = $feedItemService->mutate(
        [$rentalCars, $hotelDeals, $flightDeals]);
    foreach ($result->getValue() as $feedItem) {
      printf("Feed item with feed item ID %d was added.\n",
          $feedItem->getFeedItemId());
    }
  }

  /**
   * Creates a feed item operation to add the DSA URL.
   */
  private static function createDsaUrlAddOperation(
      DSAFeedDetails $feedDetails, $url, $labelName) {
    // Create the FeedItemAttributeValues for the URL and label.
    $urlAttributeValue = new FeedItemAttributeValue();
    $urlAttributeValue->setFeedAttributeId($feedDetails->urlAttributeId);

    // Optional: Add the {feeditem} valuetrack parameter to track which page
    // feed items lead to each click.
    $url = $url . '?id={feeditem}';
    $urlAttributeValue->setStringValues([$url]);

    $labelAttributeValue = new FeedItemAttributeValue();
    $labelAttributeValue->setFeedAttributeId(
        $feedDetails->labelAttributeId);
    $labelAttributeValue->setStringValues([$labelName]);

    // Create the feed item.
    $feedItem = new FeedItem();
    $feedItem->setFeedId($feedDetails->feedId);
    $feedItem->setAttributeValues([$urlAttributeValue, $labelAttributeValue]);

    // Create the feed item operation.
    $operation = new FeedItemOperation();
    $operation->setOperand($feedItem);
    $operation->setOperator(Operator::ADD);

    return $operation;
  }

  /**
   * Updates the campaign DSA setting to add DSA pagefeeds.
   */
  private static function updateCampaignDsaSetting(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      $campaignId,
      DSAFeedDetails $feedDetails
  ) {
    $campaignService = $adWordsServices->get($session, CampaignService::class);

    // Create selector.
    $selector = new Selector();
    $selector->setFields(['Id', 'Settings']);
    $selector->setPredicates(
        [new Predicate('CampaignId', PredicateOperator::IN, [$campaignId])]);

    $result = $campaignService->get($selector);
    if (empty($result->getEntries()) || $result->getTotalNumEntries() === 0) {
      throw new InvalidArgumentException(
          'No campaign found with ID: ' . $campaignId);
    }
    $campaign = $result->getEntries()[0];

    if ($campaign->getSettings() === null) {
      throw new InvalidArgumentException(
          'Campaign with ID ' . $campaignId . ' is not a DSA campaign.');
    }

    $dsaSetting = null;
    foreach ($campaign->getSettings() as $setting) {
      if ($setting instanceof DynamicSearchAdsSetting) {
        $dsaSetting = $setting;
        break;
      }
    }

    if ($dsaSetting === null) {
      throw new InvalidArgumentException(
          'Campaign with ID ' . $campaignId . ' is not a DSA campaign.');
    }

    // Use a page feed to specify precisely which URLs to use with your
    // Dynamic Search Ads.
    $pageFeed = new PageFeed();
    $pageFeed->setFeedIds([$feedDetails->feedId]);
    $dsaSetting->setPageFeed($pageFeed);

    // Optional: Specify whether only the supplied URLs should be used with your
    // Dynamic Search Ads.
    $dsaSetting->setUseSuppliedUrlsOnly(true);

    $updatedCampaign = new Campaign();
    $updatedCampaign->setId($campaignId);
    $updatedCampaign->setSettings($campaign->getSettings());

    $operation = new CampaignOperation();
    $operation->setOperand($updatedCampaign);
    $operation->setOperator(Operator::SET);

    // Update the campaign on the server and print out some information.
    $result = $campaignService->mutate([$operation]);
    $updatedCampaign = $result->getValue()[0];
    printf("DSA page feed for campaign ID %d was updated with feed ID %d.\n",
        $updatedCampaign->getId(), $feedDetails->feedId);
  }

  /**
   * Sets custom targeting for the page feed URLs based on a list of labels.
   */
  private static function addDsaTargeting(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      $adGroupId,
      $dsaPageUrlLabel
  ) {
    $adGroupCriterionService =
        $adWordsServices->get($session, AdGroupCriterionService::class);

    // Create a webpage criterion.
    $webpage = new Webpage();

    $parameter = new WebpageParameter();
    $parameter->setCriterionName('Test criterion');
    $webpage->setParameter($parameter);

    // Add a condition for label=specified_label_name.
    $condition = new WebpageCondition();
    $condition->setOperand(WebpageConditionOperand::CUSTOM_LABEL);
    $condition->setArgument($dsaPageUrlLabel);
    $parameter->setConditions([$condition]);

    $criterion = new BiddableAdGroupCriterion();
    $criterion->setAdGroupId($adGroupId);
    $criterion->setCriterion($webpage);

    // Set a custom bid for this criterion.
    $biddingStrategyConfiguration = new BiddingStrategyConfiguration();

    $cpcBid = new CpcBid();
    $money = new Money();
    $money->setMicroAmount(1500000);
    $cpcBid->setBid($money);
    $biddingStrategyConfiguration->setBids([$cpcBid]);

    $criterion->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

    $operation = new AdGroupCriterionOperation();
    $operation->setOperand($criterion);
    $operation->setOperator(Operator::ADD);

    // Create ad group criterion on the server and print out some information.
    $result = $adGroupCriterionService->mutate([$operation]);
    $criterion = $result->getValue()[0];
    printf("Web page criterion with ID %d and status '%s' was created.\n",
        $criterion->getCriterion()->getId(), $criterion->getUserStatus());
  }

  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::CAMPAIGN_ID),
        intval(self::AD_GROUP_ID)
    );
  }
}

/**
 * Class to keep track of DSA page feed details.
 */
final class DSAFeedDetails {
  public $feedId;
  public $urlAttributeId;
  public $labelAttributeId;
}

AddDynamicPageFeed::main();

Add a DSA campaign

<?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\v201708\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\AdGroup;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201708\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupStatus;
use Google\AdsApi\AdWords\v201708\cm\AdGroupType;
use Google\AdsApi\AdWords\v201708\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201708\cm\BiddableAdGroupCriterion;
use Google\AdsApi\AdWords\v201708\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201708\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201708\cm\Budget;
use Google\AdsApi\AdWords\v201708\cm\BudgetBudgetDeliveryMethod;
use Google\AdsApi\AdWords\v201708\cm\BudgetOperation;
use Google\AdsApi\AdWords\v201708\cm\BudgetService;
use Google\AdsApi\AdWords\v201708\cm\Campaign;
use Google\AdsApi\AdWords\v201708\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201708\cm\CampaignService;
use Google\AdsApi\AdWords\v201708\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201708\cm\CpcBid;
use Google\AdsApi\AdWords\v201708\cm\DynamicSearchAdsSetting;
use Google\AdsApi\AdWords\v201708\cm\ExpandedDynamicSearchAd;
use Google\AdsApi\AdWords\v201708\cm\Money;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\AdWords\v201708\cm\UserStatus;
use Google\AdsApi\AdWords\v201708\cm\Webpage;
use Google\AdsApi\AdWords\v201708\cm\WebpageCondition;
use Google\AdsApi\AdWords\v201708\cm\WebpageConditionOperand;
use Google\AdsApi\AdWords\v201708\cm\WebpageParameter;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This code example adds a Dynamic Search Ads campaign. To get campaigns,
 * run GetCampaigns.php.
 */
class AddDynamicSearchAdsCampaign {

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $budget = self::createBudget($adWordsServices, $session);

    $campaign = self::createCampaign($adWordsServices, $session, $budget);
    $adGroup = self::createAdGroup($adWordsServices, $session, $campaign);
    self::createExpandedDSA($adWordsServices, $session, $adGroup);
    self::addWebPageCriteria($adWordsServices, $session, $adGroup);
  }

  /**
   * Creates the budget.
   */
  private static function createBudget(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $budgetService = $adWordsServices->get($session, BudgetService::class);

    // Create a budget, which can be shared by multiple campaigns.
    $sharedBudget = new Budget();
    $sharedBudget->setName('Interplanetary Cruise #' . uniqid());
    $money = new Money();
    $money->setMicroAmount(50000000);
    $sharedBudget->setAmount($money);
    $sharedBudget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD);

    // Create a budget operation.
    $operation = new BudgetOperation();
    $operation->setOperand($sharedBudget);
    $operation->setOperator(Operator::ADD);

    // Create the budget on the server.
    $result = $budgetService->mutate([$operation]);
    $sharedBudget = $result->getValue()[0];

    return $sharedBudget;
  }

  /**
   * Creates the campaign.
   */
  private static function createCampaign(AdWordsServices $adWordsServices,
      AdWordsSession $session, Budget $budget) {
    $campaignService = $adWordsServices->get($session, CampaignService::class);

    // Create campaign with some properties set.
    $campaign = new Campaign();
    $campaign->setName('Interplanetary Cruise #' . uniqid());
    $campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH);

    // Recommendation: Set the campaign to PAUSED when creating it to prevent
    // the ads from immediately serving. Set to ENABLED once you've added
    // targeting and the ads are ready to serve.
    $campaign->setStatus(CampaignStatus::PAUSED);

    $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
    $biddingStrategyConfiguration->setBiddingStrategyType(
        BiddingStrategyType::MANUAL_CPC);
    $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

    // Only the budgetId should be sent, all other fields will be ignored by
    // CampaignService.
    $campaignBudget = new Budget();
    $campaignBudget->setBudgetId($budget->getBudgetId());
    $campaign->setBudget($campaignBudget);

    // Required: Set the campaign's Dynamic Search Ads settings.
    $dynamicSearchAdsSetting = new DynamicSearchAdsSetting();
    // Required: Set the domain name and language.
    $dynamicSearchAdsSetting->setDomainName('example.com');
    $dynamicSearchAdsSetting->setLanguageCode('en');

    // Set the campaign settings.
    $campaign->setSettings([$dynamicSearchAdsSetting]);

    // Optional: Set the start date.
    $campaign->setStartDate(date('Ymd', strtotime('+1 day')));
    // Optional: Set the end date.
    $campaign->setEndDate(date('Ymd', strtotime('+1 year')));

    // Create a campaign operation.
    $operation = new CampaignOperation();
    $operation->setOperand($campaign);
    $operation->setOperator(Operator::ADD);

    // Create the campaign on the server and print out some information.
    $result = $campaignService->mutate([$operation]);
    $campaign = $result->getValue()[0];
    printf("Campaign with name '%s' and ID %d was added.\n",
        $campaign->getName(), $campaign->getId());

    return $campaign;
  }

  /**
   * Creates the ad group.
   */
  private static function createAdGroup(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      Campaign $campaign
  ) {
    $adGroupService = $adWordsServices->get($session, AdGroupService::class);

    // Create the ad group.
    $adGroup = new AdGroup();

    // Required: Set the ad group's type to Dynamic Search Ads.
    $adGroup->setAdGroupType(AdGroupType::SEARCH_DYNAMIC_ADS);

    $adGroup->setName('Interplanetary Cruise #' . uniqid());
    $adGroup->setCampaignId($campaign->getId());
    $adGroup->setStatus(AdGroupStatus::PAUSED);

    // Recommended: Set a tracking URL template for your ad group if you want to
    // use URL tracking software.
    $adGroup->setTrackingUrlTemplate(
        'http://tracker.example.com/traveltracker/{escapedlpurl}');

    // Set the ad group bids.
    $biddingStrategyConfiguration = new BiddingStrategyConfiguration();

    $cpcBid = new CpcBid();
    $money = new Money();
    $money->setMicroAmount(3000000);
    $cpcBid->setBid($money);
    $biddingStrategyConfiguration->setBids([$cpcBid]);

    $adGroup->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

    // Create an ad group operation.
    $operation = new AdGroupOperation();
    $operation->setOperand($adGroup);
    $operation->setOperator(Operator::ADD);

    // Create the ad group on the server and print out some information.
    $result = $adGroupService->mutate([$operation]);
    $adGroup = $result->getValue()[0];
    printf("Ad group with name '%s' and ID %d was added.\n",
        $adGroup->getName(), $adGroup->getId());

    return $adGroup;
  }

  /**
   * Creates the expanded Dynamic Search Ad.
   */
  private static function createExpandedDSA(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      AdGroup $adGroup
  ) {
    $adGroupAdService
        = $adWordsServices->get($session, AdGroupAdService::class);

    // Create the expanded Dynamic Search Ad. This ad will have its headline
    // and final URL auto-generated at serving time according to domain name
    // specific information provided by DynamicSearchAdsSetting at the
    // campaign level.
    $expandedDSA = new ExpandedDynamicSearchAd();
    // Set the ad description.
    $expandedDSA->setDescription('Buy your tickets now!');

    // Create the ad group ad.
    $adGroupAd = new AdGroupAd();
    $adGroupAd->setAdGroupId($adGroup->getId());
    $adGroupAd->setAd($expandedDSA);

    // Optional: Set the status.
    $adGroupAd->setStatus(AdGroupAdStatus::PAUSED);

    // Create the operation.
    $operation = new AdGroupAdOperation();
    $operation->setOperator(Operator::ADD);
    $operation->setOperand($adGroupAd);

    // Create the ad on the server and print some information.
    $result = $adGroupAdService->mutate([$operation]);
    $newAdGroupAd = $result->getValue()[0];
    $expandedDSA = $newAdGroupAd->getAd();
    printf(
        "Expanded Dynamic Search Ad with ID %d and description '%s' was"
            . " added.\n",
        $expandedDSA->getId(),
        $expandedDSA->getDescription()
    );
  }

  /**
   * Adds a web page criteria to target Dynamic Search Ads.
   */
  private static function addWebPageCriteria(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      AdGroup $adGroup
  ) {
    $adGroupCriterionService
        = $adWordsServices->get($session, AdGroupCriterionService::class);

    // Create a webpage criterion for special offers.
    $param = new WebpageParameter();
    $param->setCriterionName('Special offers');

    // Create a webpage criterion for special offers.
    $urlCondition = new WebpageCondition();
    $urlCondition->setOperand(WebpageConditionOperand::URL);
    $urlCondition->setArgument('/specialoffers');

    $titleCondition = new WebpageCondition();
    $titleCondition->setOperand(WebpageConditionOperand::PAGE_TITLE);
    $titleCondition->setArgument('Special Offer');

    $param->setConditions([$urlCondition, $titleCondition]);

    $webpage = new Webpage();
    $webpage->setParameter($param);

    // Create a biddable ad group criterion.
    $biddableAdGroupCriterion = new BiddableAdGroupCriterion();
    $biddableAdGroupCriterion->setAdGroupId($adGroup->getId());
    $biddableAdGroupCriterion->setCriterion($webpage);
    $biddableAdGroupCriterion->setUserStatus(UserStatus::PAUSED);

    // Set a custom bid for this criterion.
    $biddingStrategyConfiguration = new BiddingStrategyConfiguration();

    // Optional: set a custom bid.
    $cpcBid = new CpcBid();
    $money = new Money();
    $money->setMicroAmount(10000000);
    $cpcBid->setBid($money);
    $biddingStrategyConfiguration->setBids([$cpcBid]);
    $biddableAdGroupCriterion->setBiddingStrategyConfiguration(
        $biddingStrategyConfiguration);

    $operation = new AdGroupCriterionOperation();
    $operation->setOperand($biddableAdGroupCriterion);
    $operation->setOperator(Operator::ADD);

    // Create the criterion on the server and print out some information.
    $result = $adGroupCriterionService->mutate([$operation]);
    $adGroupCriterion = $result->getValue()[0];
    printf(
        "Web page criterion with ID %d was added to ad group ID %d.\n",
        $adGroupCriterion->getCriterion()->getId(),
        $adGroupCriterion->getAdGroupId()
    );
  }

  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);
  }
}

AddDynamicSearchAdsCampaign::main();

Add an expanded text ad with Upgraded URLs

<?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\v201708\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201708\cm\CustomParameter;
use Google\AdsApi\AdWords\v201708\cm\CustomParameters;
use Google\AdsApi\AdWords\v201708\cm\ExpandedTextAd;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds an expanded text ad to an ad group that uses upgraded URLs.
 * To get ad groups, run GetAdGroups.php.
 */
class AddExpandedTextAdWithUpgradedUrls {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

    $operations = [];
    // Create expanded text ad with a tracking template and custom parameters.
    $expandedTextAd = new ExpandedTextAd();
    $expandedTextAd->setHeadlinePart1('Luxury Cruise to Mars');
    $expandedTextAd->setHeadlinePart2('Visit the Red Planet in style.');
    $expandedTextAd->setDescription('Low-gravity fun for everyone!');

    // Specify a tracking url for 3rd party tracking provider. You may
    // specify one at customer, campaign, ad group, ad, criterion or
    // feed item levels.
    $expandedTextAd->setTrackingUrlTemplate(
        'http://tracker.example.com/?season={_season}&promocode={_promocode}'
            . '&u={lpurl}'
    );

    // Since your tracking url has two custom parameters, provide their
    // values too. This can be provided at campaign, ad group, ad, criterion
    // or feed item levels.
    $seasonParameter = new CustomParameter();
    $seasonParameter->setKey('season');
    $seasonParameter->setValue('christmas');

    $promoCodeParameter = new CustomParameter();
    $promoCodeParameter->setKey('promocode');
    $promoCodeParameter->setValue('NYC123');

    $expandedTextAd->setUrlCustomParameters(new CustomParameters());
    $expandedTextAd->getUrlCustomParameters()->setParameters(
        [$seasonParameter, $promoCodeParameter]);

    // Specify a list of final urls. This field cannot be set if url field is
    // set. This may be specified at ad, criterion and feed item levels.
    $expandedTextAd->setFinalUrls([
        'http://www.example.com/cruise/space/',
        'http://www.example.com/locations/mars/'
    ]);

    // Specify a list of final mobile urls. This field cannot be set if url
    // field is set, or finalUrls is unset. This may be specified at ad,
    // criterion and feed item levels.
    $expandedTextAd->setFinalMobileUrls([
        'http://mobile.example.com/cruise/space/',
        'http://mobile.example.com/locations/mars/'
    ]);

    // Create ad group ad.
    $adGroupAd = new AdGroupAd();
    $adGroupAd->setAdGroupId($adGroupId);
    $adGroupAd->setAd($expandedTextAd);
    // Optional: Set additional settings.
    $adGroupAd->setStatus(AdGroupAdStatus::PAUSED);

    // Create ad group ad operation and add it to the list.
    $operation = new AdGroupAdOperation();
    $operation->setOperand($adGroupAd);
    $operation->setOperator(Operator::ADD);
    $operations[] = $operation;

    // Add an expanded text ad on the server.
    $result = $adGroupAdService->mutate($operations);

    // Create the expanded text ad on the server and print out its information.
    foreach ($result->getValue() as $adGroupAd) {
      $ad = $adGroupAd->getAd();
      printf("Ad with ID %d was added.\n", $ad->getId());
      print("Upgraded URL properties:\n");
      printf("  Final URLs: %s\n", implode(', ', $ad->getFinalUrls()));
      printf("  Final Mobile URLs: %s\n",
          implode(', ', $ad->getFinalMobileUrls()));
      printf("  Tracking URL template: %s\n", $ad->getTrackingUrlTemplate());
      printf("  Custom parameters: %s\n",
          implode(', ', array_map(
              function($param) {
                return sprintf('%s=%s', $param->getKey(), $param->getValue());
              },
              $ad->getUrlCustomParameters()->getParameters()
          ))
      );
    }
  }

  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::AD_GROUP_ID));
  }
}

AddExpandedTextAdWithUpgradedUrls::main();

Add an HTML 5 ad to an ad group

<?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\v201708\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201708\cm\Dimensions;
use Google\AdsApi\AdWords\v201708\cm\MediaBundle;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\AdWords\v201708\cm\TemplateAd;
use Google\AdsApi\AdWords\v201708\cm\TemplateElement;
use Google\AdsApi\AdWords\v201708\cm\TemplateElementField;
use Google\AdsApi\AdWords\v201708\cm\TemplateElementFieldType;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds an HTML5 ad to given ad group. To get ad groups, run
 * GetAdGroups.php.
 */
class AddHtml5Ad {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

    $operations = [];
    // Create a template ad.
    $html5Ad = new TemplateAd();
    $html5Ad->setName('Ad for HTML5');
    // 419 represents uploaded HTML5 bundle. See
    // https://developers.google.com/adwords/api/docs/appendix/templateads
    // for details.
    $html5Ad->setTemplateId(419);
    $html5Ad->setFinalUrls(['http://example.com/html5']);
    $html5Ad->setDisplayUrl('example.com/html5');

    $dimensions = new Dimensions();
    $dimensions->setWidth(300);
    $dimensions->setHeight(250);
    $html5Ad->setDimensions($dimensions);

    // The HTML5 zip file contains all the HTML, CSS, and images needed for the
    // HTML5 ad. For help on creating an HTML5 zip file, check out Google Web
    // Designer (https://www.google.com/webdesigner/).
    $html5Zip = file_get_contents('https://goo.gl/9Y7qI2');

    // Create a media bundle containing the zip file with all the HTML5
    // components.
    // NOTE: You may also upload an HTML5 zip using MediaService.upload()
    // and simply set the mediaId field below. See UploadMediaBundle.php for an
    // example.
    $mediaBundle = new MediaBundle();
    $mediaBundle->setData($html5Zip);
    $mediaBundle->setEntryPoint('carousel/index.html');
    $mediaBundle->setType('MEDIA_BUNDLE');

    // Create the template elements for the ad. You can refer to
    // https://developers.google.com/adwords/api/docs/appendix/templateads
    // for the list of avaliable template fields.
    $media = new TemplateElementField();
    $media->setName('Custom_layout');
    $media->setFieldMedia($mediaBundle);
    $media->setType(TemplateElementFieldType::MEDIA_BUNDLE);

    $layout = new TemplateElementField();
    $layout->setName('layout');
    $layout->setFieldText('Custom');
    $layout->setType(TemplateElementFieldType::ENUM);

    $adData = new TemplateElement();
    $adData->setUniqueName('adData');
    $adData->setFields([$media, $layout]);

    $html5Ad->setTemplateElements([$adData]);

    // Create ad group ad.
    $adGroupAd = new AdGroupAd();
    $adGroupAd->setAdGroupId($adGroupId);
    $adGroupAd->setAd($html5Ad);
    // Optional: Set additional settings.
    $adGroupAd->setStatus(AdGroupAdStatus::PAUSED);

    // Create ad group ad operation and add it to the list.
    $operation = new AdGroupAdOperation();
    $operation->setOperand($adGroupAd);
    $operation->setOperator(Operator::ADD);
    $operations[] = $operation;

    // Create the ad group ad on the server and print out some information
    // about it.
    $result = $adGroupAdService->mutate($operations);
    foreach ($result->getValue() as $adGroupAd) {
      printf(
          "New HTML5 ad with ID %d and display URL '%s' was created.\n",
          $adGroupAd->getAd()->getId(),
          $adGroupAd->getAd()->getDisplayUrl()
      );
    }
  }

  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::AD_GROUP_ID));
  }
}

AddHtml5Ad::main();

Add responsive ads

<?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\v201708\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201708\cm\DisplayAdFormatSetting;
use Google\AdsApi\AdWords\v201708\cm\DynamicSettings;
use Google\AdsApi\AdWords\v201708\cm\Image;
use Google\AdsApi\AdWords\v201708\cm\MediaMediaType;
use Google\AdsApi\AdWords\v201708\cm\MediaService;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\AdWords\v201708\cm\ResponsiveDisplayAd;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds an image representing the ad using the MediaService and
 * then adds a responsive display ad to an ad group. To get ad groups, run
 * GetAdGroups.php.
 */
class AddResponsiveDisplayAd {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $adGroupId) {
    $mediaService = $adWordsServices->get($session, MediaService::class);
    $adGroupAdService =
        $adWordsServices->get($session, AdGroupAdService::class);

    $operations = [];
    // Create a responsive display ad.
    $responsiveDisplayAd = new ResponsiveDisplayAd();

    // This ad format does not allow the creation of an image using the
    // Image.data field. An image must first be created using the MediaService,
    // and Image.mediaId must be populated when creating the ad.
    $adImage = self::uploadImage($mediaService, 'http://goo.gl/3b9Wfh');
    $marketingImage = new Image();
    $marketingImage->setMediaId($adImage->getMediaId());
    $responsiveDisplayAd->setMarketingImage($marketingImage);

    $responsiveDisplayAd->setShortHeadline('Travel');
    $responsiveDisplayAd->setLongHeadline('Travel the World');
    $responsiveDisplayAd->setDescription('Take to the air!');
    $responsiveDisplayAd->setBusinessName('Google');
    $responsiveDisplayAd->setFinalUrls(['http://www.example.com']);

    // Optional: Create a square marketing image using MediaService, and set it
    // to the ad.
    $squareImage = self::uploadImage($mediaService, 'https://goo.gl/mtt54n');
    $squareMarketingImage = new Image();
    $squareMarketingImage->setMediaId($squareImage->getMediaId());
    $responsiveDisplayAd->setSquareMarketingImage($squareMarketingImage);

    // Optional: Set call to action text.
    $responsiveDisplayAd->setCallToActionText('Shop Now');

    // Optional: Set dynamic display ad settings, composed of landscape logo
    // image, promotion text, and price prefix.
    $dynamicSettings = self::createDynamicDisplayAdSettings($mediaService);
    $responsiveDisplayAd->setDynamicDisplayAdSettings($dynamicSettings);

    // Whitelisted accounts only: Set color settings using hexadecimal values.
    // Set allowFlexibleColor to false if you want your ads to render by always
    // using your colors strictly.
    /*
    $responsiveDisplayAd->setMainColor('#0000ff');
    $responsiveDisplayAd->setAccentColor('#ffff00');
    $responsiveDisplayAd->setAllowFlexibleColor(false);
    */

    // Whitelisted accounts only: Set the format setting that the ad will be
    // served in.
    /*
    $responsiveDisplayAd->setFormatSetting(DisplayAdFormatSetting::NON_NATIVE);
    */

    // Create ad group ad.
    $adGroupAd = new AdGroupAd();
    $adGroupAd->setAdGroupId($adGroupId);
    $adGroupAd->setAd($responsiveDisplayAd);
    // Optional: Set additional settings.
    $adGroupAd->setStatus(AdGroupAdStatus::PAUSED);

    // Create ad group ad operation and add it to the list.
    $operation = new AdGroupAdOperation();
    $operation->setOperand($adGroupAd);
    $operation->setOperator(Operator::ADD);
    $operations[] = $operation;

    // Add a responsive display ad on the server.
    $result = $adGroupAdService->mutate($operations);

    // Create the responsive display ad on the server and print out some
    // information for each created responsive display ad.
    foreach ($result->getValue() as $adGroupAd) {
      printf(
          "Responsive display ad with ID %d and short headline '%s'"
              . " was added.\n",
          $adGroupAd->getAd()->getId(),
          $adGroupAd->getAd()->getShortHeadline()
      );
    }
  }

  private static function uploadImage(MediaService $mediaService, $url) {
    // Creates an image and upload it to the server.
    $image = new Image();
    $image->setData(file_get_contents($url));
    $image->setType(MediaMediaType::IMAGE);

    return $mediaService->upload([$image])[0];
  }

  private static function createDynamicDisplayAdSettings(
      MediaService $mediaService) {
    $logoImage = self::uploadImage($mediaService, 'https://goo.gl/dEvQeF');
    $logo = new Image();
    $logo->setMediaId($logoImage->getMediaId());

    $dynamicSettings = new DynamicSettings();
    $dynamicSettings->setLandscapeLogoImage($logo);
    $dynamicSettings->setPricePrefix('as low as');
    $dynamicSettings->setPromoText('Free shipping!');

    return $dynamicSettings;
  }

  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::AD_GROUP_ID));
  }
}

AddResponsiveDisplayAd::main();

Add a universal app campaign

<?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\v201708\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\AdvertisingChannelSubType;
use Google\AdsApi\AdWords\v201708\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201708\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201708\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201708\cm\Budget;
use Google\AdsApi\AdWords\v201708\cm\BudgetBudgetDeliveryMethod;
use Google\AdsApi\AdWords\v201708\cm\BudgetOperation;
use Google\AdsApi\AdWords\v201708\cm\BudgetService;
use Google\AdsApi\AdWords\v201708\cm\Campaign;
use Google\AdsApi\AdWords\v201708\cm\CampaignCriterion;
use Google\AdsApi\AdWords\v201708\cm\CampaignCriterionOperation;
use Google\AdsApi\AdWords\v201708\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201708\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201708\cm\CampaignService;
use Google\AdsApi\AdWords\v201708\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201708\cm\GeoTargetTypeSetting;
use Google\AdsApi\AdWords\v201708\cm\GeoTargetTypeSettingNegativeGeoTargetType;
use Google\AdsApi\AdWords\v201708\cm\Language;
use Google\AdsApi\AdWords\v201708\cm\Location;
use Google\AdsApi\AdWords\v201708\cm\Money;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\AdWords\v201708\cm\TargetCpaBiddingScheme;
use Google\AdsApi\AdWords\v201708\cm\UniversalAppBiddingStrategyGoalType;
use Google\AdsApi\AdWords\v201708\cm\UniversalAppCampaignSetting;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a Universal App campaign. To get campaigns, run
 * GetCampaigns.php. To upload image assets for this campaign, run
 * UploadImage.php.
 */
class AddUniversalAppCampaign {

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

    // Create campaign with some properties set.
    $campaign = new Campaign();
    $campaign->setName('Interplanetary Cruise #' . uniqid());
    // 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.
    $campaign->setStatus(CampaignStatus::PAUSED);

    // Set the advertising channel and subchannel types for Universal app
    // campaigns.
    $campaign->setAdvertisingChannelType(AdvertisingChannelType::MULTI_CHANNEL);
    $campaign->setAdvertisingChannelSubType(
        AdvertisingChannelSubType::UNIVERSAL_APP_CAMPAIGN);

    // Set the campaign's bidding strategy. Universal App campaigns
    // only support TARGET_CPA bidding strategy.
    $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
    $biddingStrategyConfiguration->setBiddingStrategyType(
        BiddingStrategyType::TARGET_CPA);

    // Set the target CPA to $1 / app install.
    $biddingScheme = new TargetCpaBiddingScheme();
    $money = new Money();
    $money->setMicroAmount(1000000);
    $biddingScheme->setTargetCpa($money);

    $biddingStrategyConfiguration->setBiddingScheme($biddingScheme);
    $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

    // Set shared budget (required).
    $campaign->setBudget(new Budget());
    $campaign->getBudget()->setBudgetId(
        self::createBudget($adWordsServices, $session));

    // Optional: Set the start date.
    $campaign->setStartDate(date('Ymd', strtotime('+1 day')));

    // Optional: Set the end date.
    $campaign->setEndDate(date('Ymd', strtotime('+1 year')));

    // Set the campaign's assets and ad text ideas. These values will be used to
    // generate ads.
    $universalAppSetting = new UniversalAppCampaignSetting();
    $universalAppSetting->setAppId('com.labpixies.colordrips');
    $universalAppSetting->setDescription1('A cool puzzle game');
    $universalAppSetting->setDescription2('Remove connected blocks');
    $universalAppSetting->setDescription3('3 difficulty levels');
    $universalAppSetting->setDescription4('4 colorful fun skins');

    // Optional: You can set up to 10 image assets for your campaign.
    // See UploadImage.php for an example on how to upload images.
    //
    // $universalAppSetting->imageMediaIds = [INSERT_IMAGE_MEDIA_ID_HERE];

    // Optimize this campaign for getting new users for your app.
    $universalAppSetting->setUniversalAppBiddingStrategyGoalType(
        UniversalAppBiddingStrategyGoalType
            ::OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME);

    // If you select bidding strategy goal type as
    // OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME, then you may specify a set of
    // conversion types for in-app actions to optimize the campaign towards.
    // Conversion type IDs can be retrieved using ConversionTrackerService.get.
    //
    // $campaign->selectiveOptimization = new SelectiveOptimization();
    // $campaign->selectiveOptimization->conversionTypeIds = [
    //     INSERT_CONVERSION_TYPE_ID_1_HERE,
    //     INSERT_CONVERSION_TYPE_ID_2_HERE
    // ];

    // Optional: Set the campaign settings for Advanced location options.
    $geoTargetTypeSetting = new GeoTargetTypeSetting();
    $geoTargetTypeSetting->setNegativeGeoTargetType(
        GeoTargetTypeSettingNegativeGeoTargetType::LOCATION_OF_PRESENCE);
    $campaign->setSettings([$universalAppSetting, $geoTargetTypeSetting]);

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

    // Create the campaign on the server and print out some information for the
    // campaign.
    $result = $campaignService->mutate($operations);
    foreach ($result->getValue() as $campaign) {
      printf("Universal App Campaign with name '%s' and ID %d was added.\n",
          $campaign->getName(), $campaign->getId());
      // Optional: Set the campaign's location and language targeting. No other
      // targeting criteria can be used for Universal App campaigns.
      self::setCampaignTargetingCriteria(
          $campaign->getId(), $adWordsServices, $session);
    }
  }

  /**
   * Creates the budget for the campaign.
   */
  private static function createBudget(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $budgetService = $adWordsServices->get($session, BudgetService::class);

    // Create the shared budget (required).
    $budget = new Budget();
    $budget->setName('Interplanetary Cruise Budget #' . uniqid());
    $money = new Money();
    $money->setMicroAmount(50000000);
    $budget->setAmount($money);
    $budget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD);

    // Universal App campaigns don't support shared budgets.
    $budget->setIsExplicitlyShared(false);
    $operations = [];

    // Create a budget operation.
    $operation = new BudgetOperation();
    $operation->setOperand($budget);
    $operation->setOperator(Operator::ADD);
    $operations[] = $operation;

    // Create the budget on the server.
    $result = $budgetService->mutate($operations);
    $budget = $result->getValue()[0];

    printf("Budget with name '%s' and ID %d was created.\n",
        $budget->getName(), $budget->getBudgetId());

    return $budget->getBudgetId();
  }

  /**
   * Sets the campaign's targeting criteria.
   */
  private static function setCampaignTargetingCriteria(
      $campaignId, AdWordsServices $adWordsServices, AdWordsSession $session) {
    $campaignCriterionService =
        $adWordsServices->get($session, CampaignCriterionService::class);

    $campaignCriteria = [];
    // Create locations. The IDs can be found in the documentation or retrieved
    // with the LocationCriterionService.
    $california = new Location();
    $california->setId(21137);
    $campaignCriteria[] = new CampaignCriterion($campaignId, null, $california);

    $mexico = new Location();
    $mexico->setId(2484);
    $campaignCriteria[] = new CampaignCriterion($campaignId, null, $mexico);

    // Create languages. The IDs can be found in the documentation or retrieved
    // with the ConstantDataService.
    $english = new Language();
    $english->setId(1000);
    $campaignCriteria[] = new CampaignCriterion($campaignId, null, $english);

    $spanish = new Language();
    $spanish->setId(1003);
    $campaignCriteria[] = new CampaignCriterion($campaignId, null, $spanish);

    // Create operations to add each of the criteria above.
    $operations = [];
    foreach ($campaignCriteria as $campaignCriterion) {
      $operation = new CampaignCriterionOperation();
      $operation->setOperand($campaignCriterion);
      $operation->setOperator(Operator::ADD);
      $operations[] = $operation;
    }

    // Set the campaign targets.
    $result = $campaignCriterionService->mutate($operations);

    // Display added campaign targets.
    foreach ($result->getValue() as $campaignCriterion) {
      printf("Campaign criterion of type '%s' and ID %d was added.\n",
          $campaignCriterion->getCriterion()->getType(),
          $campaignCriterion->getCriterion()->getId()
      );
    }
  }

  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);
  }
}

AddUniversalAppCampaign::main();

Get ad group bid modifiers

<?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\v201708\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\AdGroupBidModifierService;
use Google\AdsApi\AdWords\v201708\cm\OrderBy;
use Google\AdsApi\AdWords\v201708\cm\Paging;
use Google\AdsApi\AdWords\v201708\cm\Selector;
use Google\AdsApi\AdWords\v201708\cm\SortOrder;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example illustrates how to retrieve ad group level bid modifiers for
 * all campaigns.
 */
class GetAdGroupBidModifiers {

  const PAGE_LIMIT = 500;

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

    // Create a selector to select all ad group bid modifiers.
    $selector = new Selector();
    $selector->setFields(
        ['Id', 'AdGroupId', 'CampaignId', 'BidModifier']);
    $selector->setOrdering([new OrderBy('CampaignId', SortOrder::ASCENDING)]);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

    $totalNumEntries = 0;
    do {
      // Retrieve ad group bid modifiers one page at a time, continuing to
      // request pages until all ad group bid modifiers have been retrieved.
      $page = $adGroupBidModifierService->get($selector);

      // Print out some information for each ad group bid modifier.
      if ($page->getEntries() !== null) {
        $totalNumEntries = $page->getTotalNumEntries();
        foreach ($page->getEntries() as $adGroupBidModifier) {
          printf(
              "Campaign ID %d, ad group ID %d, criterion ID %d has ad group "
                  . "level modifier: %s\n",
              $adGroupBidModifier->getCampaignId(),
              $adGroupBidModifier->getAdGroupId(),
              $adGroupBidModifier->getCriterion()->getId(),
              ($adGroupBidModifier->getBidModifier() === null)
                  ? 'none' : $adGroupBidModifier->getBidModifier()
          );
        }
      }

      $selector->getPaging()->setStartIndex(
          $selector->getPaging()->getStartIndex() + self::PAGE_LIMIT);
    } while ($selector->getPaging()->getStartIndex() < $totalNumEntries);

    printf("Number of results found: %d\n", $totalNumEntries);
  }

  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);
  }
}

GetAdGroupBidModifiers::main();

Use a portfolio bidding strategy

<?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\v201708\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201708\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201708\cm\BiddingStrategyOperation;
use Google\AdsApi\AdWords\v201708\cm\BiddingStrategyService;
use Google\AdsApi\AdWords\v201708\cm\Budget;
use Google\AdsApi\AdWords\v201708\cm\BudgetBudgetDeliveryMethod;
use Google\AdsApi\AdWords\v201708\cm\BudgetOperation;
use Google\AdsApi\AdWords\v201708\cm\BudgetService;
use Google\AdsApi\AdWords\v201708\cm\Campaign;
use Google\AdsApi\AdWords\v201708\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201708\cm\CampaignService;
use Google\AdsApi\AdWords\v201708\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201708\cm\Money;
use Google\AdsApi\AdWords\v201708\cm\NetworkSetting;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\AdWords\v201708\cm\SharedBiddingStrategy;
use Google\AdsApi\AdWords\v201708\cm\TargetSpendBiddingScheme;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a portfolio bidding strategy and uses it to
 * construct a campaign.
 */
class UsePortfolioBiddingStrategy {

  // Enter the budget ID to be used or leave as null to create a new one.
  const BUDGET_ID = null;

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $sharedBudgetId = null) {
    $biddingStrategy = self::createBiddingStrategy($adWordsServices, $session);

    if ($sharedBudgetId === null) {
      $budget = self::createSharedBudget($adWordsServices, $session);
      $sharedBudgetId = $budget->getBudgetId();
    }
    self::createCampaignWithBiddingStrategy(
        $adWordsServices,
        $session,
        $biddingStrategy->getId(),
        $sharedBudgetId
    );
  }

  /**
   * Creates a shared bidding strategy.
   */
  private static function createBiddingStrategy(
      AdWordsServices $adWordsServices,
      AdWordsSession $session
  ) {
    $biddingStrategyService =
        $adWordsServices->get($session, BiddingStrategyService::class);

    // Create a portfolio bidding strategy.
    $biddingStrategy = new SharedBiddingStrategy();
    $biddingStrategy->setName("Maximize Clicks " . uniqid());

    $biddingScheme = new TargetSpendBiddingScheme();
    // Optionally set additional bidding scheme parameters.
    $bidCeiling = new Money();
    $bidCeiling->setMicroAmount(2000000);
    $biddingScheme->setBidCeiling($bidCeiling);
    $spendTarget = new Money();
    $spendTarget->setMicroAmount(20000000);
    $biddingScheme->setSpendTarget($spendTarget);

    $biddingStrategy->setBiddingScheme($biddingScheme);

    // Create the bidding strategy operation.
    $operation = new BiddingStrategyOperation();
    $operation->setOperator(Operator::ADD);
    $operation->setOperand($biddingStrategy);

    $result = $biddingStrategyService->mutate([$operation]);
    $newBiddingStrategy = $result->getValue()[0];
    printf(
        "Portfolio bidding strategy with name '%s' and ID %d of type %s was "
            . "created.\n",
        $newBiddingStrategy->getName(),
        $newBiddingStrategy->getId(),
        $newBiddingStrategy->getType()
    );

    return $newBiddingStrategy;
  }

  /**
   * Creates an explicit budget to be used to create a campaign.
   */
  private static function createSharedBudget(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $budgetService = $adWordsServices->get($session, BudgetService::class);

    // Create the shared budget.
    $budget = new Budget();
    $budget->setName('Shared Interplanetary Budget #' . uniqid());
    $money = new Money();
    $money->setMicroAmount(50000000);
    $budget->setAmount($money);
    $budget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD);
    $budget->setIsExplicitlyShared(true);

    $operations = [];

    // Create a budget operation.
    $operation = new BudgetOperation();
    $operation->setOperand($budget);
    $operation->setOperator(Operator::ADD);
    $operations[] = $operation;

    // Create the budget on the server.
    $result = $budgetService->mutate($operations);

    return $result->getValue()[0];
  }

  /**
   * Create a campaign with a portfolio bidding strategy.
   */
  private static function createCampaignWithBiddingStrategy(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      $biddingStrategyId,
      $sharedBudgetId
  ) {
    $campaignService = $adWordsServices->get($session, CampaignService::class);

    // Create campaign with some properties set.
    $campaign = new Campaign();
    $campaign->setName('Interplanetary Cruise #' . uniqid());

    // Set the budget.
    $campaign->setBudget(new Budget());
    $campaign->getBudget()->setBudgetId($sharedBudgetId);
    $campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH);

    // Set the campaign's bidding strategy.
    $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
    $biddingStrategyConfiguration->setBiddingStrategyId($biddingStrategyId);

    $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

    // Set network targeting (recommended).
    $networkSetting = new NetworkSetting();
    $networkSetting->setTargetGoogleSearch(true);
    $networkSetting->setTargetSearchNetwork(true);
    $networkSetting->setTargetContentNetwork(true);
    $campaign->setNetworkSetting($networkSetting);

    // 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.
    $campaign->setStatus(CampaignStatus::PAUSED);

    // Create a campaign operation.
    $operation = new CampaignOperation();
    $operation->setOperand($campaign);
    $operation->setOperator(Operator::ADD);

    // Create the campaign on the server and print out some information for the
    // campaign.
    $result = $campaignService->mutate([$operation]);
    $newCampaign = $result->getValue()[0];
    printf(
        "Campaign with name '%s', ID %d and bidding scheme ID %d was "
            . "created.\n",
        $newCampaign->getName(),
        $newCampaign->getId(),
        $newCampaign->getBiddingStrategyConfiguration()->getBiddingStrategyId()
    );
  }

  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,
        self::BUDGET_ID === null ? null : intval(self::BUDGET_ID));
  }
}

UsePortfolioBiddingStrategy::main();

Send feedback about...

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