Tải lượt chuyển đổi từ lượt nhấp lên

Bạn có thể sử dụng API Google Ads để tải lượt chuyển đổi từ lượt nhấp ngoại tuyến lên Google Ads để theo dõi những quảng cáo tạo ra các giao dịch bán hàng trong thế giới thực, chẳng hạn như qua điện thoại hoặc thông qua một người đại diện bán hàng.

Thiết lập

Để thiết lập lượt chuyển đổi ngoại tuyến, bạn cần đáp ứng một số điều kiện tiên quyết. Hãy đảm bảo bạn đáp ứng tất cả điều kiện tiên quyết trước khi tiến hành triển khai:

  1. Bật tính năng theo dõi lượt chuyển đổi cho khách hàng chuyển đổi Google Ads.

  2. Định cấu hình tính năng gắn thẻ và mã lượt nhấp cửa hàng.

1. Bật tính năng theo dõi lượt chuyển đổi cho khách hàng chuyển đổi Google Ads

Nếu đã hoàn tất phần hướng dẫn bắt đầu bắt đầu lượt chuyển đổi và bật tính năng theo dõi lượt chuyển đổi, bạn có thể chuyển sang bước 2: định cấu hình tính năng gắn thẻ.

Truy xuất thông tin về chế độ theo dõi lượt chuyển đổi

Bạn có thể kiểm tra chế độ theo dõi lượt chuyển đổi của tài khoản và xác nhận rằng tính năng theo dõi lượt chuyển đổi đã bật bằng cách truy vấn tài nguyên Customer cho ConversionTrackingSetting. Đưa ra truy vấn sau bằng 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

Trường google_ads_conversion_customer cho biết tài khoản Google Ads có chức năng tạo và quản lý lượt chuyển đổi cho khách hàng này. Đối với những khách hàng sử dụng tính năng theo dõi lượt chuyển đổi trên nhiều tài khoản, đây là mã nhận dạng của tài khoản người quản lý. Mã khách hàng chuyển đổi trên Google Ads phải được cung cấp dưới dạng customer_id trong các yêu cầu của API Google Ads để tạo và quản lý lượt chuyển đổi. Xin lưu ý rằng trường này được điền sẵn ngay cả khi tính năng theo dõi lượt chuyển đổi không được bật.

Trường conversion_tracking_status cho biết liệu tính năng theo dõi lượt chuyển đổi đã được bật hay chưa và liệu tài khoản có đang sử dụng tính năng theo dõi lượt chuyển đổi trên nhiều tài khoản hay không.

Tạo một hành động chuyển đổi trong mục khách hàng chuyển đổi Google Ads

Nếu giá trị conversion_tracking_statusNOT_CONVERSION_TRACKED, thì tính năng theo dõi lượt chuyển đổi chưa được bật cho tài khoản đó. Bật tính năng theo dõi lượt chuyển đổi bằng cách tạo ít nhất một ConversionAction trong tài khoản chuyển đổi Google Ads, như trong ví dụ sau. Ngoài ra, bạn có thể tạo một hành động chuyển đổi trong giao diện người dùng bằng cách làm theo hướng dẫn trong Trung tâm trợ giúp cho loại chuyển đổi mà bạn muốn bật.

Xin lưu ý rằng tính năng lượt chuyển đổi nâng cao sẽ tự động được bật khi được gửi thông qua API Google Ads, nhưng bạn có thể tắt tính năng này thông qua giao diện người dùng Google Ads.

Ví dụ về mã

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.V16.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;
    }
}
      

1.199

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}".'
    )
      

Ruby

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::V16::Resources::ConversionAction->new({
      name                          => $conversion_action_name,
      category                      => DEFAULT,
      type                          => WEBPAGE,
      status                        => ENABLED,
      viewThroughLookbackWindowDays => 15,
      valueSettings                 =>
        Google::Ads::GoogleAds::V16::Resources::ValueSettings->new({
          defaultValue          => 23.41,
          alwaysUseDefaultValue => "true"
        })});

  # Create a conversion action operation.
  my $conversion_action_operation =
    Google::Ads::GoogleAds::V16::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;
}
      

Hãy đảm bảo bạn đặt conversion_action_type thành giá trị ConversionActionType chính xác. Để biết thêm hướng dẫn về cách tạo hành động chuyển đổi trong API Google Ads, hãy xem bài viết Tạo hành động chuyển đổi.

Truy xuất hành động chuyển đổi hiện tại

Bạn có thể truy xuất thông tin chi tiết về một hành động chuyển đổi hiện có bằng cách tạo truy vấn sau. Hãy nhớ đặt mã khách hàng trong yêu cầu thành khách hàng chuyển đổi Google Ads mà bạn đã xác định ở trên và bạn đã đặt loại hành động chuyển đổi thành giá trị ConversionActionType chính xác.

SELECT
  conversion_action.resource_name,
  conversion_action.name,
  conversion_action.status
FROM conversion_action
WHERE conversion_action.type = 'INSERT_CONVERSION_ACTION_TYPE'

2. Định cấu hình tính năng gắn thẻ và mã lượt nhấp vào cửa hàng

Làm theo instructions để xác nhận bạn đã bật tính năng tự động gắn thẻ, đồng thời thiết lập tài khoản Google Ads, trang web và hệ thống theo dõi khách hàng tiềm năng để thu thập và lưu trữ GCLID, GBRAID hoặc WBRAID của từng lượt hiển thị và lượt nhấp cho quảng cáo của bạn. Theo mặc định, tính năng tự động gắn thẻ được bật cho những tài khoản mới.

Xây dựng yêu cầu

Hãy làm theo hướng dẫn bên dưới để tạo UploadClickConversionsRequest và đặt các trường của lớp đó thành các giá trị thích hợp.

customer_id

Xác định tài khoản Google Ads mà bạn tải lên. Đặt giá trị này thành khách hàng chuyển đổi Google Ads của tài khoản là nguồn của các lượt nhấp.

job_id

Cung cấp cơ chế để liên kết các yêu cầu tải lên với thông tin về mỗi công việc trong phần chẩn đoán dữ liệu ngoại tuyến.

Nếu bạn không đặt trường này, thì API Google Ads sẽ chỉ định cho mỗi yêu cầu một giá trị duy nhất trong phạm vi [2^31, 2^63). Nếu bạn muốn nhóm nhiều yêu cầu vào một công việc logic duy nhất, hãy đặt trường này thành cùng một giá trị trong phạm vi [0, 2^31) cho mọi yêu cầu trong công việc của bạn.

job_id trong phản hồi chứa mã công việc cho yêu cầu, bất kể bạn đã chỉ định giá trị hay cho phép API Google Ads chỉ định giá trị.

partial_failure_enabled

Xác định cách API Google Ads xử lý lỗi từ hoạt động.

Bạn phải đặt trường này thành true. Làm theo nguyên tắc lỗi một phần khi xử lý phản hồi.

debug_enabled

Xác định hành vi báo cáo lỗi cho hoạt động tải lượt chuyển đổi nâng cao cho khách hàng tiềm năng lên. API Google Ads sẽ bỏ qua trường này khi xử lý các tệp tải lên cho lượt chuyển đổi từ lượt nhấp bằng cách sử dụng gclid, gbraid hoặc wbraid.

Tạo hoạt động chuyển đổi nhấp chuột

Tập hợp các đối tượng ClickConversion trong UploadClickConversionRequest của bạn xác định tập hợp các lượt chuyển đổi bạn muốn tải lên. Hãy làm theo hướng dẫn bên dưới để tạo từng ClickConversion và đặt các trường của thuộc tính đó thành các giá trị thích hợp.

Đặt các trường bắt buộc của mỗi hoạt động chuyển đổi

Hãy làm theo hướng dẫn bên dưới để đặt các trường bắt buộc của ClickConversion thành các giá trị thích hợp.

gclid, gbraid, wbraid
Giá trị nhận dạng mà bạn thu thập được tại thời điểm xảy ra lượt nhấp cho lượt nhấp hoặc lượt hiển thị của lượt chuyển đổi. Chỉ đặt một trong các trường này.
conversion_date_time

Ngày và giờ của lượt chuyển đổi.

Giá trị phải được chỉ định múi giờ và định dạng phải là yyyy-mm-dd HH:mm:ss+|-HH:mm, ví dụ: 2022-01-01 19:32:45-05:00 (bỏ qua giờ mùa hè).

Múi giờ có thể dành cho bất kỳ giá trị hợp lệ nào: múi giờ không phải khớp với múi giờ của tài khoản. Tuy nhiên, nếu định so sánh dữ liệu lượt chuyển đổi đã tải lên với dữ liệu trong giao diện người dùng Google Ads, bạn nên sử dụng cùng múi giờ với tài khoản Google Ads để số lượt chuyển đổi trùng khớp. Bạn có thể tìm thêm thông tin chi tiết và ví dụ trong Trung tâm trợ giúp, đồng thời xem phần Mã và định dạng để biết danh sách mã múi giờ hợp lệ.

user_identifiers

Đừng đặt trường này khi chỉ tải những lượt chuyển đổi lên bằng mã lượt nhấp. Nếu bạn đặt trường này, Google Ads sẽ coi hoạt động tải lên là hoạt động tải lên đối với lượt chuyển đổi nâng cao cho khách hàng tiềm năng.

conversion_action

Tên tài nguyên của ConversionAction cho lượt chuyển đổi lượt nhấp.

Hành động chuyển đổi phải có giá trị typeUPLOAD_CLICKS và phải có trong tài khoản khách hàng chuyển đổi Google Ads của tài khoản Google Ads được liên kết với lượt nhấp đó.

conversion_value

Giá trị của lượt chuyển đổi.

currency_code

Mã đơn vị tiền tệ của conversion_value.

Đặt các trường không bắt buộc của mỗi hoạt động chuyển đổi

Xem lại danh sách các trường không bắt buộc bên dưới và đặt các trường đó trên ClickConversion nếu cần.

order_id
Mã giao dịch của lượt chuyển đổi. Trường này là không bắt buộc nhưng bạn nên sử dụng. Nếu đặt chế độ cài đặt này trong khi tải lên, bạn phải sử dụng chỉ số đó cho mọi điều chỉnh được thực hiện đối với lượt chuyển đổi.
external_attribution_data

Nếu dùng công cụ của bên thứ ba hoặc giải pháp nội bộ để theo dõi lượt chuyển đổi, bạn nên phân bổ cho Google Ads một phần giá trị đóng góp cho lượt chuyển đổi, hoặc phân bổ giá trị đóng góp cho một lượt chuyển đổi trên nhiều lượt nhấp. Nhập lượt chuyển đổi được phân bổ bên ngoài cho phép bạn tải lên các lượt chuyển đổi có giá trị đóng góp được chỉ định theo tỷ lệ cho mỗi lượt nhấp.

Để tải giá trị đóng góp được chia theo tỷ lệ lên, hãy đặt trường này thành một đối tượng ExternalAttributionData với các giá trị cho external_attribution_modelexternal_attribution_credit.

custom_variables

Giá trị cho biến lượt chuyển đổi tuỳ chỉnh.

Google Ads không hỗ trợ biến lượt chuyển đổi tuỳ chỉnh kết hợp với wbraid hoặc gbraid.

cart_data

Bạn có thể đưa thông tin giỏ hàng cho ClickConversion vào trường cart_data, bao gồm các thuộc tính sau:

  • merchant_id: Mã của tài khoản Merchant Center được liên kết.
  • feed_country_code: Mã vùng gồm hai ký tự theo ISO 3166 của nguồn cấp dữ liệu Merchant Center.
  • feed_language_code: Mã ngôn ngữ ISO 639-1 của nguồn cấp dữ liệu Merchant Center.
  • local_transaction_cost: Tổng của tất cả các khoản chiết khấu cấp giao dịch, trong currency_code của ClickConversion.
  • items: Các mặt hàng trong giỏ hàng.

Mỗi mục trong items bao gồm các thuộc tính sau:

  • product_id: Mã nhận dạng của sản phẩm, đôi khi được gọi là mã mặt hàng hoặc mã mặt hàng.
  • quantity: Số lượng của một mặt hàng.
  • unit_price: Đơn giá của mặt hàng.
conversion_environment

Cho biết môi trường nơi lượt chuyển đổi này được ghi lại. Ví dụ: Ứng dụng hoặc Web.

Ví dụ về mã

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.V16.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;
    }
}
      

1.199

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}"'
    )
      

Ruby

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?
      c.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::V16::Services::ConversionUploadService::ClickConversion
    ->new({
      conversionAction =>
        Google::Ads::GoogleAds::V16::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::V16::Services::ConversionUploadService::CustomVariable
        ->new({
          conversionCustomVariable =>
            Google::Ads::GoogleAds::V16::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::V16::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;
}
      

Khắc phục sự cố

Chẩn đoán dữ liệu ngoại tuyến cung cấp một tài nguyên duy nhất để đánh giá tình trạng tổng thể của các tệp tải lên dựa trên cơ sở liên tục. Tuy nhiên, trong quá trình triển khai, bạn có thể sử dụng thông tin trong phần này để điều tra mọi lỗi được báo cáo trong trường partial_failure_error của phản hồi.

Một số lỗi phổ biến nhất khi tải hành động chuyển đổi lên là lỗi uỷ quyền, chẳng hạn như USER_PERMISSION_DENIED. Hãy kiểm tra kỹ để đảm bảo rằng bạn đã đặt mã khách hàng trong yêu cầu thành khách hàng chuyển đổi Google Ads sở hữu hành động chuyển đổi đó. Truy cập hướng dẫn uỷ quyền để biết thêm thông tin và xem hướng dẫn về các lỗi thường gặp để nắm được mẹo về cách gỡ lỗi.

Gỡ lỗi các lỗi thường gặp

Lỗi
ConversionUploadError.INVALID_CONVERSION_ACTION_TYPE Hành động chuyển đổi đã chỉ định có loại không hợp lệ để tải lượt chuyển đổi từ lượt nhấp lên. Hãy đảm bảo ConversionAction được chỉ định trong yêu cầu tải lên có loại UPLOAD_CLICKS.
ConversionUploadError.NO_CONVERSION_ACTION_FOUND Chưa bật hoặc không tìm thấy hành động chuyển đổi đã chỉ định trong customer_id đang tải lên. Hãy đảm bảo hành động chuyển đổi trong tệp tải lên của bạn đã được bật và thuộc sở hữu của customer_id trong yêu cầu tải lên.
ConversionUploadError.TOO_RECENT_CONVERSION_ACTION Hành động chuyển đổi mới được tạo. Hãy chờ ít nhất 6 giờ sau khi tạo hành động rồi mới thử lại những lượt chuyển đổi không thành công.
ConversionUploadError.INVALID_CUSTOMER_FOR_CLICK customer_id của yêu cầu không giống với mã khách hàng của khách hàng chuyển đổi trên Google Ads tại thời điểm xảy ra lượt nhấp. Cập nhật customer_id của yêu cầu cho đúng khách hàng.
ConversionUploadError.EVENT_NOT_FOUND Google Ads không thể tìm thấy tổ hợp mã lượt nhấp và customer_id. Xem lại các yêu cầu đối với customer_id và xác nhận rằng bạn đang tải lên bằng đúng tài khoản Google Ads.
ConversionUploadError.DUPLICATE_CLICK_CONVERSION_IN_REQUEST Nhiều lượt chuyển đổi trong yêu cầu này có cùng một tổ hợp mã lượt nhấp là conversion_date_timeconversion_action. Xoá các lượt chuyển đổi trùng lặp khỏi yêu cầu của bạn.
ConversionUploadError.CLICK_CONVERSION_ALREADY_EXISTS Một lượt chuyển đổi có cùng tổ hợp mã lượt nhấp là conversion_date_timeconversion_action đã được tải lên trước đó. Hãy bỏ qua lỗi này nếu bạn đang thử tải lên lại và lượt chuyển đổi này đã thành công trước đó. Nếu bạn muốn thêm một lượt chuyển đổi khác ngoài lượt chuyển đổi đã tải lên trước đó, hãy điều chỉnh conversion_date_time của ClickConversion để tránh trùng lặp với lượt chuyển đổi được tải lên trước đó.
ConversionUploadError.EVENT_NOT_FOUND Google Ads không thể tìm thấy tổ hợp mã lượt nhấp và customer_id. Xem lại các yêu cầu đối với customer_id và xác nhận rằng bạn đang tải lên bằng đúng tài khoản Google Ads.
ConversionUploadError.EXPIRED_EVENT Lượt nhấp được nhập xảy ra trước khung thời gian được chỉ định trong trường click_through_lookback_window_days. Việc thay đổi đối với click_through_lookback_window_days chỉ ảnh hưởng đến những lượt nhấp được ghi lại sau thay đổi đó. Vì vậy, việc thay đổi giai đoạn xem lại sẽ không giải quyết được lỗi này đối với lượt nhấp cụ thể. Nếu thích hợp, hãy thay đổi conversion_action thành một hành động khác có giai đoạn xem lại dài hơn.
ConversionUploadError.CONVERSION_PRECEDES_GCLID conversion_date_time nằm trước ngày và giờ xảy ra lượt nhấp. Cập nhật conversion_date_time thành một giá trị mới hơn.
ConversionUploadError.GBRAID_WBRAID_BOTH_SET ClickConversion có một giá trị được đặt cho cả gbraidwbraid. Hãy cập nhật lượt chuyển đổi để chỉ sử dụng một giá trị nhận dạng lượt nhấp và đảm bảo bạn không kết hợp nhiều lượt nhấp vào cùng một lượt chuyển đổi. Mỗi lượt nhấp chỉ có một giá trị nhận dạng lượt nhấp.
FieldError.VALUE_MUST_BE_UNSET Kiểm tra location của GoogleAdsError để xác định vấn đề nào sau đây đã gây ra lỗi.
  • ClickConversion có một giá trị được đặt cho gclid cũng như ít nhất một trong gbraid hoặc wbraid. Hãy cập nhật lượt chuyển đổi để chỉ sử dụng một giá trị nhận dạng lượt nhấp và đảm bảo bạn không kết hợp nhiều lượt nhấp vào cùng một lượt chuyển đổi. Mỗi lượt nhấp chỉ có một mã lượt nhấp.
  • ClickConversion có một giá trị được đặt cho gbraid hoặc wbraid và có một giá trị cho custom_variables. Google Ads không hỗ trợ biến tuỳ chỉnh cho lượt chuyển đổi có mã lượt nhấp gbraid hoặc wbraid. Huỷ đặt trường custom_variables của lượt chuyển đổi.

Lượt chuyển đổi trong báo cáo

Các lượt chuyển đổi đã tải lên được phản ánh trong báo cáo cho ngày hiển thị của lượt nhấp ban đầu, không phải ngày yêu cầu tải lên hoặc ngày conversion_date_time của ClickConversion.

Có thể mất đến 3 giờ để số liệu thống kê về lượt chuyển đổi đã nhập xuất hiện trong tài khoản Google Ads của bạn cho mô hình phân bổ theo lượt nhấp cuối cùng. Đối với các mô hình phân bổ tìm kiếm khác, quá trình này có thể mất hơn 3 giờ. Hãy tham khảo hướng dẫn làm mới dữ liệu để biết thêm thông tin.