Share your feedback about the Google Ads (AdWords) API. Take the 2021 AdWords API and Google Ads API Annual Survey.

The AdWords API will sunset on April 27, 2022. Migrate to the Google Ads API to take advantage of the latest Google Ads features.

Advanced Operations Samples

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

Add an ad customizer feed

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        printf(
            "Created ad customizer feed with ID %d, name '%s' and attributes:\n",
            $addedFeed->getFeedId(),
            $addedFeed->getFeedName()
        );
        if (empty($addedFeed)) {
            print "  No attributes\n";
        } else {
            foreach ($addedFeed->getFeedAttributes() as $feedAttribute) {
                printf(
                    "  ID: %d, name: '%s', type: %s\n",
                    $feedAttribute->getId(),
                    $feedAttribute->getName(),
                    $feedAttribute->getType()
                );
            }
        }


        return $addedFeed;
    }

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

        $operations = [];

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

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

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

        foreach ($result->getValue() as $feedItem) {
            printf(
                'FeedItem with ID %d was added.%s',
                $feedItem->getFeedItemId(),
                PHP_EOL
            );
        }
        for ($i = 0; $i < count($result->getValue()); $i++) {
            // Add feed item targeting to restrict the feed item to specific ad
            // groups.
            self::restrictFeedItemToAdGroup(
                $adWordsServices,
                $session,
                $result->getValue()[$i],
                $adGroupIds[$i]
            );
        }
    }

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

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

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

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

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

        return $operation;
    }

    /**
     * Restricts the feed item to an ad group.
     *
     * @param AdWordsServices $adWordsServices the AdWords services
     * @param AdWordsSession $session the AdWords session
     * @param FeedItem $feedItem the feed item to restrict
     * @param int $adGroupId the ad group ID to which the feed item will be
     *     restricted
     */
    private static function restrictFeedItemToAdGroup(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        FeedItem $feedItem,
        $adGroupId
    ) {
        $feedItemTargetService =
            $adWordsServices->get($session, FeedItemTargetService::class);

        // Create a feed item ad group target.
        $adGroupTarget = new FeedItemAdGroupTarget();
        $adGroupTarget->setFeedId($feedItem->getFeedId());
        $adGroupTarget->setFeedItemId($feedItem->getFeedItemId());
        $adGroupTarget->setAdGroupId($adGroupId);

        // Create a feed item target operation.
        $operation = new FeedItemTargetOperation();
        $operation->setOperator(Operator::ADD);
        $operation->setOperand($adGroupTarget);

        // Add a feed item target on the server and print out some information.
        $result = $feedItemTargetService->mutate([$operation]);
        $addedAdGroupTarget = $result->getValue()[0];
        sprintf(
            'Feed item target for feed ID %s and feed item ID %s '
            . 'was created to restrict serving to ad group ID %s.%s',
            $addedAdGroupTarget->getFeedId(),
            $addedAdGroupTarget->getFeedItemId(),
            $addedAdGroupTarget->getAdGroupId(),
            PHP_EOL
        );
    }


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

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

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

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

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

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

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

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

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

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

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

AddAdCustomizer::main();

Add an ad group level bid modifier

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

namespace Google\AdsApi\Examples\AdWords\v201809\AdvancedOperations;

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

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

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

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

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

        $operations = [];

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

        $operation = new AdGroupBidModifierOperation();

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

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

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

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

AddAdGroupBidModifier::main();

Add a page feed specifying URLs for a DSA campaign

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

namespace Google\AdsApi\Examples\AdWords\v201809\AdvancedOperations;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return $feedDetails;
    }

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

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

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

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

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

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

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

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

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

        // See https://support.google.com/adwords/answer/7166527 for page feed
        // URL recommendations and rules.
        $urlAttributeValue->setStringValues([$url]);

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

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

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

        return $operation;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        $criterion->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

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

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


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

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

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

AddDynamicPageFeed::main();

Add a DSA campaign

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

namespace Google\AdsApi\Examples\AdWords\v201809\AdvancedOperations;

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

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

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

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

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

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

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

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

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

        return $sharedBudget;
    }

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

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

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

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

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

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

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

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

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

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

        return $campaign;
    }

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

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

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

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

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

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

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

        $adGroup->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

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

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

        return $adGroup;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

AddDynamicSearchAdsCampaign::main();

Add an expanded text ad with Upgraded URLs

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

namespace Google\AdsApi\Examples\AdWords\v201809\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\v201809\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201809\cm\CustomParameter;
use Google\AdsApi\AdWords\v201809\cm\CustomParameters;
use Google\AdsApi\AdWords\v201809\cm\ExpandedTextAd;
use Google\AdsApi\AdWords\v201809\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

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

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

AddExpandedTextAdWithUpgradedUrls::main();

Add a Gmail ad to an ad group

<?php
/**
 * Copyright 2018 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\v201809\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201809\cm\GmailAd;
use Google\AdsApi\AdWords\v201809\cm\GmailTeaser;
use Google\AdsApi\AdWords\v201809\cm\Image;
use Google\AdsApi\AdWords\v201809\cm\MediaMediaType;
use Google\AdsApi\AdWords\v201809\cm\MediaService;
use Google\AdsApi\AdWords\v201809\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This code example adds a Gmail ad to a given ad group. The ad group's
 * campaign needs to have an AdvertisingChannelType of DISPLAY and
 * AdvertisingChannelSubType of DISPLAY_GMAIL_AD.
 * To get ad groups, run BasicOperations/GetAdGroups.php.
 */
class AddGmailAd
{

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

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

        $uploadedMarketingImage =
            self::uploadImage($mediaService, 'http://goo.gl/3b9Wfh');
        $marketingImage = new Image();
        $marketingImage->setMediaId($uploadedMarketingImage->getMediaId());

        $teaser = new GmailTeaser();
        $teaser->setHeadline('Dream');
        $teaser->setDescription('Create your own adventure');
        $teaser->setBusinessName('Interplanetary Ships');
        $teaser->setLogoImage($logoImage);

        // Creates a Gmail ad.
        $gmailAd = new GmailAd();
        $gmailAd->setTeaser($teaser);
        $gmailAd->setMarketingImage($marketingImage);
        $gmailAd->setMarketingImageHeadline('Travel');
        $gmailAd->setMarketingImageDescription('Take to the skies!');
        $gmailAd->setFinalUrls(['http://www.example.com/']);

        // Creates ad group ad for the Gmail ad.
        $adGroupAd = new AdGroupAd();
        $adGroupAd->setAdGroupId($adGroupId);
        $adGroupAd->setAd($gmailAd);
        // Optional: Set additional settings.
        $adGroupAd->setStatus(AdGroupAdStatus::PAUSED);

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

        // Adds a Gmail ad on the server.
        $result = $adGroupAdService->mutate([$operation]);

        if (empty($result->getValue())) {
            print "No Gmail ads were added.\n";
            return;
        }
        // Prints out some information for each created Gmail ad.
        foreach ($result->getValue() as $adGroupAd) {
            printf(
                "A Gmail ad with ID %d and headline '%s' was added.\n",
                $adGroupAd->getAd()->getId(),
                $adGroupAd->getAd()->getTeaser()->getHeadline()
            );
        }
    }

    /**
     * Uploads an image to the server.
     *
     * @param MediaService $mediaService the media service
     * @param string $url the URL of image to upload
     * @return Image the uploaded image returned from the server
     */
    private static function uploadImage(MediaService $mediaService, $url)
    {
        // Creates an image and upload it to the server.
        $image = new Image();
        $image->setData(file_get_contents($url));
        $image->setType(MediaMediaType::IMAGE);

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

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

AddGmailAd::main();

Add an HTML 5 ad to an ad group

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

namespace Google\AdsApi\Examples\AdWords\v201809\AdvancedOperations;

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

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

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

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

AddHtml5Ad::main();

Add a multi-asset responsive display 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\v201809\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201809\cm\AssetLink;
use Google\AdsApi\AdWords\v201809\cm\AssetOperation;
use Google\AdsApi\AdWords\v201809\cm\AssetService;
use Google\AdsApi\AdWords\v201809\cm\DisplayAdFormatSetting;
use Google\AdsApi\AdWords\v201809\cm\ImageAsset;
use Google\AdsApi\AdWords\v201809\cm\MultiAssetResponsiveDisplayAd;
use Google\AdsApi\AdWords\v201809\cm\Operator;
use Google\AdsApi\AdWords\v201809\cm\TextAsset;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This code example adds a multi-asset responsive display ad
 * (MultiAssetResponsiveDisplayAd) to an ad group. Image assets are uploaded
 * using AssetService. To get ad groups, run GetAdGroups.php.
 */
class AddMultiAssetResponsiveDisplayAd
{

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

    public static function runExample(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        $adGroupId
    ) {

        $assetService = $adWordsServices->get($session, AssetService::class);
        $adGroupAdService =
            $adWordsServices->get($session, AdGroupAdService::class);

        // Create a multi-asset responsive display ad.
        $multiAssetResponsiveDisplayAd = new MultiAssetResponsiveDisplayAd();
        $headlineTextAsset1 = new TextAsset();
        $headlineTextAsset1->setAssetText('Travel to Mars');
        $headlineTextAsset2 = new TextAsset();
        $headlineTextAsset2->setAssetText('Travel to Jupiter');
        $headlineTextAsset3 = new TextAsset();
        $headlineTextAsset3->setAssetText('Travel to Pluto');
        // Text assets can be specified directly in the asset field when
        // creating the ad.
        $multiAssetResponsiveDisplayAd->setHeadlines([
            new AssetLink($headlineTextAsset1),
            new AssetLink($headlineTextAsset2),
            new AssetLink($headlineTextAsset3)
        ]);

        // Set business name and long headline.
        $multiAssetResponsiveDisplayAd->setBusinessName(
            'Galactic Luxury Cruises'
        );
        $longHeadlineTextAsset = new TextAsset();
        $longHeadlineTextAsset->setAssetText(
            'Visit the planet in a luxury spaceship.'
        );
        $multiAssetResponsiveDisplayAd->setLongHeadline(
            new AssetLink($longHeadlineTextAsset)
        );

        // Set description.
        $descriptionTextAsset1 = new TextAsset();
        $descriptionTextAsset1->setAssetText(
            'Visit the planet in a luxury spaceship.'
        );
        $descriptionTextAsset2 = new TextAsset();
        $descriptionTextAsset2->setAssetText('See the planet in style.');
        $multiAssetResponsiveDisplayAd->setDescriptions([
            new AssetLink($descriptionTextAsset1),
            new AssetLink($descriptionTextAsset2)
        ]);

        // Set a marketing image.
        $marketingImageAsset = new ImageAsset();
        // This ad format does not allow the creation of an image asset by
        // setting the Asset.imageData field. An image asset must first be
        // created using the AssetService, and Asset.assetId must be populated
        // when creating the ad.
        $marketingImageAsset->setAssetId(
            self::uploadImageAsset($assetService, 'https://goo.gl/3b9Wfh')
        );
        $multiAssetResponsiveDisplayAd->setMarketingImages([
            new AssetLink(
                $marketingImageAsset
            )
        ]);

        // Set a square image.
        $squareImageAsset = new ImageAsset();
        $squareImageAsset->setAssetId(
            self::uploadImageAsset($assetService, 'https://goo.gl/mtt54n')
        );
        $multiAssetResponsiveDisplayAd->setSquareMarketingImages([
            new AssetLink(
                $squareImageAsset
            )
        ]);

        $multiAssetResponsiveDisplayAd->setFinalUrls(
            ['http://www.example.com']
        );

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

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

        // Optional: Set the format setting that the ad will be served in.
        $multiAssetResponsiveDisplayAd->setFormatSetting(
            DisplayAdFormatSetting::NON_NATIVE
        );

        // Optional: Set dynamic display ad settings, composed of landscape logo
        // image, promotion text, and price prefix.
        $multiAssetResponsiveDisplayAd->setDynamicSettingsPricePrefix(
            'as low as'
        );
        $multiAssetResponsiveDisplayAd->setDynamicSettingsPromoText(
            'Free shipping!'
        );

        // Set a logo image.
        $logoImageAsset = new ImageAsset();
        $logoImageAsset->setAssetId(
            self::uploadImageAsset($assetService, 'https://goo.gl/mtt54n')
        );
        $multiAssetResponsiveDisplayAd->setLogoImages([
            new AssetLink(
                $logoImageAsset
            )
        ]);

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

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

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

        // Print out some information for each created ad.
        foreach ($result->getValue() as $adGroupAd) {
            $ad = $adGroupAd->getAd();
            printf(
                "Responsive display ad with ID %d and long "
                . "headline '%s' was added.%s",
                $ad->getId(),
                $ad->getLongHeadline()->getAsset()->getAssetText(),
                PHP_EOL
            );
        }
    }

    /**
     * Upload an image asset using AssetService and provided URL.
     */
    private static function uploadImageAsset(AssetService $assetService, $url)
    {
        // Creates an image asset and upload it to the server.
        $imageAsset = new ImageAsset();
        // Optional: Provide a unique friendly name to identify your asset. If
        // you specify the assetName field, then both the asset name and the
        // image being uploaded should be unique, and should not match another
        // ACTIVE asset in this customer account.
        // $imageAsset->setAssetName('Image asset #' . uniqid());
        $imageAsset->setImageData(file_get_contents($url));

        // Create an asset operation.
        $operation = new AssetOperation();
        $operation->setOperand($imageAsset);
        $operation->setOperator(Operator::ADD);

        return $assetService->mutate([$operation])->getValue()[0]->getAssetId();
    }

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

AddMultiAssetResponsiveDisplayAd::main();

Add a responsive display 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\v201809\AdvancedOperations;

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

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

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

    const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return $dynamicSettings;
    }


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

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

AddResponsiveDisplayAd::main();

Add a Shopping dynamic remarketing campaign

<?php
/**
 * Copyright 2018 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\v201809\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201809\cm\AdGroup;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201809\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201809\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201809\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201809\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201809\cm\AdGroupService;
use Google\AdsApi\AdWords\v201809\cm\AdGroupStatus;
use Google\AdsApi\AdWords\v201809\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201809\cm\BiddableAdGroupCriterion;
use Google\AdsApi\AdWords\v201809\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201809\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201809\cm\Budget;
use Google\AdsApi\AdWords\v201809\cm\Campaign;
use Google\AdsApi\AdWords\v201809\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201809\cm\CampaignService;
use Google\AdsApi\AdWords\v201809\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201809\cm\CriterionUserList;
use Google\AdsApi\AdWords\v201809\cm\DynamicSettings;
use Google\AdsApi\AdWords\v201809\cm\Image;
use Google\AdsApi\AdWords\v201809\cm\MediaMediaType;
use Google\AdsApi\AdWords\v201809\cm\MediaService;
use Google\AdsApi\AdWords\v201809\cm\Operator;
use Google\AdsApi\AdWords\v201809\cm\ResponsiveDisplayAd;
use Google\AdsApi\AdWords\v201809\cm\ShoppingPurchasePlatform;
use Google\AdsApi\AdWords\v201809\cm\ShoppingSetting;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a Shopping dynamic remarketing campaign for the Display
 * Network via the following steps:
 *
 * <ul>
 *   <li>Creates a new Display Network campaign.
 *   <li>Links the campaign with Merchant Center.
 *   <li>Links the user list to the ad group.
 *   <li>Creates a responsive display ad to render the dynamic text.
 * </ul>
 */
class AddShoppingDynamicRemarketingCampaign
{

    const BUDGET_ID = 'INSERT_BUDGET_ID_HERE';
    const MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE';
    const USER_LIST_ID = 'INSERT_USER_LIST_ID_HERE';

    public static function runExample(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        $budgetId,
        $merchantId,
        $userListId
    ) {
        $campaign = self::createCampaign(
            $adWordsServices,
            $session,
            $budgetId,
            $merchantId
        );
        printf(
            "Campaign with name '%s' and ID %d was added.\n",
            $campaign->getName(),
            $campaign->getId()
        );

        $adGroup = self::createAdGroup($adWordsServices, $session, $campaign);
        printf(
            "Ad group with name '%s' and ID %d was added.\n",
            $adGroup->getName(),
            $adGroup->getId()
        );

        $adGroupAd = self::createAd($adWordsServices, $session, $adGroup);
        printf(
            "Responsive display ad with ID %d was added.\n",
            $adGroupAd->getAd()
                ->getId()
        );

        self::attachUserList($adWordsServices, $session, $adGroup, $userListId);
        printf(
            "The user list with ID %d was attached to the ad group ID %d.\n",
            $userListId,
            $adGroup->getId()
        );
    }

    /**
     * Creates a Shopping dynamic remarketing campaign object (not including ad
     * group level and below).
     *
     * This creates a Display campaign with the merchant center feed attached.
     * Merchant Center is used for the product information in combination with
     * a user list which contains hits with {@code ecomm_prodid} specified. See
     * https://developers.google.com/adwords-remarketing-tag/parameters#retail
     * for more detail.
     *
     * @param AdWordsServices $adWordsServices the AdWords services
     * @param AdWordsSession $session the AdWords session
     * @param int $budgetId the budget ID to use for the campaign
     * @param int $merchantId the ID of the Merchant Center account
     * @return Campaign the created campaign
     */
    private static function createCampaign(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        $budgetId,
        $merchantId
    ) {
        $campaignService =
            $adWordsServices->get($session, CampaignService::class);

        // Create a campaign.
        $campaign = new Campaign();
        $campaign->setName('Shopping campaign #' . uniqid());
        // Dynamic remarketing campaigns are only available on the Google
        // Display Network.
        $campaign->setAdvertisingChannelType(AdvertisingChannelType::DISPLAY);

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

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

        // This example uses a Manual CPC bidding strategy, but you should
        // select the strategy that best aligns with your sales goals. More
        // details here: https://support.google.com/adwords/answer/2472725.
        $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
        $biddingStrategyConfiguration->setBiddingStrategyType(
            BiddingStrategyType::MANUAL_CPC
        );
        $campaign->setBiddingStrategyConfiguration(
            $biddingStrategyConfiguration
        );

        // All Shopping campaigns need a ShoppingSetting.
        $shoppingSetting = new ShoppingSetting();
        // Campaigns with numerically higher priorities take precedence over
        // those with lower priorities.
        $shoppingSetting->setCampaignPriority(0);

        // Set the Merchant Center account ID from which to source products.
        $shoppingSetting->setMerchantId($merchantId);

        // Display Network campaigns do not support partition by country. The
        // only supported value is "ZZ". This signals that products from all
        // countries are available in the campaign. The actual products which
        // serve are based on the products tagged in the user list entry.
        $shoppingSetting->setSalesCountry('ZZ');

        // Enable local inventory ads (items for sale in physical stores.)
        $shoppingSetting->setEnableLocal(true);

        $campaign->setSettings([$shoppingSetting]);

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

        // Makes the mutate request.
        $campaignAddResult = $campaignService->mutate([$campaignOperation]);
        $campaign = $campaignAddResult->getValue()[0];

        return $campaign;
    }

    /**
     * Creates an ad group in the specified campaign.
     *
     * @param AdWordsServices $adWordsServices the AdWords services
     * @param AdWordsSession $session the AdWords session
     * @param Campaign $campaign the campaign to which the ad group should be
     *     attached
     * @return AdGroup the created ad group
     */
    private static function createAdGroup(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        Campaign $campaign
    ) {
        $adGroupService =
            $adWordsServices->get($session, AdGroupService::class);

        // Creates ad group.
        $adGroup = new AdGroup();
        $adGroup->setCampaignId($campaign->getId());
        $adGroup->setName('Dynamic remarketing ad group #' . uniqid());
        $adGroup->setStatus(AdGroupStatus::ENABLED);

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

        // Makes the mutate request.
        $adGroupAddResult = $adGroupService->mutate([$adGroupOperation]);
        $adGroup = $adGroupAddResult->getValue()[0];

        return $adGroup;
    }

    /**
     * Attaches a user list to an ad group. The user list provides positive
     * targeting and feed information to drive the dynamic content of the ad.
     *
     * <p>Note: User lists are only supported at the ad group level for
     * positive targeting in dynamic remarketing campaigns.
     *
     * @param AdWordsServices $adWordsServices the AdWords services
     * @param AdWordsSession $session the AdWords session
     * @param AdGroup $adGroup the ad group to attach the user list used for
     *     dynamic feed content
     * @param int $userListId the user list ID to use for targeting and dynamic
     *     content.
     * @return BiddableAdGroupCriterion the attached ad group criterion
     */
    private static function attachUserList(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        AdGroup $adGroup,
        $userListId
    ) {
        $adGroupCriterionService =
            $adWordsServices->get($session, AdGroupCriterionService::class);

        // Creates criterion user list.
        $userList = new CriterionUserList();
        $userList->setUserListId($userListId);

        // Creates ad group criterion.
        $adGroupCriterion = new BiddableAdGroupCriterion();
        $adGroupCriterion->setCriterion($userList);
        $adGroupCriterion->setAdGroupId($adGroup->getId());

        // Creates operation.
        $adGroupCriterionOperation = new AdGroupCriterionOperation();
        $adGroupCriterionOperation->setOperand($adGroupCriterion);
        $adGroupCriterionOperation->setOperator(Operator::ADD);

        // Makes the mutate request.
        $adGroupCriterionAddResult =
            $adGroupCriterionService->mutate([$adGroupCriterionOperation]);
        $adGroupCriterion = $adGroupCriterionAddResult->getValue()[0];

        return $adGroupCriterion;
    }

    /**
     * Creates an ad for serving dynamic content in a remarketing campaign.
     *
     * @param AdWordsServices $adWordsServices the AdWords services
     * @param AdWordsSession $session the AdWords session
     * @param AdGroup $adGroup the ad group under wich to create the ad
     * @return AdGroupAd the created ad group ad
     */
    private static function createAd(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        AdGroup $adGroup
    ) {
        $adGroupAdService =
            $adWordsServices->get($session, AdGroupAdService::class);

        $responsiveDisplayAd = new ResponsiveDisplayAd();

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

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

        // Optional: Set the call-to-action text.
        // Valid texts: https://support.google.com/adwords/answer/7005917.
        $responsiveDisplayAd->setCallToActionText('Apply Now');

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

        // Optional: Creates a square marketing image using MediaService, and
        // set it to the ad.
        $squareMarketingImage = self::uploadImage(
            $adWordsServices,
            $session,
            'https://goo.gl/mtt54n'
        );
        $responsiveDisplayAd->setSquareMarketingImage($squareMarketingImage);

        // Optional: Set the logo image.
        $logoImage = self::uploadImage(
            $adWordsServices,
            $session,
            'https://goo.gl/mtt54n'
        );
        $responsiveDisplayAd->setLogoImage($logoImage);

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

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

        // Creates ad group ad.
        $adGroupAd = new AdGroupAd();
        $adGroupAd->setAdGroupId($adGroup->getId());
        $adGroupAd->setAd($responsiveDisplayAd);

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

        // Creates an ad group ad on the server.
        $adGroupAdAddResult = $adGroupAdService->mutate([$adGroupAdOperation]);
        $adGroupAd = $adGroupAdAddResult->getValue()[0];

        return $adGroupAd;
    }

    /**
     * Uploads an image from the specified URL.
     *
     * @param AdWordsServices $adWordsServices the AdWords services
     * @param AdWordsSession $session the AdWords session
     * @param string $url the URL used to upload an image
     * @return Image the uploaded image
     */
    private static function uploadImage(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        $url
    ) {
        $mediaService = $adWordsServices->get($session, MediaService::class);

        // Creates image.
        $image = new Image();
        $image->setData(file_get_contents($url));
        $image->setType(MediaMediaType::IMAGE);

        // Uploads image into the server.
        $result = $mediaService->upload([$image]);

        return $result[0];
    }

    /**
     * Creates dynamic display ad settings.
     *
     * @param AdWordsServices $adWordsServices the AdWords services
     * @param AdWordsSession $session the AdWords session
     * @return DynamicSettings the created dynamic settings
     */
    private static function createDynamicDisplayAdSettings(
        AdWordsServices $adWordsServices,
        AdWordsSession $session
    ) {
        $landscapeLogoImage = self::uploadImage(
            $adWordsServices,
            $session,
            'https://goo.gl/dEvQeF'
        );
        $dynamicSettings = new DynamicSettings();
        $dynamicSettings->setLandscapeLogoImage($landscapeLogoImage);
        $dynamicSettings->setPricePrefix('as low as');
        $dynamicSettings->setPromoText('Free shipping!');

        return $dynamicSettings;
    }

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

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

AddShoppingDynamicRemarketingCampaign::main();

Add a universal app campaign

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

namespace Google\AdsApi\Examples\AdWords\v201809\AdvancedOperations;

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

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

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

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

        // Create campaign with some properties set.
        $campaign = new Campaign();
        $campaign->setName('Interplanetary Cruise #' . uniqid());
        // Recommendation: Set the campaign to PAUSED when creating it to stop
        // the ads from immediately serving. Set to ENABLED once you've added
        // targeting and the ads are ready to serve.
        $campaign->setStatus(CampaignStatus::PAUSED);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


        return $budget->getBudgetId();
    }

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

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

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

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

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

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

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

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

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

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

AddUniversalAppCampaign::main();

Create a negative broad match keywords list and attach it 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\v201809\AdvancedOperations;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201809\cm\CampaignSharedSet;
use Google\AdsApi\AdWords\v201809\cm\CampaignSharedSetOperation;
use Google\AdsApi\AdWords\v201809\cm\CampaignSharedSetService;
use Google\AdsApi\AdWords\v201809\cm\Keyword;
use Google\AdsApi\AdWords\v201809\cm\KeywordMatchType;
use Google\AdsApi\AdWords\v201809\cm\Operator;
use Google\AdsApi\AdWords\v201809\cm\SharedCriterion;
use Google\AdsApi\AdWords\v201809\cm\SharedCriterionOperation;
use Google\AdsApi\AdWords\v201809\cm\SharedCriterionService;
use Google\AdsApi\AdWords\v201809\cm\SharedSet;
use Google\AdsApi\AdWords\v201809\cm\SharedSetOperation;
use Google\AdsApi\AdWords\v201809\cm\SharedSetService;
use Google\AdsApi\AdWords\v201809\cm\SharedSetType;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example creates a shared list of negative broad match keywords, then
 * attaches them to a campaign.
 */
class CreateAndAttachSharedKeywordSet
{

    const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';

    public static function runExample(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        $campaignId
    ) {
        $sharedSetService = $adWordsServices->get(
            $session,
            SharedSetService::class
        );
        $keywords = ['mars cruise', 'mars hotels'];

        // Create the shared negative keyword set.
        $sharedSet = new SharedSet();
        $sharedSet->setName('Negative keyword list #' . uniqid());
        $sharedSet->setType(SharedSetType::NEGATIVE_KEYWORDS);

        $sharedSetOperation = new SharedSetOperation();
        $sharedSetOperation->setOperator(Operator::ADD);
        $sharedSetOperation->setOperand($sharedSet);

        // Create the shared set on the server and print out some information.
        $sharedSet = $sharedSetService->mutate([$sharedSetOperation])->getValue()[0];
        printf(
            "Shared set with ID %d and name '%s' was successfully added.\n",
            $sharedSet->getSharedSetId(),
            $sharedSet->getName()
        );

        $sharedCriterionService = $adWordsServices->get(
            $session,
            SharedCriterionService::class
        );

        // Add negative keywords to the shared set.
        $operations = [];
        foreach ($keywords as $keyword) {
            $keywordCriterion = new Keyword();
            $keywordCriterion->setText($keyword);
            $keywordCriterion->setMatchType(KeywordMatchType::BROAD);

            $sharedCriterion = new SharedCriterion();
            $sharedCriterion->setCriterion($keywordCriterion);
            $sharedCriterion->setNegative(true);
            $sharedCriterion->setSharedSetId($sharedSet->getSharedSetId());

            $sharedCriterionOperation = new SharedCriterionOperation();
            $sharedCriterionOperation->setOperator(Operator::ADD);
            $sharedCriterionOperation->setOperand($sharedCriterion);

            $operations[] = $sharedCriterionOperation;
        }

        $result = $sharedCriterionService->mutate($operations);
        foreach ($result->getValue() as $sharedCriterion) {
            printf(
                "Added shared criterion ID %d with text '%s' to shared set with ID %d.\n",
                $sharedCriterion->getCriterion()->getId(),
                $sharedCriterion->getCriterion()->getText(),
                $sharedCriterion->getSharedSetId()
            );
        }

        $campaignSharedSetService = $adWordsServices->get(
            $session,
            CampaignSharedSetService::class
        );
        $campaignSharedSet = new CampaignSharedSet();
        $campaignSharedSet->setCampaignId($campaignId);
        $campaignSharedSet->setSharedSetId($sharedSet->getSharedSetId());

        $campaignSharedOperation = new CampaignSharedSetOperation();
        $campaignSharedOperation->setOperator(Operator::ADD);
        $campaignSharedOperation->setOperand($campaignSharedSet);

        $campaignSharedSet = $campaignSharedSetService->mutate([$campaignSharedOperation])->getValue()[0];
        printf(
            "Shared set ID %d was attached to campaign ID %d.\n",
            $campaignSharedSet->getSharedSetId(),
            $campaignSharedSet->getCampaignId()
        );
    }

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

CreateAndAttachSharedKeywordSet::main();

Find and remove shared sets and shared set criteria

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201809\cm\CampaignSharedSetService;
use Google\AdsApi\AdWords\v201809\cm\Criterion;
use Google\AdsApi\AdWords\v201809\cm\CriterionType;
use Google\AdsApi\AdWords\v201809\cm\Operator;
use Google\AdsApi\AdWords\v201809\cm\Paging;
use Google\AdsApi\AdWords\v201809\cm\Predicate;
use Google\AdsApi\AdWords\v201809\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201809\cm\Selector;
use Google\AdsApi\AdWords\v201809\cm\SharedCriterion;
use Google\AdsApi\AdWords\v201809\cm\SharedCriterionOperation;
use Google\AdsApi\AdWords\v201809\cm\SharedCriterionService;
use Google\AdsApi\AdWords\v201809\cm\SharedSetType;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example demonstrates how to find and remove shared sets and shared set
 * criteria.
 */
class FindAndRemoveCriteriaFromSharedSet
{

    const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
    const PAGE_LIMIT = 100;

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

        // Create selector.
        $selector = new Selector();
        $selector->setFields(
            [
                'SharedSetId',
                'CampaignId',
                'SharedSetName',
                'SharedSetType'
            ]
        );
        $selector->setPredicates(
            [
                new Predicate('CampaignId', PredicateOperator::EQUALS, [$campaignId]),
                new Predicate(
                    'SharedSetType',
                    PredicateOperator::IN,
                    [
                    SharedSetType::NEGATIVE_KEYWORDS,
                    SharedSetType::NEGATIVE_PLACEMENTS
                    ]
                )
            ]
        );
        $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

        $sharedSetIds = [];
        $totalNumEntries = 0;
        do {
            // Make the get request.
            $page = $campaignSharedSetService->get($selector);

            // Display results.
            if ($page->getEntries() !== null) {
                $totalNumEntries = $page->getTotalNumEntries();
                foreach ($page->getEntries() as $campaignSharedSet) {
                    $sharedSetIds[] = strval($campaignSharedSet->getSharedSetId());
                    printf(
                        "Campaign shared set ID %d and name '%s' found for campaign ID %d.\n",
                        $campaignSharedSet->getSharedSetId(),
                        $campaignSharedSet->getSharedSetName(),
                        $campaignSharedSet->getCampaignId()
                    );
                }
            }

            // Advance the paging index.
            $selector->getPaging()->setStartIndex(
                $selector->getPaging()->getStartIndex() + self::PAGE_LIMIT
            );
        } while ($selector->getPaging()->getStartIndex() < $totalNumEntries);

        if (empty($sharedSetIds)) {
            printf("No shared sets found for campaign ID %d.\n", $campaignId);

            return;
        }

        // Next, retrieve criterion IDs for all found shared sets.
        $sharedCriterionService = $adWordsServices->get(
            $session,
            SharedCriterionService::class
        );

        // Create selector.
        $selector = new Selector();
        $selector->setFields(
            [
                'SharedSetId',
                'Id',
                'KeywordText',
                'KeywordMatchType',
                'PlacementUrl'
            ]
        );
        $selector->setPredicates(
            [
                new Predicate('SharedSetId', PredicateOperator::IN, $sharedSetIds)
            ]
        );
        $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

        $removeCriterionOperations = [];
        $totalNumEntries = 0;
        do {
            // Make the get request.
            $page = $sharedCriterionService->get($selector);

            // Display results.
            if ($page->getEntries() !== null) {
                $totalNumEntries = $page->getTotalNumEntries();
                foreach ($page->getEntries() as $sharedCriterion) {
                    if (CriterionType::KEYWORD === $sharedCriterion->getCriterion()->getType()) {
                        $keyword = $sharedCriterion->getCriterion();
                        printf(
                            "Shared negative keyword with ID %d and text '%s' was found.\n",
                            $keyword->getId(),
                            $keyword->getText()
                        );
                    } elseif (CriterionType::PLACEMENT === $sharedCriterion->getCriterion()->getType()) {
                        $placement = $sharedCriterion->getCriterion();
                        printf(
                            "Shared negative placement with ID %d and URL '%s' was found.\n",
                            $placement->getId(),
                            $placement->getUrl()
                        );
                    } else {
                        printf(
                            "Shared criterion with ID %d was found.\n",
                            $sharedCriterion->getCriterion()->getId()
                        );
                    }

                    $criterionToRemove = new Criterion();
                    $criterionToRemove->setId(
                        $sharedCriterion->getCriterion()->getId()
                    );

                    $sharedCriterionToRemove = new SharedCriterion();
                    $sharedCriterionToRemove->setCriterion($criterionToRemove);
                    $sharedCriterionToRemove->setSharedSetId(
                        $sharedCriterion->getSharedSetId()
                    );

                    // Create an operation to remove this criterion.
                    $removeCriterionOperation = new SharedCriterionOperation();
                    $removeCriterionOperation->setOperator(Operator::REMOVE);
                    $removeCriterionOperation->setOperand($sharedCriterionToRemove);

                    $removeCriterionOperations[] = $removeCriterionOperation;
                }
            }

            // Advance the paging index.
            $selector->getPaging()->setStartIndex(
                $selector->getPaging()->getStartIndex() + self::PAGE_LIMIT
            );
        } while ($selector->getPaging()->getStartIndex() < $totalNumEntries);

        // Finally, remove the criteria.
        if (empty($removeCriterionOperations)) {
            printf("No shared criteria to remove.\n");
        } else {
            $result = $sharedCriterionService->mutate($removeCriterionOperations);
            foreach ($result->getValue() as $removedCriterion) {
                printf(
                    "Shared criterion ID %d was successfully removed from shared set ID %d.\n",
                    $removedCriterion->getCriterion()->getId(),
                    $removedCriterion->getSharedSetId()
                );
            }
        }
    }

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

FindAndRemoveCriteriaFromSharedSet::main();

Get ad group level bid modifiers

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

namespace Google\AdsApi\Examples\AdWords\v201809\AdvancedOperations;

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

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

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

    const PAGE_LIMIT = 500;

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

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

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

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

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

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

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

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

GetAdGroupBidModifiers::main();

Add a portfolio bidding strategy 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\v201809\AdvancedOperations;

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

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

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

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

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

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

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

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

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

        $biddingStrategy->setBiddingScheme($biddingScheme);

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

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

        return $newBiddingStrategy;
    }

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

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

        $operations = [];

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

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

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

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

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

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

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

        $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

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

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

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

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

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

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

UsePortfolioBiddingStrategy::main();