-
Notifications
You must be signed in to change notification settings - Fork 171
/
SetUpRemarketing.java
484 lines (447 loc) · 21.9 KB
/
SetUpRemarketing.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ads.googleads.examples.remarketing;
import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;
import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.lib.utils.FieldMasks;
import com.google.ads.googleads.v16.common.FlexibleRuleOperandInfo;
import com.google.ads.googleads.v16.common.FlexibleRuleUserListInfo;
import com.google.ads.googleads.v16.common.RuleBasedUserListInfo;
import com.google.ads.googleads.v16.common.UserListInfo;
import com.google.ads.googleads.v16.common.UserListRuleInfo;
import com.google.ads.googleads.v16.common.UserListRuleItemGroupInfo;
import com.google.ads.googleads.v16.common.UserListRuleItemInfo;
import com.google.ads.googleads.v16.common.UserListStringRuleItemInfo;
import com.google.ads.googleads.v16.enums.UserListFlexibleRuleOperatorEnum.UserListFlexibleRuleOperator;
import com.google.ads.googleads.v16.enums.UserListMembershipStatusEnum.UserListMembershipStatus;
import com.google.ads.googleads.v16.enums.UserListPrepopulationStatusEnum.UserListPrepopulationStatus;
import com.google.ads.googleads.v16.enums.UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator;
import com.google.ads.googleads.v16.errors.GoogleAdsError;
import com.google.ads.googleads.v16.errors.GoogleAdsException;
import com.google.ads.googleads.v16.resources.AdGroupCriterion;
import com.google.ads.googleads.v16.resources.CampaignCriterion;
import com.google.ads.googleads.v16.resources.UserList;
import com.google.ads.googleads.v16.services.AdGroupCriterionOperation;
import com.google.ads.googleads.v16.services.AdGroupCriterionServiceClient;
import com.google.ads.googleads.v16.services.CampaignCriterionOperation;
import com.google.ads.googleads.v16.services.CampaignCriterionServiceClient;
import com.google.ads.googleads.v16.services.GoogleAdsRow;
import com.google.ads.googleads.v16.services.GoogleAdsServiceClient;
import com.google.ads.googleads.v16.services.GoogleAdsServiceClient.SearchPagedResponse;
import com.google.ads.googleads.v16.services.MutateAdGroupCriteriaResponse;
import com.google.ads.googleads.v16.services.MutateAdGroupCriterionResult;
import com.google.ads.googleads.v16.services.MutateCampaignCriteriaResponse;
import com.google.ads.googleads.v16.services.MutateUserListsResponse;
import com.google.ads.googleads.v16.services.SearchGoogleAdsRequest;
import com.google.ads.googleads.v16.services.UserListOperation;
import com.google.ads.googleads.v16.services.UserListServiceClient;
import com.google.ads.googleads.v16.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Demonstrates various operations involved in remarketing, including (a) creating a user list based
* on visitors to a website, (b) targeting a user list with an ad group criterion, (c) updating the
* bid modifier value on an ad group criterion, (d) finding and removing all ad group criteria under
* a given campaign, (e) targeting a user list with a campaign criterion, and (f) updating the bid
* modifier on a campaign criterion. It is unlikely that users will need to perform all of these
* operations consecutively, and all of the operations contained herein are meant of for
* illustrative purposes.
*/
public class SetUpRemarketing {
private static final int PAGE_SIZE = 1000;
private static class SetUpRemarketingParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
private Long customerId;
@Parameter(names = ArgumentNames.AD_GROUP_ID, required = true)
private Long adGroupId;
@Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
private Long campaignId;
/** Specify the bid modifier value here or the default specified below will be used. */
@Parameter(names = ArgumentNames.BID_MODIFIER_VALUE)
private Double bidModifierValue = 1.5;
}
public static void main(String[] args) {
SetUpRemarketingParams params = new SetUpRemarketingParams();
if (!params.parseArguments(args)) {
// Either pass the required parameters for this example on the command line, or insert them
// into the code here. See the parameter class definition above for descriptions.
params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
params.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
params.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");
// Optional: To use a different bid modifier value from the default (1.5), uncomment
// the line below and insert the desired bid modifier value.
// params.bidModifierValue = Double.parseDouble("INSERT_BID_MODIFIER_VALUE_HERE");
}
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
try {
new SetUpRemarketing()
.runExample(
googleAdsClient,
params.customerId,
params.adGroupId,
params.campaignId,
params.bidModifierValue);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
System.exit(1);
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupId the adGroup on which to do the remarketing.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(
GoogleAdsClient googleAdsClient,
long customerId,
long adGroupId,
long campaignId,
double bidModifierValue) {
String userList = createUserList(googleAdsClient, customerId);
String adGroupCriterionResourceName =
targetAdsInAdGroupToUserList(googleAdsClient, customerId, adGroupId, userList);
modifyAdGroupBids(googleAdsClient, customerId, adGroupCriterionResourceName, bidModifierValue);
removeExistingListCriteriaFromAdGroup(googleAdsClient, customerId, campaignId);
String campaignCriterionResourceName =
targetAdsInCampaignToUserList(googleAdsClient, customerId, campaignId, userList);
modifyCampaignBids(
googleAdsClient, customerId, campaignCriterionResourceName, bidModifierValue);
}
/**
* Creates a user list targeting users that have visited a given url.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @return the user list resource name.
*/
// [START setup_remarketing]
private String createUserList(GoogleAdsClient googleAdsClient, long customerId) {
// Creates a rule targeting any user that visited a url containing 'example.com'.
UserListRuleItemInfo rule =
UserListRuleItemInfo.newBuilder()
// Uses a built-in parameter to create a domain URL rule.
.setName("url__")
.setStringRuleItem(
UserListStringRuleItemInfo.newBuilder()
.setOperator(UserListStringRuleItemOperator.CONTAINS)
.setValue("example.com")
.build())
.build();
// Specifies that the user list targets visitors of a page based on the provided rule.
FlexibleRuleUserListInfo flexibleRuleUserListInfo =
FlexibleRuleUserListInfo.newBuilder()
.setInclusiveRuleOperator(UserListFlexibleRuleOperator.AND)
// Inclusive operands are joined together with the specified inclusiveRuleOperator.
.addInclusiveOperands(
FlexibleRuleOperandInfo.newBuilder()
.setRule(
UserListRuleInfo.newBuilder()
.addRuleItemGroups(
UserListRuleItemGroupInfo.newBuilder().addRuleItems(rule)))
// Optional: adds a lookback window for this rule, in days.
.setLookbackWindowDays(7L))
.build();
// Defines a representation of a user list that is generated by a rule.
RuleBasedUserListInfo ruleBasedUserListInfo =
RuleBasedUserListInfo.newBuilder()
// Optional: To include past users in the user list, set the prepopulation_status to
// REQUESTED.
.setPrepopulationStatus(UserListPrepopulationStatus.REQUESTED)
.setFlexibleRuleUserList(flexibleRuleUserListInfo)
.build();
// Creates the user list.
UserList userList =
UserList.newBuilder()
.setName("All visitors to example.com" + getPrintableDateTime())
.setDescription("Any visitor to any page of example.com")
.setMembershipStatus(UserListMembershipStatus.OPEN)
.setMembershipLifeSpan(365)
.setRuleBasedUserList(ruleBasedUserListInfo)
.build();
// Creates the operation.
UserListOperation operation = UserListOperation.newBuilder().setCreate(userList).build();
// Creates the user list service client.
try (UserListServiceClient userListServiceClient =
googleAdsClient.getLatestVersion().createUserListServiceClient()) {
// Adds the user list.
MutateUserListsResponse response =
userListServiceClient.mutateUserLists(
Long.toString(customerId), ImmutableList.of(operation));
String userListResourceName = response.getResults(0).getResourceName();
// Prints the result.
System.out.printf("Created user list with resource name '%s'.%n", userListResourceName);
return userListResourceName;
}
}
// [END setup_remarketing]
/**
* Creates an ad group criterion that targets a user list with an ad group.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupId the ad group on which the user list will be targeted.
* @param userList the resource name of the user list to be targeted.
* @return the ad group criterion resource name.
*/
// [START setup_remarketing_1]
private String targetAdsInAdGroupToUserList(
GoogleAdsClient googleAdsClient, long customerId, long adGroupId, String userList) {
// Creates the ad group criterion targeting members of the user list.
AdGroupCriterion adGroupCriterion =
AdGroupCriterion.newBuilder()
.setAdGroup(ResourceNames.adGroup(customerId, adGroupId))
.setUserList(UserListInfo.newBuilder().setUserList(userList).build())
.build();
// Creates the operation.
AdGroupCriterionOperation operation =
AdGroupCriterionOperation.newBuilder().setCreate(adGroupCriterion).build();
// Creates the ad group criterion service.
try (AdGroupCriterionServiceClient adGroupCriterionServiceClient =
googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) {
// Adds the ad group criterion.
MutateAdGroupCriteriaResponse response =
adGroupCriterionServiceClient.mutateAdGroupCriteria(
Long.toString(customerId), ImmutableList.of(operation));
// Gets and prints the results.
String adGroupCriterionResourceName = response.getResults(0).getResourceName();
System.out.printf(
"Successfully created ad group criterion with resource name '%s' "
+ "targeting user list with resource name '%s' with ad group with ID %d.%n",
adGroupCriterionResourceName, userList, adGroupId);
return adGroupCriterionResourceName;
}
}
// [END setup_remarketing_1]
/**
* Updates the bid modifier value on an ad group criterion.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupCriterionResourceName the ad group criterion to update.
* @param bidModifierValue the bid modifier value.
*/
private void modifyAdGroupBids(
GoogleAdsClient googleAdsClient,
long customerId,
String adGroupCriterionResourceName,
double bidModifierValue) {
// Creates the ad group criterion with a bid modifier value. You may alternatively set the bid
// for the ad group criterion directly.
AdGroupCriterion adGroupCriterion =
AdGroupCriterion.newBuilder()
.setResourceName(adGroupCriterionResourceName)
.setBidModifier(bidModifierValue)
.build();
// Creates the update operation.
AdGroupCriterionOperation operation =
AdGroupCriterionOperation.newBuilder()
.setUpdate(adGroupCriterion)
.setUpdateMask(FieldMasks.allSetFieldsOf(adGroupCriterion))
.build();
// Creates the ad group criterion service.
try (AdGroupCriterionServiceClient adGroupCriterionServiceClient =
googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) {
// Updates the ad group criterion.
MutateAdGroupCriteriaResponse response =
adGroupCriterionServiceClient.mutateAdGroupCriteria(
Long.toString(customerId), ImmutableList.of(operation));
// Prints the results.
System.out.printf(
"Successfully updated the bid for ad group criterion with resource name '%s'.%n",
response.getResults(0).getResourceName());
}
}
/**
* Removes all ad group criteria targeting a user list under a given campaign. This is a necessary
* step before targeting a user list at the campaign level.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param campaignId the campaign under which to remove the ad group criteria.
*/
// [START setup_remarketing_3]
private void removeExistingListCriteriaFromAdGroup(
GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
// Retrieves all of the ad group criteria under a campaign.
List<String> adGroupCriteria =
getUserListAdGroupCriterion(googleAdsClient, customerId, campaignId);
List<AdGroupCriterionOperation> operations = new ArrayList<>();
// Creates a list of remove operations.
for (String adGroupCriterion : adGroupCriteria) {
operations.add(AdGroupCriterionOperation.newBuilder().setRemove(adGroupCriterion).build());
}
// Creates the ad group criterion service.
try (AdGroupCriterionServiceClient adGroupCriterionServiceClient =
googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) {
// Removes the ad group criterion.
MutateAdGroupCriteriaResponse response =
adGroupCriterionServiceClient.mutateAdGroupCriteria(
Long.toString(customerId), operations);
// Gets and prints the results.
System.out.printf("Removed %d ad group criteria.%n", response.getResultsCount());
for (MutateAdGroupCriterionResult result : response.getResultsList()) {
System.out.printf(
"Successfully removed ad group criterion with resource name '%s'.%n",
result.getResourceName());
}
}
}
// [END setup_remarketing_3]
/**
* Finds all of user list ad group criteria under a campaign.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param campaignId the campaign under which to search the ad group criteria.
* @return a list of the ad group criteria resource names.
*/
// [START setup_remarketing_2]
private List<String> getUserListAdGroupCriterion(
GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
List<String> userListCriteria = new ArrayList<>();
// Creates the Google Ads service client.
try (GoogleAdsServiceClient googleAdsServiceClient =
googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
// Creates a request that will retrieve all of the ad group criteria under a campaign.
SearchGoogleAdsRequest request =
SearchGoogleAdsRequest.newBuilder()
.setCustomerId(Long.toString(customerId))
.setPageSize(PAGE_SIZE)
.setQuery(
"SELECT ad_group_criterion.criterion_id"
+ " FROM ad_group_criterion"
+ " WHERE campaign.id = "
+ campaignId
+ " AND ad_group_criterion.type = 'USER_LIST'")
.build();
// Issues the search request.
SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request);
// Iterates over all rows in all pages. Prints the results and adds the ad group criteria
// resource names to the list.
for (GoogleAdsRow googleAdsRow : searchPagedResponse.iterateAll()) {
String adGroupCriterionResourceName = googleAdsRow.getAdGroupCriterion().getResourceName();
System.out.printf(
"Ad group criterion with resource name '%s' was found.%n",
adGroupCriterionResourceName);
userListCriteria.add(adGroupCriterionResourceName);
}
}
return userListCriteria;
}
// [END setup_remarketing_2]
/**
* Creates a campaign criterion that targets a user list with a campaign.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param campaignId the campaign on which the user list will be targeted.
* @param userList the resource name of the user list to be targeted.
* @return the campaign criterion resource name.
*/
// [START setup_remarketing_4]
private String targetAdsInCampaignToUserList(
GoogleAdsClient googleAdsClient, long customerId, long campaignId, String userList) {
// Creates the campaign criterion.
CampaignCriterion campaignCriterion =
CampaignCriterion.newBuilder()
.setCampaign(ResourceNames.campaign(customerId, campaignId))
.setUserList(UserListInfo.newBuilder().setUserList(userList).build())
.build();
// Creates the operation.
CampaignCriterionOperation operation =
CampaignCriterionOperation.newBuilder().setCreate(campaignCriterion).build();
// Creates the campaign criterion service client.
try (CampaignCriterionServiceClient campaignCriterionServiceClient =
googleAdsClient.getLatestVersion().createCampaignCriterionServiceClient()) {
// Adds the campaign criterion.
MutateCampaignCriteriaResponse response =
campaignCriterionServiceClient.mutateCampaignCriteria(
Long.toString(customerId), ImmutableList.of(operation));
// Gets and prints the campaign criterion resource name.
String campaignCriterionResourceName = response.getResults(0).getResourceName();
System.out.printf(
"Successfully created campaign criterion with resource name '%s' "
+ "targeting user list with resource name '%s' with campaign with ID %d.%n",
campaignCriterionResourceName, userList, campaignId);
return campaignCriterionResourceName;
}
}
// [END setup_remarketing_4]
/**
* Updates the bid modifier value on a campaign criterion.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param campaignCriterionResourceName the campaign criterion to update.
* @param bidModifierValue the bid modifier value.
*/
private void modifyCampaignBids(
GoogleAdsClient googleAdsClient,
long customerId,
String campaignCriterionResourceName,
double bidModifierValue) {
// Creates the campaign criterion to update.
CampaignCriterion campaignCriterion =
CampaignCriterion.newBuilder()
.setResourceName(campaignCriterionResourceName)
.setBidModifier((float) bidModifierValue)
.build();
// Creates the update operation.
CampaignCriterionOperation operation =
CampaignCriterionOperation.newBuilder()
.setUpdate(campaignCriterion)
.setUpdateMask(FieldMasks.allSetFieldsOf(campaignCriterion))
.build();
// Creates the campaign criterion service client.
try (CampaignCriterionServiceClient campaignCriterionServiceClient =
googleAdsClient.getLatestVersion().createCampaignCriterionServiceClient()) {
// Updates the campaign criterion.
MutateCampaignCriteriaResponse response =
campaignCriterionServiceClient.mutateCampaignCriteria(
Long.toString(customerId), ImmutableList.of(operation));
System.out.printf(
"Successfully updated the bid for campaign criterion with resource name '%s'.%n",
response.getResults(0).getResourceName());
}
}
}