Basic Operations Samples

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

Add ad groups to a campaign

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

namespace Google\AdsApi\Examples\AdWords\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdGroup;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdRotationMode;
use Google\AdsApi\AdWords\v201806\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201806\cm\AdGroupService;
use Google\AdsApi\AdWords\v201806\cm\AdGroupStatus;
use Google\AdsApi\AdWords\v201806\cm\AdRotationMode;
use Google\AdsApi\AdWords\v201806\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201806\cm\CpcBid;
use Google\AdsApi\AdWords\v201806\cm\CriterionTypeGroup;
use Google\AdsApi\AdWords\v201806\cm\Money;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\AdWords\v201806\cm\TargetingSetting;
use Google\AdsApi\AdWords\v201806\cm\TargetingSettingDetail;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds ad groups to a campaign. To get campaigns, run
 * GetCampaigns.php.
 */
class AddAdGroups
{

    const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';

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

        $operations = [];

        // Create an ad group with required and optional settings.
        $adGroup = new AdGroup();
        $adGroup->setCampaignId($campaignId);
        $adGroup->setName('Earth to Mars Cruise #' . uniqid());

        // Set bids (required).
        $bid = new CpcBid();
        $money = new Money();
        $money->setMicroAmount(1000000);
        $bid->setBid($money);
        $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
        $biddingStrategyConfiguration->setBids([$bid]);
        $adGroup->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

        // Set additional settings (optional).
        $adGroup->setStatus(AdGroupStatus::ENABLED);

        // Targeting restriction settings. Depending on the criterionTypeGroup
        // value, most TargetingSettingDetail only affect Display campaigns.
        // However, the USER_INTEREST_AND_LIST value works for RLSA campaigns -
        // Search campaigns targeting using a remarketing list.
        $targetingSetting = new TargetingSetting();
        $details = [];
        // Restricting to serve ads that match your ad group placements.
        // This is equivalent to choosing "Target and bid" in the UI.
        $details[] = new TargetingSettingDetail(CriterionTypeGroup::PLACEMENT, false);
        // Using your ad group verticals only for bidding. This is equivalent
        // to choosing "Bid only" in the UI.
        $details[] = new TargetingSettingDetail(CriterionTypeGroup::VERTICAL, true);
        $targetingSetting->setDetails($details);
        $adGroup->setSettings([$targetingSetting]);

        // Set the rotation mode.
        $rotationMode = new AdGroupAdRotationMode(AdRotationMode::OPTIMIZE);
        $adGroup->setAdGroupAdRotationMode($rotationMode);

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

        // Create an ad group with required settings and specified status.
        $adGroup = new AdGroup();
        $adGroup->setCampaignId($campaignId);
        $adGroup->setName('Earth to Venus Cruise #' . uniqid());
        $adGroup->setStatus(AdGroupStatus::ENABLED);

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

        // Create the ad groups on the server and print out some information for
        // each created ad group.
        $result = $adGroupService->mutate($operations);
        foreach ($result->getValue() as $adGroup) {
            printf(
                "Ad group with name '%s' and ID %d was added.\n",
                $adGroup->getName(),
                $adGroup->getId()
            );
        }
    }

    public static function main()
    {
        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct an API session configured from a properties file and the
        // OAuth2 credentials above.
        $session = (new AdWordsSessionBuilder())->fromFile()->withOAuth2Credential($oAuth2Credential)->build();
        self::runExample(
            new AdWordsServices(),
            $session,
            intval(self::CAMPAIGN_ID)
        );
    }
}

AddAdGroups::main();

Add campaigns

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201806\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201806\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201806\cm\Budget;
use Google\AdsApi\AdWords\v201806\cm\BudgetBudgetDeliveryMethod;
use Google\AdsApi\AdWords\v201806\cm\BudgetOperation;
use Google\AdsApi\AdWords\v201806\cm\BudgetService;
use Google\AdsApi\AdWords\v201806\cm\Campaign;
use Google\AdsApi\AdWords\v201806\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201806\cm\CampaignService;
use Google\AdsApi\AdWords\v201806\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201806\cm\FrequencyCap;
use Google\AdsApi\AdWords\v201806\cm\GeoTargetTypeSetting;
use Google\AdsApi\AdWords\v201806\cm\GeoTargetTypeSettingNegativeGeoTargetType;
use Google\AdsApi\AdWords\v201806\cm\GeoTargetTypeSettingPositiveGeoTargetType;
use Google\AdsApi\AdWords\v201806\cm\Level;
use Google\AdsApi\AdWords\v201806\cm\ManualCpcBiddingScheme;
use Google\AdsApi\AdWords\v201806\cm\Money;
use Google\AdsApi\AdWords\v201806\cm\NetworkSetting;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\AdWords\v201806\cm\TimeUnit;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds campaigns.
 */
class AddCampaigns
{

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

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

        $operations = [];

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

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

        $campaignService = $adWordsServices->get($session, CampaignService::class);

        $operations = [];

        // Create a campaign with required and optional settings.
        $campaign = new Campaign();
        $campaign->setName('Interplanetary Cruise #' . uniqid());
        $campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH);

        // Set shared budget (required).
        $campaign->setBudget(new Budget());
        $campaign->getBudget()->setBudgetId($budget->getBudgetId());

        // Set bidding strategy (required).
        $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
        $biddingStrategyConfiguration->setBiddingStrategyType(
            BiddingStrategyType::MANUAL_CPC
        );

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

        $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

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

        // Set additional settings (optional).
        // 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->setStartDate(date('Ymd', strtotime('+1 day')));
        $campaign->setEndDate(date('Ymd', strtotime('+1 month')));

        // Set frequency cap (optional).
        $frequencyCap = new FrequencyCap();
        $frequencyCap->setImpressions(5);
        $frequencyCap->setTimeUnit(TimeUnit::DAY);
        $frequencyCap->setLevel(Level::ADGROUP);
        $campaign->setFrequencyCap($frequencyCap);

        // Set advanced location targeting settings (optional).
        $geoTargetTypeSetting = new GeoTargetTypeSetting();
        $geoTargetTypeSetting->setPositiveGeoTargetType(
            GeoTargetTypeSettingPositiveGeoTargetType::DONT_CARE
        );
        $geoTargetTypeSetting->setNegativeGeoTargetType(
            GeoTargetTypeSettingNegativeGeoTargetType::DONT_CARE
        );
        $campaign->setSettings([$geoTargetTypeSetting]);

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

        // Create a campaign with only required settings.
        $campaign = new Campaign();
        $campaign->setName('Interplanetary Cruise #' . uniqid());
        $campaign->setAdvertisingChannelType(AdvertisingChannelType::DISPLAY);

        // Set shared budget (required).
        $campaign->setBudget(new Budget());
        $campaign->getBudget()->setBudgetId($budget->getBudgetId());

        // Set bidding strategy (required).
        $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
        $biddingStrategyConfiguration->setBiddingStrategyType(
            BiddingStrategyType::MANUAL_CPC
        );
        $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

        $campaign->setStatus(CampaignStatus::PAUSED);

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

        // Create the campaigns on the server and print out some information for
        // each created campaign.
        $result = $campaignService->mutate($operations);
        foreach ($result->getValue() as $campaign) {
            printf(
                "Campaign with name '%s' and ID %d was added.\n",
                $campaign->getName(),
                $campaign->getId()
            );
        }
    }

    public static function main()
    {
        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct an API session configured from a properties file and the
        // OAuth2 credentials above.
        $session = (new AdWordsSessionBuilder())->fromFile()->withOAuth2Credential($oAuth2Credential)->build();
        self::runExample(new AdWordsServices(), $session);
    }
}

AddCampaigns::main();

Add expanded text ads to an ad group

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

namespace Google\AdsApi\Examples\AdWords\v201806\BasicOperations;

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

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

/**
 * This example adds an expanded text ad to an ad group. To get ad groups,
 * run GetAdGroups.php.
 */
class AddExpandedTextAds
{

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

        $operations = [];
        // Create an expanded text ad.
        $expandedTextAd = new ExpandedTextAd();
        $expandedTextAd->setHeadlinePart1('Cruise to Mars #' . uniqid());
        $expandedTextAd->setHeadlinePart2('Best Space Cruise Line');
        $expandedTextAd->setDescription('Buy your tickets now!');
        $expandedTextAd->setFinalUrls(['http://www.example.com']);
        $expandedTextAd->setPath1('all-inclusive');
        $expandedTextAd->setPath2('deals');

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

        // Optional: Set additional settings.
        $adGroupAd->setStatus(AdGroupAdStatus::PAUSED);

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

        // Create another expanded text ad.
        $expandedTextAd = new ExpandedTextAd();
        $expandedTextAd->setHeadlinePart1('Cruise to Venus #' . uniqid());
        $expandedTextAd->setHeadlinePart2('Best Space Cruise Line');
        $expandedTextAd->setDescription('Buy your tickets now!');
        $expandedTextAd->setFinalUrls(['http://www.example.com']);

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

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

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

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


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

AddExpandedTextAds::main();

Add keywords to an ad group

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

namespace Google\AdsApi\Examples\AdWords\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201806\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201806\cm\BiddableAdGroupCriterion;
use Google\AdsApi\AdWords\v201806\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201806\cm\CpcBid;
use Google\AdsApi\AdWords\v201806\cm\Keyword;
use Google\AdsApi\AdWords\v201806\cm\KeywordMatchType;
use Google\AdsApi\AdWords\v201806\cm\Money;
use Google\AdsApi\AdWords\v201806\cm\NegativeAdGroupCriterion;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\AdWords\v201806\cm\UrlList;
use Google\AdsApi\AdWords\v201806\cm\UserStatus;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds keywords to an ad group. To get ad groups run
 * GetAdGroups.php.
 */
class AddKeywords
{

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

        $operations = [];

        // Create the first keyword criterion.
        $keyword = new Keyword();
        $keyword->setText('mars cruise');
        $keyword->setMatchType(KeywordMatchType::BROAD);

        // Create biddable ad group criterion.
        $adGroupCriterion = new BiddableAdGroupCriterion();
        $adGroupCriterion->setAdGroupId($adGroupId);
        $adGroupCriterion->setCriterion($keyword);

        // Set additional settings (optional).
        $adGroupCriterion->setUserStatus(UserStatus::PAUSED);
        $adGroupCriterion->setFinalUrls(
            new UrlList(['http://www.example.com/mars'])
        );

        // Set bids (optional).
        $bid = new CpcBid();
        $money = new Money();
        $money->setMicroAmount(500000);
        $bid->setBid($money);
        $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
        $biddingStrategyConfiguration->setBids([$bid]);
        $adGroupCriterion->setBiddingStrategyConfiguration(
            $biddingStrategyConfiguration
        );

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

        // Create the second keyword criterion.
        $keyword = new Keyword();
        $keyword->setText('space hotel');
        $keyword->setMatchType(KeywordMatchType::EXACT);

        // Create negative ad group criterion.
        $negativeAdGroupCriterion = new NegativeAdGroupCriterion();
        $negativeAdGroupCriterion->setAdGroupId($adGroupId);
        $negativeAdGroupCriterion->setCriterion($keyword);

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

        // Create the ad group criteria on the server and print out some information
        // for each created ad group criterion.
        $result = $adGroupCriterionService->mutate($operations);
        foreach ($result->getValue() as $adGroupCriterion) {
            printf(
                "Keyword with text '%s', match type '%s', and ID %d was added.\n",
                $adGroupCriterion->getCriterion()->getText(),
                $adGroupCriterion->getCriterion()->getMatchType(),
                $adGroupCriterion->getCriterion()->getId()
            );
        }
    }

    public static function main()
    {
        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct an API session configured from a properties file and the
        // OAuth2 credentials above.
        $session = (new AdWordsSessionBuilder())->fromFile()->withOAuth2Credential($oAuth2Credential)->build();
        self::runExample(
            new AdWordsServices(),
            $session,
            intval(self::AD_GROUP_ID)
        );
    }
}

AddKeywords::main();

Add a responsive search ad to an ad group

<?php
/**
 * Copyright 2018 Google LLC
 *
 * 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\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201806\cm\AssetLink;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\AdWords\v201806\cm\ResponsiveSearchAd;
use Google\AdsApi\AdWords\v201806\cm\ServedAssetFieldType;
use Google\AdsApi\AdWords\v201806\cm\TextAsset;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a responsive search ad to a given ad group. To get ad
 * groups, run GetAdGroups.php.
 */
class AddResponsiveSearchAd
{

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

        // Create a responsive search ad.
        $responsiveSearchAd = new ResponsiveSearchAd();
        $responsiveSearchAd->setFinalUrls(['http://www.example.com/cruise']);
        $responsiveSearchAd->setPath1('all-inclusive');
        $responsiveSearchAd->setPath2('deals');

        // Create text assets for headlines.
        $headline1 = new TextAsset();
        $headline1->setAssetText('Cruise to Mars #' . uniqid());
        $headline2 = new TextAsset();
        $headline2->setAssetText('Best Space Cruise Line');
        $headline3 = new TextAsset();
        $headline3->setAssetText('Experience the Stars');
        $responsiveSearchAd->setHeadlines(
            [
                // Set a pinning to always choose this asset for HEADLINE_1.
                // Pinning is optional; if no pinning is set, then headlines
                // and descriptions will be rotated and the ones that perform
                // best will be used more often.
                new AssetLink($headline1, ServedAssetFieldType::HEADLINE_1),
                new AssetLink($headline2),
                new AssetLink($headline3)
            ]
        );

        // Create text assets for descriptions.
        $description1 = new TextAsset();
        $description1->setAssetText('Buy your tickets now');
        $description2 = new TextAsset();
        $description2->setAssetText('Visit the Red Planet');
        $responsiveSearchAd->setDescriptions(
            [new AssetLink($description1), new AssetLink($description2)]
        );

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

        // Optional: Set additional settings.
        $adGroupAd->setStatus(AdGroupAdStatus::PAUSED);

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

        // Add the responsive search ad on the server.
        $result = $adGroupAdService->mutate([$operation]);

        // Print out some information for the created ad.
        /** @var AdGroupAd $adGroupAd */
        foreach ($result->getValue() as $adGroupAd) {
            /** @var ResponsiveSearchAd $ad */
            $ad = $adGroupAd->getAd();
            printf(
                'New responsive search ad with ID %d was added.%s',
                $ad->getId(),
                PHP_EOL
            );
            print 'Headlines:' . PHP_EOL;
            foreach ($ad->getHeadlines() as $headline) {
                /** @var TextAsset $textAsset */
                $textAsset = $headline->getAsset();
                $pinnedField = $headline->getPinnedField();
                printf('    %s%s', $textAsset->getAssetText(), PHP_EOL);
                if (!is_null($pinnedField)) {
                    printf('      (pinned to %s)%s', $pinnedField, PHP_EOL);
                }
            }
            print 'Descriptions:' . PHP_EOL;
            foreach ($ad->getDescriptions() as $description) {
                /** @var TextAsset $textAsset */
                $textAsset = $description->getAsset();
                $pinnedField = $description->getPinnedField();
                printf('    %s%s', $textAsset->getAssetText(), PHP_EOL);
                if (!is_null($pinnedField)) {
                    printf('      (pinned to %s)%s', $pinnedField, PHP_EOL);
                }
            }
        }
        if (empty($result->getValue())) {
            print 'No ads were added.';
        }
    }

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

AddResponsiveSearchAd::main();

Get the ad groups of a campaign

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

namespace Google\AdsApi\Examples\AdWords\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdGroupService;
use Google\AdsApi\AdWords\v201806\cm\OrderBy;
use Google\AdsApi\AdWords\v201806\cm\Paging;
use Google\AdsApi\AdWords\v201806\cm\Predicate;
use Google\AdsApi\AdWords\v201806\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201806\cm\Selector;
use Google\AdsApi\AdWords\v201806\cm\SortOrder;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all ad groups in a campaign. To get campaigns, run
 * GetCampaigns.php.
 */
class GetAdGroups
{

    const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
    const PAGE_LIMIT = 500;

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

        // Create a selector to select all ad groups for the specified campaign.
        $selector = new Selector();
        $selector->setFields(['Id', 'Name']);
        $selector->setOrdering([new OrderBy('Name', SortOrder::ASCENDING)]);
        $selector->setPredicates(
            [new Predicate('CampaignId', PredicateOperator::IN, [$campaignId])]
        );
        $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

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

            // Print out some information for each ad group.
            if ($page->getEntries() !== null) {
                $totalNumEntries = $page->getTotalNumEntries();
                foreach ($page->getEntries() as $adGroup) {
                    printf(
                        "Ad group with ID %d and name '%s' was found.\n",
                        $adGroup->getId(),
                        $adGroup->getName()
                    );
                }
            }

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

GetAdGroups::main();

Get all campaigns

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

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

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

/**
 * This example gets all campaigns. To add a campaign, run AddCampaign.php.
 */
class GetCampaigns
{

    const PAGE_LIMIT = 500;

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

        // Create selector.
        $selector = new Selector();
        $selector->setFields(['Id', 'Name']);
        $selector->setOrdering([new OrderBy('Name', SortOrder::ASCENDING)]);
        $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

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

            // Display results.
            if ($page->getEntries() !== null) {
                $totalNumEntries = $page->getTotalNumEntries();
                foreach ($page->getEntries() as $campaign) {
                    printf(
                        "Campaign with ID %d and name '%s' was found.\n",
                        $campaign->getId(),
                        $campaign->getName()
                    );
                }
            }

            // Advance the paging index.
            $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);
    }
}

GetCampaigns::main();

Get all campaigns using AWQL

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Query\v201806\ServiceQueryBuilder;
use Google\AdsApi\AdWords\v201806\cm\CampaignService;
use Google\AdsApi\AdWords\v201806\cm\Page;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all campaigns in the account with AWQL. To add a campaign,
 * run AddCampaign.php.
 */
class GetCampaignsWithAwql
{

    const PAGE_LIMIT = 500;

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

        // Create AWQL query.
        $query = (new ServiceQueryBuilder())
            ->select(['Id', 'Name', 'Status'])
            ->orderByAsc('Name')
            ->limit(0, self::PAGE_LIMIT)
            ->build();

        do {
            // Advance the paging offset in subsequent iterations only.
            if (isset($page)) {
                $query->nextPage();
            }

            // Make a request using an AWQL string. This request will return the
            // first page containing up to `self::PAGE_LIMIT` results
            $page = $campaignService->query(sprintf('%s', $query));

            // Display results from second and subsequent pages.
            if ($page->getEntries() !== null) {
                foreach ($page->getEntries() as $campaign) {
                    printf(
                        "Campaign with ID %d and name '%s' was found.\n",
                        $campaign->getId(),
                        $campaign->getName()
                    );
                }
            }
        } while ($query->hasNext($page));

        printf(
            "Number of results found: %d\n",
            $page->getTotalNumEntries()
        );
    }

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

GetCampaignsWithAwql::main();

Get expanded text ads in an ad group

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

namespace Google\AdsApi\Examples\AdWords\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201806\cm\AdType;
use Google\AdsApi\AdWords\v201806\cm\OrderBy;
use Google\AdsApi\AdWords\v201806\cm\Paging;
use Google\AdsApi\AdWords\v201806\cm\Predicate;
use Google\AdsApi\AdWords\v201806\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201806\cm\Selector;
use Google\AdsApi\AdWords\v201806\cm\SortOrder;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets expanded text ads in an ad group. To add expanded text ads,
 * run AddExpandedTextAds.php. To get ad groups, run GetAdGroups.php.
 */
class GetExpandedTextAds
{

    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', 'Status', 'HeadlinePart1', 'HeadlinePart2', 'Description']
        );
        $selector->setOrdering([new OrderBy('Id', SortOrder::ASCENDING)]);
        $selector->setPredicates(
            [
                new Predicate('AdGroupId', PredicateOperator::IN, [$adGroupId]),
                new Predicate(
                    'AdType',
                    PredicateOperator::IN,
                    [AdType::EXPANDED_TEXT_AD]
                ),
                new Predicate(
                    'Status',
                    PredicateOperator::IN,
                    [AdGroupAdStatus::ENABLED, AdGroupAdStatus::PAUSED]
                )
            ]
        );
        $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

        $totalNumEntries = 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) {
                    printf(
                        "Expanded text ad with ID %d, status '%s', and headline '%s - %s' was found.\n",
                        $adGroupAd->getAd()->getId(),
                        $adGroupAd->getStatus(),
                        $adGroupAd->getAd()->getHeadlinePart1(),
                        $adGroupAd->getAd()->getHeadlinePart2()
                    );
                }
            }

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

GetExpandedTextAds::main();

Get keywords in an ad group

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

namespace Google\AdsApi\Examples\AdWords\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201806\cm\CriterionType;
use Google\AdsApi\AdWords\v201806\cm\OrderBy;
use Google\AdsApi\AdWords\v201806\cm\Paging;
use Google\AdsApi\AdWords\v201806\cm\Predicate;
use Google\AdsApi\AdWords\v201806\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201806\cm\Selector;
use Google\AdsApi\AdWords\v201806\cm\SortOrder;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all keywords in an ad group. To get ad groups, run
 * GetAdGroups.php.
 */
class GetKeywords
{

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

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

        // Create a selector to select all keywords for the specified ad group.
        $selector = new Selector();
        $selector->setFields(
            ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText']
        );
        $selector->setOrdering([new OrderBy('KeywordText', SortOrder::ASCENDING)]);
        $selector->setPredicates(
            [
                new Predicate('AdGroupId', PredicateOperator::IN, [$adGroupId]),
                new Predicate(
                    'CriteriaType',
                    PredicateOperator::IN,
                    [CriterionType::KEYWORD]
                )
            ]
        );
        $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

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

            // Print out some information for each keyword.
            if ($page->getEntries() !== null) {
                $totalNumEntries = $page->getTotalNumEntries();
                foreach ($page->getEntries() as $adGroupCriterion) {
                    printf(
                        "Keyword with text '%s', match type '%s', criteria type '%s', and ID %d was found.\n",
                        $adGroupCriterion->getCriterion()->getText(),
                        $adGroupCriterion->getCriterion()->getMatchType(),
                        $adGroupCriterion->getCriterion()->getType(),
                        $adGroupCriterion->getCriterion()->getId()
                    );
                }
            }

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

GetKeywords::main();

Get labels in an account

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\LabelService;
use Google\AdsApi\AdWords\v201806\cm\OrderBy;
use Google\AdsApi\AdWords\v201806\cm\Paging;
use Google\AdsApi\AdWords\v201806\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all labels in the account.
 */
class GetLabels
{

    const PAGE_LIMIT = 500;

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

        // Create selector.
        $selector = new Selector();
        $selector->setFields(['LabelId', 'LabelName']);
        $selector->setOrdering([new OrderBy('LabelName', 'ASCENDING')]);
        $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

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

            // Print out information about labels obtained from LabelService.
            if ($page->getEntries() !== null) {
                $totalNumEntries = $page->getTotalNumEntries();
                foreach ($page->getEntries() as $label) {
                    printf(
                        "Label with ID %d and name '%s' was found.\n",
                        $label->getId(),
                        $label->getName()
                    );
                }
            }

            // Advance the paging index.
            $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);
    }
}

GetLabels::main();

Get responsive search ads in an ad group

<?php
/**
 * Copyright 2018 Google LLC
 *
 * 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\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Query\v201806\ServiceQueryBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201806\cm\AdType;
use Google\AdsApi\AdWords\v201806\cm\ResponsiveSearchAd;
use Google\AdsApi\AdWords\v201806\cm\TextAsset;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets non-removed responsive search ads in an ad group.  To add
 * responsive search ads, run AddResponsiveSearchAd.php. To get ad groups, run
 * GetAdGroups.php.
 */
class GetResponsiveSearchAds
{

    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.
        $selectedFields = [
            'Id',
            'Status',
            'ResponsiveSearchAdHeadlines',
            'ResponsiveSearchAdDescriptions'
        ];
        $query = (new ServiceQueryBuilder())->select($selectedFields)
            ->where('AdGroupId')
            ->in([$adGroupId])
            ->where('AdType')
            ->in([AdType::RESPONSIVE_SEARCH_AD])
            ->where('Status')
            ->in([AdGroupAdStatus::ENABLED, AdGroupAdStatus::PAUSED])
            ->orderByAsc('Id')
            ->limit(0, self::PAGE_LIMIT)
            ->build();

        $totalNumEntries = 0;
        do {
            // Advance the paging offset in subsequent iterations only.
            if (isset($page)) {
                $query->nextPage();
            }

            // Retrieve ad group ads one page at a time, continuing to request
            // pages until all ad group ads have been retrieved.
            $page = $adGroupAdService->query(sprintf('%s', $query));

            // Print out some information for each ad group ad.
            if ($page->getEntries() !== null) {
                $totalNumEntries = $page->getTotalNumEntries();
                /** @var AdGroupAd $adGroupAd */
                foreach ($page->getEntries() as $adGroupAd) {
                    /** @var ResponsiveSearchAd $ad */
                    $ad = $adGroupAd->getAd();
                    printf(
                        "Responsive search ad with ID %d and status '%s'"
                        . " was found.%s",
                        $ad->getId(),
                        $adGroupAd->getStatus(),
                        PHP_EOL
                    );
                    print 'Headlines:' . PHP_EOL;
                    foreach ($ad->getHeadlines() as $headline) {
                        /** @var TextAsset $textAsset */
                        $textAsset = $headline->getAsset();
                        $pinnedField = $headline->getPinnedField();
                        printf('    %s%s', $textAsset->getAssetText(), PHP_EOL);
                        if (!is_null($pinnedField)) {
                            printf(
                                '      (pinned to %s)%s',
                                $pinnedField,
                                PHP_EOL
                            );
                        }
                    }
                    print 'Descriptions:' . PHP_EOL;
                    foreach ($ad->getDescriptions() as $description) {
                        /** @var TextAsset $textAsset */
                        $textAsset = $description->getAsset();
                        $pinnedField = $description->getPinnedField();
                        printf('    %s%s', $textAsset->getAssetText(), PHP_EOL);
                        if (!is_null($pinnedField)) {
                            printf(
                                '      (pinned to %s)%s',
                                $pinnedField,
                                PHP_EOL
                            );
                        }
                    }
                    print PHP_EOL;
                }
            }
        } while ($query->hasNext($page));

        printf(
            'Number of responsive search ad(s) found: %d%s',
            $totalNumEntries,
            PHP_EOL
        );
    }

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

GetResponsiveSearchAds::main();

Pause an ad

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

namespace Google\AdsApi\Examples\AdWords\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\Ad;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example pauses an ad. To get expanded text ads, run
 * GetExpandedTextAds.php.
 */
class PauseAd
{

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
    const AD_ID = 'INSERT_AD_ID_HERE';

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

        $operations = [];
        // Create ad using an existing ID. Use the base class Ad instead of TextAd
        // to avoid having to set ad-specific fields.
        $ad = new Ad();
        $ad->setId($adId);

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

        // Update the status to PAUSED.
        $adGroupAd->setStatus(AdGroupAdStatus::PAUSED);

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

        // Pause the ad on the server.
        $adGroupAd = $adGroupAdService->mutate($operations)->getValue()[0];
        printf(
            "Ad of type '%s' with ID %d has updated status '%s'.\n",
            $adGroupAd->getAd()->getType(),
            $adGroupAd->getAd()->getId(),
            $adGroupAd->getStatus()
        );
    }

    public static function main()
    {
        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct an API session configured from a properties file and the
        // OAuth2 credentials above.
        $session = (new AdWordsSessionBuilder())->fromFile()->withOAuth2Credential($oAuth2Credential)->build();
        self::runExample(
            new AdWordsServices(),
            $session,
            intval(self::AD_GROUP_ID),
            intval(self::AD_ID)
        );
    }
}

PauseAd::main();

Remove an ad

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

namespace Google\AdsApi\Examples\AdWords\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\Ad;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201806\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example removes an ad. To get text ads, run GetExpandedTextAds.php.
 */
class RemoveAd
{

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
    const AD_ID = 'INSERT_AD_ID_HERE';

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

        $operations = [];
        // Create ad using an existing ID. Use the base class Ad instead of TextAd
        // to avoid having to set ad-specific fields.
        $ad = new Ad();
        $ad->setId($adId);

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

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

        // Remove the ad on the server.
        $result = $adGroupAdService->mutate($operations);

        $adGroupAd = $result->getValue()[0];
        printf("Ad with ID %d was removed.\n", $adGroupAd->getAd()->getId());
    }

    public static function main()
    {
        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct an API session configured from a properties file and the
        // OAuth2 credentials above.
        $session = (new AdWordsSessionBuilder())->fromFile()->withOAuth2Credential($oAuth2Credential)->build();
        self::runExample(
            new AdWordsServices(),
            $session,
            intval(self::AD_GROUP_ID),
            intval(self::AD_ID)
        );
    }
}

RemoveAd::main();

Remove an ad group

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

namespace Google\AdsApi\Examples\AdWords\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdGroup;
use Google\AdsApi\AdWords\v201806\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201806\cm\AdGroupService;
use Google\AdsApi\AdWords\v201806\cm\AdGroupStatus;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example removes an ad group. To get ad groups, run GetAdGroups.php.
 */
class RemoveAdGroup
{

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

        $operations = [];
        // Create ad group with REMOVED status.
        $adGroup = new AdGroup();
        $adGroup->setId($adGroupId);
        $adGroup->setStatus(AdGroupStatus::REMOVED);

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

        // Remove the ad group on the server.
        $result = $adGroupService->mutate($operations);

        $adGroup = $result->getValue()[0];
        printf("Ad group with ID %d was removed.\n", $adGroup->getId());
    }

    public static function main()
    {
        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct an API session configured from a properties file and the
        // OAuth2 credentials above.
        $session = (new AdWordsSessionBuilder())->fromFile()->withOAuth2Credential($oAuth2Credential)->build();
        self::runExample(
            new AdWordsServices(),
            $session,
            intval(self::AD_GROUP_ID)
        );
    }
}

RemoveAdGroup::main();

Remove a campaign

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

namespace Google\AdsApi\Examples\AdWords\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\Campaign;
use Google\AdsApi\AdWords\v201806\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201806\cm\CampaignService;
use Google\AdsApi\AdWords\v201806\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example removes a campaign. To get campaigns, run GetCampaigns.php.
 */
class RemoveCampaign
{

    const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';

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

        $operations = [];
        // Create a campaign with REMOVED status.
        $campaign = new Campaign();
        $campaign->setId($campaignId);
        $campaign->setStatus(CampaignStatus::REMOVED);

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

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

        $campaign = $result->getValue()[0];
        printf("Campaign with ID %d was removed.\n", $campaign->getId());
    }

    public static function main()
    {
        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct an API session configured from a properties file and the
        // OAuth2 credentials above.
        $session = (new AdWordsSessionBuilder())->fromFile()->withOAuth2Credential($oAuth2Credential)->build();
        self::runExample(
            new AdWordsServices(),
            $session,
            intval(self::CAMPAIGN_ID)
        );
    }
}

RemoveCampaign::main();

Remove a keyword

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdGroupCriterion;
use Google\AdsApi\AdWords\v201806\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201806\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201806\cm\Criterion;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example removes a keyword.
 */
class RemoveKeyword
{

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
    const CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE';

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

        // Create criterion using an existing ID. Use the base class Criterion
        // instead of Keyword to avoid having to set keyword-specific fields.
        $criterion = new Criterion();
        $criterion->setId($criterionId);

        // Create an ad group criterion.
        $adGroupCriterion = new AdGroupCriterion();
        $adGroupCriterion->setAdGroupId($adGroupId);
        $adGroupCriterion->setCriterion($criterion);

        // Create an ad group criterion operation and add it the operations list.
        $operation = new AdGroupCriterionOperation();
        $operation->setOperand($adGroupCriterion);
        $operation->setOperator(Operator::REMOVE);
        $operations = [$operation];

        // Remove criterion on the server.
        $result = $adGroupCriterionService->mutate($operations);

        // Print out some information for the removed keyword.
        $adGroupCriterion = $result->getValue()[0];
        printf(
            "Keyword with ID '%d' was removed.\n",
            $adGroupCriterion->getCriterion()->getId()
        );
    }

    public static function main()
    {
        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct an API session configured from a properties file and the
        // OAuth2 credentials above.
        $session = (new AdWordsSessionBuilder())->fromFile()->withOAuth2Credential($oAuth2Credential)->build();
        self::runExample(
            new AdWordsServices(),
            $session,
            intval(self::AD_GROUP_ID),
            intval(self::CRITERION_ID)
        );
    }
}

RemoveKeyword::main();

Update an ad group

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

namespace Google\AdsApi\Examples\AdWords\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdGroup;
use Google\AdsApi\AdWords\v201806\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201806\cm\AdGroupService;
use Google\AdsApi\AdWords\v201806\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201806\cm\CpcBid;
use Google\AdsApi\AdWords\v201806\cm\Money;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example updates the CPC bid and status for a given ad group. To get ad
 * groups, run GetAdGroups.php.
 */
class UpdateAdGroup
{

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

    // Set this to a micro amount of the CPC bid if you want to update it.
    // Leave this to null if you don't want to update.
    const CPC_BID_MICRO_AMOUNT = null;

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

        $operations = [];
        // Create ad group with the specified ID.
        $adGroup = new AdGroup();
        $adGroup->setId($adGroupId);

        // Update the CPC bid if specified.
        if (!is_null($cpcBidMicroAmount)) {
            $bid = new CpcBid();
            $money = new Money();
            $money->setMicroAmount($cpcBidMicroAmount);
            $bid->setBid($money);
            $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
            $biddingStrategyConfiguration->setBids([$bid]);
            $adGroup->setBiddingStrategyConfiguration($biddingStrategyConfiguration);
        }

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

        // Update the ad group on the server.
        $result = $adGroupService->mutate($operations);

        $adGroup = $result->getValue()[0];
        $biddingStrategyConfiguration = $adGroup->getBiddingStrategyConfiguration();
        // Find the CpcBid in the bidding strategy configuration's bids collection.
        $cpcBidMicros = null;
        if (!empty($biddingStrategyConfiguration)
            && !empty($biddingStrategyConfiguration->getBids())) {
            foreach ($biddingStrategyConfiguration->getBids() as $bid) {
                if ($bid instanceof CpcBid) {
                    $cpcBidMicros = $bid->getBid()->getMicroAmount();
                }
            }
        }
        printf(
            "Ad group with ID %d and name '%s' updated to have status '%s' and CPC bid %d.\n",
            $adGroup->getId(),
            $adGroup->getName(),
            $adGroup->getStatus(),
            $cpcBidMicros
        );
    }

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

UpdateAdGroup::main();

Update a campaign

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

namespace Google\AdsApi\Examples\AdWords\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\Campaign;
use Google\AdsApi\AdWords\v201806\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201806\cm\CampaignService;
use Google\AdsApi\AdWords\v201806\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example updates the status of a campaign to PAUSED. To get
 * campaigns, run GetCampaigns.php.
 */
class UpdateCampaign
{

    const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';

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

        $operations = [];
        // Create a campaign with PAUSED status.
        $campaign = new Campaign();
        $campaign->setId($campaignId);
        $campaign->setStatus(CampaignStatus::PAUSED);

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

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

        $campaign = $result->getValue()[0];
        printf(
            "Campaign with ID %d, name '%s', and budget delivery method '%s' was updated.\n",
            $campaign->getId(),
            $campaign->getName(),
            $campaign->getBudget()->getDeliveryMethod()
        );
    }

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

UpdateCampaign::main();

Update an expanded text ad

<?php
/**
 * Copyright 2018 Google LLC
 *
 * 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\v201806\BasicOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdOperation;
use Google\AdsApi\AdWords\v201806\cm\AdService;
use Google\AdsApi\AdWords\v201806\cm\ExpandedTextAd;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example updates an expanded text ad. To get expanded text ads, run
 * GetExpandedTextAds.php.
 */
class UpdateExpandedTextAd
{

    const AD_ID = 'INSERT_AD_ID_HERE';

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

        $operations = [];
        // Creates an expanded text ad using the provided ad ID.
        $expandedTextAd = new ExpandedTextAd();
        $expandedTextAd->setId($adId);
        // Updates some properties of the expanded text ad.
        $expandedTextAd->setHeadlinePart1('Cruise to Pluto #' . uniqid());
        $expandedTextAd->setHeadlinePart2('Tickets on sale now');
        $expandedTextAd->setDescription('Best space cruise ever.');
        $expandedTextAd->setFinalUrls(['http://www.example.com/']);
        $expandedTextAd->setFinalMobileUrls(['http://www.example.com/mobile']);

        // Creates ad group ad operation and add it to the list.
        $operation = new AdOperation();
        $operation->setOperand($expandedTextAd);
        $operation->setOperator(Operator::SET);
        $operations[] = $operation;

        // Updates the ad on the server.
        $result = $adService->mutate($operations);
        $updatedAd = $result->getValue()[0];

        // Prints out some information.
        printf(
            'Expanded text ad with ID %d was updated.%s',
            $updatedAd->getId(),
            PHP_EOL
        );
        printf(
            'Headline part 1 is "%1$s".%4$sHeadline part 2 is "%2$s".'
             . '%4$sDescription is "%3$s".%4$s',
            $updatedAd->getHeadlinePart1(),
            $updatedAd->getHeadlinePart2(),
            $updatedAd->getDescription(),
            PHP_EOL
        );
        printf(
            'Final URL is "%1$s".%3$sFinal mobile URL is "%2$s".%3$s',
            $updatedAd->getFinalUrls()[0],
            $updatedAd->getFinalMobileUrls()[0],
            PHP_EOL
        );
    }

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

UpdateExpandedTextAd::main();

Update a keyword

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201806\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201806\cm\BiddableAdGroupCriterion;
use Google\AdsApi\AdWords\v201806\cm\Criterion;
use Google\AdsApi\AdWords\v201806\cm\Operator;
use Google\AdsApi\AdWords\v201806\cm\UrlList;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example updates the final URL of a keyword. To get keywords, run
 * GetKeywords.php.
 */
class UpdateKeyword
{

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
    const CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE';

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

        $operations = [];

        // Create ad group criterion.
        $adGroupCriterion = new BiddableAdGroupCriterion();
        $adGroupCriterion->setAdGroupId($adGroupId);
        // Create criterion using an existing ID. Use the base class Criterion
        // instead of Keyword to avoid having to set keyword-specific fields.
        $adGroupCriterion->setCriterion(new Criterion($criterionId));

        // Update final URL.
        $adGroupCriterion->setFinalUrls(
            new UrlList(['http://www.example.com/new'])
        );

        // Create ad group criterion operation and add it to the list.
        $operation = new AdGroupCriterionOperation();
        $operation->setOperand($adGroupCriterion);
        $operation->setOperator(Operator::SET);
        $operations[] = $operation;

        // Update the keyword on the server.
        $result = $adGroupCriterionService->mutate($operations);

        $adGroupCriterion = $result->getValue()[0];
        printf(
            "Keyword with ID %d has updated final URL '%s'.\n",
            $adGroupCriterion->getCriterion()->getId(),
            $adGroupCriterion->getFinalUrls()->getUrls()[0]
        );
    }

    public static function main()
    {
        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct an API session configured from a properties file and the
        // OAuth2 credentials above.
        $session = (new AdWordsSessionBuilder())->fromFile()->withOAuth2Credential($oAuth2Credential)->build();
        self::runExample(
            new AdWordsServices(),
            $session,
            intval(self::AD_GROUP_ID),
            intval(self::CRITERION_ID)
        );
    }
}

UpdateKeyword::main();

Send feedback about...

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