创建转化操作

本指南列出了您可以使用 Google Ads API 创建的不同转化操作类型、有关这些操作与 Google Ads 网页界面的对应关系的信息,还提供了详细代码示例来演示如何创建新的转化操作。

如需衡量转化情况,请为要跟踪的转化操作的 type 设置 ConversionAction。例如,网上购买和致电需要不同的转化操作。

若要在 API 中设置新的转化操作,最佳方法是使用下面的“添加转化操作代码示例”。此示例会为您处理所有后台身份验证任务,并引导您创建 ConversionAction

大多数转化操作还需要您执行额外的步骤才能进行跟踪。例如,如需跟踪您网站上的转化情况,您必须向网站上的转化页添加一个名为代码的代码段。如需了解其他转化操作要求,请参阅我们的帮助中心文章

网站转化

通过网站转化,您可以跟踪在线销售、链接点击、网页浏览和注册等网站操作。

若要跟踪网站上的转化情况,您必须创建一个 ConversionAction 并将 ConversionActionType 设置为 WEBPAGE,并向您网站上的转化页添加一个名为代码的代码段。

ConversionAction 包含多种类型的网站转化,在 API 中,可通过 ConversionActiontag_snippets 字段中列出的每个 TagSnippet 中的 type 字段进行区分。

TagSnippet 提供了跟踪代码。为了跟踪您的转化操作,您的网站中必须包含该代码。网站电话号码点击转化需要 event_snippet,后者应放置在指示某项转化操作(如结账确认或潜在客户表单提交页面)的网页上;以及 global_site_tag(必须安装在您网站的每个网页上)。您可以使用 ConversionActionService 检索这两个属性。如需详细了解如何为网页添加代码,请访问我们的帮助中心

下表显示了与 Google Ads 网页界面中的每个来源等效的 API 参数:

跟踪代码类型 Google Ads 来源
WEBPAGE 网站、网站(Google Analytics(分析)(GA4))
WEBPAGE_ONCLICK 网站、网站(Google Analytics(分析)(GA4))
CLICK_TO_CALL 电话号码点击
--- 网站 (UA)

应用转化

借助应用转化,您可以跟踪来自 Google Play 商店的移动应用安装或应用内购买情况。

下表显示了与 Google Ads 网页界面中的每个来源等效的 ConversionActionType API 参数:

转化操作类型 Google Ads 来源
GOOGLE_PLAY_DOWNLOAD Google Play > 安装次数
GOOGLE_PLAY_IN_APP_PURCHASE Google Play > 应用内购买

如果您希望使用 Google Analytics(分析)4 媒体资源第三方应用分析工具跟踪其他移动应用操作。请参阅其他转化操作类型

致电转化

利用来电转化跟踪,您可以跟踪广告促成的来电、拨打网站上的电话号码以及点击移动网站上的号码。

下表显示了与 Google Ads 网页界面中的每个来源等效的 ConversionActionType API 参数:

转化操作类型 Google Ads 来源
AD_CALL 从带附加电话信息的广告或来电专用广告中致电
WEBSITE_CALL 用户拨打您网站上的电话号码的次数
CLICK_TO_CALL 点击您的移动网站上的电话号码

CLICK_TO_CALL 类型与 AD_CALL 类型的不同之处在于,前者不跟踪实际致电,而是仅跟踪移动设备上电话号码获得的点击。CLICK_TO_CALL当无法使用 Google 转接电话号码跟踪来电时,此功能非常有用。

AD_CALL

AD_CALL 转化操作在 Google Ads 网页界面中显示为广告致电转化。创建 AD_CALL 转化操作后,请在创建 CallAsset 时,在 call_conversion_action 字段中指定其资源名称。借助电话素材资源,您可以直接在广告中显示电话号码。

如果致电的时长超过指定的时长,则将致电报告为转化。 默认的持续时间是 60 秒。

WEBSITE_CALL

WEBSITE_CALL 转化操作在 Google Ads 网页界面中显示为来自网站的来电转化。

AD_CALL 不同,此跟踪器需要将 event_snippetglobal_site_tag 添加到您的网站,才能检索对您网站上列出的号码进行来电跟踪所需的动态 Google 转接电话号码。此外,您必须设置电话素材资源,并在客户、广告系列或广告组层级进行关联

导入线下转化数据

下表显示了与 Google Ads 网页界面中每个来源等效的 ConversionActionType API 参数,以及每个特定转化操作类型的文档的链接:

转化操作类型 Google Ads 来源 API 设置指南
UPLOAD_CLICKS 跟踪点击带来的转化和增强型潜在客户转化 “上传点击”指南
“增强型潜在客户转化”指南
UPLOAD_CALLS 跟踪致电后发生的转化 API 设置指南
STORE_SALES 跟踪实体店销售转化 API 设置指南

增强型网站转化

借助增强型网站转化,您可以在转化事件发生后的 24 小时内为 WEBPAGE 转化操作发送第一方转化数据,而不是在发生时发送。这样,您就可以从各种来源(例如客户数据库或 CRM 系统)找到第一方数据。

其他转化操作类型

Google Ads API 在报告中提供了其他类型的转化操作,但可能会限制或禁止创建或修改这些操作。

SKAdNetwork 转化次数

如果您投放 iOS 应用广告系列并实现了 SKAdNetwork,则可以使用以下资源访问在 CustomerCampaign 级别提供给 Google 的 SKAdNetwork 数据:

报告字段 说明
metrics.sk_ad_network_conversions Apple 报告的转化次数。此指标只能按 segments.sk_ad_network_conversion_value 和日期相关细分的任意组合进行细分。
segments.sk_ad_network_conversion_value

Apple 报告的转化价值。此细分不能应用于 metrics.sk_ad_network_conversions 以外的任何指标,只能与日期相关细分结合使用。

如果 Apple 报告值为 0,则返回值 0,否则返回没有值。检查 字段存在性以区分这两种情况。

您还可以通过 CustomerSkAdNetworkConversionValueSchema,为使用 iOS 应用的特定关联客户保存 SKAdNetwork 转化价值映射。

Python 代码示例

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

import argparse
import sys

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

def main(client, customer_id):
    """Adds a keyword plan, campaign, ad group, etc. to the customer account.

    Also handles errors from the API and prints them.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.
    """

    res = update_skan_cv_schema(
        client, customer_id, "my_app_id", "account_link_id"
    )
    print(res)

def update_skan_cv_schema(client, customer_id, app_id, account_link_id):
    skan_service = client.get_service(
        "CustomerSkAdNetworkConversionValueSchemaService"
    )

    req = client.get_type(
        "MutateCustomerSkAdNetworkConversionValueSchemaRequest"
    )
    operation = client.get_type(
        "CustomerSkAdNetworkConversionValueSchemaOperation"
    )
    schema_instance = client.get_type(
        "CustomerSkAdNetworkConversionValueSchema"
    )

    new_schema = operation.update
    new_schema.resource_name = (
        skan_service.customer_sk_ad_network_conversion_value_schema_path(
            "customer_id", "account_link_id"
        )
    )
    new_schema.schema.app_id = app_id
    new_schema.schema.measurement_window_hours = 48

    skan_cv_mapping = (
        schema_instance.SkAdNetworkConversionValueSchema.FineGrainedConversionValueMappings()
    )
    skan_cv_mapping.fine_grained_conversion_value = 0  # 0 - 63
    skan_cv_mapping.conversion_value_mapping.min_time_post_install_hours = 0
    skan_cv_mapping.conversion_value_mapping.max_time_post_install_hours = 48

    skan_cv_event = schema_instance.SkAdNetworkConversionValueSchema.Event()
    skan_cv_event.mapped_event_name = "TEST"
    skan_cv_event.event_revenue_value = 10

    skan_cv_mapping.conversion_value_mapping.mapped_events.append(skan_cv_event)
    new_schema.schema.fine_grained_conversion_value_mappings.append(
        skan_cv_mapping
    )

    req.operation = operation
    req.customer_id = customer_id

    res = skan_service.mutate_customer_sk_ad_network_conversion_value_schema(
        req
    )
    return res

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

    parser = argparse.ArgumentParser(
        description="Creates a keyword plan for specified customer."
    )
    # 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.",
    )
    args = parser.parse_args()

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

Google Analytics(分析)

关联的 Google Analytics(分析)媒体资源中的转化具有以下 type 值之一:

  • GA4 媒体资源转化:

    • GOOGLE_ANALYTICS_4_CUSTOM
    • GOOGLE_ANALYTICS_4_PURCHASE

    此外,您还可以从 google_analytics_4_settings 字段中检索 GA4 媒体资源 ID、媒体资源名称和事件名称。

  • Universal Analytics 媒体资源转化:

    • UNIVERSAL_ANALYTICS_GOAL
    • UNIVERSAL_ANALYTICS_TRANSACTION

您可以对 GA4 媒体资源转化进行以下更改:

  • 通过将 GA4 媒体资源的 status 字段从 HIDDEN 修改为 ENABLED,将转化数据从 GA4 媒体资源导入 Google Ads 帐号中。
  • 修改其 primary_for_goalcategory 字段,以指明该字段将如何影响 Google Ads 出价和报告
  • 更新其 namevalue_settings
  • 使用 remove 操作从您的 Google Ads 帐号中移除转化。

如果尝试修改已导入的 GA4 转化的其他属性或已导入 Universal Analytics 转化的任何属性,都会导致 MUTATE_NOT_ALLOWED 错误。您只能通过 Google Ads 界面进行这类更改。

Firebase 和第三方应用分析

如需导入第三方应用分析工具Firebase 转化数据,请使用 ConversionActionServicemutate 方法将 ConversionActionstatusHIDDEN 更改为 ENABLED。这些转化操作不支持更新 app_id

  • FIREBASE_ANDROID_FIRST_OPEN
  • FIREBASE_ANDROID_IN_APP_PURCHASE
  • FIREBASE_ANDROID_CUSTOM
  • FIREBASE_IOS_FIRST_OPEN
  • FIREBASE_IOS_IN_APP_PURCHASE
  • FIREBASE_IOS_CUSTOM
  • THIRD_PARTY_APP_ANALYTICS_ANDROID_FIRST_OPEN
  • THIRD_PARTY_APP_ANALYTICS_ANDROID_IN_APP_PURCHASE
  • THIRD_PARTY_APP_ANALYTICS_ANDROID_CUSTOM
  • THIRD_PARTY_APP_ANALYTICS_IOS_FIRST_OPEN
  • THIRD_PARTY_APP_ANALYTICS_IOS_IN_APP_PURCHASE
  • THIRD_PARTY_APP_ANALYTICS_IOS_CUSTOM

实体店销售

虽然您无法使用 Google Ads API 创建 STORE_SALESSTORE_SALES_DIRECT_UPLOAD 转化操作,但该 API 支持上传实体店销售交易数据

  • STORE_SALES
  • STORE_SALES_DIRECT_UPLOAD

其他

以下转化操作类型在 Google Ads API 中处于只读状态,提供用于报告目的。

  • ANDROID_APP_PRE_REGISTRATION
  • ANDROID_INSTALLS_ALL_OTHER_APPS
  • FLOODLIGHT_ACTION
  • FLOODLIGHT_TRANSACTION
  • GOOGLE_HOSTED
  • LEAD_FORM_SUBMIT
  • SALESFORCE
  • SEARCH_ADS_360
  • SMART_CAMPAIGN_AD_CLICKS_TO_CALL
  • SMART_CAMPAIGN_MAP_CLICKS_TO_CALL
  • SMART_CAMPAIGN_MAP_DIRECTIONS
  • SMART_CAMPAIGN_TRACKED_CALLS
  • STORE_VISITS
  • WEBPAGE_CODELESS

未知

如果您的 Google Ads 帐号包含其他类型的转化操作,您可能会发现查询和报告会返回 ConversionAction.typeUNKNOWN 的转化操作。该 API 不支持管理这些转化操作,但会在报告中返回这些操作,以便为 metrics.conversionsmetrics.conversions_value 等关键转化指标提供完整结果。

代码示例

以下代码示例逐步介绍了如何创建新的转化操作。具体而言,它会创建一个将 type 设置为 UPLOAD_CLICKS 的转化操作。这与通过依次选择导入 > 使用 API 或上传手动导入 > 跟踪点击后发生的转化来创建新的转化操作相同的 Google Ads 界面流程。此外,它还会将 category 设置为 DEFAULT

系统将应用以下默认设置:

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#

public void Run(GoogleAdsClient client, long customerId)
{
    // Get the ConversionActionService.
    ConversionActionServiceClient conversionActionService =
        client.GetService(Services.V16.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

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

def main(client, customer_id):
    conversion_action_service = client.get_service("ConversionActionService")

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

    # Create conversion action.
    conversion_action = 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 = conversion_action.value_settings
    value_settings.default_value = 15.0
    value_settings.always_use_default_value = True

    # Add the conversion action.
    conversion_action_response = (
        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

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

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::V16::Resources::ConversionAction->new({
      name                          => $conversion_action_name,
      category                      => DEFAULT,
      type                          => WEBPAGE,
      status                        => ENABLED,
      viewThroughLookbackWindowDays => 15,
      valueSettings                 =>
        Google::Ads::GoogleAds::V16::Resources::ValueSettings->new({
          defaultValue          => 23.41,
          alwaysUseDefaultValue => "true"
        })});

  # Create a conversion action operation.
  my $conversion_action_operation =
    Google::Ads::GoogleAds::V16::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;
}
      

您也可以在客户端库的“再营销”文件夹以及代码示例集合中找到此示例:添加转化操作代码示例

验证

Google Ads 和 Google Ads API 支持各种各样的转化操作,因此某些验证规则因操作的 type 而异。

到目前为止,创建转化操作时最常见的错误是 DUPLICATE_NAME。确保为每个转化操作使用唯一的名称。

以下是有关如何设置 ConversionAction 字段的一些提示:

所有枚举字段
尝试将任何枚举字段设置为 UNKNOWN 会导致 RequestError.INVALID_ENUM_VALUE 错误。
app_id
app_id 属性不可变,只能在创建新的应用转化时设置。
attribution_model_settings
如果将其设置为已弃用的选项,则会导致 CANNOT_SET_RULE_BASED_ATTRIBUTION_MODELS 错误。Google Ads 仅支持 GOOGLE_ADS_LAST_CLICKGOOGLE_SEARCH_ATTRIBUTION_DATA_DRIVEN
click_through_lookback_window_days

如果将此属性设置为允许范围之外的值,将导致 RangeError.TOO_LOWRangeError.TOO_HIGH 错误。

对于“AD_CALL”或“WEBSITE_CALL”转化操作,此属性必须在 [1,60] 范围内。对于大多数其他转化操作,允许的范围为 [1,30]

include_in_conversions_metric

createupdate 操作中设置此值会失败,并出现 FieldError.IMMUTABLE_FIELD 错误。而是应按照转化目标指南中的说明设置 primary_for_goal

phone_call_duration_seconds

如果尝试为不针对致电的转化操作设置此属性,将导致 FieldError.VALUE_MUST_BE_UNSET 错误。

type

type 属性不可变,只能在创建新转化时设置。

更新 type 等于 UNKNOWN 的转化操作会导致 MutateError.MUTATE_NOT_ALLOWED 错误。

value_settings

WEBSITE_CALLAD_CALL 转化操作的 value_settings 必须将 always_use_default_value 设置为 true。创建或更新此值时指定 false 值会导致 INVALID_VALUE 错误。

view_through_lookback_window_days

如果将此属性设置为允许范围之外的值,将导致 RangeError.TOO_LOWRangeError.TOO_HIGH 错误。对于大多数转化操作,允许的范围为 [1,30]

无法为 AD_CALLWEBSITE_CALL 转化操作设置此属性。指定值会导致 VALUE_MUST_BE_UNSET 错误。