Campaign Management Samples

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

Add a campaign group and sets a performance target for that 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\CampaignManagement;

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\Campaign;
use Google\AdsApi\AdWords\v201705\cm\CampaignGroup;
use Google\AdsApi\AdWords\v201705\cm\CampaignGroupOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignGroupPerformanceTarget;
use Google\AdsApi\AdWords\v201705\cm\CampaignGroupPerformanceTargetOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignGroupPerformanceTargetService;
use Google\AdsApi\AdWords\v201705\cm\CampaignGroupService;
use Google\AdsApi\AdWords\v201705\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignService;
use Google\AdsApi\AdWords\v201705\cm\EfficiencyTargetType;
use Google\AdsApi\AdWords\v201705\cm\Money;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\PerformanceTarget;
use Google\AdsApi\AdWords\v201705\cm\SpendTargetType;
use Google\AdsApi\AdWords\v201705\cm\VolumeGoalType;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This code example adds a campaign group and sets a performance target for
 * that group. To get campaigns, run GetCampaigns.php. To download reports, run
 * DownloadCriteriaReportWithAwql.php.
 */
class AddCampaignGroupsAndPerformanceTargets {

  const CAMPAIGN_ID_1 = 'INSERT_CAMPAIGN_ID_1_HERE';
  const CAMPAIGN_ID_2 = 'INSERT_CAMPAIGN_ID_2_HERE';

  public static function runExample(
      AdWordsServices $adWordsServices, AdWordsSession $session, $campaignIds) {
    $campaignGroup = self::createCampaignGroup($adWordsServices, $session);
    self::addCampaignsToGroup($adWordsServices, $session, $campaignGroup,
        $campaignIds);
    self::createPerformanceTarget($adWordsServices, $session, $campaignGroup);
  }

  private static function createCampaignGroup(
      AdWordsServices $adWordsServices, AdWordsSession $session) {
    $campaignGroupService =
        $adWordsServices->get($session, CampaignGroupService::class);

    // Create the campaign group.
    $campaignGroup = new CampaignGroup();
    $campaignGroup->setName('Mars campaign group #' . uniqid());

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

    $campaignGroup =
        $campaignGroupService->mutate([$operation])->getValue()[0];
    printf("Campaign group with ID %d and name '%s' was created.\n",
        $campaignGroup->getId(), $campaignGroup->getName());

    return $campaignGroup;
  }

  private static function addCampaignsToGroup(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      $campaignGroup,
      $campaignIds
  ) {
    $campaignService = $adWordsServices->get($session, CampaignService::class);

    $operations = [];
    foreach ($campaignIds as $campaignId) {
      $campaign = new Campaign();
      $campaign->setId($campaignId);
      $campaign->setCampaignGroupId($campaignGroup->getId());

      $operation = new CampaignOperation();
      $operation->setOperand($campaign);
      $operation->setOperator(Operator::SET);
      $operations[] = $operation;
    }

    $campaigns = $campaignService->mutate($operations)->getValue();
    printf("The following campaign IDs were added to the campaign group with"
        . " ID %d:\n", $campaignGroup->getId());
    foreach ($campaigns as $campaign) {
      printf("\t%d\n", $campaign->getId());
    }
  }

  private static function createPerformanceTarget(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      CampaignGroup $campaignGroup
  ) {
    $campaignGroupPerformanceTargetService = $adWordsServices->get(
        $session, CampaignGroupPerformanceTargetService::class);

    // Create the performance target.
    $performanceTarget = new PerformanceTarget();
    // Keep the CPC for the campaigns < $3.
    $performanceTarget->setEfficiencyTargetType(
        EfficiencyTargetType::CPC_LESS_THAN_OR_EQUAL_TO);
    $performanceTarget->setEfficiencyTargetValue(3000000);

    // Keep the maximum spend under $50.
    $performanceTarget->setSpendTargetType(SpendTargetType::MAXIMUM);
    $maxSpend = new Money();
    $maxSpend->setMicroAmount(500000000);
    $performanceTarget->setSpendTarget($maxSpend);

    // Aim for at least 3000 clicks.
    $performanceTarget->setVolumeTargetValue(3000);
    $performanceTarget->setVolumeGoalType(VolumeGoalType::MAXIMIZE_CLICKS);

    // Start the performance target today, and run it for the next 90 days.
    $startDate = date('Ymd', strtotime('now'));
    $endDate =  date('Ymd', strtotime('+90 day'));

    $performanceTarget->setStartDate($startDate);
    $performanceTarget->setEndDate($endDate);

    // Create the campaign group performance target.
    $campaignGroupPerformanceTarget = new CampaignGroupPerformanceTarget();
    $campaignGroupPerformanceTarget->setCampaignGroupId(
        $campaignGroup->getId());
    $campaignGroupPerformanceTarget->setPerformanceTarget($performanceTarget);

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

    $campaignGroupPerformanceTarget = $campaignGroupPerformanceTargetService
        ->mutate([$operation])->getValue()[0];

    // Display the results.
    printf(
        "Campaign group performance target with ID %d was added for campaign"
            . " group ID %d.\n",
        $campaignGroupPerformanceTarget->getId(),
        $campaignGroupPerformanceTarget->getCampaignGroupId()
    );
  }

  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_1), intval(self::CAMPAIGN_ID_2)]
    );
  }
}

AddCampaignGroupsAndPerformanceTargets::main();

Old

Add a label to multiple campaigns

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\CampaignManagement;

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\CampaignLabel;
use Google\AdsApi\AdWords\v201705\cm\CampaignLabelOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignService;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a label to multiple campaigns.
 */
class AddCampaignLabels {

  const CAMPAIGN_ID_1 = 'INSERT_CAMPAIGN_ID_1_HERE';
  const CAMPAIGN_ID_2 = 'INSERT_CAMPAIGN_ID_2_HERE';
  const LABEL_ID = 'INSERT_LABEL_ID_HERE';

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

    // Create campaign labels and campaign label operations, and add the
    // operations to the list.
    $operations = [];
    foreach ($campaignIds as $campaignId) {
      $campaignLabel = new CampaignLabel();
      $campaignLabel->setCampaignId($campaignId);
      $campaignLabel->setLabelId($labelId);

      $operation = new CampaignLabelOperation();
      $operation->setOperand($campaignLabel);
      $operation->setOperator(Operator::ADD);

      $operations[] = $operation;
    }

    // Add campaign labels on the server and print out some information for
    // each created campaign label.
    $result = $campaignService->mutateLabel($operations);
    foreach ($result->getValue() as $campaignLabel) {
      printf("Campaign label for campaign ID %d and label ID %d was added.\n",
          $campaignLabel->getCampaignId(), $campaignLabel->getLabelId());
    }
  }

  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_1), intval(self::CAMPAIGN_ID_2)],
        intval(self::LABEL_ID)
    );
  }
}

AddCampaignLabels::main();

Old

<?php
/**
 * This example adds a label to multiple campaigns.
 *
 * 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';

$campaignIds = array('INSERT_CAMPAIGN_ID_1_HERE', 'INSERT_CAMPAIGN_ID_2_HERE');
$labelId = 'INSERT_LABEL_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param array $campaignIds an array of campaign Ids to run the example with
 * @param string $labelId the label Id to run the example with
 */
function AddCampaignLabelsExample(AdWordsUser $user, array $campaignIds,
    $labelId) {
  // Get the CampaignService, which loads the required classes.
  $campaignService = $user->GetService('CampaignService', ADWORDS_VERSION);

  $operations = array();
  foreach ($campaignIds as $campaignId) {
    $campaignLabel = new CampaignLabel();
    $campaignLabel->campaignId = $campaignId;
    $campaignLabel->labelId = $labelId;

    $operation = new CampaignLabelOperation();
    $operation->operand = $campaignLabel;
    $operation->operator = 'ADD';

    $operations[] = $operation;
  }

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

  // Display results.
  foreach ($result->value as $campaignLabel) {
    printf("Campaign label for campaign ID '%s' and label ID '%d' was added.\n",
        $campaignLabel->campaignId, $campaignLabel->labelId);
  }
}

// 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.
  AddCampaignLabelsExample($user, $campaignIds, $labelId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Add complete campaigns using batch jobs

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\CampaignManagement;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\BatchJobs\v201705\BatchJobs;
use Google\AdsApi\AdWords\v201705\cm\AdGroup;
use Google\AdsApi\AdWords\v201705\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201705\cm\BatchJob;
use Google\AdsApi\AdWords\v201705\cm\BatchJobOperation;
use Google\AdsApi\AdWords\v201705\cm\BatchJobService;
use Google\AdsApi\AdWords\v201705\cm\BatchJobStatus;
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\Campaign;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201705\cm\CpcBid;
use Google\AdsApi\AdWords\v201705\cm\ExpandedTextAd;
use Google\AdsApi\AdWords\v201705\cm\Keyword;
use Google\AdsApi\AdWords\v201705\cm\KeywordMatchType;
use Google\AdsApi\AdWords\v201705\cm\ManualCpcBiddingScheme;
use Google\AdsApi\AdWords\v201705\cm\Money;
use Google\AdsApi\AdWords\v201705\cm\NegativeCampaignCriterion;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\Predicate;
use Google\AdsApi\AdWords\v201705\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use UnexpectedValueException;

/**
 * This example adds complete campaigns using BatchJobService.
 */
class AddCompleteCampaignsUsingBatchJob {

  const NUMBER_OF_CAMPAIGNS_TO_ADD = 2;
  const NUMBER_OF_ADGROUPS_TO_ADD = 2;
  const NUMBER_OF_KEYWORDS_TO_ADD = 5;
  const POLL_FREQUENCY_SECONDS = 30;
  const MAX_POLL_ATTEMPTS = 60;

  private static $temporaryId = 0;

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

    // Create a BatchJob.
    $addOp = new BatchJobOperation();
    $addOp->setOperator(Operator::ADD);
    $addOp->setOperand(new BatchJob());

    $result = $batchJobService->mutate([$addOp]);
    $batchJob = $result->getValue()[0];

    // Get the upload URL from the new job.
    $uploadUrl = $batchJob->getUploadUrl()->getUrl();
    printf("Created BatchJob with ID %d, status '%s' and upload URL '%s'.\n",
        $batchJob->getId(), $batchJob->getStatus(), $uploadUrl);

    $namePrefix = uniqid();
    // Create and add an operation to create a new budget.
    $budgetOperation = self::buildBudgetOperation($namePrefix);
    $operations = [$budgetOperation];

    // Create and add an operation to create new campaigns.
    $campaignOperations =
        self::buildCampaignOperations($namePrefix, $budgetOperation);
    $operations = array_merge($operations, $campaignOperations);

    // Create and add operations to create new negative keyword criteria for
    // each campaign.
    $campaignCriterionOperations =
        self::buildCampaignCriterionOperations($campaignOperations);
    $operations = array_merge($operations, $campaignCriterionOperations);

    // Create and add operations to create new ad groups.
    $adGroupOperations =
        self::buildAdGroupOperations($namePrefix, $campaignOperations);
    $operations = array_merge($operations, $adGroupOperations);

    // Create and add operations to create new ad group criteria (keywords).
    $adGroupCriterionOperations =
        self::buildAdGroupCriterionOperations($adGroupOperations);
    $operations = array_merge($operations, $adGroupCriterionOperations);

    // Create and add operations to create new ad group ads (text ads).
    $adGroupAdOperations = self::buildAdGroupAdOperations($adGroupOperations);
    $operations = array_merge($operations, $adGroupAdOperations);

    // Use BatchJobs to upload all operations.
    $batchJobs = new BatchJobs($session);
    $batchJobs->uploadBatchJobOperations($operations, $uploadUrl);

    printf("Uploaded %d operations for batch job with ID %d.\n",
        count($operations), $batchJob->getId());

    // Poll for completion of the batch job using an exponential back off.
    $pollAttempts = 0;
    $isPending = true;
    do {
      $sleepSeconds = self::POLL_FREQUENCY_SECONDS * pow(2, $pollAttempts);
      printf("Sleeping %d seconds...\n", $sleepSeconds);
      sleep($sleepSeconds);

      $selector = new Selector();
      $selector->setFields(
          ['Id', 'Status', 'DownloadUrl', 'ProcessingErrors', 'ProgressStats']);
      $selector->setPredicates([
          new Predicate('Id', PredicateOperator::EQUALS, [$batchJob->getId()])
      ]);
      $batchJob = $batchJobService->get($selector)->getEntries()[0];
      printf("Batch job ID %d has status '%s'.\n", $batchJob->getId(),
          $batchJob->getStatus());

      $pollAttempts++;
      if ($batchJob->getStatus() !== BatchJobStatus::ACTIVE &&
          $batchJob->getStatus() !== BatchJobStatus::AWAITING_FILE &&
          $batchJob->getStatus() !== BatchJobStatus::CANCELING) {
        $isPending = false;
      }
    } while ($isPending && $pollAttempts <= self::MAX_POLL_ATTEMPTS);

    if ($isPending) {
      throw new UnexpectedValueException(
          sprintf('Job is still pending state after polling %d times.',
              self::MAX_POLL_ATTEMPTS));
    }

    if ($batchJob->getProcessingErrors() !== null) {
      $i = 0;
      foreach ($batchJob->getProcessingErrors() as $processingError) {
        printf(
            " Processing error [%d]: errorType=%s, trigger=%s, errorString=%s,"
                . " fieldPath=%s, reason=%s\n",
            $i++,
            $processingError->getApiErrorType(),
            $processingError->getTrigger(),
            $processingError->getErrorString(),
            $processingError->getFieldPath(),
            $processingError->getReason()
        );
      }
    } else {
      printf("No processing errors found.\n");
    }

    if ($batchJob->getDownloadUrl() !== null
        && $batchJob->getDownloadUrl()->getUrl() !== null) {
      $mutateResults = $batchJobs->downloadBatchJobResults(
          $batchJob->getDownloadUrl()->getUrl());
      printf("Downloaded results from %s:\n",
          $batchJob->getDownloadUrl()->getUrl());

      if (count($mutateResults) === 0) {
        printf("  No results available.\n");
      } else {
        foreach ($mutateResults as $mutateResult) {
          $outcome =
              $mutateResult->getErrorList() === null ? 'SUCCESS' : 'FAILURE';
          printf("  Operation [%d] - %s\n", $mutateResult->getIndex(),
              $outcome);
        }
      }
    } else {
      printf("No results available for download.\n");
    }
  }

  /**
   * Builds objects of AdGroupAdOperation for creating an ad group ad for
   * ad groups in the specified ad group operations.
   *
   * @param AdGroupOperation[] $adGroupOperations an array of AdGroupOperation
   * @return array an array of AdGroupAdOperation
   */
  private static function buildAdGroupAdOperations(array $adGroupOperations) {
    $operations = [];
    foreach ($adGroupOperations as $adGroupOperation) {
      $adGroupId = $adGroupOperation->getOperand()->getId();
      $adGroupAd = new AdGroupAd();
      $adGroupAd->setAdGroupId($adGroupId);

      $expandedTextAd = new ExpandedTextAd();
      $expandedTextAd->setHeadlinePart1('Luxury Cruise to Mars');
      $expandedTextAd->setHeadlinePart2('Visit the Red Planet in style.');
      $expandedTextAd->setDescription('Low-gravity fun for everyone!');
      $expandedTextAd->setFinalUrls(['http://www.example.com/1']);

      $adGroupAd->setAd($expandedTextAd);

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

      $operations[] = $operation;
    }
    return $operations;
  }

  /**
   * Builds objects of AdGroupCriterionOperation for creating biddable criteria
   * (as keywords) for ad groups in the specified ad group operations. 50% of
   * keywords are created with some invalid characters to demonstrate how
   * BatchJobService returns information about such errors.
   *
   * @param AdGroupOperation[] $adGroupOperations an array of AdGroupOperation
   * @return array an array of AdGroupCriterionOperation
   */
  private static function buildAdGroupCriterionOperations
      (array $adGroupOperations) {
    $adGroupCriteriaOperations = [];

    // Create AdGroupCriterionOperations to add keywords.
    foreach ($adGroupOperations as $adGroupOperation) {
      $newAdGroupId = $adGroupOperation->getOperand()->getId();
      for ($i = 0; $i < self::NUMBER_OF_KEYWORDS_TO_ADD; $i++) {
        // Create Keyword.
        $text = sprintf('mars%d', $i);

        // Make 50% of keywords invalid to demonstrate error handling.
        if ($i % 2 == 0) {
          $text = $text . '!!!';
        }
        $keyword = new Keyword();
        $keyword->setText($text);
        $keyword->setMatchType(KeywordMatchType::BROAD);

        // Create BiddableAdGroupCriterion.
        $biddableAdGroupCriterion = new BiddableAdGroupCriterion();
        $biddableAdGroupCriterion->setAdGroupId($newAdGroupId);
        $biddableAdGroupCriterion->setCriterion($keyword);

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

        // Add to list.
        $adGroupCriteriaOperations[] = $operation;
      }
    }
    return $adGroupCriteriaOperations;
  }

  /**
   * Builds objects of AdGroupOperation for creating ad groups for campaigns in
   * the specified campaign operations.
   *
   * @param string $namePrefix a prefix string used to name ad groups
   * @param CampaignOperation[] $campaignOperations an array of
   *     CampaignOperation
   * @return array an array of AdGroupOperation
   */
  private static function buildAdGroupOperations($namePrefix,
      array $campaignOperations) {
    $operations = [];
    foreach ($campaignOperations as $campaignOperation) {
      for ($i = 0; $i < self::NUMBER_OF_ADGROUPS_TO_ADD; $i++) {
        $adGroup = new AdGroup();
        $adGroup->setCampaignId($campaignOperation->getOperand()->getId());
        $adGroup->setId(--self::$temporaryId);
        $adGroup->setName(sprintf('Batch Ad Group %s.%s', $namePrefix,
            strval($adGroup->getId())));

        $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
        $money = new Money();
        $money->setMicroAmount(10000000);
        $bid = new CpcBid();
        $bid->setBid($money);
        $biddingStrategyConfiguration->setBids([$bid]);

        $adGroup->setBiddingStrategyConfiguration(
            $biddingStrategyConfiguration);

        $operation = new AdGroupOperation();
        $operation->setOperand($adGroup);
        $operation->setOperator(Operator::ADD);

        $operations[] = $operation;
      }
    }
    return $operations;
  }

  /**
   * Builds objects of CampaignCriterionOperation for creating a negative
   * campaign criterion (as keyword) for campaigns in the specified campaign
   * operations.
   *
   * @param CampaignOperation[] $campaignOperations an array of
   *     CampaignOperation
   * @return array an array of CampaignCriterionOperation
   */
  private static function buildCampaignCriterionOperations(
      array $campaignOperations) {
    $operations = [];
    foreach ($campaignOperations as $campaignOperation) {
      $keyword = new Keyword();
      $keyword->setMatchType(KeywordMatchType::BROAD);
      $keyword->setText('venus');

      $negativeCriterion = new NegativeCampaignCriterion();
      $negativeCriterion->setCampaignId(
          $campaignOperation->getOperand()->getId());
      $negativeCriterion->setCriterion($keyword);

      $operation = new CampaignCriterionOperation();
      $operation->setOperand($negativeCriterion);
      $operation->setOperator(Operator::ADD);

      $operations[] = $operation;
    }
    return $operations;
  }

  /**
   * Builds objects of CampaignOperation for creating a campaign using the ID of
   * budget in the specified budget operation.
   *
   * @param string $namePrefix a prefix string used to name campaigns
   * @param BudgetOperation $budgetOperation an object of BudgetOperation
   * @return array an array of CampaignOperation
   */
  private static function buildCampaignOperations($namePrefix,
      BudgetOperation $budgetOperation) {
    $budgetId = $budgetOperation->getOperand()->getBudgetId();

    $operations = [];
    for ($i = 0; $i < self::NUMBER_OF_CAMPAIGNS_TO_ADD; $i++) {
      $campaign = new Campaign();
      $campaign->setId(--self::$temporaryId);
      $campaign->setName(sprintf('Batch Campaign %s.%s', $namePrefix,
          strval($campaign->getId())));

      // 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);
      $campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH);

      $budget = new Budget();
      $budget->setBudgetId($budgetId);
      $campaign->setBudget($budget);
      $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
      $biddingStrategyConfiguration->setBiddingStrategyType(
          BiddingStrategyType::MANUAL_CPC);

      // You can optionally provide a bidding scheme in place of the type.
      $cpcBiddingScheme = new ManualCpcBiddingScheme();
      $cpcBiddingScheme->setEnhancedCpcEnabled(false);
      $biddingStrategyConfiguration->setBiddingScheme($cpcBiddingScheme);

      $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

      $operation = new CampaignOperation();
      $operation->setOperand($campaign);
      $operation->setOperator(Operator::ADD);
      $operations[] = $operation;
    }
    return $operations;
  }

  /**
   * Builds BudgetOperation for creating a budget.
   *
   * @param string $namePrefix a prefix string used to name a budget
   * @return BudgetOperation an object of BudgetOperation
   */
  private static function buildBudgetOperation($namePrefix) {
    $budget = new Budget();
    $budget->setBudgetId(--self::$temporaryId);
    $budget->setName('Interplanetary Cruise #' . $namePrefix);
    $budgetAmount = new Money();
    $budgetAmount->setMicroAmount(50000000);
    $budget->setAmount($budgetAmount);
    $budget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD);

    $budgetOperation = new BudgetOperation();
    $budgetOperation->setOperand($budget);
    $budgetOperation->setOperator(Operator::ADD);
    return $budgetOperation;
  }

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

AddCompleteCampaignsUsingBatchJob::main();

Old

<?php
/**
 * This code sample illustrates how to use BatchJobService to create a complete
 * campaign, including ad groups and keywords.
 *
 * 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 ADWORDS_UTIL_PATH . '/TempIdGenerator.php';
require_once ADWORDS_UTIL_PATH . '/XmlDeserializer.php';
require_once ADWORDS_UTIL_PATH . '/XmlSerializer.php';
require_once ADWORDS_UTIL_VERSION_PATH . '/BatchJobUtils.php';

define('NUMBER_OF_CAMPAIGNS_TO_ADD', 2);
define('NUMBER_OF_ADGROUPS_TO_ADD', 2);
define('NUMBER_OF_KEYWORDS_TO_ADD', 5);
define('POLL_FREQUENCY_SECONDS', 30);
define('MAX_POLL_ATTEMPTS', 60);

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

  // Create a BatchJob.
  $addOp = new BatchJobOperation();
  $addOp->operator = 'ADD';
  $addOp->operand = new BatchJob();
  $addOps[] = $addOp;

  $result = $batchJobService->mutate($addOps);
  $batchJob = $result->value[0];

  // Get the upload URL from the new job.
  $uploadUrl = $batchJob->uploadUrl->url;
  printf("Created BatchJob with ID %d, status '%s' and upload 'URL' %s.\n",
      $batchJob->id, $batchJob->status, $uploadUrl);

  $namePrefix = uniqid();
  // Create and add an operation to create a new budget.
  $budgetOperation = buildBudgetOperation($namePrefix);
  $operations = array($budgetOperation);

  // Create and add an operation to create new campaigns.
  $campaignOperations = buildCampaignOperations($namePrefix, $budgetOperation);
  $operations = array_merge($operations, $campaignOperations);

  // Create and add operations to create new negative keyword criteria for
  // each campaign.
  $campaignCriterionOperations =
      buildCampaignCriterionOperations($campaignOperations);
  $operations = array_merge($operations, $campaignCriterionOperations);

  // Create and add operations to create new ad groups.
  $adGroupOperations = buildAdGroupOperations($namePrefix, $campaignOperations);
  $operations = array_merge($operations, $adGroupOperations);

  // Create and add operations to create new ad group criteria (keywords).
  $adGroupCriterionOperations =
      buildAdGroupCriterionOperations($adGroupOperations);
  $operations = array_merge($operations, $adGroupCriterionOperations);

  // Create and add operations to create new ad group ads (text ads).
  $adGroupAdOperations = buildAdGroupAdOperations($adGroupOperations);
  $operations = array_merge($operations, $adGroupAdOperations);

  // Use BatchJobUtils to upload all operations.
  $batchJobUtils = new BatchJobUtils($batchJob->uploadUrl->url);
  $batchJobUtils->UploadBatchJobOperations($operations);

  printf("Uploaded %d operations for batch job with ID %d.\n",
      count($operations), $batchJob->id);

  // Poll for completion of the batch job using an exponential back off.
  $pollAttempts = 0;
  $isPending = true;
  do {
    $sleepSeconds = POLL_FREQUENCY_SECONDS * pow(2, $pollAttempts);
    printf("Sleeping %d seconds...\n", $sleepSeconds);
    sleep($sleepSeconds);

    $selector = new Selector();
    $selector->fields = array('Id', 'Status', 'DownloadUrl', 'ProcessingErrors',
        'ProgressStats');
    $selector->predicates[] = new Predicate('Id', 'EQUALS', $batchJob->id);
    $batchJob = $batchJobService->get($selector)->entries[0];
    printf("Batch job ID %d has status '%s'.\n", $batchJob->id,
        $batchJob->status);

    $pollAttempts++;
    if ($batchJob->status !== 'ACTIVE' &&
        $batchJob->status !== 'AWAITING_FILE' &&
        $batchJob->status !== 'CANCELING') {
      $isPending = false;
    }
  } while ($isPending && $pollAttempts <= MAX_POLL_ATTEMPTS);

  if ($isPending) {
    throw new BatchJobException(
        sprintf("Job is still pending state after polling %d times.",
            MAX_POLL_ATTEMPTS));
  }

  if ($batchJob->processingErrors !== null) {
    $i = 0;
    foreach ($batchJob->processingErrors as $processingError) {
      printf(
          " Processing error [%d]: errorType=%s, trigger=%s, errorString=%s,"
              . " fieldPath=%s, reason=%s\n",
          $i++,
          $processingError->ApiErrorType,
          $processingError->trigger,
          $processingError->errorString,
          $processingError->fieldPath,
          $processingError->reason
      );
    }
  } else {
    printf("No processing errors found.\n");
  }

  if ($batchJob->downloadUrl !== null && $batchJob->downloadUrl->url !== null) {
    $xmlResponse =
        $batchJobUtils->DownloadBatchJobResults($batchJob->downloadUrl->url);
    printf("Downloaded results from %s:\n", $batchJob->downloadUrl->url);
    $deserializer = new XmlDeserializer(BatchJobUtils::$CLASS_MAP);
    $mutateResponse = $deserializer->ConvertXmlToObject($xmlResponse);
    if (empty($mutateResponse)) {
      printf("  No results available.\n");
    } else {
      foreach ($mutateResponse->rval as $mutateResult) {
        $outcome = $mutateResult->errorList === null ? 'SUCCESS' : 'FAILURE';
        printf("  Operation [%d] - %s\n", $mutateResult->index, $outcome);
      }
    }
  } else {
    printf("No results available for download.\n");
  }
}

/**
 * Builds objects of AdGroupAdOperation for creating an ad group ad for
 * ad groups in the specified ad group operations.
 *
 * @param array $adGroupOperations an array of AdGroupOperation
 * @return array an array of AdGroupAdOperation
 */
function buildAdGroupAdOperations(array $adGroupOperations) {
  $operations = array();
  foreach ($adGroupOperations as $adGroupOperation) {
    $adGroupId = $adGroupOperation->operand->id;
    $adGroupAd = new AdGroupAd();
    $adGroupAd->adGroupId = $adGroupId;

    $expandedTextAd = new ExpandedTextAd();
    $expandedTextAd->headlinePart1 = 'Luxury Cruise to Mars';
    $expandedTextAd->headlinePart2 = 'Visit the Red Planet in style.';
    $expandedTextAd->description = 'Low-gravity fun for everyone!';
    $expandedTextAd->finalUrls[] = 'http://www.example.com/1';

    $adGroupAd->ad = $expandedTextAd;

    $operation = new AdGroupAdOperation();
    $operation->operator = 'ADD';
    $operation->operand = $adGroupAd;

    $operations[] = $operation;
  }
  return $operations;
}

/**
 * Builds objects of AdGroupCriterionOperation for creating biddable criteria
 * (as keywords) for ad groups in the specified ad group operations. 50% of
 * keywords are created with some invalid characters to demonstrate how
 * BatchJobService returns information about such errors.
 *
 * @param array $adGroupOperations an array of AdGroupOperation
 * @return array an array of AdGroupCriterionOperation
 */
function buildAdGroupCriterionOperations(array $adGroupOperations) {
  $adGroupCriteriaOperations = array();

  // Create AdGroupCriterionOperations to add keywords.
  foreach ($adGroupOperations as $adGroupOperation) {
    $newAdGroupId = $adGroupOperation->operand->id;
    for ($i = 0; $i < NUMBER_OF_KEYWORDS_TO_ADD; $i++) {
      // Create Keyword.
      $text = sprintf("mars%d", $i);

      // Make 50% of keywords invalid to demonstrate error handling.
      if ($i % 2 == 0) {
        $text = $text . '!!!';
      }
      $keyword = new Keyword();
      $keyword->text = $text;
      $keyword->matchType = 'BROAD';

      // Create BiddableAdGroupCriterion.
      $biddableAdGroupCriterion = new BiddableAdGroupCriterion();
      $biddableAdGroupCriterion->adGroupId = $newAdGroupId;
      $biddableAdGroupCriterion->criterion = $keyword;

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

      // Add to list.
      $adGroupCriteriaOperations[] = $operation;
    }
  }
  return $adGroupCriteriaOperations;
}

/**
 * Builds objects of AdGroupOperation for creating ad groups for campaigns in
 * the specified campaign operations.
 *
 * @param string $namePrefix a prefix string used to name ad groups
 * @param array $campaignOperations an array of CampaignOperation
 * @return array an array of AdGroupOperation
 */
function buildAdGroupOperations($namePrefix, array $campaignOperations) {
  $operations = array();
  foreach ($campaignOperations as $campaignOperation) {
    for ($i = 0; $i < NUMBER_OF_ADGROUPS_TO_ADD; $i++) {
      $adGroup = new AdGroup();
      $adGroup->campaignId = $campaignOperation->operand->id;
      $adGroup->id = TempIdGenerator::Generate();
      $adGroup->name = sprintf("Batch Ad Group %s.%s", $namePrefix,
          strval($adGroup->id));

      $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
      $bid = new CpcBid();
      $bid->bid = new Money(10000000);
      $biddingStrategyConfiguration->bids[] = $bid;

      $adGroup->biddingStrategyConfiguration = $biddingStrategyConfiguration;

      $operation = new AdGroupOperation();
      $operation->operand = $adGroup;
      $operation->operator = 'ADD';

      $operations[] = $operation;
    }
  }
  return $operations;
}

/**
 * Builds objects of CampaignCriterionOperation for creating a negative campaign
 * criterion (as keyword) for campaigns in the specified campaign operations.
 *
 * @param array $campaignOperations an array of CampaignOperation
 * @return array an array of CampaignCriterionOperation
 */
function buildCampaignCriterionOperations(array $campaignOperations) {
  $operations = array();
  foreach ($campaignOperations as $campaignOperation) {
    $keyword = new Keyword();
    $keyword->matchType = 'BROAD';
    $keyword->text = 'venus';

    $negativeCriterion = new NegativeCampaignCriterion();
    $negativeCriterion->campaignId = $campaignOperation->operand->id;
    $negativeCriterion->criterion = $keyword;

    $operation = new CampaignCriterionOperation();
    $operation->operand = $negativeCriterion;
    $operation->operator = 'ADD';

    $operations[] = $operation;
  }
  return $operations;
}

/**
 * Builds objects of CampaignOperation for creating a campaign using the ID of
 * budget in the specified budget operation.
 *
 * @param string $namePrefix a prefix string used to name campaigns
 * @param BudgetOperation $budgetOperation an object of BudgetOperation
 * @return array an array of CampaignOperation
 */
function buildCampaignOperations($namePrefix,
    BudgetOperation $budgetOperation) {
  $budgetId = $budgetOperation->operand->budgetId;

  $operations = array();
  for ($i = 0; $i < NUMBER_OF_CAMPAIGNS_TO_ADD; $i++) {
    $campaign = new Campaign();
    $campaign->id = TempIdGenerator::Generate();
    $campaign->name = sprintf("Batch Campaign %s.%s", $namePrefix,
        strval($campaign->id));

    // 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';
    $campaign->advertisingChannelType = 'SEARCH';

    $budget = new Budget();
    $budget->budgetId = $budgetId;
    $campaign->budget = $budget;
    $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
    $biddingStrategyConfiguration->biddingStrategyType = 'MANUAL_CPC';

    // You can optionally provide a bidding scheme in place of the type.
    $cpcBiddingScheme = new ManualCpcBiddingScheme();
    $cpcBiddingScheme->enhancedCpcEnabled = false;
    $biddingStrategyConfiguration->biddingScheme = $cpcBiddingScheme;

    $campaign->biddingStrategyConfiguration = $biddingStrategyConfiguration;

    $operation = new CampaignOperation();
    $operation->operand = $campaign;
    $operation->operator = 'ADD';
    $operations[] = $operation;
  }
  return $operations;
}

/**
 * Builds BudgetOperation for creating a budget.
 *
 * @param string $namePrefix a prefix string used to name a budget
 * @return BudgetOperation an object of BudgetOperation
 */
function buildBudgetOperation($namePrefix) {
  $budget = new Budget();
  $budget->budgetId = TempIdGenerator::Generate();
  $budget->name = 'Interplanetary Cruise #' . $namePrefix;
  $budgetAmount = new Money();
  $budgetAmount->microAmount = 50000000;
  $budget->amount = $budgetAmount;
  $budget->deliveryMethod = 'STANDARD';

  $budgetOperation = new BudgetOperation();
  $budgetOperation->operand = $budget;
  $budgetOperation->operator = 'ADD';
  return $budgetOperation;
}

// 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.
  AddCompleteCampaignUsingBatchJobExample($user);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Add a draft

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\CampaignManagement;

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\CampaignCriterion;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201705\cm\Draft;
use Google\AdsApi\AdWords\v201705\cm\DraftOperation;
use Google\AdsApi\AdWords\v201705\cm\DraftService;
use Google\AdsApi\AdWords\v201705\cm\Language;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example shows how to create a draft and access its associated
 * draft campaign.
 */
class AddDraft {

  const BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE';

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

    $operations = [];
    // Create a draft.
    $draft = new Draft();
    $draft->setBaseCampaignId($baseCampaignId);
    $draft->setDraftname('Test Draft #' . uniqid());

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

    // Create the draft on the server and print out some information for
    // the created draft.
    $result = $draftService->mutate($operations);
    $draft = $result->getValue()[0];
    printf(
        "Draft with ID %d, base campaign ID %d, and draft campaign ID"
            . " %d was added.\n",
        $draft->getDraftId(),
        $draft->getBaseCampaignId(),
        $draft->getDraftCampaignId()
    );

    // Once the draft is created, you can modify the draft campaign as if it
    // were a real campaign. For example, you may add criteria, adjust bids, or
    // even include additional ads. Adding a criterion is shown here.
    $campaignCriterionService =
        $adWordsServices->get($session, CampaignCriterionService::class);

    // Create a criterion.
    $language = new Language();
    $language->setId(1003); // Spanish
    $campaignCriterion = new CampaignCriterion();
    $campaignCriterion->setCampaignId($draft->getDraftCampaignId());
    $campaignCriterion->setCriterion($language);

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

    // Create a campaign criterion on the server.
    $campaignCriterion =
        $campaignCriterionService->mutate($operations)->getValue()[0];

    printf("Draft updated to include criteria in the campaign with ID %d.\n",
        $draft->getDraftCampaignId());
  }

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

AddDraft::main();

Old

<?php
/**
 * This example shows how to create a draft and access its associated
 * draft campaign.
 *
 * See the Campaign Drafts and Experiments guide for more information:
 * https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments
 *
 * 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.
$baseCampaignId = 'INSERT_BASE_CAMPAIGN_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param int $baseCampaignId the ID of the base campaign used to create
 *     a draft
 */
function AddDraftExample(AdWordsUser $user, $baseCampaignId) {
  // Get the DraftService, which loads the required classes.
  $draftService = $user->GetService('DraftService', ADWORDS_VERSION);

  // Create a draft.
  $draft = new Draft();
  $draft->baseCampaignId = $baseCampaignId;
  $draft->draftName = 'Test Draft #' . uniqid();

  // Create an operation.
  $operation = new DraftOperation();
  $operation->operand = $draft;
  $operation->operator = 'ADD';
  $operations[] = $operation;

  // Make the mutate request.
  $result = $draftService->mutate($operations);
  $draft = $result->value[0];
  printf(
      "Draft with ID %d, base campaign ID %d, and draft campaign ID"
          . " %d was added.\n",
      $draft->draftId,
      $draft->baseCampaignId,
      $draft->draftCampaignId
  );

  // Once the draft is created, you can modify the draft campaign as if it were
  // a real campaign. For example, you may add criteria, adjust bids, or even
  // include additional ads. Adding a criterion is shown here.
  $campaignCriterionService =
      $user->GetService('CampaignCriterionService', ADWORDS_VERSION);

  // Create a criterion.
  $language = new Language();
  $language->id = 1003; // Spanish
  $campaignCriterion = new CampaignCriterion();
  $campaignCriterion->campaignId = $draft->draftCampaignId;
  $campaignCriterion->criterion = $language;

  // Create an operation.
  $operations = array();
  $operation = new CampaignCriterionOperation();
  $operation->operand = $campaignCriterion;
  $operation->operator = 'ADD';
  $operations[] = $operation;

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

  printf("Draft updated to include criteria in the campaign with ID %d.\n",
      $draft->draftCampaignId);
}

// 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.
  AddDraftExample($user, $baseCampaignId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Add keywords using an incremental batch job

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\CampaignManagement;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\BatchJobs\BatchJobUploadStatus;
use Google\AdsApi\AdWords\BatchJobs\v201705\BatchJobs;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\ApiException;
use Google\AdsApi\AdWords\v201705\cm\BatchJob;
use Google\AdsApi\AdWords\v201705\cm\BatchJobError;
use Google\AdsApi\AdWords\v201705\cm\BatchJobErrorReason;
use Google\AdsApi\AdWords\v201705\cm\BatchJobOperation;
use Google\AdsApi\AdWords\v201705\cm\BatchJobService;
use Google\AdsApi\AdWords\v201705\cm\BatchJobStatus;
use Google\AdsApi\AdWords\v201705\cm\BiddableAdGroupCriterion;
use Google\AdsApi\AdWords\v201705\cm\Keyword;
use Google\AdsApi\AdWords\v201705\cm\KeywordMatchType;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\Predicate;
use Google\AdsApi\AdWords\v201705\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use UnexpectedValueException;

/**
 * This code sample illustrates how to perform multiple requests using the
 * BatchJobService using incremental uploads.
 */
class AddKeywordsUsingIncrementalBatchJob {

  const NUMBER_OF_KEYWORDS_TO_ADD = 100;
  const POLL_FREQUENCY_SECONDS = 30;
  const MAX_POLL_ATTEMPTS = 5;

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

    // Create a BatchJob.
    $addOp = new BatchJobOperation();
    $addOp->setOperator(Operator::ADD);
    $addOp->setOperand(new BatchJob());

    $result = $batchJobService->mutate([$addOp]);
    $batchJob = $result->getValue()[0];

    // Get the upload URL from the new job.
    $uploadUrl = $batchJob->getUploadUrl()->getUrl();
    printf("Created BatchJob with ID %d, status '%s' and upload URL '%s'.\n",
        $batchJob->getId(), $batchJob->getStatus(), $uploadUrl);

    // Use BatchJobs to upload all operations.
    $batchJobs = new BatchJobs($session);

    // Generate and upload the first set of operations.
    $adGroupCriterionOperations =
        self::buildAdGroupCriterionOperations($adGroupId);
    $batchJobUploadStatus = $batchJobs->uploadIncrementalBatchJobOperations(
        $adGroupCriterionOperations,
        new BatchJobUploadStatus($uploadUrl, $session)
    );
    printf("Uploaded %d operations for batch job with ID %d.\n",
        count($adGroupCriterionOperations), $batchJob->getId());

    // Generate and upload the second set of operations.
    $adGroupCriterionOperations =
        self::buildAdGroupCriterionOperations($adGroupId);
    $batchJobUploadStatus = $batchJobs->uploadIncrementalBatchJobOperations(
        $adGroupCriterionOperations, $batchJobUploadStatus);
    printf("Uploaded %d operations for batch job with ID %d.\n",
        count($adGroupCriterionOperations), $batchJob->getId());

    // Generate and upload the third and final set of operations.
    $adGroupCriterionOperations =
        self::buildAdGroupCriterionOperations($adGroupId);
    $batchJobUploadStatus = $batchJobs->uploadIncrementalBatchJobOperations(
        $adGroupCriterionOperations, $batchJobUploadStatus);
    printf("Uploaded %d operations for batch job with ID %d.\n",
        count($adGroupCriterionOperations), $batchJob->getId());
    $batchJobs->closeIncrementalUpload($batchJobUploadStatus);

    // Poll for completion of the batch job using an exponential back off.
    $pollAttempts = 0;
    $isPending = true;
    $wasCancelRequested = false;

    $selector = new Selector();
    $selector->setFields(
        ['Id', 'Status', 'DownloadUrl', 'ProcessingErrors', 'ProgressStats']);
    $selector->setPredicates([
        new Predicate('Id', PredicateOperator::EQUALS, [$batchJob->getId()])
    ]);
    do {
      $sleepSeconds = self::POLL_FREQUENCY_SECONDS * pow(2, $pollAttempts);
      printf("Sleeping %d seconds...\n", $sleepSeconds);
      sleep($sleepSeconds);

      $batchJob = $batchJobService->get($selector)->getEntries()[0];
      printf("Batch job ID %d has status '%s'.\n", $batchJob->getId(),
          $batchJob->getStatus());

      $pollAttempts++;
      if ($batchJob->getStatus() !== BatchJobStatus::ACTIVE &&
          $batchJob->getStatus() !== BatchJobStatus::AWAITING_FILE &&
          $batchJob->getStatus() !== BatchJobStatus::CANCELING) {
        $isPending = false;
      }

      // Optional: Cancel the job if it has not completed after polling
      // MAX_POLL_ATTEMPTS times.
      if ($isPending && !$wasCancelRequested
          && $pollAttempts === self::MAX_POLL_ATTEMPTS) {
        $batchJob->setStatus(BatchJobStatus::CANCELING);
        $batchJobSetOperation = new BatchJobOperation();
        $batchJobSetOperation->setOperand($batchJob);
        $batchJobSetOperation->setOperator(Operator::SET);

        // Only request cancellation once per job.
        $wasCancelRequested = true;
        try {
          $batchJob =
              $batchJobService->mutate([$batchJobSetOperation])->getValue()[0];
          printf("Requested cancellation of batch job with ID %d.\n",
              $batchJob->getId());
          // Reset the poll attempt counter to wait for cancellation.
          $pollAttempts = 0;
        } catch (ApiException $e) {
          $errors = $e->getErrors();
          if ($errors !== null
              && count($errors) > 0
              && $errors[0] instanceof BatchJobError) {
            $batchJobError = $errors[0];
            if ($batchJobError->getReason()
                === BatchJobErrorReason::INVALID_STATE_CHANGE) {
              printf(
                  "Attempt to cancel batch job with ID %d was rejected because"
                      . " the job already completed or was canceled.\n",
                  $batchJob->getId()
              );
              continue;
            }
          }
          throw $e;
        } finally {
          // Reset the poll attempt counter to wait for cancellation.
          $pollAttempts = 0;
        }
      }
    } while ($isPending && $pollAttempts <= self::MAX_POLL_ATTEMPTS);

    if ($isPending) {
      throw new UnexpectedValueException(
          sprintf('Job is still pending state after polling %d times.',
              self::MAX_POLL_ATTEMPTS));
    }

    if ($batchJob->getProcessingErrors() !== null) {
      $i = 0;
      foreach ($batchJob->getProcessingErrors() as $processingError) {
        printf(
            " Processing error [%d]: errorType=%s, trigger=%s, errorString=%s,"
                . " fieldPath=%s, reason=%s\n",
            $i++,
            $processingError->getApiErrorType(),
            $processingError->getTrigger(),
            $processingError->getErrorString(),
            $processingError->getFieldPath(),
            $processingError->getReason()
        );
      }
    } else {
      printf("No processing errors found.\n");
    }

    if ($batchJob->getDownloadUrl() !== null
        && $batchJob->getDownloadUrl()->getUrl() !== null) {
      $mutateResults = $batchJobs->downloadBatchJobResults(
          $batchJob->getDownloadUrl()->getUrl());
      printf("Downloaded results from %s:\n",
          $batchJob->getDownloadUrl()->getUrl());

      if (count($mutateResults) === 0) {
        printf("  No results available.\n");
      } else {
        foreach ($mutateResults as $mutateResult) {
          $outcome =
              $mutateResult->getErrorList() === null ? 'SUCCESS' : 'FAILURE';
          printf("  Operation [%d] - %s\n", $mutateResult->getIndex(),
              $outcome);
        }
      }
    } else {
      printf("No results available for download.\n");
    }
  }

  /**
   * Builds objects of AdGroupCriterionOperation for creating biddable criteria
   * (as keywords) for ad groups with the specified ID. 10% of keywords are
   * created with some invalid characters to demonstrate how `BatchJobService`
   * returns information about such errors.
   *
   * @param string $adGroupId the ID of the ad group to add the keywords to
   * @return array an array of AdGroupCriterionOperation
   */
  private static function buildAdGroupCriterionOperations($adGroupId) {
    $adGroupCriteriaOperations = [];

    $suffix = uniqid();
    // Create AdGroupCriterionOperations to add keywords.
    for ($i = 0; $i < self::NUMBER_OF_KEYWORDS_TO_ADD; $i++) {
      // Create Keyword.
      $text = sprintf("mars%s-%d", $suffix, $i);

      // Make 10% of keywords invalid to demonstrate error handling.
      if ($i % 10 === 0) {
        $text = $text . '!!!';
      }
      $keyword = new Keyword();
      $keyword->setText($text);
      $keyword->setMatchType(KeywordMatchType::BROAD);

      // Create BiddableAdGroupCriterion.
      $biddableAdGroupCriterion = new BiddableAdGroupCriterion();
      $biddableAdGroupCriterion->setAdGroupId($adGroupId);
      $biddableAdGroupCriterion->setCriterion($keyword);

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

      // Add to list.
      $adGroupCriteriaOperations[] = $operation;
    }
    return $adGroupCriteriaOperations;
  }

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

AddKeywordsUsingIncrementalBatchJob::main();

Old

<?php
/**
 * This code sample illustrates how to perform multiple requests using the
 * BatchJobService using incremental uploads.
 *
 * 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 ADWORDS_UTIL_PATH . '/XmlDeserializer.php';
require_once ADWORDS_UTIL_VERSION_PATH . '/BatchJobUtils.php';

define('NUMBER_OF_KEYWORDS_TO_ADD', 100);
define('POLL_FREQUENCY_SECONDS', 30);
define('MAX_POLL_ATTEMPTS', 5);

$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 keywords to
 */
function AddKeywordsUsingIncrementalBatchJob(AdWordsUser $user, $adGroupId) {
  // Get the service, which loads the required classes.
  $batchJobService = $user->GetService('BatchJobService', ADWORDS_VERSION);

  // Create a BatchJob.
  $addOp = new BatchJobOperation();
  $addOp->operator = 'ADD';
  $addOp->operand = new BatchJob();
  $addOps[] = $addOp;

  $result = $batchJobService->mutate($addOps);
  $batchJob = $result->value[0];

  // Get the upload URL from the new job.
  $uploadUrl = $batchJob->uploadUrl->url;
  printf("Created BatchJob with ID %d, status '%s' and upload URL '%s'.\n",
      $batchJob->id, $batchJob->status, $uploadUrl);

  // Use BatchJobUtils to upload all operations.
  $batchJobUtils = new BatchJobUtils($uploadUrl);

  // Generate and upload the first set of operations.
  $adGroupCriterionOperations =
      buildAdGroupCriterionOperations($adGroupId);
  $batchJobUtils->UploadIncrementalBatchJobOperations(
      $adGroupCriterionOperations);
  printf("Uploaded %d operations for batch job with ID %d.\n",
      count($adGroupCriterionOperations), $batchJob->id);

  // Generate and upload the second set of operations.
  $adGroupCriterionOperations =
      buildAdGroupCriterionOperations($adGroupId);
  $batchJobUtils->UploadIncrementalBatchJobOperations(
      $adGroupCriterionOperations);
  printf("Uploaded %d operations for batch job with ID %d.\n",
      count($adGroupCriterionOperations), $batchJob->id);

  // Generate and upload the third and final set of operations.
  $adGroupCriterionOperations =
      buildAdGroupCriterionOperations($adGroupId);
  $batchJobUtils->UploadIncrementalBatchJobOperations(
      $adGroupCriterionOperations, true);
  printf("Uploaded %d operations for batch job with ID %d.\n",
      count($adGroupCriterionOperations), $batchJob->id);

  // Poll for completion of the batch job using an exponential back off.
  $pollAttempts = 0;
  $isPending = true;
  $wasCancelRequested = false;

  $selector = new Selector();
  $selector->fields = array('Id', 'Status', 'DownloadUrl', 'ProcessingErrors',
      'ProgressStats');
  $selector->predicates[] = new Predicate('Id', 'EQUALS', $batchJob->id);
  do {
    $sleepSeconds = POLL_FREQUENCY_SECONDS * pow(2, $pollAttempts);
    printf("Sleeping %d seconds...\n", $sleepSeconds);
    sleep($sleepSeconds);

    $batchJob = $batchJobService->get($selector)->entries[0];
    printf("Batch job ID %d has status '%s'.\n", $batchJob->id,
        $batchJob->status);

    $pollAttempts++;
    if ($batchJob->status !== 'ACTIVE' &&
        $batchJob->status !== 'AWAITING_FILE' &&
        $batchJob->status !== 'CANCELING') {
      $isPending = false;
    }

    // Optional: Cancel the job if it has not completed after polling
    // MAX_POLL_ATTEMPTS times.
    if ($isPending && !$wasCancelRequested
        && $pollAttempts == MAX_POLL_ATTEMPTS) {
      $batchJob->status = 'CANCELING';
      $batchJobSetOperation = new BatchJobOperation();
      $batchJobSetOperation->operand = $batchJob;
      $batchJobSetOperation->operator = 'SET';

      // Only request cancellation once per job.
      $wasCancelRequested = true;
      try {
        $operations[] = $batchJobSetOperation;
        $batchJob = $batchJobService->mutate($operations)->value[0];
        printf("Requested cancellation of batch job with ID %d.\n",
            $batchJob->id);
        // Reset the poll attempt counter to wait for cancellation.
        $pollAttempts = 0;
      } catch (Exception $e) {
        $errors = $e->detail->ApiExceptionFault->errors;
        if ($errors !== null
            && $errors->enc_value instanceof BatchJobError) {
          if ($errors->enc_value->reason === 'INVALID_STATE_CHANGE') {
            printf("Attempt to cancel batch job with ID %d was rejected because"
                . " the job already completed or was canceled.\n",
                $batchJob->id);
            // Reset the poll attempt counter to wait for cancellation.
            $pollAttempts = 0;
            continue;
          }
        }
        throw $e;
      }
    }
  } while ($isPending && $pollAttempts <= MAX_POLL_ATTEMPTS);

  if ($isPending) {
    throw new BatchJobException(
        sprintf("Job is still pending state after polling %d times.",
            MAX_POLL_ATTEMPTS));
  }

  if ($batchJob->processingErrors !== null) {
    $i = 0;
    foreach ($batchJob->processingErrors as $processingError) {
      printf(
          " Processing error [%d]: errorType=%s, trigger=%s, errorString=%s,"
              . " fieldPath=%s, reason=%s\n",
          $i++,
          $processingError->ApiErrorType,
          $processingError->trigger,
          $processingError->errorString,
          $processingError->fieldPath,
          $processingError->reason
      );
    }
  } else {
    printf("No processing errors found.\n");
  }

  if ($batchJob->downloadUrl !== null && $batchJob->downloadUrl->url !== null) {
    $xmlResponse =
        $batchJobUtils->DownloadBatchJobResults($batchJob->downloadUrl->url);
    printf("Downloaded results from %s:\n", $batchJob->downloadUrl->url);
    $deserializer = new XmlDeserializer(BatchJobUtils::$CLASS_MAP);
    $mutateResponse = $deserializer->ConvertXmlToObject($xmlResponse);
    if (empty($mutateResponse)) {
      printf("  No results available.\n");
    } else {
      foreach ($mutateResponse->rval as $mutateResult) {
        $outcome = $mutateResult->errorList === null ? 'SUCCESS' : 'FAILURE';
        printf("  Operation [%d] - %s\n", $mutateResult->index, $outcome);
      }
    }
  } else {
    printf("No results available for download.\n");
  }
}

/**
 * Builds objects of AdGroupCriterionOperation for creating biddable criteria
 * (as keywords) for an ad group with the specified ID. 10% of
 * keywords are created with some invalid characters to demonstrate how
 * BatchJobService returns information about such errors.
 *
 * @param string $adGroupId the ID of the ad group to add the keywords to
 * @return array an array of AdGroupCriterionOperation
 */
function buildAdGroupCriterionOperations($adGroupId) {
  $adGroupCriterionOperations = array();

  $suffix = uniqid();
  // Create AdGroupCriterionOperations to add keywords.
  for ($i = 0; $i < NUMBER_OF_KEYWORDS_TO_ADD; $i++) {
    // Create Keyword.
    $text = sprintf("mars%s-%d", $suffix, $i);

    // Make 10% of keywords invalid to demonstrate error handling.
    if ($i % 10 == 0) {
      $text = $text . '!!!';
    }
    $keyword = new Keyword();
    $keyword->text = $text;
    $keyword->matchType = 'BROAD';

    // Create BiddableAdGroupCriterion.
    $biddableAdGroupCriterion = new BiddableAdGroupCriterion();
    $biddableAdGroupCriterion->adGroupId = $adGroupId;
    $biddableAdGroupCriterion->criterion = $keyword;

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

    // Add to list.
    $adGroupCriterionOperations[] = $operation;
  }
  return $adGroupCriterionOperations;
}

// 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.
  AddKeywordsUsingIncrementalBatchJob($user, $adGroupId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Add a trial

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\CampaignManagement;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\Predicate;
use Google\AdsApi\AdWords\v201705\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\AdWords\v201705\cm\Trial;
use Google\AdsApi\AdWords\v201705\cm\TrialAsyncErrorService;
use Google\AdsApi\AdWords\v201705\cm\TrialOperation;
use Google\AdsApi\AdWords\v201705\cm\TrialService;
use Google\AdsApi\AdWords\v201705\cm\TrialStatus;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example shows how to create a trial and wait for it to complete.
 * See the Campaign Drafts and Experiments guide for more information:
 * https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments
 */
class AddTrial {

  const MAX_POLL_ATTEMPTS = 5;
  const POLL_FREQUENCY_SECONDS = 30;

  const DRAFT_ID = 'INSERT_DRAFT_ID_HERE';
  const BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $draftId, $baseCampaignId) {
    $trialService = $adWordsServices->get($session, TrialService::class);
    $trialAsynErrorService =
        $adWordsServices->get($session, TrialAsyncErrorService::class);

    // Create a trial.
    $trial = new Trial();
    $trial->setDraftId($draftId);
    $trial->setBaseCampaignId($baseCampaignId);
    $trial->setName('Test Trial #' . uniqid());
    $trial->setTrafficSplitPercent(50);

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

    // Create the trial on the server.
    $trial = $trialService->mutate($operations)->getValue()[0];

    $selector = new Selector();
    $selector->setFields(
        ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId']);
    $selector->setPredicates(
        [new Predicate('Id', PredicateOperator::IN, [$trial->getId()])]);

    // Since creating a trial is asynchronous, we have to poll it to wait for it
    // to finish.
    $pollAttempts = 0;
    $isPending = true;
    $trial = null;
    do {
      $sleepSeconds = self::POLL_FREQUENCY_SECONDS * pow(2, $pollAttempts);
      printf("Sleeping %d seconds...\n", $sleepSeconds);
      sleep($sleepSeconds);

      $trial = $trialService->get($selector)->getEntries()[0];
      printf("Trial ID %d has status '%s'.\n",
          $trial->getId(), $trial->getStatus());

      $pollAttempts++;
      $isPending = ($trial->getStatus() === TrialStatus::CREATING)
          ? true : false;
    } while ($isPending && $pollAttempts <= self::MAX_POLL_ATTEMPTS);

    if ($trial->getStatus() === TrialStatus::ACTIVE) {
      // The trial creation was successful.
      printf("Trial created with ID %d and trial campaign ID %d\n",
          $trial->getId(), $trial->getTrialCampaignId());
    } else if ($trial->getStatus() === TrialStatus::CREATION_FAILED) {
      // The trial creation failed, and errors can be fetched from the
      // TrialAsyncErrorService.
      $selector = new Selector();
      $selector->setFields(['TrialId', 'AsyncError']);
      $selector->setPredicates(
          [new Predicate('TrialId', PredicateOperator::IN, [$trial->getId()])]);

      $errors = $trialAsynErrorService->get($selector)->getEntries();

      if (count($errors) === 0) {
        printf("Could not retrieve errors for the trial with ID %d\n",
            $trial->getId());
      } else {
        printf("Could not create trial due to the following errors:\n");
        $i = 0;
        foreach ($errors as $error) {
          printf("Error #%d: %s\n", $i++, $error->getAsyncError());
        }
      }
    } else {
      // Most likely, the trial is still being created. You can continue
      // polling, but we have limited the number of attempts in the example.
      printf("Timed out waiting to create trial from draft with ID %d with base"
          . " campaign with ID %d\n", $draftId, $baseCampaignId);
    }
  }

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

AddTrial::main();

Old

<?php
/**
 * This example shows how to create a trial and wait for it to complete.
 * See the Campaign Drafts and Experiments guide for more information:
 * https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments
 *
 * 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.
define('MAX_POLL_ATTEMPTS', 5);
define('POLL_FREQUENCY_SECONDS', 30);

$draftId = 'INSERT_DRAFT_ID_HERE';
$baseCampaignId = 'INSERT_BASE_CAMPAIGN_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param int $draftId the ID of the draft used to create a trial
 * @param int $baseCampaignId the ID of the base campaign used to create
 *     a trial
 */
function AddTrialExample(AdWordsUser $user, $draftId, $baseCampaignId) {
  // Get the TrialService, which loads the required classes.
  $trialService = $user->GetService('TrialService', ADWORDS_VERSION);
  $trialAsynErrorService =
      $user->GetService('TrialAsyncErrorService', ADWORDS_VERSION);

  // Create a trial.
  $trial = new Trial();
  $trial->draftId = $draftId;
  $trial->baseCampaignId = $baseCampaignId;
  $trial->name = 'Test Trial #' . uniqid();
  $trial->trafficSplitPercent = 50;

  // Create an operation.
  $operation = new TrialOperation();
  $operation->operand = $trial;
  $operation->operator = 'ADD';
  $operations[] = $operation;

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

  $selector = new Selector();
  $selector->fields =
      array('Id', 'Status', 'BaseCampaignId', 'TrialCampaignId');
  $selector->predicates = new Predicate('Id', 'IN', array($trial->id));

  // Since creating a trial is asynchronous, we have to poll it to wait for it
  // to finish.
  $pollAttempts = 0;
  $isPending = true;
  $trial = null;
  do {
    $sleepSeconds = POLL_FREQUENCY_SECONDS * pow(2, $pollAttempts);
    printf("Sleeping %d seconds...\n", $sleepSeconds);
    sleep($sleepSeconds);

    $trial = $trialService->get($selector)->entries[0];
    printf("Trial ID %d has status '%s'.\n", $trial->id, $trial->status);

    $pollAttempts++;
    $isPending = ($trial->status === 'CREATING') ? true : false;
  } while ($isPending && $pollAttempts <= MAX_POLL_ATTEMPTS);

  if ($trial->status === 'ACTIVE') {
    // The trial creation was successful.
    printf("Trial created with ID %d and trial campaign ID %d\n", $trial->id,
        $trial->trialCampaignId);
  } else if ($trial->status === 'CREATION_FAILED') {
    // The trial creation failed, and errors can be fetched from the
    // TrialAsyncErrorService.
    $selector = new Selector();
    $selector->fields = array('TrialId', 'AsyncError');
    $selector->predicates = new Predicate('TrialId', 'IN', array($trial->id));

    $errors = $trialAsynErrorService->get($selector)->entries;

    if (count($errors) === 0) {
      printf("Could not retrieve errors for the trial with ID %d\n",
          $trial->id);
    } else {
      printf("Could not create trial due to the following errors:\n");
      $i = 0;
      foreach ($errors as $error) {
        printf("Error #%d: %s\n", $i++, $error->asyncError);
      }
    }
  } else {
    // Most likely, the trial is still being created. You can continue polling,
    // but we have limited the number of attempts in the example.
    printf("Timed out waiting to create trial from draft with ID %d with base "
        . "campaign with ID %d\n", $draftId, $baseCampaignId);
  }
}

// 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.
  AddTrialExample($user, $draftId, $baseCampaignId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Get all disapproved ads in 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\CampaignManagement;

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\AdGroupAdService;
use Google\AdsApi\AdWords\v201705\cm\ApprovalStatus;
use Google\AdsApi\AdWords\v201705\cm\OrderBy;
use Google\AdsApi\AdWords\v201705\cm\Paging;
use Google\AdsApi\AdWords\v201705\cm\Predicate;
use Google\AdsApi\AdWords\v201705\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201705\cm\PolicyApprovalStatus;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\AdWords\v201705\cm\SortOrder;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all disapproved ads in an ad group. To get ad groups, run
 * BasicOperation/GetAdGroups.php.
 */
class GetAllDisapprovedAds {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
  const PAGE_LIMIT = 500;

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

    // Create a selector to select all ads for the specified ad group.
    $selector = new Selector();
    $selector->setFields(['Id', 'PolicySummary']);
    $selector->setOrdering([new OrderBy('Id', SortOrder::ASCENDING)]);
    // Create the predicate to get only disapproved ads.
    $selector->setPredicates([
        new Predicate('AdGroupId', PredicateOperator::IN, [$adGroupId])]);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

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

      // Print out some information for each ad group ad.
      if ($page->getEntries() !== null) {
        $totalNumEntries = $page->getTotalNumEntries();
        foreach ($page->getEntries() as $adGroupAd) {
          $policySummary = $adGroupAd->getPolicySummary();
          if (PolicyApprovalStatus::DISAPPROVED
              !== $policySummary->getCombinedApprovalStatus()) {
            // Skip ad group ads that are not disapproved.
            continue;
          }

          $disapprovedAdsCount++;
          printf(
              "Ad with ID %d and type '%s' was disapproved with the following"
                  . " policy topic entries:\n",
              $adGroupAd->getAd()->getId(),
              $adGroupAd->getAd()->getType()
          );
          foreach ($policySummary->getPolicyTopicEntries()
              as $policyTopicEntry) {
            printf(
                "  topic id: %s, topic name: '%s'\n",
                $policyTopicEntry->getPolicyTopicId(),
                $policyTopicEntry->getPolicyTopicName()
            );
          }
        }
      }

      $selector->getPaging()->setStartIndex(
          $selector->getPaging()->getStartIndex() + self::PAGE_LIMIT);
    } while ($selector->getPaging()->getStartIndex() < $totalNumEntries);
    printf("%d disapproved ads were found.\n", $disapprovedAdsCount);
  }

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

GetAllDisapprovedAds::main();

Old

<?php
/**
 * This example gets all disapproved ads in an ad group. To get ad groups, run
 * BasicOperation/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';

// 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 parent ad group id of the ads to retrieve
 */
function GetAllDisapprovedAdsExample(AdWordsUser $user, $adGroupId) {
  // Get the service, which loads the required classes.
  $adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);

  // Create selector.
  $selector = new Selector();
  $selector->fields = array('Id', 'PolicySummary');
  $selector->ordering = array(new OrderBy('Id', 'ASCENDING'));

  // Create predicates.
  $selector->predicates[] = new Predicate('AdGroupId', 'IN', array($adGroupId));

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

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

    // Display results.
    if (isset($page->entries)) {
      foreach ($page->entries as $adGroupAd) {
        if ($adGroupAd->policySummary->combinedApprovalStatus
            !== 'DISAPPROVED') {
          // Skip ad group ads that are not disapproved.
          continue;
        }

        $disapprovedAdsCount++;
        printf(
            "Ad with ID %d, and type '%s' was disapproved with the "
                . "following policy topic entries:\n",
            $adGroupAd->ad->id,
            $adGroupAd->ad->AdType
        );
        foreach ($adGroupAd->policySummary->policyTopicEntries
            as $policyTopicEntry) {
          printf(
              "  topic id: %s, topic name: '%s'\n",
              $policyTopicEntry->policyTopicId,
              $policyTopicEntry->policyTopicName
          );
        }
      }
    }

    // Advance the paging index.
    $selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
  } while ($page->totalNumEntries > $selector->paging->startIndex);
  printf("%d disapproved ads were found.\n", $disapprovedAdsCount);
}

// 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.
  GetAllDisapprovedAdsExample($user, $adGroupId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Get all disapproved ads in an ad group using AWQL

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\CampaignManagement;

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\AdGroupAdService;
use Google\AdsApi\AdWords\v201705\cm\PolicyApprovalStatus;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all disapproved ads in an ad group with AWQL. To get ad
 * groups, run BasicOperation/GetAdGroups.php.
 */
class GetAllDisapprovedAdsWithAwql {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
  const PAGE_LIMIT = 500;

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

    // Create an AWQL query.
    $query = sprintf(
        'SELECT Id, PolicySummary WHERE AdGroupId = %d ORDER BY Id',
        $adGroupId
    );

    // Create paging controls.
    $totalNumEntries = 0;
    $offset = 0;
    $disapprovedAdsCount = 0;
    do {
      $pageQuery = sprintf('%s LIMIT %d,%d', $query, $offset, self::PAGE_LIMIT);

      // Make the query request.
      $page = $adGroupAdService->query($pageQuery);

      // Display results from the query.
      if ($page->getEntries() !== null) {
        $totalNumEntries = $page->getTotalNumEntries();
        foreach ($page->getEntries() as $adGroupAd) {
          $policySummary = $adGroupAd->getPolicySummary();
          if (PolicyApprovalStatus::DISAPPROVED
              !== $policySummary->getCombinedApprovalStatus()) {
            // Skip ad group ads that are not disapproved.
            continue;
          }

          $disapprovedAdsCount++;
          printf(
              "Ad with ID %d and type '%s' was disapproved with the following"
                  . " policy topic entries:\n",
              $adGroupAd->getAd()->getId(),
              $adGroupAd->getAd()->getType()
          );
          foreach ($policySummary->getPolicyTopicEntries()
              as $policyTopicEntry) {
            printf(
                "  topic id: %s, topic name: '%s'\n",
                $policyTopicEntry->getPolicyTopicId(),
                $policyTopicEntry->getPolicyTopicName()
            );
          }
        }
      }

      // Advance the paging offset.
      $offset += self::PAGE_LIMIT;
    } while ($offset < $totalNumEntries);
    printf("%d disapproved ads were found.\n", $disapprovedAdsCount);
  }

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

GetAllDisapprovedAdsWithAwql::main();

Old

<?php
/**
 * This example gets all disapproved ads in an ad group with AWQL. To get ad
 * groups, run BasicOperation/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';

// 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 parent ad group id of the ads to retrieve
 */
function GetAllDisapprovedAdsWithAwqlExample(AdWordsUser $user, $adGroupId) {
  // Get the service, which loads the required classes.
  $adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);

  // Create a query.
  $query = sprintf('SELECT Id, PolicySummary WHERE AdGroupId = %d ORDER BY Id',
      $adGroupId);

  // Create paging controls.
  $offset = 0;
  $disapprovedAdsCount = 0;
  do {
    $pageQuery = sprintf('%s LIMIT %d,%d', $query, $offset,
        AdWordsConstants::RECOMMENDED_PAGE_SIZE);

    // Make the query request.
    $page = $adGroupAdService->query($pageQuery);

    // Display results.
    if (isset($page->entries)) {
      foreach ($page->entries as $adGroupAd) {
        if ($adGroupAd->policySummary->combinedApprovalStatus
            !== 'DISAPPROVED') {
          // Skip ad group ads that are not disapproved.
          continue;
        }

        $disapprovedAdsCount++;
        printf(
            "Ad with ID %d, and type '%s' was disapproved with the "
                . "following policy topic entries:\n",
            $adGroupAd->ad->id,
            $adGroupAd->ad->AdType
        );
        foreach ($adGroupAd->policySummary->policyTopicEntries
            as $policyTopicEntry) {
          printf(
              "  topic id: %s, topic name: '%s'\n",
              $policyTopicEntry->policyTopicId,
              $policyTopicEntry->policyTopicName
          );
        }
      }
    }

    // Advance the paging offset.
    $offset += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
  } while ($page->totalNumEntries > $offset);
  printf("%d disapproved ads were found.\n", $disapprovedAdsCount);
}

// 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.
  GetAllDisapprovedAdsWithAwqlExample($user, $adGroupId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Get all campaigns with a specific label

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\CampaignManagement;

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\CampaignService;
use Google\AdsApi\AdWords\v201705\cm\OrderBy;
use Google\AdsApi\AdWords\v201705\cm\Paging;
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\SortOrder;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all campaigns with a specific label. To add a label to
 * campaigns, run AddCampaignLabels.php.
 */
class GetCampaignsByLabel {

  const LABEL_ID = 'INSERT_LABEL_ID_HERE';
  const PAGE_LIMIT = 500;

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

    // Create a selector to select all campaigns by the specified label.
    $selector = new Selector();
    $selector->setFields(['Id', 'Name', 'Labels']);
    // Labels filtering is performed by ID. You can use CONTAINS_ANY to select
    // campaigns with any of the label IDs, CONTAINS_ALL to select campaigns
    // with all of the label IDs, or CONTAINS_NONE to select campaigns with none
    // of the label IDs.
    $selector->setPredicates([
        new Predicate('Labels', PredicateOperator::CONTAINS_ANY, [$labelId])
    ]);
    $selector->setOrdering([new OrderBy('Name', SortOrder::ASCENDING)]);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

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

      // Print out some information for each campaign.
      if ($page->getEntries() !== null) {
        $totalNumEntries = $page->getTotalNumEntries();
        foreach ($page->getEntries() as $campaign) {
          printf(
              "Campaign with name '%s' and ID %d and labels '%s'"
                  . " was found.\n",
              $campaign->getName(),
              $campaign->getId(),
              implode(', ', array_map(
                  function($label) {
                    return sprintf('%d/%s', $label->getId(), $label->getName());
                  },
                  $campaign->getLabels()
              ))
          );
        }
      }

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

GetCampaignsByLabel::main();

Old

<?php
/**
 * This example gets all campaigns with a specific label. To add a label to
 * campaigns, run AddCampaignLabels.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';

$labelId = 'INSERT_LABEL_ID_HERE';

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

  // Create selector.
  $selector = new Selector();
  $selector->fields = array('Id', 'Name', 'Labels');
  // Labels filtering is performed by ID. You can use containsAny to select
  // campaigns with any of the label IDs, containsAll to select campaigns with
  // all of the label IDs, or containsNone to select campaigns with none of the
  // label IDs.
  $selector->predicates[] = new Predicate('Labels', 'CONTAINS_ANY',
      array($labelId));
  $selector->ordering[] = new OrderBy('Name', 'ASCENDING');

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

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

    // Display results.
    if (isset($page->entries)) {
      foreach ($page->entries as $campaign) {
        printf("Campaign with name '%s' and ID '%d' and labels '%s'" .
            " was found.\n", $campaign->name, $campaign->id,
            implode(', ',
                array_map(function($label) {
                  return sprintf('%d/%s', $label->id, $label->name);
                }, $campaign->labels)));
      }
    } else {
      print "No campaigns 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.
  GetCampaignsByLabelExample($user, $labelId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Graduate a trial

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\CampaignManagement;

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\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\Money;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\Trial;
use Google\AdsApi\AdWords\v201705\cm\TrialOperation;
use Google\AdsApi\AdWords\v201705\cm\TrialService;
use Google\AdsApi\AdWords\v201705\cm\TrialStatus;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example shows how to graduate a trial.
 * See the Campaign Drafts and Experiments guide for more information:
 * https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments
 */
class GraduateTrial {

  const TRIAL_ID = 'INSERT_TRIAL_ID_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $trialId) {
    $trialService = $adWordsServices->get($session, TrialService::class);
    $budgetService =
        $adWordsServices->get($session, BudgetService::class);

    // To graduate a trial, you must specify a different budget from the base
    // campaign. The base campaign (in order to have had a trial based on it)
    // must have a non-shared budget, so it cannot be shared with the new
    // independent campaign created by graduation.
    $budget = new Budget();
    $budget->setName('Trial Budget #' . uniqid());
    $money = new Money();
    $money->setMicroAmount(50000000);
    $budget->setAmount($money);
    $budget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD);

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

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

    // Create a trial.
    $trial = new Trial();
    $trial->setId($trialId);
    $trial->setBudgetId($budget->getBudgetId());
    $trial->setStatus(TrialStatus::GRADUATED);

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

    // Update the trial on the server.
    $trial = $trialService->mutate($operations)->getValue()[0];

    // Graduation is a synchronous operation, so the campaign is already ready.
    // If you promote instead, make sure to see the polling scheme demonstrated
    // in AddTrial.php to wait for the asynchronous operation to finish.
    printf(
        "Trial with ID %d graduated. Campaign with ID %d was given a new budget"
            . " ID %d and is no longer dependent on this trial.\n",
        $trial->getId(),
        $trial->getTrialCampaignId(),
        $budget->getBudgetId()
    );
  }

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

GraduateTrial::main();

Old

<?php
/**
 * This example shows how to graduate a trial.
 * See the Campaign Drafts and Experiments guide for more information:
 * https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments
 *
 * 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.
$trialId = 'INSERT_TRIAL_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param int $trialId the ID of the trial to graduate
 */
function GraduateTrialExample(AdWordsUser $user, $trialId) {
  // Get the TrialService, which loads the required classes.
  $trialService = $user->GetService('TrialService', ADWORDS_VERSION);
  $budgetService = $user->GetService('BudgetService', ADWORDS_VERSION);

  // To graduate a trial, you must specify a different budget from the base
  // campaign. The base campaign (in order to have had a trial based on it)
  // must have a non-shared budget, so it cannot be shared with the new
  // independent campaign created by graduation.
  $budget = new Budget();
  $budget->name = 'Trial Budget #' . uniqid();
  $budget->amount = new Money(50000000);
  $budget->deliveryMethod = 'STANDARD';

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

  $budget = $budgetService->mutate($operations)->value[0];

  // Create a trial.
  $trial = new Trial();
  $trial->id = $trialId;
  $trial->budgetId = $budget->budgetId;
  $trial->status = 'GRADUATED';

  // Create an operation.
  $operations = array();
  $operation = new TrialOperation();
  $operation->operand = $trial;
  $operation->operator = 'SET';
  $operations[] = $operation;

  // Make the mutate request.
  $trial = $trialService->mutate($operations)->value[0];

  // Graduation is a synchronous operation, so the campaign is already ready.
  // If you promote instead, make sure to see the polling scheme demonstrated
  // in AddTrial.php to wait for the asynchronous operation to finish.
  printf(
      "Trial with ID %d graduated. Campaign with ID %d was given a new budget "
          . "ID %d and is no longer dependent on this trial.\n",
      $trial->id,
      $trial->trialCampaignId,
      $budget->budgetId
  );
}

// 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.
  GraduateTrialExample($user, $trialId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Set ad parameters

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\CampaignManagement;

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\AdParam;
use Google\AdsApi\AdWords\v201705\cm\AdParamOperation;
use Google\AdsApi\AdWords\v201705\cm\AdParamService;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example sets ad parameters for a keyword. To get keywords, run
 * BasicOperations/GetKeywords.php.
 */
class SetAdParameters {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
  const KEYWORD_ID = 'INSERT_KEYWORD_ID_HERE';

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

    // Create ad parameters.
    $adParam1 = new AdParam($adGroupId, $keywordId, '100', 1);
    $adParam2 = new AdParam($adGroupId, $keywordId, '$40', 2);

    $adParamOperation1s = [];

    $adParamOperation1 = new AdParamOperation();
    $adParamOperation1->setOperand($adParam1);
    $adParamOperation1->setOperator(Operator::SET);
    $operations[] = $adParamOperation1;

    $adParamOperation2 = new AdParamOperation();
    $adParamOperation2->setOperand($adParam2);
    $adParamOperation2->setOperator(Operator::SET);
    $operations[] = $adParamOperation2;

    // Add ad params on the server.
    $adParams = $adParamService->mutate($operations);

    // Print out some information about added ad parameters.
    foreach ($adParams as $adParam) {
      printf(
          "Ad parameter with insertion text '%s' and parameter index %d "
              . "was set.\n",
          $adParam->getInsertionText(),
          $adParam->getParamIndex()
      );
    }
  }

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

SetAdParameters::main();

Old

<?php
/**
 * This example sets ad parameters for a keyword. To get keywords, run
 * BasicOperaitons/GetKeywords.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';

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

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the id of the parent ad group of the keyword
 * @param string $keywordId the id of the keyword to set ad parameters for
 */
function SetAdParametersExample(AdWordsUser $user, $adGroupId, $keywordId) {
  // Get the service, which loads the required classes.
  $adParamService = $user->GetService('AdParamService', ADWORDS_VERSION);

  // Create ad parameters.
  $adParam1 = new AdParam($adGroupId, $keywordId, '100', 1);
  $adParam2 = new AdParam($adGroupId, $keywordId, '$40', 2);

  // Create operations.
  $operations = array();

  $adParamOperation1 = new AdParamOperation();
  $adParamOperation1->operand = $adParam1;
  $adParamOperation1->operator = 'SET';
  $operations[] = $adParamOperation1;

  $adParamOperation2 = new AdParamOperation();
  $adParamOperation2->operand = $adParam2;
  $adParamOperation2->operator = 'SET';
  $operations[] = $adParamOperation2;

  // Make the mutate request.
  $adParams = $adParamService->mutate($operations);

  // Display results.
  foreach ($adParams as $adParam) {
    printf("Ad parameter with insertion text '%s' and parameter index '%s' "
        . "was set.\n", $adParam->insertionText, $adParam->paramIndex);
  }
}

// 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.
  SetAdParametersExample($user, $adGroupId, $keywordId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Set 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\CampaignManagement;

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\CampaignCriterion;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\Platform;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example sets a bid modifier on a campaign.
 */
class SetBidModifier {

  const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
  // Bid modifiers are float number, not percentages, e.g., 1.5 means 50% more
  // bidding.
  const BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $campaignId, $bidModifier) {
    $campaignCriterionService =
        $adWordsServices->get($session, CampaignCriterionService::class);

    // Create a mobile platform. The ID can be found in the documentation.
    // https://developers.google.com/adwords/api/docs/appendix/platforms
    $mobile = new Platform();
    $mobile->setId(30001); // HighEndMobile = 30001

    // Create a criterion with modified bid.
    $criterion = new CampaignCriterion();
    $criterion->setCampaignId($campaignId);
    $criterion->setCriterion($mobile);
    $criterion->setBidModifier($bidModifier);

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

    // Update campaign criteria on the server.
    $results = $campaignCriterionService->mutate($operations);

    // Print out some information about the updated campaign criterion.
    foreach ($results->getValue() as $campaignCriterion) {
      printf(
          "Campaign criterion with campaign ID %d, criterion ID %d, "
              . "and type '%s' was modified with bid %.2f.\n",
          $campaignCriterion->getCampaignId(),
          $campaignCriterion->getCriterion()->getId(),
          $campaignCriterion->getCriterion()->getType(),
          $campaignCriterion->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::CAMPAIGN_ID),
        floatval(self::BID_MODIFIER));
  }
}

SetBidModifier::main();

Old

<?php
/**
 * This example sets a Bid Modifier on 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.
$campaignId = 'INSERT_CAMPAIGN_ID_HERE';
$bidModifier = 1.5;

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $campaignId the id of the campaign to modify
 * @param float $bidModifier the multiplier to set on the campaign
 */
function SetBidModifierExample(AdWordsUser $user, $campaignId, $bidModifier) {
  // Get the CampaignCriterionService, also loads classes
  $campaignCriterionService =
      $user->GetService('CampaignCriterionService', ADWORDS_VERSION);

  // Create Mobile Platform. The ID can be found in the documentation.
  // https://developers.google.com/adwords/api/docs/appendix/platforms
  $mobile = new Platform();
  $mobile->id = 30001; // HighEndMobile = 30001

  // Create criterion with modified bid.
  $criterion = new CampaignCriterion();
  $criterion->campaignId = $campaignId;
  $criterion->criterion = $mobile;
  $criterion->bidModifier = $bidModifier;

  // Create SET operation.
  $operation = new CampaignCriterionOperation();
  $operation->operator = 'SET';
  $operation->operand = $criterion;

  // Update campaign criteria.
  $results = $campaignCriterionService->mutate(array($operation));

  // Display campaign criteria.
  if (count($results->value)) {
    foreach ($results->value as $campaignCriterion) {
      printf(
          "Campaign criterion with campaign ID '%s', criterion ID '%s', "
          . "and type '%s' was modified with bid %.2f.\n",
          $campaignCriterion->campaignId,
          $campaignCriterion->criterion->id,
          $campaignCriterion->criterion->type,
          $campaignCriterion->bidModifier);
    }

    return true;
  }
  print 'No campaign criterias were modified.';
}

// 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.
  SetBidModifierExample($user, $campaignId, $bidModifier);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Validate text 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\CampaignManagement;

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\ApiException;
use Google\AdsApi\AdWords\v201705\cm\ExpandedTextAd;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example validates a text ad without creating it using the validateOnly
 * mode, which can be useful when checking for policy violations.
 */
class ValidateTextAd {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

    $operations = [];
    // Create invalid expanded text ad.
    $expandedTextAd = new ExpandedTextAd();
    $expandedTextAd->setHeadlinePart1('Luxury Cruise to Mars !!!');
    $expandedTextAd->setHeadlinePart2('Visit the Red Planet in style.');
    $expandedTextAd->setDescription(
        'Low-gravity fun for all astronauts in orbit.');
    $expandedTextAd->setFinalUrls(['http://www.example.com']);

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

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

    try {
      $result = $adGroupAdService->mutate($operations);
      printf("The expanded text ad is valid.\n");
    } catch (ApiException $e) {
      $errors = $e->getErrors();
      if (count($errors) > 0) {
        printf("The expanded text ad is invalid for the following reasons:\n");
        foreach ($errors as $error) {
          printf("  %s @ %s\n", $error->getErrorString(),
              $error->getFieldPath());
        }
      }
    }
  }

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

ValidateTextAd::main();

Old

<?php
/**
 * This example validates a text ad without creating it, which can be useful
 * when checking for policy violations.
 *
 * 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 . '/ErrorUtils.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 hypothetically add the
 *     expanded text ad to
 */
function ValidateTextAdExample(AdWordsUser $user, $adGroupId) {
  // Get the service, which loads the required classes. Passing true for the
  // parameter $validateOnly will ensure that ads aren't created.
  $adGroupAdValidationService =
      $user->GetService('AdGroupAdService', ADWORDS_VERSION, null, null, true);

  // Create invalid expanded text ad.
  $expandedTextAd = new ExpandedTextAd();
  $expandedTextAd->headlinePart1 = 'Luxury Cruise to Mars';
  $expandedTextAd->headlinePart2 = 'Visit the Red Planet in style.';
  $expandedTextAd->description = 'Low-gravity fun for all astronauts in orbit.';
  $expandedTextAd->finalUrls = array('http://www.example.com');

  // 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 = array($operation);

  // Make the mutate request.
  try {
    $result = $adGroupAdValidationService->mutate($operations);
    printf("The expanded text ad is valid.\n");
  } catch (SoapFault $e) {
    $errors = ErrorUtils::GetApiErrors($e);
    if (sizeof($errors) > 0) {
      printf("The expanded text ad is invalid for the following reasons:\n");
      foreach ($errors as $error) {
        printf("  %s @ %s\n", $error->errorString, $error->fieldPath);
      }
    } else {
      // Not an API error, so throw it up a level.
      throw $e;
    }
  }
}

// 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.
  ValidateTextAdExample($user, $adGroupId);
} 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.