Mit der Google Ads API können Sie Offline-Conversions in Google Ads importieren, um Anzeigen zu erfassen, die zu Offline-Verkäufen geführt haben, z. B. per Telefon oder über einen Vertriebsmitarbeiter.
Wenn Sie die Vorteile des Imports von Conversion-Daten voll ausschöpfen möchten, empfehlen wir Ihnen, erweiterte Conversions für Leads zu implementieren. Dabei werden GCLIDs und von Nutzern bereitgestellte Daten verwendet, um Nachhaltigkeit und Leistung zu maximieren.
Erweiterte Conversions
Mit erweiterten Conversions können Sie die Genauigkeit Ihrer Conversion-Analyse verbessern, indem Sie Ihre Conversions mit selbst erhobenen Conversion-Daten wie E‑Mail-Adresse, Telefonnummer und Postanschrift ergänzen.
Es gibt zwei Arten von erweiterten Conversions. Weitere Informationen finden Sie unter Erweiterte Conversions.
Im folgenden Abschnitt wird erläutert, wie Sie Offline-Conversions optimieren. Diese Funktion wird auch als erweiterte Conversions für Leads bezeichnet.
Was sind erweiterte Conversions für Leads?
Die Funktion „Erweiterte Conversions für Leads“ ist eine verbesserte Version des Imports von Offline-Conversions. Dabei werden von Nutzern bereitgestellte Daten wie E‑Mail-Adressen verwendet, um die importierten Offline-Conversion-Daten zu ergänzen und so die Genauigkeit und die Leistung der Gebotsstrategie zu verbessern. Wenn Sie Ihre Offline-Conversions importieren, werden die bereitgestellten gehashten Kundendaten verwendet, um die Conversions der Google Ads-Kampagne zuzuordnen. Dazu werden sie mit den Daten, die auf Ihrer Website erfasst wurden (z. B. über ein Lead-Formular), und mit den Daten angemeldeter Nutzer abgeglichen, die mit Ihrer Anzeige interagiert haben. Weitere Informationen finden Sie unter Erweiterte Conversions für Leads.
Es gibt zwei Möglichkeiten, erweiterte Conversions für Leads zu implementieren. Welche Sie wählen, hängt davon ab, ob Sie das Google-Tag verwenden, um Ereignisse für das Einreichen von Formularen auf Ihrer Webseite zu erfassen. Für optimale Leistung und Langlebigkeit empfehlen wir, das Google-Tag für erweiterte Conversions für Leads zu verwenden.
- Wenn Sie von vorn beginnen, fangen Sie mit dem Abschnitt Voraussetzungen an.
- Wenn Sie bereits Importe von Offline-Conversions eingerichtet haben und auf erweiterte Conversions für Leads umstellen möchten, empfehlen wir, mit dem Abschnitt Tagging konfigurieren zu beginnen.
- Wenn Sie das Google-Tag bereits eingerichtet haben oder es nicht verwenden möchten und mit der Integration der Google Ads API beginnen, fahren Sie mit dem Abschnitt API-Implementierung fort.
- Wenn Sie von Nutzern bereitgestellte Daten nicht importieren können oder sich bei der Zuordnung Ihrer Conversions auf externe Quellen verlassen, lesen Sie den Leitfaden zum Import von Legacy-Offline-Conversions.
Vorbereitung
Prüfen Sie zuerst, ob Sie die Schritte im Abschnitt Erste Schritte ausgeführt haben.
Sie müssen erweiterte Conversions aktivieren und die Nutzungsbedingungen für Kundendaten akzeptieren, bevor Sie erweiterte Conversions für Leads verwenden können. Sie können prüfen, ob diese Voraussetzungen bereits erfüllt sind, indem Sie die folgende Anfrage an den Google Ads-Conversion-Kunden senden:
SELECT
customer.id,
customer.conversion_tracking_setting.accepted_customer_data_terms,
customer.conversion_tracking_setting.enablement_setting,
customer.conversion_tracking_setting.effective_enablement_setting
FROM customer
Wenn accepted_customer_data_terms gleich false ist oder enablement_setting (oder effective_enablement_setting beim kontoübergreifenden Conversion-Tracking) nicht ON ist, folgen Sie der Anleitung unter Neue Conversion-Aktion erstellen, um diese Voraussetzungen zu erfüllen.
Tagging konfigurieren
Konfigurieren Sie das Google-Tag für erweiterte Conversions für Leads. Folgen Sie dazu der Anleitung unter Google-Tag-Einstellungen konfigurieren. Anleitung zum Einrichten erweiterter Conversions für Leads mit Google Tag Manager
API-Implementierung
Hier ist der allgemeine Ablauf für den Import erweiterter Conversions für Leads mithilfe der Google Ads API.
Normalisieren und hashen Sie die von Nutzern bereitgestellten Daten, z. B. E‑Mail-Adresse, Telefonnummer und Postanschrift.
Füllen Sie
ClickConversion-Objekte mit den normalisierten und gehashten von Nutzern bereitgestellten Daten.Importieren Sie
ClickConversion-Objekte mit derConversionUploadServicein die Google Ads API. Weitere Informationen finden Sie unterUploadClickConversions.
Ressourcennamen der Conversion-Aktion abrufen
Wenn Sie Conversions hochladen möchten, müssen Sie den Ressourcennamen der ConversionAction angeben, die Sie in Google Ads für den Import von Klick-Conversions eingerichtet haben. Sie können den Ressourcennamen abrufen, indem Sie die conversion_action-Ressource mit der folgenden GAQL-Abfrage abfragen:
SELECT
customer.id,
conversion_action.id,
conversion_action.name,
conversion_action.type,
conversion_action.resource_name
FROM conversion_action
WHERE conversion_action.type = 'UPLOAD_CLICKS'
AND conversion_action.status = 'ENABLED'
Von Nutzern bereitgestellte Daten normalisieren und hashen
Aus Datenschutzgründen müssen die folgenden Daten vor dem Importieren mit SHA-256 gehasht werden:
- E-Mail-Adresse
- Telefonnummer
- Vorname
- Nachname
- Adresse
Hashen Sie die folgenden Daten nicht:
- Land
- Bundesland
- Stadt
- Postleitzahl
Um die Hash-Ergebnisse zu standardisieren, müssen Sie vor dem Hashen jedes dieser Werte Folgendes tun:
- Entfernen Sie Leerzeichen am Anfang und Ende.
- Verwenden Sie nur Kleinbuchstaben im Text.
- Formatieren Sie Telefonnummern gemäß dem E.164-Standard.
Formatierung von E-Mail-Adressen für erweiterte Conversions
Damit Sie die höchsten Abgleichsraten für erweiterte Conversions erzielen, müssen Sie E-Mail-Adressen richtig formatieren und hashen. Gehen Sie dazu so vor:
Standardnormalisierung anwenden (alle E‑Mail-Adressen):
- Entfernen Sie alle voran- und nachgestellten ASCII-Leerzeichen.
- Wandeln Sie alle Zeichen in der E-Mail-Adresse in Kleinbuchstaben um.
Domainspezifische Normalisierung anwenden (nur
gmail.comundgooglemail.com):- Prüfen Sie nach der Umwandlung der E-Mail-Adresse in Kleinbuchstaben, ob die Domain (nach dem Symbol
@)gmail.comodergooglemail.comlautet. - Punkte (
.) entfernen: Entfernen Sie alle Punkte aus dem Nutzernamen (vor dem Symbol@). - Plus-Suffixe entfernen (
+): Entfernen Sie aus dem Nutzernamen den ersten Plus-Suffix (+) und alle nachfolgenden Zeichen bis zum Symbol@.- Beispiel:
Jane.Doe+Shopping@googlemail.comwird zuerst zujane.doe+shopping@googlemail.com(Kleinbuchstaben) und dann zujanedoe@googlemail.com(Gmail- und Googlemail-Regeln).
- Beispiel:
- Andere Domains: Bei allen Domains außer
gmail.comodergooglemail.comdürfen Sie keine Punkte oder Plus-Suffixe aus dem Nutzernamen entfernen. Nur Standardnormalisierung anwenden (Leerzeichen entfernen und in Kleinbuchstaben umwandeln).- Beispiel:
user.name+NYC@Example.comwird zuuser.name+nyc@example.comnormalisiert.
- Beispiel:
- Prüfen Sie nach der Umwandlung der E-Mail-Adresse in Kleinbuchstaben, ob die Domain (nach dem Symbol
Normalisierte E‑Mail-Adresse hashen:
- Codieren Sie den normalisierten E‑Mail-String als UTF-8.
- Hashen Sie die UTF‑8‑Bytes mit dem SHA-256.
- Formatieren Sie den resultierenden Digest als hexadezimalen String in Kleinbuchstaben (64 Zeichen).
import hashlib
import re
def normalize_and_hash_email(email: str) -> str:
"""Normalizes and SHA-256 hashes an email address for enhanced conversions."""
normalized = email.strip().lower()
parts = normalized.split("@")
if len(parts) != 2:
raise ValueError("Invalid email address format.")
username, domain = parts
if domain in ("gmail.com", "googlemail.com"):
username = username.replace(".", "")
username = re.sub(r"\+.*$", "", username)
normalized = f"{username}@{domain}"
return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
Codebeispiel
In diesem Beispiel wird gezeigt, wie Sie von Nutzern bereitgestellte Daten normalisieren und hashen.
Java
private String normalizeAndHash(MessageDigest digest, String s) throws UnsupportedEncodingException { // Normalizes by first converting all characters to lowercase, then trimming spaces. String normalized = s.toLowerCase(); // Removes leading, trailing, and intermediate spaces. normalized = normalized.replaceAll("\\s+", ""); // Hashes the normalized string using the hashing algorithm. byte[] hash = digest.digest(normalized.getBytes("UTF-8")); StringBuilder result = new StringBuilder(); for (byte b : hash) { result.append(String.format("%02x", b)); } return result.toString(); } /** * Returns the result of normalizing and hashing an email address. For this use case, Google Ads * requires removal of any '.' characters or trailing '+' and characters that follow it from the * username portion of the email address if the domain is {@code gmail.com} or {@code * googlemail.com}. * * @param digest the digest to use to hash the normalized string. * @param emailAddress the email address to normalize and hash. */ private String normalizeAndHashEmailAddress(MessageDigest digest, String emailAddress) throws UnsupportedEncodingException { // Removes all whitespace (leading, trailing, and intermediate) from the email address. String normalizedEmail = emailAddress.toLowerCase().replaceAll("\\s+", ""); String[] emailParts = normalizedEmail.split("@", 2); if (emailParts.length == 2 && emailParts[1].matches("^(gmail|googlemail)\\.com$")) { // Removes any '.' characters from the portion of the email address before the domain if the // domain is gmail.com or googlemail.com. emailParts[0] = emailParts[0].replaceAll("\\.", ""); // Removes any '+' and all characters that follow it from the portion of the email address // before the domain if the domain is gmail.com or googlemail.com. emailParts[0] = emailParts[0].replaceAll("\\+.*", ""); normalizedEmail = String.format("%s@%s", emailParts[0], emailParts[1]); } return normalizeAndHash(digest, normalizedEmail); } /** * Returns the result of normalizing and hashing a phone number. For this use case, Google Ads * requires phone numbers to be in E.164 format. * * @param digest the digest to use to hash the normalized string. * @param phoneNumber the phone number to normalize and hash. */ private String normalizeAndHashPhoneNumber(MessageDigest digest, String phoneNumber) throws UnsupportedEncodingException { // Removes non-digit characters and prepends a leading '+' sign. String digitsOnly = phoneNumber.replaceAll("[^0-9]", ""); String formattedPhone = "+" + digitsOnly; if (!formattedPhone.matches("^\\+[1-9]\\d{6,14}$")) { throw new IllegalArgumentException("Phone number must be in E.164 format: " + phoneNumber); } return normalizeAndHash(digest, formattedPhone); }
C#
/// <summary> /// Normalizes the email address and hashes it. For this use case, Google Ads requires /// removal of any '.' characters preceding <code>gmail.com</code> or /// <code>googlemail.com</code>. /// </summary> /// <param name="emailAddress">The email address.</param> /// <returns>The hash code.</returns> private string NormalizeAndHashEmailAddress(string emailAddress) { string normalizedEmail = emailAddress.ToLower(); string[] emailParts = normalizedEmail.Split('@'); if (emailParts.Length > 1 && (emailParts[1] == "gmail.com" || emailParts[1] == "googlemail.com")) { // Removes any '.' characters from the portion of the email address before // the domain if the domain is gmail.com or googlemail.com. emailParts[0] = emailParts[0].Replace(".", ""); normalizedEmail = $"{emailParts[0]}@{emailParts[1]}"; } return NormalizeAndHash(normalizedEmail); } /// <summary> /// Normalizes and hashes a string value. /// </summary> /// <param name="value">The value to normalize and hash.</param> /// <returns>The normalized and hashed value.</returns> private static string NormalizeAndHash(string value) { return ToSha256String(digest, ToNormalizedValue(value)); } /// <summary> /// Hash a string value using SHA-256 hashing algorithm. /// </summary> /// <param name="digest">Provides the algorithm for SHA-256.</param> /// <param name="value">The string value (e.g. an email address) to hash.</param> /// <returns>The hashed value.</returns> private static string ToSha256String(SHA256 digest, string value) { byte[] digestBytes = digest.ComputeHash(Encoding.UTF8.GetBytes(value)); // Convert the byte array into an unhyphenated hexadecimal string. return BitConverter.ToString(digestBytes).Replace("-", string.Empty); } /// <summary> /// Removes leading and trailing whitespace and converts all characters to /// lower case. /// </summary> /// <param name="value">The value to normalize.</param> /// <returns>The normalized value.</returns> private static string ToNormalizedValue(string value) { return value.Trim().ToLower(); }
PHP
private static function normalizeAndHash(string $hashAlgorithm, string $value): string { // Normalizes by first converting all characters to lowercase, then trimming spaces. $normalized = strtolower($value); // Removes leading, trailing, and intermediate spaces. $normalized = str_replace(' ', '', $normalized); return hash($hashAlgorithm, strtolower(trim($normalized))); } /** * Returns the result of normalizing and hashing an email address. For this use case, Google * Ads requires removal of any '.' characters or trailing '+' and characters that follow it * from the username portion of the email address if the domain is "gmail.com" or * "googlemail.com". * * @param string $hashAlgorithm the hash algorithm to use * @param string $emailAddress the email address to normalize and hash * @return string the normalized and hashed email address */ private static function normalizeAndHashEmailAddress( string $hashAlgorithm, string $emailAddress ): string { // Removes all whitespace (leading, trailing, and intermediate) from the email address. $normalizedEmail = preg_replace('/\s+/', '', strtolower($emailAddress)); $emailParts = explode('@', $normalizedEmail, 2); if ( count($emailParts) === 2 && preg_match('/^(gmail|googlemail)\.com$/', $emailParts[1]) ) { // Removes any '.' characters from the portion of the email address before the domain // if the domain is gmail.com or googlemail.com. $emailParts[0] = str_replace('.', '', $emailParts[0]); // Removes any '+' and all characters that follow it from the portion of the email // address before the domain if the domain is gmail.com or googlemail.com. $emailParts[0] = preg_replace('/\+.*/', '', $emailParts[0]); $normalizedEmail = sprintf('%s@%s', $emailParts[0], $emailParts[1]); } return self::normalizeAndHash($hashAlgorithm, $normalizedEmail); } /** * Returns the result of normalizing and hashing a phone number. For this use case, Google Ads * requires phone numbers to be in E.164 format. * * @param string $hashAlgorithm the hash algorithm to use * @param string $phoneNumber the phone number to normalize and hash * @return string the normalized and hashed phone number * @throws \InvalidArgumentException if the phone number is not in E.164 format */ private static function normalizeAndHashPhoneNumber( string $hashAlgorithm, string $phoneNumber ): string { // Removes non-digit characters and prepends a leading '+' sign. $digitsOnly = preg_replace('/[^0-9]/', '', $phoneNumber); $formattedPhone = '+' . $digitsOnly; if (!preg_match('/^\+[1-9]\d{6,14}$/', $formattedPhone)) { throw new \InvalidArgumentException( "Phone number must be in E.164 format: $phoneNumber" ); } return self::normalizeAndHash($hashAlgorithm, $formattedPhone); }
Python
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" Args: email_address: An email address to normalize. Returns: A normalized (lowercase, removed whitespace) and SHA-265 hashed string. """ normalized_email: str = email_address.strip().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) return normalize_and_hash(normalized_email) def normalize_and_hash(s: str) -> 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. Returns: A normalized (lowercase, removed whitespace) and SHA-256 hashed string. """ return hashlib.sha256(s.strip().lower().encode()).hexdigest()
Ruby
# Returns the result of normalizing and then hashing the string using the # provided digest. Private customer data must be hashed during upload, as # described at https://support.google.com/google-ads/answer/7474263. def normalize_and_hash(str) # Remove leading and trailing whitespace and ensure all letters are lowercase # before hashing. Digest::SHA256.hexdigest(str.strip.downcase) end # 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'. def normalize_and_hash_email(email) email_parts = email.downcase.split("@") # Removes any '.' characters from the portion of the email address before the # domain if the domain is gmail.com or googlemail.com. if email_parts.last =~ /^(gmail|googlemail)\.com\s*/ email_parts[0] = email_parts[0].gsub('.', '') end normalize_and_hash(email_parts.join('@')) end
Perl
sub normalize_and_hash { my $value = shift; # Removes leading, trailing, and intermediate spaces. $value =~ s/\s+//g; return sha256_hex(lc $value); } # 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'. sub normalize_and_hash_email_address { my $email_address = shift; my $normalized_email = lc $email_address; my @email_parts = split('@', $normalized_email); if (scalar @email_parts > 1 && $email_parts[1] =~ /^(gmail|googlemail)\.com\s*/) { # Remove any '.' characters from the portion of the email address before the # domain if the domain is 'gmail.com' or 'googlemail.com'. $email_parts[0] =~ s/\.//g; $normalized_email = sprintf '%s@%s', $email_parts[0], $email_parts[1]; } return normalize_and_hash($normalized_email); }
curl
ClickConversion-Objekte erstellen
Die Sammlung von ClickConversion-Objekten in Ihrer UploadClickConversionsRequest stellt die Gruppe von Conversions dar, die Sie importieren möchten. Beachten Sie beim Erstellen von ClickConversion-Objekten Folgendes:
gclidGCLIDs sind Kennungen, die aus URL-Parametern erfasst werden, wenn ein Nutzer auf Ihre Anzeige klickt und Ihre Website aufruft.
gbraidEine
gbraidist ein URL-Parameter, der vorhanden ist, wenn ein Nutzer im Web auf eine Anzeige klickt und zu Ihrer iOS-App weitergeleitet wird.wbraidEine
wbraidist ein URL-Parameter, der vorhanden ist, wenn ein Nutzer auf eine Anzeige in einer iOS-App klickt und zu Ihrer Webseite weitergeleitet wird.cart_dataEnthält Details auf Artikelebene zu einer Conversion. Das Feld
cart_datamuss ausgefüllt werden, damit Berichte zu Warenkorbdaten (z. B. gekaufte Artikel, Preis und Menge) in der Google Ads-Benutzeroberfläche erstellt werden können. Die erforderliche Struktur finden Sie in der ObjektdefinitionCartData. Weitere Informationen finden Sie unter Conversions mit Warenkorbdaten.user_identifiersWenn Sie erweiterte Conversions für Leads verwenden, müssen Sie das Feld
user_identifiersmit normalisierten und gehashten von Nutzern bereitgestellten Daten füllen. Wenn Sie mehrere Nutzer-IDs haben, erstellen Sie für jede eine separateUserIdentifier(bis zu fünf IDs).conversion_date_timeDatum und Uhrzeit der Conversion.
Für den Wert muss eine Zeitzone angegeben werden und das Format muss
yyyy-mm-dd HH:mm:ss+|-HH:mmsein, z. B.2022-01-01 19:32:45-05:00(Sommerzeit wird ignoriert).Die Zeitzone kann ein beliebiger gültiger Wert sein. Sie muss nicht mit der Zeitzone des Kontos übereinstimmen. Wenn Sie Ihre importierten Conversion-Daten jedoch mit den Daten in der Google Ads-Benutzeroberfläche vergleichen möchten, empfehlen wir, dieselbe Zeitzone wie für Ihr Google Ads-Konto zu verwenden, damit die Conversion-Anzahl übereinstimmt. Weitere Informationen und Beispiele finden Sie unter Daten für den Import vorbereiten. Eine Liste der gültigen Zeitzonen-IDs finden Sie unter Codes und Formate.
conversion_actionDer Ressourcenname des
ConversionActionfür die Offline-Conversion.Die Conversion-Aktion muss einen
typevonUPLOAD_CLICKShaben und im Google Ads-Conversion-Kunden des Google Ads-Kontos vorhanden sein, das mit dem Klick verknüpft ist.conversion_valueDer Wert der Conversion.
currency_codeDer Währungscode des
conversion_value.consentEs wird dringend empfohlen, das Feld
consentdesClickConversion-Objekts auszufüllen. Wenn Sie sie nicht festlegen, können Ihre Conversions möglicherweise nicht zugeordnet werden.order_idAuch als Transaktions-ID für die Conversion bezeichnet. Dieses Feld ist zwar optional, wird aber dringend empfohlen, weil es die Bezugnahme auf importierte Conversions bei Anpassungen erheblich vereinfacht. Wenn Sie die Bestell-ID beim Import festgelegt haben, müssen Sie sie bei allen Anpassungen verwenden. Weitere Informationen dazu, wie Sie mit einer Transaktions-ID doppelte Conversions minimieren können, finden Sie unter Weniger doppelte Conversions durch Transaktions-IDs.
custom_variablesDie Werte für benutzerdefinierte Conversion-Variablen. Benutzerdefinierte Conversion-Variablen werden in Google Ads nicht in Kombination mit
wbraidodergbraidunterstützt.conversion_environmentGibt die Umgebung an, in der diese Conversion erfasst wurde. Beispiel:
APPoderWEB.
session_attributes_encodedundsession_attributes_key_value_pairsSitzungsattribute sind aggregierte Kennungen, die für die Conversion-Attribution verwendet werden. Sie funktionieren zusätzlich zu GCLIDs und URL-Parametern (z. B. GBRAIDs) sowie von Nutzern bereitgestellten Daten, die für erweiterte Conversions für Leads von zentraler Bedeutung sind. Es gibt zwei Möglichkeiten, Sitzungsattribute zu importieren: durch Bereitstellen des codierten Tokens, das von unserem JavaScript-Code im Browser generiert wird, oder durch Bereitstellen einzelner Schlüssel/Wert-Paare für jede der Kennungen.
Wenn Sie die Kampagnenleistung maximieren möchten, sollten Sie nach Möglichkeit Klick-IDs, von Nutzern bereitgestellte Daten und Sitzungsattribute mit allen Conversions importieren.
Java
// Sets one of the sessionAttributesEncoded or sessionAttributesKeyValuePairs if either is // provided. The session attribute fields are only available to allowlisted users. // To include these fields in conversion imports, upgrade to the Data Manager API. if (rawRecord.containsKey("sessionAttributesEncoded")) { clickConversionBuilder.setSessionAttributesEncoded( ByteString.copyFromUtf8(rawRecord.get("sessionAttributesEncoded"))); } else if (rawRecord.containsKey("sessionAttributesMap")) { List<String> pairings = Arrays.stream(rawRecord.get("sessionAttributesMap").split(" ")) .map(String::trim) .collect(Collectors.toList()); SessionAttributesKeyValuePairs.Builder sessionAttributePairs = SessionAttributesKeyValuePairs.newBuilder(); for (String pair : pairings) { String[] parts = pair.split("=", 2); if (parts.length != 2) { throw new IllegalArgumentException( "Failed to read the sessionAttributesMap. SessionAttributesMap must use a" + " space-delimited list of session attribute key value pairs. Each pair should" + " be separated by an equal sign, for example: 'gad_campaignid=12345" + " gad_source=1'"); } sessionAttributePairs.addKeyValuePairs( SessionAttributeKeyValuePair.newBuilder() .setSessionAttributeKey(parts[0]) .setSessionAttributeValue(parts[1]) .build()); } clickConversionBuilder.setSessionAttributesKeyValuePairs(sessionAttributePairs.build()); }
C#
// The session attribute fields are only available to allowlisted users. To // include these fields in conversion imports, upgrade to the Data Manager API. if (!string.IsNullOrEmpty(sessionAttributesEncoded)) { clickConversion.SessionAttributesEncoded = ByteString.CopyFrom(sessionAttributesEncoded, Encoding.Unicode); } else if (!string.IsNullOrEmpty(sessionAttributes)) { IEnumerable<SessionAttributeKeyValuePair> parsedSessionAttributes = sessionAttributes.Split(';').Select(pair => { string[] split = pair.Split('='); return new SessionAttributeKeyValuePair() { SessionAttributeKey = split[0], SessionAttributeValue = split[1] }; }); clickConversion.SessionAttributesKeyValuePairs = new SessionAttributesKeyValuePairs(); clickConversion.SessionAttributesKeyValuePairs.KeyValuePairs .AddRange(parsedSessionAttributes); }
PHP
This example is not yet available in PHP; you can take a look at the other languages.
Python
# Set one of the session_attributes_encoded or # session_attributes_key_value_pairs fields if either are provided. # The session attribute fields are only available to allowlisted users. # To include these fields in conversion imports, upgrade to the Data Manager API. if session_attributes_encoded: click_conversion.session_attributes_encoded = session_attributes_encoded elif session_attributes_dict: for key, value in session_attributes_dict.items(): pair: SessionAttributeKeyValuePair = client.get_type( "SessionAttributeKeyValuePair" ) pair.session_attribute_key = key pair.session_attribute_value = value click_conversion.session_attributes_key_value_pairs.key_value_pairs.append( pair )
Ruby
# Set one of the session_attributes_encoded or # session_attributes_key_value_pairs fields if either are provided. # The session attribute fields are only available to allowlisted users. # To include these fields in conversion imports, upgrade to the Data Manager API. if session_attributes_encoded != nil cc.class.module_eval { attr_accessor :session_attributes_encoded} cc.session_attributes_encoded = session_attributes_encoded elsif session_attributes_hash != nil # Add new attribute to click conversion object cc.class.module_eval { attr_accessor :session_attributes_key_value_pairs} cc.session_attributes_key_value_pairs = ::Google::Ads::GoogleAds::V19::Services::SessionAttributesKeyValuePairs.new # Loop thru inputted session_attributes_hash to populate session_attributes_key_value_pairs session_attributes_hash.each do |key, value| pair = ::Google::Ads::GoogleAds::V19::Services::SessionAttributeKeyValuePair.new pair.session_attribute_key = key pair.session_attribute_value = value cc.session_attributes_key_value_pairs.key_value_pairs << pair end end
Perl
# Set one of the session_attributes_encoded or session_attributes_key_value_pairs # fields if either are provided. if (defined $session_attributes_encoded) { $click_conversion->{sessionAttributesEncoded} = $session_attributes_encoded; } elsif (defined $session_attributes_hash) { while (my ($key, $value) = each %$session_attributes_hash) { my $pair = Google::Ads::GoogleAds::V25::Services::ConversionUploadService::SessionAttributeKeyValuePair ->new({sessionAttributeKey => $key, sessionAttributeValue => $value}); push @{$click_conversion->{sessionAttributesKeyValuePairs}{keyValuePairs} }, $pair; } }
curl
user_ip_addressDie IP-Adresse des Kunden, als er nach einem Anzeigenklick und vor einem Conversion-Ereignis auf der Landingpage ankam. Das ist die IP-Adresse des Geräts des Kunden, nicht die des Servers des Werbetreibenden.
Dieses Feld ist ein String, der eine IP-Adresse im IPv4- oder IPv6-Format darstellt. Beispiel:
- IPv4:
"192.0.2.0" - IPv6:
"2001:0DB8:1234:5678:9999:1111:0000:0001"
- IPv4:
Codebeispiel
In diesem Beispiel wird gezeigt, wie Sie Ihre normalisierten und gehashten, von Nutzern bereitgestellten Daten in einem ClickConversion-Objekt festlegen.
Java
// Creates an empty builder for constructing the click conversion. ClickConversion.Builder clickConversionBuilder = ClickConversion.newBuilder(); // Extracts user email and phone from the raw data, normalizes and hashes it, then wraps it in // UserIdentifier objects. // Creates a separate UserIdentifier object for each. The data in this example is hardcoded, but // in your application you might read the raw data from an input file. // IMPORTANT: Since the identifier attribute of UserIdentifier // (https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier) is a // oneof // (https://protobuf.dev/programming-guides/proto3/#oneof-features), you must set only ONE of // hashedEmail, hashedPhoneNumber, mobileId, thirdPartyUserId, or addressInfo. Setting more // than one of these attributes on the same UserIdentifier will clear all the other members // of the oneof. For example, the following code is INCORRECT and will result in a // UserIdentifier with ONLY a hashedPhoneNumber. // // UserIdentifier incorrectlyPopulatedUserIdentifier = // UserIdentifier.newBuilder() // .setHashedEmail("...") // .setHashedPhoneNumber("...") // .build(); ImmutableMap.Builder<String, String> rawRecordBuilder = ImmutableMap.<String, String>builder() .put("email", "alex.2+myalias@gmail.com") // Phone number to be converted to E.164 format, with a leading '+' as required. .put("phone", "+1 (800) 555-0102") // This example lets you put conversion details as arguments, but in reality you might // store this data alongside other user data, so we include it in this sample user // record. .put("conversionActionId", Long.toString(conversionActionId)) .put("conversionDateTime", conversionDateTime) .put("conversionValue", Double.toString(conversionValue)) .put("currencyCode", "USD"); // Adds entries for the optional fields. if (orderId != null) { rawRecordBuilder.put("orderId", orderId); } if (gclid != null) { rawRecordBuilder.put("gclid", gclid); } if (adUserDataConsent != null) { rawRecordBuilder.put("adUserDataConsent", adUserDataConsent.name()); } if (sessionAttributesEncoded != null) { rawRecordBuilder.put("sessionAttributesEncoded", sessionAttributesEncoded); } if (sessionAttributesMap != null) { rawRecordBuilder.put("sessionAttributesMap", sessionAttributesMap); } // Builds the map representing the record. Map<String, String> rawRecord = rawRecordBuilder.build(); // Creates a SHA256 message digest for hashing user identifiers in a privacy-safe way, as // described at https://support.google.com/google-ads/answer/9888656. MessageDigest sha256Digest = MessageDigest.getInstance("SHA-256"); // Creates a list for the user identifiers. List<UserIdentifier> userIdentifiers = new ArrayList<>(); // Creates a user identifier using the hashed email address, using the normalize and hash method // specifically for email addresses. UserIdentifier emailIdentifier = UserIdentifier.newBuilder() // Optional: specify the user identifier source. .setUserIdentifierSource(UserIdentifierSource.FIRST_PARTY) // Uses the normalize and hash method specifically for email addresses. .setHashedEmail(normalizeAndHashEmailAddress(sha256Digest, rawRecord.get("email"))) .build(); userIdentifiers.add(emailIdentifier); // Creates a user identifier using normalized and hashed phone info. UserIdentifier hashedPhoneNumberIdentifier = UserIdentifier.newBuilder() .setHashedPhoneNumber(normalizeAndHashPhoneNumber(sha256Digest, rawRecord.get("phone"))) .build(); // Adds the hashed phone number identifier to the UserData object's list. userIdentifiers.add(hashedPhoneNumberIdentifier); // Adds the user identifiers to the conversion. clickConversionBuilder.addAllUserIdentifiers(userIdentifiers);
C#
// Adds a user identifier using the hashed email address, using the normalize // and hash method specifically for email addresses. clickConversion.UserIdentifiers.Add(new UserIdentifier() { HashedEmail = NormalizeAndHashEmailAddress("alex.2@example.com"), // Optional: Specifies the user identifier source. UserIdentifierSource = UserIdentifierSource.FirstParty }); // Adds a user identifier using normalized and hashed phone info. clickConversion.UserIdentifiers.Add(new UserIdentifier() { HashedPhoneNumber = NormalizeAndHash("+1 800 5550102"), // Optional: Specifies the user identifier source. UserIdentifierSource = UserIdentifierSource.FirstParty }); // Adds a user identifier with all the required mailing address elements. clickConversion.UserIdentifiers.Add(new UserIdentifier() { AddressInfo = new OfflineUserAddressInfo() { // FirstName and LastName must be normalized and hashed. HashedFirstName = NormalizeAndHash("Alex"), HashedLastName = NormalizeAndHash("Quinn"), // CountryCode and PostalCode are sent in plain text. CountryCode = "US", PostalCode = "94045" } });
PHP
// Creates a click conversion with the specified attributes. $clickConversion = new ClickConversion(); // Extract user email and phone from the raw data, normalize and hash it, then wrap it in // UserIdentifier objects. Creates a separate UserIdentifier object for each. // The data in this example is hardcoded, but in your application you might read the raw // data from an input file. // IMPORTANT: Since the identifier attribute of UserIdentifier // (https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier) is a // oneof // (https://protobuf.dev/programming-guides/proto3/#oneof-features), you must set only ONE // of hashedEmail, hashedPhoneNumber, mobileId, thirdPartyUserId, or addressInfo. Setting // more than one of these attributes on the same UserIdentifier will clear all the other // members of the oneof. For example, the following code is INCORRECT and will result in a // UserIdentifier with ONLY a hashedPhoneNumber. // // $incorrectlyPopulatedUserIdentifier = new UserIdentifier([ // 'hashed_email' => '...', // 'hashed_phone_number' => '...' // ]); $rawRecord = [ // Email address that includes a period (.) and plus (+) suffix before the Gmail domain. 'email' => 'alex.2+myalias@gmail.com', // Phone number to be converted to E.164 format, with a leading '+' as required. 'phone' => '+1 (800) 555-0102', // This example lets you input conversion details as arguments, but in reality you might // store this data alongside other user data, so we include it in this sample user // record. 'orderId' => $orderId, 'gclid' => $gclid, 'conversionActionId' => $conversionActionId, 'conversionDateTime' => $conversionDateTime, 'conversionValue' => $conversionValue, 'currencyCode' => 'USD', 'adUserDataConsent' => $adUserDataConsent, 'sessionAttributesEncoded' => $sessionAttributesEncoded, 'sessionAttributesDict' => $sessionAttributesDict ]; // Creates a list for the user identifiers. $userIdentifiers = []; // Uses the SHA-256 hash algorithm for hashing user identifiers in a privacy-safe way, as // described at https://support.google.com/google-ads/answer/9888656. $hashAlgorithm = "sha256"; // Creates a user identifier using the hashed email address, using the normalize and hash // method specifically for email addresses. $emailIdentifier = new UserIdentifier( [ // Uses the normalize and hash method specifically for email addresses. 'hashed_email' => self::normalizeAndHashEmailAddress( $hashAlgorithm, $rawRecord['email'] ), // Optional: Specifies the user identifier source. 'user_identifier_source' => UserIdentifierSource::FIRST_PARTY ] ); $userIdentifiers[] = $emailIdentifier; // Checks if the record has a phone number, and if so, adds a UserIdentifier for it. if (array_key_exists('phone', $rawRecord)) { $hashedPhoneNumberIdentifier = new UserIdentifier( [ 'hashed_phone_number' => self::normalizeAndHashPhoneNumber( $hashAlgorithm, $rawRecord['phone'] ) ] ); // Adds the hashed phone number identifier to the user identifiers list. $userIdentifiers[] = $hashedPhoneNumberIdentifier; } // Adds the user identifiers to the conversion. $clickConversion->setUserIdentifiers($userIdentifiers);
Python
# Extract user email and phone from the raw data, normalize and hash it, # then wrap it in UserIdentifier objects. Create a separate UserIdentifier # object for each. The data in this example is hardcoded, but in your # application you might read the raw data from an input file. # IMPORTANT: Since the identifier attribute of UserIdentifier # (https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier) # is a oneof # (https://protobuf.dev/programming-guides/proto3/#oneof-features), you must # set only ONE of hashed_email, hashed_phone_number, mobile_id, # third_party_user_id, or address_info. Setting more than one of these # attributes on the same UserIdentifier will clear all the other members of # the oneof. For example, the following code is INCORRECT and will result in # 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 = "..."" raw_record: Dict[str, Union[str, float]] = { # Email address that includes a period (.) before the Gmail domain. "email": "alex.2@example.com", # Phone number to be converted to E.164 format, with a leading '+' as # required. "phone": "+1 800 5550102", # This example lets you input conversion details as arguments, # but in reality you might store this data alongside other user data, # so we include it in this sample user record. "order_id": order_id, "gclid": gclid, "conversion_action_id": conversion_action_id, "conversion_date_time": conversion_date_time, "conversion_value": conversion_value, "currency_code": "USD", "ad_user_data_consent": ad_user_data_consent, } # Constructs the click conversion. click_conversion: ClickConversion = client.get_type("ClickConversion") # Creates a user identifier using the hashed email address, using the # normalize and hash method specifically for email addresses. email_identifier: UserIdentifier = client.get_type("UserIdentifier") # Optional: Specifies the user identifier source. email_identifier.user_identifier_source = ( client.enums.UserIdentifierSourceEnum.FIRST_PARTY ) # Uses the normalize and hash method specifically for email addresses. email_identifier.hashed_email = normalize_and_hash_email_address( raw_record["email"] ) # Adds the user identifier to the conversion. click_conversion.user_identifiers.append(email_identifier) # Checks if the record has a phone number, and if so, adds a UserIdentifier # for it. 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"] ) # Adds the phone identifier to the conversion adjustment. click_conversion.user_identifiers.append(phone_identifier)
Ruby
# Extract user email and phone from the raw data, normalize and hash it, # then wrap it in UserIdentifier objects. Create a separate UserIdentifier # object for each. The data in this example is hardcoded, but in your # application you might read the raw data from an input file. # IMPORTANT: Since the identifier attribute of UserIdentifier # (https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier) # is a oneof # (https://protobuf.dev/programming-guides/proto3/#oneof-features), you must # set only ONE of hashed_email, hashed_phone_number, mobile_id, # third_party_user_id, or address_info. Setting more than one of these # attributes on the same UserIdentifier will clear all the other members of # the oneof. For example, the following code is INCORRECT and will result in # a UserIdentifier with ONLY a 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", # Phone number to be converted to E.164 format, with a leading '+' as # required. "phone" => "+1 800 5550102", # This example lets you input conversion details as arguments, # but in reality you might store this data alongside other user data, # so we include it in this sample user record. "order_id" => order_id, "gclid" => gclid, "conversion_action_id" => conversion_action_id, "conversion_date_time" => conversion_date_time, "conversion_value" => conversion_value, "currency_code" => "USD", "ad_user_data_consent" => ad_user_data_consent, "session_attributes_encoded" => session_attributes_encoded, "session_attributes_hash" => session_attributes_hash } click_conversion = client.resource.click_conversion do |cc| cc.conversion_action = client.path.conversion_action(customer_id, conversion_action_id) cc.conversion_date_time = conversion_date_time cc.conversion_value = conversion_value.to_f cc.currency_code = 'USD' unless order_id.nil? cc.order_id = order_id end unless raw_record["gclid"].nil? cc.gclid = gclid end # Specifies whether user consent was obtained for the data you are # uploading. For more details, see: # https://www.google.com/about/company/user-consent-policy unless raw_record["ad_user_data_consent"].nil? cc.consent = client.resource.consent do |c| c.ad_user_data = ad_user_data_consent end end # Set one of the session_attributes_encoded or # session_attributes_key_value_pairs fields if either are provided. # The session attribute fields are only available to allowlisted users. # To include these fields in conversion imports, upgrade to the Data Manager API. if session_attributes_encoded != nil cc.class.module_eval { attr_accessor :session_attributes_encoded} cc.session_attributes_encoded = session_attributes_encoded elsif session_attributes_hash != nil # Add new attribute to click conversion object cc.class.module_eval { attr_accessor :session_attributes_key_value_pairs} cc.session_attributes_key_value_pairs = ::Google::Ads::GoogleAds::V19::Services::SessionAttributesKeyValuePairs.new # Loop thru inputted session_attributes_hash to populate session_attributes_key_value_pairs session_attributes_hash.each do |key, value| pair = ::Google::Ads::GoogleAds::V19::Services::SessionAttributeKeyValuePair.new pair.session_attribute_key = key pair.session_attribute_value = value cc.session_attributes_key_value_pairs.key_value_pairs << pair end end # Creates a user identifier using the hashed email address, using the # normalize and hash method specifically for email addresses. # If using a phone number, use the normalize_and_hash method instead. cc.user_identifiers << client.resource.user_identifier do |ui| ui.hashed_email = normalize_and_hash_email(raw_record["email"]) # Optional: Specifies the user identifier source. ui.user_identifier_source = :FIRST_PARTY end # Checks if the record has a phone number, and if so, adds a UserIdentifier # for it. unless raw_record["phone"].nil? cc.user_identifiers << client.resource.user_identifier do |ui| ui.hashed_phone_number = normalize_and_hash(raw_record["phone"]) end end end
Perl
# Create an empty click conversion. my $click_conversion = Google::Ads::GoogleAds::V25::Services::ConversionUploadService::ClickConversion ->new({}); # Extract user email and phone from the raw data, normalize and hash it, # then wrap it in UserIdentifier objects. Create a separate UserIdentifier # object for each. # The data in this example is hardcoded, but in your application # you might read the raw data from an input file. # # IMPORTANT: Since the identifier attribute of UserIdentifier # (https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier) # is a oneof # (https://protobuf.dev/programming-guides/proto3/#oneof-features), you must set # only ONE of hashed_email, hashed_phone_number, mobile_id, third_party_user_id, # or address-info. Setting more than one of these attributes on the same UserIdentifier # will clear all the other members of the oneof. For example, the following code is # INCORRECT and will result in a UserIdentifier with ONLY a hashed_phone_number: # # my $incorrect_user_identifier = Google::Ads::GoogleAds::V25::Common::UserIdentifier->new({ # hashedEmail => '...', # hashedPhoneNumber => '...', # }); my $raw_record = { # Email address that includes a period (.) before the Gmail domain. email => 'alex.2@example.com', # Phone number to be converted to E.164 format, with a leading '+' as # required. phone => '+1 800 5550102', # This example lets you input conversion details as arguments, # but in reality you might store this data alongside other user data, # so we include it in this sample user record. orderId => $order_id, gclid => $gclid, conversionActionId => $conversion_action_id, conversionDateTime => $conversion_date_time, conversionValue => $conversion_value, currencyCode => "USD", adUserDataConsent => $ad_user_data_consent }; my $user_identifiers = []; # Create a user identifier using the hashed email address, using the normalize # and hash method specifically for email addresses. my $hashed_email = normalize_and_hash_email_address($raw_record->{email}); push( @$user_identifiers, Google::Ads::GoogleAds::V25::Common::UserIdentifier->new({ hashedEmail => $hashed_email, # Optional: Specify the user identifier source. userIdentifierSource => FIRST_PARTY })); # Create a user identifier using normalized and hashed phone info. my $hashed_phone = normalize_and_hash($raw_record->{phone}); push( @$user_identifiers, Google::Ads::GoogleAds::V25::Common::UserIdentifier->new({ hashedPhone => $hashed_phone, # Optional: Specify the user identifier source. userIdentifierSource => FIRST_PARTY })); # Add the user identifiers to the conversion. $click_conversion->{userIdentifiers} = $user_identifiers;
curl
In diesem Beispiel wird gezeigt, wie andere erforderliche Felder für ein ClickConversion-Objekt festgelegt werden.
Java
// Adds details of the conversion. clickConversionBuilder.setConversionAction( ResourceNames.conversionAction( customerId, Long.parseLong(rawRecord.get("conversionActionId")))); clickConversionBuilder.setConversionDateTime(rawRecord.get("conversionDateTime")); clickConversionBuilder.setConversionValue(Double.parseDouble(rawRecord.get("conversionValue"))); clickConversionBuilder.setCurrencyCode(rawRecord.get("currencyCode")); // Sets the order ID if provided. if (rawRecord.containsKey("orderId")) { clickConversionBuilder.setOrderId(rawRecord.get("orderId")); } // Sets the Google click ID (gclid) if provided. if (rawRecord.containsKey("gclid")) { clickConversionBuilder.setGclid(rawRecord.get("gclid")); } // Sets the consent information, if provided. if (rawRecord.containsKey("adUserDataConsent")) { // Specifies whether user consent was obtained for the data you are uploading. See // https://www.google.com/about/company/user-consent-policy for details. clickConversionBuilder.setConsent( Consent.newBuilder() .setAdUserData(ConsentStatus.valueOf(rawRecord.get("adUserDataConsent")))); } // Sets one of the sessionAttributesEncoded or sessionAttributesKeyValuePairs if either is // provided. The session attribute fields are only available to allowlisted users. // To include these fields in conversion imports, upgrade to the Data Manager API. if (rawRecord.containsKey("sessionAttributesEncoded")) { clickConversionBuilder.setSessionAttributesEncoded( ByteString.copyFromUtf8(rawRecord.get("sessionAttributesEncoded"))); } else if (rawRecord.containsKey("sessionAttributesMap")) { List<String> pairings = Arrays.stream(rawRecord.get("sessionAttributesMap").split(" ")) .map(String::trim) .collect(Collectors.toList()); SessionAttributesKeyValuePairs.Builder sessionAttributePairs = SessionAttributesKeyValuePairs.newBuilder(); for (String pair : pairings) { String[] parts = pair.split("=", 2); if (parts.length != 2) { throw new IllegalArgumentException( "Failed to read the sessionAttributesMap. SessionAttributesMap must use a" + " space-delimited list of session attribute key value pairs. Each pair should" + " be separated by an equal sign, for example: 'gad_campaignid=12345" + " gad_source=1'"); } sessionAttributePairs.addKeyValuePairs( SessionAttributeKeyValuePair.newBuilder() .setSessionAttributeKey(parts[0]) .setSessionAttributeValue(parts[1]) .build()); } clickConversionBuilder.setSessionAttributesKeyValuePairs(sessionAttributePairs.build()); } // Calls build to build the conversion. ClickConversion clickConversion = clickConversionBuilder.build();
C#
// Adds details of the conversion. clickConversion.ConversionAction = ResourceNames.ConversionAction(customerId, conversionActionId); clickConversion.ConversionDateTime = conversionDateTime; clickConversion.ConversionValue = conversionValue; clickConversion.CurrencyCode = "USD"; // Sets the order ID if provided. if (!string.IsNullOrEmpty(orderId)) { clickConversion.OrderId = orderId; } // Sets the Google click ID (gclid) if provided. if (!string.IsNullOrEmpty(gclid)) { clickConversion.Gclid = gclid; } // The session attribute fields are only available to allowlisted users. To // include these fields in conversion imports, upgrade to the Data Manager API. if (!string.IsNullOrEmpty(sessionAttributesEncoded)) { clickConversion.SessionAttributesEncoded = ByteString.CopyFrom(sessionAttributesEncoded, Encoding.Unicode); } else if (!string.IsNullOrEmpty(sessionAttributes)) { IEnumerable<SessionAttributeKeyValuePair> parsedSessionAttributes = sessionAttributes.Split(';').Select(pair => { string[] split = pair.Split('='); return new SessionAttributeKeyValuePair() { SessionAttributeKey = split[0], SessionAttributeValue = split[1] }; }); clickConversion.SessionAttributesKeyValuePairs = new SessionAttributesKeyValuePairs(); clickConversion.SessionAttributesKeyValuePairs.KeyValuePairs .AddRange(parsedSessionAttributes); }
PHP
// Adds details of the conversion. $clickConversion->setConversionAction( ResourceNames::forConversionAction($customerId, $rawRecord['conversionActionId']) ); $clickConversion->setConversionDateTime($rawRecord['conversionDateTime']); $clickConversion->setConversionValue($rawRecord['conversionValue']); $clickConversion->setCurrencyCode($rawRecord['currencyCode']); // Sets the order ID if provided. if (!empty($rawRecord['orderId'])) { $clickConversion->setOrderId($rawRecord['orderId']); } // Sets the Google click ID (gclid) if provided. if (!empty($rawRecord['gclid'])) { $clickConversion->setGclid($rawRecord['gclid']); } // Sets the ad user data consent if provided. if (!empty($rawRecord['adUserDataConsent'])) { // Specifies whether user consent was obtained for the data you are uploading. See // https://www.google.com/about/company/user-consent-policy for details. $clickConversion->setConsent( new Consent(['ad_user_data' => $rawRecord['adUserDataConsent']]) ); } // Set one of the sessionAttributesEncoded or // SessionAttributeKeyValuePair fields if either are provided. The session attribute // fields are only available to allowlisted users. To include these fields in conversion // imports, upgrade to the Data Manager API. if (!empty($sessionAttributesEncoded)) { $clickConversion->setSessionAttributesEncoded($sessionAttributesEncoded); } elseif (!empty($sessionAttributesDict)) { // Create a new container object to hold key-value pairs. $sessionAttributesKeyValuePairs = new SessionAttributesKeyValuePairs(); // Initialize an array to hold individual key-value pair messages. $keyValuePairs = []; // Append each key-value pair provided to the $keyValuePairs array foreach ($sessionAttributesDict as $key => $value) { $pair = new SessionAttributeKeyValuePair(); $pair->setSessionAttributeKey($key); $pair->setSessionAttributeValue($value); $keyValuePairs[] = $pair; } // Set the the full list of key-value pairs on the container object. $sessionAttributesKeyValuePairs->setKeyValuePairs($keyValuePairs); // Attach the container of key-value pairs to the ClickConversion object. $clickConversion->setSessionAttributesKeyValuePairs($sessionAttributesKeyValuePairs); }
Python
# Add details of the conversion. # Gets the conversion action resource name. conversion_action_service: ConversionActionServiceClient = ( client.get_service("ConversionActionService") ) click_conversion.conversion_action = ( conversion_action_service.conversion_action_path( customer_id, raw_record["conversion_action_id"] ) ) click_conversion.conversion_date_time = raw_record["conversion_date_time"] click_conversion.conversion_value = raw_record["conversion_value"] click_conversion.currency_code = raw_record["currency_code"] # Sets the order ID if provided. if raw_record.get("order_id"): click_conversion.order_id = raw_record["order_id"] # Sets the gclid if provided. if raw_record.get("gclid"): click_conversion.gclid = raw_record["gclid"] # Specifies whether user consent was obtained for the data you are # uploading. For more details, see: # https://www.google.com/about/company/user-consent-policy if raw_record["ad_user_data_consent"]: click_conversion.consent.ad_user_data = client.enums.ConsentStatusEnum[ raw_record["ad_user_data_consent"] ] # Set one of the session_attributes_encoded or # session_attributes_key_value_pairs fields if either are provided. # The session attribute fields are only available to allowlisted users. # To include these fields in conversion imports, upgrade to the Data Manager API. if session_attributes_encoded: click_conversion.session_attributes_encoded = session_attributes_encoded elif session_attributes_dict: for key, value in session_attributes_dict.items(): pair: SessionAttributeKeyValuePair = client.get_type( "SessionAttributeKeyValuePair" ) pair.session_attribute_key = key pair.session_attribute_value = value click_conversion.session_attributes_key_value_pairs.key_value_pairs.append( pair )
Ruby
cc.conversion_action = client.path.conversion_action(customer_id, conversion_action_id) cc.conversion_date_time = conversion_date_time cc.conversion_value = conversion_value.to_f cc.currency_code = 'USD' unless order_id.nil? cc.order_id = order_id end unless raw_record["gclid"].nil? cc.gclid = gclid end # Specifies whether user consent was obtained for the data you are # uploading. For more details, see: # https://www.google.com/about/company/user-consent-policy unless raw_record["ad_user_data_consent"].nil? cc.consent = client.resource.consent do |c| c.ad_user_data = ad_user_data_consent end end # Set one of the session_attributes_encoded or # session_attributes_key_value_pairs fields if either are provided. # The session attribute fields are only available to allowlisted users. # To include these fields in conversion imports, upgrade to the Data Manager API. if session_attributes_encoded != nil cc.class.module_eval { attr_accessor :session_attributes_encoded} cc.session_attributes_encoded = session_attributes_encoded elsif session_attributes_hash != nil # Add new attribute to click conversion object cc.class.module_eval { attr_accessor :session_attributes_key_value_pairs} cc.session_attributes_key_value_pairs = ::Google::Ads::GoogleAds::V19::Services::SessionAttributesKeyValuePairs.new # Loop thru inputted session_attributes_hash to populate session_attributes_key_value_pairs session_attributes_hash.each do |key, value| pair = ::Google::Ads::GoogleAds::V19::Services::SessionAttributeKeyValuePair.new pair.session_attribute_key = key pair.session_attribute_value = value cc.session_attributes_key_value_pairs.key_value_pairs << pair end end
Perl
# Add details of the conversion. $click_conversion->{conversionAction} = Google::Ads::GoogleAds::V25::Utils::ResourceNames::conversion_action( $customer_id, $raw_record->{conversionActionId}); $click_conversion->{conversionDateTime} = $raw_record->{conversionDateTime}; $click_conversion->{conversionValue} = $raw_record->{conversionValue}; $click_conversion->{currencyCode} = $raw_record->{currencyCode}; # Set the order ID if provided. if (defined $raw_record->{orderId}) { $click_conversion->{orderId} = $raw_record->{orderId}; } # Set the Google click ID (gclid) if provided. if (defined $raw_record->{gclid}) { $click_conversion->{gclid} = $raw_record->{gclid}; } # Set the consent information, if provided. if (defined $raw_record->{adUserDataConsent}) { $click_conversion->{consent} = Google::Ads::GoogleAds::V25::Common::Consent->new({ adUserData => $raw_record->{adUserDataConsent}}); } # Set one of the session_attributes_encoded or session_attributes_key_value_pairs # fields if either are provided. if (defined $session_attributes_encoded) { $click_conversion->{sessionAttributesEncoded} = $session_attributes_encoded; } elsif (defined $session_attributes_hash) { while (my ($key, $value) = each %$session_attributes_hash) { my $pair = Google::Ads::GoogleAds::V25::Services::ConversionUploadService::SessionAttributeKeyValuePair ->new({sessionAttributeKey => $key, sessionAttributeValue => $value}); push @{$click_conversion->{sessionAttributesKeyValuePairs}{keyValuePairs} }, $pair; } }
curl
Erstellen Sie die Anfrage
Nachdem Sie die ClickConversion-Objekte konfiguriert und dem Feld conversions des UploadClickConversionsRequest-Objekts hinzugefügt haben, legen Sie die folgenden Felder fest und übergeben Sie die Anfrage an die Methode UploadClickConversions für ConversionUploadService.
customer_id- Legen Sie hier den Google Ads-Conversion-Kunden des Kontos fest, aus dem die Klicks stammen. Wenn Sie sich nicht sicher sind, welches Konto das richtige ist, sehen Sie sich das Feld
customer.conversion_tracking_setting.google_ads_conversion_customerin der Beispielabfrage im Abschnitt Erste Schritte an. job_idBietet einen Mechanismus zum Zuordnen Ihrer Importanfragen zu den Informationen pro Job in der Diagnose von Offlinedaten.
Wenn Sie dieses Feld nicht festlegen, weist die Google Ads API jeder Anfrage einen eindeutigen Wert im Bereich von
[2^31, 2^63)zu. Wenn Sie mehrere Anfragen in einem einzigen logischen Job gruppieren möchten, legen Sie dieses Feld in jeder Anfrage in Ihrem Job auf denselben Wert im Bereich[0, 2^31)fest.Die
job_idin der Antwort enthält die Job-ID für die Anfrage, unabhängig davon, ob Sie einen Wert angegeben oder die Google Ads API einen Wert zugewiesen haben.partial_failureDieses Feld muss beim Importieren von Conversions auf
truefestgelegt werden. Folgen Sie bei der Verarbeitung der Antwort den Richtlinien für Teilfehler.
Anfrage importieren
Sobald Sie Ihre ClickConversion-Objekte mit Daten gefüllt und Ihre Anfrage erstellt haben, können Sie den Import senden.
Java
// Creates the conversion upload service client. try (ConversionUploadServiceClient conversionUploadServiceClient = googleAdsClient.getLatestVersion().createConversionUploadServiceClient()) { // Uploads the click conversion. Partial failure should always be set to true. // NOTE: This request contains a single conversion as a demonstration. However, if you have // multiple conversions to upload, it's best to upload multiple conversions per request // instead of sending a separate request per conversion. See the following for per-request // limits: // https://developers.google.com/google-ads/api/docs/best-practices/quotas#conversion_upload_service UploadClickConversionsResponse response = conversionUploadServiceClient.uploadClickConversions( UploadClickConversionsRequest.newBuilder() .setCustomerId(Long.toString(customerId)) .addConversions(clickConversion) // Enables partial failure (must be true). .setPartialFailure(true) .build());
C#
// Uploads the click conversion. Partial failure should always be set to true. // NOTE: This request contains a single conversion as a demonstration. // However, if you have multiple conversions to upload, it's best to upload multiple // conversions per request instead of sending a separate request per conversion. // See the following for per-request limits: // https://developers.google.com/google-ads/api/docs/best-practices/quotas#conversion_upload UploadClickConversionsResponse response = conversionUploadService.UploadClickConversions( new UploadClickConversionsRequest() { CustomerId = customerId.ToString(), Conversions = { clickConversion }, // Enables partial failure (must be true). PartialFailure = true });
PHP
// Issues a request to upload the click conversion. $conversionUploadServiceClient = $googleAdsClient->getConversionUploadServiceClient(); // NOTE: This request contains a single conversion as a demonstration. However, if you have // multiple conversions to upload, it's best to upload multiple conversions per request // instead of sending a separate request per conversion. See the following for per-request // limits: // https://developers.google.com/google-ads/api/docs/best-practices/quotas#conversion_upload_service $response = $conversionUploadServiceClient->uploadClickConversions( // Enables partial failure (must be true). UploadClickConversionsRequest::build($customerId, [$clickConversion], true) );
Python
# Creates the conversion upload service client. conversion_upload_service: ConversionUploadServiceClient = ( client.get_service("ConversionUploadService") ) # Uploads the click conversion. Partial failure should always be set to # True. # NOTE: This request only uploads a single conversion, but if you have # multiple conversions to upload, it's most efficient to upload them in a # single request. See the following for per-request limits for reference: # https://developers.google.com/google-ads/api/docs/best-practices/quotas#conversion_upload_service response: UploadClickConversionsResponse = ( conversion_upload_service.upload_click_conversions( customer_id=customer_id, conversions=[click_conversion], # Enables partial failure (must be true). partial_failure=True, ) )
Ruby
response = client.service.conversion_upload.upload_click_conversions( customer_id: customer_id, conversions: [click_conversion], # Partial failure must be true. partial_failure: true, ) if response.partial_failure_error puts "Partial failure encountered: #{response.partial_failure_error.message}" else result = response.results.first puts "Uploaded click conversion that happened at #{result.conversion_date_time} " \ "to #{result.conversion_action}." end
Perl
# Upload the click conversion. Partial failure should always be set to true. # # NOTE: This request contains a single conversion as a demonstration. # However, if you have multiple conversions to upload, it's best to # upload multiple conversions per request instead of sending a separate # request per conversion. See the following for per-request limits: # https://developers.google.com/google-ads/api/docs/best-practices/quotas#conversion_upload_service my $response = $api_client->ConversionUploadService()->upload_click_conversions({ customerId => $customer_id, conversions => [$click_conversion], # Enable partial failure (must be true). partialFailure => "true" });
curl
Importe überprüfen
Mithilfe des Diagnoseberichts zu erweiterten Conversions für Leads können Sie den allgemeinen Status Ihrer letzten Importe prüfen.
Importierte Conversions werden in Berichten für das Impressionsdatum des ursprünglichen Klicks und nicht für das Datum der Importanfrage oder das Datum des conversion_date_time der ClickConversion berücksichtigt.
Es kann bis zu drei Stunden dauern, bis Statistiken zu importierten Conversions in Ihrem Google Ads-Konto für das Attributionsmodell „Letzter Klick“ angezeigt werden. Bei anderen Attributionsmodellen für die Suche kann es länger als drei Stunden dauern. Weitere Informationen zur Datenaktualität
Wenn Sie Conversion-Messwerte für Ihre Kampagnen erfassen, finden Sie unter Messwerte der Benutzeroberfläche zuordnen Informationen dazu, wie Sie Messwerte der Google Ads-Benutzeroberfläche mit Berichtsfeldern der Google Ads API korrelieren. Sie können auch die Ressource conversion_action abfragen, um die Gesamtzahl der Conversions und den Gesamt-Conversion-Wert für eine bestimmte Conversion-Aktion zu sehen.
Best Practices
Beachten Sie die folgenden Best Practices, wenn Sie erweiterte Conversions für Leads implementieren.
Alle Conversion-Daten senden, unabhängig von der Vollständigkeit
Damit Sie vollständige und genaue Conversion-Berichte erhalten, sollten Sie alle verfügbaren Offline-Conversion-Ereignisse importieren – auch solche, die nicht aus Google Ads stammen. Conversions, die nur von Nutzern bereitgestellte Daten enthalten, sind weiterhin nützlich und können zur Optimierung von Google Ads-Kampagnen beitragen.
Wenn Sie einer Conversion ein order_id zuweisen, empfehlen wir, es einzubeziehen. Wenn Sie die GCLID für eine Conversion haben, empfehlen wir, sie zusätzlich zu user_identifiers zu senden, um die Leistung zu verbessern. Wenn Sie mehr als eine UserIdentifier für die Conversion haben, sollten Sie alle im ClickConversion-Objekt angeben, um die Wahrscheinlichkeit einer Übereinstimmung zu erhöhen.
Mehrere Conversions in einer einzigen Anfrage zusammenfassen
Wenn Sie mehrere Conversions importieren möchten, fassen Sie sie in einem UploadClickConversionsRequest zusammen, anstatt für jede Conversion eine Importanfrage zu senden.
Informationen zu den Limits für die Anzahl der Konvertierungen pro Anfrage finden Sie im Kontingentleitfaden.
Wenn Sie möchten, dass die Offlinedatendiagnose eine Reihe von Anfragen unter demselben logischen Job gruppiert, legen Sie für die job_id aller Anfragen denselben Wert fest. Das kann nützlich sein, wenn Sie einen einzelnen Job oder Prozess haben, der eine große Anzahl von Conversions über mehrere Anfragen importiert. Wenn Sie für jede dieser Anfragen denselben Wert für job_id festlegen, können Sie einen einzelnen Eintrag für den Job aus job_summaries abrufen.
Wenn Sie stattdessen zulassen, dass die Google Ads API der job_id jeder Anfrage einen vom System generierten Wert zuweist, enthält die job_summaries für jede Anfrage einen separaten Eintrag. Das kann die Analyse des Gesamtzustands Ihres Jobs erschweren.
Keine externen Attributionsdaten verwenden
Wenn Sie erweiterte Conversions für Leads verwenden, legen Sie für ClickConversion nicht external_attribution_data fest und geben Sie keine conversion_action an, die ein externes Attributionsmodell verwendet. Google Ads unterstützt keine extern zugeordneten Conversions für Importe mit von Nutzern bereitgestellten Daten.
Benutzerdefinierte Variablen nicht einbeziehen
Wenn Sie erweiterte Conversions für Leads verwenden, dürfen Sie keine custom_variables einfügen. Google Ads unterstützt die Verwendung benutzerdefinierter Variablen mit von Nutzern bereitgestellten Daten in Conversion-Importen nicht. Wenn benutzerdefinierte Variablen in Conversions enthalten sind, die von Nutzern bereitgestellte Daten enthalten, werden diese Conversions als ungültig betrachtet und verworfen.
Fehlerbehebung
Die Offlinedaten-Diagnose bietet eine zentrale Ressource, mit der Sie die Gesamtqualität Ihrer Importe kontinuierlich überprüfen können. Während der Implementierung können Sie jedoch die Informationen in diesem Abschnitt verwenden, um alle Fehler zu untersuchen, die im Feld partial_failure_error der Antwort gemeldet werden.
Zu den häufigsten Fehlern beim Importieren von Conversion-Aktionen gehören Autorisierungsfehler wie USER_PERMISSION_DENIED. Prüfen Sie, ob die Kundennummer in Ihrer Anfrage auf den Google Ads-Anzeigen-Conversion-Kunden festgelegt ist, der Inhaber der Conversion-Aktion ist. Weitere Informationen finden Sie in unserem Autorisierungsleitfaden. Tipps zur Fehlerbehebung bei diesen verschiedenen Fehlern finden Sie in unserem Leitfaden zu häufigen Fehlern.
Häufige Fehler beheben
Die folgenden Informationen helfen Ihnen, häufige Fehler bei erweiterten Conversions für Leads zu diagnostizieren und zu beheben.
| Fehler | |
|---|---|
NO_CONVERSION_ACTION_FOUND
|
Die angegebene Conversion-Aktion ist entweder nicht aktiviert oder kann nicht über das Kundenkonto aufgerufen werden, das im Feld Dieser Fehler kann auch auftreten, wenn der GCLID-Wert in der Anfrage zu einem Kundenkonto gehört, das keinen Zugriff auf die in der Anfrage angegebene Conversion-Aktion hat. Sie können mit der Ressource |
INVALID_CONVERSION_ACTION_TYPE
|
Die angegebene Conversion-Aktion hat einen Typ, der für erweiterte Conversions für Leads nicht gültig ist. Der in Ihrer Uploadanfrage angegebene ConversionAction muss vom Typ UPLOAD_CLICKS sein.
|
CUSTOMER_NOT_ENABLED_ENHANCED_CONVERSIONS_FOR_LEADS
|
Achten Sie darauf, dass Sie in den Conversion-Einstellungen erweiterte Conversions für Leads aktiviert haben. Eine Anleitung dazu finden Sie im Leitfaden zu den Voraussetzungen. |
DUPLICATE_ORDER_ID
|
Die importierten Ereignisse umfassen mehrere Conversions mit derselben Bestell-ID und wurden nicht verarbeitet. Vergewissern Sie sich, dass die Bestell-IDs eindeutig sind, und versuchen Sie es noch einmal. |
CLICK_NOT_FOUND
|
Es wurde kein Klick gefunden, der mit den angegebenen Nutzer-IDs übereinstimmt.
Wenn bei einer Conversion diese Warnung auftritt, wird sie in der Google Ads API in die Dieser Fehler wird erwartet, wenn der Klick nicht aus einer Google Ads-Kampagne stammt. Sie können beispielsweise aus SA360 oder DV360 stammen. Weitere mögliche Ursachen:
In seltenen Fällen, in denen sich der hochladende Kunde vom Google Ads-Conversion-Kunden unterscheidet, kann dieser Fehler bedeuten, dass der hochladende Kunde die Nutzungsbedingungen für Kundendaten akzeptiert hat, der bereitstellende Kunde jedoch nicht. Sie können feststellen, ob ein Konto die Nutzungsbedingungen für Kundendaten akzeptiert hat, indem Sie die Ressourcecustomer abfragen und das Feld customer.conversion_tracking_setting.accepted_customer_data_terms prüfen.
|