Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 30 additions & 25 deletions examples/remarketing/upload_enhanced_conversions_for_leads.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@

import argparse
import hashlib
import re
import sys
from typing import Dict, Optional, Union

Expand Down Expand Up @@ -99,12 +98,13 @@ def main(
# a UserIdentifier with ONLY a hashed_phone_number:
#
# incorrectly_populated_user_identifier = client.get_type("UserIdentifier")
# incorrectly_populated_user_identifier.hashed_email = "...""
# incorrectly_populated_user_identifier.hashed_phone_number = "...""
# incorrectly_populated_user_identifier.hashed_email = "..."
# incorrectly_populated_user_identifier.hashed_phone_number = "..."

raw_record: Dict[str, Union[str, float]] = {
# Email address that includes a period (.) before the Gmail domain.
"email": "alex.2@example.com",
# Email address that includes a period (.) and '+' suffix before the
# Gmail domain, both of which will be removed during normalization.
"email": "alex.2+myalias@gmail.com",
# Phone number to be converted to E.164 format, with a leading '+' as
# required.
"phone": "+1 800 5550102",
Expand Down Expand Up @@ -141,9 +141,9 @@ def main(
if raw_record.get("phone") is not None:
phone_identifier: UserIdentifier = client.get_type("UserIdentifier")
phone_identifier.hashed_phone_number = normalize_and_hash(
raw_record["phone"]
raw_record["phone"], remove_all_whitespace=True
)
Comment thread
pattersonlois marked this conversation as resolved.
Resolved
# Adds the phone identifier to the conversion adjustment.
# Adds the phone identifier to the conversion.
click_conversion.user_identifiers.append(phone_identifier)
# [END add_user_identifiers]

Expand Down Expand Up @@ -242,42 +242,47 @@ def normalize_and_hash_email_address(email_address: str) -> str:
"""Returns the result of normalizing and hashing an email address.

For this use case, Google Ads requires removal of any '.' characters
preceding "gmail.com" or "googlemail.com"
and '+' suffixes preceding "gmail.com" or "googlemail.com".

Args:
email_address: An email address to normalize.

Returns:
A normalized (lowercase, removed whitespace) and SHA-265 hashed string.
A normalized (lowercase, removed whitespace) and SHA-256 hashed string.
"""
normalized_email: str = email_address.strip().lower()
normalized_email: str = "".join(email_address.split()).lower()
email_parts: list[str] = normalized_email.split("@")

# Check that there are at least two segments
if len(email_parts) > 1:
# Removes any '.' and '+' characters from the portion of the email address
# before the domain
chars_to_remove = ".+"
translation_table = str.maketrans("", "", chars_to_remove)
email_parts[0] = email_parts[0].translate(translation_table)
normalized_email = "@".join(email_parts)
# Checks that the email has exactly two segments (local and domain).
if len(email_parts) == 2:
local_part, domain = email_parts
if domain in ("gmail.com", "googlemail.com"):
# Removes any '+' suffix and '.' characters from the local part.
local_part = local_part.partition("+")[0].replace(".", "")
normalized_email = f"{local_part}@{domain}"

return normalize_and_hash(normalized_email)
return normalize_and_hash(normalized_email, remove_all_whitespace=True)


def normalize_and_hash(s: str) -> str:
def normalize_and_hash(s: str, remove_all_whitespace: bool = False) -> str:
"""Normalizes and hashes a string with SHA-256.

Private customer data must be hashed during upload, as described at:
https://support.google.com/google-ads/answer/7474263

Args:
s: The string to perform this operation on.
remove_all_whitespace: If True, removes leading, trailing, and
intermediate whitespace before hashing (use for email and phone).
If False, removes only leading and trailing whitespace (use for
first_name, last_name, and street_address).

Returns:
A normalized (lowercase, removed whitespace) and SHA-256 hashed string.
A normalized (lowercase, trimmed whitespace) and SHA-256 hashed
string.
"""
return hashlib.sha256(s.strip().lower().encode()).hexdigest()
normalized: str = "".join(s.split()) if remove_all_whitespace else s.strip()
return hashlib.sha256(normalized.lower().encode()).hexdigest()
# [END normalize_and_hash]


Expand All @@ -289,8 +294,8 @@ def normalize_and_hash(s: str) -> str:
)

parser: argparse.ArgumentParser = argparse.ArgumentParser(
description="Imports offline call conversion values for calls related "
"to your ads."
description="Uploads an enhanced conversion for leads by uploading a "
"ClickConversion."
)
# The following argument(s) should be provided to run the example.
parser.add_argument(
Expand Down Expand Up @@ -398,7 +403,7 @@ def normalize_and_hash(s: str) -> str:
)
except GoogleAdsException as ex:
print(
f"Request with ID '{ex.request_id}'' failed with status "
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:
Expand Down
57 changes: 31 additions & 26 deletions examples/remarketing/upload_enhanced_conversions_for_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@

import argparse
import hashlib
import re
import sys

from google.ads.googleads.client import GoogleAdsClient
Expand Down Expand Up @@ -61,12 +60,13 @@ def main(
# a UserIdentifier with ONLY a hashed_phone_number:
#
# incorrectly_populated_user_identifier = client.get_type("UserIdentifier")
# incorrectly_populated_user_identifier.hashed_email = "...""
# incorrectly_populated_user_identifier.hashed_phone_number = "...""
# incorrectly_populated_user_identifier.hashed_email = "..."
# incorrectly_populated_user_identifier.hashed_phone_number = "..."

raw_record = {
# Email address that includes a period (.) before the Gmail domain.
"email": "alex.2@example.com",
# Email address that includes a period (.) and '+' suffix before the
# Gmail domain, both of which will be removed during normalization.
"email": "alex.2+myalias@gmail.com",
# Address that includes all four required elements: first name, last
# name, country code, and postal code.
"first_name": "Alex",
Expand Down Expand Up @@ -111,7 +111,7 @@ def main(
if raw_record.get("phone") is not None:
phone_identifier = client.get_type("UserIdentifier")
phone_identifier.hashed_phone_number = normalize_and_hash(
raw_record["phone"]
raw_record["phone"], remove_all_whitespace=True
)
# Adds the phone identifier to the conversion adjustment.
conversion_adjustment.user_identifiers.append(phone_identifier)
Expand All @@ -129,7 +129,7 @@ def main(
]
if len(missing_keys) > 0:
print(
"Skipping addition of mailing address information because the"
"Skipping addition of mailing address information because the "
f"following required keys are missing: {missing_keys}"
)
else:
Expand Down Expand Up @@ -210,7 +210,7 @@ def main(
result = response.results[0]
print(
f"Uploaded conversion adjustment of {result.conversion_action} for "
f"order ID {result,order_id}."
f"order ID {result.order_id}."
)


Expand All @@ -219,49 +219,54 @@ def normalize_and_hash_email_address(email_address):
"""Returns the result of normalizing and hashing an email address.

For this use case, Google Ads requires removal of any '.' characters
preceding "gmail.com" or "googlemail.com"
and '+' suffixes preceding "gmail.com" or "googlemail.com".

Args:
email_address: An email address to normalize.

Returns:
A normalized (lowercase, removed whitespace) and SHA-265 hashed string.
A normalized (lowercase, removed whitespace) and SHA-256 hashed string.
"""
normalized_email = email_address.strip().lower()
normalized_email = "".join(email_address.split()).lower()
email_parts = normalized_email.split("@")

# Check that there are at least two segments
if len(email_parts) > 1:
# Removes any '.' and '+' characters from the portion of the email address
# before the domain
chars_to_remove = ".+"
translation_table = str.maketrans("", "", chars_to_remove)
email_parts[0] = email_parts[0].translate(translation_table)
normalized_email = "@".join(email_parts)
# Checks that the email has exactly two segments (local and domain).
if len(email_parts) == 2:
local_part, domain = email_parts
if domain in ("gmail.com", "googlemail.com"):
# Removes any '+' suffix and '.' characters from the local part.
local_part = local_part.partition("+")[0].replace(".", "")
normalized_email = f"{local_part}@{domain}"

return normalize_and_hash(normalized_email)
return normalize_and_hash(normalized_email, remove_all_whitespace=True)


def normalize_and_hash(s):
def normalize_and_hash(s, remove_all_whitespace=False):
"""Normalizes and hashes a string with SHA-256.

Private customer data must be hashed during upload, as described at:
https://support.google.com/google-ads/answer/9888656

Args:
s: The string to perform this operation on.
remove_all_whitespace: If True, removes leading, trailing, and
intermediate whitespace before hashing (use for email and phone).
If False, removes only leading and trailing whitespace (use for
first_name, last_name, and street_address).

Returns:
A normalized (lowercase, removed whitespace) and SHA-256 hashed string.
A normalized (lowercase, trimmed whitespace) and SHA-256 hashed
string.
"""
return hashlib.sha256(s.strip().lower().encode()).hexdigest()
normalized = "".join(s.split()) if remove_all_whitespace else s.strip()
return hashlib.sha256(normalized.lower().encode()).hexdigest()
# [END normalize_and_hash]


if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Imports offline call conversion values for calls related "
"to your ads."
description="Enhances a web conversion by uploading a "
"ConversionAdjustment."
)
# The following argument(s) should be provided to run the example.
parser.add_argument(
Expand Down Expand Up @@ -318,7 +323,7 @@ def normalize_and_hash(s):
)
except GoogleAdsException as ex:
print(
f"Request with ID '{ex.request_id}'' failed with status "
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:
Expand Down
Empty file.
Loading