You must enable conversion tracking in your Google Ads conversion account in
order to record conversions. This guide provides details on how to confirm
whether conversion tracking is enabled, enable it if it isn't enabled already,
and retrieve information about existing conversion actions.

Most conversion actions also require additional steps on your part to track
them. For more information on the various conversion action types and their
requirements, see [Conversion action categories](https://developers.google.com/google-ads/api/docs/conversions/categories) and
[Create conversion actions](https://developers.google.com/google-ads/api/docs/conversions/getting-started#create-conversion-actions).

## Prepare to provide consent

When importing conversions or user data, you must confirm that you have
permission to share conversion data with Google. You can do this in one of two
ways:

1. Configure account-level default consent settings. In the [Google Ads UI](https://ads.google.com/), click **Tools** \> **Data Manager** \> **Consent settings** \> **Default consent settings**.
2. Set the consent field on each imported conversion or user data payload (for example, [`ClickConversion.consent`](https://developers.google.com/google-ads/api/reference/rpc/v26/ClickConversion#consent), [`CallConversion.consent`](https://developers.google.com/google-ads/api/reference/rpc/v26/CallConversion#consent), or [`UserData.consent`](https://developers.google.com/google-ads/api/reference/rpc/v26/UserData#consent)).

## Set up your website to track conversions

If you're tracking website conversions or implementing enhanced conversions for
leads, configure your website tagging first. Follow the steps in
[Configure the Google tag for enhanced conversions for leads](https://support.google.com/google-ads/answer/11021502),
or use Google Tag Manager by following [Configure Google Tag Manager for
enhanced conversions for leads](https://support.google.com/google-ads/answer/11347292).

## Enable conversion tracking in your Google Ads conversion account

Follow these steps to verify your account's conversion tracking setup and
create or retrieve conversion actions.

### Steps to enable conversion tracking

#### Retrieve information about your conversion tracking setup

You can check your account's conversion tracking setup and confirm conversion
tracking is enabled by querying the [`Customer`](https://developers.google.com/google-ads/api/fields/v26/customer) resource
for the
[`ConversionTrackingSetting`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionTrackingSetting).
Issue the following query with
[`GoogleAdsService.SearchStream`](https://developers.google.com/google-ads/api/reference/rpc/v26/GoogleAdsService/SearchStream):

    SELECT
      customer.conversion_tracking_setting.google_ads_conversion_customer,
      customer.conversion_tracking_setting.conversion_tracking_status,
      customer.conversion_tracking_setting.conversion_tracking_id,
      customer.conversion_tracking_setting.cross_account_conversion_tracking_id
    FROM customer

The `google_ads_conversion_customer` field indicates the Google Ads account that
creates and manages conversions for this customer. For customers using
[cross-account conversion
tracking](https://support.google.com/google-ads/answer/3030657), this is the ID
of a manager account. The Google Ads conversion customer ID should be given as the
`customer_id` in Google Ads API requests to create and manage conversions. Note that
this field is populated even if conversion tracking is not enabled.

The
[`conversion_tracking_status`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionTrackingStatusEnum.ConversionTrackingStatus)
field indicates whether conversion tracking is enabled and whether the account
is using cross-account conversion tracking.

#### Create a conversion action under the Google Ads conversion customer

If the `conversion_tracking_status` value is `NOT_CONVERSION_TRACKED`,
conversion tracking is not enabled for the account. Enable conversion tracking
by creating at least one [`ConversionAction`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction) in
the Google Ads conversion account, like in the following example. Alternatively, you
can create a conversion action in the UI by following the instructions in the
[Google Ads Help Center article on conversion tracking
setup](https://support.google.com/google-ads/answer/1722054#choose) for the
conversion type you want to enable.

Note that enhanced conversions are enabled automatically when sent through the
Google Ads API, but they can be disabled through the Google Ads UI.

#### Code example

### Java

```java
private void runExample(GoogleAdsClient googleAdsClient, long customerId) {

  // Creates a ConversionAction.
  ConversionAction conversionAction =
      ConversionAction.newBuilder()
          // Note that conversion action names must be unique. If a conversion action already
          // exists with the specified conversion_action_name the create operation will fail with
          // a ConversionActionError.DUPLICATE_NAME error.
          .setName("Earth to Mars Cruises Conversion #" + getPrintableDateTime())
          .setCategory(ConversionActionCategory.DEFAULT)
          .setType(ConversionActionType.WEBPAGE)
          .setStatus(ConversionActionStatus.ENABLED)
          .setViewThroughLookbackWindowDays(15L)
          .setValueSettings(
              ValueSettings.newBuilder()
                  .setDefaultValue(23.41)
                  .setAlwaysUseDefaultValue(true)
                  .build())
          .build();

  // Creates the operation.
  ConversionActionOperation operation =
      ConversionActionOperation.newBuilder().setCreate(conversionAction).build();

  try (ConversionActionServiceClient conversionActionServiceClient =
      googleAdsClient.getLatestVersion().createConversionActionServiceClient()) {
    MutateConversionActionsResponse response =
        conversionActionServiceClient.mutateConversionActions(
            Long.toString(customerId), Collections.singletonList(operation));
    System.out.printf("Added %d conversion actions:%n", response.getResultsCount());
    for (MutateConversionActionResult result : response.getResultsList()) {
      System.out.printf(
          "New conversion action added with resource name: '%s'%n", result.getResourceName());
    }
  }
}
      
```

### C#

```c#
public void Run(GoogleAdsClient client, long customerId)
{
    // Get the ConversionActionService.
    ConversionActionServiceClient conversionActionService =
        client.GetService(Services.V26.ConversionActionService);

    // Note that conversion action names must be unique.
    // If a conversion action already exists with the specified name the create operation
    // will fail with a ConversionAction.DUPLICATE_NAME error.
    string ConversionActionName = "Earth to Mars Cruises Conversion #"
        + ExampleUtilities.GetRandomString();

    // Add a conversion action.
    ConversionAction conversionAction = new ConversionAction()
    {
        Name = ConversionActionName,
        Category = ConversionActionCategory.Default,
        Type = ConversionActionType.Webpage,
        Status = ConversionActionStatus.Enabled,
        ViewThroughLookbackWindowDays = 15,
        ValueSettings = new ConversionAction.Types.ValueSettings()
        {
            DefaultValue = 23.41,
            AlwaysUseDefaultValue = true
        }
    };

    // Create the operation.
    ConversionActionOperation operation = new ConversionActionOperation()
    {
        Create = conversionAction
    };

    try
    {
        // Create the conversion action.
        MutateConversionActionsResponse response =
            conversionActionService.MutateConversionActions(customerId.ToString(),
                    new ConversionActionOperation[] { operation });

        // Display the results.
        foreach (MutateConversionActionResult newConversionAction in response.Results)
        {
            Console.WriteLine($"New conversion action with resource name = " +
                $"'{newConversionAction.ResourceName}' was added.");
        }
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      
```

### PHP

```php
    public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
    {
        // Creates a conversion action.
        $conversionAction = new ConversionAction(
            [
            // Note that conversion action names must be unique.
            // If a conversion action already exists with the specified conversion_action_name
            // the create operation will fail with a ConversionActionError.DUPLICATE_NAME error.
            'name' => 'Earth to Mars Cruises Conversion #' . Helper::getPrintableDatetime(),
            'category' => ConversionActionCategory::PBDEFAULT,
            'type' => ConversionActionType::WEBPAGE,
            'status' => ConversionActionStatus::ENABLED,
            'view_through_lookback_window_days' => 15,
            'value_settings' => new ValueSettings(
                [
                'default_value' => 23.41,
                'always_use_default_value' => true
                ]
            )
            ]
        );

        // Creates a conversion action operation.
        $conversionActionOperation = new ConversionActionOperation();
        $conversionActionOperation->setCreate($conversionAction);

        // Issues a mutate request to add the conversion action.
        $conversionActionServiceClient = $googleAdsClient->getConversionActionServiceClient();
        $response = $conversionActionServiceClient->mutateConversionActions(
            MutateConversionActionsRequest::build($customerId, [$conversionActionOperation])
        );

        printf("Added %d conversion actions:%s", $response->getResults()->count(), PHP_EOL);

        foreach ($response->getResults() as $addedConversionAction) {
            /**
 * @var ConversionAction $addedConversionAction
*/
            printf(
                "New conversion action added with resource name: '%s'%s",
                $addedConversionAction->getResourceName(),
                PHP_EOL
            );
        }
    }
      
```

### Python

```python
def main(client: GoogleAdsClient, customer_id: str) -> None:
    conversion_action_service: ConversionActionServiceClient = (
        client.get_service("ConversionActionService")
    )

    # Create the operation.
    conversion_action_operation: ConversionActionOperation = client.get_type(
        "ConversionActionOperation"
    )

    # Create conversion action.
    conversion_action: ConversionAction = conversion_action_operation.create

    # Note that conversion action names must be unique. If a conversion action
    # already exists with the specified conversion_action_name, the create
    # operation will fail with a ConversionActionError.DUPLICATE_NAME error.
    conversion_action.name = f"Earth to Mars Cruises Conversion {uuid.uuid4()}"
    conversion_action.type_ = (
        client.enums.ConversionActionTypeEnum.UPLOAD_CLICKS
    )
    conversion_action.category = (
        client.enums.ConversionActionCategoryEnum.DEFAULT
    )
    conversion_action.status = client.enums.ConversionActionStatusEnum.ENABLED
    conversion_action.view_through_lookback_window_days = 15

    # Create a value settings object.
    value_settings: ConversionAction.ValueSettings = (
        conversion_action.value_settings
    )
    value_settings.default_value = 15.0
    value_settings.always_use_default_value = True

    # Add the conversion action.
    conversion_action_response: MutateConversionActionsResponse = (
        conversion_action_service.mutate_conversion_actions(
            customer_id=customer_id,
            operations=[conversion_action_operation],
        )
    )

    print(
        "Created conversion action "
        f'"{conversion_action_response.results[0].resource_name}".'
    )
      
```

### Ruby

```ruby
def add_conversion_action(customer_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new


  # Add a conversion action.
  conversion_action = client.resource.conversion_action do |ca|
    ca.name = "Earth to Mars Cruises Conversion #{(Time.new.to_f * 100).to_i}"
    ca.type = :UPLOAD_CLICKS
    ca.category = :DEFAULT
    ca.status = :ENABLED
    ca.view_through_lookback_window_days = 15

    # Create a value settings object.
    ca.value_settings = client.resource.value_settings do |vs|
      vs.default_value = 15
      vs.always_use_default_value = true
    end
  end

  # Create the operation.
  conversion_action_operation = client.operation.create_resource.conversion_action(conversion_action)

  # Add the ad group ad.
  response = client.service.conversion_action.mutate_conversion_actions(
    customer_id: customer_id,
    operations: [conversion_action_operation],
  )

  puts "New conversion action with resource name = #{response.results.first.resource_name}."
end
      
```

### Perl

```perl
sub add_conversion_action {
  my ($api_client, $customer_id) = @_;

  # Note that conversion action names must be unique.
  # If a conversion action already exists with the specified conversion_action_name,
  # the create operation fails with error ConversionActionError.DUPLICATE_NAME.
  my $conversion_action_name = "Earth to Mars Cruises Conversion #" . uniqid();

  # Create a conversion action.
  my $conversion_action =
    Google::Ads::GoogleAds::V26::Resources::ConversionAction->new({
      name                          => $conversion_action_name,
      category                      => DEFAULT,
      type                          => WEBPAGE,
      status                        => ENABLED,
      viewThroughLookbackWindowDays => 15,
      valueSettings                 =>
        Google::Ads::GoogleAds::V26::Resources::ValueSettings->new({
          defaultValue          => 23.41,
          alwaysUseDefaultValue => "true"
        })});

  # Create a conversion action operation.
  my $conversion_action_operation =
    Google::Ads::GoogleAds::V26::Services::ConversionActionService::ConversionActionOperation
    ->new({create => $conversion_action});

  # Add the conversion action.
  my $conversion_actions_response =
    $api_client->ConversionActionService()->mutate({
      customerId => $customer_id,
      operations => [$conversion_action_operation]});

  printf "New conversion action added with resource name: '%s'.\n",
    $conversion_actions_response->{results}[0]{resourceName};

  return 1;
}
      
```

### curl

> [!NOTE]
> **Note:** While a direct REST code sample for this step isn't provided here, you can achieve this using a manual REST request.   
>
> Refer to the Google Ads API REST interface documentation and the method-specific reference pages. You will need to construct the JSON payload based on the proto definitions.   
>
> Key Resources:
>
> - [Using REST](https://developers.google.com/google-ads/api/rest/overview)
> - [REST Interface Structure](https://developers.google.com/google-ads/api/rest/design/overview)
> - [JSON Field Mappings](https://developers.google.com/google-ads/api/rest/design/json-mappings)
> - Consult the [REST API Reference](https://developers.google.com/google-ads/api/reference/rpc/latest/overview) for the specific service and method.

Make sure the [`type`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction#type)
is set to the correct
[`ConversionActionType`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionTypeEnum.ConversionActionType)
value. For more guidance on creating conversion actions in the Google Ads API, see
[Create
conversion actions](https://developers.google.com/google-ads/api/docs/conversions/getting-started#create-conversion-actions).

#### Retrieve an existing conversion action

You can retrieve details for an existing conversion action by issuing the
following query. Make sure the customer ID in the request is set to the Google Ads
conversion customer you identified earlier, and the conversion action type is
set to the correct
[`ConversionActionType`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionTypeEnum.ConversionActionType)
value.

    SELECT
      conversion_action.id,
      conversion_action.resource_name,
      conversion_action.name,
      conversion_action.type,
      conversion_action.category,
      conversion_action.status
    FROM conversion_action

    WHERE conversion_action.type = 'INSERT_CONVERSION_ACTION_TYPE'

## Cross-account conversion tracking

Cross-account conversion tracking allows Google Ads accounts to import
conversions on behalf of other accounts, which may have trafficked the ads that
generated conversions. This can help to simplify your integration by allowing
you to consolidate the accounts that make import requests.

### Enabling cross-account conversion tracking in the Google Ads API

> [!NOTE]
> **Note:** Using the Google Ads API to modify the cross-account conversion tracking settings is an allowlist-only feature. To use it, contact your account manager, or [set it up using the Google Ads UI](https://support.google.com/google-ads/answer/3061730).

You can use the Google Ads API to opt into cross-conversion tracking when creating or
updating client accounts.

On a [`Customer`](https://developers.google.com/google-ads/api/reference/rpc/v26/Customer) resource, set the
[`conversion_tracking_setting.google_ads_conversion_customer`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionTrackingSetting#google_ads_conversion_customer)
field to the [resource name](https://developers.google.com/google-ads/api/docs/concepts/api-structure#resource-names) of the manager account that should
manage conversion actions on behalf of the client account.

Requests that modify the conversion customer of a client account must be sent by
the manager account that is becoming the new conversion customer for the client.
Do this by setting the [`login-customer-id`](https://developers.google.com/google-ads/api/docs/concepts/call-structure#cid) to the manager account
ID.

When you opt into cross-account conversion tracking, or switch the conversion
tracking manager for an existing client account, the same caveats apply as if
you were to [make this change in the UI](https://support.google.com/google-ads/answer/3061730#zippy=%2Cstep-choose-accounts-for-conversion-action-sharing). Specifically:

- The client account will adopt the default conversion value rules, and the default customer lifecycle goals of its new conversion tracking manager.
- Campaigns that target a specific conversion action will switch to using the conversion manager account's default conversion goals. If you continue to target a specific conversion action, that can produce inconsistent behavior, as the manager account may not have the same goals as the client account. Make sure that your campaigns are optimized to the right goals.
- If an account belongs to more than one manager account, it can only use conversion actions from one manager. If no conversion tracking account is specified, the account will use itself as the conversion tracking account by default.

### Importing conversions across accounts

With cross-account tracking enabled, client and manager accounts can import
conversions on behalf of the serving account. This makes it possible to
simplify your import logic so that you don't need to determine the serving
account for each conversion at import time, you can just choose one account from
your account tree to import all conversions.

> [!WARNING]
> **Warning:** To avoid creating duplicate conversions, don't upload the same conversion multiple times using different accounts.

To successfully upload a conversion, the uploading account must have access to
the conversion action. In a cross-account tracking hierarchy, the uploading
account has access to the action if it is a parent (manager) or descendant of
the conversion action owner in the account tree.

The following diagram illustrates the authorization structure for importing
conversions. Here `C1` is the client account that served the ad that generated
the conversion, and `M2` is the conversion action owner and `C1`'s
conversion tracking parent. The accounts highlighted in green are allowed to
import conversions on behalf of `C1`, while the accounts highlighted in red
cannot.

![Authorization structure](https://developers.google.com/static/google-ads/api/images/oci_auth_relationships.png)

## Create conversion actions

To measure conversions, set up a [`ConversionAction`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction) for the
[`type`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionTypeEnum.ConversionActionType) of conversion action you want to track.
For example, an online purchase and a phone call require different conversion
actions.

The best way to set up new conversion actions in the API is to use the
[Add Conversion Action code example](https://developers.google.com/google-ads/api/docs/conversions/getting-started#code_example). The sample handles all the
background authentication tasks for you, and walks you through creating a
[`ConversionAction`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction).

Most conversion actions also require additional steps on your part to track
them. For example, to track conversions on your website, you must add a code
snippet called a [**tag**](https://support.google.com/google-ads/answer/7548399) to the conversion page on your website. For
detailed requirements of other conversion action types, see our
[Google Ads Help Center article on conversion types](https://support.google.com/google-ads/answer/1722054#choose).

If you're using [cross-account conversion tracking](https://support.google.com/google-ads/answer/3030657), the
[`ConversionActionService`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionService) returns the following
conversion actions:

- All conversion actions defined by the manager account used by the account for cross-account conversion tracking
- All conversion actions on which the customer has accrued stats, including system-defined actions, and actions owned by the manager even if that manager unlinks subsequently
- All actions the customer has defined in their own account
- Analytics conversions created in linked Google Analytics properties. This includes actions for Analytics conversions not imported into Google Ads, which have a status of [`HIDDEN`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionStatusEnum.ConversionActionStatus).

### Code example

The following code example walks you through the process of creating a new
conversion action. Specifically, it creates a conversion action with the
[`type`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction#type) set to [`UPLOAD_CLICKS`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionTypeEnum.ConversionActionType#upload_clicks).
It also sets the [`category`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction#category) to
[`DEFAULT`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionCategoryEnum.ConversionActionCategory#default).

The following default settings apply:

- The Google Ads API sets the [`primary_for_goal`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction#primary_for_goal) field
  automatically, but you can set this field explicitly to control how a
  conversion action impacts reporting and bidding in your account when [combined
  with your conversion goals](https://developers.google.com/google-ads/api/docs/conversions/goals/overview#conversion_action_settings).

- The Google Ads API sets the [`counting_type`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction#counting_type) automatically to
  [`MANY_PER_CLICK`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionCountingTypeEnum.ConversionActionCountingType#many_per_click). See
  [About conversion counting options](https://support.google.com/google-ads/answer/3438531) for more details.

- The Google Ads API sets the attribution model to be [Data driven](https://support.google.com/google-ads/answer/6394265) by
  setting the [`attribution_model_settings`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction#attribution_model_settings) field
  to the `GOOGLE_SEARCH_ATTRIBUTION_DATA_DRIVEN` value of
  [`AttributionModel`](https://developers.google.com/google-ads/api/reference/rpc/v26/AttributionModelEnum.AttributionModel#google_search_attribution_data_driven). See [About attribution
  models](https://support.google.com/google-ads/answer/6259715) to learn more about attribution models.


### Java

```java
private void runExample(GoogleAdsClient googleAdsClient, long customerId) {

  // Creates a ConversionAction.
  ConversionAction conversionAction =
      ConversionAction.newBuilder()
          // Note that conversion action names must be unique. If a conversion action already
          // exists with the specified conversion_action_name the create operation will fail with
          // a ConversionActionError.DUPLICATE_NAME error.
          .setName("Earth to Mars Cruises Conversion #" + getPrintableDateTime())
          .setCategory(ConversionActionCategory.DEFAULT)
          .setType(ConversionActionType.WEBPAGE)
          .setStatus(ConversionActionStatus.ENABLED)
          .setViewThroughLookbackWindowDays(15L)
          .setValueSettings(
              ValueSettings.newBuilder()
                  .setDefaultValue(23.41)
                  .setAlwaysUseDefaultValue(true)
                  .build())
          .build();

  // Creates the operation.
  ConversionActionOperation operation =
      ConversionActionOperation.newBuilder().setCreate(conversionAction).build();

  try (ConversionActionServiceClient conversionActionServiceClient =
      googleAdsClient.getLatestVersion().createConversionActionServiceClient()) {
    MutateConversionActionsResponse response =
        conversionActionServiceClient.mutateConversionActions(
            Long.toString(customerId), Collections.singletonList(operation));
    System.out.printf("Added %d conversion actions:%n", response.getResultsCount());
    for (MutateConversionActionResult result : response.getResultsList()) {
      System.out.printf(
          "New conversion action added with resource name: '%s'%n", result.getResourceName());
    }
  }
}
      
```

### C#

```c#
public void Run(GoogleAdsClient client, long customerId)
{
    // Get the ConversionActionService.
    ConversionActionServiceClient conversionActionService =
        client.GetService(Services.V26.ConversionActionService);

    // Note that conversion action names must be unique.
    // If a conversion action already exists with the specified name the create operation
    // will fail with a ConversionAction.DUPLICATE_NAME error.
    string ConversionActionName = "Earth to Mars Cruises Conversion #"
        + ExampleUtilities.GetRandomString();

    // Add a conversion action.
    ConversionAction conversionAction = new ConversionAction()
    {
        Name = ConversionActionName,
        Category = ConversionActionCategory.Default,
        Type = ConversionActionType.Webpage,
        Status = ConversionActionStatus.Enabled,
        ViewThroughLookbackWindowDays = 15,
        ValueSettings = new ConversionAction.Types.ValueSettings()
        {
            DefaultValue = 23.41,
            AlwaysUseDefaultValue = true
        }
    };

    // Create the operation.
    ConversionActionOperation operation = new ConversionActionOperation()
    {
        Create = conversionAction
    };

    try
    {
        // Create the conversion action.
        MutateConversionActionsResponse response =
            conversionActionService.MutateConversionActions(customerId.ToString(),
                    new ConversionActionOperation[] { operation });

        // Display the results.
        foreach (MutateConversionActionResult newConversionAction in response.Results)
        {
            Console.WriteLine($"New conversion action with resource name = " +
                $"'{newConversionAction.ResourceName}' was added.");
        }
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      
```

### PHP

```php
    public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
    {
        // Creates a conversion action.
        $conversionAction = new ConversionAction(
            [
            // Note that conversion action names must be unique.
            // If a conversion action already exists with the specified conversion_action_name
            // the create operation will fail with a ConversionActionError.DUPLICATE_NAME error.
            'name' => 'Earth to Mars Cruises Conversion #' . Helper::getPrintableDatetime(),
            'category' => ConversionActionCategory::PBDEFAULT,
            'type' => ConversionActionType::WEBPAGE,
            'status' => ConversionActionStatus::ENABLED,
            'view_through_lookback_window_days' => 15,
            'value_settings' => new ValueSettings(
                [
                'default_value' => 23.41,
                'always_use_default_value' => true
                ]
            )
            ]
        );

        // Creates a conversion action operation.
        $conversionActionOperation = new ConversionActionOperation();
        $conversionActionOperation->setCreate($conversionAction);

        // Issues a mutate request to add the conversion action.
        $conversionActionServiceClient = $googleAdsClient->getConversionActionServiceClient();
        $response = $conversionActionServiceClient->mutateConversionActions(
            MutateConversionActionsRequest::build($customerId, [$conversionActionOperation])
        );

        printf("Added %d conversion actions:%s", $response->getResults()->count(), PHP_EOL);

        foreach ($response->getResults() as $addedConversionAction) {
            /**
 * @var ConversionAction $addedConversionAction
*/
            printf(
                "New conversion action added with resource name: '%s'%s",
                $addedConversionAction->getResourceName(),
                PHP_EOL
            );
        }
    }
      
```

### Python

```python
def main(client: GoogleAdsClient, customer_id: str) -> None:
    conversion_action_service: ConversionActionServiceClient = (
        client.get_service("ConversionActionService")
    )

    # Create the operation.
    conversion_action_operation: ConversionActionOperation = client.get_type(
        "ConversionActionOperation"
    )

    # Create conversion action.
    conversion_action: ConversionAction = conversion_action_operation.create

    # Note that conversion action names must be unique. If a conversion action
    # already exists with the specified conversion_action_name, the create
    # operation will fail with a ConversionActionError.DUPLICATE_NAME error.
    conversion_action.name = f"Earth to Mars Cruises Conversion {uuid.uuid4()}"
    conversion_action.type_ = (
        client.enums.ConversionActionTypeEnum.UPLOAD_CLICKS
    )
    conversion_action.category = (
        client.enums.ConversionActionCategoryEnum.DEFAULT
    )
    conversion_action.status = client.enums.ConversionActionStatusEnum.ENABLED
    conversion_action.view_through_lookback_window_days = 15

    # Create a value settings object.
    value_settings: ConversionAction.ValueSettings = (
        conversion_action.value_settings
    )
    value_settings.default_value = 15.0
    value_settings.always_use_default_value = True

    # Add the conversion action.
    conversion_action_response: MutateConversionActionsResponse = (
        conversion_action_service.mutate_conversion_actions(
            customer_id=customer_id,
            operations=[conversion_action_operation],
        )
    )

    print(
        "Created conversion action "
        f'"{conversion_action_response.results[0].resource_name}".'
    )
      
```

### Ruby

```ruby
def add_conversion_action(customer_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new


  # Add a conversion action.
  conversion_action = client.resource.conversion_action do |ca|
    ca.name = "Earth to Mars Cruises Conversion #{(Time.new.to_f * 100).to_i}"
    ca.type = :UPLOAD_CLICKS
    ca.category = :DEFAULT
    ca.status = :ENABLED
    ca.view_through_lookback_window_days = 15

    # Create a value settings object.
    ca.value_settings = client.resource.value_settings do |vs|
      vs.default_value = 15
      vs.always_use_default_value = true
    end
  end

  # Create the operation.
  conversion_action_operation = client.operation.create_resource.conversion_action(conversion_action)

  # Add the ad group ad.
  response = client.service.conversion_action.mutate_conversion_actions(
    customer_id: customer_id,
    operations: [conversion_action_operation],
  )

  puts "New conversion action with resource name = #{response.results.first.resource_name}."
end
      
```

### Perl

```perl
sub add_conversion_action {
  my ($api_client, $customer_id) = @_;

  # Note that conversion action names must be unique.
  # If a conversion action already exists with the specified conversion_action_name,
  # the create operation fails with error ConversionActionError.DUPLICATE_NAME.
  my $conversion_action_name = "Earth to Mars Cruises Conversion #" . uniqid();

  # Create a conversion action.
  my $conversion_action =
    Google::Ads::GoogleAds::V26::Resources::ConversionAction->new({
      name                          => $conversion_action_name,
      category                      => DEFAULT,
      type                          => WEBPAGE,
      status                        => ENABLED,
      viewThroughLookbackWindowDays => 15,
      valueSettings                 =>
        Google::Ads::GoogleAds::V26::Resources::ValueSettings->new({
          defaultValue          => 23.41,
          alwaysUseDefaultValue => "true"
        })});

  # Create a conversion action operation.
  my $conversion_action_operation =
    Google::Ads::GoogleAds::V26::Services::ConversionActionService::ConversionActionOperation
    ->new({create => $conversion_action});

  # Add the conversion action.
  my $conversion_actions_response =
    $api_client->ConversionActionService()->mutate({
      customerId => $customer_id,
      operations => [$conversion_action_operation]});

  printf "New conversion action added with resource name: '%s'.\n",
    $conversion_actions_response->{results}[0]{resourceName};

  return 1;
}
      
```

### curl

> [!NOTE]
> **Note:** While a direct REST code sample for this step isn't provided here, you can achieve this using a manual REST request.   
>
> Refer to the Google Ads API REST interface documentation and the method-specific reference pages. You will need to construct the JSON payload based on the proto definitions.   
>
> Key Resources:
>
> - [Using REST](https://developers.google.com/google-ads/api/rest/overview)
> - [REST Interface Structure](https://developers.google.com/google-ads/api/rest/design/overview)
> - [JSON Field Mappings](https://developers.google.com/google-ads/api/rest/design/json-mappings)
> - Consult the [REST API Reference](https://developers.google.com/google-ads/api/reference/rpc/latest/overview) for the specific service and method.

<br />

You can see this example in the Remarketing folder of your client library
and in the code examples collection: [Add Conversion Action code
example](https://developers.google.com/google-ads/api/samples/add-conversion-action).

### `ConversionActionService.MutateConversionActions` field reference

Use [`MutateConversionActions`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionService/MutateConversionActions) on
[`ConversionActionService`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionService) to create, update, or
remove conversion actions under the Google Ads conversion customer:

    POST https://googleads.googleapis.com/v26/customers/{customer_id}/conversionActions:mutate

The following table lists the top-level request and operation fields on
[`MutateConversionActionsRequest`](https://developers.google.com/google-ads/api/reference/rpc/v26/MutateConversionActionsRequest):

| Field | Requirement | Description |
|---|---|---|
| `customer_id` | Required | The 10-digit ID (`string`) of the Google Ads conversion customer (`google_ads_conversion_customer`), without hyphens. |
| `partial_failure` | Optional | When `true` (`bool`), valid operations are executed and failed operations return errors in `partial_failure_error`. Defaults to `false`. |
| `validate_only` | Optional | When `true` (`bool`), validates the request without executing mutations. |
| `response_content_type` | Optional | [`ResponseContentType`](https://developers.google.com/google-ads/api/reference/rpc/v26/ResponseContentTypeEnum.ResponseContentType) controlling whether the response returns only `resource_name` (`RESOURCE_NAME_ONLY`, default) or the mutated `ConversionAction` object (`MUTABLE_RESOURCE`). |
| `operations[].create` | Required (on create) | The [`ConversionAction`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction) resource to create. No `resource_name` is expected. |
| `operations[].update` | Required (on update) | The [`ConversionAction`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction) resource to update (must include `resource_name` and a sibling `update_mask` on the `ConversionActionOperation`). |
| `operations[].update_mask` | Required (on update) | `FieldMask` (comma-separated list of modified `ConversionAction` field paths in `snake_case`; REST JSON `updateMask` accepts `snake_case` or `camelCase`, while gRPC and client libraries require `snake_case`) on the `ConversionActionOperation` (sibling of `update`, not nested inside `ConversionAction`). |
| `operations[].remove` | Required (on remove) | Resource name (`customers/{customer_id}/conversionActions/{action_id}`) of the conversion action to remove. |

When configuring a [`ConversionAction`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction) in
`operations[].create` or `operations[].update`, observe the following field
requirements and mutability constraints (see [Validations](https://developers.google.com/google-ads/api/docs/conversions/getting-started#validations) for
type-specific error rules):

| `ConversionAction` field | Requirement and mutability | Description |
|---|---|---|
| `name` | Required (mutable) | Unique display name (`string`) within the conversion customer account. |
| `type` | Required on `create` (`IMMUTABLE`) | [`ConversionActionType`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionTypeEnum.ConversionActionType) (such as `WEBPAGE`, `UPLOAD_CLICKS`, `UPLOAD_CALLS`, `AD_CALL`, or `WEBSITE_CALL`). |
| `category` | Optional (mutable) | [`ConversionActionCategory`](https://developers.google.com/google-ads/api/docs/conversions/categories) (such as `DEFAULT`, `PURCHASE`, `SUBMIT_LEAD_FORM`, `SIGNUP`, or `PHONE_CALL_LEAD`). Defaults to `DEFAULT`. |
| `status` | Optional (mutable) | [`ConversionActionStatus`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionStatusEnum.ConversionActionStatus) (`ENABLED`, `REMOVED`, or `HIDDEN`). Defaults to `ENABLED`. |
| `primary_for_goal` | Optional (mutable) | `bool` controlling whether the action is biddable in standard customer and campaign conversion goals (note: `CustomConversionGoal` resources ignore this setting). Defaults to `true`. |
| `counting_type` | Optional (mutable) | [`ConversionActionCountingType`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionCountingTypeEnum.ConversionActionCountingType) (`MANY_PER_CLICK` default, or `ONE_PER_CLICK`). |
| `value_settings` | Optional (mutable) | [`ValueSettings`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction.ValueSettings) (`default_value`, `default_currency_code`, `always_use_default_value`). |
| `attribution_model_settings` | Optional (mutable) | [`AttributionModelSettings`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction#attribution_model_settings) (`attribution_model`: `GOOGLE_SEARCH_ATTRIBUTION_DATA_DRIVEN` default or `GOOGLE_ADS_LAST_CLICK`). |
| `click_through_lookback_window_days` | Optional (mutable) | `int64` click-through lookback window in days (`1` to `90` for most types; `1` to `60` for call types). |
| `view_through_lookback_window_days` | Optional (mutable) | `int64` view-through lookback window in days (`1` to `30` for most types; unset for call types). |
| `phone_call_duration_seconds` | Call types only (mutable) | `int64` minimum call duration in seconds (`0` to `10000`). |
| `app_id` | App types only (immutable after creation) | Mobile app identifier (`string`); can only be set on `create` for app conversion actions. |
| `include_in_conversions_metric` | Read-only in mutations | Cannot be modified directly; configure `primary_for_goal` instead. |
| `tag_snippets[]` | `OUTPUT_ONLY` | Website tracking code snippets ([`TagSnippet`](https://developers.google.com/google-ads/api/reference/rpc/v26/TagSnippet)) populated on `WEBPAGE` conversion actions. |

#### REST request and response structure

To create or update a [`ConversionAction`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction) over REST, send a
`POST` request to
[`ConversionActionService.MutateConversionActions`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionService/MutateConversionActions).
When updating an existing conversion action, specify `updateMask` on the
operation object as a sibling of `update`:

    POST https://googleads.googleapis.com/v26/customers/{customer_id}/conversionActions:mutate

    {
      "operations": [
        {
          "create": {
            "name": "Earth to Mars Cruise Conversion",
            "type": "UPLOAD_CLICKS",
            "category": "DEFAULT",
            "status": "ENABLED",
            "primaryForGoal": true,
            "countingType": "ONE_PER_CLICK",
            "clickThroughLookbackWindowDays": "60",
            "valueSettings": {
              "defaultValue": 23.41,
              "defaultCurrencyCode": "USD",
              "alwaysUseDefaultValue": true
            }
          }
        },
        {
          "updateMask": "primary_for_goal,value_settings.default_value",
          "update": {
            "resourceName": "customers/{customer_id}/conversionActions/6666666666",
            "primaryForGoal": false,
            "valueSettings": {
              "defaultValue": 45.00
            }
          }
        }
      ]
    }

A successful response returns
[`MutateConversionActionResult`](https://developers.google.com/google-ads/api/reference/rpc/v26/MutateConversionActionResult) entries in `results[]`:

    {
      "results": [
        {
          "resourceName": "customers/{customer_id}/conversionActions/7777777777"
        },
        {
          "resourceName": "customers/{customer_id}/conversionActions/6666666666"
        }
      ]
    }

## Inspect conversion action settings and tag snippets with GAQL

In addition to the basic query shown in [Steps to enable conversion
tracking](https://developers.google.com/google-ads/api/docs/conversions/getting-started#steps_to_enable_conversion_tracking), you can query the
[`conversion_action`](https://developers.google.com/google-ads/api/fields/v26/conversion_action) resource using
[`GoogleAdsService.SearchStream`](https://developers.google.com/google-ads/api/reference/rpc/v26/GoogleAdsService/SearchStream) to inspect `primary_for_goal`,
attribution model status, lookback windows, value settings, and website
`tag_snippets`:

    SELECT
      conversion_action.id,
      conversion_action.resource_name,
      conversion_action.name,
      conversion_action.type,
      conversion_action.category,
      conversion_action.status,
      conversion_action.primary_for_goal,
      conversion_action.counting_type,
      conversion_action.click_through_lookback_window_days,
      conversion_action.view_through_lookback_window_days,
      conversion_action.value_settings.default_value,
      conversion_action.value_settings.default_currency_code,
      conversion_action.value_settings.always_use_default_value,
      conversion_action.attribution_model_settings.attribution_model,
      conversion_action.attribution_model_settings.data_driven_model_status,
      conversion_action.tag_snippets
    FROM conversion_action
    WHERE conversion_action.status = 'ENABLED'

## Validations

Google Ads and the Google Ads API support a wide variety of conversion actions, so some
validation rules vary based on the [`type`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionAction#type) of
action.

By far the most common error when creating a conversion action is
[`DUPLICATE_NAME`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionErrorEnum.ConversionActionError#duplicate_name). Make sure you are using a unique name for
each conversion action.

Here are some tips on setting the `ConversionAction` fields:

All enum fields
:   Attempting to set any enum field to `UNKNOWN` results in a
    `RequestError.INVALID_ENUM_VALUE` error.

`app_id`
:   The `app_id` attribute is immutable and can only be set when creating a new
    app conversion.

`attribution_model_settings`
:   Setting this to a [deprecated option](https://ads-developers.googleblog.com/2023/04/first-click-linear-time-decay-and.html) results in
    a [`CANNOT_SET_RULE_BASED_ATTRIBUTION_MODELS`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionErrorEnum.ConversionActionError#cannot_set_rule_based_attribution_models) error.
    Google Ads only supports [`GOOGLE_ADS_LAST_CLICK`](https://developers.google.com/google-ads/api/reference/rpc/v26/AttributionModelEnum.AttributionModel#google_ads_last_click) and
    [`GOOGLE_SEARCH_ATTRIBUTION_DATA_DRIVEN`](https://developers.google.com/google-ads/api/reference/rpc/v26/AttributionModelEnum.AttributionModel#google_search_attribution_data_driven).

`click_through_lookback_window_days`

:   Setting this attribute to a value outside of the allowed range results in a
    `RangeError.TOO_LOW` or `RangeError.TOO_HIGH` error.

    This attribute must be between 1 and 60 days for an `AD_CALL` or
    `WEBSITE_CALL` conversion action. For most other conversion actions, the
    allowed range is 1 to 90 days.

`include_in_conversions_metric`

:   Setting this value in a `create` or `update` operation fails with a
    `FieldError.IMMUTABLE_FIELD` error. Instead, set `primary_for_goal` as
    described in the [Conversion goals guide](https://developers.google.com/google-ads/api/docs/conversions/goals/overview).

`phone_call_duration_seconds`

:   Attempting to set this attribute on a conversion action that isn't for calls
    results in a `FieldError.VALUE_MUST_BE_UNSET` error.

`type`

:   The `type` attribute is immutable and can only be set when creating a new
    conversion.

    Updating a conversion action with [`type` equal to `UNKNOWN`](https://developers.google.com/google-ads/api/reference/rpc/v26/ConversionActionTypeEnum.ConversionActionType#unknown)
    results in a `MutateError.MUTATE_NOT_ALLOWED` error.

`value_settings`

:   The `value_settings` for a `WEBSITE_CALL` or `AD_CALL` conversion action must
    have `always_use_default_value` set to `true`. Specifying a value of `false`
    when creating or updating this value results in an `INVALID_VALUE` error.

`view_through_lookback_window_days`

:   Setting this attribute to a value outside of the allowed range results in a
    `RangeError.TOO_LOW` or `RangeError.TOO_HIGH` error. For most conversion
    actions, the allowed range is 1 to 30 days.

    This attribute cannot be set on `AD_CALL` or `WEBSITE_CALL` conversion
    actions. Specifying a value results in a `VALUE_MUST_BE_UNSET` error.