您可以使用 Google Ads API 將離線點擊轉換上傳至 Google Ads,以便追蹤在實體通路促成銷售的廣告,例如透過電話或業務代表銷售。
設定
設定離線轉換時,必須先完成一些必要條件。請先確認已滿足所有先決條件,再繼續進行導入作業:
在 Google Ads 轉換客戶中啟用轉換追蹤。
設定標記和儲存點擊 ID。
1. 在 Google Ads 轉換客戶中啟用轉換追蹤
如果您已完成轉換入門指南,並已啟用轉換追蹤,請直接跳到步驟二:設定代碼。
擷取轉換追蹤設定的相關資訊
您可以查詢 ConversionTrackingSetting
的 Customer
資源,檢查帳戶的轉換追蹤設定,並確認已啟用轉換追蹤。使用 GoogleAdsService.SearchStream
發出下列查詢:
SELECT
customer.conversion_tracking_setting.google_ads_conversion_customer,
customer.conversion_tracking_setting.conversion_tracking_status,
customer.conversion_tracking_setting.conversion_tracking_id,
customer.conversion_tracking_setting.cross_account_conversion_tracking_id
FROM customer
google_ads_conversion_customer
欄位會指出為這位客戶建立及管理轉換的 Google Ads 帳戶。如果客戶使用跨帳戶轉換追蹤,則這是管理員帳戶的 ID。如要建立及管理轉換,Google Ads 轉換客戶 ID 應設為 Google Ads API 要求中的 customer_id
。請注意,即使未啟用轉換追蹤,這個欄位也會填入資料。
conversion_tracking_status
欄位會指出轉換追蹤是否已啟用,以及帳戶是否使用跨帳戶轉換追蹤。
在 Google Ads 轉換顧客下方建立轉換動作
如果 conversion_tracking_status
值為 NOT_CONVERSION_TRACKED
,表示帳戶未啟用轉換追蹤。在 Google Ads 轉換帳戶中建立至少一個 ConversionAction
,即可啟用轉換追蹤功能,如以下範例所示。或者,您也可以按照說明中心中所列的操作說明,在 UI 中建立轉換動作,並啟用所需的轉換類型。
請注意,透過 Google Ads API 傳送時,系統會自動啟用強化轉換,但您可以透過 Google Ads UI 停用這項功能。
程式碼範例
Java
private void runExample(GoogleAdsClient googleAdsClient, long customerId) { // Creates a ConversionAction. ConversionAction conversionAction = ConversionAction.newBuilder() // Note that conversion action names must be unique. If a conversion action already // exists with the specified conversion_action_name the create operation will fail with // a ConversionActionError.DUPLICATE_NAME error. .setName("Earth to Mars Cruises Conversion #" + getPrintableDateTime()) .setCategory(ConversionActionCategory.DEFAULT) .setType(ConversionActionType.WEBPAGE) .setStatus(ConversionActionStatus.ENABLED) .setViewThroughLookbackWindowDays(15L) .setValueSettings( ValueSettings.newBuilder() .setDefaultValue(23.41) .setAlwaysUseDefaultValue(true) .build()) .build(); // Creates the operation. ConversionActionOperation operation = ConversionActionOperation.newBuilder().setCreate(conversionAction).build(); try (ConversionActionServiceClient conversionActionServiceClient = googleAdsClient.getLatestVersion().createConversionActionServiceClient()) { MutateConversionActionsResponse response = conversionActionServiceClient.mutateConversionActions( Long.toString(customerId), Collections.singletonList(operation)); System.out.printf("Added %d conversion actions:%n", response.getResultsCount()); for (MutateConversionActionResult result : response.getResultsList()) { System.out.printf( "New conversion action added with resource name: '%s'%n", result.getResourceName()); } } }
C#
public void Run(GoogleAdsClient client, long customerId) { // Get the ConversionActionService. ConversionActionServiceClient conversionActionService = client.GetService(Services.V18.ConversionActionService); // Note that conversion action names must be unique. // If a conversion action already exists with the specified name the create operation // will fail with a ConversionAction.DUPLICATE_NAME error. string ConversionActionName = "Earth to Mars Cruises Conversion #" + ExampleUtilities.GetRandomString(); // Add a conversion action. ConversionAction conversionAction = new ConversionAction() { Name = ConversionActionName, Category = ConversionActionCategory.Default, Type = ConversionActionType.Webpage, Status = ConversionActionStatus.Enabled, ViewThroughLookbackWindowDays = 15, ValueSettings = new ConversionAction.Types.ValueSettings() { DefaultValue = 23.41, AlwaysUseDefaultValue = true } }; // Create the operation. ConversionActionOperation operation = new ConversionActionOperation() { Create = conversionAction }; try { // Create the conversion action. MutateConversionActionsResponse response = conversionActionService.MutateConversionActions(customerId.ToString(), new ConversionActionOperation[] { operation }); // Display the results. foreach (MutateConversionActionResult newConversionAction in response.Results) { Console.WriteLine($"New conversion action with resource name = " + $"'{newConversionAction.ResourceName}' was added."); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
PHP
public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId) { // Creates a conversion action. $conversionAction = new ConversionAction([ // Note that conversion action names must be unique. // If a conversion action already exists with the specified conversion_action_name // the create operation will fail with a ConversionActionError.DUPLICATE_NAME error. 'name' => 'Earth to Mars Cruises Conversion #' . Helper::getPrintableDatetime(), 'category' => ConversionActionCategory::PBDEFAULT, 'type' => ConversionActionType::WEBPAGE, 'status' => ConversionActionStatus::ENABLED, 'view_through_lookback_window_days' => 15, 'value_settings' => new ValueSettings([ 'default_value' => 23.41, 'always_use_default_value' => true ]) ]); // Creates a conversion action operation. $conversionActionOperation = new ConversionActionOperation(); $conversionActionOperation->setCreate($conversionAction); // Issues a mutate request to add the conversion action. $conversionActionServiceClient = $googleAdsClient->getConversionActionServiceClient(); $response = $conversionActionServiceClient->mutateConversionActions( MutateConversionActionsRequest::build($customerId, [$conversionActionOperation]) ); printf("Added %d conversion actions:%s", $response->getResults()->count(), PHP_EOL); foreach ($response->getResults() as $addedConversionAction) { /** @var ConversionAction $addedConversionAction */ printf( "New conversion action added with resource name: '%s'%s", $addedConversionAction->getResourceName(), PHP_EOL ); } }
Python
def main(client, customer_id): conversion_action_service = client.get_service("ConversionActionService") # Create the operation. conversion_action_operation = client.get_type("ConversionActionOperation") # Create conversion action. conversion_action = conversion_action_operation.create # Note that conversion action names must be unique. If a conversion action # already exists with the specified conversion_action_name, the create # operation will fail with a ConversionActionError.DUPLICATE_NAME error. conversion_action.name = f"Earth to Mars Cruises Conversion {uuid.uuid4()}" conversion_action.type_ = ( client.enums.ConversionActionTypeEnum.UPLOAD_CLICKS ) conversion_action.category = ( client.enums.ConversionActionCategoryEnum.DEFAULT ) conversion_action.status = client.enums.ConversionActionStatusEnum.ENABLED conversion_action.view_through_lookback_window_days = 15 # Create a value settings object. value_settings = conversion_action.value_settings value_settings.default_value = 15.0 value_settings.always_use_default_value = True # Add the conversion action. conversion_action_response = ( conversion_action_service.mutate_conversion_actions( customer_id=customer_id, operations=[conversion_action_operation], ) ) print( "Created conversion action " f'"{conversion_action_response.results[0].resource_name}".' )
小茹
def add_conversion_action(customer_id) # GoogleAdsClient will read a config file from # ENV['HOME']/google_ads_config.rb when called without parameters client = Google::Ads::GoogleAds::GoogleAdsClient.new # Add a conversion action. conversion_action = client.resource.conversion_action do |ca| ca.name = "Earth to Mars Cruises Conversion #{(Time.new.to_f * 100).to_i}" ca.type = :UPLOAD_CLICKS ca.category = :DEFAULT ca.status = :ENABLED ca.view_through_lookback_window_days = 15 # Create a value settings object. ca.value_settings = client.resource.value_settings do |vs| vs.default_value = 15 vs.always_use_default_value = true end end # Create the operation. conversion_action_operation = client.operation.create_resource.conversion_action(conversion_action) # Add the ad group ad. response = client.service.conversion_action.mutate_conversion_actions( customer_id: customer_id, operations: [conversion_action_operation], ) puts "New conversion action with resource name = #{response.results.first.resource_name}." end
Perl
sub add_conversion_action { my ($api_client, $customer_id) = @_; # Note that conversion action names must be unique. # If a conversion action already exists with the specified conversion_action_name, # the create operation fails with error ConversionActionError.DUPLICATE_NAME. my $conversion_action_name = "Earth to Mars Cruises Conversion #" . uniqid(); # Create a conversion action. my $conversion_action = Google::Ads::GoogleAds::V18::Resources::ConversionAction->new({ name => $conversion_action_name, category => DEFAULT, type => WEBPAGE, status => ENABLED, viewThroughLookbackWindowDays => 15, valueSettings => Google::Ads::GoogleAds::V18::Resources::ValueSettings->new({ defaultValue => 23.41, alwaysUseDefaultValue => "true" })}); # Create a conversion action operation. my $conversion_action_operation = Google::Ads::GoogleAds::V18::Services::ConversionActionService::ConversionActionOperation ->new({create => $conversion_action}); # Add the conversion action. my $conversion_actions_response = $api_client->ConversionActionService()->mutate({ customerId => $customer_id, operations => [$conversion_action_operation]}); printf "New conversion action added with resource name: '%s'.\n", $conversion_actions_response->{results}[0]{resourceName}; return 1; }
確認 conversion_action_type
已設為正確的 ConversionActionType
值。如要進一步瞭解如何在 Google Ads API 中建立轉換動作,請參閱「建立轉換動作」一文。
擷取現有的轉換動作
您可以發出下列查詢,擷取現有轉換動作的詳細資料。請確認要求中的客戶 ID 已設為您在上述步驟中指定的 Google Ads 轉換客戶,且轉換動作類型已設為正確的 ConversionActionType
值。
SELECT
conversion_action.resource_name,
conversion_action.name,
conversion_action.status
FROM conversion_action
WHERE conversion_action.type = 'INSERT_CONVERSION_ACTION_TYPE'
2. 設定代碼和儲存點擊 ID
請按照操作說明確認已啟用自動標記,並設定 Google Ads 帳戶、網站和待開發客戶追蹤系統,以便擷取及儲存廣告的每個曝光和點擊的 GCLID、GBRAID 或 WBRAID。新帳戶預設會啟用自動標記。
建構要求
請按照以下指示建構 UploadClickConversionsRequest
,並將其欄位設為適當的值。
customer_id
指出上傳檔案的 Google Ads 帳戶。將這個值設為點擊來源帳戶的 Google Ads 轉換客戶。
job_id
提供機制,可將上傳要求與離線資料診斷中的個別工作資訊建立關聯。
如果您未設定這個欄位,Google Ads API 會為每個要求指派
[2^31, 2^63)
範圍內的專屬值。如果您想將多個要求合併為單一邏輯工作,請將此欄位設為工作中每個要求的[0, 2^31)
範圍內相同的值。無論您是否指定值或讓 Google Ads API 指派值,回應中的
job_id
都會包含要求的工作 ID。partial_failure_enabled
決定 Google Ads API 如何處理作業錯誤。
這個欄位必須設為
true
。處理回應時,請遵循部分失敗規範。debug_enabled
決定待開發客戶強化轉換上傳作業的錯誤回報行為。使用
gclid
、gbraid
或wbraid
處理點擊轉換上傳作業時,Google Ads API 會忽略這個欄位。
建立點擊轉換作業
UploadClickConversionRequest
中的 ClickConversion
物件集合會定義您要上傳的轉換組合。請按照下列指示建構每個 ClickConversion
,並將其欄位設為適當的值。
設定每個轉換作業的必填欄位
請按照下列說明,將 ClickConversion
的必填欄位設為適當的值。
gclid
、gbraid
、wbraid
- 您在點擊或曝光時擷取的轉換點擊 ID。請只設定一個這些欄位。
conversion_date_time
轉換的日期和時間。
這個值必須指定時區,且格式必須為
yyyy-mm-dd HH:mm:ss+|-HH:mm
,例如:2022-01-01 19:32:45-05:00
(忽略夏令時間)。時區可以是任何有效值,不必與帳戶時區相符。不過,如果您打算將上傳的轉換資料與 Google Ads 使用者介面中的資料進行比較,建議您使用與 Google Ads 帳戶相同的時區,以便轉換次數相符。如需詳細資訊和範例,請前往說明中心,並查看代碼和格式,瞭解有效時區 ID 的清單。
user_identifiers
上傳僅使用點擊 ID 的轉換時,請勿設定這個欄位。如果設定這個欄位,Google Ads 會將上傳作業視為待開發客戶強化轉換的上傳作業。
conversion_action
點擊轉換的
ConversionAction
資源名稱。轉換動作的
type
必須為UPLOAD_CLICKS
,且必須存在於與點擊相關聯的 Google Ads 帳戶的 Google Ads 轉換客戶中。conversion_value
轉換的價值。
currency_code
conversion_value
的貨幣代碼。
設定每項轉換作業的選用欄位
請查看下方的選用欄位清單,並視需要在 ClickConversion
上設定這些欄位。
order_id
- 轉換的交易 ID。這個欄位為選填欄位,但我們強烈建議您填寫。如果您在上傳期間設定了這個參數,則必須使用該參數對轉換進行任何調整。
external_attribution_data
如果您使用第三方工具或自家解決方案來追蹤轉換,建議您將轉換功勞的一部分歸給 Google Ads,或是將轉換功勞分配給多個點擊。外部歸因轉換匯入功能可讓您上傳轉換,並為每次點擊分配部分功勞。
如要上傳部分學分,請將這個欄位設為
ExternalAttributionData
物件,並提供external_attribution_model
和external_attribution_credit
的值。custom_variables
自訂轉換變數的值。
Google Ads 不支援將自訂轉換變數與
wbraid
或gbraid
搭配使用。cart_data
您可以在
cart_data
欄位中加入ClickConversion
的購物車資訊,該欄位包含下列屬性:merchant_id
:相關聯的 Merchant Center 帳戶 ID。feed_country_code
:Merchant Center 動態饋給的 ISO 3166 兩位元地區代碼。feed_language_code
:Merchant Center 動態饋給的 ISO 639-1 語言代碼。local_transaction_cost
:ClickConversion
的currency_code
中所有交易折扣的總和。items
:購物車中的商品。
items
中的每個項目都包含下列屬性:product_id
:產品的ID,有時又稱為優惠 ID 或商品 ID。quantity
:商品數量。unit_price
:商品的單價。
conversion_environment
表示記錄這項轉換的環境。例如應用程式或網頁。
程式碼範例
Java
private void runExample( GoogleAdsClient googleAdsClient, long customerId, long conversionActionId, String gclid, String gbraid, String wbraid, String conversionDateTime, Double conversionValue, Long conversionCustomVariableId, String conversionCustomVariableValue, String orderId, ConsentStatus adUserDataConsent) throws InvalidProtocolBufferException { // Verifies that exactly one of gclid, gbraid, and wbraid is specified, as required. // See https://developers.google.com/google-ads/api/docs/conversions/upload-clicks for details. long numberOfIdsSpecified = Arrays.asList(gclid, gbraid, wbraid).stream().filter(idField -> idField != null).count(); if (numberOfIdsSpecified != 1) { throw new IllegalArgumentException( "Exactly 1 of gclid, gbraid, or wbraid is required, but " + numberOfIdsSpecified + " ID values were provided"); } // Constructs the conversion action resource name from the customer and conversion action IDs. String conversionActionResourceName = ResourceNames.conversionAction(customerId, conversionActionId); // Creates the click conversion. ClickConversion.Builder clickConversionBuilder = ClickConversion.newBuilder() .setConversionAction(conversionActionResourceName) .setConversionDateTime(conversionDateTime) .setConversionValue(conversionValue) .setCurrencyCode("USD"); // Sets the single specified ID field. if (gclid != null) { clickConversionBuilder.setGclid(gclid); } else if (gbraid != null) { clickConversionBuilder.setGbraid(gbraid); } else { clickConversionBuilder.setWbraid(wbraid); } if (conversionCustomVariableId != null && conversionCustomVariableValue != null) { // Sets the custom variable and value, if provided. clickConversionBuilder.addCustomVariables( CustomVariable.newBuilder() .setConversionCustomVariable( ResourceNames.conversionCustomVariable(customerId, conversionCustomVariableId)) .setValue(conversionCustomVariableValue)); } if (orderId != null) { // Sets the order ID (unique transaction ID), if provided. clickConversionBuilder.setOrderId(orderId); } // Sets the consent information, if provided. if (adUserDataConsent != null) { // 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(adUserDataConsent)); } ClickConversion clickConversion = clickConversionBuilder.build(); // 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()); // Prints any partial errors returned. if (response.hasPartialFailureError()) { GoogleAdsFailure googleAdsFailure = ErrorUtils.getInstance().getGoogleAdsFailure(response.getPartialFailureError()); // Constructs a protocol buffer printer that will print error details in a concise format. Printer errorPrinter = JsonFormat.printer().omittingInsignificantWhitespace(); for (int operationIndex = 0; operationIndex < response.getResultsCount(); operationIndex++) { ClickConversionResult conversionResult = response.getResults(operationIndex); if (ErrorUtils.getInstance().isPartialFailureResult(conversionResult)) { // Prints the errors for the failed operation. System.out.printf("Operation %d failed with the following errors:%n", operationIndex); for (GoogleAdsError resultError : ErrorUtils.getInstance().getGoogleAdsErrors(operationIndex, googleAdsFailure)) { // Prints the error with newlines and extra spaces removed. System.out.printf(" %s%n", errorPrinter.print(resultError)); } } else { // Prints the information about the successful operation. StringBuilder clickInfoBuilder = new StringBuilder("conversion that occurred at ") .append(String.format("'%s' ", conversionResult.getConversionDateTime())) .append("with "); if (conversionResult.hasGclid()) { clickInfoBuilder.append(String.format("gclid '%s'", conversionResult.getGclid())); } else if (!conversionResult.getGbraid().isEmpty()) { clickInfoBuilder.append(String.format("gbraid '%s'", conversionResult.getGbraid())); } else if (!conversionResult.getWbraid().isEmpty()) { clickInfoBuilder.append(String.format("wbraid '%s'", conversionResult.getWbraid())); } else { clickInfoBuilder.append("no click ID"); } System.out.printf("Operation %d for %s succeeded.%n", operationIndex, clickInfoBuilder); } } } } }
C#
public void Run(GoogleAdsClient client, long customerId, long conversionActionId, string gclid, string gbraid, string wbraid, string conversionTime, double conversionValue, ConsentStatus? adUserDataConsent) { // Get the ConversionActionService. ConversionUploadServiceClient conversionUploadService = client.GetService(Services.V18.ConversionUploadService); // Creates a click conversion by specifying currency as USD. ClickConversion clickConversion = new ClickConversion() { ConversionAction = ResourceNames.ConversionAction(customerId, conversionActionId), ConversionValue = conversionValue, ConversionDateTime = conversionTime, CurrencyCode = "USD", }; // Sets the consent information, if provided. if (adUserDataConsent != null) { // 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.Consent = new Consent() { AdUserData = (ConsentStatus)adUserDataConsent }; } // Verifies that exactly one of gclid, gbraid, and wbraid is specified, as required. // See https://developers.google.com/google-ads/api/docs/conversions/upload-clicks // for details. string[] ids = { gclid, gbraid, wbraid }; int idCount = ids.Where(id => !string.IsNullOrEmpty(id)).Count(); if (idCount != 1) { throw new ArgumentException($"Exactly 1 of gclid, gbraid, or wbraid is " + $"required, but {idCount} ID values were provided"); } // Sets the single specified ID field. if (!string.IsNullOrEmpty(gclid)) { clickConversion.Gclid = gclid; } else if (!string.IsNullOrEmpty(wbraid)) { clickConversion.Wbraid = wbraid; } else if (!string.IsNullOrEmpty(gbraid)) { clickConversion.Gbraid = gbraid; } try { // Issues a request to upload the click conversion. UploadClickConversionsResponse response = conversionUploadService.UploadClickConversions( new UploadClickConversionsRequest() { CustomerId = customerId.ToString(), Conversions = { clickConversion }, PartialFailure = true, ValidateOnly = false }); // Prints the result. ClickConversionResult uploadedClickConversion = response.Results[0]; Console.WriteLine($"Uploaded conversion that occurred at " + $"'{uploadedClickConversion.ConversionDateTime}' from Google " + $"Click ID '{uploadedClickConversion.Gclid}' to " + $"'{uploadedClickConversion.ConversionAction}'."); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
PHP
public static function runExample( GoogleAdsClient $googleAdsClient, int $customerId, int $conversionActionId, ?string $gclid, ?string $gbraid, ?string $wbraid, ?string $orderId, string $conversionDateTime, float $conversionValue, ?string $conversionCustomVariableId, ?string $conversionCustomVariableValue, ?int $adUserDataConsent ) { // Verifies that exactly one of gclid, gbraid, and wbraid is specified, as required. // See https://developers.google.com/google-ads/api/docs/conversions/upload-clicks for details. $nonNullFields = array_filter( [$gclid, $gbraid, $wbraid], function ($field) { return !is_null($field); } ); if (count($nonNullFields) !== 1) { throw new \UnexpectedValueException( sprintf( "Exactly 1 of gclid, gbraid or wbraid is required, but %d ID values were " . "provided", count($nonNullFields) ) ); } // Creates a click conversion by specifying currency as USD. $clickConversion = new ClickConversion([ 'conversion_action' => ResourceNames::forConversionAction($customerId, $conversionActionId), 'conversion_value' => $conversionValue, 'conversion_date_time' => $conversionDateTime, 'currency_code' => 'USD' ]); // Sets the single specified ID field. if (!is_null($gclid)) { $clickConversion->setGclid($gclid); } elseif (!is_null($gbraid)) { $clickConversion->setGbraid($gbraid); } else { $clickConversion->setWbraid($wbraid); } if (!is_null($conversionCustomVariableId) && !is_null($conversionCustomVariableValue)) { $clickConversion->setCustomVariables([new CustomVariable([ 'conversion_custom_variable' => ResourceNames::forConversionCustomVariable( $customerId, $conversionCustomVariableId ), 'value' => $conversionCustomVariableValue ])]); } // Sets the consent information, if provided. if (!empty($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' => $adUserDataConsent])); } if (!empty($orderId)) { // Sets the order ID (unique transaction ID), if provided. $clickConversion->setOrderId($orderId); } // Issues a request to upload the click conversion. $conversionUploadServiceClient = $googleAdsClient->getConversionUploadServiceClient(); /** @var UploadClickConversionsResponse $response */ // 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( // Uploads the click conversion. Partial failure should always be set to true. UploadClickConversionsRequest::build($customerId, [$clickConversion], true) ); // Prints the status message if any partial failure error is returned. // Note: The details of each partial failure error are not printed here, you can refer to // the example HandlePartialFailure.php to learn more. if ($response->hasPartialFailureError()) { printf( "Partial failures occurred: '%s'.%s", $response->getPartialFailureError()->getMessage(), PHP_EOL ); } else { // Prints the result if exists. /** @var ClickConversionResult $uploadedClickConversion */ $uploadedClickConversion = $response->getResults()[0]; printf( "Uploaded click conversion that occurred at '%s' from Google Click ID '%s' " . "to '%s'.%s", $uploadedClickConversion->getConversionDateTime(), $uploadedClickConversion->getGclid(), $uploadedClickConversion->getConversionAction(), PHP_EOL ); } }
Python
def main( client, customer_id, conversion_action_id, gclid, conversion_date_time, conversion_value, conversion_custom_variable_id, conversion_custom_variable_value, gbraid, wbraid, order_id, ad_user_data_consent, ): """Creates a click conversion with a default currency of USD. Args: client: An initialized GoogleAdsClient instance. customer_id: The client customer ID string. conversion_action_id: The ID of the conversion action to upload to. gclid: The Google Click Identifier ID. If set, the wbraid and gbraid parameters must be None. conversion_date_time: The the date and time of the conversion (should be after the click time). The format is 'yyyy-mm-dd hh:mm:ss+|-hh:mm', e.g. '2021-01-01 12:32:45-08:00'. conversion_value: The conversion value in the desired currency. conversion_custom_variable_id: The ID of the conversion custom variable to associate with the upload. conversion_custom_variable_value: The str value of the conversion custom variable to associate with the upload. gbraid: The GBRAID for the iOS app conversion. If set, the gclid and wbraid parameters must be None. wbraid: The WBRAID for the iOS app conversion. If set, the gclid and gbraid parameters must be None. order_id: The order ID for the click conversion. ad_user_data_consent: The ad user data consent for the click. """ click_conversion = client.get_type("ClickConversion") conversion_upload_service = client.get_service("ConversionUploadService") conversion_action_service = client.get_service("ConversionActionService") click_conversion.conversion_action = ( conversion_action_service.conversion_action_path( customer_id, conversion_action_id ) ) # Sets the single specified ID field. if gclid: click_conversion.gclid = gclid elif gbraid: click_conversion.gbraid = gbraid else: click_conversion.wbraid = wbraid click_conversion.conversion_value = float(conversion_value) click_conversion.conversion_date_time = conversion_date_time click_conversion.currency_code = "USD" if conversion_custom_variable_id and conversion_custom_variable_value: conversion_custom_variable = client.get_type("CustomVariable") conversion_custom_variable.conversion_custom_variable = ( conversion_upload_service.conversion_custom_variable_path( customer_id, conversion_custom_variable_id ) ) conversion_custom_variable.value = conversion_custom_variable_value click_conversion.custom_variables.append(conversion_custom_variable) if order_id: click_conversion.order_id = order_id # Sets the consent information, if provided. if ad_user_data_consent: # 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 click_conversion.consent.ad_user_data = client.enums.ConsentStatusEnum[ ad_user_data_consent ] # Uploads the click conversion. Partial failure must be set to True here. # # 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 request = client.get_type("UploadClickConversionsRequest") request.customer_id = customer_id request.conversions.append(click_conversion) request.partial_failure = True conversion_upload_response = ( conversion_upload_service.upload_click_conversions( request=request, ) ) uploaded_click_conversion = conversion_upload_response.results[0] print( f"Uploaded conversion that occurred at " f'"{uploaded_click_conversion.conversion_date_time}" from ' f'Google Click ID "{uploaded_click_conversion.gclid}" ' f'to "{uploaded_click_conversion.conversion_action}"' )
小茹
def upload_offline_conversion( customer_id, conversion_action_id, gclid, gbraid, wbraid, conversion_date_time, conversion_value, conversion_custom_variable_id, conversion_custom_variable_value, ad_user_data_consent) # GoogleAdsClient will read a config file from # ENV['HOME']/google_ads_config.rb when called without parameters client = Google::Ads::GoogleAds::GoogleAdsClient.new # Verifies that exactly one of gclid, gbraid, and wbraid is specified, as required. # See https://developers.google.com/google-ads/api/docs/conversions/upload-clicks for details. identifiers_specified = [gclid, gbraid, wbraid].reject {|v| v.nil?}.count if identifiers_specified != 1 raise "Must specify exactly one of GCLID, GBRAID, and WBRAID. " \ "#{identifiers_specified} values were provided." end click_conversion = client.resource.click_conversion do |cc| cc.conversion_action = client.path.conversion_action(customer_id, conversion_action_id) # Sets the single specified ID field. if !gclid.nil? cc.gclid = gclid elsif !gbraid.nil? cc.gbraid = gbraid else cc.wbraid = wbraid end cc.conversion_value = conversion_value.to_f cc.conversion_date_time = conversion_date_time cc.currency_code = 'USD' if conversion_custom_variable_id && conversion_custom_variable_value cc.custom_variables << client.resource.custom_variable do |cv| cv.conversion_custom_variable = client.path.conversion_custom_variable( customer_id, conversion_custom_variable_id) cv.value = conversion_custom_variable_value end end # Sets the consent information, if provided. unless ad_user_data_consent.nil? cc.consent = client.resource.consent do |c| # 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 c.ad_user_data = ad_user_data_consent end end end response = client.service.conversion_upload.upload_click_conversions( customer_id: customer_id, # 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 conversions: [click_conversion], partial_failure: true, ) if response.partial_failure_error.nil? result = response.results.first puts "Uploaded conversion that occurred at #{result.conversion_date_time} " \ "from Google Click ID #{result.gclid} to #{result.conversion_action}." else failures = client.decode_partial_failure_error(response.partial_failure_error) puts "Request failed. Failure details:" failures.each do |failure| failure.errors.each do |error| puts "\t#{error.error_code.error_code}: #{error.message}" end end end end
Perl
sub upload_offline_conversion { my ( $api_client, $customer_id, $conversion_action_id, $gclid, $gbraid, $wbraid, $conversion_date_time, $conversion_value, $conversion_custom_variable_id, $conversion_custom_variable_value, $order_id, $ad_user_data_consent ) = @_; # Verify that exactly one of gclid, gbraid, and wbraid is specified, as required. # See https://developers.google.com/google-ads/api/docs/conversions/upload-clicks for details. my $number_of_ids_specified = grep { defined $_ } ($gclid, $gbraid, $wbraid); if ($number_of_ids_specified != 1) { die sprintf "Exactly 1 of gclid, gbraid, or wbraid is required, " . "but %d ID values were provided.\n", $number_of_ids_specified; } # Create a click conversion by specifying currency as USD. my $click_conversion = Google::Ads::GoogleAds::V18::Services::ConversionUploadService::ClickConversion ->new({ conversionAction => Google::Ads::GoogleAds::V18::Utils::ResourceNames::conversion_action( $customer_id, $conversion_action_id ), conversionDateTime => $conversion_date_time, conversionValue => $conversion_value, currencyCode => "USD" }); # Set the single specified ID field. if (defined $gclid) { $click_conversion->{gclid} = $gclid; } elsif (defined $gbraid) { $click_conversion->{gbraid} = $gbraid; } else { $click_conversion->{wbraid} = $wbraid; } if ($conversion_custom_variable_id && $conversion_custom_variable_value) { $click_conversion->{customVariables} = [ Google::Ads::GoogleAds::V18::Services::ConversionUploadService::CustomVariable ->new({ conversionCustomVariable => Google::Ads::GoogleAds::V18::Utils::ResourceNames::conversion_custom_variable( $customer_id, $conversion_custom_variable_id ), value => $conversion_custom_variable_value })]; } if (defined $order_id) { # Set the order ID (unique transaction ID), if provided. $click_conversion->{orderId} = $order_id; } # Set the consent information, if provided. if ($ad_user_data_consent) { # Specify whether user consent was obtained for the data you are uploading. # See https://www.google.com/about/company/user-consent-policy for details. $click_conversion->{consent} = Google::Ads::GoogleAds::V18::Common::Consent->new({ adUserData => $ad_user_data_consent }); } # Issue a request to 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 $upload_click_conversions_response = $api_client->ConversionUploadService()->upload_click_conversions({ customerId => $customer_id, conversions => [$click_conversion], partialFailure => "true" }); # Print any partial errors returned. if ($upload_click_conversions_response->{partialFailureError}) { printf "Partial error encountered: '%s'.\n", $upload_click_conversions_response->{partialFailureError}{message}; } # Print the result if valid. my $uploaded_click_conversion = $upload_click_conversions_response->{results}[0]; if (%$uploaded_click_conversion) { printf "Uploaded conversion that occurred at '%s' from Google Click ID '%s' " . "to the conversion action with resource name '%s'.\n", $uploaded_click_conversion->{conversionDateTime}, $uploaded_click_conversion->{gclid}, $uploaded_click_conversion->{conversionAction}; } return 1; }
疑難排解
離線資料診斷功能提供單一資源,可讓您持續查看上傳內容的整體健康狀況。不過,在導入期間,您可以使用本節中的資訊,調查回應中 partial_failure_error
欄位所回報的任何錯誤。
上傳轉換動作時最常見的錯誤是授權錯誤,例如 USER_PERMISSION_DENIED
。請仔細確認要求中的客戶 ID 已設為擁有轉換動作的 Google Ads 轉換客戶。如需更多詳細資訊,請參閱授權指南,並查看常見錯誤指南,瞭解如何偵錯這些不同錯誤。
排除常見錯誤
錯誤 | |
---|---|
ConversionUploadError.INVALID_CONVERSION_ACTION_TYPE
|
指定的轉換動作類型無法用於上傳點擊轉換。請確認上傳要求中指定的 ConversionAction 為 UPLOAD_CLICKS 類型。 |
ConversionUploadError.NO_CONVERSION_ACTION_FOUND
|
指定的轉換動作未啟用,或是無法在上傳的 customer_id 中找到。請確認上傳內容中的轉換動作已啟用,且由上傳要求的 customer_id 擁有。 |
ConversionUploadError.TOO_RECENT_CONVERSION_ACTION
|
轉換動作已新建。建立動作後,請等待至少 6 小時,再重試失敗的轉換。 |
ConversionUploadError.INVALID_CUSTOMER_FOR_CLICK
|
要求的 customer_id 與點擊時的 Google Ads API 轉換帳戶 客戶 ID 不同。請將要求的 customer_id 更新為正確的客戶。 |
ConversionUploadError.EVENT_NOT_FOUND
|
Google Ads 找不到點擊 ID 和 customer_id 的組合。請詳閱customer_id 的相關規定,並確認您使用的是正確的 Google Ads 帳戶上傳資料。 |
ConversionUploadError.DUPLICATE_CLICK_CONVERSION_IN_REQUEST
|
要求中的多筆轉換具有相同的點擊 ID、conversion_date_time 和 conversion_action 組合。請從要求中移除重複的轉換。 |
ConversionUploadError.CLICK_CONVERSION_ALREADY_EXISTS
|
先前已上傳含有相同點擊 ID、conversion_date_time 和 conversion_action 組合的轉換資料。如果您嘗試重試上傳作業,且先前這項轉換已成功,請忽略這項錯誤。如果您想在先前上傳的轉換之外,新增其他轉換,請調整 ClickConversion 的 conversion_date_time ,以免重複先前上傳的轉換。 |
ConversionUploadError.EVENT_NOT_FOUND
|
Google Ads 找不到點擊 ID 和 customer_id 的組合。請詳閱customer_id 的相關規定,並確認您使用的是正確的 Google Ads 帳戶上傳資料。 |
ConversionUploadError.EXPIRED_EVENT
|
匯入的點擊發生在 click_through_lookback_window_days 欄位中指定的時間範圍之前。變更 click_through_lookback_window_days 只會影響變更後記錄的點擊次數,因此變更回溯期不會解決特定點擊的這項錯誤。視情況將 conversion_action 變更為回溯期較長的其他動作。 |
ConversionUploadError.CONVERSION_PRECEDES_EVENT
|
conversion_date_time 會出現在點擊日期和時間之前。將 conversion_date_time 更新為較晚的值。 |
ConversionUploadError.GBRAID_WBRAID_BOTH_SET
|
ClickConversion 為 gbraid 和 wbraid 都設有值。請更新轉換,只使用一個點擊 ID,並確保不會將多個點擊合併為同一個轉換。每個點擊都只有一個點擊 ID。 |
FieldError.VALUE_MUST_BE_UNSET
|
請檢查 GoogleAdsError 的 location ,判斷是哪一個問題導致錯誤。
|
報表中的轉換
上傳的轉換會在報表中顯示為原始點擊的曝光日期,而非上傳要求日期或 ClickConversion
的 conversion_date_time
日期。
匯入的轉換統計資料最多可能要過 3 小時,才會列在 Google Ads 帳戶中,以便進行最終點擊歸因。其他搜尋歸因模式可能需要超過 3 小時。詳情請參閱資料更新間隔指南。