Upload Offline Conversion

Java

// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.ads.googleads.examples.remarketing;

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v4.utils.ResourceNames;
import com.google.ads.googleads.v4.errors.GoogleAdsError;
import com.google.ads.googleads.v4.errors.GoogleAdsException;
import com.google.ads.googleads.v4.services.ClickConversion;
import com.google.ads.googleads.v4.services.ClickConversionResult;
import com.google.ads.googleads.v4.services.ConversionUploadServiceClient;
import com.google.ads.googleads.v4.services.UploadClickConversionsRequest;
import com.google.ads.googleads.v4.services.UploadClickConversionsResponse;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.StringValue;
import java.io.FileNotFoundException;
import java.io.IOException;

/** Imports offline conversion values for specific clicks to an account. */
public class UploadOfflineConversion {
  private static class UploadOfflineConversionParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private long customerId;

    @Parameter(names = ArgumentNames.CONVERSION_ACTION_ID, required = true)
    private long conversionActionId;

    @Parameter(names = ArgumentNames.GCLID, required = true)
    private String gclid;

    @Parameter(
        names = ArgumentNames.CONVERSION_DATE_TIME,
        required = true,
        description =
            "The date time at which the conversion occurred. "
                + "Must be after the click time, and must include the time zone offset. "
                + "The format is  'yyyy-mm-dd hh:mm:ss+|-hh:mm', e.g. '2019-01-01 12:32:45-08:00'.")
    private String conversionDateTime;

    @Parameter(names = ArgumentNames.CONVERSION_VALUE, required = true)
    private Double conversionValue;
  }

  public static void main(String[] args) {
    UploadOfflineConversionParams params = new UploadOfflineConversionParams();
    if (!params.parseArguments(args)) {

      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
      params.conversionActionId = Long.parseLong("INSERT_CONVERSION_ACTION_ID_HERE");
      params.gclid = "INSERT_GCL_ID_HERE";
      params.conversionDateTime = "INSERT_CONVERSION_DATE_TIME_HERE";
      params.conversionValue = Double.parseDouble("INSERT_CONVERSION_VALUE_HERE");
    }

    GoogleAdsClient googleAdsClient;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      return;
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      return;
    }

    try {
      new UploadOfflineConversion()
          .runExample(
              googleAdsClient,
              params.customerId,
              params.conversionActionId,
              params.gclid,
              params.conversionDateTime,
              params.conversionValue);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
    }
  }

  /**
   * Runs the example.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param conversionActionId conversion action ID associated with this conversion.
   * @param gclid the GCLID for the conversion.
   * @param conversionDateTime date and time of the conversion.
   * @param conversionValue the value of the conversion.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient,
      long customerId,
      long conversionActionId,
      String gclid,
      String conversionDateTime,
      Double conversionValue) {
    // Gets the conversion action resource name.
    String conversionActionResourceName =
        ResourceNames.conversionAction(customerId, conversionActionId);

    // Creates the click conversion.
    ClickConversion clickConversion =
        ClickConversion.newBuilder()
            .setConversionAction(StringValue.of(conversionActionResourceName))
            .setConversionDateTime(StringValue.of(conversionDateTime))
            .setConversionValue(DoubleValue.of(conversionValue))
            .setCurrencyCode(StringValue.of("USD"))
            .setGclid(StringValue.of(gclid))
            .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.
      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()) {
        System.out.printf(
            "Partial error encountered: '%s'.%n", response.getPartialFailureError().getMessage());
      }

      // Prints the result.
      ClickConversionResult result = response.getResults(0);
      // Only prints valid results.
      if (result.hasGclid()) {
        System.out.printf(
            "Uploaded conversion that occurred at '%s' from Google Click ID '%s' to '%s'.%n",
            result.getConversionDateTime().getValue(),
            result.getGclid().getValue(),
            result.getConversionAction().getValue());
      }
    }
  }
}

C#

// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V4.Errors;
using Google.Ads.GoogleAds.V4.Services;

using System;

namespace Google.Ads.GoogleAds.Examples.V4
{
    /// <summary>
    /// This code example imports offline conversion values for specific clicks to your account.
    /// To get Google Click ID for a click, use the "click_view" resource:
    /// https://developers.google.com/google-ads/api/fields/latest/click_view.
    /// To set up a conversion action, run the AddConversionAction.cs example.
    /// </summary>
    public class UploadOfflineConversion : ExampleBase
    {
        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            UploadOfflineConversion codeExample = new UploadOfflineConversion();
            Console.WriteLine(codeExample.Description);

            // The Google Ads customer ID for which the call is made.
            long customerId = long.Parse("INSERT_CUSTOMER_ID_HERE");

            // The conversion action ID.
            long conversionActionId = long.Parse("INSERT_CONVERSION_ACTION_ID_HERE");

            // The Google Click ID for which conversions are uploaded.
            string gclid = "INSERT_GCLID_HERE";

            // The conversion time in "yyyy-mm-dd hh:mm:ss+|-hh:mm" format.
            string conversionTime = "INSERT_CONVERSION_TIME_HERE";

            // The conversion value.
            double conversionValue = double.Parse("CONVERSION_VALUE");

            codeExample.Run(new GoogleAdsClient(), customerId, conversionActionId, gclid,
                conversionTime, conversionValue);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example imports offline conversion values for specific " +
                    "clicks to your account. To get Google Click ID for a click, use the " +
                    "'click_view' resource: " +
                    "https://developers.google.com/google-ads/api/fields/latest/click_view. " +
                    "To set up a conversion action, run the AddConversionAction.cs example.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for the conversion action is
        /// added.</param>
        /// <param name="conversionActionId">The conversion action ID.</param>
        /// <param name="conversionTime">The conversion time.</param>
        /// <param name="gclid">The click ID.</param>
        /// <param name="conversionValue">The convsersion value.</param>
        public void Run(GoogleAdsClient client, long customerId, long conversionActionId,
            string gclid, string conversionTime, double conversionValue)
        {
            // Get the ConversionActionService.
            ConversionUploadServiceClient conversionUploadService =
                client.GetService(Services.V4.ConversionUploadService);

            // Creates a click conversion by specifying currency as USD.
            ClickConversion clickConversion = new ClickConversion()
            {
                ConversionAction = ResourceNames.ConversionAction(customerId, conversionActionId),
                Gclid = gclid,
                ConversionValue = conversionValue,
                ConversionDateTime = conversionTime,
                CurrencyCode = "USD"
            };

            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

<?php

/**
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Google\Ads\GoogleAds\Examples\Remarketing;

require __DIR__ . '/../../vendor/autoload.php';

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V4\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V4\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V4\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V4\ResourceNames;
use Google\Ads\GoogleAds\V4\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V4\Services\ClickConversion;
use Google\Ads\GoogleAds\V4\Services\UploadClickConversionsResponse;
use Google\ApiCore\ApiException;
use Google\Protobuf\DoubleValue;
use Google\Protobuf\StringValue;

/**
 * This code example imports offline conversion values for specific clicks to your account.
 * To get Google Click ID for a click, use the "click_view" resource:
 * https://developers.google.com/google-ads/api/fields/latest/click_view.
 * To set up a conversion action, run the AddConversionAction.php example.
 */
class UploadOfflineConversion
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const CONVERSION_ACTION_ID = 'INSERT_CONVERSION_ACTION_ID_HERE';
    // The Google Click ID for which conversions are uploaded.
    private const GCLID = 'INSERT_GCLID_HERE';
    // The conversion date time in "yyyy-mm-dd hh:mm:ss+|-hh:mm" format.
    private const CONVERSION_DATE_TIME = 'INSERT_CONVERSION_DATE_TIME_HERE';
    private const CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE';

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::CONVERSION_ACTION_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::GCLID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::CONVERSION_DATE_TIME => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::CONVERSION_VALUE => GetOpt::REQUIRED_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::CONVERSION_ACTION_ID] ?: self::CONVERSION_ACTION_ID,
                $options[ArgumentNames::GCLID] ?: self::GCLID,
                $options[ArgumentNames::CONVERSION_DATE_TIME] ?: self::CONVERSION_DATE_TIME,
                $options[ArgumentNames::CONVERSION_VALUE] ?: self::CONVERSION_VALUE
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
            exit(1);
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
            exit(1);
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param int $conversionActionId the ID of the conversion action to upload to
     * @param string $gclid the GCLID for the conversion (should be newer than the number of days
     *      set on the conversion window of the conversion action)
     * @param string $conversionDateTime 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.
     *      “2019-01-01 12:32:45-08:00”
     * @param float $conversionValue the value of the conversion
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $conversionActionId,
        string $gclid,
        string $conversionDateTime,
        float $conversionValue
    ) {
        // Creates a click conversion by specifying currency as USD.
        $clickConversion = new ClickConversion([
            'conversion_action' => new StringValue([
                'value' => ResourceNames::forConversionAction($customerId, $conversionActionId)
            ]),
            'gclid' => new StringValue(['value' => $gclid]),
            'conversion_value' => new DoubleValue(['value' => $conversionValue]),
            'conversion_date_time' => new StringValue(['value' => $conversionDateTime]),
            'currency_code' => new StringValue(['value' => 'USD']),
        ]);

        // Issues a request to upload the click conversion.
        $conversionUploadServiceClient = $googleAdsClient->getConversionUploadServiceClient();
        /** @var UploadClickConversionsResponse $response */
        $response = $conversionUploadServiceClient->uploadClickConversions(
            $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 (!is_null($response->getPartialFailureError())) {
            printf(
                "Partial failures occurred: '%s'.%s",
                $response->getPartialFailureError()->getMessage(),
                PHP_EOL
            );
        } else {
            // Prints the result if exists.
            /** @var ClickConversion $uploadedClickConversion */
            $uploadedClickConversion = $response->getResults()[0];
            printf(
                "Uploaded click conversion that occurred at '%s' from Google Click ID '%s' " .
                "to '%s'.%s",
                $uploadedClickConversion->getConversionDateTimeUnwrapped(),
                $uploadedClickConversion->getGclidUnwrapped(),
                $uploadedClickConversion->getConversionActionUnwrapped(),
                PHP_EOL
            );
        }
    }
}

UploadOfflineConversion::main();

Python

#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example imports offline conversion values for specific clicks.

To get Google Click ID for a click, use the "click_view" resource:
https://developers.google.com/google-ads/api/fields/latest/click_view.
To set up a conversion action, run the add_conversion_action.py example.
"""


import argparse
import sys

from google.ads.google_ads.client import GoogleAdsClient
from google.ads.google_ads.errors import GoogleAdsException


def main(client, customer_id, conversion_action_id, gclid, 
         conversion_date_time, conversion_value):
    """Creates a click conversion with a default currency of USD."""

    click_conversion = client.get_type('ClickConversion', version='v4')
    conversion_action_service = client.get_service('ConversionActionService',
                                                   version='v4')
    click_conversion.conversion_action.value = (
        conversion_action_service.conversion_action_path(
            customer_id, conversion_action_id))
    click_conversion.gclid.value = gclid
    click_conversion.conversion_value.value = float(conversion_value)
    click_conversion.conversion_date_time.value = conversion_date_time
    click_conversion.currency_code.value = 'USD'

    conversion_upload_service = client.get_service('ConversionUploadService',
                                                   version='v4')

    try:
        conversion_upload_response = (
            conversion_upload_service.upload_click_conversions(customer_id,
                [click_conversion], partial_failure=True))
        uploaded_click_conversion = conversion_upload_response.results[0]
        print(f'Uploaded conversion that occurred at '
              f'"{uploaded_click_conversion.conversion_date_time.value}" from '
              f'Google Click ID "{uploaded_click_conversion.gclid.value}" '
              f'to "{uploaded_click_conversion.conversion_action.value}"')
    except GoogleAdsException as ex:
        print(f'Request with ID "{ex.request_id}" failed with status '
              f'"{ex.error.code().name}" and includes the following errors:')
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f'\t\tOn field: {field_path_element.field_name}')
        sys.exit(1)


if __name__ == '__main__':
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    google_ads_client = GoogleAdsClient.load_from_storage()

    parser = argparse.ArgumentParser(
        description='Uploads an offline conversion.')
    # The following argument(s) should be provided to run the example.
    parser.add_argument('-c', '--customer_id', type=str,
                        required=True, help='The Google Ads customer ID.')
    parser.add_argument('-a', '--conversion_action_id', type=str,
                        required=True, help='The conversion action ID.')
    parser.add_argument('-g', '--gclid', type=str,
                        required=True, help='The Google Click Identifier ID '
                        '(gclid) which should be newer than the number of '
                        'days set on the conversion window of the conversion '
                        'action.')
    parser.add_argument('-t', '--conversion_date_time', type=str,
                        required=True, help='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. '
                        '“2019-01-01 12:32:45-08:00”')
    parser.add_argument('-v', '--conversion_value', type=str,
                        required=True, help='The conversion value.')
    args = parser.parse_args()

    main(google_ads_client, args.customer_id, args.conversion_action_id,
         args.gclid, args.conversion_date_time, args.conversion_value)

Perl

#!/usr/bin/perl -w
#
# Copyright 2019, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example imports offline conversion values for specific clicks to your account.
# To get Google Click ID for a click, use the "click_view" resource:
# https://developers.google.com/google-ads/api/fields/latest/click_view.
# To set up a conversion action, run the add_conversion_action.pl example.

use strict;
use warnings;
use utf8;

use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use
  Google::Ads::GoogleAds::V4::Services::ConversionUploadService::ClickConversion;
use Google::Ads::GoogleAds::V4::Utils::ResourceNames;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);

# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id          = "INSERT_CUSTOMER_ID_HERE";
my $conversion_action_id = "INSERT_CONVERSION_ACTION_ID_HERE";
my $gclid                = "INSERT_GCLID_HERE";
my $conversion_date_time = "INSERT_CONVERSION_DATE_TIME_HERE";
my $conversion_value     = "INSERT_CONVERSION_VALUE_HERE";

sub upload_offline_conversion {
  my ($api_client, $customer_id, $conversion_action_id, $gclid,
    $conversion_date_time, $conversion_value)
    = @_;

  # Create a click conversion by specifying currency as USD.
  my $click_conversion =
    Google::Ads::GoogleAds::V4::Services::ConversionUploadService::ClickConversion
    ->new({
      conversionAction =>
        Google::Ads::GoogleAds::V4::Utils::ResourceNames::conversion_action(
        $customer_id, $conversion_action_id
        ),
      gclid              => $gclid,
      conversionDateTime => $conversion_date_time,
      conversionValue    => $conversion_value,
      currencyCode       => "USD"
    });

  # Issue a request to upload the click conversion.
  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;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();

# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);

# Parameters passed on the command line will override any parameters set in code.
GetOptions(
  "customer_id=s"          => \$customer_id,
  "conversion_action_id=i" => \$conversion_action_id,
  "gclid=s"                => \$gclid,
  "conversion_date_time=s" => \$conversion_date_time,
  "conversion_value=f"     => \$conversion_value
);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2)
  if not check_params($customer_id, $conversion_action_id, $gclid,
  $conversion_date_time, $conversion_value);

# Call the example.
upload_offline_conversion($api_client, $customer_id =~ s/-//gr,
  $conversion_action_id, $gclid, $conversion_date_time, $conversion_value);

=pod

=head1 NAME

upload_offline_conversion

=head1 DESCRIPTION

This example imports offline conversion values for specific clicks to your account.
To get Google Click ID for a click, use the "click_view" resource:
https://developers.google.com/google-ads/api/fields/latest/click_view.
To set up a conversion action, run the add_conversion_action.pl example.

=head1 SYNOPSIS

upload_offline_conversion.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -conversion_action_id       The ID of the conversion action to upload to.
    -gclid                      The GCLID for the conversion (should be newer than the number of days
                                set on the conversion window of the conversion action).
    -conversion_date_time       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. "2019-01-01 12:32:45-08:00".
    -conversion_value           The value of the conversion.

=cut