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.v17.enums.ConversionAdjustmentTypeEnum.ConversionAdjustmentType;
import com.google.ads.googleads.v17.errors.GoogleAdsError;
import com.google.ads.googleads.v17.errors.GoogleAdsException;
import com.google.ads.googleads.v17.errors.GoogleAdsFailure;
import com.google.ads.googleads.v17.services.ConversionAdjustment;
import com.google.ads.googleads.v17.services.ConversionAdjustmentResult;
import com.google.ads.googleads.v17.services.ConversionAdjustmentUploadServiceClient;
import com.google.ads.googleads.v17.services.RestatementValue;
import com.google.ads.googleads.v17.services.UploadConversionAdjustmentsRequest;
import com.google.ads.googleads.v17.services.UploadConversionAdjustmentsResponse;
import com.google.ads.googleads.v17.utils.ErrorUtils;
import com.google.ads.googleads.v17.utils.ResourceNames;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import com.google.protobuf.util.JsonFormat.Printer;
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.ORDER_ID,
        required = true,
        description =
            "The transaction ID of the conversion to adjust. Required if the conversion being"
                + " adjusted meets the criteria described at"
                + " https://developers.google.com/google-ads/api/docs/conversions/upload-adjustments#requirements.")
    private String orderId;

    @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.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) throws InvalidProtocolBufferException {
    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.orderId = "INSERT_ORDER_ID_HERE";
      params.adjustmentType = "INSERT_ADJUSTMENT_TYPE_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.orderId,
              params.adjustmentType,
              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 orderId the orderId for the conversion. Strongly recommended instead of using {@code
   *     gclid} and {@code conversionDateTime}.
   * @param adjustmentType the type of adjustment, e.g. RETRACTION, RESTATEMENT.
   * @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 orderId,
      String adjustmentType,
      String adjustmentDateTime,
      @Nullable Float restatementValue)
      throws InvalidProtocolBufferException {
    // Gets the conversion adjustment enum value from the adjustmentType String.
    ConversionAdjustmentType conversionAdjustmentType =
        ConversionAdjustmentType.valueOf(adjustmentType);

    // Applies the conversion adjustment to the existing conversion.
    ConversionAdjustment conversionAdjustment =
        ConversionAdjustment.newBuilder()
            .setConversionAction(ResourceNames.conversionAction(customerId, conversionActionId))
            .setAdjustmentType(conversionAdjustmentType)
            // Sets the orderId to identify the conversion to adjust.
            .setOrderId(orderId)
            // As an alternative to setting orderId, you can provide a GclidDateTimePair, but
            // setting orderId instead is strongly recommended.
            // .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.
      UploadConversionAdjustmentsRequest request =
          UploadConversionAdjustmentsRequest.newBuilder()
              .setCustomerId(Long.toString(customerId))
              // Enables partial failure (must be true).
              .setPartialFailure(true)
              .addConversionAdjustments(conversionAdjustment)
              .build();
      UploadConversionAdjustmentsResponse response =
          conversionUploadServiceClient.uploadConversionAdjustments(request);

      // Extracts the partial failure error if present on the response.
      ErrorUtils errorUtils = ErrorUtils.getInstance();
      GoogleAdsFailure googleAdsFailure =
          response.hasPartialFailureError()
              ? errorUtils.getGoogleAdsFailure(response.getPartialFailureError())
              : null;

      // Constructs a protocol buffer printer that will print error details in a concise format.
      final Printer errorPrinter = JsonFormat.printer().omittingInsignificantWhitespace();
      // Prints the results for each adjustment, including any partial errors returned.
      for (int opIndex = 0; opIndex < request.getConversionAdjustmentsCount(); opIndex++) {
        ConversionAdjustmentResult result = response.getResults(opIndex);
        if (errorUtils.isPartialFailureResult(result)) {
          // The operation failed. Prints the error details.
          for (GoogleAdsError googleAdsError :
              errorUtils.getGoogleAdsErrors(opIndex, googleAdsFailure)) {
            System.out.printf(
                "%4d: Partial failure occurred: %s%n", opIndex, errorPrinter.print(googleAdsError));
          }
        } else {
          System.out.printf(
              "%4d: Uploaded conversion adjustment for conversion action '%s' and order ID '%s'.%n",
              opIndex, result.getConversionAction(), result.getOrderId());
        }
      }
    }
  }
}

      

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

namespace Google.Ads.GoogleAds.Examples.V17
{
    /// <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 transaction ID of the conversion to adjust. Required if the conversion being
            /// adjusted meets the criteria described at
            /// https://developers.google.com/google-ads/api/docs/conversions/upload-adjustments#requirements.
            /// </summary>
            [Option("orderId", Required = true, HelpText =
                "The transaction ID of the conversion to adjust. Required if the conversion " +
                "being adjusted meets the criteria described at " +
                "https://developers.google.com/google-ads/api/docs/conversions/upload-adjustments#requirements."
            )]
            public string OrderId { 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.OrderId, 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="orderId">The order ID for the conversion. Strongly recommended instead
        /// of using GCLID and conversionDateTime.</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 orderId, string adjustmentDateTime,
            ConversionAdjustmentType adjustmentType,
            double? restatementValue)
        {
            // Get the ConversionAdjustmentUploadService.
            ConversionAdjustmentUploadServiceClient conversionAdjustmentUploadService =
                client.GetService(Services.V17.ConversionAdjustmentUploadService);

            // Associate conversion adjustments with the existing conversion action.
            ConversionAdjustment conversionAdjustment = new ConversionAdjustment()
            {
                ConversionAction = ResourceNames.ConversionAction(customerId, conversionActionId),
                AdjustmentType = adjustmentType,
                // Sets the orderId to identify the conversion to adjust.
                OrderId = orderId,
                // As an alternative to setting orderId, you can provide a GclidDateTimePair,
                // but setting orderId instead is strongly recommended.
                //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 },
                            // Enables partial failure (must be true).
                            PartialFailure = true,
                            ValidateOnly = false
                        });

                // Prints any partial errors returned.
                // To review the overall health of your recent uploads, see:
                // https://developers.google.com/google-ads/api/docs/conversions/upload-summaries
                if (response.PartialFailureError != null)
                {
                    // Extracts the partial failure from the response status.
                    GoogleAdsFailure partialFailure = response.PartialFailure;
                    Console.WriteLine($"{partialFailure.Errors.Count} partial failure error(s) " +
                        $"occurred");
                }
                else
                {
                    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\V17\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V17\ResourceNames;
use Google\Ads\GoogleAds\V17\Enums\ConversionAdjustmentTypeEnum\ConversionAdjustmentType;
use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V17\Services\ConversionAdjustment;
use Google\Ads\GoogleAds\V17\Services\ConversionAdjustmentResult;
use Google\Ads\GoogleAds\V17\Services\GclidDateTimePair;
use Google\Ads\GoogleAds\V17\Services\RestatementValue;
use Google\Ads\GoogleAds\V17\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';
    // The transaction ID of the conversion to adjust. Required if the conversion being adjusted
    // meets the criteria described at
    // https://developers.google.com/google-ads/api/docs/conversions/upload-adjustments#requirements.
    private const ORDER_ID = 'INSERT_ORDER_ID_HERE';
    // RETRACTION negates a conversion, and RESTATEMENT changes the value of a conversion.
    private const ADJUSTMENT_TYPE = "INSERT_ADJUSTMENT_TYPE_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::ORDER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::ADJUSTMENT_TYPE => 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)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::CONVERSION_ACTION_ID] ?: self::CONVERSION_ACTION_ID,
                $options[ArgumentNames::ORDER_ID] ?: self::ORDER_ID,
                $options[ArgumentNames::ADJUSTMENT_TYPE] ?: self::ADJUSTMENT_TYPE,
                $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 $orderId the order ID for the conversion. Strongly recommended instead of
     *     using GCLID and conversion date time
     * @param string $adjustmentType the type of adjustment, e.g. RETRACTION, RESTATEMENT
     * @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 $orderId,
        string $adjustmentType,
        string $adjustmentDateTime,
        ?float $restatementValue
    ) {
        $conversionAdjustmentType = ConversionAdjustmentType::value($adjustmentType);

        // Applies the conversion adjustment to the existing conversion.
        $conversionAdjustment = new ConversionAdjustment([
            'conversion_action' =>
                ResourceNames::forConversionAction($customerId, $conversionActionId),
            'adjustment_type' => $conversionAdjustmentType,
            // Sets the orderId to identify the conversion to adjust.
            'order_id' => $orderId,
            // As an alternative to setting orderId, you can provide a 'gclid_date_time_pair', but
            // setting 'order_id' instead is strongly recommended.
            // 'conversion_date_time' must be in "yyyy-mm-dd hh:mm:ss+|-hh:mm" format.
            /*
            'gclid_date_time_pair' => new GclidDateTimePair([
                'gclid' => 'INSERT_YOUR_GCLID_HERE',
                'conversion_date_time' => 'INSERT_YOUR_CONVERSION_DATE_TIME_HERE'
            ]),
            */
            '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(
            // Enables partial failure (must be true).
            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 order ID '%s'.%s",
                $uploadedConversionAdjustment->getConversionAction(),
                $uploadedConversionAdjustment->getOrderId(),
                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,
    adjustment_type,
    order_id,
    adjustment_date_time,
    restatement_value=None,
):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        conversion_action_id: the ID of the conversion action to upload the
            adjustment to.
        adjustment_type: the adjustment type, e.g. " "RETRACTION, RESTATEMENT.
        order_id: the transaction ID of the conversion to adjust. Strongly
            recommended instead of using gclid and conversion_date_time.
        adjustment_date_time: the date and time of the adjustment.
        restatement_value: the adjusted value for adjustment type RESTATEMENT.
    """
    conversion_adjustment_type_enum = client.enums.ConversionAdjustmentTypeEnum
    # Determine the adjustment type.
    conversion_adjustment_type = conversion_adjustment_type_enum[
        adjustment_type
    ].value

    # Applies the conversion adjustment to the existing 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

    # Sets the order_id to identify the conversion to adjust.
    conversion_adjustment.order_id = order_id

    # As an alternative to setting order_id, you can provide a
    # gclid_date_time_pair, but setting order_id instead is strongly recommended.
    # 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
        )

    # Uploads the click conversion. Partial failure should always be set to
    # true.
    service = client.get_service("ConversionAdjustmentUploadService")
    request = client.get_type("UploadConversionAdjustmentsRequest")
    request.customer_id = customer_id
    request.conversion_adjustments.append(conversion_adjustment)
    # Enables partial failure (must be true)
    request.partial_failure = True

    response = service.upload_conversion_adjustments(request=request)

    # Extracts the partial failure error if present on the response.
    if response.partial_failure_error:
        error_details = response.partial_failure_error.details

    for i, conversion_adjustment_result in enumerate(response.results):
        # If there's a GoogleAdsFailure in error_details at this position then
        # the uploaded operation failed and we print the error message.
        if error_details and error_details[i]:
            error_detail = error_details[i]
            failure_message = client.get_type("GoogleAdsFailure")
            # Parse the string into a GoogleAdsFailure message instance.
            # To access class-only methods on the message we retrieve its type.
            GoogleAdsFailure = type(failure_message)
            failure_object = GoogleAdsFailure.deserialize(error_detail.value)

            for error in failure_object.errors:
                # Construct and print a string that details which element in
                # the operation list failed (by index number) as well as the
                # error message and error code.
                print(
                    "A partial failure at index "
                    f"{error.location.field_path_elements[0].index} occurred "
                    f"\nError message: {error.message}\nError code: "
                    f"{error.error_code}"
                )
        else:
            print(
                "Uploaded conversion adjustment for conversion action "
                f"'{conversion_adjustment_result.conversion_action}' and order "
                f"ID '{conversion_adjustment_result.order_id}'."
            )


if __name__ == "__main__":
    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 ID of the conversion action to upload the adjustment to.",
    )
    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(
        "-o",
        "--order_id",
        type=str,
        required=True,
        help=(
            "The transaction ID of the conversion to adjust. Required if the "
            "conversion being adjusted meets the criteria described at: "
            "https://developers.google.com/google-ads/api/docs/conversions/upload-adjustments#requirements."
        ),
    )
    parser.add_argument(
        "-v",
        "--adjustment_date_time",
        type=str,
        required=True,
        help=(
            "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()

    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v17")

    try:
        main(
            googleads_client,
            args.customer_id,
            args.conversion_action_id,
            args.adjustment_type,
            args.order_id,
            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,
  order_id,
  adjustment_type,
  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

  # Applies the conversion adjustment to the existing 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.order_id = order_id
    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 for conversion action #{result.conversion_action} "\
        "and order ID #{result.order_id}."
    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|
        index = error.location.field_path_elements.first.index
        puts "\toperation[#{index}] #{error.error_code.error_code}: #{error.message}"
      end
    end
  end
end

if __FILE__ == $0
  options = {}
  # Running the example with -h will print the command line usage.

  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('-O', '--order-id ORDER-ID', String,
            'The transaction ID of the conversion to adjust. Required if the conversion being '\
            'adjusted meets the criteria described at '\
            'https://developers.google.com/google-ads/api/docs/conversions/upload-adjustments#requirements.'
        ) do |v|
      options[:order_id] = v
    end

    opts.on('-a', '--adjustment-type ADJUSTMENT-TYPE', String,
            'RETRACTION negates a conversion, and RESTATEMENT changes the value of a conversion.') do |v|
      options[:adjustment_type] = 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(:order_id),
      options.fetch(:adjustment_type).to_sym,
      options.fetch(:adjustment_date_time),
      options[: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::V17::Enums::ConversionAdjustmentTypeEnum
  qw(RESTATEMENT);
use
  Google::Ads::GoogleAds::V17::Services::ConversionAdjustmentUploadService::ConversionAdjustment;
use
  Google::Ads::GoogleAds::V17::Services::ConversionAdjustmentUploadService::GclidDateTimePair;
use
  Google::Ads::GoogleAds::V17::Services::ConversionAdjustmentUploadService::RestatementValue;
use Google::Ads::GoogleAds::V17::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";
# The transaction ID of the conversion to adjust. Required if the conversion
# being adjusted meets the criteria described at
# https://developers.google.com/google-ads/api/docs/conversions/upload-adjustments#requirements.
my $order_id = "INSERT_ORDER_ID_HERE";
# RETRACTION negates a conversion, and RESTATEMENT changes the value of a conversion.
my $adjustment_type      = "INSERT_ADJUSTMENT_TYPE_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, $order_id,
    $adjustment_type, $adjustment_date_time, $restatement_value)
    = @_;

  # Applies the conversion adjustment to the existing conversion.
  my $conversion_adjustment =
    Google::Ads::GoogleAds::V17::Services::ConversionAdjustmentUploadService::ConversionAdjustment
    ->new({
      conversionAction =>
        Google::Ads::GoogleAds::V17::Utils::ResourceNames::conversion_action(
        $customer_id, $conversion_action_id
        ),
      adjustmentType => $adjustment_type,
      # Sets the orderId to identify the conversion to adjust.
      orderId => $order_id,
      # As an alternative to setting orderId, you can provide a 'gclid_date_time_pair',
      # but setting 'order_id' instead is strongly recommended.
      # gclidDateTimePair =>
      #  Google::Ads::GoogleAds::V17::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::V17::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 order ID '%s'.\n",
      $uploaded_conversion_adjustment->{conversionAction},
      $uploaded_conversion_adjustment->{orderId};
  }

  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,
  "order_id=s"             => \$order_id,
  "adjustment_type=s"      => \$adjustment_type,
  "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, $order_id,
  $adjustment_type, $adjustment_date_time);

# Call the example.
upload_conversion_adjustment($api_client, $customer_id =~ s/-//gr,
  $conversion_action_id, $order_id,
  $adjustment_type, $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.
    -order_id                   The order ID of the conversion. Strongly recommended instead of using GCLID and conversion date time.
    -adjustment_type            The type of adjustment, e.g. RETRACTION, RESTATEMENT.
    -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