Advanced Operations Samples

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

Add an ad customizer

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdCustomizerFeed;
use Google\AdsApi\AdWords\v201705\cm\AdCustomizerFeedAttribute;
use Google\AdsApi\AdWords\v201705\cm\AdCustomizerFeedAttributeType;
use Google\AdsApi\AdWords\v201705\cm\AdCustomizerFeedOperation;
use Google\AdsApi\AdWords\v201705\cm\AdCustomizerFeedService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201705\cm\ExpandedTextAd;
use Google\AdsApi\AdWords\v201705\cm\FeedItem;
use Google\AdsApi\AdWords\v201705\cm\FeedItemAdGroupTargeting;
use Google\AdsApi\AdWords\v201705\cm\FeedItemAttributeValue;
use Google\AdsApi\AdWords\v201705\cm\FeedItemOperation;
use Google\AdsApi\AdWords\v201705\cm\FeedItemService;
use Google\AdsApi\AdWords\v201705\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();

Old

<?php
/**
 * 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.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

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

// Enter parameters required by the code example.
$adGroupIds = array('INSERT_AD_GROUP_ID_HERE', 'INSERT_AD_GROUP_ID_HERE');
$feedName = 'INSERT_FEED_NAME_HERE';

/**
 * Runs the example.
 *
 * @param AdWordsUser $user the user to run the example with
 * @param array $adGroupIds the IDs of the ad groups to target with the FeedItem
 * @param string $feedName the name of the new AdCustomizerFeed
 */
function AddAdCustomizerExample(AdWordsUser $user, $adGroupIds, $feedName) {
  // Create a customizer feed. One feed per account can be used for all ads.
  $adCustomizerFeed = CreateCustomizerFeed($user, $feedName);

  // Add feed items containing the values we'd like to place in ads.
  CreateCustomizerFeedItems($user, $adGroupIds, $adCustomizerFeed);

  // All set! We can now create ads with customizations.
  CreateAdsWithCustomizations($user, $adGroupIds, $feedName);
}

/**
 * Creates a new Feed for AdCustomizerFeed.
 *
 * @param AdWordsUser $user the user to run the example with
 * @param string $feedName the name of the new AdCustomizerFeed
 */
function CreateCustomizerFeed(AdWordsUser $user, $feedName) {
  // Map that holds IDs associated to the feeds metadata.
  $dataHolder = array();

  // Get the AdCustomizerFeedService, which loads the required classes.
  $adCustomizerFeedService = $user->GetService('AdCustomizerFeedService',
      ADWORDS_VERSION);

  $nameAttribute = new AdCustomizerFeedAttribute();
  $nameAttribute->name = 'Name';
  $nameAttribute->type = 'STRING';

  $priceAttribute = new AdCustomizerFeedAttribute();
  $priceAttribute->name = 'Price';
  $priceAttribute->type = 'STRING';

  $dateAttribute = new AdCustomizerFeedAttribute();
  $dateAttribute->name = 'Date';
  $dateAttribute->type = 'DATE_TIME';

  $customizerFeed = new AdCustomizerFeed();
  $customizerFeed->feedName = $feedName;
  $customizerFeed->feedAttributes = array($nameAttribute, $priceAttribute,
      $dateAttribute);

  $feedOperation = new AdCustomizerFeedOperation();
  $feedOperation->operand = $customizerFeed;
  $feedOperation->operator = 'ADD';

  $operations = array($feedOperation);

  // Add the feed.
  $result = $adCustomizerFeedService->mutate($operations);
  $addedFeed = $result->value[0];

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

  return $addedFeed;
}

/**
 * Creates FeedItems with the values to use in ad customizations for each ad
 * group in adGroupIds
 *
 * @param AdWordsUser $user the user to run the example with
 * @param array $adGroupIds the IDs of the ad groups to target with the FeedItem
 * @param AdCustomizerFeed $adCustomizerFeed the customizer feed
 */
function CreateCustomizerFeedItems(AdWordsUser $user, $adGroupIds,
    $adCustomizerFeed) {
  // Get the FeedItemService, which loads the required classes.
  $feedItemService = $user->GetService('FeedItemService', ADWORDS_VERSION);

  $operations = array();

  $marsDate = mktime(0, 0, 0, date('m'), 1, date('Y'));
  $venusDate = mktime(0, 0, 0, date('m'), 15, date('Y'));
  // Create operations to add FeedItems.
  $operations[] = CreateFeedItemAddOperation('Mars', '$1234.56',
      date('Ymd His', $marsDate), $adGroupIds[0], $adCustomizerFeed);
  $operations[] = CreateFeedItemAddOperation('Venus', '$1450.00',
      date('Ymd His', $venusDate), $adGroupIds[1], $adCustomizerFeed);

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

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

  return $adCustomizerFeed;
}

/**
 * Creates a FeedItemOperation that will create a FeedItem with the specified
 * values and ad group target when sent to FeedItemService.mutate.
 *
 * @param string $name the value for the name attribute of the FeedItem
 * @param string $price the value for the price attribute of the FeedItem
 * @param string $date the value for the date attribute of the FeedItem
 * @param string $adGroupId the ID of the ad group to target with the FeedItem
 * @param AdCustomizerFeed $adCustomizerFeed the customizer feed
 */
function CreateFeedItemAddOperation($name, $price, $date, $adGroupId,
    $adCustomizerFeed) {
  // Create the FeedItemAttributeValues for our text values.
  $nameAttributeValue = new FeedItemAttributeValue();
  $nameAttributeValue->feedAttributeId =
      $adCustomizerFeed->feedAttributes[0]->id;
  $nameAttributeValue->stringValue = $name;
  $priceAttributeValue = new FeedItemAttributeValue();
  $priceAttributeValue->feedAttributeId =
      $adCustomizerFeed->feedAttributes[1]->id;
  $priceAttributeValue->stringValue = $price;
  $dateAttributeValue = new FeedItemAttributeValue();
  $dateAttributeValue->feedAttributeId =
      $adCustomizerFeed->feedAttributes[2]->id;
  $dateAttributeValue->stringValue = $date;

  // Create the feed item and operation.
  $item = new FeedItem();
  $item->feedId = $adCustomizerFeed->feedId;
  $item->attributeValues =
      array($nameAttributeValue, $priceAttributeValue, $dateAttributeValue);

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

  $operation = new FeedItemOperation();
  $operation->operand = $item;
  $operation->operator = 'ADD';
  return $operation;
}

/**
 * Creates text ads that use ad customizations for the specified ad group IDs.
 *
 * @param AdWordsUser $user the user to run the example with
 * @param array $adGroupIds the IDs of the ad groups to target with the FeedItem
 * @param string $feedName the name of the new AdCustomizerFeed
 */
function CreateAdsWithCustomizations(AdWordsUser $user, $adGroupIds,
    $feedName) {
  // Get the service, which loads the required classes.
  $adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);

  $expandedTextAd = new ExpandedTextAd();
  $expandedTextAd->headlinePart1 =
      sprintf('Luxury Cruise to {=%s.Name}', $feedName);
  $expandedTextAd->headlinePart2 = sprintf('Only {=%s.Price}', $feedName);
  $expandedTextAd->description = sprintf('Offer ends in {=countdown(%s.Date)}!',
      $feedName);
  $expandedTextAd->finalUrls = array('http://www.example.com');

  // We add the same ad to both ad groups. When they serve, they will show
  // different values, since they match different feed items.
  $operations = array();

  foreach ($adGroupIds as $adGroupId) {
    // Create ad group ad.
    $adGroupAd = new AdGroupAd();
    $adGroupAd->adGroupId = $adGroupId;
    $adGroupAd->ad = $expandedTextAd;

    // Create operation.
    $operation = new AdGroupAdOperation();
    $operation->operand = $adGroupAd;
    $operation->operator = 'ADD';
    $operations[] = $operation;
  }

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

  // Display results.
  foreach ($result->value as $adGroupAd) {
    printf("Text ad with ID %d and status '%s' was added.\n",
        $adGroupAd->ad->id, $adGroupAd->status);
  }
}

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

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

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

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

Add an ad group bid modifier

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdGroupBidModifier;
use Google\AdsApi\AdWords\v201705\cm\AdGroupBidModifierOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupBidModifierService;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\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();

Old

<?php
/**
 * This code example illustrates how to add ad group level mobile bid modifier
 * override for a campaign.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

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

// Enter parameters required by the code example.
$adGroupId = 'INSERT_ADGROUP_ID_HERE';
$bidModifier = 1.5;

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the ID of the ad group to add the bid modifier to
 * @param int $bidModifier the bid modifier multiplier
 */
function AddAdGroupBidModifierExample(AdWordsUser $user, $adGroupId,
    $bidModifier) {
  // Get the AdGroupBidModifierService, which loads the r©equired classes.
  $bidModifierService = $user->GetService('AdGroupBidModifierService',
      ADWORDS_VERSION);

  // Mobile criterion ID.
  $criterionId = 30001;

  // Prepare to add an ad group level override.
  $agBidModifier = new AdGroupBidModifier();
  $agBidModifier->adGroupId = $adGroupId;
  $agBidModifier->criterion = new Platform();
  $agBidModifier->criterion->id = $criterionId;
  $agBidModifier->bidModifier = $bidModifier;

  $operation = new AdGroupBidModifierOperation();

  // Use 'ADD' to add a new modifier and 'SET' to update an existing one. A
  // modifier can be removed with the 'REMOVE' operator.
  $operation->operator = 'ADD';
  $operation->operand = $agBidModifier;

  $response = $bidModifierService->mutate(array($operation));

  foreach ($response->value as $modifier) {
    $value = 'none';
    if (is_numeric($modifier->bidModifier)) {
      $value = $modifier->bidModifier;
    }
    printf(
      'AdGroup ID %d, Criterion ID %d was updated with ' .
          "ad group level modifier: %s\n",
      $modifier->adGroupId,
      $modifier->criterion->id,
      $value
    );
  }
}

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

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

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

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

Add a click-to-download ad

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201705\cm\Image;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\TemplateAd;
use Google\AdsApi\AdWords\v201705\cm\TemplateElement;
use Google\AdsApi\AdWords\v201705\cm\TemplateElementField;
use Google\AdsApi\AdWords\v201705\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();

Old

<?php
/**
 * 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.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

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

// Enter parameters required by the code example.
$adGroupId = 'INSERT_ADGROUP_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the ID of the ad group to add the ad to
 */
function AddClickToDownloadAd(AdWordsUser $user, $adGroupId) {
  // Get the AdGroupAdService, which loads the required classes.
  $adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);

  // 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 = MediaUtils::GetBase64Data('http://goo.gl/9JmyKk');

  // Create the template ad.
  $clickToDownloadAppAd = new TemplateAd();

  $clickToDownloadAppAd->name = 'Ad for demo game';
  $clickToDownloadAppAd->templateId = 353;
  $clickToDownloadAppAd->finalUrls = array(
      'http://play.google.com/store/apps/details?id=com.example.demogame');
  $clickToDownloadAppAd->displayUrl = '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->name = 'headline';
  $headline->fieldText = 'Enjoy your drive in Mars';
  $headline->type = 'TEXT';

  $description1 = new TemplateElementField();
  $description1->name = 'description1';
  $description1->fieldText = 'Realistic physics simulation';
  $description1->type = 'TEXT';

  $description2 = new TemplateElementField();
  $description2->name = 'description2';
  $description2->fieldText = 'Race against players online';
  $description2->type = 'TEXT';

  $appId = new TemplateElementField();
  $appId->name = 'appId';
  $appId->fieldText = 'com.example.demogame';
  $appId->type = 'TEXT';

  $appStore = new TemplateElementField();
  $appStore->name = 'appStore';
  $appStore->fieldText = '2';
  $appStore->type = 'ENUM';

  $landscapeImage = new TemplateElementField();
  $landscapeImage->name = 'landscapeImage';
  $landscapeImage->fieldMedia = new Image($imageData);
  $landscapeImage->type = 'IMAGE';

  $adData = new TemplateElement();
  $adData->uniqueName = 'adData';
  $adData->fields = array($headline, $description1, $description2, $appId,
      $appStore, $landscapeImage);

  $clickToDownloadAppAd->templateElements = array($adData);

  // Create the adgroupad.
  $clickToDownloadAppAdGroupAd = new AdGroupAd();
  $clickToDownloadAppAdGroupAd->adGroupId = $adGroupId;
  $clickToDownloadAppAdGroupAd->ad = $clickToDownloadAppAd;

  // Optional: Set the status.
  $clickToDownloadAppAdGroupAd->status = 'PAUSED';

  // Create the operation.
  $operation = new AdGroupAdOperation();
  $operation->operator = 'ADD';
  $operation->operand = $clickToDownloadAppAdGroupAd;

  $operations = array($operation);

  // Create the ads.
  $result = $adGroupAdService->mutate($operations);

  foreach ($result->value as $adGroupAd) {
    printf('New click-to-download ad with ID = %d and URL = "%s" ' .
        "was created.\n", $adGroupAd->ad->id, $adGroupAd->ad->finalUrls[0]);
  }
}

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

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

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

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

Add a page feed specifying URLs for a DSA campaign

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201705\cm\AttributeFieldMapping;
use Google\AdsApi\AdWords\v201705\cm\BiddableAdGroupCriterion;
use Google\AdsApi\AdWords\v201705\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201705\cm\Campaign;
use Google\AdsApi\AdWords\v201705\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignService;
use Google\AdsApi\AdWords\v201705\cm\CpcBid;
use Google\AdsApi\AdWords\v201705\cm\DynamicSearchAdsSetting;
use Google\AdsApi\AdWords\v201705\cm\Feed;
use Google\AdsApi\AdWords\v201705\cm\FeedAttribute;
use Google\AdsApi\AdWords\v201705\cm\FeedAttributeType;
use Google\AdsApi\AdWords\v201705\cm\FeedItem;
use Google\AdsApi\AdWords\v201705\cm\FeedItemAttributeValue;
use Google\AdsApi\AdWords\v201705\cm\FeedItemOperation;
use Google\AdsApi\AdWords\v201705\cm\FeedItemService;
use Google\AdsApi\AdWords\v201705\cm\FeedMapping;
use Google\AdsApi\AdWords\v201705\cm\FeedMappingOperation;
use Google\AdsApi\AdWords\v201705\cm\FeedMappingService;
use Google\AdsApi\AdWords\v201705\cm\FeedOperation;
use Google\AdsApi\AdWords\v201705\cm\FeedOrigin;
use Google\AdsApi\AdWords\v201705\cm\FeedService;
use Google\AdsApi\AdWords\v201705\cm\Money;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\PageFeed;
use Google\AdsApi\AdWords\v201705\cm\Predicate;
use Google\AdsApi\AdWords\v201705\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\AdWords\v201705\cm\Webpage;
use Google\AdsApi\AdWords\v201705\cm\WebpageCondition;
use Google\AdsApi\AdWords\v201705\cm\WebpageConditionOperand;
use Google\AdsApi\AdWords\v201705\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();

Old

Add a DSA campaign

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdGroup;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupStatus;
use Google\AdsApi\AdWords\v201705\cm\AdGroupType;
use Google\AdsApi\AdWords\v201705\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201705\cm\BiddableAdGroupCriterion;
use Google\AdsApi\AdWords\v201705\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201705\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201705\cm\Budget;
use Google\AdsApi\AdWords\v201705\cm\BudgetBudgetDeliveryMethod;
use Google\AdsApi\AdWords\v201705\cm\BudgetOperation;
use Google\AdsApi\AdWords\v201705\cm\BudgetService;
use Google\AdsApi\AdWords\v201705\cm\Campaign;
use Google\AdsApi\AdWords\v201705\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignService;
use Google\AdsApi\AdWords\v201705\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201705\cm\CpcBid;
use Google\AdsApi\AdWords\v201705\cm\DynamicSearchAdsSetting;
use Google\AdsApi\AdWords\v201705\cm\ExpandedDynamicSearchAd;
use Google\AdsApi\AdWords\v201705\cm\Money;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\UserStatus;
use Google\AdsApi\AdWords\v201705\cm\Webpage;
use Google\AdsApi\AdWords\v201705\cm\WebpageCondition;
use Google\AdsApi\AdWords\v201705\cm\WebpageConditionOperand;
use Google\AdsApi\AdWords\v201705\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();

Old

Add an expanded text ad with Upgraded URLs

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201705\cm\CustomParameter;
use Google\AdsApi\AdWords\v201705\cm\CustomParameters;
use Google\AdsApi\AdWords\v201705\cm\ExpandedTextAd;
use Google\AdsApi\AdWords\v201705\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();

Old

<?php
/**
 * This example adds an expanded text ad to an ad group that uses upgraded URLs.
 *
 * To get ad groups, run GetAdGroups.php.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

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

require_once UTIL_PATH . '/MediaUtils.php';

// Enter parameters required by the code example.
$adGroupId = 'INSERT_AD_GROUP_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the id of the ad group to add the ads to
 */
function AddExpandedTextAdWithUpgradedUrlsExample(AdWordsUser $user,
    $adGroupId) {
  // Get the service, which loads the required classes.
  $adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);

  $operations = array();

  // Create expanded text ad with a tracking template and custom parameters.
  $expandedTextAd = new ExpandedTextAd();
  $expandedTextAd->headlinePart1 = 'Luxury Cruise to Mars';
  $expandedTextAd->headlinePart2 = 'Visit the Red Planet in style.';
  $expandedTextAd->description = '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->trackingUrlTemplate =
      '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->key = 'season';
  $seasonParameter->value = 'christmas';

  $promoCodeParameter = new CustomParameter();
  $promoCodeParameter->key = 'promocode';
  $promoCodeParameter->value = 'NYC123';

  $expandedTextAd->urlCustomParameters = new CustomParameters();
  $expandedTextAd->urlCustomParameters->parameters = array($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->finalUrls = array('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->finalMobileUrls = array(
      'http://mobile.example.com/cruise/space/',
      'http://mobile.example.com/locations/mars/'
  );

  // Create ad group ad.
  $adGroupAd = new AdGroupAd();
  $adGroupAd->adGroupId = $adGroupId;
  $adGroupAd->ad = $expandedTextAd;

  // Set additional settings (optional).
  $adGroupAd->status = 'PAUSED';

  // Create operation.
  $operation = new AdGroupAdOperation();
  $operation->operand = $adGroupAd;
  $operation->operator = 'ADD';
  $operations[] = $operation;

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

  // Display results.
  foreach ($result->value as $adGroupAd) {
    $ad = $adGroupAd->ad;
    printf("Ad with ID %d was added.\n", $ad->id);
    print("Upgraded URL properties:\n");
    printf("  Final URLs: %s\n", implode(', ', $ad->finalUrls));
    printf("  Final Mobile URLs: %s\n", implode(', ', $ad->finalMobileUrls));
    printf("  Tracking URL template: %s\n", $ad->trackingUrlTemplate);
    printf("  Custom parameters: %s\n",
        implode(', ',
            array_map(function($param) {
              return sprintf('%s=%s', $param->key, $param->value);
            },
            $ad->urlCustomParameters->parameters)));
  }
}

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

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

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

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

Add an HTML 5 ad to an ad group

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201705\cm\Dimensions;
use Google\AdsApi\AdWords\v201705\cm\MediaBundle;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\TemplateAd;
use Google\AdsApi\AdWords\v201705\cm\TemplateElement;
use Google\AdsApi\AdWords\v201705\cm\TemplateElementField;
use Google\AdsApi\AdWords\v201705\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();

Old

<?php
/**
 * This example adds an HTML5 ad to given ad group. To get ad groups, run
 * GetAdGroups.php.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

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

// Enter parameters required by the code example.
$adGroupId = 'INSERT_AD_GROUP_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the ID of the ad group to add the ad to
 */
function AddHtml5Ad(AdWordsUser $user, $adGroupId) {
  // Get the AdGroupAdService, which loads the required classes.
  $adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);

  // Create the template ad.
  $html5Ad = new TemplateAd();

  $html5Ad->name = 'Ad for HTML5';
  $html5Ad->templateId = 419;
  $html5Ad->finalUrls = array('http://example.com/html5');
  $html5Ad->displayUrl = 'example.com/html5';

  $dimensions = new Dimensions();
  $dimensions->width = 300;
  $dimensions->height = 250;
  $html5Ad->dimensions = $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 = MediaUtils::GetBase64Data('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->data = $html5Zip;
  $mediaBundle->entryPoint = 'carousel/index.html';
  $mediaBundle->type = '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->name = 'Custom_layout';
  $media->fieldMedia = $mediaBundle;
  $media->type = 'MEDIA_BUNDLE';

  $layout = new TemplateElementField();
  $layout->name = 'layout';
  $layout->fieldText = 'Custom';
  $layout->type = 'ENUM';

  $adData = new TemplateElement();
  $adData->uniqueName = 'adData';
  $adData->fields = array($media, $layout);

  $html5Ad->templateElements = array($adData);

  // Create the ad group ad.
  $html5AdGroupAd = new AdGroupAd();
  $html5AdGroupAd->adGroupId = $adGroupId;
  $html5AdGroupAd->ad = $html5Ad;

  // Optional: Set the status.
  $html5AdGroupAd->status = 'PAUSED';

  // Create the operation.
  $operation = new AdGroupAdOperation();
  $operation->operator = 'ADD';
  $operation->operand = $html5AdGroupAd;

  $operations = array($operation);

  // Create the ads.
  $result = $adGroupAdService->mutate($operations);

  foreach ($result->value as $adGroupAd) {
    printf("New HTML5 ad with ID %d and display URL '%s' was created.\n",
        $adGroupAd->ad->id, $adGroupAd->ad->displayUrl);
  }
}

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

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

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

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

Add responsive ads

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201705\cm\Image;
use Google\AdsApi\AdWords\v201705\cm\MediaMediaType;
use Google\AdsApi\AdWords\v201705\cm\MediaService;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\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);

    // Create an image and add it to the images list.
    $image = new Image();
    $image->setData(file_get_contents('http://goo.gl/3b9Wfh'));
    $image->setType(MediaMediaType::IMAGE);
    $images = [$image];

    // Upload the image to the server.
    $image = $mediaService->upload($images)[0];

    $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.
    $marketingImage = new Image();
    $marketingImage->setMediaId($image->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']);

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

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

Old

<?php
/**
 * 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.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

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

require_once UTIL_PATH . '/MediaUtils.php';

// Enter parameters required by the code example.
$adGroupId = 'INSERT_AD_GROUP_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the ID of the ad group to add the ads to
 */
function AddResponsiveDisplayAd(AdWordsUser $user, $adGroupId) {
  // Get the service, which loads the required classes.
  $mediaService = $user->GetService('MediaService', ADWORDS_VERSION);

  // Creates image.
  $image = new Image();
  $image->data = MediaUtils::GetBase64Data('https://goo.gl/3b9Wfh');
  $image->type = 'IMAGE';

  // Make the upload request.
  $result = $mediaService->upload(array($image));
  $image = $result[0];

  // Get the service, which loads the required classes.
  $adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);

  // 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.
  $marketingImage = new Image();
  $marketingImage->mediaId = $image->mediaId;

  $responsiveDisplayAd->marketingImage = $marketingImage;
  $responsiveDisplayAd->shortHeadline = 'Travel';
  $responsiveDisplayAd->longHeadline = 'Travel the World';
  $responsiveDisplayAd->description = 'Take to the air!';
  $responsiveDisplayAd->businessName = 'Google';
  $responsiveDisplayAd->finalUrls = array('http://www.example.com');

  // Create ad group ad.
  $adGroupAd = new AdGroupAd();
  $adGroupAd->adGroupId = $adGroupId;
  $adGroupAd->ad = $responsiveDisplayAd;

  // Set additional settings (optional).
  $adGroupAd->status = 'PAUSED';

  // Create operation.
  $operation = new AdGroupAdOperation();
  $operation->operand = $adGroupAd;
  $operation->operator = 'ADD';
  $operations[] = $operation;

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

  // Display results.
  foreach ($result->value as $adGroupAd) {
    printf("Responsive display ad with ID '%d' and short headline '%s'"
        . " was added.\n", $adGroupAd->ad->id, $adGroupAd->ad->shortHeadline);
  }
}

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

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

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

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

Add a universal app campaign

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdvertisingChannelSubType;
use Google\AdsApi\AdWords\v201705\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201705\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201705\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201705\cm\Budget;
use Google\AdsApi\AdWords\v201705\cm\BudgetBudgetDeliveryMethod;
use Google\AdsApi\AdWords\v201705\cm\BudgetOperation;
use Google\AdsApi\AdWords\v201705\cm\BudgetService;
use Google\AdsApi\AdWords\v201705\cm\Campaign;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterion;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201705\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignService;
use Google\AdsApi\AdWords\v201705\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201705\cm\GeoTargetTypeSetting;
use Google\AdsApi\AdWords\v201705\cm\GeoTargetTypeSettingNegativeGeoTargetType;
use Google\AdsApi\AdWords\v201705\cm\Language;
use Google\AdsApi\AdWords\v201705\cm\Location;
use Google\AdsApi\AdWords\v201705\cm\Money;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\TargetCpaBiddingScheme;
use Google\AdsApi\AdWords\v201705\cm\UniversalAppBiddingStrategyGoalType;
use Google\AdsApi\AdWords\v201705\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();

Old

<?php
/**
 * This example adds a Universal App campaign. To get campaigns, run
 * GetCampaigns.php. To upload image assets for this campaign, run
 * UploadImage.php.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

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

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

  // Create campaign with some properties set.
  $campaign = new Campaign();
  $campaign->name = '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->status = 'PAUSED';

  // Set the advertising channel and subchannel types for Universal app
  // campaigns.
  $campaign->advertisingChannelType = 'MULTI_CHANNEL';
  $campaign->advertisingChannelSubType = 'UNIVERSAL_APP_CAMPAIGN';

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

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

  $biddingStrategyConfiguration->biddingScheme = $biddingScheme;
  $campaign->biddingStrategyConfiguration = $biddingStrategyConfiguration;

  // Set the campaign's budget.
  $campaign->budget = new Budget();
  $campaign->budget->budgetId = CreateBudget($user);

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

  // Optional: Set the end date.
  $campaign->endDate = 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->appId = 'com.labpixies.colordrips';
  $universalAppSetting->description1 = 'A cool puzzle game';
  $universalAppSetting->description2 = 'Remove connected blocks';
  $universalAppSetting->description3 = '3 difficulty levels';
  $universalAppSetting->description4 = '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 = array(INSERT_IMAGE_MEDIA_ID_HERE);

  // Optimize this campaign for getting new users for your app.
  $universalAppSetting->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 = array(
  //     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->negativeGeoTargetType = 'LOCATION_OF_PRESENCE';
  $campaign->settings = array($universalAppSetting, $geoTargetTypeSetting);

  // Create the campaign operation.
  $operations = array();
  $operation = new CampaignOperation();
  $operation->operand = $campaign;
  $operation->operator = 'ADD';
  $operations[] = $operation;

  // Add campaigns on the server.
  $result = $campaignService->mutate($operations);

  // Print information for each campaign.
  foreach ($result->value as $campaign) {
    printf("Universal App Campaign with name '%s' and ID %d was added.\n",
        $campaign->name, $campaign->id);
    // Optional: Set the campaign's location and language targeting. No other
    // targeting criteria can be used for Universal App campaigns.
    SetCampaignTargetingCriteria($campaign->id, $user);
  }
}

/**
 * Creates the budget for the campaign.
 *
 * @return the new budget ID
 */
function CreateBudget(AdWordsUser $user) {
  // Get the BudgetService, which loads the required classes.
  $budgetService = $user->GetService('BudgetService', ADWORDS_VERSION);

  // Create the shared budget (required).
  $budget = new Budget();
  $budget->name = 'Interplanetary Cruise Budget #' . uniqid();
  $budget->amount = new Money(50000000);
  $budget->deliveryMethod = 'STANDARD';

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

  // Create operation.
  $operation = new BudgetOperation();
  $operation->operand = $budget;
  $operation->operator = 'ADD';
  $operations[] = $operation;

  // Make the mutate request.
  $result = $budgetService->mutate($operations);
  $budget = $result->value[0];

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

  return $budget->budgetId;
}

/**
 * Sets the campaign's targeting criteria.
 *
 * @param AdWordsUser $user the AdWords user object
 */
function SetCampaignTargetingCriteria($campaignId, AdWordsUser $user) {
  // Get the service, which loads the required classes.
  $campaignCriterionService =
      $user->GetService('CampaignCriterionService', ADWORDS_VERSION);

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

  $mexico = new Location();
  $mexico->id = 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->id = 1000;
  $campaignCriteria[] = new CampaignCriterion($campaignId, null, $english);

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

  // Create operations to add each of the criteria above.
  $operations = array();
  foreach ($campaignCriteria as $campaignCriterion) {
    $operations[] = new CampaignCriterionOperation($campaignCriterion, 'ADD');
  }

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

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

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

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

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

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

Get ad group bid modifiers

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdGroupBidModifierService;
use Google\AdsApi\AdWords\v201705\cm\OrderBy;
use Google\AdsApi\AdWords\v201705\cm\Paging;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\AdWords\v201705\cm\SortOrder;
use Google\AdsApi\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();

Old

<?php
/**
 * This example illustrates how to retrieve ad group level bid modifiers for a
 * campaign.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

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

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

  // Create selector.
  $selector = new Selector();
  $selector->fields = array('CampaignId', 'AdGroupId', 'BidModifier', 'Id');
  $selector->ordering[] = new OrderBy('CampaignId', 'ASCENDING');

  // Create paging controls.
  $selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);

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

    // Display results.
    if (isset($page->entries)) {
      foreach ($page->entries as $modifier) {
        $value = 'none';
        if (is_numeric($modifier->bidModifier)) {
          $value = $modifier->bidModifier;
        }
        printf("Campaign ID %d, AdGroup ID %d, Criterion ID %d has ad group " .
            "level modifier: %s\n",
          $modifier->campaignId,
          $modifier->adGroupId,
          $modifier->criterion->id,
          $value
        );
      }
    } else {
      print "No bid modifiers were found.\n";
    }

    // Advance the paging index.
    $selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
  } while ($page->totalNumEntries > $selector->paging->startIndex);
}

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

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

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

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

Use a portfolio bidding strategy

New

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201705\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201705\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201705\cm\BiddingStrategyOperation;
use Google\AdsApi\AdWords\v201705\cm\BiddingStrategyService;
use Google\AdsApi\AdWords\v201705\cm\Budget;
use Google\AdsApi\AdWords\v201705\cm\BudgetBudgetDeliveryMethod;
use Google\AdsApi\AdWords\v201705\cm\BudgetOperation;
use Google\AdsApi\AdWords\v201705\cm\BudgetService;
use Google\AdsApi\AdWords\v201705\cm\Campaign;
use Google\AdsApi\AdWords\v201705\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignService;
use Google\AdsApi\AdWords\v201705\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201705\cm\Money;
use Google\AdsApi\AdWords\v201705\cm\NetworkSetting;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\SharedBiddingStrategy;
use Google\AdsApi\AdWords\v201705\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();

Old

<?php
/**
 * This example adds a Portfolio Bidding Strategy and uses it to
 * construct a campaign.
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

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

// Enter budgetId required by the code example, or leave as null to create one.
$budgetId = null;

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string|null $sharedBudgetId the shared budget ID to re-use or null
 *    to create a new one
 */
function UsePortfolioBiddingStrategyExample(AdWordsUser $user,
    $sharedBudgetId = null) {
  $biddingStrategy = CreateBiddingStrategy($user);

  if (!$sharedBudgetId) {
    $budget = CreateSharedBudget($user);
    $sharedBudgetId = $budget->budgetId;
  }
  CreateCampaignWithBiddingStrategy($user, $biddingStrategy->id,
      $sharedBudgetId);
}

/**
 * Creates the bidding strategy object.
 * @param AdWordsUser $user the user to run the example with
 */
function CreateBiddingStrategy(AdWordsUser $user) {
  // Get the BiddingStrategyService, which loads the required classes.
  $biddingStrategyService =
      $user->GetService('BiddingStrategyService', ADWORDS_VERSION);

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

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

  $biddingStrategy->biddingScheme = $biddingScheme;

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

  $result = $biddingStrategyService->mutate(array($operation));

  $newBiddingStrategy = $result->value[0];

  printf(
      "Portfolio bidding strategy with name '%s' and ID %d of type %s was "
          . "created.\n",
      $newBiddingStrategy->name,
      $newBiddingStrategy->id,
      $newBiddingStrategy->biddingScheme->biddingSchemeType
  );

  return $newBiddingStrategy;
}

/**
 * Creates an explicit budget to be used only to create the Campaign.
 * @param AdWordsUser $user the user to run the example with
 */
function CreateSharedBudget($user) {
  // Get the BudgetService, which loads the required classes.
  $budgetService = $user->GetService('BudgetService', ADWORDS_VERSION);

  // Create a shared budget
  $budget = new Budget();
  $budget->name = "Shared Interplanetary Budget #" . uniqid();
  $budget->period = 'DAILY';
  $budget->amount = new Money(50000000);
  $budget->deliveryMethod = 'STANDARD';
  $budget->isExplicitlyShared = true;

  $operations = array();

  // Create operation.
  $operation = new BudgetOperation();
  $operation->operand = $budget;
  $operation->operator = 'ADD';
  $operations[] = $operation;

  // Make the mutate request.
  $result = $budgetService->mutate($operations);
  return $result->value[0];
}

/**
 * Create a Campaign with a Portfolio Bidding Strategy.
 * @param AdWordsUser $user the user to run the example with
 * @param string $biddingStrategyId the bidding strategy id to use
 * @param string $sharedBudgetId the shared budget id to use
 */
function CreateCampaignWithBiddingStrategy(AdWordsUser $user,
    $biddingStrategyId, $sharedBudgetId) {
  // Get the CampaignService, which loads the required classes.
  $campaignService = $user->GetService('CampaignService', ADWORDS_VERSION);

  // Create campaign.
  $campaign = new Campaign();
  $campaign->name = 'Interplanetary Cruise #' . uniqid();

  // Set the budget.
  $campaign->budget = new Budget();
  $campaign->budget->budgetId = $sharedBudgetId;
  $campaign->advertisingChannelType = 'SEARCH';

  // Set bidding strategy (required).
  $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
  $biddingStrategyConfiguration->biddingStrategyId = $biddingStrategyId;

  $campaign->biddingStrategyConfiguration = $biddingStrategyConfiguration;

  // Set network targeting (recommended).
  $networkSetting = new NetworkSetting();
  $networkSetting->targetGoogleSearch = true;
  $networkSetting->targetSearchNetwork = true;
  $networkSetting->targetContentNetwork = true;
  $campaign->networkSetting = $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->status = 'PAUSED';

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

  $result = $campaignService->mutate(array($operation));

  $newCampaign = $result->value[0];

  printf("Campaign with name '%s', ID %d and bidding scheme ID %d was "
        . "created.\n", $newCampaign->name, $newCampaign->id,
          $newCampaign->biddingStrategyConfiguration->biddingStrategyId);

  return $newCampaign;
}

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

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

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

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

Send feedback about...

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