Visitors who Took Specific Actions

You can populate your audience list with people who have taken specific actions on your website. If you're using conversion tracking, you can target ads to people who previously triggered a conversion (such as a purchase) on your website.

You can also target ads to people who have taken a particular action on your website that you do not consider a conversion, such as when a person adds but then deletes an item from their shopping cart without making a purchase.

In either case, you would set the basic_user_list field of a UserList with a BasicUserListInfo object containing references to the conversions you are targeting.

Triggered a conversion

If you haven't yet created a conversion tracker, you can do so using ConversionActionService. You can then install the conversion tracker tag on your website.

A basic user list defines its membership as people who had triggered one or more conversion trackers on your website. When you create a basic user list, you provide the resource name of the ConversionAction to a UserListActionInfo object, which is ultimately passed to the UserList.

The following example creates a basic user list associated with two existing conversion trackers:

Java

private void runExample(
    GoogleAdsClient googleAdsClient, long customerId, List<Long> conversionActionIds) {
  List<UserListActionInfo> userListActionInfoList = new ArrayList<>();
  for (long conversionActionId : conversionActionIds) {
    // Creates the UserListActionInfo object for a given conversion action. This specifies the
    // conversion action that, when triggered, will cause a user to be added to a UserList.
    UserListActionInfo userListActionInfo =
        UserListActionInfo.newBuilder()
            .setConversionAction(ResourceNames.conversionAction(customerId, conversionActionId))
            .build();
    userListActionInfoList.add(userListActionInfo);
  }

  // Creates a basic user list info object with all of the conversion actions.
  BasicUserListInfo basicUserListInfo =
      BasicUserListInfo.newBuilder().addAllActions(userListActionInfoList).build();

  // Creates the basic user list.
  UserList basicUserList =
      UserList.newBuilder()
          .setName("Example BasicUserList #" + getPrintableDateTime())
          .setDescription("A list of people who have triggered one or more conversion actions")
          .setMembershipLifeSpan(365)
          .setBasicUserList(basicUserListInfo)
          .setMembershipStatus(UserListMembershipStatus.OPEN)
          .build();

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

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

C#

public void Run(GoogleAdsClient client, long customerId, long[] conversionActionIds)
{
    // Creates the service client.
    UserListServiceClient userListServiceClient =
        client.GetService(Services.V13.UserListService);

    List<UserListActionInfo> userListActionInfoList = new List<UserListActionInfo>();
    foreach (long conversionActionId in conversionActionIds)
    {
        // Creates the UserListActionInfo object for a given conversion action. This
        // specifies the conversion action that, when triggered, will cause a user to be
        // added to a UserList.
        userListActionInfoList.Add(new UserListActionInfo
        {
            ConversionAction =
                ResourceNames.ConversionAction(customerId, conversionActionId)
        });
    }

    // Creates a basic user list info object with all of the conversion actions.
    BasicUserListInfo basicUserListInfo = new BasicUserListInfo();
    basicUserListInfo.Actions.Add(userListActionInfoList);

    // Creates the basic user list.
    UserList basicUserList = new UserList
    {
        Name = $"Example BasicUserList #{ExampleUtilities.GetShortRandomString()}",
        Description = "A list of people who have triggered one or more conversion actions",
        MembershipLifeSpan = 365L,
        BasicUserList = basicUserListInfo,
        MembershipStatus = UserListMembershipStatus.Open
    };

    // Creates the operation.
    UserListOperation operation = new UserListOperation
    {
        Create = basicUserList
    };

    try
    {
        // Adds the new user list.
        MutateUserListsResponse response = userListServiceClient.MutateUserLists
            (customerId.ToString(), new[] { operation });

        // Prints the result.
        Console.WriteLine("Created basic user list with resource name: " +
            $"{response.Results.First().ResourceName}");
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      

PHP

public static function runExample(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    array $conversionActionIds
) {
    $userListActionInfoList = [];
    foreach ($conversionActionIds as $conversionActionId) {
        // Creates the UserListActionInfo object for a given conversion action. This specifies
        // the conversion action that, when triggered, will cause a user to be added to a
        // UserList.
        $userListActionInfoList[] = new UserListActionInfo([
            'conversion_action' => ResourceNames::forConversionAction(
                $customerId,
                $conversionActionId
            )
        ]);
    }

    // Creates a basic user list info object with all of the conversion actions.
    $basicUserListInfo = new BasicUserListInfo(['actions' => $userListActionInfoList]);

    // Creates the basic user list.
    $basicUserList = new UserList([
        'name' => 'Example BasicUserList #' . Helper::getPrintableDatetime(),
        'description' => 'A list of people who have triggered one or more conversion actions',
        'membership_status' => UserListMembershipStatus::OPEN,
        'membership_life_span' => 365,
        'basic_user_list' => $basicUserListInfo
    ]);

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

    // Issues a mutate request to add the user list and prints some information.
    $userListServiceClient = $googleAdsClient->getUserListServiceClient();
    $response = $userListServiceClient->mutateUserLists($customerId, [$operation]);
    printf(
        "Created basic user list with resource name '%s'.%s",
        $response->getResults()[0]->getResourceName(),
        PHP_EOL
    );
}
      

Python

def main(client, customer_id, conversion_action_ids):
    """Creates a combination user list.

    Args:
        client: The Google Ads client.
        customer_id: The customer ID for which to add the user list.
        conversion_action_ids: The IDs of the conversion actions for the basic
            user list.
    """
    # Get the UserListService and ConversionActionService clients.
    user_list_service = client.get_service("UserListService")
    conversion_action_service = client.get_service("ConversionActionService")

    # Create a list of UserListActionInfo objects for the given conversion
    # actions. These specify the conversion actions that, when triggered, will
    # cause a user to be added to a UserList.
    user_list_action_info_list = []
    for conversion_action_id in conversion_action_ids:
        user_list_action_info = client.get_type("UserListActionInfo")
        user_list_action_info.conversion_action = conversion_action_service.conversion_action_path(
            customer_id, conversion_action_id
        )
        user_list_action_info_list.append(user_list_action_info)

    # Create a UserListOperation and populate the UserList.
    user_list_operation = client.get_type("UserListOperation")
    user_list = user_list_operation.create
    user_list.name = f"Example BasicUserList #{uuid4()}"
    user_list.description = (
        "A list of people who have triggered one or more conversion actions"
    )
    user_list.membership_status = client.enums.UserListMembershipStatusEnum.OPEN
    user_list.membership_life_span = 365
    # The basic user list info object contains the conversion action info.
    user_list.basic_user_list.actions.extend(user_list_action_info_list)

    # 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 basic user list with resource name "
        f"'{response.results[0].resource_name}.'"
    )
      

Ruby

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

  # Creates the basic user list.
  operation = client.operation.create_resource.user_list do |u|
    u.name = "Example BasicUserList ##{(Time.new.to_f * 100).to_i}"
    u.description = "A list of people who have triggered one or more conversion actions"
    u.membership_status = :OPEN
    u.membership_life_span = 365
    # Creates a basic user list info object with all of the conversion actions.
    u.basic_user_list = client.resource.basic_user_list_info do |info|
      conversion_action_ids.each do |conversion_action_id|
        # Creates the UserListActionInfo object for a given conversion action.
        # This specifies the conversion action that, when triggered, will cause a
        # user to be added to a user_list.
        info.actions << client.resource.user_list_action_info do |action|
          action.conversion_action =
            client.path.conversion_action(customer_id, conversion_action_id)
        end
      end
    end
  end

  # Issues a mutate request to add the user list and prints some information.
  response = client.service.user_list.mutate_user_lists(
    customer_id: customer_id,
    operations: [operation],
  )

  puts "Created basic user list with resource name " \
    "#{response.results.first.resource_name}"
end
      

Perl

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

  my $user_list_action_info_list = [];
  foreach my $conversion_action_id (@$conversion_action_ids) {
    # Create the UserListActionInfo object for a given conversion action. This
    # specifies the conversion action that, when triggered, will cause a user to
    # be added to a UserList.
    push @$user_list_action_info_list,
      Google::Ads::GoogleAds::V13::Common::UserListActionInfo->new({
        conversionAction =>
          Google::Ads::GoogleAds::V13::Utils::ResourceNames::conversion_action(
          $customer_id, $conversion_action_id
          )});
  }

  # Create a basic user list info object with all of the conversion actions.
  my $basic_user_list_info =
    Google::Ads::GoogleAds::V13::Common::BasicUserListInfo->new({
      actions => $user_list_action_info_list
    });

  # Create the basic user list.
  my $basic_user_list = Google::Ads::GoogleAds::V13::Resources::UserList->new({
    name        => "Example BasicUserList #" . uniqid(),
    description =>
      "A list of people who have triggered one or more conversion actions",
    membershipStatus   => OPEN,
    membershipLifeSpan => 365,
    basicUserList      => $basic_user_list_info
  });

  # Create the operation.
  my $user_list_operation =
    Google::Ads::GoogleAds::V13::Services::UserListService::UserListOperation->
    new({
      create => $basic_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 basic user list with resource name '%s'.\n",
    $user_lists_response->{results}[0]{resourceName};

  return 1;
}
      

Non-conversion actions

You can create a basic user list for people who took actions on your website that you do not consider conversions by associating it with a RemarketingAction instead of a ConversionAction. The example below demonstrates how to create a RemarketingAction and retrieve the associated site tags.

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId) {

  // Creates a remarketing action with the specified name.
  RemarketingAction remarketingAction =
      RemarketingAction.newBuilder()
          .setName("Remarketing action #" + getPrintableDateTime())
          .build();

  // Creates a remarketing action operation.
  RemarketingActionOperation operation =
      RemarketingActionOperation.newBuilder().setCreate(remarketingAction).build();

  // Issues a mutate request to add the remarketing action and prints out some information.
  String remarketingActionResourceName;
  try (RemarketingActionServiceClient conversionActionServiceClient =
      googleAdsClient.getLatestVersion().createRemarketingActionServiceClient()) {
    MutateRemarketingActionsResponse response =
        conversionActionServiceClient.mutateRemarketingActions(
            Long.toString(customerId), Collections.singletonList(operation));
    remarketingActionResourceName = response.getResults(0).getResourceName();
    System.out.printf(
        "Added remarketing action with resource name '%s'.%n", remarketingActionResourceName);
  }

  // Creates a query that retrieves the previously created remarketing action with its generated
  // tag snippets.
  String query =
      String.format(
          "SELECT remarketing_action.id,"
              + " remarketing_action.name,"
              + " remarketing_action.tag_snippets "
              + "FROM remarketing_action "
              + "WHERE remarketing_action.resource_name = '%s'",
          remarketingActionResourceName);
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    // Issues a search request.
    SearchPagedResponse searchPagedResponse =
        googleAdsServiceClient.search(Long.toString(customerId), query);

    // There is only one row because we limited the search using the resource name, which is
    // unique.
    GoogleAdsRow googleAdsRow = searchPagedResponse.iterateAll().iterator().next();

    // Prints some attributes of the remarketing action. The ID and tag snippets are generated by
    // the API.
    RemarketingAction newRemarketingAction = googleAdsRow.getRemarketingAction();
    System.out.printf(
        "Remarketing action has ID %d and name '%s'.%n%n",
        newRemarketingAction.getId(), newRemarketingAction.getName());
    System.out.println("It has the following generated tag snippets:");
    for (TagSnippet tagSnippet : newRemarketingAction.getTagSnippetsList()) {
      System.out.printf(
          "Tag snippet with code type '%s' and code page format '%s' has the following global"
              + " site tag:%n%s%n",
          tagSnippet.getType(), tagSnippet.getPageFormat(), tagSnippet.getGlobalSiteTag());
      System.out.printf("and the following event snippet:%n%s%n%n", tagSnippet.getEventSnippet());
    }
  }
}
      

C#

        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the RemarketingActionService.
            RemarketingActionServiceClient remarketingActionService =
                client.GetService(Services.V13.RemarketingActionService);

            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService =
                client.GetService(Services.V13.GoogleAdsService);

            try
            {
                // Creates a remarketing action with the specified name.
                RemarketingAction remarketingAction = new RemarketingAction()
                {
                    Name = $"Remarketing action # {ExampleUtilities.GetRandomString()}"
                };
                // Creates a remarketing action operation.
                RemarketingActionOperation remarketingActionOperation =
                    new RemarketingActionOperation()
                    {
                        Create = remarketingAction
                    };

                // Issues a mutate request to add the remarketing action and prints out
                // some information.
                MutateRemarketingActionsResponse response =
                    remarketingActionService.MutateRemarketingActions(
                        customerId.ToString(), new[] { remarketingActionOperation });

                string remarketingActionResourceName = response.Results[0].ResourceName;

                Console.WriteLine($"Added remarketing action with resource name " +
                    $"'{remarketingActionResourceName}'.");

                // Creates a query that retrieves the previously created remarketing action
                // with its generated tag snippets.
                var query = $"SELECT remarketing_action.id, remarketing_action.name, " +
                    $"remarketing_action.tag_snippets FROM remarketing_action " +
                    $"WHERE remarketing_action.resource_name = '{remarketingActionResourceName}'";

                // Issues a search request and retrieve the results. There is only one row
                // because we limited the search using the resource name, which is unique.
                RemarketingAction result = googleAdsService.Search(customerId.ToString(), query)
                    .First()
                    .RemarketingAction;

                // Display the result.
                Console.WriteLine($"Remarketing action has ID {result.Id} and name" +
                    $" '{result.Id}'.");

                Console.WriteLine("It has the following generated tag snippets:");
                foreach (TagSnippet tagSnippet in result.TagSnippets)
                {
                    Console.WriteLine($"Tag snippet with code type '{tagSnippet.Type}' and code " +
                        $"page format '{tagSnippet.PageFormat}' has the following global site " +
                        $"tag:{tagSnippet.GlobalSiteTag} \n\nand the following event snippet:" +
                        $"{tagSnippet.EventSnippet}.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
    }
}

      

PHP

public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
{
    // Creates a remarketing action with the specified name.
    $remarketingAction = new RemarketingAction([
        'name' => 'Remarketing action #' . Helper::getPrintableDatetime()
    ]);

    // Creates a remarketing action operation.
    $remarketingActionOperation =
        new RemarketingActionOperation(['create' => $remarketingAction]);

    // Issues a mutate request to add the remarketing action and prints out some information.
    $remarketingActionServiceClient = $googleAdsClient->getRemarketingActionServiceClient();
    $response = $remarketingActionServiceClient->mutateRemarketingActions(
        $customerId,
        [$remarketingActionOperation]
    );
    $remarketingActionResourceName = $response->getResults()[0]->getResourceName();
    printf(
        "Added remarketing action with resource name '%s'.%s",
        $remarketingActionResourceName,
        PHP_EOL
    );

    // Creates a query that retrieves the previously created remarketing action with its
    // generated tag snippets.
    $query =
        "SELECT remarketing_action.id, "
        . "remarketing_action.name, "
        . "remarketing_action.tag_snippets "
        . "FROM remarketing_action "
        . "WHERE remarketing_action.resource_name = '$remarketingActionResourceName'";

    // Issues a search request by specifying page size.
    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    $response =
        $googleAdsServiceClient->search($customerId, $query, ['pageSize' => self::PAGE_SIZE]);

    // There is only one row because we limited the search using the resource name, which is
    // unique.
    /** @var GoogleAdsRow $googleAdsRow */
    $googleAdsRow = $response->iterateAllElements()->current();

    // Prints some attributes of the remarketing action. The ID and tag snippets are generated
    // by the API.
    printf(
        "Remarketing action has ID %d and name '%s'.%s%s",
        $googleAdsRow->getRemarketingAction()->getId(),
        $googleAdsRow->getRemarketingAction()->getName(),
        PHP_EOL,
        PHP_EOL
    );
    print 'It has the following generated tag snippets:' . PHP_EOL;
    foreach ($googleAdsRow->getRemarketingAction()->getTagSnippets() as $tagSnippet) {
        /** @var TagSnippet $tagSnippet */
        printf(
            "Tag snippet with code type '%s' and code page format '%s' has the following"
            . " global site tag:%s%s%s",
            TrackingCodeType::name($tagSnippet->getType()),
            TrackingCodePageFormat::name($tagSnippet->getPageFormat()),
            PHP_EOL,
            $tagSnippet->getGlobalSiteTag(),
            PHP_EOL
        );
        printf(
            "and the following event snippet:%s%s%s%s",
            PHP_EOL,
            $tagSnippet->getEventSnippet(),
            PHP_EOL,
            PHP_EOL
        );
    }
}
      

Python

def add_remarketing_action(client, customer_id):
    remarketing_action_service = client.get_service("RemarketingActionService")
    remarketing_action_operation = client.get_type("RemarketingActionOperation")

    remarketing_action = remarketing_action_operation.create
    remarketing_action.name = f"Remarketing action #{uuid4()}"

    try:
        remarketing_action_response = remarketing_action_service.mutate_remarketing_actions(
            customer_id=customer_id, operations=[remarketing_action_operation],
        )
    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)

    return remarketing_action_response.results[0].resource_name
      

Ruby

def add_remarketing_action(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

  # Step 1: Create a remarketing action.
  operation = client.operation.create_resource.remarketing_action do |action|
    action.name = "Remarketing action ##{(Time.new.to_f * 100).to_i}"
  end

  response = client.service.remarketing_action.mutate_remarketing_actions(
    customer_id: customer_id,
    operations: [operation],
  )

  remarketing_action_resource_name = response.results.first.resource_name

  # Step 2: Look up the remarketing action we created to get some extra
  # information about it, like its tag snippets.
  query = <<~EOQUERY
    SELECT
      remarketing_action.id,
      remarketing_action.name,
      remarketing_action.tag_snippets
    FROM
      remarketing_action
    WHERE
      remarketing_action.resource_name = "#{remarketing_action_resource_name}"
  EOQUERY

  response = client.service.google_ads.search(
    customer_id: customer_id,
    query: query,
  )

  action = response.first.remarketing_action
  puts "Remarking action has ID #{action.id} and name '#{action.name}.'"
  puts "It has the following generated tag snippets:"
  action.tag_snippets.each do |ts|
    puts "Tag snippet with code type '#{ts.type}' and code page format " \
      "'#{ts.page_format}' has the following global site tag:\n#{ts.global_site_tag}"
    puts "and the following event snippet:\n#{ts.event_snippet}"
  end
end
      

Perl

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

  # Create a remarketing action with the specified name.
  my $remarketing_action =
    Google::Ads::GoogleAds::V13::Resources::RemarketingAction->new({
      name => "Remarketing action #" . uniqid()});

  # Create a remarketing action operation.
  my $remarketing_action_operation =
    Google::Ads::GoogleAds::V13::Services::RemarketingActionService::RemarketingActionOperation
    ->new({
      create => $remarketing_action
    });

  # Issue a mutate request to add the remarketing action and print out some information.
  my $remarketing_actions_response =
    $api_client->RemarketingActionService()->mutate({
      customerId => $customer_id,
      operations => [$remarketing_action_operation]});

  my $remarketing_action_resource_name =
    $remarketing_actions_response->{results}[0]{resourceName};
  printf
    "Added remarketing action with resource name '%s'.\n",
    $remarketing_action_resource_name;

  # Create a query that retrieves the previously created remarketing action with
  # its generated tag snippets.
  my $search_query =
    sprintf "SELECT remarketing_action.id, remarketing_action.name, " .
    "remarketing_action.tag_snippets FROM remarketing_action " .
    "WHERE remarketing_action.resource_name = '%s'",
    $remarketing_action_resource_name;

  # Issue a search request by specifying page size.
  my $search_response = $api_client->GoogleAdsService()->search({
    customerId => $customer_id,
    query      => $search_query,
    pageSize   => PAGE_SIZE
  });

  # There is only one row because we limited the search using the resource name,
  # which is unique.
  my $google_ads_row = $search_response->{results}[0];

  # Print some attributes of the remarketing action. The ID and tag snippets are
  # generated by the API.
  printf
    "Remarketing action has ID %d and name '%s'.\n\n",
    $google_ads_row->{remarketingAction}{id},
    $google_ads_row->{remarketingAction}{name};

  print "It has the following generated tag snippets:\n";

  foreach my $tag_snippet (@{$google_ads_row->{remarketingAction}{tagSnippets}})
  {
    printf "Tag snippet with code type '%s' and code page format '%s' " .
      "has the following global site tag:\n%s\n",
      $tag_snippet->{type},
      $tag_snippet->{pageFormat},
      $tag_snippet->{globalSiteTag};

    printf "and the following event snippet:\n%s\n\n",
      $tag_snippet->{eventSnippet};
  }

  return 1;
}