Shopping Campaign Samples

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

Add product partition tree

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Shopping\v201708\ProductPartitions;
use Google\AdsApi\AdWords\v201708\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201708\cm\Criterion;
use Google\AdsApi\AdWords\v201708\cm\ProductBiddingCategory;
use Google\AdsApi\AdWords\v201708\cm\ProductBrand;
use Google\AdsApi\AdWords\v201708\cm\ProductCanonicalCondition;
use Google\AdsApi\AdWords\v201708\cm\ProductCanonicalConditionCondition;
use Google\AdsApi\AdWords\v201708\cm\ProductDimensionType;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example creates a product partition tree.
 */
class AddProductPartitionTree {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

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

    // The most trivial partition tree has only a unit node as the root:
    //   $productPartitions->createBiddableUnit(null, null, 100000);

    $operations = [];
    $root = ProductPartitions::createSubdivision();
    $criterion =
        ProductPartitions::asBiddableAdGroupCriterion($adGroupId, $root);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    $newCondition = new ProductCanonicalCondition();
    $newCondition->setCondition(ProductCanonicalConditionCondition::NEW_VALUE);
    $newConditionUnit = ProductPartitions::createUnit($root, $newCondition);
    $criterion = ProductPartitions::asBiddableAdGroupCriterion(
        $adGroupId, $newConditionUnit, 200000);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    $usedCondition = new ProductCanonicalCondition();
    $usedCondition->setCondition(ProductCanonicalConditionCondition::USED);
    $usedConditionUnit = ProductPartitions::createUnit($root, $usedCondition);
    $criterion = ProductPartitions::asBiddableAdGroupCriterion(
        $adGroupId, $usedConditionUnit, 100000);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    $otherCondition = ProductPartitions::createSubdivision(
        $root, new ProductCanonicalCondition());
    $criterion = ProductPartitions::asBiddableAdGroupCriterion(
        $adGroupId, $otherCondition);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    $coolBrand = new ProductBrand();
    $coolBrand->setValue('CoolBrand');
    $coolBrandUnit = ProductPartitions::createUnit($otherCondition, $coolBrand);
    $criterion = ProductPartitions::asBiddableAdGroupCriterion(
        $adGroupId, $coolBrandUnit, 900000);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    $cheapBrand = new ProductBrand();
    $cheapBrand->setValue('CheapBrand');
    $cheapBrandUnit =
        ProductPartitions::createUnit($otherCondition, $cheapBrand);
    $criterion = ProductPartitions::asBiddableAdGroupCriterion(
        $adGroupId, $cheapBrandUnit, 10000);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    $otherBrand = ProductPartitions::createSubdivision(
        $otherCondition, new ProductBrand());
    $criterion = ProductPartitions::asBiddableAdGroupCriterion(
        $adGroupId, $otherBrand);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    // The value for the bidding category is a fixed ID for the 'Luggage & Bags'
    // category. You can retrieve IDs for categories from the
    // ConstantDataService.
    // See the 'GetProductCategoryTaxonomy' example for more details.
    $productBiddingCategory = new ProductBiddingCategory();
    $productBiddingCategory->setType(ProductDimensionType::BIDDING_CATEGORY_L1);
    $productBiddingCategory->setValue(-5914235892932915235);
    $productBiddingCategoryUnit =
        ProductPartitions::createUnit($otherBrand, $productBiddingCategory);
    $criterion = ProductPartitions::asBiddableAdGroupCriterion(
        $adGroupId, $productBiddingCategoryUnit, 750000);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    $productBiddingCategory = new ProductBiddingCategory();
    $productBiddingCategory->setType(ProductDimensionType::BIDDING_CATEGORY_L1);
    $productBiddingCategoryUnit =
        ProductPartitions::createUnit($otherBrand, $productBiddingCategory);
    $criterion = ProductPartitions::asBiddableAdGroupCriterion(
        $adGroupId, $productBiddingCategoryUnit, 110000);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    $adGroupCriterionService =
        $adWordsServices->get($session, AdGroupCriterionService::class);

    // Creates ad group criteria on the server.
    $adGroupCriterionService->mutate($operations);

    // Display the production partition tree.
    printf("%s\n", ProductPartitions::showAdGroupTree(
        $adWordsServices, $session, $adGroupId));
  }

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

AddProductPartitionTree::main();

Add product scope

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\CampaignCriterion;
use Google\AdsApi\AdWords\v201708\cm\CampaignCriterionOperation;
use Google\AdsApi\AdWords\v201708\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\AdWords\v201708\cm\ProductBiddingCategory;
use Google\AdsApi\AdWords\v201708\cm\ProductBrand;
use Google\AdsApi\AdWords\v201708\cm\ProductCanonicalCondition;
use Google\AdsApi\AdWords\v201708\cm\ProductCanonicalConditionCondition;
use Google\AdsApi\AdWords\v201708\cm\ProductCustomAttribute;
use Google\AdsApi\AdWords\v201708\cm\ProductDimensionType;
use Google\AdsApi\AdWords\v201708\cm\ProductOfferId;
use Google\AdsApi\AdWords\v201708\cm\ProductScope;
use Google\AdsApi\AdWords\v201708\cm\ProductType;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example restricts the products that will be included in the campaign by
 * setting a ProductScope.
 */
class AddProductScope {

  const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';

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

    $productScope = new ProductScope();
    // This set of dimensions is for demonstration purposes only. It would be
    // extremely unlikely that you want to include so many dimensions in your
    // product scope.
    $dimensions = [];
    $productBrand = new ProductBrand();
    $productBrand->setValue('Nexus');

    $productCanonicalCondition = new ProductCanonicalCondition();
    $productCanonicalCondition->setCondition(
        ProductCanonicalConditionCondition::NEW_VALUE);

    $productCustomAttribute = new ProductCustomAttribute();
    $productCustomAttribute->setType(ProductDimensionType::CUSTOM_ATTRIBUTE_0);
    $productCustomAttribute->setValue('my attribute value');

    $productOfferId = new ProductOfferId();
    $productOfferId->setValue('book1');

    $productType1 = new ProductType();
    $productType1->setType(ProductDimensionType::PRODUCT_TYPE_L1);
    $productType1->setValue('Media');

    $productType2 = new ProductType();
    $productType2->setType(ProductDimensionType::PRODUCT_TYPE_L2);
    $productType2->setValue('Books');

    // The value for the bidding category is a fixed ID for the 'Luggage & Bags'
    // category. You can retrieve IDs for categories from the
    // ConstantDataService.
    // See the 'GetProductCategoryTaxonomy' example for more details.
    $productBiddingCategory = new ProductBiddingCategory();
    $productBiddingCategory->setType(ProductDimensionType::BIDDING_CATEGORY_L1);
    $productBiddingCategory->setValue(-5914235892932915235);

    $productScope->setDimensions([
        $productBrand,
        $productCanonicalCondition,
        $productCustomAttribute,
        $productOfferId,
        $productType1,
        $productType2,
        $productBiddingCategory
    ]);

    $campaignCriterion = new CampaignCriterion();
    $campaignCriterion->setCampaignId($campaignId);
    $campaignCriterion->setCriterion($productScope);

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

    // Create the campaign criterion on the server and print out some
    // information.
    $campaignCrtierion =
        $campaignCriterionService->mutate($operations)->getValue()[0];
    printf("Created a ProductScope criterion with ID %d.\n",
        $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,
        intval(self::CAMPAIGN_ID));
  }
}

AddProductScope::main();

Add Shopping campaign

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\AdGroup;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupService;
use Google\AdsApi\AdWords\v201708\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201708\cm\BiddableAdGroupCriterion;
use Google\AdsApi\AdWords\v201708\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201708\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201708\cm\Budget;
use Google\AdsApi\AdWords\v201708\cm\Campaign;
use Google\AdsApi\AdWords\v201708\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201708\cm\CampaignService;
use Google\AdsApi\AdWords\v201708\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201708\cm\CpcBid;
use Google\AdsApi\AdWords\v201708\cm\Money;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\AdWords\v201708\cm\ProductAd;
use Google\AdsApi\AdWords\v201708\cm\ProductPartition;
use Google\AdsApi\AdWords\v201708\cm\ProductPartitionType;
use Google\AdsApi\AdWords\v201708\cm\ShoppingSetting;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a shopping campaign.
 */
class AddShoppingCampaign {

  const BUDGET_ID = 'INSERT_BUDGET_ID_HERE';
  const MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE';
  // If set to true, a default partition will be created. If running the
  // AddProductPartitionTree.php example right after this example, make sure
  // this stays set to false.
  const SHOULD_CREATE_DEFAULT_PARTITION = false;

  public static function runExample(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      $budgetId,
      $merchantId,
      $shouldCreateDefaultPartition
  ) {
    $campaignService = $adWordsServices->get($session, CampaignService::class);
    $adGroupService = $adWordsServices->get($session, AdGroupService::class);
    $adGroupAdService =
        $adWordsServices->get($session, AdGroupAdService::class);
    $adGroupCriterionService =
        $adWordsServices->get($session, AdGroupCriterionService::class);

    // Create a campaign with required and optional settings.
    $campaign = new Campaign();
    $campaign->setName('Shopping campaign #' . uniqid());
    // The advertisingChannelType is what makes this a Shopping campaign
    $campaign->setAdvertisingChannelType(AdvertisingChannelType::SHOPPING);
    // 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 portfolio budget (required).
    $campaign->setBudget(new Budget());
    $campaign->getBudget()->setBudgetId($budgetId);

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

    $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

    // All Shopping campaigns need a ShoppingSetting.
    $shoppingSetting = new ShoppingSetting();
    $shoppingSetting->setSalesCountry('US');
    $shoppingSetting->setCampaignPriority(0);
    $shoppingSetting->setMerchantId($merchantId);
    // Set to "true" to enable Local Inventory Ads in your campaign.
    $shoppingSetting->setEnableLocal(true);
    $campaign->setSettings([$shoppingSetting]);

    // 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.
    $campaign = $campaignService->mutate($operations)->getValue()[0];
    printf("Campaign with name '%s' and ID %d was added.\n",
        $campaign->getName(),
        $campaign->getId()
    );

    // Create ad group.
    $adGroup = new AdGroup();
    $adGroup->setCampaignId($campaign->getId());
    $adGroup->setName('Ad Group #' . uniqid());

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

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

    // Create product ad.
    $productAd = new ProductAd();

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

    // Create an ad group ad operation and add it to the operations list.
    $operations = [];
    $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.
    $adGroupAd = $adGroupAdService->mutate($operations)->getValue()[0];
    printf("Product ad with ID %d was added.\n", $adGroupAd->getAd()->getId());

    if ($shouldCreateDefaultPartition) {
      $operation =
          self::createDefaultPartitionOperation($adGroup->getId(), 500000);
      $adGroupCriterion =
          $adGroupCriterionService->mutate([$operation])->getValue()[0];
      printf(
          "Ad group criterion with ID %d in ad group with ID %d was added.\n",
          $adGroupCriterion->getCriterion()->getId(),
          $adGroupCriterion->getAdGroupId()
      );
    }
  }

  private static function createDefaultPartitionOperation(
      $adGroupId, $bidAmount) {
    // Creates an ad group criterion for 'All products'.
    $productPartition = new ProductPartition();
    $productPartition->setPartitionType(ProductPartitionType::UNIT);
    // Make sure the caseValue is null and the parentCriterionId is null.
    $productPartition->setParentCriterionId(null);
    $productPartition->setCaseValue(null);

    // Creates a biddable ad group criterion.
    $criterion = new BiddableAdGroupCriterion();
    $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
    $cpcBid = new CpcBid();
    $money = new Money();
    $money->setMicroAmount($bidAmount);
    $cpcBid->setBid($money);
    $biddingStrategyConfiguration->setBids([$cpcBid]);

    $criterion->setBiddingStrategyConfiguration($biddingStrategyConfiguration);
    $criterion->setAdGroupId($adGroupId);
    $criterion->setCriterion($productPartition);

    // Creates an ad group criterion operation.
    $operation = new AdGroupCriterionOperation();
    $operation->setOperand($criterion);
    $operation->setOperator(Operator::ADD);

    return $operation;
  }

  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),
        boolval(self::SHOULD_CREATE_DEFAULT_PARTITION)
    );
  }
}

AddShoppingCampaign::main();

Add campaign for Showcase Shopping ads

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Shopping\v201708\ProductPartitions;
use Google\AdsApi\AdWords\v201708\cm\AdGroup;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201708\cm\AdGroupService;
use Google\AdsApi\AdWords\v201708\cm\AdGroupType;
use Google\AdsApi\AdWords\v201708\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201708\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201708\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201708\cm\Budget;
use Google\AdsApi\AdWords\v201708\cm\Campaign;
use Google\AdsApi\AdWords\v201708\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201708\cm\CampaignService;
use Google\AdsApi\AdWords\v201708\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201708\cm\CpcBid;
use Google\AdsApi\AdWords\v201708\cm\Image;
use Google\AdsApi\AdWords\v201708\cm\MediaMediaType;
use Google\AdsApi\AdWords\v201708\cm\MediaService;
use Google\AdsApi\AdWords\v201708\cm\Money;
use Google\AdsApi\AdWords\v201708\cm\Operator;
use Google\AdsApi\AdWords\v201708\cm\ProductCanonicalCondition;
use Google\AdsApi\AdWords\v201708\cm\ProductCanonicalConditionCondition;
use Google\AdsApi\AdWords\v201708\cm\ShoppingSetting;
use Google\AdsApi\AdWords\v201708\cm\ShowcaseAd;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a Shopping campaign for Showcase ads.
 */
class AddShoppingCampaignForShowcaseAds {

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

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $budgetId, $merchantId) {
    $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::createShowcaseAd($adWordsServices, $session, $adGroup);
    printf("Showcase ad with ID %d was added.\n", $adGroupAd->getAd()->getId());

    self::createProductPartitions(
        $adWordsServices, $session, $adGroup->getId());
    printf(
        "Product partition tree is:\n%s\n",
        ProductPartitions::showAdGroupTree(
            $adWordsServices, $session, $adGroup->getId())
    );
  }

  /** Creates a Shopping 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());
    // The advertisingChannelType is what makes this a Shopping campaign.
    $campaign->setAdvertisingChannelType(AdvertisingChannelType::SHOPPING);

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

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

    // All Shopping campaigns need a ShoppingSetting.
    $shoppingSetting = new ShoppingSetting();
    $shoppingSetting->setSalesCountry('US');
    $shoppingSetting->setCampaignPriority(0);
    $shoppingSetting->setMerchantId($merchantId);

    // Set to 'true' to enable Local Inventory Ads in your campaign.
    $shoppingSetting->setEnableLocal(true);

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

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

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

    return $campaign;
  }

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

    // Create ad group.
    $adGroup = new AdGroup();
    $adGroup->setCampaignId($campaign->getId());
    $adGroup->setName('Ad Group #' . uniqid());

    // Required: Set the ad group type to SHOPPING_SHOWCASE_ADS.
    $adGroup->setAdGroupType(AdGroupType::SHOPPING_SHOWCASE_ADS);

    // Required: Set the ad group's bidding strategy configuration.
    // Note: Showcase ads require either ManualCpc or EnhancedCpc in the
    // campaign's BiddingStrategyConfiguration.
    $biddingStrategyConfiguration = new BiddingStrategyConfiguration();

    // Optional: Set the bids.
    $bidAmount = new Money();
    $bidAmount->setMicroAmount(100000);
    $cpcBid = new CpcBid();
    $cpcBid->setBid($bidAmount);
    $biddingStrategyConfiguration->setBids([$cpcBid]);

    $adGroup->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

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

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

    return $adGroup;
  }

  /** Creates a Showcase ad. */
  private static function createShowcaseAd(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      AdGroup $adGroup
  ) {
    // Create the Showcase ad.
    $adGroupAdService =
        $adWordsServices->get($session, AdGroupAdService::class);

    $showcaseAd = new ShowcaseAd();
    $showcaseAd->setName('Showcase ad #' . uniqid());
    $showcaseAd->setFinalUrls(['http://example.com/showcase']);
    $showcaseAd->setDisplayUrl('example.com');

    // Required: Set the ad's expanded image.
    $expandedImage = new Image();
    $expandedImage->setMediaId(self::uploadImage(
        $adWordsServices,
        $session,
        'https://goo.gl/IfVlpF'
    ));
    $showcaseAd->setExpandedImage($expandedImage);

    // Optional: Set the collapsed image.
    $collapsedImage = new Image();
    $collapsedImage->setMediaId(self::uploadImage(
        $adWordsServices,
        $session,
        'https://goo.gl/NqTxAE'
    ));
    $showcaseAd->setCollapsedImage($collapsedImage);

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

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

  /** Creates the product partition tree for the ad group. */
  private static function createProductPartitions(
      AdWordsServices $adWordsServices, AdWordsSession $session, $adGroupId) {
    $adGroupCriterionService =
        $adWordsServices->get($session, AdGroupCriterionService::class);

    $operations = [];

    $root = ProductPartitions::createSubdivision();
    $criterion =
        ProductPartitions::asBiddableAdGroupCriterion($adGroupId, $root);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    $newCondition = new ProductCanonicalCondition();
    $newCondition->setCondition(ProductCanonicalConditionCondition::NEW_VALUE);
    $newConditionUnit = ProductPartitions::createUnit($root, $newCondition);
    $criterion = ProductPartitions::asBiddableAdGroupCriterion(
        $adGroupId, $newConditionUnit);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    $usedCondition = new ProductCanonicalCondition();
    $usedCondition->setCondition(ProductCanonicalConditionCondition::USED);
    $usedConditionUnit = ProductPartitions::createUnit($root, $usedCondition);
    $criterion = ProductPartitions::asBiddableAdGroupCriterion(
        $adGroupId, $usedConditionUnit);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    // Exclude everything else.
    $excludedUnit =
        ProductPartitions::createUnit($root, new ProductCanonicalCondition());
    $criterion = ProductPartitions::asNegativeAdGroupCriterion(
        $adGroupId, $excludedUnit);
    $operation = ProductPartitions::createAddOperation($criterion);
    $operations[] = $operation;

    $adGroupCriterionService =
        $adWordsServices->get($session, AdGroupCriterionService::class);

    // Creates ad group criteria on the server.
    $adGroupCriterionService->mutate($operations);
  }

  /** Uploads an image. */
  private static function uploadImage(AdWordsServices $adWordsServices,
      AdWordsSession $session, $url) {
    $mediaService = $adWordsServices->get($session, MediaService::class);

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

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

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

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

AddShoppingCampaignForShowcaseAds::main();

Get product category taxonomy

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\ConstantDataService;
use Google\AdsApi\AdWords\v201708\cm\Predicate;
use Google\AdsApi\AdWords\v201708\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201708\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example fetches the set of valid `ProductBiddingCategory`.
 */
class GetProductCategoryTaxonomy {

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

    // Create a selector to select product bidding categories in US.
    $selector = new Selector();
    $selector->setPredicates(
        [new Predicate('Country', PredicateOperator::IN, ['US'])]);

    // A mapping from ID to bidding category.
    $biddingCategories = [];
    // An array of root bidding categories (those that don't have any parents).
    $rootCategories = [];

    $productBiddingCategories =
        $constantDataService->getProductBiddingCategoryData($selector);
    foreach ($productBiddingCategories as $productBiddingCategory) {
      $id = $productBiddingCategory->getDimensionValue()->getvalue();
      $name = $productBiddingCategory->getDisplayValue()[0]->getvalue();
      $parentId = ($productBiddingCategory->getParentDimensionValue() !== null)
          ? $productBiddingCategory->getParentDimensionValue()->getvalue()
          : null;

      if (array_key_exists($id, $biddingCategories) === false) {
        $biddingCategories[$id] = [
            'children' => []
        ];
      }
      $biddingCategories[$id]['id'] = $id;
      $biddingCategories[$id]['name'] = $name;

      if ($parentId !== null) {
        if (array_key_exists($parentId, $biddingCategories) === false) {
          // 'id' and 'name' of $biddingCategories[$parentId] will get
          // populated in its iteration of this loop.
          $biddingCategories[$parentId] = [
              'children' => []
          ];
        }
        $biddingCategories[$parentId]['children'][] = $biddingCategories[$id];
      } else {
        $rootCategories[] = $biddingCategories[$id];
      }
    }

    self::displayCategories($rootCategories, '');
  }

  private static function displayCategories(array $categories, $prefix) {
    foreach ($categories as $category) {
      printf("%s%s [%s]\n", $prefix, $category['name'], $category['id']);
      if (count($category['children']) > 0) {
        self::displayCategories($category['children'],
            sprintf('%s%s > ', $prefix, $category['name']));
      }
    }
  }

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

GetProductCategoryTaxonomy::main();

Send feedback about...

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