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.v6.errors.GoogleAdsError; import com.google.ads.googleads.v6.errors.GoogleAdsException; import com.google.ads.googleads.v6.services.ClickConversion; import com.google.ads.googleads.v6.services.ClickConversionResult; import com.google.ads.googleads.v6.services.ConversionUploadServiceClient; import com.google.ads.googleads.v6.services.UploadClickConversionsRequest; import com.google.ads.googleads.v6.services.UploadClickConversionsResponse; import com.google.ads.googleads.v6.utils.ResourceNames; 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 = null; try { googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build(); } catch (FileNotFoundException fnfe) { System.err.printf( "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe); System.exit(1); } catch (IOException ioe) { System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe); System.exit(1); } 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); } System.exit(1); } } /** * 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(conversionActionResourceName) .setConversionDateTime(conversionDateTime) .setConversionValue(conversionValue) .setCurrencyCode("USD") .setGclid(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(), result.getGclid(), result.getConversionAction()); } } } }
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.V6.Errors; using Google.Ads.GoogleAds.V6.Services; using System; namespace Google.Ads.GoogleAds.Examples.V6 { /// <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 => "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.V6.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\V6\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V6\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V6\GoogleAdsException; use Google\Ads\GoogleAds\Util\V6\ResourceNames; use Google\Ads\GoogleAds\V6\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V6\Services\ClickConversion; use Google\Ads\GoogleAds\V6\Services\ClickConversionResult; use Google\Ads\GoogleAds\V6\Services\UploadClickConversionsResponse; use Google\ApiCore\ApiException; /** * 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' => ResourceNames::forConversionAction($customerId, $conversionActionId), 'gclid' => $gclid, 'conversion_value' => $conversionValue, 'conversion_date_time' => $conversionDateTime, 'currency_code' => '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 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 ); } } } 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.googleads.client import GoogleAdsClient from google.ads.googleads.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") conversion_action_service = client.get_service("ConversionActionService") click_conversion.conversion_action = ( conversion_action_service.conversion_action_path( customer_id, conversion_action_id ) ) click_conversion.gclid = gclid click_conversion.conversion_value = float(conversion_value) click_conversion.conversion_date_time = conversion_date_time click_conversion.currency_code = "USD" conversion_upload_service = client.get_service("ConversionUploadService") request = client.get_type("UploadClickConversionsRequest") request.customer_id = customer_id request.conversions = [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}"' ) if __name__ == "__main__": # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. googleads_client = GoogleAdsClient.load_from_storage(version="v6") 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() try: main( googleads_client, args.customer_id, args.conversion_action_id, args.gclid, args.conversion_date_time, args.conversion_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)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # 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.rb example. require 'optparse' require 'google/ads/google_ads' def upload_offline_conversion(customer_id, conversion_action_id, gclid, conversion_date_time, conversion_value) # GoogleAdsClient will read a config file from # ENV['HOME']/google_ads_config.rb when called without parameters client = Google::Ads::GoogleAds::GoogleAdsClient.new click_conversion = client.resource.click_conversion do |cc| cc.conversion_action = client.path.conversion_action(customer_id, conversion_action_id) cc.gclid = gclid cc.conversion_value = conversion_value.to_f cc.conversion_date_time = conversion_date_time cc.currency_code = 'USD' end response = client.service.conversion_upload.upload_click_conversions( customer_id: customer_id, 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 if __FILE__ == $0 options = {} # 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. options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE' options[:conversion_action_id] = 'INSERT_CONVERSION_ACTION_ID_HERE' options[:gclid] = 'INSERT_GCLID_HERE' options[:conversion_date_time] = 'INSERT_CONVERSION_DATE_TIME_HERE' options[:conversion_value] = 'INSERT_CONVERSION_VALUE_HERE' OptionParser.new do |opts| opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__)) opts.separator '' opts.separator 'Options:' opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v| options[:customer_id] = v end opts.on('-c', '--conversion-action-id CONVERSION-ACTION-ID', String, 'Conversion Action ID') do |v| options[:conversion_action_id] = v end opts.on('-g', '--gclid GCLID', String, 'Google Click ID (should be newer than the number of days set ' \ 'on the conversion window of the conversion action).') do |v| options[:gclid] = v end opts.on('-t', '--conversion-date-time CONVERSION-DATE-TIME', String, 'The date and time of the conversion (should be after click time). ' \ 'The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", ' \ 'for example: “2019-01-01 12:32:45-08:00”') do |v| options[:conversion_date_time] = v end opts.on('-v', '--conversion-value CONVERSION-VALUE', String, 'Conversion Value') do |v| options[:conversion_value] = v end opts.separator '' opts.separator 'Help:' opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end end.parse! begin upload_offline_conversion( options.fetch(:customer_id).tr("-", ""), options.fetch(:conversion_action_id), options.fetch(:gclid), options.fetch(:conversion_date_time), options.fetch(:conversion_value), ) rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e e.failure.errors.each do |error| STDERR.printf("Error with message: %s\n", error.message) if error.location error.location.field_path_elements.each do |field_path_element| STDERR.printf("\tOn field: %s\n", field_path_element.field_name) end end error.error_code.to_h.each do |k, v| next if v == :UNSPECIFIED STDERR.printf("\tType: %s\n\tCode: %s\n", k, v) end end end end
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::V6::Services::ConversionUploadService::ClickConversion; use Google::Ads::GoogleAds::V6::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::V6::Services::ConversionUploadService::ClickConversion ->new({ conversionAction => Google::Ads::GoogleAds::V6::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