Upload Konversi Klik

Anda dapat menggunakan Google Ads API untuk mengupload konversi klik offline ke Google Ads guna melacak iklan yang menghasilkan penjualan di dunia offline, seperti melalui ponsel atau melalui tenaga penjualan.

Penyiapan

Ada beberapa prasyarat untuk penyiapan konversi offline yang berfungsi. Pastikan semua prasyarat terpenuhi sebelum melanjutkan ke penerapan:

  1. Aktifkan tracking konversi di pelanggan konversi Google Ads Anda.

  2. Konfigurasikan pemberian tag dan simpan ID klik.

1. Mengaktifkan tracking konversi di pelanggan konversi Google Ads

Jika telah menyelesaikan panduan memulai konversi dan mengaktifkan tracking konversi, Anda dapat langsung ke langkah kedua: mengonfigurasi pemberian tag.

Mengambil informasi tentang penyiapan tracking konversi Anda

Anda dapat memeriksa penyiapan tracking konversi akun dan mengonfirmasi bahwa tracking konversi diaktifkan dengan membuat kueri resource Customer untuk ConversionTrackingSetting. Buat kueri berikut dengan 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

Kolom google_ads_conversion_customer menunjukkan akun Google Ads yang membuat dan mengelola konversi untuk pelanggan ini. Untuk pelanggan yang menggunakan tracking konversi lintas-akun, ini adalah ID akun pengelola. ID pelanggan konversi Google Ads harus diberikan sebagai customer_id dalam permintaan Google Ads API untuk membuat dan mengelola konversi. Perhatikan bahwa kolom ini diisi meskipun tracking konversi tidak diaktifkan.

Kolom conversion_tracking_status menunjukkan apakah tracking konversi diaktifkan dan apakah akun menggunakan tracking konversi lintas-akun.

Membuat tindakan konversi di bagian pelanggan konversi Google Ads

Jika nilai conversion_tracking_status adalah NOT_CONVERSION_TRACKED, tracking konversi tidak diaktifkan untuk akun. Aktifkan tracking konversi dengan membuat setidaknya satu ConversionAction di akun konversi Google Ads, seperti dalam contoh berikut. Atau, Anda dapat membuat tindakan konversi di UI dengan mengikuti petunjuk di Pusat Bantuan untuk jenis konversi yang ingin diaktifkan.

Perhatikan bahwa konversi yang disempurnakan diaktifkan secara otomatis saat dikirim melalui Google Ads API, tetapi dapat dinonaktifkan melalui UI Google Ads.

Contoh kode

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

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::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;
}
      

Pastikan conversion_action_type disetel ke nilai ConversionActionType yang benar. Untuk panduan selengkapnya tentang cara membuat tindakan konversi di Google Ads API, lihat Membuat Tindakan Konversi.

Mengambil tindakan konversi yang ada

Anda dapat mengambil detail untuk tindakan konversi yang ada dengan mengeluarkan kueri berikut. Pastikan ID pelanggan dalam permintaan ditetapkan ke pelanggan konversi Google Ads yang Anda identifikasi di atas, dan jenis tindakan konversi ditetapkan ke nilai ConversionActionType yang benar.

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

2. Mengonfigurasi pemberian tag dan menyimpan ID klik

Ikuti petunjuk untuk mengonfirmasi bahwa pemberian tag otomatis diaktifkan dan siapkan akun Google Ads, situs, dan sistem pelacakan prospek Anda untuk mengambil dan menyimpan GCLID, GBRAID, atau WBRAID dari setiap tayangan dan klik untuk iklan Anda. Pemberian tag otomatis diaktifkan secara default untuk akun baru.

Membuat permintaan

Ikuti panduan di bawah untuk membuat UploadClickConversionsRequest dan menetapkan kolomnya ke nilai yang sesuai.

customer_id

Mengidentifikasi akun Google Ads dari upload Anda. Tetapkan ke pelanggan konversi Google Ads akun yang merupakan sumber klik.

job_id

Menyediakan mekanisme untuk mengaitkan permintaan upload Anda dengan informasi per tugas dalam diagnostik data offline.

Jika Anda tidak menetapkan kolom ini, Google Ads API akan menetapkan nilai unik dalam rentang [2^31, 2^63) untuk setiap permintaan. Jika Anda lebih memilih untuk mengelompokkan beberapa permintaan ke dalam satu tugas logis, tetapkan kolom ini ke nilai yang sama dalam rentang [0, 2^31) pada setiap permintaan dalam tugas Anda.

job_id dalam respons berisi ID tugas untuk permintaan, terlepas dari apakah Anda menentukan nilai atau membiarkan Google Ads API menetapkan nilai.

partial_failure_enabled

Menentukan cara Google Ads API menangani error dari operasi.

Kolom ini harus ditetapkan ke true. Ikuti panduan kegagalan sebagian saat memproses respons.

debug_enabled

Menentukan perilaku pelaporan error untuk upload konversi yang disempurnakan untuk prospek. Google Ads API mengabaikan kolom ini saat menangani upload untuk konversi klik menggunakan gclid, gbraid, atau wbraid.

Membuat operasi konversi klik

Kumpulan objek ClickConversion di UploadClickConversionRequest menentukan kumpulan konversi yang ingin Anda upload. Ikuti panduan di bawah untuk membuat setiap ClickConversion dan menetapkan kolomnya ke nilai yang sesuai.

Menetapkan kolom wajib diisi dari setiap operasi konversi

Ikuti petunjuk di bawah untuk menetapkan kolom ClickConversion yang diperlukan ke nilai yang sesuai.

gclid, gbraid, wbraid
ID yang Anda ambil pada saat klik untuk klik atau tayangan iklan konversi. Hanya tetapkan satu kolom ini.
conversion_date_time

Tanggal dan waktu konversi.

Nilai harus memiliki zona waktu yang ditentukan, dan formatnya harus yyyy-mm-dd HH:mm:ss+|-HH:mm, misalnya: 2022-01-01 19:32:45-05:00 (mengabaikan waktu musim panas) .

Zona waktu dapat berupa nilai valid apa pun: zona waktu tidak harus cocok dengan zona waktu akun. Namun, jika Anda berencana membandingkan data konversi yang diupload dengan data di UI Google Ads, sebaiknya gunakan zona waktu yang sama dengan akun Google Ads Anda agar jumlah konversi cocok. Anda dapat menemukan detail dan contoh selengkapnya di Pusat Bantuan dan memeriksa Kode dan format untuk mengetahui daftar ID zona waktu yang valid.

user_identifiers

Jangan tetapkan kolom ini saat mengupload konversi hanya menggunakan ID klik. Jika kolom ini ditetapkan, Google Ads akan memperlakukan operasi upload sebagai upload untuk konversi yang disempurnakan untuk prospek.

conversion_action

Nama resource ConversionAction untuk konversi klik.

Tindakan konversi harus memiliki type UPLOAD_CLICKS, dan harus ada di pelanggan konversi Google Ads dari akun Google Ads yang terkait dengan klik.

conversion_value

Nilai konversi.

currency_code

Kode mata uang conversion_value.

Menetapkan kolom opsional dari setiap operasi konversi

Tinjau daftar kolom opsional di bawah dan tetapkan di ClickConversion sesuai kebutuhan.

order_id
ID transaksi untuk konversi. Kolom ini bersifat opsional, tetapi sangat direkomendasikan. Jika menetapkannya selama upload, Anda harus menggunakannya untuk penyesuaian apa pun yang dilakukan pada konversi.
external_attribution_data

Jika menggunakan alat pihak ketiga atau solusi buatan sendiri untuk melacak konversi, Anda dapat memberikan sebagian kredit konversi saja kepada Google Ads, atau mendistribusikan kredit konversi ke beberapa klik. Impor konversi yang diatribusikan secara eksternal memungkinkan Anda mengupload konversi dengan kredit pecahan yang ditetapkan ke setiap klik.

Untuk mengupload kredit pecahan, tetapkan kolom ini ke objek ExternalAttributionData dengan nilai untuk external_attribution_model dan external_attribution_credit.

custom_variables

Nilai untuk variabel konversi kustom.

Google Ads tidak mendukung variabel konversi kustom yang dikombinasikan dengan wbraid atau gbraid.

cart_data

Anda dapat menyertakan informasi keranjang belanja untuk ClickConversion di kolom cart_data, yang terdiri dari atribut berikut:

  • merchant_id: ID akun Merchant Center terkait.
  • feed_country_code: Kode wilayah dua karakter ISO 3166 dari feed Merchant Center.
  • feed_language_code: Kode bahasa ISO 639-1 feed Merchant Center.
  • local_transaction_cost: Jumlah semua diskon tingkat transaksi, dalam currency_code ClickConversion.
  • items: Item di keranjang belanja.

Setiap item di items terdiri dari atribut berikut:

  • product_id: ID produk, terkadang disebut sebagai ID penawaran atau ID item.
  • quantity: Jumlah item.
  • unit_price: Harga satuan item.

conversion_environment

Menunjukkan lingkungan tempat konversi ini dicatat. Misalnya, Aplikasi atau Web.

Contoh kode

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

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?
      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;
}
      

Memecahkan masalah

Diagnostik data offline menyediakan satu referensi untuk meninjau kondisi keseluruhan upload Anda secara berkelanjutan. Namun, selama penerapan, Anda dapat menggunakan informasi di bagian ini untuk menyelidiki error yang dilaporkan di kolom partial_failure_error respons.

Beberapa error yang paling umum saat mengupload tindakan konversi adalah error otorisasi, seperti USER_PERMISSION_DENIED. Periksa kembali apakah Anda memiliki ID pelanggan dalam permintaan yang ditetapkan ke pelanggan konversi Google Ads yang memiliki tindakan konversi. Buka panduan otorisasi untuk mengetahui detail selengkapnya dan lihat panduan error umum untuk mendapatkan tips tentang cara men-debug berbagai error ini.

Men-debug error umum

Error
ConversionUploadError.INVALID_CONVERSION_ACTION_TYPE Tindakan konversi yang ditentukan memiliki jenis yang tidak valid untuk mengupload konversi klik. Pastikan ConversionAction yang ditentukan dalam permintaan upload Anda memiliki jenis UPLOAD_CLICKS.
ConversionUploadError.NO_CONVERSION_ACTION_FOUND Tindakan konversi yang ditentukan tidak diaktifkan atau tidak dapat ditemukan dalam customer_id upload. Pastikan tindakan konversi dalam upload Anda diaktifkan dan dimiliki oleh customer_id permintaan upload.
ConversionUploadError.TOO_RECENT_CONVERSION_ACTION Tindakan konversi baru saja dibuat. Tunggu minimal 6 jam setelah tindakan dibuat sebelum mencoba lagi konversi yang gagal.
ConversionUploadError.INVALID_CUSTOMER_FOR_CLICK customer_id permintaan bukan ID pelanggan yang sama dengan akun konversi Google Ads API pada saat klik. Perbarui customer_id permintaan ke pelanggan yang benar.
ConversionUploadError.EVENT_NOT_FOUND Google Ads tidak dapat menemukan kombinasi ID klik dan customer_id. Tinjau persyaratan untuk customer_id dan confirmasikan bahwa Anda mengupload menggunakan akun Google Ads yang benar.
ConversionUploadError.DUPLICATE_CLICK_CONVERSION_IN_REQUEST Beberapa konversi dalam permintaan memiliki kombinasi ID klik, conversion_date_time, dan conversion_action yang sama. Hapus konversi duplikat dari permintaan Anda.
ConversionUploadError.CLICK_CONVERSION_ALREADY_EXISTS Konversi dengan kombinasi ID klik, conversion_date_time, dan conversion_action yang sama telah diupload sebelumnya. Abaikan error ini jika Anda mencoba lagi upload dan konversi ini sebelumnya berhasil. Jika Anda ingin menambahkan konversi lain selain konversi yang diupload sebelumnya, sesuaikan conversion_date_time ClickConversion untuk menghindari duplikasi konversi yang diupload sebelumnya.
ConversionUploadError.EVENT_NOT_FOUND Google Ads tidak dapat menemukan kombinasi ID klik dan customer_id. Tinjau persyaratan untuk customer_id dan confirmasikan bahwa Anda mengupload menggunakan akun Google Ads yang benar.
ConversionUploadError.EXPIRED_EVENT Klik yang diimpor terjadi sebelum jangka waktu yang ditentukan di kolom click_through_lookback_window_days. Perubahan pada click_through_lookback_window_days hanya memengaruhi klik yang dicatat setelah perubahan, sehingga mengubah periode lihat balik tidak akan menyelesaikan error ini untuk klik tertentu. Jika sesuai, ubah conversion_action ke tindakan lain dengan periode lihat balik yang lebih lama.
ConversionUploadError.CONVERSION_PRECEDES_EVENT conversion_date_time berada sebelum tanggal dan waktu klik. Perbarui conversion_date_time ke nilai yang lebih baru.
ConversionUploadError.GBRAID_WBRAID_BOTH_SET ClickConversion memiliki nilai yang ditetapkan untuk gbraid dan wbraid. Perbarui konversi agar hanya menggunakan satu ID klik, dan pastikan Anda tidak menggabungkan beberapa klik ke dalam konversi yang sama. Setiap klik hanya memiliki satu ID klik.
FieldError.VALUE_MUST_BE_UNSET Periksa location dari GoogleAdsError untuk menentukan masalah mana dari berikut ini yang menyebabkan error.
  • ClickConversion memiliki nilai yang ditetapkan untuk gclid serta setidaknya salah satu dari gbraid atau wbraid. Perbarui konversi agar hanya menggunakan satu ID klik, dan pastikan Anda tidak menggabungkan beberapa klik ke dalam konversi yang sama. Setiap klik hanya memiliki satu ID klik.
  • ClickConversion memiliki nilai yang ditetapkan untuk gbraid atau wbraid dan memiliki nilai untuk custom_variables. Google Ads tidak mendukung variabel kustom untuk konversi dengan ID klik gbraid atau wbraid. Hapus penetapan kolom custom_variables konversi.

Konversi dalam laporan

Konversi yang diupload akan ditampilkan dalam laporan untuk tanggal tayangan iklan klik asli, bukan tanggal permintaan upload atau tanggal conversion_date_time dari ClickConversion.

Perlu waktu hingga 3 jam agar statistik konversi yang diimpor muncul di akun Google Ads Anda untuk atribusi klik terakhir. Untuk model atribusi penelusuran lainnya, mungkin diperlukan waktu lebih dari 3 jam. Lihat panduan keaktualan data untuk informasi selengkapnya.