Remarketing Samples

The code samples below provide examples of common remarketing functions using the AdWords API. Client Library.

Add audience

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

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\ConversionTrackerService;
use Google\AdsApi\AdWords\v201705\cm\Predicate;
use Google\AdsApi\AdWords\v201705\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\Selector;
use Google\AdsApi\AdWords\v201705\rm\AdwordsUserListService;
use Google\AdsApi\AdWords\v201705\rm\BasicUserList;
use Google\AdsApi\AdWords\v201705\rm\UserListConversionType;
use Google\AdsApi\AdWords\v201705\rm\UserListMembershipStatus;
use Google\AdsApi\AdWords\v201705\rm\UserListOperation;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a new remarketing list audience to the account and
 * retrieves the associated remarketing tag code.
 */
class AddAudience {

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $userListService =
        $adWordsServices->get($session, AdwordsUserListService::class);
    $conversionTrackerService =
        $adWordsServices->get($session, ConversionTrackerService::class);

    // Create a conversion type (tag).
    $conversionType = new UserListConversionType();
    $conversionType->setName('Mars cruise customers #' . uniqid());

    // Create a basic user list.
    $userList = new BasicUserList();
    $userList->setName('Mars cruise customers #' . uniqid());
    $userList->setConversionTypes([$conversionType]);

    // Set additional settings (optional).
    $userList->setDescription(
        'A list of mars cruise customers in the last year');
    $userList->setStatus(UserListMembershipStatus::OPEN);
    $userList->setMembershipLifeSpan(365);

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

    // Create the user list on the server.
    $userList = $userListService->mutate($operations)->getValue()[0];

    // Create the selector.
    $selector = new Selector();
    $selector->setFields(['Id']);
    $selector->setPredicates(
        [new Predicate('Id', PredicateOperator::IN,
            [$userList->getConversionTypes()[0]->getId()])]);

    // Retrieve the conversion tracker and print out its information.
    $conversionTracker =
        $conversionTrackerService->get($selector)->getEntries()[0];
    printf("Audience with name '%s' and ID %d was added.\n",
        $userList->getName(), $userList->getId());
    printf("Conversion tracker snippet:\n%s\n",
        $conversionTracker->getSnippet());
  }

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

AddAudience::main();

Old

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

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

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 */
function AddAudienceExample(AdWordsUser $user) {
  // Get the services, which loads the required classes.
  $userListService = $user->GetService('AdwordsUserListService', ADWORDS_VERSION);
  $conversionTrackerService =
      $user->GetService('ConversionTrackerService', ADWORDS_VERSION);

  // Create conversion type (tag).
  $conversionType = new UserListConversionType();
  $conversionType->name = 'Mars cruise customers #' . uniqid();

  // Create remarketing user list.
  $userList = new BasicUserList();
  $userList->name = 'Mars cruise customers #' . uniqid();
  $userList->conversionTypes = array($conversionType);

  // Set additional settings (optional).
  $userList->description = 'A list of mars cruise customers in the last year';
  $userList->status = 'OPEN';
  $userList->membershipLifeSpan = 365;

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

  $operations = array($operation);

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

  // Wait a moment before retrieving the conversion snippet.
  sleep(1);

  // Create the selector.
  $selector = new Selector();
  $selector->fields = array('Id');
  $selector->predicates[] =
      new Predicate('Id', 'IN', array($userList->conversionTypes[0]->id));

  // Make the get request.
  $page = $conversionTrackerService->get($selector);
  $conversionTracker = $page->entries[0];

  // Display result.
  printf("Audience with name '%s' and ID '%.0f' was added.\n", $userList->name,
      $userList->id);
  printf("Tag code:\n%s\n", $conversionTracker->snippet);
}

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

Add conversion tracker

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

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\AdWordsConversionTracker;
use Google\AdsApi\AdWords\v201705\cm\AdWordsConversionTrackerTextFormat;
use Google\AdsApi\AdWords\v201705\cm\ConversionTrackerCategory;
use Google\AdsApi\AdWords\v201705\cm\ConversionTrackerOperation;
use Google\AdsApi\AdWords\v201705\cm\ConversionTrackerService;
use Google\AdsApi\AdWords\v201705\cm\ConversionTrackerStatus;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a new conversion type to the account.
 */
class AddConversionTracker {

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

    // Create a conversion tracker.
    $conversionTracker = new AdWordsConversionTracker();
    $conversionTracker->setName(
        'Interplanetary Cruise Conversion #' . uniqid());

    // Set additional settings (optional).
    $conversionTracker->setStatus(ConversionTrackerStatus::ENABLED);
    $conversionTracker->setCategory(ConversionTrackerCategory::DEFAULT_VALUE);
    $conversionTracker->setViewthroughLookbackWindow(15);
    $conversionTracker->setTextFormat(
        AdWordsConversionTrackerTextFormat::HIDDEN);
    $conversionTracker->setConversionPageLanguage('en');
    $conversionTracker->setBackgroundColor('#0000FF');

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

    // Create the conversion tracker on the server and print out some
    // information.
    $conversionTracker =
        $conversionTrackerService->mutate($operations)->getValue()[0];
    printf("Conversion type with name '%s' and ID %d was added.\n",
        $conversionTracker->getName(), $conversionTracker->getId());
    printf("Conversion tracker snippet:\n%s\n",
        $conversionTracker->getSnippet());
  }

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

AddConversionTracker::main();

Old

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

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

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

  // Create conversion tracker.
  $conversionTracker = new AdWordsConversionTracker();
  $conversionTracker->name = 'Interplanetary Cruise Conversion #' . uniqid();

  // Set additional settings (optional).
  $conversionTracker->status = 'ENABLED';
  $conversionTracker->category = 'DEFAULT';
  $conversionTracker->viewthroughLookbackWindow = 15;
  $conversionTracker->textFormat = 'HIDDEN';
  $conversionTracker->conversionPageLanguage = 'en';
  $conversionTracker->backgroundColor = '#0000FF';

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

  $operations = array($operation);

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

  // Display result.
  $conversionTracker = $result->value[0];
  printf("Conversion type with name '%s' and ID '%.0f' was added.\n",
      $conversionTracker->name, $conversionTracker->id);
  printf("Tag code:\n%s\n", $conversionTracker->snippet);
}

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

Add CRM-based user list

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

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

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\rm\AddressInfo;
use Google\AdsApi\AdWords\v201705\rm\AdwordsUserListService;
use Google\AdsApi\AdWords\v201705\rm\CrmBasedUserList;
use Google\AdsApi\AdWords\v201705\rm\Member;
use Google\AdsApi\AdWords\v201705\rm\MutateMembersOperand;
use Google\AdsApi\AdWords\v201705\rm\MutateMembersOperandDataType;
use Google\AdsApi\AdWords\v201705\rm\MutateMembersOperation;
use Google\AdsApi\AdWords\v201705\rm\UserListOperation;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds a user list (a.k.a. audience) and uploads members to
 * populate the list.
 *
 * <p><em>Note:</em> It may take up to several hours for the list to be
 * populated with members.
 * Email addresses must be associated with a Google account.
 * For privacy purposes, the user list size will show as zero until the list has
 * at least 1,000 members. After that, the size will be rounded to the two most
 * significant digits.
 */
class AddCrmBasedUserList {

  private static $EMAILS = ['customer1@example.com', 'customer2@example.com',
      ' Client3@example.com '];

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, array $emails) {
    $userListService =
        $adWordsServices->get($session, AdwordsUserListService::class);

    // Create a CRM based user list.
    $userList = new CrmBasedUserList();
    $userList->setName('Customer relationship management list #' . uniqid());
    $userList->setDescription(
        'A list of customers that originated from email addresses');

    // Maximum life span is 180 days.
    $userList->setMembershipLifeSpan(180);

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

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

    // Create operation to add members to the user list based on email
    // addresses.
    $mutateMembersOperations = [];
    $mutateMembersOperation = new MutateMembersOperation();
    $operand = new MutateMembersOperand();
    $operand->setUserListId($userList->getId());

    $members = [];
    // Hash normalized email addresses based on SHA-256 hashing algorithm.
    foreach ($emails as $email) {
      $memberByEmail = new Member();
      $memberByEmail->setHashedEmail(self::normalizeAndHash($email));
      $members[] = $memberByEmail;
    }

    // Adding address info is currently available on a whitelist-only basis.
    // This code demonstrates how to do it, and you can uncomment it if you are
    // on the whitelist.
    /*
    $firstName = 'John';
    $lastName = 'Doe';
    $countryCode = 'US';
    $zipCode = '10011';

    $addressInfo = new AddressInfo();
    // First and last name must be normalized and hashed.
    $addressInfo->setHashedFirstName(self::normalizeAndHash($firstName));
    $addressInfo->setHashedLastName(self::normalizeAndHash($lastName));
    // Country code and zip code are sent in plain text.
    $addressInfo->setCountryCode($countryCode);
    $addressInfo->setZipCode($zipCode);

    $memberByAddress = new Member();
    $memberByAddress->setAddressInfo($addressInfo);
    $members[] = $memberByAddress;
     */

    // Add members to the operand and add the operation to the list.
    $operand->setMembersList($members);
    $mutateMembersOperation->setOperand($operand);
    $mutateMembersOperation->setOperator(Operator::ADD);
    $mutateMembersOperations[] = $mutateMembersOperation;

    // Add members to the user list based on email addresses.
    $result = $userListService->mutateMembers($mutateMembersOperations);

    // Print out some information about the added user list.
    // Reminder: it may take several hours for the list to be populated with
    // members.
    foreach ($result->getUserLists() as $userList) {
      printf(
          "%d email addresses were uploaded to user list with name '%s' and ID"
              . " %d and are scheduled for review.\n",
          count($emails),
          $userList->getName(),
          $userList->getId()
      );
    }
  }

  private static function normalizeAndHash($value) {
    return hash('sha256', strtolower(trim($value)));
  }

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

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

AddCrmBasedUserList::main();

Old

<?php
/**
 * This example adds a user list (a.k.a. audience) and uploads members to
 * populate the list.
 *
 * <p>
 * <em>Note:</em> It may take up to several hours for the list to be populated
 * with members.
 * Email addresses must be associated with a Google account.
 * For privacy purposes, the user list size will show as zero until the list has
 * at least 1,000 members. After that, the size will be rounded to the two most
 * significant digits.
 * </p>
 *
 * PHP version 5
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

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

$EMAILS = array('customer1@example.com', 'customer2@example.com',
    'Client3@example.com ');

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param array $EMAILS a list of member emails to be added to a user list
 */
function AddCrmBasedUserList(AdWordsUser $user, array $EMAILS) {
  // Get the services, which loads the required classes.
  $userListService = $user->GetService('AdwordsUserListService',
      ADWORDS_VERSION);

  // Create a user list.
  $userList = new CrmBasedUserList();
  $userList->name = 'Customer relationship management list #' . uniqid();
  $userList->description =
      'A list of customers that originated from email addresses';

  // Maximum life span is 180 days.
  $userList->membershipLifeSpan = 180;

  // Create operations to add the user list.
  $operation = new UserListOperation();
  $operation->operand = $userList;
  $operation->operator = 'ADD';

  $operations = array($operation);

  // Add user list.
  $result = $userListService->mutate($operations);

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

  // Get a user list ID.
  $userListId = $userListAdded->id;

  $mutateMembersOperations = array();
  // Create operation to add members to the user list based on email addresses.
  $mutateMembersOperation = new MutateMembersOperation();
  $operand = new MutateMembersOperand();
  $operand->userListId = $userListId;

  $members = array();
  // Hash normalized email addresses based on SHA-256 hashing algorithm.
  foreach ($EMAILS as $email) {
    $memberByEmail = new Member();
    $memberByEmail->hashedEmail = normalizeAndHash($email);
    $members[] = $memberByEmail;
  }

  // Adding address info is currently available on a whitelist-only basis.
  // This code demonstrates how to do it, and you can uncomment it if you are on
  // the whitelist.
  /*
  $firstName = 'John';
  $lastName = 'Doe';
  $countryCode = 'US';
  $zipCode = '10011';

  $addressInfo = new AddressInfo();
  // First and last name must be normalized and hashed.
  $addressInfo->hashedFirstName = normalizeAndHash($firstName);
  $addressInfo->hashedLastName = normalizeAndHash($lastName);
  // Country code and zip code are sent in plain text.
  $addressInfo->countryCode = $countryCode;
  $addressInfo->zipCode = $zipCode;

  $memberByAddress = new Member();
  $memberByAddress->addressInfo = $addressInfo;
  $members[] = $memberByAddress;
  */

  // Add members to the operand and add the operation to the list.
  $operand->membersList = $members;
  $mutateMembersOperation->operand = $operand;
  $mutateMembersOperation->operator = 'ADD';
  $mutateMembersOperations[] = $mutateMembersOperation;

  // Add members to the user list based on email addresses.
  $mutateMembersResult =
      $userListService->mutateMembers($mutateMembersOperations);

  // Display results.
  // Reminder: it may take several hours for the list to be populated with
  //     members.
  foreach ($mutateMembersResult->userLists as $userListResult) {
    printf(
        "%d email addresses were uploaded to user list with name '%s' and ID"
            . " '%d' and are scheduled for review.\n",
        count($EMAILS),
        $userListResult->name,
        $userListResult->id
    );
  }
}

function normalizeAndHash($value) {
  return hash('sha256', strtolower(trim($value)));
}

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

Add rule-based user list

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

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

use DateTime;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\rm\AdwordsUserListService;
use Google\AdsApi\AdWords\v201705\rm\DateKey;
use Google\AdsApi\AdWords\v201705\rm\DateRuleItem;
use Google\AdsApi\AdWords\v201705\rm\DateRuleItemDateOperator;
use Google\AdsApi\AdWords\v201705\rm\DateSpecificRuleUserList;
use Google\AdsApi\AdWords\v201705\rm\ExpressionRuleUserList;
use Google\AdsApi\AdWords\v201705\rm\NumberKey;
use Google\AdsApi\AdWords\v201705\rm\NumberRuleItem;
use Google\AdsApi\AdWords\v201705\rm\NumberRuleItemNumberOperator;
use Google\AdsApi\AdWords\v201705\rm\Rule;
use Google\AdsApi\AdWords\v201705\rm\RuleBasedUserListPrepopulationStatus;
use Google\AdsApi\AdWords\v201705\rm\RuleItem;
use Google\AdsApi\AdWords\v201705\rm\RuleItemGroup;
use Google\AdsApi\AdWords\v201705\rm\StringKey;
use Google\AdsApi\AdWords\v201705\rm\StringRuleItem;
use Google\AdsApi\AdWords\v201705\rm\StringRuleItemStringOperator;
use Google\AdsApi\AdWords\v201705\rm\UserListOperation;
use Google\AdsApi\AdWords\v201705\rm\UserListRuleTypeEnumsEnum;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds two rule-based remarketing user lists: one with no site
 * visit date restrictions, and another that will only include users who visit
 * your site in the next six months.
 */
class AddRuleBasedUserLists {

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

    // Create the user list with no restrictions on site visit date.
    $expressionUserList = new ExpressionRuleUserList();
    $expressionUserList->setName(
        sprintf('Expression based user list created at %s', date('Y-m-d_His')));
    $expressionUserList->setDescription('Users who checked out in three month '
        . 'window OR visited the checkout page with more than one item in '
        . 'their cart');
    $expressionUserList->setRule(self::createUserListRule());

    // Optional: Set the prepopulationStatus to REQUESTED to include past users
    // in the user list.
    $expressionUserList->setPrepopulationStatus(
        RuleBasedUserListPrepopulationStatus::REQUESTED);

    // Create the user list restricted to users who visit your site within the
    // next six months.
    $startDate = new DateTime();
    $endDate = new DateTime('+6 month');

    $dateUserList = new DateSpecificRuleUserList();
    $dateUserList->setName(
        sprintf('Date rule user list created at %s', date('Y-m-d_His')));
    $dateUserList->setDescription(sprintf(
        'Users who visited the site between %s '
            . 'and %s and checked out in three month window OR visited the '
            . 'checkout page with more than one item in their cart',
        $startDate->format('Ymd'),
        $endDate->format('Ymd')
    ));
    $dateUserList->setRule(self::createUserListRule());

    // Set the start and end dates of the user list.
    $dateUserList->setStartDate($startDate->format('Ymd'));
    $dateUserList->setEndDate($endDate->format('Ymd'));

    // Create operations to add the user lists.
    $operations = [];
    foreach ([$expressionUserList, $dateUserList] as $userList) {
      $operation = new UserListOperation();
      $operation->setOperand($userList);
      $operation->setOperator(Operator::ADD);
      $operations[] = $operation;
    }

    // Create the user lists on the server.
    $result = $userListService->mutate($operations);

    // Print out some information about created user lists.
    foreach ($result->getValue() as $userListResult) {
      printf(
          "User list added with ID %d, name '%s', status '%s', list type '%s'"
              . ", account user list status '%s', description '%s'.\n",
          $userListResult->getId(),
          $userListResult->getName(),
          $userListResult->getStatus(),
          $userListResult->getListType(),
          $userListResult->getAccountUserListStatus(),
          $userListResult->getDescription()
      );
    }
  }

  /**
   * Create a user list rule composed of two rule item groups.
   *
   * @return Rule the created user list
   */
  private static function createUserListRule() {
    // First rule item group - users who visited the checkout page and had more
    // than one item in their shopping cart.
    $checkoutStringRuleItem = new StringRuleItem();
    $checkoutStringKey = new StringKey();
    $checkoutStringKey->setName('ecomm_pagetype');
    $checkoutStringRuleItem->setKey($checkoutStringKey);
    $checkoutStringRuleItem->setOp(StringRuleItemStringOperator::EQUALS);
    $checkoutStringRuleItem->setValue('checkout');
    $checkoutRuleItem = new RuleItem();
    $checkoutRuleItem->setStringRuleItem($checkoutStringRuleItem);

    $cartSizeNumberRuleItem = new NumberRuleItem();
    $cartSizeNumberKey = new NumberKey();
    $cartSizeNumberKey->setName('cartsize');
    $cartSizeNumberRuleItem->setKey($cartSizeNumberKey);
    $cartSizeNumberRuleItem->setOp(NumberRuleItemNumberOperator::GREATER_THAN);
    $cartSizeNumberRuleItem->setValue(1.0);
    $cartSizeRuleItem = new RuleItem();
    $cartSizeRuleItem->setNumberRuleItem($cartSizeNumberRuleItem);

    // Combine the two rule items into a RuleItemGroup so AdWords will AND their
    // rules together.
    $checkoutMultipleItemGroup = new RuleItemGroup();
    $checkoutMultipleItemGroup->setItems(
        [$checkoutRuleItem, $cartSizeRuleItem]);

    // Second rule item group - users who checked out within the next 3 months.
    $today = new DateTime();
    $startDateDateRuleItem = new DateRuleItem();
    $startDateDateKey = new DateKey();
    $startDateDateKey->setName('checkoutdate');
    $startDateDateRuleItem->setKey($startDateDateKey);
    $startDateDateRuleItem->setOp(DateRuleItemDateOperator::AFTER);
    $startDateDateRuleItem->setValue($today->format('Ymd'));
    $startDateRuleItem = new RuleItem();
    $startDateRuleItem->setDateRuleItem($startDateDateRuleItem);

    $threeMonthsLater = new DateTime('+3 month');
    $endDateDateRuleItem = new DateRuleItem();
    $endDateDateKey = new DateKey();
    $endDateDateKey->setName('checkoutdate');
    $endDateDateRuleItem->setKey($endDateDateKey);
    $endDateDateRuleItem->setOp(DateRuleItemDateOperator::BEFORE);
    $endDateDateRuleItem->setValue($threeMonthsLater->format('Ymd'));
    $endDateRuleItem = new RuleItem();
    $endDateRuleItem->setDateRuleItem($endDateDateRuleItem);

    // Combine the date rule items into a RuleItemGroup.
    $checkedOutDateRangeItemGroup = new RuleItemGroup();
    $checkedOutDateRangeItemGroup->setItems(
        [$startDateRuleItem, $endDateRuleItem]);

    // Combine the rule item groups into a Rule so AdWords knows how to apply
    // the rules.
    $rule = new Rule();
    $rule->setGroups(
        [$checkoutMultipleItemGroup, $checkedOutDateRangeItemGroup]);
    // ExpressionRuleUserLists can use either CNF or DNF for matching. CNF means
    // 'at least one item in each rule item group must match', and DNF means 'at
    // least one entire rule item group must match'. DateSpecificRuleUserList
    // only supports DNF. You can also omit the rule type altogether to default
    // to DNF.
    $rule->setRuleType(UserListRuleTypeEnumsEnum::DNF);

    return $rule;
  }

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

AddRuleBasedUserLists::main();

Old

<?php
/**
 * This example adds two rule-based remarketing user lists: one with no site
 * visit date restrictions, and another that will only include users who visit
 * your site in the next six months.
 *
 * PHP version 5
 *
 * Copyright 2016, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    GoogleApiAdsAdWords
 * @subpackage v201705
 * @category   WebServices
 * @copyright  2016, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 */

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

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

  // First rule item group - users who visited the checkout page and had more
  // than one item in their shopping cart.
  $checkoutStringRuleItem = new StringRuleItem();
  $checkoutStringKey = new StringKey();
  $checkoutStringKey->name = 'ecomm_pagetype';
  $checkoutStringRuleItem->key = $checkoutStringKey;
  $checkoutStringRuleItem->op = 'EQUALS';
  $checkoutStringRuleItem->value = 'checkout';
  $checkoutRuleItem = new RuleItem();
  $checkoutRuleItem->StringRuleItem = $checkoutStringRuleItem;

  $cartSizeNumberRuleItem = new NumberRuleItem();
  $cartSizeNumberKey = new NumberKey();
  $cartSizeNumberKey->name = 'cartsize';
  $cartSizeNumberRuleItem->key = $cartSizeNumberKey;
  $cartSizeNumberRuleItem->op = 'GREATER_THAN';
  $cartSizeNumberRuleItem->value = 1.0;
  $cartSizeRuleItem = new RuleItem();
  $cartSizeRuleItem->NumberRuleItem = $cartSizeNumberRuleItem;

  // Combine the two rule items into a RuleItemGroup so AdWords will AND their
  // rules together.
  $checkoutMultipleItemGroup = new RuleItemGroup();
  $checkoutMultipleItemGroup->items = array($checkoutRuleItem,
      $cartSizeRuleItem);

  // Second rule item group - users who checked out within the next 3 months.
  $today = new DateTime();
  $startDateDateRuleItem = new DateRuleItem();
  $startDateDateKey = new DateKey();
  $startDateDateKey->name = 'checkoutdate';
  $startDateDateRuleItem->key = $startDateDateKey;
  $startDateDateRuleItem->op = 'AFTER';
  $startDateDateRuleItem->value = $today->format('Ymd');
  $startDateRuleItem = new RuleItem();
  $startDateRuleItem->DateRuleItem = $startDateDateRuleItem;

  $threeMonthsLater = clone($today);
  $threeMonthsLater->modify('+3 month');
  $endDateDateRuleItem = new DateRuleItem();
  $endDateDateKey = new DateKey();
  $endDateDateKey->name = 'checkoutdate';
  $endDateDateRuleItem->key = $endDateDateKey;
  $endDateDateRuleItem->op = 'BEFORE';
  $endDateDateRuleItem->value = $threeMonthsLater->format('Ymd');
  $endDateRuleItem = new RuleItem();
  $endDateRuleItem->DateRuleItem = $endDateDateRuleItem;

  // Combine the date rule items into a RuleItemGroup.
  $checkedOutDateRangeItemGroup = new RuleItemGroup();
  $checkedOutDateRangeItemGroup->items = array($startDateRuleItem,
      $endDateRuleItem);

  // Combine the rule item groups into a Rule so AdWords knows how to apply
  // the rules.
  $rule = new Rule();
  $rule->groups = array($checkoutMultipleItemGroup,
      $checkedOutDateRangeItemGroup);
  // ExpressionRuleUserLists can use either CNF or DNF for matching. CNF means
  // 'at least one item in each rule item group must match', and DNF means 'at
  // least one entire rule item group must match'. DateSpecificRuleUserList
  // only supports DNF. You can also omit the rule type altogether to default
  // to DNF.
  $rule->ruleType = 'DNF';

  // Create the user list with no restrictions on site visit date.
  $expressionUserList = new ExpressionRuleUserList();
  $expressionUserList->name = sprintf('Expression based user list created at '
      . '%s', date('Y-m-d_His'));
  $expressionUserList->description = 'Users who checked out in three month '
      . 'window OR visited the checkout page with more than one item in '
      . 'their cart';
  $expressionUserList->rule = $rule;

  // Create the user list restricted to users who visit your site within the
  // next six months.
  $startDate = clone($today);
  $endDate = clone($today);
  $endDate->modify('+6 month');

  $dateUserList = new DateSpecificRuleUserList();
  $dateUserList->name = sprintf('Date rule user list created at %s',
      date('Y-m-d_His'));
  $dateUserList->description = sprintf('Users who visited the site between %s '
      . 'and %s and checked out in three month window OR visited the checkout '
      . 'page with more than one item in their cart',
      $startDate->format('Ymd'),
      $endDate->format('Ymd'));
  $dateUserList->rule = $rule;

  // Set the start and end dates of the user list.
  $dateUserList->startDate = $startDate->format('Ymd');
  $dateUserList->endDate = $endDate->format('Ymd');

  // Create operations to add the user lists.
  $operations = array();
  foreach (array($expressionUserList, $dateUserList) as $userList) {
    $operation = new UserListOperation();
    $operation->operand = $userList;
    $operation->operator = 'ADD';
    $operations[] = $operation;
  }

  // Submit the operations.
  $result = $userListService->mutate($operations);

  // Display the results.
  foreach ($result->value as $userListResult) {
    printf("User list added with ID %d, name '%s', status '%s', list type '%s'"
        . ", accountUserListStatus '%s', description '%s'.\n",
    $userListResult->id,
    $userListResult->name,
    $userListResult->status,
    $userListResult->listType,
    $userListResult->accountUserListStatus,
    $userListResult->description);
  }
}

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

Upload offline conversions

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

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\OfflineConversionFeed;
use Google\AdsApi\AdWords\v201705\cm\OfflineConversionFeedOperation;
use Google\AdsApi\AdWords\v201705\cm\OfflineConversionFeedService;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This code example imports offline conversion values for specific clicks to
 * your account. To get Google Click ID for a click, run
 * CLICK_PERFORMANCE_REPORT.
 */
class UploadOfflineConversions {

  const CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE';
  const GCLID = 'INSERT_GOOGLE_CLICK_ID_HERE';
  const CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE';
  const CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE';

  public static function runExample(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      $conversionName,
      $gclid,
      $conversionTime,
      $conversionValue
  ) {
    $offlineConversionService =
        $adWordsServices->get($session, OfflineConversionFeedService::class);

    // Associate offline conversions with the existing named conversion tracker.
    // If this tracker was newly created, it may be a few hours before it can
    // accept conversions.
    $feed = new OfflineConversionFeed();
    $feed->setConversionName($conversionName);
    $feed->setConversionTime($conversionTime);
    $feed->setConversionValue($conversionValue);
    $feed->setGoogleClickId($gclid);

    $offlineConversionOperation = new OfflineConversionFeedOperation();
    $offlineConversionOperation->setOperator(Operator::ADD);
    $offlineConversionOperation->setOperand($feed);
    $offlineConversionOperations = [$offlineConversionOperation];

    $result = $offlineConversionService->mutate($offlineConversionOperations);

    $feed = $result->getValue()[0];
    printf(
        "Uploaded offline conversion value of %d for Google Click ID = "
            . "'%s' to '%s'.\n",
        $feed->getConversionValue(),
        $feed->getGoogleClickId(),
        $feed->getConversionName()
    );
  }

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

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

UploadOfflineConversions::main();

Old

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

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

// Enter parameters required by the code example.
$conversionName = 'INSERT_CONVERSION_NAME_HERE';
$gclid = 'INSERT_GOOGLE_CLICK_ID_HERE';
$conversionTime = 'INSERT_CONVERSION_TIME_HERE';
$conversionValue = 'INSERT_CONVERSION_VALUE_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $conversionName the name of conversion
 * @param string $gclid the Google click ID
 * @param string $conversionTime the conversion time
 * @param string $conversionValue the conversion value
 */
function UploadOfflineConversionsExample(AdWordsUser $user, $conversionName,
    $gclid, $conversionTime, $conversionValue) {
  // Get the services, which loads the required classes.
  $offlineConversionService = $user->GetService('OfflineConversionFeedService',
      ADWORDS_VERSION);

  // Associate offline conversions with the existing named conversion tracker.
  // If this tracker was newly created, it may be a few hours before it can
  // accept conversions.
  $feed = new OfflineConversionFeed();
  $feed->conversionName = $conversionName;
  $feed->conversionTime = $conversionTime;
  $feed->conversionValue = $conversionValue;
  $feed->googleClickId = $gclid;

  $offlineConversionOperation = new OfflineConversionFeedOperation();
  $offlineConversionOperation->operator = 'ADD';
  $offlineConversionOperation->operand = $feed;

  $offlineConversionOperations = array($offlineConversionOperation);
  $result = $offlineConversionService->mutate($offlineConversionOperations);

  $feed = $result->value[0];
  printf('Uploaded offline conversion value of %d for Google Click ID = ' .
      "'%s' to '%s'.", $feed->conversionValue, $feed->googleClickId,
      $feed->conversionName);
}

// 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.
  UploadOfflineConversionsExample($user, $conversionName, $gclid,
      $conversionTime, $conversionValue);
} catch (OAuth2Exception $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (ValidationException $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}

Upload offline call conversions

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

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\OfflineCallConversionFeed;
use Google\AdsApi\AdWords\v201705\cm\OfflineCallConversionFeedOperation;
use Google\AdsApi\AdWords\v201705\cm\OfflineCallConversionFeedService;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This code example imports offline call conversion values for calls related
 * to the ads in your account.
 */
class UploadOfflineCallConversions {

  const CALLER_ID = 'INSERT_CALLER_ID_HERE';
  // For times use the format yyyyMMdd HHmmss tz. For more details on formats,
  // see:
  // https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats
  // For time zones, see:
  // https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids
  const CALL_START_TIME = 'INSERT_CALL_START_TIME_HERE';
  const CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE';
  const CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE';
  const CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE';

  public static function runExample(
      AdWordsServices $adWordsServices,
      AdWordsSession $session,
      $callerId,
      $callStartTime,
      $conversionName,
      $conversionTime,
      $conversionValue
  ) {
    $offlineCallConversionService = $adWordsServices->get(
        $session, OfflineCallConversionFeedService::class);

    // Associate offline call conversions with the existing named conversion
    // tracker. If this tracker was newly created, it may be a few hours before
    // it can accept conversions.
    $feed = new OfflineCallConversionFeed();
    $feed->setCallerId($callerId);
    $feed->setCallStartTime($callStartTime);
    $feed->setConversionName($conversionName);
    $feed->setConversionTime($conversionTime);
    $feed->setConversionValue($conversionValue);

    $offlineCallConversionOperations = [];
    $offlineCallConversionOperation = new OfflineCallConversionFeedOperation();
    $offlineCallConversionOperation->setOperator(Operator::ADD);
    $offlineCallConversionOperation->setOperand($feed);
    $offlineCallConversionOperations[] = $offlineCallConversionOperation;

    // This example uploads only one call conversion, but you can upload
    // multiple call conversions by passing additional operations.
    $result =
        $offlineCallConversionService->mutate($offlineCallConversionOperations);

    $feed = $result->getValue()[0];
    printf(
        "Uploaded offline call conversion value of '%s' for caller ID '%s'.\n",
        $feed->getConversionValue(),
        $feed->getCallerId()
    );
  }

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

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

UploadOfflineCallConversions::main();

Old

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

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

// Enter parameters required by the code example.
$callerId = 'INSERT_CALLER_ID_HERE';
// For times use the format yyyyMMdd HHmmss tz. For more details on formats,
// see: https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats
// For time zones, see: https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids
$callStartTime = 'INSERT_CALL_START_TIME_HERE';
$conversionName = 'INSERT_CONVERSION_NAME_HERE';
$conversionTime = 'INSERT_CONVERSION_TIME_HERE';
$conversionValue = 'INSERT_CONVERSION_VALUE_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $callerId the caller ID
 * @param string $callStartTime the call start time
 * @param string $conversionName the conversion name
 * @param string $conversionTime the time that the conversion has occurred
 * @param string $conversionValue the conversion value
 */
function UploadOfflineCallConversionsExample(AdWordsUser $user, $callerId,
    $callStartTime, $conversionName, $conversionTime, $conversionValue) {
  // Get the services, which loads the required classes.
  $offlineCallConversionService =
      $user->GetService('OfflineCallConversionFeedService', ADWORDS_VERSION);

  // Associate offline call conversions with the existing named conversion
  // tracker. If this tracker was newly created, it may be a few hours before
  // it can accept conversions.
  $feed = new OfflineCallConversionFeed();
  $feed->callerId = $callerId;
  $feed->callStartTime = $callStartTime;
  $feed->conversionName = $conversionName;
  $feed->conversionTime = $conversionTime;
  $feed->conversionValue = $conversionValue;

  $offlineCallConversionOperation = new OfflineCallConversionFeedOperation();
  $offlineCallConversionOperation->operator = 'ADD';
  $offlineCallConversionOperation->operand = $feed;

  $offlineCallConversionOperations = array($offlineCallConversionOperation);
  // This example uploads only one call conversion, but you can upload multiple
  // call conversions by passing additional operations.
  $result =
      $offlineCallConversionService->mutate($offlineCallConversionOperations);

  $feed = $result->value[0];
  printf("Uploaded offline call conversion value of '%s' for caller ID '%s'.\n",
      $feed->conversionValue, $feed->callerId);
}

// 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.
  UploadOfflineCallConversionsExample($user, $callerId, $callStartTime,
      $conversionName, $conversionTime, $conversionValue);
} catch (OAuth2Exception $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (ValidationException $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} 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.