Set Up Advanced Remarketing

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.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.UserListDateRuleItemInfo;
import com.google.ads.googleads.v17.common.UserListNumberRuleItemInfo;
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.UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator;
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.UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator;
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.UserList;
import com.google.ads.googleads.v17.services.MutateUserListsResponse;
import com.google.ads.googleads.v17.services.UserListOperation;
import com.google.ads.googleads.v17.services.UserListServiceClient;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Creates a rule-based user list defined by an expression rule for users who have either checked
 * out in November or December OR visited the checkout page with more than one item in their cart.
 */
public class SetUpAdvancedRemarketing {

  private static class SetUpAdvancedRemarketingParams extends CodeSampleParams {

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

  public static void main(String[] args) {
    SetUpAdvancedRemarketingParams params = new SetUpAdvancedRemarketingParams();
    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");
    }

    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 SetUpAdvancedRemarketing().runExample(googleAdsClient, params.customerId);
    } 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.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
    // Creates a rule targeting any user that visited the checkout page.
    UserListRuleItemInfo checkoutRule =
        UserListRuleItemInfo.newBuilder()
            // The rule variable name must match a corresponding key name fired from a pixel.
            // To learn more about setting up remarketing tags, visit
            // https://support.google.com/google-ads/answer/2476688.
            // To learn more about remarketing events and parameters, visit
            // https://support.google.com/google-ads/answer/7305793.
            .setName("ecomm_pagetype")
            .setStringRuleItem(
                UserListStringRuleItemInfo.newBuilder()
                    .setOperator(UserListStringRuleItemOperator.EQUALS)
                    .setValue("checkout")
                    .build())
            .build();

    // Creates a rule targeting any user that had more than one item in their cart.
    UserListRuleItemInfo cartSizeRule =
        UserListRuleItemInfo.newBuilder()
            // The rule variable name must match a corresponding key name fired from a pixel.
            .setName("cart_size")
            .setNumberRuleItem(
                UserListNumberRuleItemInfo.newBuilder()
                    .setOperator(UserListNumberRuleItemOperator.GREATER_THAN)
                    .setValue(1.0)
                    .build())
            .build();

    // Creates a rule group that includes the checkout and cart size rules. Combining the two rule
    // items into a UserListRuleItemGroupInfo object causes Google Ads to AND their rules together.
    // To instead OR the rules together, each rule should be placed in its own rule item group.
    UserListRuleItemGroupInfo checkoutAndCartSizeRuleGroup =
        UserListRuleItemGroupInfo.newBuilder()
            .addAllRuleItems(ImmutableList.of(checkoutRule, cartSizeRule))
            .build();

    // Creates the RuleItem for checkout start date.
    // The tags and keys used below must have been in place in the past for the date range specified
    // in the rules.
    UserListRuleItemInfo startDateRule =
        UserListRuleItemInfo.newBuilder()
            // The rule variable name must match a corresponding key name fired from a pixel.
            .setName("checkoutdate")
            .setDateRuleItem(
                UserListDateRuleItemInfo.newBuilder()
                    // Available UserListDateRuleItemOperators can be found at
                    // https://developers.google.com/google-ads/api/reference/rpc/latest/UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator
                    .setOperator(UserListDateRuleItemOperator.AFTER)
                    .setValue("20191031")
                    .build())
            .build();

    // Creates the RuleItem for checkout end date.
    UserListRuleItemInfo endDateRule =
        UserListRuleItemInfo.newBuilder()
            // The rule variable name must match a corresponding key name fired from a pixel.
            .setName("checkoutdate")
            .setDateRuleItem(
                UserListDateRuleItemInfo.newBuilder()
                    .setOperator(UserListDateRuleItemOperator.BEFORE)
                    .setValue("20200101")
                    .build())
            .build();

    // Creates a rule group targeting users who checked out between November and December by using
    // the start and end date rules. Combining the two rule items into a UserListRuleItemGroupInfo
    // object causes Google Ads to AND their rules together. To instead OR the rules together, each
    // rule should be placed in its own rule item group.
    UserListRuleItemGroupInfo checkoutDateRuleGroup =
        UserListRuleItemGroupInfo.newBuilder()
            .addAllRuleItems(ImmutableList.of(startDateRule, endDateRule))
            .build();

    // Creates a FlexibleRuleUserListInfo object, or a flexible rule representation of visitors with
    // multiple actions. FlexibleRuleUserListInfo wraps UserListRuleInfo in a
    // FlexibleRuleOperandInfo object that represents which user lists to include or exclude.
    FlexibleRuleUserListInfo flexibleRuleUserListInfo =
        FlexibleRuleUserListInfo.newBuilder()
            .setInclusiveRuleOperator(UserListFlexibleRuleOperator.AND)
            .addInclusiveOperands(
                FlexibleRuleOperandInfo.newBuilder()
                    .setRule(
                        // The default rule_type for a UserListRuleInfo object is OR of ANDs
                        // (disjunctive normal form). That is, rule items will be ANDed together
                        // within rule item groups and the groups themselves will be ORed together.
                        UserListRuleInfo.newBuilder()
                            .addRuleItemGroups(checkoutDateRuleGroup)
                            .addRuleItemGroups(checkoutAndCartSizeRuleGroup))
                    // Optional: includes 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 a user list.
    UserList userList =
        UserList.newBuilder()
            .setName("My expression rule user list #" + getPrintableDateTime())
            .setDescription(
                "Users who checked out in November or December OR visited the checkout page"
                    + " with more than one item in their cart")
            .setMembershipStatus(UserListMembershipStatus.OPEN)
            .setMembershipLifeSpan(90)
            .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);
    }
  }
}

      

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.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.UserListDateRuleItemOperatorEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.UserListMembershipStatusEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.UserListNumberRuleItemOperatorEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.UserListPrepopulationStatusEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.UserListStringRuleItemOperatorEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V17
{
    /// <summary>
    /// Creates a rule-based user list defined by an expression rule for users who have either
    /// checked out in November or December OR visited the checkout page with more than one item
    /// in their cart.
    /// </summary>
    public class SetUpAdvancedRemarketing : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="SetUpAdvancedRemarketing"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the conversion action is added.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the conversion action is added.")]
            public long CustomerId { 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);

            SetUpAdvancedRemarketing codeExample = new SetUpAdvancedRemarketing();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "Creates a rule-based user list defined by an expression rule for users who have " +
            "either checked out in November or December OR visited the checkout page with more " +
            "than one item in their cart.";

        /// <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 conversion action is
        /// added.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the user list service client.
            UserListServiceClient userListServiceClient =
                client.GetService(Services.V17.UserListService);

            try
            {
                // Create a rule targeting any user that visited the checkout page.
                UserListRuleItemInfo checkoutRule = new UserListRuleItemInfo
                {
                    // The rule variable name must match a corresponding key name fired from a pixel.
                    // To learn more about setting up remarketing tags, visit
                    // https://support.google.com/google-ads/answer/2476688.
                    // To learn more about remarketing events and parameters, visit
                    // https://support.google.com/google-ads/answer/7305793.
                    Name = "ecomm_pagetype",
                    StringRuleItem = new UserListStringRuleItemInfo
                    {
                        Operator = UserListStringRuleItemOperator.Equals,
                        Value = "checkout"
                    }
                };

                // Create a rule targeting any user that had more than one item in their cart.
                UserListRuleItemInfo cartSizeRule = new UserListRuleItemInfo
                {
                    // The rule variable name must match a corresponding key name fired from a pixel.
                    Name = "cart_size",
                    NumberRuleItem = new UserListNumberRuleItemInfo
                    {
                        Operator = UserListNumberRuleItemOperator.GreaterThan,
                        Value = 1.0
                    }
                };

                // Create a rule group that includes the checkout and cart size rules. Combining the
                // two rule items into a UserListRuleItemGroupInfo object causes Google Ads to AND
                // their rules together. To instead OR the rules together, each rule should be
                // placed in its own rule item group.
                UserListRuleItemGroupInfo checkoutAndCartSizeRuleGroup =
                    new UserListRuleItemGroupInfo();
                checkoutAndCartSizeRuleGroup.RuleItems.Add(checkoutRule);
                checkoutAndCartSizeRuleGroup.RuleItems.Add(cartSizeRule);

                // Create the RuleItem for checkout start date.
                // The tags and keys used below must have been in place in the past for the date
                // range specified in the rules.
                UserListRuleItemInfo startDateRule = new UserListRuleItemInfo
                {
                    // The rule variable name must match a corresponding key name fired from a pixel.
                    Name = "checkoutdate",
                    DateRuleItem = new UserListDateRuleItemInfo
                    {
                        // Available UserListDateRuleItemOperators can be found at
                        // https://developers.google.com/google-ads/api/reference/rpc/latest/UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator
                        Operator = UserListDateRuleItemOperator.After,
                        Value = "20191031"
                    }
                };

                // Create the RuleItem for checkout end date.
                UserListRuleItemInfo endDateRule = new UserListRuleItemInfo
                {
                    // The rule variable name must match a corresponding key name fired from a pixel.
                    Name = "checkoutdate",
                    DateRuleItem = new UserListDateRuleItemInfo
                    {
                        Operator = UserListDateRuleItemOperator.Before,
                        Value = "20200101"
                    }
                };

                // Create a rule group targeting users who checked out between November and December
                // by using the start and end date rules. Combining the two rule items into a
                // UserListRuleItemGroupInfo object causes Google Ads to AND their rules together.
                // To instead OR the rules together, each rule should be placed in its own rule item
                // group.
                UserListRuleItemGroupInfo checkoutDateRuleGroup = new UserListRuleItemGroupInfo();
                checkoutDateRuleGroup.RuleItems.Add(startDateRule);
                checkoutDateRuleGroup.RuleItems.Add(endDateRule);

                // Create an ExpressionRuleUserListInfo object, or a boolean rule that defines this
                // user list. The default rule_type for a UserListRuleInfo object is OR of ANDs
                // (disjunctive normal form). That is, rule items will be ANDed together within rule
                // item groups and the groups themselves will be ORed together.
                FlexibleRuleUserListInfo flexibleRuleUserListInfo = new FlexibleRuleUserListInfo();
                FlexibleRuleOperandInfo flexibleRuleOperandInfo = new FlexibleRuleOperandInfo() {
                    Rule = new UserListRuleInfo()
                };
                flexibleRuleOperandInfo.Rule.RuleItemGroups.Add(checkoutAndCartSizeRuleGroup);
                flexibleRuleOperandInfo.Rule.RuleItemGroups.Add(checkoutDateRuleGroup);
                flexibleRuleUserListInfo.InclusiveOperands.Add(flexibleRuleOperandInfo);

                // Defines 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 a user list.
                UserList userList = new UserList
                {
                    Name = $"My expression rule user list #{ExampleUtilities.GetRandomString()}",
                    Description =
                        "Users who checked out in November or December OR visited the checkout " +
                        "page with more than one item in their cart",
                    MembershipLifeSpan = 90L,
                    MembershipStatus = UserListMembershipStatus.Open,
                    RuleBasedUserList = ruleBasedUserListInfo
                };

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

                // Add the user list and print the results.
                MutateUserListsResponse response =
                    userListServiceClient.MutateUserLists(customerId.ToString(),
                        new[] { userListOperation });

                string userListResourceName = response.Results.First().ResourceName;
                Console.WriteLine(
                    $"Created user list with resource name '{userListResourceName}'.");
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
    }
}

      

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\V17\Common\FlexibleRuleOperandInfo;
use Google\Ads\GoogleAds\V17\Common\FlexibleRuleUserListInfo;
use Google\Ads\GoogleAds\V17\Common\RuleBasedUserListInfo;
use Google\Ads\GoogleAds\V17\Common\UserListDateRuleItemInfo;
use Google\Ads\GoogleAds\V17\Common\UserListNumberRuleItemInfo;
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\UserListDateRuleItemOperatorEnum\UserListDateRuleItemOperator;
use Google\Ads\GoogleAds\V17\Enums\UserListFlexibleRuleOperatorEnum\UserListFlexibleRuleOperator;
use Google\Ads\GoogleAds\V17\Enums\UserListMembershipStatusEnum\UserListMembershipStatus;
use Google\Ads\GoogleAds\V17\Enums\UserListNumberRuleItemOperatorEnum\UserListNumberRuleItemOperator;
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\UserList;
use Google\Ads\GoogleAds\V17\Services\MutateUserListsRequest;
use Google\Ads\GoogleAds\V17\Services\MutateUserListsResponse;
use Google\Ads\GoogleAds\V17\Services\UserListOperation;
use Google\ApiCore\ApiException;

/**
 * Creates a rule-based user list defined by an expression rule for users who have either checked
 * out in November or December OR visited the checkout page with more than one item in their cart.
 */
class SetUpAdvancedRemarketing
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';

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

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

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID
            );
        } 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
     */
    private static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
    {
        // Creates a rule targeting any user that visited the checkout page.
        $checkoutRule = new UserListRuleItemInfo([
            // The rule variable name must match a corresponding key name fired from a pixel.
            // To learn more about setting up remarketing tags, visit
            // https://support.google.com/google-ads/answer/2476688.
            // To learn more about remarketing events and parameters, visit
            // https://support.google.com/google-ads/answer/7305793.
            'name' => 'ecomm_pagetype',
            'string_rule_item' => new UserListStringRuleItemInfo([
                'operator' => UserListStringRuleItemOperator::EQUALS,
                'value' => 'checkout'
            ])
        ]);

        // Creates a rule targeting any user that had more than one item in their cart.
        $cartSizeRule = new UserListRuleItemInfo([
            // The rule variable name must match a corresponding key name fired from a pixel.
            'name' => 'cart_size',
            'number_rule_item' => new UserListNumberRuleItemInfo([
                'operator' => UserListNumberRuleItemOperator::GREATER_THAN,
                'value' => 1.0
            ])
        ]);

        // Creates a rule group that includes the checkout and cart size rules. Combining the two
        // rule items into a UserListRuleItemGroupInfo object causes Google Ads to AND their rules
        // together. To instead OR the rules together, each rule should be placed in its own rule
        // item group.
        $checkoutAndCartSizeRuleGroup = new UserListRuleItemGroupInfo([
            'rule_items' => [$checkoutRule, $cartSizeRule]
        ]);

        // Creates the RuleItem for checkout start date. The tags and keys used below must have been
        // in place in the past for the date range specified in the rules.
        $startDateRule = new UserListRuleItemInfo([
            // The rule variable name must match a corresponding key name fired from a pixel.
            'name' => 'checkoutdate',
            'date_rule_item' => new UserListDateRuleItemInfo([
                // Available UserListDateRuleItemOperators can be found at
                // https://developers.google.com/google-ads/api/reference/rpc/latest/UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator
                'operator' => UserListDateRuleItemOperator::AFTER,
                'value' => '20191031'
            ])
        ]);

        // Creates the RuleItem for checkout end date.
        $endDateRule = new UserListRuleItemInfo([
            // The rule variable name must match a corresponding key name fired from a pixel.
            'name' => 'checkoutdate',
            'date_rule_item' => new UserListDateRuleItemInfo([
                'operator' => UserListDateRuleItemOperator::BEFORE,
                'value' => '20200101'
            ])
        ]);

        // Creates a rule group targeting users who checked out between November and December by
        // using the start and end date rules. Combining the two rule items into a
        // UserListRuleItemGroupInfo object causes Google Ads to AND their rules together. To
        // instead OR the rules together, each rule should be placed in its own rule item group.
        $checkoutDateRuleGroup = new UserListRuleItemGroupInfo([
            'rule_items' => [$startDateRule, $endDateRule]
        ]);

        // Create a FlexibleRuleUserListInfo object, or a flexible rule representation of visitors
        // with one or multiple actions. FlexibleRuleUserListInfo wraps UserListRuleInfo in a
        // FlexibleRuleOperandInfo object that represents which users lists to include or exclude.
        $flexibleRuleUserListInfo = new FlexibleRuleUserListInfo([
            'inclusive_rule_operator' => UserListFlexibleRuleOperator::PBAND,
            'inclusive_operands' => [
                new FlexibleRuleOperandInfo([
                    'rule' => new UserListRuleInfo([
                        // The default rule_type for a UserListRuleInfo object is OR of ANDs
                        // (disjunctive normal form). That is, rule items will be ANDed together
                        // within rule item groups and the groups themselves will be ORed together.
                        'rule_item_groups' => [
                            $checkoutAndCartSizeRuleGroup,
                            $checkoutDateRuleGroup
                        ]
                    ]),
                    // 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' => 'My expression rule user list #' . Helper::getPrintableDatetime(),
            'description' => 'Users who checked out in November or December OR ' .
                'visited the checkout page with more than one item in their cart',
            'membership_status' => UserListMembershipStatus::OPEN,
            'membership_life_span' => 90,
            '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])
        );

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

SetUpAdvancedRemarketing::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.
"""This example illustrates how to set up advanced remarketing.

Creates a rule-based user list defined by an expression rule for users who have
either checked out in November, or December, OR visited the checkout page with
more than one item in their cart.
"""

import argparse
import sys
from uuid import uuid4

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


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

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
    """
    # Get the UserListService client.
    user_list_service = client.get_service("UserListService")

    # Creates the operation.
    user_list_operation = client.get_type("UserListOperation")

    # Creates a user list.
    user_list = user_list_operation.create
    user_list.name = f"My expression rule user list #{uuid4()}"
    user_list.description = (
        "Users who checked out in November or December OR visited the "
        "checkout page with more than one item in their cart"
    )
    user_list.membership_status = client.enums.UserListMembershipStatusEnum.OPEN
    user_list.membership_life_span = 90

    # Defines a representation of a user list that is generated by a rule.
    rule_based_user_list_info = user_list.rule_based_user_list
    rule_based_user_list_info.prepopulation_status = (
        client.enums.UserListPrepopulationStatusEnum.REQUESTED
    )

    # Creates a rule group that includes the checkout and cart size rules.
    # Combining the two rule items into a UserListRuleItemGroupInfo object
    # causes Google Ads to AND their rules together. To instead OR the rules
    # together, each rule should be placed in its own rule item group.
    checkout_and_cart_size_rule_group = client.get_type(
        "UserListRuleItemGroupInfo"
    )
    # Creates a rule targeting any user that visited the checkout page.
    checkout_rule = client.get_type("UserListRuleItemInfo")

    # The rule variable name must match a corresponding key name fired from a
    # pixel. To learn more about setting up remarketing tags, visit:
    # https://support.google.com/google-ads/answer/2476688.
    #
    # To learn more about remarketing events and parameters, visit:
    # https://support.google.com/google-ads/answer/7305793.
    checkout_rule.name = "ecomm_pagetype"
    checkout_string_rule_item = checkout_rule.string_rule_item
    checkout_string_rule_item.operator = (
        client.enums.UserListStringRuleItemOperatorEnum.EQUALS
    )
    checkout_string_rule_item.value = "checkout"

    # Creates a rule targeting any user that had more than one item in their
    # cart.
    cart_size_rule = client.get_type("UserListRuleItemInfo")
    # The rule variable name must match a corresponding key name fired from a
    # pixel.
    cart_size_rule.name = "cart_size"
    cart_size_number_rule_item = cart_size_rule.number_rule_item
    cart_size_number_rule_item.operator = (
        client.enums.UserListNumberRuleItemOperatorEnum.GREATER_THAN
    )
    cart_size_number_rule_item.value = 1.0

    # Creates a rule group targeting users who checked out between November
    # and December by using the start and end date rules. Combining the two
    # rule items into a UserListRuleItemGroupInfo object causes Google Ads to
    # AND their rules together. To instead OR the rules together, each rule
    # should be placed in its own rule item group.
    checkout_date_rule_group = client.get_type("UserListRuleItemGroupInfo")

    # Creates the rule item for checkout start date.
    # The tags and keys used below must have been in place in the past for the
    # date range specified in the rules.
    start_date_rule = client.get_type("UserListRuleItemInfo")
    start_date_rule.name = "checkoutdate"
    start_date_rule_item = start_date_rule.date_rule_item
    # Available UserListDateRuleItemOperators can be found at:
    # https://developers.google.com/google-ads/api/reference/rpc/latest/UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator
    user_list_data_rule_item_operator_enum = (
        client.enums.UserListDateRuleItemOperatorEnum
    )
    start_date_rule_item.operator = user_list_data_rule_item_operator_enum.AFTER
    start_date_rule_item.value = "20191031"

    # Creates the rule item for checkout end date.
    end_date_rule = client.get_type("UserListRuleItemInfo")
    end_date_rule.name = "checkoutdate"
    end_date_rule_item = end_date_rule.date_rule_item
    end_date_rule_item.operator = user_list_data_rule_item_operator_enum.BEFORE
    end_date_rule_item.value = "20200101"

    checkout_and_cart_size_rule_group.rule_items.extend(
        [
            checkout_rule,
            cart_size_rule,
        ]
    )
    checkout_date_rule_group.rule_items.extend(
        [
            start_date_rule,
            end_date_rule,
        ]
    )

    # Create a FlexibleRuleUserListInfo object, or a flexible rule
    # representation of visitors with one or multiple actions.
    # FlexibleRuleUserListInfo wraps UserListRuleInfo in a
    # FlexibleRuleOperandInfo object that represents which user lists to
    # include or exclude.
    flexible_rule_user_list_info = (
        rule_based_user_list_info.flexible_rule_user_list
    )
    flexible_rule_user_list_info.inclusive_rule_operator = (
        client.enums.UserListFlexibleRuleOperatorEnum.AND
    )
    # The default rule_type for a UserListRuleInfo object is OR of
    # ANDs (disjunctive normal form). That is, rule items will be
    # ANDed together within rule item groups and the groups
    # themselves will be ORed together.
    rule_operand = client.get_type("FlexibleRuleOperandInfo")
    rule_operand.rule.rule_item_groups.extend(
        [
            checkout_and_cart_size_rule_group,
            checkout_date_rule_group,
        ]
    )
    rule_operand.lookback_window_days = 7
    flexible_rule_user_list_info.inclusive_operands.append(rule_operand)

    # Issue a mutate request to add the user list, then print the results.
    response = user_list_service.mutate_user_lists(
        customer_id=customer_id, operations=[user_list_operation]
    )
    print(
        "Created user list with resource name "
        f"'{response.results[0].resource_name}.'"
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Creates a rule-based user list defined by an expression "
        "rule for users who have either checked out in November, "
        "or December, OR visited the checkout page with more than "
        "one item in their cart."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    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)
    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.
#
# Creates a rule-based user list defined by an expression rule for users who
# have either checked out in November or December OR visited the checkout page
# with more than one item in their cart.

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

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

  # Create a rule targeting any user that visited the checkout page.
  checkout_rule = client.resource.user_list_rule_item_info do |rule|
    # The rule variable name must match a corresponding key name fired
    # from a pixel.
    # To learn more about setting up remarketing tags, visit
    # https://support.google.com/google-ads/answer/2476688.
    # To learn more about remarketing events and parameters, visit
    # https://support.google.com/google-ads/answer/7305793.
    rule.name = "ecomm_pagetype"
    rule.string_rule_item = client.resource.user_list_string_rule_item_info do |sr|
      sr.operator = :EQUALS
      sr.value = "checkout"
    end
  end

  # Create a rule targeting any user that had more than one item in their cart.
  cart_size_rule = client.resource.user_list_rule_item_info do |rule|
    # The rule variable name must match a corresponding key name fired
    # from a pixel.
    rule.name = "cart_size"
    rule.number_rule_item = client.resource.user_list_number_rule_item_info do |nr|
      nr.operator = :GREATER_THAN
      nr.value = 1.0
    end
  end

  # Create a rule group that includes the checkout and cart size rules.
  # Combining the two rule items into a UserListRuleItemGroupInfo object causes
  # Google Ads to AND their rules together. To instead OR the rules together,
  # each rule should be placed in its own rule item group.
  checkout_and_cart_size_rule_group = client.resource.user_list_rule_item_group_info do |g|
    g.rule_items += [checkout_rule, cart_size_rule]
  end

  # Create the RuleItem for checkout start date.
  # The tags and keys used below must have been in place in the past for the
  # date range specified in the rules.
  start_date_rule = client.resource.user_list_rule_item_info do |rule|
    # The rule variable name must match a corresponding key name fired
    # from a pixel.
    rule.name = "checkoutdate"
    rule.date_rule_item = client.resource.user_list_date_rule_item_info do |dr|
      dr.operator = :AFTER
      dr.value = "20191031"
    end
  end

  # Create the RuleItem for checkout end date.
  end_date_rule = client.resource.user_list_rule_item_info do |rule|
    # The rule variable name must match a corresponding key name fired
    # from a pixel.
    rule.name = "checkoutdate"
    rule.date_rule_item = client.resource.user_list_date_rule_item_info do |dr|
      dr.operator = :BEFORE
      dr.value = "20200101"
    end
  end

  # Creates a rule group targeting users who checked out between
  # November and December by using the start and end date rules.
  # Combining the two rule items into a user_list_rule_item_group_info
  # object causes Google Ads to AND their rules together.
  # To instead OR the rules together, each rule should be placed in its
  # own rule item group.
  checkout_date_rule_group = client.resource.user_list_rule_item_group_info do |g|
    g.rule_items += [start_date_rule, end_date_rule]
  end

  # Creates the user list operation.
  operation = client.operation.create_resource.user_list do |ul|
    ul.name = "My expression rule user list ##{(Time.new.to_f * 1000).to_i}"
    ul.description = "Users who checked out in November or December OR visited " \
      "the checkout page with more than one item in their cart"
    ul.membership_status = :OPEN
    ul.membership_life_span = 90
    ul.rule_based_user_list = client.resource.rule_based_user_list_info do |r|
      # Optional: To include past users in the user list, set the
      # prepopulation_status to REQUESTED.
      r.prepopulation_status = :REQUESTED
      # Create a flexible_rule_user_list object, or a flexible rule representation
      # of visitors with one or multiple actions. FlexibleRuleUserListInfo wraps
      # UserListRuleInfo in a FlexibleRuleOperandInfo object that represents which
      # user lists to include or exclude.
      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 |info|
            info.rule_item_groups += [checkout_date_rule_group, checkout_and_cart_size_rule_group]
          end
          # Optionally include a lookback window for this rule, in days.
          froi.lookback_window_days = 7
        end
      end
    end
  end

  # Issues a muate request to create the user list.
  response = client.service.user_list.mutate_user_lists(
    customer_id: customer_id,
    operations: [operation],
  )
  puts "Created user list 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.
  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.separator ''
    opts.separator 'Help:'

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

  begin
    set_up_advanced_remarketing(options.fetch(:customer_id).tr("-", ""))
  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.
#
# Creates a rule-based user list defined by an expression rule for users who
# have either checked out in November or December OR visited the checkout page
# with more than one item in their cart.

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::V17::Resources::UserList;
use Google::Ads::GoogleAds::V17::Common::RuleBasedUserListInfo;
use Google::Ads::GoogleAds::V17::Common::FlexibleRuleOperandInfo;
use Google::Ads::GoogleAds::V17::Common::FlexibleRuleUserListInfo;
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::Common::UserListNumberRuleItemInfo;
use Google::Ads::GoogleAds::V17::Common::UserListDateRuleItemInfo;
use Google::Ads::GoogleAds::V17::Enums::UserListFlexibleRuleOperatorEnum
  qw(AND);
use Google::Ads::GoogleAds::V17::Enums::UserListStringRuleItemOperatorEnum
  qw(EQUALS);
use Google::Ads::GoogleAds::V17::Enums::UserListNumberRuleItemOperatorEnum
  qw(GREATER_THAN);
use Google::Ads::GoogleAds::V17::Enums::UserListDateRuleItemOperatorEnum
  qw(AFTER BEFORE);
use Google::Ads::GoogleAds::V17::Enums::UserListMembershipStatusEnum qw(OPEN);
use Google::Ads::GoogleAds::V17::Enums::UserListPrepopulationStatusEnum
  qw(REQUESTED);
use Google::Ads::GoogleAds::V17::Services::UserListService::UserListOperation;

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

sub set_up_advanced_remarketing {
  my ($api_client, $customer_id) = @_;

  # Create a rule targeting any user that visited the checkout page.
  my $checkout_rule =
    Google::Ads::GoogleAds::V17::Common::UserListRuleItemInfo->new({
      # The rule variable name must match a corresponding key name fired from a
      # pixel. To learn more about setting up remarketing tags, visit
      # https://support.google.com/google-ads/answer/2476688.
      # To learn more about remarketing events and parameters, visit
      # https://support.google.com/google-ads/answer/7305793.
      name           => "ecomm_pagetype",
      stringRuleItem =>
        Google::Ads::GoogleAds::V17::Common::UserListStringRuleItemInfo->new({
          operator => EQUALS,
          value    => "checkout"
        })});

  # Create a rule targeting any user that had more than one item in their cart.
  my $cart_size_rule =
    Google::Ads::GoogleAds::V17::Common::UserListRuleItemInfo->new({
      # The rule variable name must match a corresponding key name fired from a
      # pixel.
      name           => "cart_size",
      numberRuleItem =>
        Google::Ads::GoogleAds::V17::Common::UserListNumberRuleItemInfo->new({
          # Available UserListNumberRuleItemOperators can be found at
          # https://developers.google.com/google-ads/api/reference/rpc/latest/UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator
          operator => GREATER_THAN,
          value    => 1.0
        })});

  # Create a rule group that includes the checkout and cart size rules.
  # Combining the two rule items into a UserListRuleItemGroupInfo object causes
  # Google Ads to AND their rules together. To instead OR the rules together,
  # each rule should be placed in its own rule item group.
  my $checkout_and_cart_size_rule_group =
    Google::Ads::GoogleAds::V17::Common::UserListRuleItemGroupInfo->new(
    {ruleItems => [$checkout_rule, $cart_size_rule]});

  # Create the RuleItem for checkout start date.
  # The tags and keys used below must have been in place in the past for the
  # date range specified in the rules.
  my $start_date_rule =
    Google::Ads::GoogleAds::V17::Common::UserListRuleItemInfo->new({
      # The rule variable name must match a corresponding key name fired from a
      # pixel.
      name         => "checkoutdate",
      dateRuleItem =>
        Google::Ads::GoogleAds::V17::Common::UserListDateRuleItemInfo->new({
          # Available UserListDateRuleItemOperators can be found at
          # https://developers.google.com/google-ads/api/reference/rpc/latest/UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator
          operator => AFTER,
          value    => "20191031"
        })});

  # Create the RuleItem for checkout end date.
  my $end_date_rule =
    Google::Ads::GoogleAds::V17::Common::UserListRuleItemInfo->new({
      # The rule variable name must match a corresponding key name fired from a
      # pixel.
      name         => "checkoutdate",
      dateRuleItem =>
        Google::Ads::GoogleAds::V17::Common::UserListDateRuleItemInfo->new({
          operator => BEFORE,
          value    => "20200101"
        })});

  # Create a rule group targeting users who checked out between November and
  # December by using the start and end date rules. Combining the two rule items
  # into a UserListRuleItemGroupInfo object causes Google Ads to AND their rules
  # together. To instead OR the rules together, each rule should be placed in
  # its own rule item group.
  my $checkout_date_rule_group =
    Google::Ads::GoogleAds::V17::Common::UserListRuleItemGroupInfo->new(
    {ruleItems => [$start_date_rule, $end_date_rule]});

  # Create a FlexibleRuleUserListInfo object, or a flexible rule representation
  # of visitors with one or multiple actions. FlexibleRuleUserListInfo wraps
  # UserListRuleInfo in a FlexibleRuleOperandInfo object that represents which
  # user lists to include or exclude.
  my $flexible_rule_user_list_info =
    Google::Ads::GoogleAds::V17::Common::FlexibleRuleUserListInfo->new({
      inclusiveRuleOperator => AND,
      inclusiveOperands     => [
        Google::Ads::GoogleAds::V17::Common::FlexibleRuleOperandInfo->new({
            rule => Google::Ads::GoogleAds::V17::Common::UserListRuleInfo->new({
                # The default rule_type for a UserListRuleInfo object is OR of
                # ANDs (disjunctive normal form). That is, rule items will be
                # ANDed together within rule item groups and the groups
                # themselves will be ORed together.
                ruleItemGroups => [
                  $checkout_date_rule_group, $checkout_and_cart_size_rule_group
                ]}
            ),
            # Optionally include a lookback window for this rule, in days.
            lookback_window_days => 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
      # prepopulation status 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        => "My expression rule user list #" . uniqid(),
    description => "Users who checked out in November or December OR " .
      "visited the checkout page with more than one item in their cart",
    membershipLifespan => 90,
    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
    });

  # Issue a mutate request to add the user list and print some information.
  my $user_lists_response = $api_client->UserListService()->mutate({
      customerId => $customer_id,
      operations => [$user_list_operation]});
  printf "Created user list with resource name '%s'.\n",
    $user_lists_response->{results}[0]{resourceName};

  return 1;
}

# 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;

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

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

# Call the example.
set_up_advanced_remarketing($api_client, $customer_id =~ s/-//gr);

=pod

=head1 NAME

set_up_advanced_remarketing

=head1 DESCRIPTION

Creates a rule-based user list defined by an expression rule for users who have
either checked out in November or December OR visited the checkout page with
more than one item in their cart.

=head1 SYNOPSIS

set_up_advanced_remarketing.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.

=cut