Shopping Campaign Samples

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

Add product partition tree

New

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Shopping\v201705\ProductPartitions;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201705\cm\Criterion;
use Google\AdsApi\AdWords\v201705\cm\ProductBiddingCategory;
use Google\AdsApi\AdWords\v201705\cm\ProductBrand;
use Google\AdsApi\AdWords\v201705\cm\ProductCanonicalCondition;
use Google\AdsApi\AdWords\v201705\cm\ProductCanonicalConditionCondition;
use Google\AdsApi\AdWords\v201705\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();

Old

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

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

$adGroupId = 'INSERT_AD_GROUP_ID_HERE';

/**
 * A helper for creating ProductPartition trees
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 */
class ProductPartitionHelper {
  /**
   * The next temporary criterion ID to be used.
   *
   * When creating our tree we need to specify the parent-child relationships
   * between nodes. However, until a criterion has been created on the server
   * we do not have a criterionId with which to refer to it.
   *
   * Instead we can specify temporary IDs that are specific to a single mutate
   * request. Once the criteria have been created they are assigned an ID as
   * normal and the temporary ID will no longer refer to it.
   *
   * A valid temporary ID is any negative integer.
   * @var integer
   */
  private $nextId = -1;

  /**
   * The set of mutate operations needed to create the current tree.
   * @var array
   */
  private $operations = array();

  /**
   * The ID of the AdGroup that we wish to attach the partition tree to.
   * @var int
   */
  private $adGroupId;

  /**
   * Constructor
   * @param int $adGroupId The ID of the AdGroup that we wish to attach the
   *                       partition tree to.
   */
  public function __construct($adGroupId) {
    $this->adGroupId = $adGroupId;
  }

  /**
   * Creates a subdivision node
   * @param  ProductPartition $parent The node that should be this node's parent
   * @param  ProductDimension $value The value being partitioned on
   * @return ProductPartition A new subdivision node
   */
  public function createSubdivision(ProductPartition $parent = null,
      ProductDimension $value = null) {
    $division = new ProductPartition('SUBDIVISION');
    $division->id = $this->nextId--;

    // The root node has neither a parent nor a value
    if (!is_null($parent)) {
      $division->parentCriterionId = $parent->id;
      $division->caseValue = $value;
    }

    $criterion = new BiddableAdGroupCriterion();
    $criterion->adGroupId = $this->adGroupId;
    $criterion->criterion = $division;

    $this->createAddOperation($criterion);

    return $division;
  }

  /**
   * Creates a unit node.
   * @param  ProductPartition $parent The node that should be this node's parent
   * @param  ProductDimension $value The value being partitioned on
   * @param  int $bid_amount The amount to bid for matching products, in micros
   * @return ProductPartition A new unit node
   */
  public function createUnit(ProductPartition $parent = null,
      ProductDimension $value = null, $bid_amount = null) {
    $unit = new ProductPartition('UNIT');

    // The root node has neither a parent nor a value
    if (!is_null($parent)) {
      $unit->parentCriterionId = $parent->id;
      $unit->caseValue = $value;
    }

    if (!is_null($bid_amount) && $bid_amount > 0) {
      $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
      $biddingStrategyConfiguration->bids = array();
      $cpcBid = new CpcBid();
      $cpcBid->bid = new Money($bid_amount);
      $biddingStrategyConfiguration->bids[] = $cpcBid;

      $criterion = new BiddableAdGroupCriterion();
      $criterion->biddingStrategyConfiguration = $biddingStrategyConfiguration;
    } else {
      $criterion = new NegativeAdGroupCriterion();
    }

    $criterion->adGroupId = $this->adGroupId;
    $criterion->criterion = $unit;

    $this->createAddOperation($criterion);

    return $unit;
  }

  /**
   * Returns the set of mutate operations needed to create the current tree.
   * @return array The set of operations
   */
  public function getOperations() {
    return $this->operations;
  }

  /**
   * Creates an AdGroupCriterionOperation for the given criterion
   * @param  AdGroupCriterion $criterion The criterion we want to add
   */
  private function createAddOperation(AdGroupCriterion $criterion) {
    $operation = new AdGroupCriterionOperation();
    $operation->operand = $criterion;
    $operation->operator = 'ADD';
    $this->operations[] = $operation;
  }
}

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param int $adGroupId the ad group to add the tree to
 */
function addProductPartitionTreeExample(AdWordsUser $user, $adGroupId) {
  // Get the AdGroupCriterionService, which loads the required classes.
  $adGroupCriterionService = $user->GetService('AdGroupCriterionService',
        ADWORDS_VERSION);

  $helper = new ProductPartitionHelper($adGroupId);

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

  $root = $helper->createSubdivision();

  $helper->createUnit($root, new ProductCanonicalCondition('NEW'), 200000);
  $helper->createUnit($root, new ProductCanonicalCondition('USED'), 100000);
  $otherCondition = $helper->createSubdivision($root,
      new ProductCanonicalCondition());

  $helper->createUnit($otherCondition, new ProductBrand('CoolBrand'), 900000);
  $helper->createUnit($otherCondition, new ProductBrand('CheapBrand'), 10000);
  $otherBrand =
      $helper->createSubdivision($otherCondition, new ProductBrand());

  // 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.
  $helper->createUnit($otherBrand,
      new ProductBiddingCategory('BIDDING_CATEGORY_L1',
      '-5914235892932915235'), 750000);
  $helper->createUnit($otherBrand,
      new ProductBiddingCategory('BIDDING_CATEGORY_L1'), 110000);

  // Make the mutate request.
  $result = $adGroupCriterionService->mutate($helper->getOperations());

  $children = array();
  $rootNode = null;
  // For each criterion, make an array containing each of its children
  // We always create the parent before the child, so we can rely on that here
  foreach ($result->value as $adGroupCriterion) {
    $children[$adGroupCriterion->criterion->id] = array();

    if (isset($adGroupCriterion->criterion->parentCriterionId)) {
      $children[$adGroupCriterion->criterion->parentCriterionId][] =
          $adGroupCriterion->criterion;
    } else {
      $rootNode = $adGroupCriterion->criterion;
    }
  }

  // Show the tree
  displayTree($rootNode, $children);
}

function displayTree($node, $children, $level = 0) {
  // Recursively display a node and each of its children
  $value = "";
  $type = "";

  if (isset($node->caseValue)) {
    $type = $node->caseValue->ProductDimensionType;
    switch ($type) {
      case 'ProductCanonicalCondition':
        $value = $node->caseValue->condition;
        break;

      case 'ProductBiddingCategory':
        $value = $node->caseValue->type . "(" . $node->caseValue->value . ")";
        break;

      default:
        $value = $node->caseValue->value;
        break;
    }
  }

  printf("%sid: %s, type: %s, value: %s\n", str_repeat("  ", $level),
      $node->id, $type, $value);
  foreach ($children[$node->id] as $childNode) {
    displayTree($childNode, $children, $level + 1);
  }
}

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

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

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

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

Add product scope

New

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterion;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\ProductBiddingCategory;
use Google\AdsApi\AdWords\v201705\cm\ProductBrand;
use Google\AdsApi\AdWords\v201705\cm\ProductCanonicalCondition;
use Google\AdsApi\AdWords\v201705\cm\ProductCanonicalConditionCondition;
use Google\AdsApi\AdWords\v201705\cm\ProductCustomAttribute;
use Google\AdsApi\AdWords\v201705\cm\ProductDimensionType;
use Google\AdsApi\AdWords\v201705\cm\ProductOfferId;
use Google\AdsApi\AdWords\v201705\cm\ProductScope;
use Google\AdsApi\AdWords\v201705\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();

Old

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

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

$campaignId = 'INSERT_CAMPAIGN_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param int $campaignId the campaign to modify
 */
function addProductScopeExample(AdWordsUser $user, $campaignId) {
  // Get the CampaignCriterionService, which loads the required classes.
  $campaignCriterionService = $user->GetService('CampaignCriterionService',
        ADWORDS_VERSION);

  $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.
  $productScope->dimensions[] = new ProductBrand('Nexus');
  $productScope->dimensions[] = new ProductCanonicalCondition('NEW');
  $productScope->dimensions[] =
      new ProductCustomAttribute('CUSTOM_ATTRIBUTE_0', 'my attribute value');
  $productScope->dimensions[] = new ProductOfferId('book1');
  $productScope->dimensions[] = new ProductType('PRODUCT_TYPE_L1', 'Media');
  $productScope->dimensions[] = new ProductType('PRODUCT_TYPE_L2', '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.
  $productScope->dimensions[] =
      new ProductBiddingCategory('BIDDING_CATEGORY_L1', '-5914235892932915235');

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

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

  // Make the mutate request.
  $result = $campaignCriterionService->mutate(array($operation));

  printf("Created a ProductScope criterion with ID '%s'",
        $result->value[0]->criterion->id);
}

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

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

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

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

Add Shopping campaign

New

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\AdGroup;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupService;
use Google\AdsApi\AdWords\v201705\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201705\cm\BiddableAdGroupCriterion;
use Google\AdsApi\AdWords\v201705\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201705\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201705\cm\Budget;
use Google\AdsApi\AdWords\v201705\cm\Campaign;
use Google\AdsApi\AdWords\v201705\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignService;
use Google\AdsApi\AdWords\v201705\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201705\cm\CpcBid;
use Google\AdsApi\AdWords\v201705\cm\Money;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\ProductAd;
use Google\AdsApi\AdWords\v201705\cm\ProductPartition;
use Google\AdsApi\AdWords\v201705\cm\ProductPartitionType;
use Google\AdsApi\AdWords\v201705\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();

Old

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

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

$budgetId = 'INSERT_BUDGET_ID_HERE';
$merchantId = 'INSERT_MERCHANT_CENTER_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param int $budgetId the ID of a portfolio budget to use for the campaign
 * @param int $merchantId the Merchant Center account ID to use for product data
 */
function addShoppingCampaignExample(AdWordsUser $user, $budgetId, $merchantId) {
  // Get the services, which loads the required classes.
  $campaignService = $user->GetService('CampaignService', ADWORDS_VERSION);
  $adGroupService = $user->GetService('AdGroupService', ADWORDS_VERSION);
  $adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);

  // Create campaign.
  $campaign = new Campaign();
  $campaign->name = 'Shopping campaign #' . uniqid();
  // The advertisingChannelType is what makes this a Shopping campaign
  $campaign->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->status = 'PAUSED';

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

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

  $campaign->biddingStrategyConfiguration = $biddingStrategyConfiguration;

  // All Shopping campaigns need a ShoppingSetting.
  $shoppingSetting = new ShoppingSetting();
  $shoppingSetting->salesCountry = 'US';
  $shoppingSetting->campaignPriority = 0;
  $shoppingSetting->merchantId = $merchantId;
  // Set to "true" to enable Local Inventory Ads in your campaign.
  $shoppingSetting->enableLocal = true;
  $campaign->settings[] = $shoppingSetting;

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

  // Make the mutate request.
  $result = $campaignService->mutate(array($operation));

  // Display result.
  $campaign = $result->value[0];
  printf("Campaign with name '%s' and ID '%s' was added.\n", $campaign->name,
        $campaign->id);

  // Create ad group.
  $adGroup = new AdGroup();
  $adGroup->campaignId = $campaign->id;
  $adGroup->name = 'Ad Group #' . uniqid();

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

  // Make the mutate request.
  $result = $adGroupService->mutate(array($operation));

  // Display result.
  $adGroup = $result->value[0];
  printf("Ad group with name '%s' and ID '%s' was added.\n", $adGroup->name,
        $adGroup->id);

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

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

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

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

  // Display result.
  $adGroupAd = $result->value[0];
  printf("Product ad with ID '%s' was added.\n", $adGroupAd->ad->id);
}

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

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

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

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

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\v201705\ShoppingCampaigns;

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Shopping\v201705\ProductPartitions;
use Google\AdsApi\AdWords\v201705\cm\AdGroup;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201705\cm\AdGroupService;
use Google\AdsApi\AdWords\v201705\cm\AdGroupType;
use Google\AdsApi\AdWords\v201705\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201705\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201705\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201705\cm\Budget;
use Google\AdsApi\AdWords\v201705\cm\Campaign;
use Google\AdsApi\AdWords\v201705\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignService;
use Google\AdsApi\AdWords\v201705\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201705\cm\CpcBid;
use Google\AdsApi\AdWords\v201705\cm\Image;
use Google\AdsApi\AdWords\v201705\cm\MediaMediaType;
use Google\AdsApi\AdWords\v201705\cm\MediaService;
use Google\AdsApi\AdWords\v201705\cm\Money;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\ProductCanonicalCondition;
use Google\AdsApi\AdWords\v201705\cm\ProductCanonicalConditionCondition;
use Google\AdsApi\AdWords\v201705\cm\ShoppingSetting;
use Google\AdsApi\AdWords\v201705\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

New

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

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

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

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

Old

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

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

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

  $selector = new Selector();
  $selector->predicates[] = new Predicate('Country', 'IN', array('US'));

  $results = $constantDataService->getProductBiddingCategoryData($selector);

  $biddingCategories = array();
  $rootCategories = array();

  foreach ($results as $productBiddingCategory) {
    $id = $productBiddingCategory->dimensionValue->value;
    $parentId = null;
    $name = $productBiddingCategory->displayValue[0]->value;

    if ($productBiddingCategory->parentDimensionValue) {
      $parentId = $productBiddingCategory->parentDimensionValue->value;
    }

    if (!isset($biddingCategories[$id])) {
      $biddingCategories[$id] = new StdClass();
    }

    $category = $biddingCategories[$id];

    if ($parentId) {
      if (!isset($biddingCategories[$parentId])) {
        $biddingCategories[$parentId] = new StdClass();
      }
      $parent = $biddingCategories[$parentId];
      if (!isset($parent->children)) {
        $parent->children = array();
      }
      $parent->children[] = $category;
    } else {
      $rootCategories[] = $category;
    }

    $category->id = $id;
    $category->name = $name;
  }

  displayCategories($rootCategories);
}

function displayCategories($categories, $prefix = "") {
  foreach ($categories as $category) {
    printf("%s%s [%s]\n", $prefix, $category->name, $category->id);
    if (isset($category->children)) {
      displayCategories($category->children, "{$prefix}{$category->name} > ");
    }
  }
}

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

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

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

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

Send feedback about...

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