Upload Conversion Adjustment

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.v16.enums.ConversionAdjustmentTypeEnum.ConversionAdjustmentType;
import com.google.ads.googleads.v16.errors.GoogleAdsError;
import com.google.ads.googleads.v16.errors.GoogleAdsException;
import com.google.ads.googleads.v16.errors.GoogleAdsFailure;
import com.google.ads.googleads.v16.services.ConversionAdjustment;
import com.google.ads.googleads.v16.services.ConversionAdjustmentResult;
import com.google.ads.googleads.v16.services.ConversionAdjustmentUploadServiceClient;
import com.google.ads.googleads.v16.services.GclidDateTimePair;
import com.google.ads.googleads.v16.services.RestatementValue;
import com.google.ads.googleads.v16.services.UploadConversionAdjustmentsRequest;
import com.google.ads.googleads.v16.services.UploadConversionAdjustmentsResponse;
import com.google.ads.googleads.v16.utils.ErrorUtils;
import com.google.ads.googleads.v16.utils.ResourceNames;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.annotation.Nullable;

/**
 * Imports conversion adjustments for conversions that already exist. To set up a conversion action,
 * run the AddConversionAction.java example.
 */
public class UploadConversionAdjustment {
  private static class UploadConversionAdjustmentParams 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.ADJUSTMENT_TYPE,
        required = true,
        description =
            "RETRACTION negates a conversion, and RESTATEMENT changes the value of a conversion.")
    private String adjustmentType;

    @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.ADJUSTMENT_DATE_TIME,
        required = true,
        description =
            "The date time at which the adjustment 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 adjustmentDateTime;

    @Parameter(
        names = ArgumentNames.RESTATEMENT_VALUE,
        description =
            "The updated value of the conversion. Only applicable for ADJUSTMENT_TYPE of"
                + " RESTATEMENT.")
    private Float restatementValue;
  }

  public static void main(String[] args) {
    UploadConversionAdjustmentParams params = new UploadConversionAdjustmentParams();
    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.adjustmentType = "INSERT_ADJUSTMENT_TYPE_HERE";
      params.conversionDateTime = "INSERT_CONVERSION_DATE_TIME_HERE";
      params.adjustmentDateTime = "INSERT_ADJUSTMENT_DATE_TIME_HERE";

      // Optional: Specify a restatement value for adjustments of type RESTATEMENT.
      params.restatementValue = null;
    }

    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 UploadConversionAdjustment()
          .runExample(
              googleAdsClient,
              params.customerId,
              params.conversionActionId,
              params.gclid,
              params.adjustmentType,
              params.conversionDateTime,
              params.adjustmentDateTime,
              params.restatementValue);
    } 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 adjustmentType the type of adjustment, e.g. RETRACTION, RESTATEMENT.
   * @param conversionDateTime date and time of the conversion.
   * @param adjustmentDateTime date and time of the adjustment.
   * @param restatementValue the adjusted value for adjustment type RESTATEMENT.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient,
      long customerId,
      long conversionActionId,
      String gclid,
      String adjustmentType,
      String conversionDateTime,
      String adjustmentDateTime,
      @Nullable Float restatementValue) {
    // Gets the conversion adjustment enum value from the adjustmentType String.
    ConversionAdjustmentType conversionAdjustmentType =
        ConversionAdjustmentType.valueOf(adjustmentType);

    // Associates conversion adjustments with the existing conversion action.
    // The GCLID should have been uploaded before with a conversion.
    ConversionAdjustment conversionAdjustment =
        ConversionAdjustment.newBuilder()
            .setConversionAction(ResourceNames.conversionAction(customerId, conversionActionId))
            .setAdjustmentType(conversionAdjustmentType)
            .setGclidDateTimePair(
                GclidDateTimePair.newBuilder()
                    .setGclid(gclid)
                    .setConversionDateTime(conversionDateTime)
                    .build())
            .setAdjustmentDateTime(adjustmentDateTime)
            .build();

    // Sets adjusted value for adjustment type RESTATEMENT.
    if (restatementValue != null
        && conversionAdjustmentType == ConversionAdjustmentType.RESTATEMENT) {
      conversionAdjustment =
          conversionAdjustment.toBuilder()
              .setRestatementValue(
                  RestatementValue.newBuilder().setAdjustedValue(restatementValue).build())
              .build();
    }

    // Creates the conversion upload service client.
    try (ConversionAdjustmentUploadServiceClient conversionUploadServiceClient =
        googleAdsClient.getLatestVersion().createConversionAdjustmentUploadServiceClient()) {
      // Uploads the click conversion. Partial failure should always be set to true.
      UploadConversionAdjustmentsResponse response =
          conversionUploadServiceClient.uploadConversionAdjustments(
              UploadConversionAdjustmentsRequest.newBuilder()
                  .setCustomerId(Long.toString(customerId))
                  .addConversionAdjustments(conversionAdjustment)
                  // Enables partial failure (must be true).
                  .setPartialFailure(true)
                  .build());

      // Prints any partial errors returned.
      if (response.hasPartialFailureError()) {
        GoogleAdsFailure googleAdsFailure =
            ErrorUtils.getInstance().getGoogleAdsFailure(response.getPartialFailureError());
        googleAdsFailure
            .getErrorsList()
            .forEach(e -> System.out.println("Partial failure occurred: " + e.getMessage()));
      } else {
        // Prints the result.
        ConversionAdjustmentResult result = response.getResults(0);
        System.out.printf(
            "Uploaded conversion adjustment of '%s' for Google Click ID '%s'.%n",
            result.getConversionAction(), result.getGclidDateTimePair().getGclid());
      }
    }
  }
}

      

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 CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V16.Errors;
using Google.Ads.GoogleAds.V16.Resources;
using Google.Ads.GoogleAds.V16.Services;
using System;
using System.Collections.Generic;
using static Google.Ads.GoogleAds.V16.Enums.ConversionAdjustmentTypeEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V16
{
    /// <summary>
    /// This code example imports conversion adjustments for conversions that already exist.
    /// To set up a conversion action, run AddConversionAction.cs.
    /// </summary>
    public class UploadConversionAdjustment : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="UploadConversionAdjustment"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the conversion action is added.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the conversion action is added.")]
            public long CustomerId { get; set; }

            /// <summary>
            /// ID of the conversion action for which adjustments are uploaded.
            /// </summary>
            [Option("conversionActionId", Required = true, HelpText =
                "ID of the conversion action for which adjustments are uploaded.")]
            public long ConversionActionId { get; set; }

            /// <summary>
            /// The type of adjustment.
            /// </summary>
            [Option("adjustmentType", Required = true, HelpText =
                "The type of adjustment.")]
            public ConversionAdjustmentType AdjustmentType { get; set; }

            /// <summary>
            /// The original conversion time.
            /// </summary>
            [Option("conversionDateTime", Required = true, HelpText =
                "The original conversion time.")]
            public string ConversionDateTime { get; set; }

            /// <summary>
            /// The Google Click ID for which adjustments are uploaded.
            /// </summary>
            [Option("gclid", Required = true, HelpText =
                "The Google Click ID for which adjustments are uploaded.")]
            public string Gclid { get; set; }

            /// <summary>
            /// The adjustment date and time.
            /// </summary>
            [Option("adjustmentDateTime", Required = true, HelpText =
                "The adjustment date and time.")]
            public string AdjustmentDateTime { get; set; }

            /// <summary>
            /// The restatement value.
            /// </summary>
            [Option("restatementValue", Required = true, HelpText =
                "The restatement value.")]
            public double? RestatementValue { get; set; }
        }

        /// <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)
        {
            Options options = ExampleUtilities.ParseCommandLine<Options>(args);

            UploadConversionAdjustment codeExample = new UploadConversionAdjustment();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.ConversionActionId,
                options.Gclid, options.ConversionDateTime, options.AdjustmentDateTime,
                options.AdjustmentType, options.RestatementValue);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example imports conversion adjustments for conversions that already " +
            "exist. To set up a conversion action, run AddConversionAction.cs.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the conversion action is
        /// added.</param>
        /// <param name="conversionActionId">ID of the conversion action for which adjustments are
        /// uploaded.</param>
        /// <param name="adjustmentType">The type of adjustment.</param>
        /// <param name="conversionDateTime">The original conversion time.</param>
        /// <param name="gclid">The Google Click ID for which adjustments are uploaded.</param>
        /// <param name="adjustmentDateTime">The adjustment date and time.</param>
        /// <param name="restatementValue">The restatement value.</param>
        public void Run(GoogleAdsClient client, long customerId, long conversionActionId,
            string gclid, string conversionDateTime, string adjustmentDateTime,
            ConversionAdjustmentType adjustmentType,
            double? restatementValue)
        {
            // Get the ConversionAdjustmentUploadService.
            ConversionAdjustmentUploadServiceClient conversionAdjustmentUploadService =
                client.GetService(Services.V16.ConversionAdjustmentUploadService);

            // Associate conversion adjustments with the existing conversion action.
            // The GCLID should have been uploaded before with a conversion.
            ConversionAdjustment conversionAdjustment = new ConversionAdjustment()
            {
                ConversionAction = ResourceNames.ConversionAction(customerId, conversionActionId),
                AdjustmentType = adjustmentType,
                GclidDateTimePair = new GclidDateTimePair()
                {
                    Gclid = gclid,
                    ConversionDateTime = conversionDateTime,
                },
                AdjustmentDateTime = adjustmentDateTime,
            };

            // Set adjusted value for adjustment type RESTATEMENT.
            if (adjustmentType == ConversionAdjustmentType.Restatement)
            {
                conversionAdjustment.RestatementValue = new RestatementValue()
                {
                    AdjustedValue = restatementValue.Value
                };
            }

            try
            {
                // Issue a request to upload the conversion adjustment.
                UploadConversionAdjustmentsResponse response =
                    conversionAdjustmentUploadService.UploadConversionAdjustments(
                        new UploadConversionAdjustmentsRequest()
                        {
                            CustomerId = customerId.ToString(),
                            ConversionAdjustments = { conversionAdjustment },
                            PartialFailure = true,
                            ValidateOnly = false
                        });

                ConversionAdjustmentResult result = response.Results[0];
                // Print the result.
                Console.WriteLine($"Uploaded conversion adjustment value of" +
                    $" '{result.ConversionAction}' for Google Click ID " +
                    $"'{result.GclidDateTimePair.Gclid}'");
            }
            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 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.
 */

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\V16\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V16\ResourceNames;
use Google\Ads\GoogleAds\V16\Enums\ConversionAdjustmentTypeEnum\ConversionAdjustmentType;
use Google\Ads\GoogleAds\V16\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V16\Services\ConversionAdjustment;
use Google\Ads\GoogleAds\V16\Services\ConversionAdjustmentResult;
use Google\Ads\GoogleAds\V16\Services\GclidDateTimePair;
use Google\Ads\GoogleAds\V16\Services\RestatementValue;
use Google\Ads\GoogleAds\V16\Services\UploadConversionAdjustmentsRequest;
use Google\ApiCore\ApiException;

/**
 * This example imports conversion adjustments for conversions that already exist.
 * To set up a conversion action, run the AddConversionAction.php example.
 */
class UploadConversionAdjustment
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const CONVERSION_ACTION_ID = 'INSERT_CONVERSION_ACTION_ID_HERE';
    private const GCLID = 'INSERT_GCLID_HERE';
    private const ADJUSTMENT_TYPE = "INSERT_ADJUSTMENT_TYPE_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';
    // The adjustment date time in "yyyy-mm-dd hh:mm:ss+|-hh:mm" format.
    private const ADJUSTMENT_DATE_TIME = "INSERT_ADJUSTMENT_DATE_TIME_HERE";
    // Optional: Specify an adjusted value below for adjustment type RESTATEMENT.
    // This value will be ignored if you specify RETRACTION as adjustment type.
    private const RESTATEMENT_VALUE = null;

    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::ADJUSTMENT_TYPE => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::CONVERSION_DATE_TIME => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::ADJUSTMENT_DATE_TIME => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::RESTATEMENT_VALUE => GetOpt::OPTIONAL_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)
            // We set this value to true to show how to use GAPIC v2 source code. You can remove the
            // below line if you wish to use the old-style source code. Note that in that case, you
            // probably need to modify some parts of the code below to make it work.
            // For more information, see
            // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic.
            ->usingGapicV2Source(true)
            ->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::ADJUSTMENT_TYPE] ?: self::ADJUSTMENT_TYPE,
                $options[ArgumentNames::CONVERSION_DATE_TIME] ?: self::CONVERSION_DATE_TIME,
                $options[ArgumentNames::ADJUSTMENT_DATE_TIME] ?: self::ADJUSTMENT_DATE_TIME,
                $options[ArgumentNames::RESTATEMENT_VALUE] ?: self::RESTATEMENT_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 adjustment to
     * @param string $gclid the GCLID for the conversion
     * @param string $adjustmentType the type of adjustment, e.g. RETRACTION, RESTATEMENT
     * @param string $conversionDateTime the date and time of the conversion.
     *      The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", e.g. “2019-01-01 12:32:45-08:00”
     * @param string $adjustmentDateTime the date and time of the adjustment.
     *      The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", e.g. “2019-01-01 12:32:45-08:00”
     * @param float|null $restatementValue the adjusted value for adjustment type RESTATEMENT
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $conversionActionId,
        string $gclid,
        string $adjustmentType,
        string $conversionDateTime,
        string $adjustmentDateTime,
        float $restatementValue
    ) {
        $conversionAdjustmentType = ConversionAdjustmentType::value($adjustmentType);

        // Associates conversion adjustments with the existing conversion action.
        // The GCLID should have been uploaded before with a conversion.
        $conversionAdjustment = new ConversionAdjustment([
            'conversion_action' =>
                ResourceNames::forConversionAction($customerId, $conversionActionId),
            'adjustment_type' => $conversionAdjustmentType,
            'gclid_date_time_pair' => new GclidDateTimePair([
                'gclid' => $gclid,
                'conversion_date_time' => $conversionDateTime
            ]),
            'adjustment_date_time' => $adjustmentDateTime
        ]);

        // Sets adjusted value for adjustment type RESTATEMENT.
        if (
            $restatementValue !== null
            && $conversionAdjustmentType === ConversionAdjustmentType::RESTATEMENT
        ) {
            $conversionAdjustment->setRestatementValue(new RestatementValue([
                'adjusted_value' => $restatementValue
            ]));
        }

        // Issues a request to upload the conversion adjustment.
        $conversionAdjustmentUploadServiceClient =
            $googleAdsClient->getConversionAdjustmentUploadServiceClient();
        $response = $conversionAdjustmentUploadServiceClient->uploadConversionAdjustments(
            UploadConversionAdjustmentsRequest::build($customerId, [$conversionAdjustment], 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 ConversionAdjustmentResult $uploadedConversionAdjustment */
            $uploadedConversionAdjustment = $response->getResults()[0];
            printf(
                "Uploaded conversion adjustment of '%s' for Google Click ID '%s'.%s",
                $uploadedConversionAdjustment->getConversionAction(),
                $uploadedConversionAdjustment->getGclidDateTimePair()->getGclid(),
                PHP_EOL
            );
        }
    }
}

UploadConversionAdjustment::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 conversion adjustments for existing conversions.

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,
    adjustment_type,
    conversion_date_time,
    adjustment_date_time,
    restatement_value,
):
    conversion_adjustment_type_enum = client.enums.ConversionAdjustmentTypeEnum
    # Determine the adjustment type.
    conversion_adjustment_type = conversion_adjustment_type_enum[
        adjustment_type
    ].value

    # Associates conversion adjustments with the existing conversion action.
    # The GCLID should have been uploaded before with a conversion
    conversion_adjustment = client.get_type("ConversionAdjustment")
    conversion_action_service = client.get_service("ConversionActionService")
    conversion_adjustment.conversion_action = (
        conversion_action_service.conversion_action_path(
            customer_id, conversion_action_id
        )
    )
    conversion_adjustment.adjustment_type = conversion_adjustment_type
    conversion_adjustment.adjustment_date_time = adjustment_date_time

    # Set the Gclid Date
    conversion_adjustment.gclid_date_time_pair.gclid = gclid
    conversion_adjustment.gclid_date_time_pair.conversion_date_time = (
        conversion_date_time
    )

    # Sets adjusted value for adjustment type RESTATEMENT.
    if (
        restatement_value
        and conversion_adjustment_type
        == conversion_adjustment_type_enum.RESTATEMENT.value
    ):
        conversion_adjustment.restatement_value.adjusted_value = float(
            restatement_value
        )

    conversion_adjustment_upload_service = client.get_service(
        "ConversionAdjustmentUploadService"
    )
    request = client.get_type("UploadConversionAdjustmentsRequest")
    request.customer_id = customer_id
    request.conversion_adjustments = [conversion_adjustment]
    request.partial_failure = True
    response = (
        conversion_adjustment_upload_service.upload_conversion_adjustments(
            request=request,
        )
    )
    conversion_adjustment_result = response.results[0]
    print(
        f"Uploaded conversion that occurred at "
        f'"{conversion_adjustment_result.adjustment_date_time}" '
        f"from Gclid "
        f'"{conversion_adjustment_result.gclid_date_time_pair.gclid}"'
        f' to "{conversion_adjustment_result.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="v16")

    parser = argparse.ArgumentParser(
        description="Uploads a conversion adjustment."
    )
    # 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 to be " "uploaded to.",
    )
    parser.add_argument(
        "-g",
        "--gclid",
        type=str,
        required=True,
        help="The Google Click Identifier ID.",
    )
    parser.add_argument(
        "-d",
        "--adjustment_type",
        type=str,
        required=True,
        choices=[
            e.name for e in googleads_client.enums.ConversionAdjustmentTypeEnum
        ],
        help="The Adjustment type, e.g. " "RETRACTION, RESTATEMENT",
    )
    parser.add_argument(
        "-t",
        "--conversion_date_time",
        type=str,
        required=True,
        help="The the date and time of the "
        "conversion. 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",
        "--adjustment_date_time",
        type=str,
        required=True,
        help="The the date and time of the "
        "adjustment. The format is "
        '"yyyy-mm-dd hh:mm:ss+|-hh:mm", e.g. '
        "“2019-01-01 12:32:45-08:00”",
    )
    # Optional: Specify an adjusted value for adjustment type RESTATEMENT.
    # This value will be ignored if you specify RETRACTION as adjustment type.
    parser.add_argument(
        "-r",
        "--restatement_value",
        type=str,
        required=False,
        help="The adjusted value for " "adjustment type RESTATEMENT.",
    )
    args = parser.parse_args()

    try:
        main(
            googleads_client,
            args.customer_id,
            args.conversion_action_id,
            args.gclid,
            args.adjustment_type,
            args.conversion_date_time,
            args.adjustment_date_time,
            args.restatement_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

#
# 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 conversion adjustments for conversions that already exist.
# To set up a conversion action, run add_conversion_action.rb.

require 'optparse'
require 'google/ads/google_ads'

def upload_conversion_adjustment(
  customer_id,
  conversion_action_id,
  gclid,
  adjustment_type,
  conversion_date_time,
  adjustment_date_time,
  restatement_value
)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  # Associate conversion adjustments with the existing conversion action.
  # The GCLID should have been uploaded before with a conversion.
  conversion_adjustment = client.resource.conversion_adjustment do |ca|
    ca.conversion_action = client.path.conversion_action(customer_id, conversion_action_id)
    ca.adjustment_type = adjustment_type
    ca.gclid_date_time_pair = client.resource.gclid_date_time_pair do |gdtp|
      gdtp.gclid = gclid
      gdtp.conversion_date_time = conversion_date_time
    end
    ca.adjustment_date_time = adjustment_date_time

    # Set adjusted value for adjustment type RESTATEMENT.
    if adjustment_type == :RESTATEMENT
      ca.restatement_value = client.resource.restatement_value do |ra|
        ra.adjusted_value = restatement_value.to_f
      end
    end
  end

  # Issue a request to upload the conversion adjustment(s).
  response = client.service.conversion_adjustment_upload.upload_conversion_adjustments(
    customer_id: customer_id,
    # This example shows just one adjustment but you may upload multiple ones.
    conversion_adjustments: [conversion_adjustment],
    partial_failure: true
  )

  if response.partial_failure_error.nil?
    # Process and print all results for multiple adjustments
    response.results.each do |result|
      puts "Uploaded conversion adjustment at #{result.adjustment_date_time} " \
      "for adjustment #{result.adjustment_type} to #{result.conversion_action}."
    end
  else
    # Print any partial errors returned.
    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'
  # RETRACTION negates a conversion, and RESTATEMENT changes the value of a
  # conversion.
  options[:adjustment_type] = 'INSERT_ADJUSTMENT_TYPE_HERE'
  options[:conversion_date_time] = 'INSERT_CONVERSION_DATE_TIME_HERE'
  options[:adjustment_date_time] = 'INSERT_ADJUSTMENT_DATE_TIME_HERE'
  # Optional: Specify an adjusted value below for adjustment type RESTATEMENT.
  # This value will be ignored if you specify RETRACTION as adjustment type.
  options[:restatement_value] = 'INSERT_RESTATEMENT_VALUE_HERE'

  OptionParser.new do |opts|
    opts.banner = format('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('-a', '--adjustment-type ADJUSTMENT-TYPE', String,
            'Adjustment Type, e.g. RETRACTION, RESTATEMENT') do |v|
      options[:adjustment_type] = v
    end

    opts.on('-o', '--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", '\
            'e.g. "2019-01-01 12:32:45-08:00".') do |v|
      options[:conversion_date_time] = v
    end

    opts.on('-A', '--adjustment-date-time ADJUSTMENT-DATE-TIME', String,
            'The date and time of the adjustment. '\
            'The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", '\
            'e.g. "2019-01-01 12:32:45-08:00".') do |v|
      options[:adjustment_date_time] = v
    end

    opts.on('-r', '--restatement-value RESTATEMENT-VALUE', String,
            '[optional] The adjusted value for adjustment type RESTATEMENT.') do |v|
      options[:restatement_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_conversion_adjustment(
      options.fetch(:customer_id).tr('-', ''),
      options.fetch(:conversion_action_id),
      options.fetch(:gclid),
      options.fetch(:adjustment_type).to_sym,
      options.fetch(:conversion_date_time),
      options.fetch(:adjustment_date_time),
      options.fetch(:restatement_value)
    )
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      error.location&.field_path_elements&.each do |field_path_element|
        STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
      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
    raise
  end
end

      

Perl

#!/usr/bin/perl -w
#
# 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.
#
# This example imports conversion adjustments for conversions that already exist.
# To set up a conversion action, run add_conversion_action.pl.

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::V16::Enums::ConversionAdjustmentTypeEnum
  qw(RESTATEMENT);
use
  Google::Ads::GoogleAds::V16::Services::ConversionAdjustmentUploadService::ConversionAdjustment;
use
  Google::Ads::GoogleAds::V16::Services::ConversionAdjustmentUploadService::GclidDateTimePair;
use
  Google::Ads::GoogleAds::V16::Services::ConversionAdjustmentUploadService::RestatementValue;
use Google::Ads::GoogleAds::V16::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";
# RETRACTION negates a conversion, and RESTATEMENT changes the value of a conversion.
my $adjustment_type      = "INSERT_ADJUSTMENT_TYPE_HERE";
my $conversion_date_time = "INSERT_CONVERSION_DATE_TIME_HERE";
my $adjustment_date_time = "INSERT_ADJUSTMENT_DATE_TIME_HERE";
# Optional: Specify an adjusted value below for adjustment type RESTATEMENT.
# This value will be ignored if you specify RETRACTION as adjustment type.
my $restatement_value = undef;

sub upload_conversion_adjustment {
  my ($api_client, $customer_id, $conversion_action_id, $gclid,
    $adjustment_type, $conversion_date_time, $adjustment_date_time,
    $restatement_value)
    = @_;

  # Associate conversion adjustments with the existing conversion action.
  # The GCLID should have been uploaded before with a conversion.
  my $conversion_adjustment =
    Google::Ads::GoogleAds::V16::Services::ConversionAdjustmentUploadService::ConversionAdjustment
    ->new({
      conversionAction =>
        Google::Ads::GoogleAds::V16::Utils::ResourceNames::conversion_action(
        $customer_id, $conversion_action_id
        ),
      adjustmentType    => $adjustment_type,
      gclidDateTimePair =>
        Google::Ads::GoogleAds::V16::Services::ConversionAdjustmentUploadService::GclidDateTimePair
        ->new({
          gclid              => $gclid,
          conversionDateTime => $conversion_date_time
        }
        ),
      adjustmentDateTime => $adjustment_date_time,
    });

  # Set adjusted value for adjustment type RESTATEMENT.
  $conversion_adjustment->{restatementValue} =
    Google::Ads::GoogleAds::V16::Services::ConversionAdjustmentUploadService::RestatementValue
    ->new({
      adjustedValue => $restatement_value
    }) if defined $restatement_value && $adjustment_type eq RESTATEMENT;

  # Issue a request to upload the conversion adjustment.
  my $upload_conversion_adjustments_response =
    $api_client->ConversionAdjustmentUploadService()
    ->upload_conversion_adjustments({
      customerId            => $customer_id,
      conversionAdjustments => [$conversion_adjustment],
      partialFailure        => "true"
    });

  # Print any partial errors returned.
  if ($upload_conversion_adjustments_response->{partialFailureError}) {
    printf "Partial error encountered: '%s'.\n",
      $upload_conversion_adjustments_response->{partialFailureError}{message};
  }

  # Print the result if valid.
  my $uploaded_conversion_adjustment =
    $upload_conversion_adjustments_response->{results}[0];
  if (%$uploaded_conversion_adjustment) {
    printf "Uploaded conversion adjustment of the conversion action " .
      "with resource name '%s' for Google Click ID '%s'.\n",
      $uploaded_conversion_adjustment->{conversionAction},
      $uploaded_conversion_adjustment->{gclidDateTimePair}{gclid};
  }

  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,
  "adjustment_type=s"      => \$adjustment_type,
  "conversion_date_time=s" => \$conversion_date_time,
  "adjustment_date_time=s" => \$adjustment_date_time,
  "restatement_value=f"    => \$restatement_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,
  $adjustment_type, $conversion_date_time, $adjustment_date_time);

# Call the example.
upload_conversion_adjustment($api_client, $customer_id =~ s/-//gr,
  $conversion_action_id, $gclid,
  $adjustment_type, $conversion_date_time, $adjustment_date_time,
  $restatement_value);

=pod

=head1 NAME

upload_conversion_adjustment

=head1 DESCRIPTION

This example imports conversion adjustments for conversions that already exist.
To set up a conversion action, run add_conversion_action.pl.

=head1 SYNOPSIS

upload_conversion_adjustment.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.
    -adjustment_type            The type of adjustment, e.g. RETRACTION, RESTATEMENT.
    -conversion_date_time       The date and time of the conversion.
                                The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", e.g. "2019-01-01 12:32:45-08:00".
    -adjustment_date_time       The date and time of the adjustment.
                                The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", e.g. "2019-01-01 12:32:45-08:00".
    -restatement_value          [optional] The adjusted value for adjustment type RESTATEMENT.

=cut