-
Notifications
You must be signed in to change notification settings - Fork 471
/
add_merchant_center_dynamic_remarketing_campaign.py
356 lines (310 loc) · 13.4 KB
/
add_merchant_center_dynamic_remarketing_campaign.py
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
#!/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 campaign associated with an existing Merchant Center account.
Creates a shopping campaign, related ad group and dynamic display ad, and
targets a user list for remarketing purposes.
"""
import argparse
import requests
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,
merchant_center_account_id,
campaign_budget_id,
user_list_id,
):
"""Creates a campaign associated with an existing Merchant Center account.
Args:
client: An initialized GoogleAds client.
customer_id: The Google Ads customer ID.
merchant_center_account_id: The target Merchant Center account ID.
campaign_budget_id: The ID of the campaign budget to utilize.
user_list_id: The ID of the user list to target for remarketing.
"""
# Create a shopping campaign associated with a given Merchant Center
# account.
campaign_resource_name = create_campaign(
client, customer_id, merchant_center_account_id, campaign_budget_id
)
# Create an ad group for the campaign.
ad_group_resource_name = create_ad_group(
client, customer_id, campaign_resource_name
)
# Create a dynamic display ad in the ad group.
create_ad(client, customer_id, ad_group_resource_name)
# Target a specific user list for remarketing.
attach_user_list(client, customer_id, ad_group_resource_name, user_list_id)
# [START add_merchant_center_dynamic_remarketing_campaign_2]
def create_campaign(
client, customer_id, merchant_center_account_id, campaign_budget_id
):
"""Creates a campaign linked to a Merchant Center product feed.
Args:
client: An initialized GoogleAds client.
customer_id: The Google Ads customer ID.
merchant_center_account_id: The target Merchant Center account ID.
campaign_budget_id: The ID of the campaign budget to utilize.
Returns:
The string resource name of the newly created campaign.
"""
# Gets the CampaignService client.
campaign_service = client.get_service("CampaignService")
# Creates a campaign operation and configures the new campaign.
campaign_operation = client.get_type("CampaignOperation")
campaign = campaign_operation.create
campaign.name = f"Shopping campaign #{uuid4()}"
# Configures the settings for the shopping campaign.
campaign.shopping_setting.campaign_priority = 0
# This connects the campaign to the Merchant Center account.
campaign.shopping_setting.merchant_id = merchant_center_account_id
campaign.shopping_setting.enable_local = True
# Dynamic remarketing campaigns are only available on the Google Display
# Network.
campaign.advertising_channel_type = (
client.enums.AdvertisingChannelTypeEnum.DISPLAY
)
campaign.status = client.enums.CampaignStatusEnum.PAUSED
campaign.campaign_budget = client.get_service(
"CampaignBudgetService"
).campaign_budget_path(customer_id, campaign_budget_id)
client.copy_from(campaign.manual_cpc, client.get_type("ManualCpc"))
# Issues a mutate request to add the campaign.
campaign_response = campaign_service.mutate_campaigns(
customer_id=customer_id, operations=[campaign_operation]
)
campaign_resource_name = campaign_response.results[0].resource_name
print(f"Created campaign with resource name '{campaign_resource_name}'.")
return campaign_resource_name
# [END add_merchant_center_dynamic_remarketing_campaign_2]
# [START add_merchant_center_dynamic_remarketing_campaign_1]
def create_ad_group(client, customer_id, campaign_resource_name):
"""Creates an ad group for the remarketing campaign.
Args:
client: An initialized GoogleAds client.
customer_id: The Google Ads customer ID.
campaign_resource_name: The resource name of the target campaign.
Returns:
The string resource name of the newly created ad group.
"""
# Gets the AdGroupService.
ad_group_service = client.get_service("AdGroupService")
# Creates an ad group operation and configures the new ad group.
ad_group_operation = client.get_type("AdGroupOperation")
ad_group = ad_group_operation.create
ad_group.name = "Dynamic remarketing ad group"
ad_group.campaign = campaign_resource_name
ad_group.status = client.enums.AdGroupStatusEnum.ENABLED
# Issues a mutate request to add the ad group.
ad_group_response = ad_group_service.mutate_ad_groups(
customer_id=customer_id, operations=[ad_group_operation]
)
ad_group_resource_name = ad_group_response.results[0].resource_name
return ad_group_resource_name
# [END add_merchant_center_dynamic_remarketing_campaign_1]
# [START add_merchant_center_dynamic_remarketing_campaign]
def create_ad(client, customer_id, ad_group_resource_name):
"""Creates the responsive display ad.
Args:
client: An initialized GoogleAds client.
customer_id: The Google Ads customer ID.
ad_group_resource_name: The resource name of the target ad group.
"""
# Get the AdGroupAdService client.
ad_group_ad_service = client.get_service("AdGroupAdService")
# Upload image assets for the ad.
marketing_image_resource_name = upload_image_asset(
client, customer_id, "https://gaagl.page.link/Eit5", "Marketing Image"
)
square_marketing_image_resource_name = upload_image_asset(
client,
customer_id,
"https://gaagl.page.link/bjYi",
"Square Marketing Image",
)
# Create the relevant asset objects for the ad.
marketing_image = client.get_type("AdImageAsset")
marketing_image.asset = marketing_image_resource_name
square_marketing_image = client.get_type("AdImageAsset")
square_marketing_image.asset = square_marketing_image_resource_name
headline = client.get_type("AdTextAsset")
headline.text = "Travel"
description = client.get_type("AdTextAsset")
description.text = "Take to the air!"
# Create an ad group ad operation and set the ad group ad values.
ad_group_ad_operation = client.get_type("AdGroupAdOperation")
ad_group_ad = ad_group_ad_operation.create
ad_group_ad.ad_group = ad_group_resource_name
ad_group_ad.ad.final_urls.append("http://www.example.com/")
# Configure the responsive display ad info object.
responsive_display_ad_info = ad_group_ad.ad.responsive_display_ad
responsive_display_ad_info.marketing_images.append(marketing_image)
responsive_display_ad_info.square_marketing_images.append(
square_marketing_image
)
responsive_display_ad_info.headlines.append(headline)
responsive_display_ad_info.long_headline.text = "Travel the World"
responsive_display_ad_info.descriptions.append(description)
responsive_display_ad_info.business_name = "Interplanetary Cruises"
# Optional: Call to action text.
# Valid texts: https://support.google.com/google-ads/answer/7005917
responsive_display_ad_info.call_to_action_text = "Apply Now"
# Optional: Set the ad colors.
responsive_display_ad_info.main_color = "#0000ff"
responsive_display_ad_info.accent_color = "#ffff00"
# Optional: Set to false to strictly render the ad using the colors.
responsive_display_ad_info.allow_flexible_color = False
# Optional: Set the format setting that the ad will be served in.
responsive_display_ad_info.format_setting = (
client.enums.DisplayAdFormatSettingEnum.NON_NATIVE
)
# Optional: Create a logo image and set it to the ad.
# logo_image = client.get_type("AdImageAsset")
# logo_image.asset = "INSERT_LOGO_IMAGE_RESOURCE_NAME_HERE"
# responsive_display_ad_info.logo_images.append(logo_image)
# Optional: Create a square logo image and set it to the ad.
# square_logo_image = client.get_type("AdImageAsset")
# square_logo_image.asset = "INSERT_SQUARE_LOGO_IMAGE_RESOURCE_NAME_HERE"
# responsive_display_ad_info.square_logo_images.append(square_logo_image)
# Issue a mutate request to add the ad group ad.
ad_group_ad_response = ad_group_ad_service.mutate_ad_group_ads(
customer_id=customer_id, operations=[ad_group_ad_operation]
)
print(
"Created ad group ad with resource name "
f"'{ad_group_ad_response.results[0].resource_name}'."
)
# [END add_merchant_center_dynamic_remarketing_campaign]
def upload_image_asset(client, customer_id, image_url, asset_name):
"""Adds an image asset to the Google Ads account.
Args:
client: An initialized GoogleAds client.
customer_id: The Google Ads customer ID.
image_url: The URL of the image source.
asset_name: The string label for this image asset.
Returns:
The string resource name of the newly uploaded image asset.
"""
# Get the AssetService client.
asset_service = client.get_service("AssetService")
# Fetch the image data.
image_data = requests.get(image_url).content
# Create an asset operation and set the image asset values.
asset_operation = client.get_type("AssetOperation")
asset = asset_operation.create
asset.type_ = client.enums.AssetTypeEnum.IMAGE
asset.image_asset.data = image_data
asset.name = asset_name
mutate_asset_response = asset_service.mutate_assets(
customer_id=customer_id, operations=[asset_operation]
)
image_asset_resource_name = mutate_asset_response.results[0].resource_name
print(
"Created image asset with resource name "
f"'{image_asset_resource_name}'."
)
return image_asset_resource_name
# [START add_merchant_center_dynamic_remarketing_campaign_3]
def attach_user_list(client, customer_id, ad_group_resource_name, user_list_id):
"""Targets a user list with an ad group.
Args:
client: An initialized GoogleAds client.
customer_id: The Google Ads customer ID.
ad_group_resource_name: The resource name of the target ad group.
user_list_id: The ID of the user list to target for remarketing.
"""
# Get the AdGroupCriterionService client.
ad_group_criterion_service = client.get_service("AdGroupCriterionService")
# Create an ad group criterion operation and set the ad group criterion
# values.
ad_group_criterion_operation = client.get_type("AdGroupCriterionOperation")
ad_group_criterion = ad_group_criterion_operation.create
ad_group_criterion.ad_group = ad_group_resource_name
ad_group_criterion.user_list.user_list = client.get_service(
"UserListService"
).user_list_path(customer_id, user_list_id)
# Issue a mutate request to add the ad group criterion.
ad_group_criterion_response = (
ad_group_criterion_service.mutate_ad_group_criteria(
customer_id=customer_id, operations=[ad_group_criterion_operation]
)
)
print(
"Created ad group criterion with resource name "
f"'{ad_group_criterion_response.results[0].resource_name}'."
)
# [END add_merchant_center_dynamic_remarketing_campaign_3]
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=(
"Creates a shopping campaign associated with an existing "
"Merchant Center account."
)
)
# 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(
"-m",
"--merchant_center_account_id",
type=int,
required=True,
help="The target Merchant Center account ID.",
)
parser.add_argument(
"-b",
"--campaign_budget_id",
type=int,
required=True,
help="The campaign budget ID to apply to the campaign.",
)
parser.add_argument(
"-u",
"--user_list_id",
type=int,
required=True,
help="The user list ID to target.",
)
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="v16")
try:
main(
googleads_client,
args.customer_id,
args.merchant_center_account_id,
args.campaign_budget_id,
args.user_list_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)