Ява
// 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.BasicUserListInfo;
import com.google.ads.googleads.v17.common.UserListActionInfo;
import com.google.ads.googleads.v17.enums.UserListMembershipStatusEnum.UserListMembershipStatus;
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.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.Arrays;
import java.util.List;
/** Creates a basic user list consisting of people who triggered one or more conversion actions. */
public class AddConversionBasedUserList {
private static class AddConversionBasedUserListParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
private Long customerId;
@Parameter(names = ArgumentNames.CONVERSION_ACTION_IDS, required = true)
private List<Long> conversionActionIds;
}
public static void main(String[] args) {
AddConversionBasedUserListParams params = new AddConversionBasedUserListParams();
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.conversionActionIds =
Arrays.asList(
Long.parseLong("INSERT_CONVERSION_ACTION_ID_HERE"),
Long.parseLong("INSERT_CONVERSION_ACTION_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 AddConversionBasedUserList()
.runExample(googleAdsClient, params.customerId, params.conversionActionIds);
} 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 conversionActionIds the IDs of the conversion actions for the basic user list.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
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());
}
}
}
С#
// 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.UserListMembershipStatusEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V17
{
/// <summary>
/// This code example creates a basic user list consisting of people who triggered one or more
/// conversion actions.
/// </summary>
public class AddConversionBasedUserList : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddConversionBasedUserList"/> 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 IDs of the conversion actions for the basic user list.
/// </summary>
[Option("conversionActionIds", Required = true, HelpText =
"The IDs of the conversion actions for the basic user list.")]
public IEnumerable<long> ConversionActionIds { 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);
AddConversionBasedUserList codeExample = new AddConversionBasedUserList();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId,
options.ConversionActionIds.ToArray());
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example creates a basic user list consisting of people who triggered one " +
"or more conversion actions.";
/// <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="conversionActionIds">The IDs of the conversion actions for the basic user
/// list.</param>
public void Run(GoogleAdsClient client, long customerId, long[] conversionActionIds)
{
// Creates the service client.
UserListServiceClient userListServiceClient =
client.GetService(Services.V17.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
<?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\V17\ResourceNames;
use Google\Ads\GoogleAds\V17\Common\BasicUserListInfo;
use Google\Ads\GoogleAds\V17\Common\UserListActionInfo;
use Google\Ads\GoogleAds\V17\Enums\UserListMembershipStatusEnum\UserListMembershipStatus;
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\UserListOperation;
use Google\ApiCore\ApiException;
/**
* Creates a basic user list consisting of people who triggered one or more conversion actions.
*/
class AddConversionBasedUserList
{
private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
private const CONVERSION_ACTION_ID_1 = 'INSERT_CONVERSION_ACTION_ID_1_HERE';
private const CONVERSION_ACTION_ID_2 = 'INSERT_CONVERSION_ACTION_ID_2_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,
ArgumentNames::CONVERSION_ACTION_IDS => GetOpt::MULTIPLE_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,
$options[ArgumentNames::CONVERSION_ACTION_IDS] ?:
[self::CONVERSION_ACTION_ID_1, self::CONVERSION_ACTION_ID_2]
);
} 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 array $conversionActionIds the IDs of the conversion actions for the basic user list
*/
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(
MutateUserListsRequest::build($customerId, [$operation])
);
printf(
"Created basic user list with resource name '%s'.%s",
$response->getResults()[0]->getResourceName(),
PHP_EOL
);
}
}
AddConversionBasedUserList::main();
Питон
#!/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.
"""Creates a basic user list based on conversion actions.
The given conversion action IDs will be associated with the new user list.
A user will be added to the list upon triggering more than one of the actions,
e.g. by visiting a site and making a purchase.
"""
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, 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}.'"
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Creates a basic user list based on conversion actions."
)
# 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.",
)
parser.add_argument(
"-a",
"--conversion_action_ids",
nargs="+",
type=str,
required=True,
help="The IDs of the conversion actions for the basic user list.",
)
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.conversion_action_ids)
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)
Руби
#!/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 basic user list consisting of people who triggered one or more
# conversion actions.
require 'optparse'
require 'google/ads/google_ads'
require 'date'
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
if __FILE__ == $0
options = {}
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
options[:conversion_action_ids] = [
'INSERT_CONVERSION_ACTION_ID_1_HERE',
'INSERT_CONVERSION_ACTION_ID_2_HERE',
]
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', '--conversion-action-ids CONVERSION-ACTION-IDS', String,
'Conversion Action IDs (comma-separated)') do |v|
options[:conversion_action_ids] = v
end
opts.separator ''
opts.separator 'Help:'
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
begin
add_conversion_based_user_list(
options.fetch(:customer_id).tr("-", ""),
options[:conversion_action_ids].split(','),
)
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
Перл
#!/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 basic user list consisting of people who triggered one or more
# conversion actions.
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::UserListActionInfo;
use Google::Ads::GoogleAds::V17::Common::BasicUserListInfo;
use Google::Ads::GoogleAds::V17::Enums::UserListMembershipStatusEnum qw(OPEN);
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);
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id = "INSERT_CUSTOMER_ID_HERE";
my $conversion_action_id_1 = "INSERT_CONVERSION_ACTION_ID_1_HERE";
my $conversion_action_id_2 = "INSERT_CONVERSION_ACTION_ID_2_HERE";
my $conversion_action_ids = [];
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::V17::Common::UserListActionInfo->new({
conversionAction =>
Google::Ads::GoogleAds::V17::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::V17::Common::BasicUserListInfo->new({
actions => $user_list_action_info_list
});
# Create the basic user list.
my $basic_user_list = Google::Ads::GoogleAds::V17::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::V17::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;
}
# 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);
# Parameters passed on the command line will override any parameters set in code.
GetOptions(
"customer_id=s" => \$customer_id,
"conversion_action_ids=s" => \@$conversion_action_ids,
);
$conversion_action_ids = [$conversion_action_id_1, $conversion_action_id_2]
unless @$conversion_action_ids;
# 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, $conversion_action_ids);
# Call the example.
add_conversion_based_user_list($api_client, $customer_id =~ s/-//gr,
$conversion_action_ids);
=pod
=head1 NAME
add_conversion_based_user_list
=head1 DESCRIPTION
Creates a basic user list consisting of people who triggered one or more
conversion actions.
=head1 SYNOPSIS
add_conversion_based_user_list.pl [options]
-help Show the help message.
-customer_id The Google Ads customer ID.
-conversion_action_ids The IDs of the conversion actions for the basic user list.
=cut