Thiết lập tính năng tái tiếp thị

Java

// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://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 com.google.ads.googleads.examples.remarketing;

import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.lib.utils.FieldMasks;
import com.google.ads.googleads.v17.common.FlexibleRuleOperandInfo;
import com.google.ads.googleads.v17.common.FlexibleRuleUserListInfo;
import com.google.ads.googleads.v17.common.RuleBasedUserListInfo;
import com.google.ads.googleads.v17.common.UserListInfo;
import com.google.ads.googleads.v17.common.UserListRuleInfo;
import com.google.ads.googleads.v17.common.UserListRuleItemGroupInfo;
import com.google.ads.googleads.v17.common.UserListRuleItemInfo;
import com.google.ads.googleads.v17.common.UserListStringRuleItemInfo;
import com.google.ads.googleads.v17.enums.UserListFlexibleRuleOperatorEnum.UserListFlexibleRuleOperator;
import com.google.ads.googleads.v17.enums.UserListMembershipStatusEnum.UserListMembershipStatus;
import com.google.ads.googleads.v17.enums.UserListPrepopulationStatusEnum.UserListPrepopulationStatus;
import com.google.ads.googleads.v17.enums.UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator;
import com.google.ads.googleads.v17.errors.GoogleAdsError;
import com.google.ads.googleads.v17.errors.GoogleAdsException;
import com.google.ads.googleads.v17.resources.AdGroupCriterion;
import com.google.ads.googleads.v17.resources.CampaignCriterion;
import com.google.ads.googleads.v17.resources.UserList;
import com.google.ads.googleads.v17.services.AdGroupCriterionOperation;
import com.google.ads.googleads.v17.services.AdGroupCriterionServiceClient;
import com.google.ads.googleads.v17.services.CampaignCriterionOperation;
import com.google.ads.googleads.v17.services.CampaignCriterionServiceClient;
import com.google.ads.googleads.v17.services.GoogleAdsRow;
import com.google.ads.googleads.v17.services.GoogleAdsServiceClient;
import com.google.ads.googleads.v17.services.GoogleAdsServiceClient.SearchPagedResponse;
import com.google.ads.googleads.v17.services.MutateAdGroupCriteriaResponse;
import com.google.ads.googleads.v17.services.MutateAdGroupCriterionResult;
import com.google.ads.googleads.v17.services.MutateCampaignCriteriaResponse;
import com.google.ads.googleads.v17.services.MutateUserListsResponse;
import com.google.ads.googleads.v17.services.SearchGoogleAdsRequest;
import com.google.ads.googleads.v17.services.UserListOperation;
import com.google.ads.googleads.v17.services.UserListServiceClient;
import com.google.ads.googleads.v17.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Demonstrates various operations involved in remarketing, including (a) creating a user list based
 * on visitors to a website, (b) targeting a user list with an ad group criterion, (c) updating the
 * bid modifier value on an ad group criterion, (d) finding and removing all ad group criteria under
 * a given campaign, (e) targeting a user list with a campaign criterion, and (f) updating the bid
 * modifier on a campaign criterion. It is unlikely that users will need to perform all of these
 * operations consecutively, and all of the operations contained herein are meant of for
 * illustrative purposes.
 */
public class SetUpRemarketing {

  private static class SetUpRemarketingParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;

    @Parameter(names = ArgumentNames.AD_GROUP_ID, required = true)
    private Long adGroupId;

    @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
    private Long campaignId;

    /** Specify the bid modifier value here or the default specified below will be used. */
    @Parameter(names = ArgumentNames.BID_MODIFIER_VALUE)
    private Double bidModifierValue = 1.5;
  }

  public static void main(String[] args) {
    SetUpRemarketingParams params = new SetUpRemarketingParams();
    if (!params.parseArguments(args)) {

      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
      params.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
      params.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");
      // Optional: To use a different bid modifier value from the default (1.5), uncomment
      // the line below and insert the desired bid modifier value.
      // params.bidModifierValue = Double.parseDouble("INSERT_BID_MODIFIER_VALUE_HERE");
    }

    GoogleAdsClient googleAdsClient = null;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      System.exit(1);
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      System.exit(1);
    }

    try {
      new SetUpRemarketing()
          .runExample(
              googleAdsClient,
              params.customerId,
              params.adGroupId,
              params.campaignId,
              params.bidModifierValue);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
      System.exit(1);
    }
  }

  /**
   * Runs the example.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param adGroupId the adGroup on which to do the remarketing.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient,
      long customerId,
      long adGroupId,
      long campaignId,
      double bidModifierValue) {
    String userList = createUserList(googleAdsClient, customerId);
    String adGroupCriterionResourceName =
        targetAdsInAdGroupToUserList(googleAdsClient, customerId, adGroupId, userList);
    modifyAdGroupBids(googleAdsClient, customerId, adGroupCriterionResourceName, bidModifierValue);
    removeExistingListCriteriaFromAdGroup(googleAdsClient, customerId, campaignId);
    String campaignCriterionResourceName =
        targetAdsInCampaignToUserList(googleAdsClient, customerId, campaignId, userList);
    modifyCampaignBids(
        googleAdsClient, customerId, campaignCriterionResourceName, bidModifierValue);
  }

  /**
   * Creates a user list targeting users that have visited a given url.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @return the user list resource name.
   */
  private String createUserList(GoogleAdsClient googleAdsClient, long customerId) {
    // Creates a rule targeting any user that visited a url containing 'example.com'.
    UserListRuleItemInfo rule =
        UserListRuleItemInfo.newBuilder()
            // Uses a built-in parameter to create a domain URL rule.
            .setName("url__")
            .setStringRuleItem(
                UserListStringRuleItemInfo.newBuilder()
                    .setOperator(UserListStringRuleItemOperator.CONTAINS)
                    .setValue("example.com")
                    .build())
            .build();

    // Specifies that the user list targets visitors of a page based on the provided rule.
    FlexibleRuleUserListInfo flexibleRuleUserListInfo =
        FlexibleRuleUserListInfo.newBuilder()
            .setInclusiveRuleOperator(UserListFlexibleRuleOperator.AND)
            // Inclusive operands are joined together with the specified inclusiveRuleOperator.
            .addInclusiveOperands(
                FlexibleRuleOperandInfo.newBuilder()
                    .setRule(
                        UserListRuleInfo.newBuilder()
                            .addRuleItemGroups(
                                UserListRuleItemGroupInfo.newBuilder().addRuleItems(rule)))
                    // Optional: adds a lookback window for this rule, in days.
                    .setLookbackWindowDays(7L))
            .build();

    // Defines a representation of a user list that is generated by a rule.
    RuleBasedUserListInfo ruleBasedUserListInfo =
        RuleBasedUserListInfo.newBuilder()
            // Optional: To include past users in the user list, set the prepopulation_status to
            // REQUESTED.
            .setPrepopulationStatus(UserListPrepopulationStatus.REQUESTED)
            .setFlexibleRuleUserList(flexibleRuleUserListInfo)
            .build();

    // Creates the user list.
    UserList userList =
        UserList.newBuilder()
            .setName("All visitors to example.com" + getPrintableDateTime())
            .setDescription("Any visitor to any page of example.com")
            .setMembershipStatus(UserListMembershipStatus.OPEN)
            .setMembershipLifeSpan(365)
            .setRuleBasedUserList(ruleBasedUserListInfo)
            .build();

    // Creates the operation.
    UserListOperation operation = UserListOperation.newBuilder().setCreate(userList).build();

    // Creates the user list service client.
    try (UserListServiceClient userListServiceClient =
        googleAdsClient.getLatestVersion().createUserListServiceClient()) {
      // Adds the user list.
      MutateUserListsResponse response =
          userListServiceClient.mutateUserLists(
              Long.toString(customerId), ImmutableList.of(operation));
      String userListResourceName = response.getResults(0).getResourceName();
      // Prints the result.
      System.out.printf("Created user list with resource name '%s'.%n", userListResourceName);
      return userListResourceName;
    }
  }


  /**
   * Creates an ad group criterion that targets a user list with an ad group.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param adGroupId the ad group on which the user list will be targeted.
   * @param userList the resource name of the user list to be targeted.
   * @return the ad group criterion resource name.
   */
  private String targetAdsInAdGroupToUserList(
      GoogleAdsClient googleAdsClient, long customerId, long adGroupId, String userList) {
    // Creates the ad group criterion targeting members of the user list.
    AdGroupCriterion adGroupCriterion =
        AdGroupCriterion.newBuilder()
            .setAdGroup(ResourceNames.adGroup(customerId, adGroupId))
            .setUserList(UserListInfo.newBuilder().setUserList(userList).build())
            .build();

    // Creates the operation.
    AdGroupCriterionOperation operation =
        AdGroupCriterionOperation.newBuilder().setCreate(adGroupCriterion).build();

    // Creates the ad group criterion service.
    try (AdGroupCriterionServiceClient adGroupCriterionServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) {
      // Adds the ad group criterion.
      MutateAdGroupCriteriaResponse response =
          adGroupCriterionServiceClient.mutateAdGroupCriteria(
              Long.toString(customerId), ImmutableList.of(operation));
      // Gets and prints the results.
      String adGroupCriterionResourceName = response.getResults(0).getResourceName();
      System.out.printf(
          "Successfully created ad group criterion with resource name '%s' "
              + "targeting user list with resource name '%s' with ad group with ID %d.%n",
          adGroupCriterionResourceName, userList, adGroupId);
      return adGroupCriterionResourceName;
    }
  }


  /**
   * Updates the bid modifier value on an ad group criterion.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param adGroupCriterionResourceName the ad group criterion to update.
   * @param bidModifierValue the bid modifier value.
   */
  private void modifyAdGroupBids(
      GoogleAdsClient googleAdsClient,
      long customerId,
      String adGroupCriterionResourceName,
      double bidModifierValue) {
    // Creates the ad group criterion with a bid modifier value. You may alternatively set the bid
    // for the ad group criterion directly.
    AdGroupCriterion adGroupCriterion =
        AdGroupCriterion.newBuilder()
            .setResourceName(adGroupCriterionResourceName)
            .setBidModifier(bidModifierValue)
            .build();

    // Creates the update operation.
    AdGroupCriterionOperation operation =
        AdGroupCriterionOperation.newBuilder()
            .setUpdate(adGroupCriterion)
            .setUpdateMask(FieldMasks.allSetFieldsOf(adGroupCriterion))
            .build();

    // Creates the ad group criterion service.
    try (AdGroupCriterionServiceClient adGroupCriterionServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) {
      // Updates the ad group criterion.
      MutateAdGroupCriteriaResponse response =
          adGroupCriterionServiceClient.mutateAdGroupCriteria(
              Long.toString(customerId), ImmutableList.of(operation));
      // Prints the results.
      System.out.printf(
          "Successfully updated the bid for ad group criterion with resource name '%s'.%n",
          response.getResults(0).getResourceName());
    }
  }

  /**
   * Removes all ad group criteria targeting a user list under a given campaign. This is a necessary
   * step before targeting a user list at the campaign level.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param campaignId the campaign under which to remove the ad group criteria.
   */
  private void removeExistingListCriteriaFromAdGroup(
      GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
    // Retrieves all of the ad group criteria under a campaign.
    List<String> adGroupCriteria =
        getUserListAdGroupCriterion(googleAdsClient, customerId, campaignId);

    List<AdGroupCriterionOperation> operations = new ArrayList<>();

    // Creates a list of remove operations.
    for (String adGroupCriterion : adGroupCriteria) {
      operations.add(AdGroupCriterionOperation.newBuilder().setRemove(adGroupCriterion).build());
    }

    // Creates the ad group criterion service.
    try (AdGroupCriterionServiceClient adGroupCriterionServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) {
      // Removes the ad group criterion.
      MutateAdGroupCriteriaResponse response =
          adGroupCriterionServiceClient.mutateAdGroupCriteria(
              Long.toString(customerId), operations);
      // Gets and prints the results.
      System.out.printf("Removed %d ad group criteria.%n", response.getResultsCount());
      for (MutateAdGroupCriterionResult result : response.getResultsList()) {
        System.out.printf(
            "Successfully removed ad group criterion with resource name '%s'.%n",
            result.getResourceName());
      }
    }
  }


  /**
   * Finds all of user list ad group criteria under a campaign.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param campaignId the campaign under which to search the ad group criteria.
   * @return a list of the ad group criteria resource names.
   */
  private List<String> getUserListAdGroupCriterion(
      GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
    List<String> userListCriteria = new ArrayList<>();
    // Creates the Google Ads service client.
    try (GoogleAdsServiceClient googleAdsServiceClient =
        googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
      // Creates a request that will retrieve all of the ad group criteria under a campaign.
      SearchGoogleAdsRequest request =
          SearchGoogleAdsRequest.newBuilder()
              .setCustomerId(Long.toString(customerId))
              .setQuery(
                  "SELECT ad_group_criterion.criterion_id"
                      + " FROM ad_group_criterion"
                      + " WHERE campaign.id = "
                      + campaignId
                      + " AND ad_group_criterion.type = 'USER_LIST'")
              .build();
      // Issues the search request.
      SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request);
      // Iterates over all rows in all pages. Prints the results and adds the ad group criteria
      // resource names to the list.
      for (GoogleAdsRow googleAdsRow : searchPagedResponse.iterateAll()) {
        String adGroupCriterionResourceName = googleAdsRow.getAdGroupCriterion().getResourceName();
        System.out.printf(
            "Ad group criterion with resource name '%s' was found.%n",
            adGroupCriterionResourceName);
        userListCriteria.add(adGroupCriterionResourceName);
      }
    }
    return userListCriteria;
  }


  /**
   * Creates a campaign criterion that targets a user list with a campaign.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param campaignId the campaign on which the user list will be targeted.
   * @param userList the resource name of the user list to be targeted.
   * @return the campaign criterion resource name.
   */
  private String targetAdsInCampaignToUserList(
      GoogleAdsClient googleAdsClient, long customerId, long campaignId, String userList) {
    // Creates the campaign criterion.
    CampaignCriterion campaignCriterion =
        CampaignCriterion.newBuilder()
            .setCampaign(ResourceNames.campaign(customerId, campaignId))
            .setUserList(UserListInfo.newBuilder().setUserList(userList).build())
            .build();

    // Creates the operation.
    CampaignCriterionOperation operation =
        CampaignCriterionOperation.newBuilder().setCreate(campaignCriterion).build();

    // Creates the campaign criterion service client.
    try (CampaignCriterionServiceClient campaignCriterionServiceClient =
        googleAdsClient.getLatestVersion().createCampaignCriterionServiceClient()) {
      // Adds the campaign criterion.
      MutateCampaignCriteriaResponse response =
          campaignCriterionServiceClient.mutateCampaignCriteria(
              Long.toString(customerId), ImmutableList.of(operation));
      // Gets and prints the campaign criterion resource name.
      String campaignCriterionResourceName = response.getResults(0).getResourceName();
      System.out.printf(
          "Successfully created campaign criterion with resource name '%s' "
              + "targeting user list with resource name '%s' with campaign with ID %d.%n",
          campaignCriterionResourceName, userList, campaignId);
      return campaignCriterionResourceName;
    }
  }


  /**
   * Updates the bid modifier value on a campaign criterion.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param campaignCriterionResourceName the campaign criterion to update.
   * @param bidModifierValue the bid modifier value.
   */
  private void modifyCampaignBids(
      GoogleAdsClient googleAdsClient,
      long customerId,
      String campaignCriterionResourceName,
      double bidModifierValue) {
    // Creates the campaign criterion to update.
    CampaignCriterion campaignCriterion =
        CampaignCriterion.newBuilder()
            .setResourceName(campaignCriterionResourceName)
            .setBidModifier((float) bidModifierValue)
            .build();

    // Creates the update operation.
    CampaignCriterionOperation operation =
        CampaignCriterionOperation.newBuilder()
            .setUpdate(campaignCriterion)
            .setUpdateMask(FieldMasks.allSetFieldsOf(campaignCriterion))
            .build();

    // Creates the campaign criterion service client.
    try (CampaignCriterionServiceClient campaignCriterionServiceClient =
        googleAdsClient.getLatestVersion().createCampaignCriterionServiceClient()) {
      // Updates the campaign criterion.
      MutateCampaignCriteriaResponse response =
          campaignCriterionServiceClient.mutateCampaignCriteria(
              Long.toString(customerId), ImmutableList.of(operation));
      System.out.printf(
          "Successfully updated the bid for campaign criterion with resource name '%s'.%n",
          response.getResults(0).getResourceName());
    }
  }
}

      

C#

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

using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.Gax.Util;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V17.Common;
using Google.Ads.GoogleAds.V17.Errors;
using Google.Ads.GoogleAds.V17.Resources;
using Google.Ads.GoogleAds.V17.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V17.Enums.UserListMembershipStatusEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.UserListPrepopulationStatusEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.UserListStringRuleItemOperatorEnum.Types;
using static Google.Ads.GoogleAds.V17.Errors.CriterionErrorEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V17
{
    /// <summary>
    /// Demonstrates various operations involved in remarketing, including:
    ///   (a) creating a user list based on visitors to a website,
    ///   (b) targeting a user list with an ad group criterion,
    ///   (c) updating the bid modifier on an ad group criterion,
    ///   (d) finding and removing all ad group criteria under a given campaign,
    ///   (e) targeting a user list with a campaign criterion, and
    ///   (f) updating the bid modifier on a campaign criterion.
    /// It is unlikely that users will need to perform all of these operations consecutively, and
    /// all of the operations contained herein are meant of for illustrative purposes.
    /// Note: you can use user lists to target at the campaign or ad group level, but not both
    /// simultaneously. Consider removing or disabling any existing user lists at the campaign level
    /// before running this example.
    /// </summary>
    public class SetUpRemarketing : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="SetUpRemarketing"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the call is made.")]
            public long CustomerId { get; set; }

            /// <summary>
            /// The ad group ID on which criteria will be targeted.
            /// </summary>
            [Option("adGroupId", Required = true, HelpText =
                "The ad group ID on which criteria will be targeted.")]
            public long AdGroupId { get; set; }

            /// <summary>
            /// The campaign ID on which criteria will be targeted.
            /// </summary>
            [Option("campaignId", Required = true, HelpText =
                "The campaign ID on which criteria will be targeted.")]
            public long CampaignId { get; set; }

            /// <summary>
            /// The bid modifier value.
            /// </summary>
            [Option("bidModifierValue", Required = true, HelpText =
                "The bid modifier value.")]
            public double BidModifierValue { get; set; }
        }

        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            Options options = ExampleUtilities.ParseCommandLine<Options>(args);

            SetUpRemarketing codeExample = new SetUpRemarketing();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.AdGroupId,
                options.CampaignId, options.BidModifierValue);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "Demonstrates various operations involved in remarketing, including:\n" +
            "\t(a) creating a user list based on visitors to a website,\n" +
            "\t(b) targeting a user list with an ad group criterion,\n" +
            "\t(c) updating the bid modifier on an ad group criterion,\n" +
            "\t(d) finding and removing all ad group criteria under a given campaign,\n" +
            "\t(e) targeting a user list with a campaign criterion, and\n" +
            "\t(f) updating the bid modifier on a campaign criterion.\n" +
            "It is unlikely that users will need to perform all of these operations " +
            "consecutively, and all of the operations contained herein are meant of for " +
            "illustrative purposes.\n" +
            "Note: you can use user lists to target at the campaign or ad group level, but not " +
            "both simultaneously. Consider removing or disabling any existing user lists at the " +
            "campaign level before running this example.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupId">The ad group ID on which criteria will be targeted.</param>
        /// <param name="campaignId">The campaign ID on which criteria will be targeted.</param>
        /// <param name="bidModifierValue">The bid modifier value.</param>
        public void Run(GoogleAdsClient client, long customerId, long adGroupId, long campaignId,
            double bidModifierValue)
        {
            try
            {
                // Create a new example user list.
                string userListResourceName = CreateUserList(client, customerId);

                // Target an ad group to the new user list.
                string adGroupCriterionResourceName =
                    TargetAdsInAdGroupToUserList(client, customerId, adGroupId,
                        userListResourceName);
                ModifyAdGroupBids(client, customerId, adGroupCriterionResourceName,
                    bidModifierValue);

                // Remove any existing user lists at the ad group level.
                RemoveExistingListCriteriaFromAdGroup(client, customerId, campaignId);

                // Target the campaign to the new user list.
                string campaignCriterionResourceName =
                    TargetAdsInCampaignToUserList(client, customerId, campaignId,
                        userListResourceName);
                ModifyCampaignBids(client, customerId, campaignCriterionResourceName,
                    bidModifierValue);
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                if (e.Failure.Errors.First().ErrorCode.CriterionError ==
                    CriterionError.CannotAttachCriteriaAtCampaignAndAdgroup)
                {
                    Console.WriteLine("This error can occur when user lists are already targeted " +
                        "at the campaign level. You can use user lists to target at the campaign " +
                        "or ad group level, but not both simultaneously. Consider removing or " +
                        "disabling any existing user lists at the campaign level before running " +
                        "this example.");
                }

                throw;
            }
        }

        /// <summary>
        /// Creates a user list targeting users that have visited a given url.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <returns>The resource name of the newly created user list.</returns>
        private string CreateUserList(GoogleAdsClient client, long customerId)
        {
            // Get the UserListService client.
            UserListServiceClient userListServiceClient =
                client.GetService(Services.V17.UserListService);

            // Create a rule targeting any user that visited a url containing 'example.com'.
            UserListRuleItemInfo rule = new UserListRuleItemInfo
            {
                // Use a built-in parameter to create a domain URL rule.
                Name = "url__",
                StringRuleItem = new UserListStringRuleItemInfo
                {
                    Operator = UserListStringRuleItemOperator.Contains,
                    Value = "example.com"
                }
            };

            // Specify that the user list targets visitors of a page based on the provided rule.
            FlexibleRuleUserListInfo flexibleRuleUserListInfo = new FlexibleRuleUserListInfo();
            FlexibleRuleOperandInfo flexibleRuleOperandInfo = new FlexibleRuleOperandInfo() {
                Rule = new UserListRuleInfo()
            };
            UserListRuleItemGroupInfo userListRuleItemGroupInfo = new UserListRuleItemGroupInfo();
            userListRuleItemGroupInfo.RuleItems.Add(rule);
            flexibleRuleOperandInfo.Rule.RuleItemGroups.Add(userListRuleItemGroupInfo);
            flexibleRuleUserListInfo.InclusiveOperands.Add(flexibleRuleOperandInfo);

            // Define a representation of a user list that is generated by a rule.
            RuleBasedUserListInfo ruleBasedUserListInfo = new RuleBasedUserListInfo
            {
                // Optional: To include past users in the user list, set the prepopulation_status to
                // REQUESTED.
                PrepopulationStatus = UserListPrepopulationStatus.Requested,
                FlexibleRuleUserList = flexibleRuleUserListInfo
            };

            // Create the user list.
            UserList userList = new UserList
            {
                Name = $"All visitors to example.com #{ExampleUtilities.GetRandomString()}",
                Description = "Any visitor to any page of example.com",
                MembershipStatus = UserListMembershipStatus.Open,
                MembershipLifeSpan = 365L,
                RuleBasedUserList = ruleBasedUserListInfo
            };

            // Create the operation.
            UserListOperation userListOperation = new UserListOperation
            {
                Create = userList
            };

            // Add the user list, then print and return the new list's resource name.
            MutateUserListsResponse mutateUserListsResponse = userListServiceClient
                .MutateUserLists(customerId.ToString(), new[] { userListOperation });
            string userListResourceName = mutateUserListsResponse.Results.First().ResourceName;
            Console.WriteLine($"Created user list with resource name '{userListResourceName}'.");

            return userListResourceName;
        }

        /// <summary>
        /// Creates an ad group criterion that targets a user list with an ad group.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupId">The ad group on which the user list will be targeted.</param>
        /// <param name="userListResourceName">The resource name of the user list to be
        /// targeted.</param>
        /// <returns>The resource name of the newly created ad group criterion.</returns>
        private string TargetAdsInAdGroupToUserList(
            GoogleAdsClient client, long customerId, long adGroupId, string userListResourceName)
        {
            // Get the AdGroupCriterionService client.
            AdGroupCriterionServiceClient adGroupCriterionServiceClient = client.GetService
                (Services.V17.AdGroupCriterionService);

            // Create the ad group criterion targeting members of the user list.
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion
            {
                AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
                UserList = new UserListInfo
                {
                    UserList = userListResourceName
                }
            };

            // Create the operation.
            AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation
            {
                Create = adGroupCriterion
            };

            // Add the ad group criterion, then print and return the new criterion's resource name.
            MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
                adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId.ToString(),
                    new[] { adGroupCriterionOperation });

            string adGroupCriterionResourceName =
                mutateAdGroupCriteriaResponse.Results.First().ResourceName;
            Console.WriteLine("Successfully created ad group criterion with resource name " +
                $"'{adGroupCriterionResourceName}' targeting user list with resource name " +
                $"'{userListResourceName}' with ad group with ID {adGroupId}.");
            return adGroupCriterionResourceName;
        }

        /// <summary>
        /// Updates the bid modifier on an ad group criterion.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupCriterionResourceName">The resource name of the ad group criterion to update.</param>
        /// <param name="bidModifierValue">The bid modifier value.</param>
        private void ModifyAdGroupBids(
            GoogleAdsClient client,
            long customerId,
            string adGroupCriterionResourceName,
            double bidModifierValue)
        {
            // Get the AdGroupCriterionService client.
            AdGroupCriterionServiceClient adGroupCriterionServiceClient =
                client.GetService(Services.V17.AdGroupCriterionService);

            // Create the ad group criterion with a bid modifier. You may alternatively set the bid
            // for the ad group criterion directly.
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion
            {
                ResourceName = adGroupCriterionResourceName,
                BidModifier = bidModifierValue
            };

            // Create the update operation.
            AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation
            {
                Update = adGroupCriterion,
                UpdateMask = FieldMasks.AllSetFieldsOf(adGroupCriterion)
            };

            // Update the ad group criterion and print the results.
            MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
                adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId.ToString(),
                    new[] { adGroupCriterionOperation });
            Console.WriteLine("Successfully updated the bid for ad group criterion with resource " +
                $"name '{mutateAdGroupCriteriaResponse.Results.First().ResourceName}'.");
        }

        /// <summary>
        /// Removes all ad group criteria targeting a user list under a given campaign. This is a
        /// necessary step before targeting a user list at the campaign level.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">The campaign from which to remove the ad group criteria.</param>
        private void RemoveExistingListCriteriaFromAdGroup(GoogleAdsClient client, long customerId,
            long campaignId)
        {
            // Get the AdGroupCriterionService client.
            AdGroupCriterionServiceClient adGroupCriterionServiceClient =
                client.GetService(Services.V17.AdGroupCriterionService);

            // Retrieve all of the ad group criteria under a campaign.
            List<string> adGroupCriteria =
                GetUserListAdGroupCriteria(client, customerId, campaignId);

            // Create a list of remove operations.
            List<AdGroupCriterionOperation> operations = adGroupCriteria.Select(adGroupCriterion =>
                new AdGroupCriterionOperation { Remove = adGroupCriterion }).ToList();

            // Remove the ad group criteria and print the resource names of the removed criteria.
            MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
                adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId.ToString(),
                    operations);

            Console.WriteLine($"Removed {mutateAdGroupCriteriaResponse.Results.Count} ad group " +
                "criteria.");
            foreach (MutateAdGroupCriterionResult result in mutateAdGroupCriteriaResponse.Results)
            {
                Console.WriteLine("Successfully removed ad group criterion with resource name " +
                    $"'{result.ResourceName}'.");
            }
        }

        /// <summary>
        /// Finds all of user list ad group criteria under a campaign.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">The campaign in which to search the ad group criteria.</param>
        /// <returns>A list of ad group criteria resource names.</returns>
        private List<string> GetUserListAdGroupCriteria(
            GoogleAdsClient client, long customerId, long campaignId)
        {
            // Get the GoogleAdsService client.
            GoogleAdsServiceClient googleAdsServiceClient =
                client.GetService(Services.V17.GoogleAdsService);

            List<string> userListCriteriaResourceNames = new List<string>();

            // Create a query that will retrieve all of the ad group criteria under a campaign.
            string query = $@"
                SELECT ad_group_criterion.criterion_id
                FROM ad_group_criterion
                WHERE
                  campaign.id = {campaignId}
                  AND ad_group_criterion.type = 'USER_LIST'";

            // Issue the search request.
            googleAdsServiceClient.SearchStream(customerId.ToString(), query,
                delegate (SearchGoogleAdsStreamResponse resp)
                {
                    // Display the results and add the resource names to the list.
                    foreach (GoogleAdsRow googleAdsRow in resp.Results)
                    {
                        string adGroupCriterionResourceName =
                            googleAdsRow.AdGroupCriterion.ResourceName;
                        Console.WriteLine("Ad group criterion with resource name " +
                            $"{adGroupCriterionResourceName} was found.");
                        userListCriteriaResourceNames.Add(adGroupCriterionResourceName);
                    }
                });

            return userListCriteriaResourceNames;
        }

        /// <summary>
        /// Creates a campaign criterion that targets a user list with a campaign.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">The campaign on which the user list will be targeted.</param>
        /// <param name="userListResourceName">The resource name of the user list to be
        /// targeted.</param>
        /// <returns>The resource name of the newly created campaign criterion.</returns>
        private string TargetAdsInCampaignToUserList(
            GoogleAdsClient client, long customerId, long campaignId, string userListResourceName)
        {
            // Get the CampaignCriterionService client.
            CampaignCriterionServiceClient campaignCriterionServiceClient =
                client.GetService(Services.V17.CampaignCriterionService);

            // Create the campaign criterion.
            CampaignCriterion campaignCriterion = new CampaignCriterion
            {
                Campaign = ResourceNames.Campaign(customerId, campaignId),
                UserList = new UserListInfo
                {
                    UserList = userListResourceName
                }
            };

            // Create the operation.
            CampaignCriterionOperation campaignCriterionOperation = new CampaignCriterionOperation
            {
                Create = campaignCriterion
            };

            // Add the campaign criterion and print the resulting criterion's resource name.
            MutateCampaignCriteriaResponse mutateCampaignCriteriaResponse =
                campaignCriterionServiceClient.MutateCampaignCriteria(customerId.ToString(),
                    new[] { campaignCriterionOperation });

            string campaignCriterionResourceName =
                mutateCampaignCriteriaResponse.Results.First().ResourceName;
            Console.WriteLine("Successfully created campaign criterion with resource name " +
                $"'{campaignCriterionResourceName}' targeting user list with resource name " +
                $"'{userListResourceName}' with campaign with ID {campaignId}.");

            return campaignCriterionResourceName;
        }

        /// <summary>
        /// Updates the bid modifier on a campaign criterion.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignCriterionResourceName">The resource name of the campaign criterion to update.</param>
        /// <param name="bidModifierValue">The bid modifier value.</param>
        private void ModifyCampaignBids(
            GoogleAdsClient client,
            long customerId,
            string campaignCriterionResourceName,
            double bidModifierValue)
        {
            // Get the CampaignCriterionService client.
            CampaignCriterionServiceClient campaignCriterionServiceClient =
                client.GetService(Services.V17.CampaignCriterionService);

            // Create the campaign criterion to update.
            CampaignCriterion campaignCriterion = new CampaignCriterion
            {
                ResourceName = campaignCriterionResourceName,
                BidModifier = (float) bidModifierValue
            };

            // Create the update operation.
            CampaignCriterionOperation campaignCriterionOperation = new CampaignCriterionOperation
            {
                Update = campaignCriterion,
                UpdateMask = FieldMasks.AllSetFieldsOf(campaignCriterion)
            };

            // Update the campaign criterion and print the results.
            MutateCampaignCriteriaResponse mutateCampaignCriteriaResponse =
                campaignCriterionServiceClient.MutateCampaignCriteria(customerId.ToString(),
                    new[] { campaignCriterionOperation });
            Console.WriteLine("Successfully updated the bid for campaign criterion with resource " +
                $"name '{mutateCampaignCriteriaResponse.Results.First().CampaignCriterion}'.");
        }
    }
}

      

PHP

<?php

/**
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://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\Ads\GoogleAds\Examples\Remarketing;

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

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Examples\Utils\Helper;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException;
use Google\Ads\GoogleAds\Util\FieldMasks;
use Google\Ads\GoogleAds\Util\V17\ResourceNames;
use Google\Ads\GoogleAds\V17\Common\FlexibleRuleOperandInfo;
use Google\Ads\GoogleAds\V17\Common\FlexibleRuleUserListInfo;
use Google\Ads\GoogleAds\V17\Common\RuleBasedUserListInfo;
use Google\Ads\GoogleAds\V17\Common\UserListInfo;
use Google\Ads\GoogleAds\V17\Common\UserListRuleInfo;
use Google\Ads\GoogleAds\V17\Common\UserListRuleItemGroupInfo;
use Google\Ads\GoogleAds\V17\Common\UserListRuleItemInfo;
use Google\Ads\GoogleAds\V17\Common\UserListStringRuleItemInfo;
use Google\Ads\GoogleAds\V17\Enums\UserListFlexibleRuleOperatorEnum\UserListFlexibleRuleOperator;
use Google\Ads\GoogleAds\V17\Enums\UserListMembershipStatusEnum\UserListMembershipStatus;
use Google\Ads\GoogleAds\V17\Enums\UserListPrepopulationStatusEnum\UserListPrepopulationStatus;
use Google\Ads\GoogleAds\V17\Enums\UserListStringRuleItemOperatorEnum\UserListStringRuleItemOperator;
use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V17\Resources\AdGroupCriterion;
use Google\Ads\GoogleAds\V17\Resources\CampaignCriterion;
use Google\Ads\GoogleAds\V17\Resources\UserList;
use Google\Ads\GoogleAds\V17\Services\AdGroupCriterionOperation;
use Google\Ads\GoogleAds\V17\Services\CampaignCriterionOperation;
use Google\Ads\GoogleAds\V17\Services\GoogleAdsRow;
use Google\Ads\GoogleAds\V17\Services\MutateAdGroupCriteriaRequest;
use Google\Ads\GoogleAds\V17\Services\MutateAdGroupCriteriaResponse;
use Google\Ads\GoogleAds\V17\Services\MutateCampaignCriteriaRequest;
use Google\Ads\GoogleAds\V17\Services\MutateCampaignCriteriaResponse;
use Google\Ads\GoogleAds\V17\Services\MutateUserListsRequest;
use Google\Ads\GoogleAds\V17\Services\MutateUserListsResponse;
use Google\Ads\GoogleAds\V17\Services\SearchGoogleAdsRequest;
use Google\Ads\GoogleAds\V17\Services\UserListOperation;
use Google\ApiCore\ApiException;

/**
 * Demonstrates various operations involved in remarketing, including (a) creating a user list based
 * on visitors to a website, (b) targeting a user list with an ad group criterion, (c) updating the
 * bid modifier on an ad group criterion, (d) finding and removing all ad group criteria under a
 * given campaign, (e) targeting a user list with a campaign criterion, and (f) updating the bid
 * modifier on a campaign criterion. It is unlikely that users will need to perform all of these
 * operations consecutively, and all of the operations contained herein are meant of for
 * illustrative purposes.
 */
class SetUpRemarketing
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
    private const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

    // Optional: To use a different bid modifier value from the default (1.5), modify
    // the line below with your desired bid modifier value.
    private const BID_MODIFIER_VALUE = 1.5;

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::CAMPAIGN_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::AD_GROUP_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::BID_MODIFIER_VALUE => GetOpt::OPTIONAL_ARGUMENT
        ]);

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

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            // We set this value to true to show how to use GAPIC v2 source code. You can remove the
            // below line if you wish to use the old-style source code. Note that in that case, you
            // probably need to modify some parts of the code below to make it work.
            // For more information, see
            // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic.
            ->usingGapicV2Source(true)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::CAMPAIGN_ID] ?: self::CAMPAIGN_ID,
                $options[ArgumentNames::AD_GROUP_ID] ?: self::AD_GROUP_ID,
                $options[ArgumentNames::BID_MODIFIER_VALUE] ?: self::BID_MODIFIER_VALUE
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
            exit(1);
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
            exit(1);
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param int $campaignId the campaign ID
     * @param int $adGroupId the ad group ID
     * @param float $bidModifierValue the bid modifier value
     */
    private static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $campaignId,
        int $adGroupId,
        float $bidModifierValue
    ) {
        $userListResourceName = self::createUserList($googleAdsClient, $customerId);
        $adGroupCriterionResourceName = self::targetAdsInAdGroupToUserList(
            $googleAdsClient,
            $customerId,
            $adGroupId,
            $userListResourceName
        );
        self::modifyAdGroupBids(
            $googleAdsClient,
            $customerId,
            $adGroupCriterionResourceName,
            $bidModifierValue
        );
        self::removeExistingListCriteriaFromAdGroup($googleAdsClient, $customerId, $campaignId);
        $campaignCriterionResourceName = self::targetAdsInCampaignToUserList(
            $googleAdsClient,
            $customerId,
            $campaignId,
            $userListResourceName
        );
        self::modifyCampaignBids(
            $googleAdsClient,
            $customerId,
            $campaignCriterionResourceName,
            $bidModifierValue
        );
    }

    /**
     * Creates a user list targeting users that have visited a given URL.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @return string the user list resource name
     */
    private static function createUserList(
        GoogleAdsClient $googleAdsClient,
        int $customerId
    ): string {
        // Creates a rule targeting any user that visited a URL containing 'example.com'.
        $rule = new UserListRuleItemInfo([
            // Uses a built-in parameter to create a domain URL rule.
            'name' => 'url__',
            'string_rule_item' => new UserListStringRuleItemInfo([
                'operator' => UserListStringRuleItemOperator::CONTAINS,
                'value' => 'example.com'
            ])
        ]);

        // Specifies that the user list targets visitors of a page based on the provided rule.
        $flexibleRuleUserListInfo = new FlexibleRuleUserListInfo([
            'inclusive_rule_operator' => UserListFlexibleRuleOperator::PBAND,
            // Inclusive operands are joined together with the specified inclusive rule operator.
            'inclusive_operands' => [
                new FlexibleRuleOperandInfo([
                    'rule' => new UserListRuleInfo([
                        'rule_item_groups' =>
                            [new UserListRuleItemGroupInfo(['rule_items' => [$rule]])]
                    ]),
                    // Optionally add a lookback window for this rule, in days.
                    'lookback_window_days' => 7
                ])
            ],
            'exclusive_operands' => []
        ]);

        // Defines a representation of a user list that is generated by a rule.
        $ruleBasedUserListInfo = new RuleBasedUserListInfo([
            'flexible_rule_user_list' => $flexibleRuleUserListInfo,
            // Optional: To include past users in the user list, set the prepopulation_status to
            // REQUESTED.
            'prepopulation_status' => UserListPrepopulationStatus::REQUESTED
        ]);

        // Creates the user list.
        $userList = new UserList([
            'name' => "All visitors to example.com #" . Helper::getPrintableDatetime(),
            'description' => "Any visitor to any page of example.com",
            'membership_status' => UserListMembershipStatus::OPEN,
            'membership_life_span' => 365,
            'rule_based_user_list' => $ruleBasedUserListInfo
        ]);

        // Creates the operation.
        $operation = new UserListOperation();
        $operation->setCreate($userList);

        // Issues a mutate request to add a user list.
        $userListServiceClient = $googleAdsClient->getUserListServiceClient();
        /** @var MutateUserListsResponse $userListResponse */
        $userListResponse = $userListServiceClient->mutateUserLists(
            MutateUserListsRequest::build($customerId, [$operation])
        );

        $userListResourceName = $userListResponse->getResults()[0]->getResourceName();
        printf("Created user list with resource name '%s'.%s", $userListResourceName, PHP_EOL);

        return $userListResourceName;
    }

    /**
     * Creates an ad group criterion that targets a user list with an ad group.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param int $adGroupId the ad group ID
     * @param string $userListResourceName the user list resource name
     * @return string the ad group criterion resource name
     */
    private static function targetAdsInAdGroupToUserList(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $adGroupId,
        string $userListResourceName
    ): string {
        // Creates the ad group criterion targeting members of the user list.
        $adGroupCriterion = new AdGroupCriterion([
            'ad_group' => ResourceNames::forAdGroup($customerId, $adGroupId),
            'user_list' => new UserListInfo(['user_list' => $userListResourceName])
        ]);

        // Creates the operation.
        $operation = new AdGroupCriterionOperation();
        $operation->setCreate($adGroupCriterion);

        // Issues a mutate request to add an ad group criterion.
        $adGroupCriterionServiceClient = $googleAdsClient->getAdGroupCriterionServiceClient();
        /** @var MutateAdGroupCriteriaResponse $adGroupCriterionResponse */
        $adGroupCriterionResponse = $adGroupCriterionServiceClient->mutateAdGroupCriteria(
            MutateAdGroupCriteriaRequest::build($customerId, [$operation])
        );

        $adGroupCriterionResourceName =
            $adGroupCriterionResponse->getResults()[0]->getResourceName();
        printf(
            "Successfully created ad group criterion with resource name '%s' " .
            "targeting user list with resource name '%s' with ad group with ID %d.%s",
            $adGroupCriterionResourceName,
            $userListResourceName,
            $adGroupId,
            PHP_EOL
        );

        return $adGroupCriterionResourceName;
    }

    /**
     * Updates the bid modifier on an ad group criterion.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $adGroupCriterionResourceName the ad group criterion to update
     * @param float $bidModifierValue the bid modifier value
     */
    private static function modifyAdGroupBids(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $adGroupCriterionResourceName,
        float $bidModifierValue
    ) {
        // Creates the ad group criterion with a bid modifier. You may alternatively set the bid for
        // the ad group criterion directly.
        $adGroupCriterion = new AdGroupCriterion([
            'resource_name' => $adGroupCriterionResourceName,
            'bid_modifier' => $bidModifierValue
        ]);

        // Constructs an operation that will update the ad group criterion with the specified
        // resource name, using the FieldMasks utility to derive the update mask. This mask tells
        // the Google Ads API which attributes of the ad group criterion you want to change.
        $operation = new AdGroupCriterionOperation();
        $operation->setUpdate($adGroupCriterion);
        $operation->setUpdateMask(FieldMasks::allSetFieldsOf($adGroupCriterion));

        // Issues a mutate request to update an ad group criterion.
        $adGroupCriterionServiceClient = $googleAdsClient->getAdGroupCriterionServiceClient();
        /** @var MutateAdGroupCriteriaResponse $adGroupCriteriaResponse */
        $adGroupCriteriaResponse = $adGroupCriterionServiceClient->mutateAdGroupCriteria(
            MutateAdGroupCriteriaRequest::build($customerId, [$operation])
        );

        printf(
            "Updated bid for ad group criterion with resource name '%s'.%s",
            $adGroupCriteriaResponse->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }

    /**
     * Removes all ad group criteria targeting a user list under a given campaign. This is a
     * necessary step before targeting a user list at the campaign level.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param int $campaignId the campaign ID
     */
    private static function removeExistingListCriteriaFromAdGroup(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $campaignId
    ) {
        // Retrieves all of the ad group criteria under a campaign.
        $allAdGroupCriteria = self::getUserListAdGroupCriteria(
            $googleAdsClient,
            $customerId,
            $campaignId
        );

        $removeOperations = [];
        // Creates a list of remove operations.
        foreach ($allAdGroupCriteria as $adGroupCriterionResourceName) {
            $operation = new AdGroupCriterionOperation();
            $operation->setRemove($adGroupCriterionResourceName);
            $removeOperations[] = $operation;
        }

        // Issues a mutate request to remove the ad group criteria.
        $adGroupCriterionServiceClient = $googleAdsClient->getAdGroupCriterionServiceClient();
        /** @var MutateAdGroupCriteriaResponse $adGroupCriteriaResponse */
        $adGroupCriteriaResponse = $adGroupCriterionServiceClient->mutateAdGroupCriteria(
            MutateAdGroupCriteriaRequest::build($customerId, $removeOperations)
        );

        foreach ($adGroupCriteriaResponse->getResults() as $adGroupCriteriaResult) {
            printf(
                "Successfully removed ad group criterion with resource name '%s'.%s",
                $adGroupCriteriaResult->getResourceName(),
                PHP_EOL
            );
        }
    }

    /**
     * Finds all of user list ad group criteria under a campaign.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param int $campaignId the campaign ID under which to search the ad group criteria
     * @return string[] the list of the ad group criteria resource names
     */
    private static function getUserListAdGroupCriteria(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $campaignId
    ): array {
        // Creates a query that retrieves all of the ad group criteria under a campaign.
        $query = sprintf(
            "SELECT ad_group_criterion.criterion_id " .
            "FROM ad_group_criterion " .
            "WHERE campaign.id = %d " .
            "AND ad_group_criterion.type = 'USER_LIST'",
            $campaignId
        );

        // Creates the Google Ads service client.
        $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();

        // Issues the search request.
        $response =
            $googleAdsServiceClient->search(SearchGoogleAdsRequest::build($customerId, $query));

        $userListCriteria = [];
        // Iterates over all rows in all pages. Prints the user list criteria and adds the ad group
        // criteria resource names to the list.
        foreach ($response->iterateAllElements() as $googleAdsRow) {
            /** @var GoogleAdsRow $googleAdsRow */
            $adGroupCriterionResourceName = $googleAdsRow->getAdGroupCriterion()->getResourceName();

            printf(
                "Ad group criterion with resource name '%s' was found.%s",
                $adGroupCriterionResourceName,
                PHP_EOL
            );

            $userListCriteria[] = $adGroupCriterionResourceName;
        }

        return $userListCriteria;
    }

    /**
     * Creates a campaign criterion that targets a user list with a campaign.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param int $campaignId the campaign ID on which the user list will be targeted
     * @param string $userListResourceName the resource name of the user list to be targeted
     * @return string the campaign criterion resource name
     */
    private static function targetAdsInCampaignToUserList(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $campaignId,
        string $userListResourceName
    ): string {
        // Creates the campaign criterion.
        $campaignCriterion = new CampaignCriterion([
            'campaign' => ResourceNames::forCampaign($customerId, $campaignId),
            'user_list' => new UserListInfo(['user_list' => $userListResourceName])
        ]);

        // Creates the operation.
        $operation = new CampaignCriterionOperation();
        $operation->setCreate($campaignCriterion);

        // Issues a mutate request to create a campaign criterion.
        $campaignCriterionServiceClient = $googleAdsClient->getCampaignCriterionServiceClient();
        /** @var MutateCampaignCriteriaResponse $campaignCriteriaResponse */
        $campaignCriteriaResponse = $campaignCriterionServiceClient->mutateCampaignCriteria(
            MutateCampaignCriteriaRequest::build($customerId, [$operation])
        );

        $campaignCriterionResourceName =
            $campaignCriteriaResponse->getResults()[0]->getResourceName();
        printf(
            "Successfully created campaign criterion with resource name '%s' " .
            "targeting user list with resource name '%s' with campaign with ID %d.%s",
            $campaignCriterionResourceName,
            $userListResourceName,
            $campaignId,
            PHP_EOL
        );

        return $campaignCriterionResourceName;
    }

    /**
     * Updates the bid modifier on a campaign criterion.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $campaignCriterionResourceName the campaign criterion to update
     * @param float $bidModifierValue the bid modifier value
     */
    private static function modifyCampaignBids(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $campaignCriterionResourceName,
        float $bidModifierValue
    ) {
        // Creates the campaign criterion to update.
        $campaignCriterion = new CampaignCriterion([
            'resource_name' => $campaignCriterionResourceName,
            'bid_modifier' => $bidModifierValue
        ]);

        // Constructs an operation that will update the campaign criterion with the specified
        // resource name, using the FieldMasks utility to derive the update mask. This mask tells
        // the Google Ads API which attributes of the campaign criterion you want to change.
        $operation = new CampaignCriterionOperation();
        $operation->setUpdate($campaignCriterion);
        $operation->setUpdateMask(FieldMasks::allSetFieldsOf($campaignCriterion));

        // Issues a request to update a campaign criterion.
        $campaignCriterionServiceClient = $googleAdsClient->getCampaignCriterionServiceClient();
        /** @var MutateCampaignCriteriaResponse $campaignCriteriaResponse */
        $campaignCriteriaResponse = $campaignCriterionServiceClient->mutateCampaignCriteria(
            MutateCampaignCriteriaRequest::build($customerId, [$operation])
        );

        printf(
            "Successfully updated the bid for campaign criterion with resource name '%s'.%s",
            $campaignCriteriaResponse->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }
}

SetUpRemarketing::main();

      

Python

#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://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.
"""Demonstrates various operations involved in remarketing.

Operations include (a) creating a user list based on visitors to a website,
(b) targeting a user list with an ad group criterion, (c) updating the bid
modifier on an ad group criterion, (d) finding and removing all ad group
criteria under a given campaign, (e) targeting a user list with a campaign
criterion, and (f) updating the bid modifier on a campaign criterion. It is
unlikely that users will need to perform all of these operations consecutively,
and all of the operations contained herein are meant of for illustrative
purposes.
"""


import argparse
import sys
from uuid import uuid4

from google.api_core import protobuf_helpers

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException


def main(client, customer_id, campaign_id, ad_group_id, bid_modifier_value):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a str client customer ID used to create a user list and
            other various entities required for the example.
        campaign_id: a str ID for a campaign used to create an ad group
            criterion that targets members of a user list.
        ad_group_id: a str ID for an ad group used to create an ad group
            criterion that targets members of a user list.
        bid_modifier_value: a float that specifies a modifier on the bid amount
            for newly created ad group criterion.
    """
    user_list_resource_name = create_user_list(client, customer_id)
    ad_group_criterion_resource_name = target_ads_in_ad_group_to_user_list(
        client, customer_id, ad_group_id, user_list_resource_name
    )
    modify_ad_group_bids(
        client,
        customer_id,
        ad_group_criterion_resource_name,
        bid_modifier_value,
    )
    remove_existing_criteria_from_ad_group(client, customer_id, campaign_id)
    campaign_criterion_resource_name = target_ads_in_campaign_to_user_list(
        client, customer_id, campaign_id, user_list_resource_name
    )
    modify_campaign_bids(
        client,
        customer_id,
        campaign_criterion_resource_name,
        bid_modifier_value,
    )


def create_user_list(client, customer_id):
    """Creates a user list targeting users that have visited a given URL.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a str client customer ID used to create a user list.

    Returns:
        a str resource name for the newly created user list.
    """
    # Creates a UserListOperation.
    user_list_operation = client.get_type("UserListOperation")
    # Creates a UserList.
    user_list = user_list_operation.create
    user_list.name = f"All visitors to example.com #{uuid4()}"
    user_list.description = "Any visitor to any page of example.com"
    user_list.membership_status = client.enums.UserListMembershipStatusEnum.OPEN
    user_list.membership_life_span = 365
    # Optional: To include past users in the user list, set the
    # prepopulation_status to REQUESTED.
    user_list.rule_based_user_list.prepopulation_status = (
        client.enums.UserListPrepopulationStatusEnum.REQUESTED
    )
    # Specifies that the user list targets visitors of a page with a URL that
    # contains 'example.com'.
    user_list_rule_item_group_info = client.get_type(
        "UserListRuleItemGroupInfo"
    )
    user_list_rule_item_info = client.get_type("UserListRuleItemInfo")
    # Uses a built-in parameter to create a domain URL rule.
    user_list_rule_item_info.name = "url__"
    user_list_rule_item_info.string_rule_item.operator = (
        client.enums.UserListStringRuleItemOperatorEnum.CONTAINS
    )
    user_list_rule_item_info.string_rule_item.value = "example.com"
    user_list_rule_item_group_info.rule_items.append(user_list_rule_item_info)

    # Specify that the user list targets visitors of a page based on the
    # provided rule.
    flexible_rule_user_list_info = (
        user_list.rule_based_user_list.flexible_rule_user_list
    )
    flexible_rule_user_list_info.inclusive_rule_operator = (
        client.enums.UserListFlexibleRuleOperatorEnum.AND
    )
    # Inclusive operands are joined together with the specified
    # inclusive rule operator.
    rule_operand = client.get_type("FlexibleRuleOperandInfo")
    rule_operand.rule.rule_item_groups.extend([user_list_rule_item_group_info])
    rule_operand.lookback_window_days = 7
    flexible_rule_user_list_info.inclusive_operands.append(rule_operand)

    user_list_service = client.get_service("UserListService")
    response = user_list_service.mutate_user_lists(
        customer_id=customer_id, operations=[user_list_operation]
    )
    resource_name = response.results[0].resource_name
    print(f"Created user list with resource name: '{resource_name}'")
    return resource_name


def target_ads_in_ad_group_to_user_list(
    client, customer_id, ad_group_id, user_list_resource_name
):
    """Creates an ad group criterion that targets a user list with an ad group.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a str client customer ID used to create an ad group
            criterion.
        ad_group_id: a str ID for an ad group used to create an ad group
            criterion that targets members of a user list.
        user_list_resource_name: a str resource name for a user list.

    Returns:
        a str resource name for an ad group criterion.
    """
    ad_group_criterion_operation = client.get_type("AdGroupCriterionOperation")
    # Creates the ad group criterion targeting members of the user list.
    ad_group_criterion = ad_group_criterion_operation.create
    ad_group_criterion.ad_group = client.get_service(
        "AdGroupService"
    ).ad_group_path(customer_id, ad_group_id)
    ad_group_criterion.user_list.user_list = user_list_resource_name

    ad_group_criterion_service = client.get_service("AdGroupCriterionService")
    response = ad_group_criterion_service.mutate_ad_group_criteria(
        customer_id=customer_id, operations=[ad_group_criterion_operation]
    )
    resource_name = response.results[0].resource_name
    print(
        "Successfully created ad group criterion with resource name: "
        f"'{resource_name}' targeting user list with resource name: "
        f"'{user_list_resource_name}' and with ad group with ID "
        f"{ad_group_id}."
    )
    return resource_name


def modify_ad_group_bids(
    client, customer_id, ad_group_criterion_resource_name, bid_modifier_value
):
    """Updates the bid modifier on an ad group criterion.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a str client customer ID.
        ad_group_criterion.resource_name: a str resource name for an ad group
            criterion.
        bid_modifier_value: a float value specifying an ad group criterion
            bid modifier.
    """
    # Constructs an operation that will update the ad group criterion with the
    # specified resource name.
    ad_group_criterion_operation = client.get_type("AdGroupCriterionOperation")
    ad_group_criterion = ad_group_criterion_operation.update
    # Creates the ad group criterion with a bid modifier. You may alternatively
    # set the bid for the ad group criterion directly.
    ad_group_criterion.resource_name = ad_group_criterion_resource_name
    ad_group_criterion.bid_modifier = bid_modifier_value
    # Using the FieldMasks utility to derive the update mask tells the Google
    # Ads API which attributes of the ad group criterion you want to change.
    client.copy_from(
        ad_group_criterion_operation.update_mask,
        protobuf_helpers.field_mask(None, ad_group_criterion._pb),
    )
    ad_group_criterion_service = client.get_service("AdGroupCriterionService")
    response = ad_group_criterion_service.mutate_ad_group_criteria(
        customer_id=customer_id, operations=[ad_group_criterion_operation]
    )
    print(
        "Updated bid for ad group criterion with resource name: "
        f"'{response.results[0].resource_name}'"
    )


def remove_existing_criteria_from_ad_group(client, customer_id, campaign_id):
    """Removes all ad group criteria targeting a user list under a campaign.

    This is a necessary step before targeting a user list at the campaign level.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a str client customer ID.
        campaign_id: a str ID for a campaign that will have all ad group
            criteria that targets user lists removed.
    """
    # Retrieves all of the ad group criteria under a campaign.
    all_ad_group_criteria = get_user_list_ad_group_criteria(
        client, customer_id, campaign_id
    )

    # Creates a list of remove operations.
    remove_operations = []
    for ad_group_criterion_resource_name in all_ad_group_criteria:
        remove_operation = client.get_type("AdGroupCriterionOperation")
        remove_operation.remove = ad_group_criterion_resource_name
        remove_operations.append(remove_operation)

    ad_group_criterion_service = client.get_service("AdGroupCriterionService")
    response = ad_group_criterion_service.mutate_ad_group_criteria(
        customer_id=customer_id, operations=remove_operations
    )
    print(
        "Successfully removed ad group criterion with resource name: "
        f"'{response.results[0].resource_name}'"
    )


def get_user_list_ad_group_criteria(client, customer_id, campaign_id):
    """Finds all of user list ad group criteria under a campaign.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a str client customer ID.
        campaign_id: a str campaign ID.

    Returns:
        a list of ad group criterion resource names.
    """
    # Creates a query that retrieves all of the ad group criteria under a
    # campaign.
    query = f"""
        SELECT
          ad_group_criterion.criterion_id
        FROM ad_group_criterion
        WHERE campaign.id = {campaign_id}
        AND ad_group_criterion.type = USER_LIST"""

    googleads_service = client.get_service("GoogleAdsService")
    search_request = client.get_type("SearchGoogleAdsRequest")
    search_request.customer_id = customer_id
    search_request.query = query
    response = googleads_service.search(request=search_request)

    # Iterates over all rows in all pages. Prints the user list criteria and
    # adds the ad group criteria resource names to the list.
    user_list_criteria = []
    for row in response:
        resource_name = row.ad_group_criterion.resource_name
        print(
            "Ad group criterion with resource name '{resource_name}' was "
            "found."
        )
        user_list_criteria.append(resource_name)

    return user_list_criteria


def target_ads_in_campaign_to_user_list(
    client, customer_id, campaign_id, user_list_resource_name
):
    """Creates a campaign criterion that targets a user list with a campaign.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a str client customer ID used to create an campaign
            criterion.
        campaign_id: a str ID for a campaign used to create a campaign
            criterion that targets members of a user list.
        user_list_resource_name: a str resource name for a user list.

    Returns:
        a str resource name for a campaign criterion.
    """
    campaign_criterion_operation = client.get_type("CampaignCriterionOperation")
    campaign_criterion = campaign_criterion_operation.create
    campaign_criterion.campaign = client.get_service(
        "CampaignService"
    ).campaign_path(customer_id, campaign_id)
    campaign_criterion.user_list.user_list = user_list_resource_name

    campaign_criterion_service = client.get_service("CampaignCriterionService")
    response = campaign_criterion_service.mutate_campaign_criteria(
        customer_id=customer_id, operations=[campaign_criterion_operation]
    )
    resource_name = response.results[0].resource_name
    print(
        "Successfully created campaign criterion with resource name "
        f"'{resource_name}' targeting user list with resource name "
        f"'{user_list_resource_name}' with campaign with ID {campaign_id}"
    )
    return resource_name


def modify_campaign_bids(
    client, customer_id, campaign_criterion_resource_name, bid_modifier_value
):
    """Updates the bid modifier on a campaign criterion.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a str client customer ID.
        campaign_criterion_resource_name: a str resource name for a campaign
            criterion.
        bid_modifier_value: a float value specifying a campaign criterion
            bid modifier.
    """
    # Constructs an operation that will update the campaign criterion with the
    # specified resource name.
    campaign_criterion_operation = client.get_type("CampaignCriterionOperation")
    campaign_criterion = campaign_criterion_operation.update
    campaign_criterion.resource_name = campaign_criterion_resource_name
    campaign_criterion.bid_modifier = bid_modifier_value

    # Using the FieldMasks utility to derive the update mask tells the Google
    # Ads API which attributes of the campaign criterion you want to change.
    client.copy_from(
        campaign_criterion_operation.update_mask,
        protobuf_helpers.field_mask(None, campaign_criterion._pb),
    )

    campaign_criterion_service = client.get_service("CampaignCriterionService")
    response = campaign_criterion_service.mutate_campaign_criteria(
        customer_id=customer_id, operations=[campaign_criterion_operation]
    )
    print(
        "Successfully updated the bid for campaign criterion with resource "
        f"name: '{response.results[0].resource_name}'"
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Demonstrates various operations involved in remarketing."
    )
    # The following arguments are required to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help=(
            "A Google Ads customer ID used to create a user list and other "
            "various entities required for the example."
        ),
    )
    parser.add_argument(
        "-i",
        "--campaign_id",
        type=str,
        required=True,
        help=(
            "The ID for a campaign that will have its ad group criteria "
            "modified to target user lists members."
        ),
    )
    parser.add_argument(
        "-a",
        "--ad_group_id",
        type=str,
        required=True,
        help=(
            "The ID for an ad group used to create an ad group criterion "
            "that targets members of a user list."
        ),
    )
    # The following argument is optional.
    parser.add_argument(
        "-b",
        "--bid_modifier_value",
        type=float,
        default=1.5,
        help=(
            "A float that specifies a modifier on the bid amount "
            "for newly created ad group criterion."
        ),
    )
    args = parser.parse_args()

    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v17")

    try:
        main(
            googleads_client,
            args.customer_id,
            args.campaign_id,
            args.ad_group_id,
            args.bid_modifier_value,
        )
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

      

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://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.
#
# Demonstrates various operations involved in remarketing, including:
# (a) creating a user list based on visitors to a website
# (b) targeting a user list with an ad group criterion
# (c) updating the bid modifier on an ad group criterion
# (d) finding and removing all ad group criteria under a given campaign
# (e) targeting a user list with a campaign criterion
# (f) updating the bid modifier on a campaign criterion
# It is unlikely that users will need to perform all of these operations
# consecutively, and all of the operations contained herein are meant of for
# illustrative purposes.

require 'optparse'
require 'google/ads/google_ads'
require 'date'

def set_up_remarketing(customer_id, campaign_id, ad_group_id, bid_modifier_value)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  user_list = create_user_list(client, customer_id)

  ad_group_criterion_resource_name = target_ads_in_ad_group_to_user_list(
    client,
    customer_id,
    ad_group_id,
    user_list,
  )

  modify_ad_group_bids(
    client,
    customer_id,
    ad_group_criterion_resource_name,
    bid_modifier_value,
  )

  remove_existing_list_criteria_from_ad_group(
    client,
    customer_id,
    campaign_id,
  )

  campaign_criterion_resource_name = target_ads_in_campaign_to_user_list(
    client,
    customer_id,
    campaign_id,
    user_list,
  )

  modify_campaign_bids(
    client,
    customer_id,
    campaign_criterion_resource_name,
    bid_modifier_value,
  )
end

# Creates a user list targeting users that have visited a given url.
def create_user_list(client, customer_id)
  # Creates the user list operation.
  operation = client.operation.create_resource.user_list do |ul|
    ul.name = "All visitors to example.com ##{(Time.new.to_f * 1000).to_i}"
    ul.description = "Any visitor to any page of example.com"
    ul.membership_status = :OPEN
    ul.membership_life_span = 365
    # Defines a representation of a user list that is generated by a rule.
    ul.rule_based_user_list = client.resource.rule_based_user_list_info do |r|
      # To include past users in the user list, set the prepopulation_status
      # to REQUESTED.
      r.prepopulation_status = :REQUESTED
      # Specifies that the user list targets visitors of a page based on
      # the provided rule.
      r.flexible_rule_user_list = client.resource.flexible_rule_user_list_info do |frul|
        frul.inclusive_rule_operator = :AND
        frul.inclusive_operands << client.resource.flexible_rule_operand_info do |froi|
          froi.rule = client.resource.user_list_rule_info do |u|
            u.rule_item_groups << client.resource.user_list_rule_item_group_info do |group|
              group.rule_items << client.resource.user_list_rule_item_info do |item|
                # Uses a built-in parameter to create a domain URL rule.
                item.name = "url__"
                item.string_rule_item = client.resource.user_list_string_rule_item_info do |s|
                  s.operator = :CONTAINS
                  s.value = "example.com"
                end
              end
            end
          end
          # Optionally add a lookback window for this rule, in days.
          froi.lookback_window_days = 7
        end
      end
    end
  end

  # Issues a mutate request to add the user list.
  response = client.service.user_list.mutate_user_lists(
    customer_id: customer_id,
    operations: [operation],
  )
  user_list_resource_name = response.results.first.resource_name
  puts "Created user list with resource name '#{user_list_resource_name}'"

  user_list_resource_name
end

# Creates an ad group criterion that targets a user list with an ad group.
def target_ads_in_ad_group_to_user_list(
  client,
  customer_id,
  ad_group_id,
  user_list
)
  # Creates the ad group criterion targeting members of the user list.
  operation = client.operation.create_resource.ad_group_criterion do |agc|
    agc.ad_group = client.path.ad_group(customer_id, ad_group_id)
    agc.user_list = client.resource.user_list_info do |info|
      info.user_list = user_list
    end
  end

  # Issues a mutate request to create the ad group criterion.
  response = client.service.ad_group_criterion.mutate_ad_group_criteria(
    customer_id: customer_id,
    operations: [operation],
  )
  ad_group_criterion_resource_name = response.results.first.resource_name
  puts "Successfully created ad group criterion with resource name " \
    "'#{ad_group_criterion_resource_name}' targeting user list with resource name " \
    "'#{user_list}' with ad group with ID #{ad_group_id}"

  ad_group_criterion_resource_name
end

# Updates the bid modifier on an ad group criterion.
def modify_ad_group_bids(
  client,
  customer_id,
  ad_group_criterion_resource_name,
  bid_modifier_value
)
  # Creates the update operation to modify the bid.
  operation = client.operation.update_resource.ad_group_criterion(
    ad_group_criterion_resource_name) do |agc|
    agc.bid_modifier = bid_modifier_value
  end

  # Issues a mutate request to update the ad group criterion.
  response = client.service.ad_group_criterion.mutate_ad_group_criteria(
    customer_id: customer_id,
    operations: [operation],
  )
  puts "Successfully updated the bid for ad group criterion with resource name " \
    "#{response.results.first.resource_name}"
end

# Removes all ad group criteria targeting a user list under a given campaign.
# This is a necessary step before targeting a user list at the campaign level.
def remove_existing_list_criteria_from_ad_group(
  client,
  customer_id,
  campaign_id
)
  # Retrieves all of the ad group criteria under a campaign.
  ad_group_criteria = get_user_list_ad_group_criterion(
    client, customer_id, campaign_id)

  # Creates a list of remove operations.
  operations = []
  ad_group_criteria.each do |agc|
    operations << client.operation.remove_resource.ad_group_criterion(agc)
  end

  # Issues a mutate request to remove all ad group criteria.
  response = client.service.ad_group_criterion.mutate_ad_group_criteria(
    customer_id: customer_id,
    operations: operations,
  )
  puts "Removed #{response.results.size} ad group criteria."
  response.results.each do |result|
    puts "Successfully removed ad group criterion with resource name " \
      "'#{result.resource_name}'"
  end
end

# Finds all of user list ad group criteria under a campaign.
def get_user_list_ad_group_criterion(
  client,
  customer_id,
  campaign_id
)
  user_list_criteria = []

  # Creates a query that will retrieve all of the ad group criteria 
  # under a campaign.
  query = <<~QUERY
    SELECT ad_group_criterion.criterion_id
    FROM ad_group_criterion
    WHERE campaign.id = #{campaign_id}
    AND ad_group_criterion.type = 'USER_LIST'
  QUERY

  # Issues the search request.
  response = client.service.google_ads.search(
    customer_id: customer_id,
    query: query,
    page_size: PAGE_SIZE,
  )

  # Iterates over all rows in all pages. Prints the results and adds the ad
  # group criteria resource names to the list.
  response.each do |row|
    ad_group_criterion_resource_name = row.ad_group_criterion.resource_name
    puts "Ad group criterion with resource name " \
      "'#{ad_group_criterion_resource_name}' was found"
    user_list_criteria << ad_group_criterion_resource_name
  end

  user_list_criteria
end

# Creates a campaign criterion that targets a user list with a campaign.
def target_ads_in_campaign_to_user_list(
  client,
  customer_id,
  campaign_id,
  user_list
)
  # Creates the campaign criterion targeting members of the user list.
  operation = client.operation.create_resource.campaign_criterion do |cc|
    cc.campaign = client.path.campaign(customer_id, campaign_id)
    cc.user_list = client.resource.user_list_info do |info|
      info.user_list = user_list
    end
  end

  # Issues a mutate request to create the campaign criterion.
  response = client.service.campaign_criterion.mutate_campaign_criteria(
    customer_id: customer_id,
    operations: [operation],
  )
  campaign_criterion_resource_name = response.results.first.resource_name
  puts "Successfully created campaign criterion with resource name " \
    "'#{campaign_criterion_resource_name}' targeting user list with resource name " \
    "'#{user_list}' with campaign with ID #{campaign_id}"

  campaign_criterion_resource_name
end

# Updates the bid modifier on a campaign criterion.
def modify_campaign_bids(
  client,
  customer_id,
  campaign_criterion_resource_name,
  bid_modifier_value
)
  # Creates the update operation to modify the bid.
  operation = client.operation.update_resource.campaign_criterion(
    campaign_criterion_resource_name) do |cc|
    cc.bid_modifier = bid_modifier_value
  end

  # Issues a mutate request to update the campaign criterion.
  response = client.service.campaign_criterion.mutate_campaign_criteria(
    customer_id: customer_id,
    operations: [operation],
  )
  puts "Successfully updated the bid for campaign criterion with resource name " \
    "#{response.results.first.resource_name}"
end

if __FILE__ == $0
  PAGE_SIZE = 1000

  options = {}

  # Running the example with -h will print the command line usage.
  options[:bid_modifier_value] = 1.5

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))

    opts.separator ''
    opts.separator 'Options:'

    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.on('-c', '--campaign-id CAMPAIGN-ID', String, 'Campaign ID') do |v|
      options[:campaign_id] = v
    end

    opts.on('-A', '--ad-group-id AD-GROUP-ID', String, 'Ad Group ID') do |v|
      options[:ad_group_id] = v
    end

    opts.on('-B', '--bid-modifier-value BID-MODIFIER-VALUE', Float, 
      'Bid Modifier Value (Optional)') do |v|
      options[:bid_modifier_value] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    set_up_remarketing(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:campaign_id),
      options.fetch(:ad_group_id),
      options.fetch(:bid_modifier_value),
    )
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
        end
      end
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
      end
    end
    raise
  end
end

      

Perl

#!/usr/bin/perl -w
#
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Demonstrates various operations involved in remarketing, including:
#   (a) Creating a user list based on visitors to a website.
#   (b) Targeting a user list with an ad group criterion.
#   (c) Updating the bid modifier on an ad group criterion.
#   (d) Finding and removing all ad group criteria under a given campaign.
#   (e) Targeting a user list with a campaign criterion.
#   (f) Updating the bid modifier on a campaign criterion.
# It is unlikely that users will need to perform all of these operations
# consecutively, and all of the operations contained herein are meant for
# illustrative purposes.
#
# Note: you can use user lists to target at the campaign or ad group level, but
# not both simultaneously. Consider removing or disabling any existing user
# lists at the campaign level before running this example.

use strict;
use warnings;
use utf8;

use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::Utils::FieldMasks;
use Google::Ads::GoogleAds::Utils::SearchStreamHandler;
use Google::Ads::GoogleAds::V17::Resources::AdGroupCriterion;
use Google::Ads::GoogleAds::V17::Resources::CampaignCriterion;
use Google::Ads::GoogleAds::V17::Resources::UserList;
use Google::Ads::GoogleAds::V17::Common::FlexibleRuleOperandInfo;
use Google::Ads::GoogleAds::V17::Common::FlexibleRuleUserListInfo;
use Google::Ads::GoogleAds::V17::Common::RuleBasedUserListInfo;
use Google::Ads::GoogleAds::V17::Common::UserListInfo;
use Google::Ads::GoogleAds::V17::Common::UserListRuleInfo;
use Google::Ads::GoogleAds::V17::Common::UserListRuleItemInfo;
use Google::Ads::GoogleAds::V17::Common::UserListRuleItemGroupInfo;
use Google::Ads::GoogleAds::V17::Common::UserListStringRuleItemInfo;
use Google::Ads::GoogleAds::V17::Enums::UserListFlexibleRuleOperatorEnum
  qw(AND);
use Google::Ads::GoogleAds::V17::Enums::UserListMembershipStatusEnum qw(OPEN);
use Google::Ads::GoogleAds::V17::Enums::UserListPrepopulationStatusEnum
  qw(REQUESTED);
use Google::Ads::GoogleAds::V17::Enums::UserListStringRuleItemOperatorEnum
  qw(CONTAINS);
use
  Google::Ads::GoogleAds::V17::Services::AdGroupCriterionService::AdGroupCriterionOperation;
use
  Google::Ads::GoogleAds::V17::Services::CampaignCriterionService::CampaignCriterionOperation;
use
  Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsStreamRequest;
use Google::Ads::GoogleAds::V17::Services::UserListService::UserListOperation;
use Google::Ads::GoogleAds::V17::Utils::ResourceNames;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd          qw(abs_path);
use Data::Uniqid qw(uniqid);

sub set_up_remarketing {
  my ($api_client, $customer_id, $ad_group_id, $campaign_id,
    $bid_modifier_value)
    = @_;

  # Create a new example user list.
  my $user_list_resource_name = create_user_list($api_client, $customer_id);

  # Target an ad group to the new user list.
  my $ad_group_criterion_resource_name =
    target_ads_in_ad_group_to_user_list($api_client, $customer_id,
    $ad_group_id, $user_list_resource_name);
  modify_ad_group_bids($api_client, $customer_id,
    $ad_group_criterion_resource_name,
    $bid_modifier_value);

  # Remove any existing user lists at the ad group level.
  remove_existing_list_criteria_from_ad_group($api_client, $customer_id,
    $campaign_id);

  # Target the campaign to the new user list.
  my $campaign_criterion_resource_name =
    target_ads_in_campaign_to_user_list($api_client, $customer_id, $campaign_id,
    $user_list_resource_name);
  modify_campaign_bids($api_client, $customer_id,
    $campaign_criterion_resource_name,
    $bid_modifier_value);

  return 1;
}

# Creates a user list targeting users that have visited a given url.
sub create_user_list {
  my ($api_client, $customer_id) = @_;

  # Create a rule targeting any user that visited a url containing 'example.com'.
  my $rule = Google::Ads::GoogleAds::V17::Common::UserListRuleItemInfo->new({
      # Use a built-in parameter to create a domain URL rule.
      name           => "url__",
      stringRuleItem =>
        Google::Ads::GoogleAds::V17::Common::UserListStringRuleItemInfo->new({
          operator => CONTAINS,
          value    => "example.com"
        })});

  # Specify that the user list targets visitors of a page based on the provided rule.
  my $user_list_rule_item_group_info =
    Google::Ads::GoogleAds::V17::Common::UserListRuleItemGroupInfo->new(
    {ruleItems => [$rule]});
  my $flexible_rule_user_list_info =
    Google::Ads::GoogleAds::V17::Common::FlexibleRuleUserListInfo->new({
      inclusiveRuleOperator => AND,
      # Inclusive operands are joined together with the specified inclusiveRuleOperator.
      inclusiveOperands => [
        Google::Ads::GoogleAds::V17::Common::FlexibleRuleOperandInfo->new({
            rule => Google::Ads::GoogleAds::V17::Common::UserListRuleInfo->new({
                ruleItemGroups => [$user_list_rule_item_group_info]}
            ),
            # Optionally add a lookback window for this rule, in days.
            lookbackWindowDays => 7
          })
      ],
      exclusiveOperands => []});

  # Define a representation of a user list that is generated by a rule.
  my $rule_based_user_list_info =
    Google::Ads::GoogleAds::V17::Common::RuleBasedUserListInfo->new({
      # Optional: To include past users in the user list, set the
      # prepopulationStatus to REQUESTED.
      prepopulationStatus  => REQUESTED,
      flexibleRuleUserList => $flexible_rule_user_list_info
    });

  # Create the user list.
  my $user_list = Google::Ads::GoogleAds::V17::Resources::UserList->new({
    name               => "All visitors to example.com #" . uniqid(),
    description        => "Any visitor to any page of example.com",
    membershipLifespan => 365,
    membershipStatus   => OPEN,
    ruleBasedUserList  => $rule_based_user_list_info
  });

  # Create the operation.
  my $user_list_operation =
    Google::Ads::GoogleAds::V17::Services::UserListService::UserListOperation->
    new({
      create => $user_list
    });

  # Add the user list, then print and return the new list's resource name.
  my $user_lists_response = $api_client->UserListService()->mutate({
      customerId => $customer_id,
      operations => [$user_list_operation]});

  my $user_list_resource_name =
    $user_lists_response->{results}[0]{resourceName};
  printf "Created user list with resource name '%s'.\n",
    $user_list_resource_name;

  return $user_list_resource_name;
}

# Creates an ad group criterion that targets a user list with an ad group.
sub target_ads_in_ad_group_to_user_list {
  my ($api_client, $customer_id, $ad_group_id, $user_list_resource_name) = @_;

  # Create the ad group criterion targeting members of the user list.
  my $ad_group_criterion =
    Google::Ads::GoogleAds::V17::Resources::AdGroupCriterion->new({
      adGroup => Google::Ads::GoogleAds::V17::Utils::ResourceNames::ad_group(
        $customer_id, $ad_group_id
      ),
      userList => Google::Ads::GoogleAds::V17::Common::UserListInfo->new({
          userList => $user_list_resource_name
        })});

  # Create the operation.
  my $ad_group_criterion_operation =
    Google::Ads::GoogleAds::V17::Services::AdGroupCriterionService::AdGroupCriterionOperation
    ->new({
      create => $ad_group_criterion
    });

  # Add the ad group criterion, then print and return the new criterion's resource name.
  my $ad_group_criteria_response =
    $api_client->AdGroupCriterionService()->mutate({
      customerId => $customer_id,
      operations => [$ad_group_criterion_operation]});

  my $ad_group_criterion_resource_name =
    $ad_group_criteria_response->{results}[0]{resourceName};
  printf "Successfully created ad group criterion with resource name '%s' " .
    "targeting user list with resource name '%s' with ad group with ID %d.\n",
    $ad_group_criterion_resource_name, $user_list_resource_name, $ad_group_id;

  return $ad_group_criterion_resource_name;
}

# Updates the bid modifier on an ad group criterion.
sub modify_ad_group_bids {
  my ($api_client, $customer_id, $ad_group_criterion_resource_name,
    $bid_modifier_value)
    = @_;

  # Create the ad group criterion with a bid modifier. You may alternatively set
  # the bid for the ad group criterion directly.
  my $ad_group_criterion =
    Google::Ads::GoogleAds::V17::Resources::AdGroupCriterion->new({
      resourceName => $ad_group_criterion_resource_name,
      bidModifier  => $bid_modifier_value
    });

  # Create the update operation.
  my $ad_group_criterion_operation =
    Google::Ads::GoogleAds::V17::Services::AdGroupCriterionService::AdGroupCriterionOperation
    ->new({
      update     => $ad_group_criterion,
      updateMask => all_set_fields_of($ad_group_criterion)});

  # Update the ad group criterion and print the results.
  my $ad_group_criteria_response =
    $api_client->AdGroupCriterionService()->mutate({
      customerId => $customer_id,
      operations => [$ad_group_criterion_operation]});
  printf "Successfully updated the bid for ad group criterion with resource " .
    "name '%s'.\n",
    $ad_group_criteria_response->{results}[0]{resourceName};
}

# Removes all ad group criteria targeting a user list under a given campaign.
# This is a necessary step before targeting a user list at the campaign level.
sub remove_existing_list_criteria_from_ad_group {
  my ($api_client, $customer_id, $campaign_id) = @_;

  # Retrieve all of the ad group criteria under a campaign.
  my $ad_group_criteria =
    get_user_list_ad_group_criteria($api_client, $customer_id, $campaign_id);

  # Create a list of remove operations.
  my $operations = [];
  foreach my $ad_group_criterion (@$ad_group_criteria) {
    push(
      @$operations,
      Google::Ads::GoogleAds::V17::Services::AdGroupCriterionService::AdGroupCriterionOperation
        ->new({
          remove => $ad_group_criterion
        }));
  }

  # Remove the ad group criteria and print the resource names of the removed criteria.
  my $ad_group_criteria_response =
    $api_client->AdGroupCriterionService()->mutate({
      customerId => $customer_id,
      operations => $operations
    });

  printf "Removed %d ad group criteria.\n",
    scalar @{$ad_group_criteria_response->{results}};
  foreach my $result (@{$ad_group_criteria_response->{results}}) {
    printf "Successfully removed ad group criterion with resource name '%s'.\n",
      $result->{resourceName};
  }
}

# Finds all of user list ad group criteria under a campaign.
sub get_user_list_ad_group_criteria {
  my ($api_client, $customer_id, $campaign_id) = @_;

  my $user_list_criterion_resource_names = [];

  # Create a search stream request that will retrieve all of the user list ad
  # group criteria under a campaign.
  my $search_stream_request =
    Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
    ->new({
      customerId => $customer_id,
      query      => sprintf(
        "SELECT ad_group_criterion.criterion_id " .
          "FROM ad_group_criterion " .
          "WHERE campaign.id = %d AND ad_group_criterion.type = 'USER_LIST'",
        $campaign_id
      )});

  my $search_stream_handler =
    Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
      service => $api_client->GoogleAdsService(),
      request => $search_stream_request
    });

  # Issue a search request and process the stream response.
  $search_stream_handler->process_contents(
    sub {
      # Display the results and add the resource names to the list.
      my $google_ads_row = shift;

      my $ad_group_criterion_resource_name =
        $google_ads_row->{adGroupCriterion}{resourceName};
      printf "Ad group criterion with resource name '%s' was found.\n",
        $ad_group_criterion_resource_name;
      push(@$user_list_criterion_resource_names,
        $ad_group_criterion_resource_name);
    });

  return $user_list_criterion_resource_names;
}

# Creates a campaign criterion that targets a user list with a campaign.
sub target_ads_in_campaign_to_user_list {
  my ($api_client, $customer_id, $campaign_id, $user_list_resource_name) = @_;

  # Create the campaign criterion.
  my $campaign_criterion =
    Google::Ads::GoogleAds::V17::Resources::CampaignCriterion->new({
      campaign => Google::Ads::GoogleAds::V17::Utils::ResourceNames::campaign(
        $customer_id, $campaign_id
      ),
      userList => Google::Ads::GoogleAds::V17::Common::UserListInfo->new({
          userList => $user_list_resource_name
        })});

  # Create the operation.
  my $campaign_criterion_operation =
    Google::Ads::GoogleAds::V17::Services::CampaignCriterionService::CampaignCriterionOperation
    ->new({
      create => $campaign_criterion
    });

  # Add the campaign criterion and print the resulting criterion's resource name.
  my $campaign_criteria_response =
    $api_client->CampaignCriterionService()->mutate({
      customerId => $customer_id,
      operations => [$campaign_criterion_operation]});

  my $campaign_criterion_resource_name =
    $campaign_criteria_response->{results}[0]{resourceName};
  printf "Successfully created campaign criterion with resource name '%s' " .
    "targeting user list with resource name '%s' with campaign with ID %d.\n",
    $campaign_criterion_resource_name, $user_list_resource_name, $campaign_id;

  return $campaign_criterion_resource_name;
}

# Updates the bid modifier on a campaign criterion.
sub modify_campaign_bids {
  my ($api_client, $customer_id, $campaign_criterion_resource_name,
    $bid_modifier_value)
    = @_;

  # Create the campaign criterion to update.
  my $campaign_criterion =
    Google::Ads::GoogleAds::V17::Resources::CampaignCriterion->new({
      resourceName => $campaign_criterion_resource_name,
      bidModifier  => $bid_modifier_value
    });

  # Create the update operation.
  my $campaign_criterion_operation =
    Google::Ads::GoogleAds::V17::Services::CampaignCriterionService::CampaignCriterionOperation
    ->new({
      update     => $campaign_criterion,
      updateMask => all_set_fields_of($campaign_criterion)});

  # Update the campaign criterion and print the results.
  my $campaign_criteria_response =
    $api_client->CampaignCriterionService()->mutate({
      customerId => $customer_id,
      operations => [$campaign_criterion_operation]});
  printf "Successfully updated the bid for campaign criterion with " .
    "resource name '%s'.\n",
    $campaign_criteria_response->{results}[0]{resourceName};
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();

# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);

my $customer_id        = undef;
my $ad_group_id        = undef;
my $campaign_id        = undef;
my $bid_modifier_value = undef;

# Parameters passed on the command line will override any parameters set in code.
GetOptions(
  "customer_id=s"        => \$customer_id,
  "ad_group_id=i"        => \$ad_group_id,
  "campaign_id=i"        => \$campaign_id,
  "bid_modifier_value=f" => \$bid_modifier_value
);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2)
  if not check_params($customer_id, $ad_group_id, $campaign_id,
  $bid_modifier_value);

# Call the example.
set_up_remarketing($api_client, $customer_id =~ s/-//gr,
  $ad_group_id, $campaign_id, $bid_modifier_value);

=pod

=head1 NAME

set_up_remarketing

=head1 DESCRIPTION

Demonstrates various operations involved in remarketing, including:

   (a) Creating a user list based on visitors to a website.
   (b) Targeting a user list with an ad group criterion.
   (c) Updating the bid modifier on an ad group criterion.
   (d) Finding and removing all ad group criteria under a given campaign.
   (e) Targeting a user list with a campaign criterion.
   (f) Updating the bid modifier on a campaign criterion.

It is unlikely that users will need to perform all of these operations
consecutively, and all of the operations contained herein are meant of for
illustrative purposes.

Note: you can use user lists to target at the campaign or ad group level, but
not both simultaneously. Consider removing or disabling any existing user lists
at the campaign level before running this example.

=head1 SYNOPSIS

set_up_remarketing.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -ad_group_id                The ad group ID on which criteria will be targeted.
    -campaign_id                The campaign ID on which criteria will be targeted.
    -bid_modifier               The bid modifier value.

=cut