Você pode usar a API Google Ads para importar conversões off-line para o Google Ads e acompanhar os anúncios que geraram vendas no mundo off-line, como por telefone ou por um representante de vendas.
Para aproveitar ao máximo os benefícios da importação de dados de conversão, recomendamos implementar as conversões otimizadas para leads, que usam GCLIDs e dados fornecidos pelo usuário para maximizar a durabilidade e a performance.
Conversões otimizadas
As conversões otimizadas ajudam a melhorar a precisão da medição de conversões, complementando-as com dados próprios, como e-mail, nome, endereço residencial e número de telefone.
Há dois tipos de conversões otimizadas. Para mais detalhes, consulte o artigo da Central de Ajuda Sobre as conversões otimizadas.
A seção a seguir explica como otimizar as conversões off-line, um recurso também chamado de conversões otimizadas para leads.
O que são as conversões otimizadas para leads?
As conversões otimizadas para leads são uma versão atualizada da importação de conversões off-line que usa dados fornecidos pelo usuário, como endereços de e-mail, para complementar os dados de conversão off-line importados e melhorar a precisão e a performance dos lances. Quando você importa suas conversões off-line, os dados com hash fornecidos dos clientes são usados para atribuir as conversões de volta à campanha do Google Ads, fazendo a correspondência com os mesmos dados coletados no seu site, como um formulário de lead, e com os clientes conectados que interagiram com seu anúncio. Para mais informações sobre como as conversões otimizadas para leads funcionam, leia nosso artigo Sobre as conversões otimizadas para leads.
Há duas maneiras de implementar as conversões otimizadas para leads, dependendo de se você usa a tag do Google para acompanhar os eventos de envio de formulários na sua página da Web. Para ter a melhor performance e durabilidade, recomendamos usar a tag do Google para conversões otimizadas para leads.
- Se você está começando do zero, comece pela seção Pré-requisitos.
- Se você já tiver as importações de conversões off-line configuradas e quiser fazer upgrade para as conversões otimizadas para leads, recomendamos começar pela seção Configurar a inclusão de tags.
- Se você já tiver configurado a tag do Google ou não pretende usá-la e estiver começando a trabalhar na integração da API Google Ads, pule para a seção Implementação da API.
- Se não for possível importar dados fornecidos pelo usuário ou se você depender da atribuição externa para suas conversões, consulte o guia de importação de conversões off-line legados.
Pré-requisitos
Primeiro, verifique se você concluiu as etapas na seção de início.
Você precisa ativar as conversões otimizadas para leads e aceitar os termos de dados do cliente antes de usar esse recurso. É possível verificar se esses pré-requisitos já foram atendidos emitindo a consulta a seguir para o cliente de conversão do Google Ads:
SELECT
customer.id,
customer.conversion_tracking_setting.accepted_customer_data_terms,
customer.conversion_tracking_setting.enhanced_conversions_for_leads_enabled
FROM customer
Se um dos campos accepted_customer_data_terms
ou
enhanced_conversions_for_leads_enabled
estiver false
, siga as instruções na
Central de Ajuda para
concluir esses pré-requisitos.
Configurar a inclusão de tags
Configure a tag do Google para ativar as conversões otimizadas para leads seguindo as instruções no Centro de ajuda. Para configurar conversões otimizadas para leads com o Gerenciador de tags do Google, siga estas instruções.
Implementação da API
Confira o fluxo geral para importar conversões otimizadas para leads usando a API Google Ads.
Normalizar e gerar hash dos dados fornecidos pelo usuário, como endereço de e-mail, número de telefone e endereço postal.
Preencha objetos
ClickConversion
com os dados fornecidos pelo usuário normalizados e com hash.Importe objetos
ClickConversion
para a API Google Ads usando oConversionUploadService
.
Normalizar e gerar hash de dados fornecidos pelo usuário
Por questões de privacidade, os seguintes dados precisam ser criptografados com hash usando SHA-256 antes de serem importados:
- Endereço de e-mail
- Número de telefone
- Nome
- Sobrenome
- Endereço
Para padronizar os resultados do hash, antes de gerar hash a esses valores, você precisa fazer o seguinte:
- Remova os espaços em branco à esquerda e à direita.
- Converter o texto em letras minúsculas.
- Formate números de telefone de acordo com o padrão E.164.
- Remova todos os pontos (
.
) que antecedem o nome de domínio nos endereços de e-mailgmail.com
egooglemail.com
.
Não gere hash dos seguintes dados:
- País
- Estado
- Cidade
- CEP
Exemplo de código
Este exemplo mostra como normalizar e gerar hash dos dados fornecidos pelo usuário.
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 preceding {@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 { String normalizedEmail = emailAddress.toLowerCase(); String[] emailParts = normalizedEmail.split("@"); if (emailParts.length > 1 && emailParts[1].matches("^(gmail|googlemail)\\.com\\s*")) { // 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("\\.", ""); normalizedEmail = String.format("%s@%s", emailParts[0], emailParts[1]); } return normalizeAndHash(digest, normalizedEmail); }
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 preceding "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 { $normalizedEmail = strtolower($emailAddress); $emailParts = explode("@", $normalizedEmail); if ( count($emailParts) > 1 && preg_match('/^(gmail|googlemail)\.com\s*/', $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]); $normalizedEmail = sprintf('%s@%s', $emailParts[0], $emailParts[1]); } return self::normalizeAndHash($hashAlgorithm, $normalizedEmail); }
Python
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" Args: email_address: An email address to normalize. Returns: A normalized (lowercase, removed whitespace) and SHA-265 hashed string. """ normalized_email = email_address.strip().lower() email_parts = normalized_email.split("@") # Check that there are at least two segments if len(email_parts) > 1: # Checks whether the domain of the email address is either "gmail.com" # or "googlemail.com". If this regex does not match then this statement # will evaluate to None. if re.match(r"^(gmail|googlemail)\.com$", email_parts[1]): # Removes any '.' characters from the portion of the email address # before the domain if the domain is gmail.com or googlemail.com. email_parts[0] = email_parts[0].replace(".", "") normalized_email = "@".join(email_parts) return normalize_and_hash(normalized_email) def normalize_and_hash(s): """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); }
Preencher objetos ClickConversion
A coleção de objetos ClickConversion
no UploadClickConversionRequest
representa o conjunto de conversões que você quer importar. Considere os seguintes detalhes ao criar objetos
ClickConversion
:
gclid
Os GCLIDs são identificadores de clique capturados nos parâmetros de URL quando alguém clica no seu anúncio e navega até o site.
user_identifiers
Ao usar as conversões otimizadas para leads, é necessário preencher o campo
user_identifiers
com dados fornecidos pelo usuário normalizados e com hash. Se você tiver vários identificadores de usuário disponíveis, crie umUserIdentifier
separado para cada um deles, até cinco identificadores.conversion_date_time
A data e a hora da conversão.
O valor precisa ter um fuso horário especificado, e o formato precisa ser
yyyy-mm-dd HH:mm:ss+|-HH:mm
, por exemplo:2022-01-01 19:32:45-05:00
(ignorando o horário de verão) .O fuso horário pode ser qualquer valor válido: ele não precisa corresponder ao fuso horário da conta. No entanto, se você planeja comparar os dados de conversão importados com os da interface do Google Ads, recomendamos usar o mesmo fuso horário da sua conta do Google Ads para que as contagens de conversão sejam correspondentes. Confira mais detalhes e exemplos na Central de Ajuda e consulte a página "Códigos e formatos" para ver uma lista de IDs de fuso horário válidos.
conversion_action
O nome do recurso do
ConversionAction
para a conversão off-line.A ação de conversão precisa ter um
type
deUPLOAD_CLICKS
e existir no cliente de conversão do Google Ads da conta do Google Ads associada ao clique.conversion_value
É o valor da conversão.
currency_code
O código da moeda do
conversion_value
.consent
É altamente recomendável preencher o campo
consent
do objetoClickConversion
. Se não estiver definido, talvez suas conversões não sejam atribuídas.order_id
Também conhecido como ID da transação da conversão. Esse campo é opcional, mas altamente recomendado, porque facilita a referência a conversões importadas ao fazer ajustes. Se você definir o valor durante a importação, ele será usado para todos os ajustes. Para saber como usar um ID da transação para minimizar as conversões duplicadas, consulte este artigo da Central de Ajuda.
custom_variables
Os valores das variáveis personalizadas de conversão.
O Google Ads não aceita variáveis personalizadas de conversão em combinação com
wbraid
ougbraid
.conversion_environment
Indica o ambiente em que essa conversão foi registrada. Por exemplo,
APP
ouWEB
.session_attributes_encoded
esession_attributes_key_value_pairs
Os atributos de sessão representam identificadores agregados usados para atribuição de conversão. Eles funcionam em conjunto com identificadores de clique (como GCLIDs e GBRAIDs) e dados fornecidos pelo usuário, que são essenciais para as conversões otimizadas para leads. Há duas maneiras de importar atributos de sessão: fornecendo o token codificado gerado pelo nosso código JavaScript no navegador ou fornecendo pares de chave-valor individuais para cada um dos identificadores.
Para maximizar a performance da campanha, recomendamos importar identificadores de clique, dados fornecidos pelo usuário e atributos de sessão com todas as conversões, se possível.
Java
This example is not yet available in Java; you can take a look at the other languages.
C#
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. 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 = 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
This example is not yet available in Ruby; you can take a look at the other languages.
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::V19::Services::ConversionUploadService::SessionAttributeKeyValuePair ->new({sessionAttributeKey => $key, sessionAttributeValue => $value}); push @{$click_conversion->{sessionAttributesKeyValuePairs}{keyValuePairs} }, $pair; } }
Exemplo de código
Este exemplo mostra como definir os dados normalizados e com hash fornecidos pelo usuário em
um objeto ClickConversion
.
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@example.com") // Phone number to be converted to E.164 format, with a leading '+' as required. .put("phone", "+1 800 5550102") // 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(normalizeAndHash(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 (.) 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' => $orderId, 'gclid' => $gclid, 'conversionActionId' => $conversionActionId, 'conversionDateTime' => $conversionDateTime, 'conversionValue' => $conversionValue, 'currencyCode' => 'USD', 'adUserDataConsent' => $adUserDataConsent ]; // 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::normalizeAndHash( $hashAlgorithm, $rawRecord['phone'], true ) ]); // Adds the hashed email 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 = { # 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 = 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 = 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 = 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. 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::V19::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::V19::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::V19::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::V19::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;
Este exemplo mostra como definir outros campos necessários em um objeto ClickConversion
.
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. 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; } 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']]) ); }
Python
# Add details of the conversion. # Gets the conversion action resource name. conversion_action_service = 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. 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 = 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. 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::V19::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::V19::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::V19::Services::ConversionUploadService::SessionAttributeKeyValuePair ->new({sessionAttributeKey => $key, sessionAttributeValue => $value}); push @{$click_conversion->{sessionAttributesKeyValuePairs}{keyValuePairs} }, $pair; } }
Crie a solicitação
Depois que os objetos ClickConversion
forem configurados e adicionados ao campo conversions
do objeto UploadClickConversionRequest
, defina os campos a seguir e transmita a solicitação para o método UploadClickConversions
no ConversionUploadService
.
customer_id
- Defina esse valor como o cliente de conversão do Google Ads da conta que é a origem dos cliques. Se você não tiver certeza de qual conta é a correta, consulte
o campo
customer.conversion_tracking_setting.google_ads_conversion_customer
na consulta de exemplo na seção Primeiros passos . job_id
Fornece um mecanismo para associar suas solicitações de importação às informações por job no diagnóstico de dados off-line.
Se você não definir esse campo, a API do Google Ads vai atribuir a cada solicitação um valor exclusivo no intervalo de
[2^31, 2^63)
. Se você preferir agrupar várias solicitações em um único job lógico, defina esse campo com o mesmo valor no intervalo[0, 2^31)
em cada solicitação do job.O
job_id
na resposta contém o ID do job para a solicitação, independentemente de você ter especificado um valor ou deixado a API Google Ads atribuir um valor.partial_failure
Esse campo precisa ser definido como
true
ao importar conversões. Siga as diretrizes de falhas parciais ao processar a resposta.
Importar a solicitação
Depois de preencher os objetos ClickConversion
e criar a
solicitação, você pode enviar a importação.
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 = 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 = 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" });
Analisar as importações
Use o Relatório de diagnóstico de conversões otimizadas para leads para analisar a integridade geral das suas importações recentes.
As conversões importadas são refletidas nos relatórios da data da impressão do clique original, não da solicitação de importação ou da data do conversion_date_time
do ClickConversion
.
As estatísticas das conversões importadas levam até três horas para aparecer na sua conta do Google Ads para atribuição do último clique. Para outros modelos de atribuição de pesquisa, pode levar mais de três horas. Consulte o guia de atualização de dados para mais informações.
Ao gerar relatórios sobre as métricas de conversão das suas campanhas, consulte Como mapear métricas da interface do usuário para correlacionar as métricas da interface do Google Ads com os campos de relatórios da API Google Ads. Também é possível consultar o recurso conversion_action
para conferir o número total de conversões e o valor total de conversão de uma determinada ação de conversão.
Práticas recomendadas
Considere as práticas recomendadas a seguir ao implementar conversões otimizadas para leads.
Enviar todos os dados de conversão, independentemente do nível de preenchimento
Para garantir que os relatórios de conversão sejam completos e precisos, importe todos os eventos de conversão off-line disponíveis, incluindo aqueles que não vieram do Google Ads. As conversões que incluem apenas dados fornecidos pelo usuário ainda são úteis e podem contribuir positivamente para a otimização da campanha do Google Ads.
Se você atribuir uma order_id
a uma conversão, recomendamos que a inclua.
Se você tiver o GCLID de uma conversão, recomendamos enviá-lo junto com o user_identifiers
para melhorar a performance. Além disso, se você tiver mais de um UserIdentifier
para a conversão, inclua todos eles no objeto ClickConversion
para aumentar a probabilidade de correspondência.
Agrupar várias conversões em uma única solicitação
Se você tiver várias conversões para importar, faça um lote delas em um
UploadClickConversionsRequest
,
em vez de enviar uma solicitação de importação por conversão.
Consulte o guia de cotas para conferir os limites do número de conversões por solicitação.
Se você quiser que o diagnóstico de dados off-line agrupe um conjunto de solicitações no mesmo job lógico, defina o job_id
de todas as solicitações como o mesmo valor. Isso pode ser útil se você tiver um único job ou
processo que importe um grande número de conversões usando várias solicitações. Se
você definir o job_id
em cada uma dessas solicitações com o mesmo valor, poderá
extrair uma única entrada para o job em
job_summaries
.
Se você permitir que a API Google Ads atribua um valor gerado pelo sistema ao job_id
de cada solicitação, o job_summaries
vai conter uma entrada separada para cada solicitação, o que pode tornar a análise da integridade geral do seu job mais difícil.
Não use dados de atribuição externa
Ao usar as conversões otimizadas para leads, não defina external_attribution_data
no ClickConversion
nem especifique um conversion_action
que use um modelo de atribuição
externo. O Google Ads não oferece suporte a conversões atribuídas externamente para
importações que usam dados fornecidos pelo usuário.
Solução de problemas
O diagnóstico de dados off-line oferece um único recurso para analisar a integridade geral das suas importações de forma contínua. No entanto, durante a implementação, você pode usar as informações desta
seção para investigar os erros informados no campo
partial_failure_error
da resposta.
Alguns dos erros mais comuns ao importar ações de conversão são
erros de autorização, como USER_PERMISSION_DENIED
. Verifique se o ID do cliente na sua solicitação está definido como o cliente de conversão do Google Ads que é proprietário da ação de conversão. Acesse nosso
guia de autorização para mais detalhes e consulte nosso
guia de erros comuns para dicas sobre como
depurar esses diferentes erros.
Depurar erros comuns
Erro | |
---|---|
NO_CONVERSION_ACTION_FOUND
|
A ação de conversão especificada não está ativada ou não pode ser acessada pela conta de cliente especificada pelo campo "client_id" na solicitação. Verifique se a ação de conversão no seu upload está ativada e é de propriedade do cliente que enviou a solicitação de upload. Esse erro também pode ocorrer se o GCLID na solicitação pertencer a uma conta de cliente que não
tenha acesso à ação de conversão especificada na solicitação. É possível verificar se um GCLID pertence a uma conta de cliente usando o recurso |
INVALID_CONVERSION_ACTION_TYPE
|
A ação de conversão especificada tem um tipo que não é válido para conversões otimizadas para leads. Verifique se o ConversionAction especificado na
solicitação de upload tem o tipo UPLOAD_CLICKS .
|
CUSTOMER_NOT_ENABLED_ENHANCED_CONVERSIONS_FOR_LEADS
|
Verifique se você ativou as conversões otimizadas para leads nas configurações de conversão. Encontre instruções para isso no guia de pré-requisitos. |
DUPLICATE_ORDER_ID
|
Os eventos importados incluem várias conversões com o mesmo código de pedido e não foram processados. Verifique se os códigos dos pedidos são únicos e tente de novo. |
CLICK_NOT_FOUND
|
Nenhum clique foi encontrado que correspondesse aos identificadores de usuário fornecidos. A API Google Ads
só vai retornar esse erro se debug_enabled for true no
UploadClickConversionsRequest .
Se uma conversão encontrar esse aviso, a API Google Ads vai incluí-lo no Esse erro é esperado se o clique não for de uma campanha do Google Ads. Por exemplo, pode ser do SA360 ou do DV360. Outras causas possíveis são as seguintes:
Em casos raros, quando o cliente que faz o upload é diferente do cliente de conversão do Google Ads, esse erro pode significar que o cliente que faz o upload aceitou os termos de dados do cliente, mas o cliente de veiculação não. Para determinar se uma conta aceitou os termos de dados do cliente, consulte o recursocustomer e verifique o
customer.offline_conversion_tracking_info.accepted_customer_data_terms .
|