4.1.5 转化跟踪

价值和业务影响


为了有效地为商家客户的广告系列提供 Google 生态系统强大的机器学习和分析功能,您需要在客户网站上放置转化跟踪代码和再营销代码。

在 Google Ads 中,转化是指用户在点击广告后执行了某项指定的操作,例如购买商品、安装移动应用或注册电子邮件收件人列表。转化跟踪功能可以提供重要的洞察信息,供您了解用户在浏览或点击广告后所执行的操作,包括用于计算和比较投资回报率 (ROI) 的信息,从而帮助您的客户决定广告支出的投入重点。跟踪还有助于确保数据可用于对帐。订单因产品或类别而异,因此转化跟踪还可用于显示特定产品信息组如何转化为销售。

转化目标是指一组具有相同基本目标的转化操作。例如,“购买”可以是包含“网站购买”和“实体店销售”转化操作的转化目标。

转化操作仍会用于跟踪转化情况并优化广告系列。您可以创建转化操作,然后 Google 将其分组到转化目标中。

购买转化操作

通过实现本文所述的转化跟踪,商家的 Google Ads 账号可以衡量“购买”类转化的次数以及这些转化的价值。如果没有转化跟踪,您将无法衡量广告系列在广告支出回报率方面的业务价值。它还会发送额外的数据信号,使广告系列能够优化效果。

其他转化操作

虽然只有购买转化操作是必需的,但跟踪其他转化操作可以为您的商家提供额外的数据洞见。我们建议您尽可能记录所有操作,同时实现尽可能多的核心转化操作。技术 API 指南部分介绍了推荐的转化操作的完整列表。

一般来说,建议您跟踪以下事项:

  • 任何与价值直接相关的成功事件
  • 有助于促成核心转化的成功事件,例如 add_to_cart 和 sign_up。
  • 深度互动和用户互动,有助于广告客户了解他们与最终用户的互动情况

次要转化操作仅用于观察和报告,会影响出价。详细了解主要和次要转化操作

用户体验指南


为了最大限度地降低错误风险,我们建议您在没有商家输入的情况下以编程方式实现转化跟踪,不过,您应确保商家知道已设置转化跟踪。

当商家关联现有 Google Ads 帐号时,我们建议显示一则通知,告知其帐号可能已设置转化跟踪,因为可能存在必须解决的冲突。相关示例如下所示。

connect_your_google_ads_account

技术指南


下面介绍了转化跟踪的工作原理。本部分将详细介绍各个步骤:

  1. 您在商家的 Google Ads 帐号中创建 'ConversionAction' 即可跟踪在商家网站上进行的购买(还可以跟踪其他客户操作)。

  2. 您可以将该转化操作的代码或代码段添加到网站或移动应用。如需了解详情,请参阅为网站设置转化跟踪

  3. 当客户点击广告时,系统会在客户的计算机或移动设备上放置一个临时 Cookie。

  4. 当客户完成为广告客户定义的操作后,Google 会识别该 Cookie(通过添加的代码段),并在适用的情况下记录一次转化以及其他参数(例如“value”)。

前提条件

在开始之前,请确保您拥有 Google 代码开发者 ID。如果您没有 Google 代码开发者 ID,请填写 Google 代码开发者 ID 申请表单。开发者 ID 不同于最终用户添加到其网站衡量代码中的其他 ID(例如衡量 ID 或转化 ID)。

创建和配置转化操作

以下示例展示了如何创建转化操作并将其添加到 Google Ads 帐号。每个示例都会为您处理所有后台身份验证任务,并逐步指导您创建转化操作:

Java

// Copyright 2018 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 static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;

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.ConversionActionCategoryEnum.ConversionActionCategory;
import com.google.ads.googleads.v17.enums.ConversionActionStatusEnum.ConversionActionStatus;
import com.google.ads.googleads.v17.enums.ConversionActionTypeEnum.ConversionActionType;
import com.google.ads.googleads.v17.errors.GoogleAdsError;
import com.google.ads.googleads.v17.errors.GoogleAdsException;
import com.google.ads.googleads.v17.resources.ConversionAction;
import com.google.ads.googleads.v17.resources.ConversionAction.ValueSettings;
import com.google.ads.googleads.v17.services.ConversionActionOperation;
import com.google.ads.googleads.v17.services.ConversionActionServiceClient;
import com.google.ads.googleads.v17.services.MutateConversionActionResult;
import com.google.ads.googleads.v17.services.MutateConversionActionsResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;

/** Adds a conversion action. */
public class AddConversionAction {

  private static class AddConversionActionParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;
  }

  public static void main(String[] args) {
    AddConversionActionParams params = new AddConversionActionParams();
    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");
    }

    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 AddConversionAction().runExample(googleAdsClient, params.customerId);
    } 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.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  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#

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

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 static Google.Ads.GoogleAds.V17.Enums.ConversionActionCategoryEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.ConversionActionStatusEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.ConversionActionTypeEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V17
{
    /// <summary>
    /// This code example illustrates adding a conversion action.
    /// </summary>
    public class AddConversionAction : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="AddConversionAction"/> 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>
        /// 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);

            AddConversionAction codeExample = new AddConversionAction();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example illustrates adding a conversion action.";

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

/**
 * Copyright 2018 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\Examples\Utils\Helper;
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\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\V17\Enums\ConversionActionCategoryEnum\ConversionActionCategory;
use Google\Ads\GoogleAds\V17\Enums\ConversionActionStatusEnum\ConversionActionStatus;
use Google\Ads\GoogleAds\V17\Enums\ConversionActionTypeEnum\ConversionActionType;
use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V17\Resources\ConversionAction;
use Google\Ads\GoogleAds\V17\Resources\ConversionAction\ValueSettings;
use Google\Ads\GoogleAds\V17\Services\ConversionActionOperation;
use Google\Ads\GoogleAds\V17\Services\MutateConversionActionsRequest;
use Google\ApiCore\ApiException;

/** This example illustrates adding a conversion action. */
class AddConversionAction
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            // We set this value to true to show how to use GAPIC v2 source code. You can remove the
            // below line if you wish to use the old-style source code. Note that in that case, you
            // probably need to modify some parts of the code below to make it work.
            // For more information, see
            // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic.
            ->usingGapicV2Source(true)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID
            );
        } 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
     */
    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
            );
        }
    }
}

AddConversionAction::main();

      

Python

#!/usr/bin/env python
# Copyright 2018 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 illustrates adding a conversion action."""


import argparse
import sys
import uuid

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


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}".'
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Adds a conversion action 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()

    # 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)
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

      

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2018 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 code example illustrates adding a conversion action.

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

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

if __FILE__ == $0
  options = {}
  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))

    opts.separator ''
    opts.separator 'Options:'

    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    add_conversion_action(options.fetch(:customer_id).tr("-", ""))
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
        end
      end
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
      end
    end
    raise
  end
end

      

Perl

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

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::Resources::ConversionAction;
use Google::Ads::GoogleAds::V17::Resources::ValueSettings;
use Google::Ads::GoogleAds::V17::Enums::ConversionActionCategoryEnum
  qw(DEFAULT);
use Google::Ads::GoogleAds::V17::Enums::ConversionActionTypeEnum   qw(WEBPAGE);
use Google::Ads::GoogleAds::V17::Enums::ConversionActionStatusEnum qw(ENABLED);
use
  Google::Ads::GoogleAds::V17::Services::ConversionActionService::ConversionActionOperation;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd          qw(abs_path);
use Data::Uniqid qw(uniqid);

# 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";

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

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

# 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);

# 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);

# Call the example.
add_conversion_action($api_client, $customer_id =~ s/-//gr);

=pod

=head1 NAME

add_conversion_action

=head1 DESCRIPTION

This example illustrates adding a conversion action.

=head1 SYNOPSIS

add_conversion_action.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.

=cut

      

由于上述示例本质上属于通用示例,因此特意在下面添加一些补充说明,以确保针对效果最大化广告系列正确配置 ConversionAction。每项转化操作都应按如下方式配置:

  • 类型 - 将 ConversionActionType 设置为“网页”,因为这些购买事件发生在网站上。

  • 可出价 - 请将主要转化操作(购买)设置为 true,以以提高销售额为目标优化广告系列。对于次要转化操作(例如“添加到购物车”),请将值设置为 false

  • 类别 - 针对每项转化操作(主要或次要),设置 ConversionActionCategory。下面分别列出了我们建议实现的 7 种转化操作的相关对话操作类别。请注意,Google Ads 会根据转化操作类别自动为标准转化目标分配转化操作。例如,购买转化操作会分配给名为“购买”的标准转化目标。之后,您可以将效果最大化广告系列配置为针对此“购买”目标进行优化。

您可以在下方找到建议的转化操作列表。建议您至少实现前四种转化操作,以及尽可能多的其他推荐操作。

您还可以考虑实现与线上销售相关的其他事件。如需进行更精细的跟踪,您还可以创建其他转化操作或自定义转化操作(例如,在用户每次使用网站上的搜索选项时执行“添加付款信息”操作,或每当用户在网站上使用搜索选项时为“搜索”操作)。次要转化操作可为您的商家提供额外的跟踪信息,并供 Google Ads 用于观察。

优先级 转化操作 转化操作类别 Google 代码事件名称 说明
强制 购买 购买 purchase 用户完成购买
强烈建议所有实体店开设者参考 添加到购物车 ADD_TO_CART add_to_cart 用户将产品添加到购物车
强烈建议所有实体店开设者参考 开始结账 BEGIN_CHECKOUT begin_checkout 用户开始结账流程
强烈建议所有实体店开设者参考 查看商品 PAGE_VIEW page_view 用户打开商品页面
在适用情况下强烈建议使用(通常不适用于商店开设平台) 注册 注册 sign_up 用户注册帐号
在适用情况下强烈建议使用(通常不适用于商店开设平台) 产生潜在客户 SUBMIT_LEAD_FORM generate_lead 用户通过表单发掘潜在客户
在适用情况下强烈建议使用(通常不适用于商店开设平台) 订阅 SUBSCRIBE_PAID 不适用(自定义) 用户订阅付费服务
在适用情况下强烈建议使用(通常不适用于商店开设平台) 预约服务 BOOK_APPOINTMENT 不适用(自定义) 用户进行预约
在适用情况下强烈建议使用(通常不适用于商店开设平台) 咨询报价 REQUEST_QUOTE 不适用(自定义) 用户提交了估算价格的表单

已有 Google Ads 帐号的商家

如果您允许商家使用现有 Google Ads 帐号建立合作关系,则可能会遇到该帐号已包含转化操作的情况。我们不建议使用现有转化操作,因为无法保证它已正确设置。此外,您必须执行额外的步骤,才能处理以下潜在情景:

  • 帐号有多个目标(例如“购买”“网页浏览量”+“联系人”)均标记为“帐号默认”。制作新的广告系列时,系统会默认针对所有这些目标进行优化。对于效果最大化广告系列,建议您不要这样做。

  • 帐号已有一项或多项转化操作用于跟踪购买情况,并且该操作已归在“购买”目标下。这意味着,广告系列会翻倍统计一次购买,因为触发了两个转化跟踪代码。

若要确保效果最大化广告系列仅使用您的自定义转化操作及该操作,请执行以下操作:

  1. 创建一个 CustomConversionGoal,并将您的购买转化操作添加到目标的 conversion_actions[] 列表中。将状态设置为已启用

  2. 在效果最大化广告系列的 ConversionGoalCampaignConfig 中,将 custom_conversion_goal 设置为您在第 (1) 步中创建的自定义目标。

  3. 作为第 (2) 步的结果,Google Ads 应该已经自动更新广告系列的 ConversionGoalCampaignConfig,将 goal_config_level 设置为 CAMPAIGN(而不是 CUSTOMER,这会指示其使用帐号默认目标),但还是有必要再次确认是否发生了这种情况。

检索转化操作的代码

创建转化操作后,您需要将相应的代码段(称为“代码”)插入到广告客户网站上的转化页中。为确保无论客户使用何种浏览器,Google Ads 都可以衡量所有转化,请使用新版 Google Ads 转化跟踪代码。此代码由两部分组成:

  • global_site_tag,必须安装在广告客户网站的每个网页上。

  • event_snippet,应放置在指示转化操作的网页上,例如结账确认页或潜在客户提交页。

您可以使用 ConversionActionService 获取这两部分内容。

该代码会设置 Cookie,用于存储客户的唯一标识符或将客户引导至网站的广告点击。这些 Cookie 会从转化跟踪代码中包含的 Google 点击标识符 (GCLID) 参数接收广告点击信息。您必须使广告客户的网站和潜在客户跟踪系统能够捕获和存储 GCLID,即 Google Ads 为 Google 广告的每次展示提供的唯一 ID。

详细了解全局代码及其添加位置

Google 代码 (gtag.js) 是一种代码植入框架兼 API,供您用来将事件数据同时发送到 Google Ads 和 Google Analytics(分析)。全局网站代码可与事件代码段或电话号码代码段配合使用来跟踪转化。向广告客户网站上每个网页的 <head> 部分添加 Google 代码,并将其配置为与 Google Ads 搭配使用。然后,您可以使用 gtag() 命令捕获事件并将数据发送到 Google Ads。 如需了解其工作原理,请参阅使用全局网站代码进行 Google Ads 转化跟踪

您可以使用以下命令与 Google 代码搭配使用:

  • config:初始化 Google 产品(Google Ads、Google Analytics [分析]等),配置设置,并准备将数据发送到帐号。

  • event:通过发送购买(推荐)或添加到购物车(次要转化操作)等事件来注册转化。我们建议您查看 gtag.js 事件参考指南

  • set:设置页面上所有事件通用的参数(例如币种)。

以下示例是全局网站代码的一个 JavaScript 代码段,用于向 Google Ads 发送数据。GOOGLE_CONVERSION_ID 占位符值是单个广告客户帐号的唯一数字 ID。

<!-- Google Tag (gtag.js) - Google Ads: GOOGLE_CONVERSION_ID -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-GOOGLE_CONVERSION_ID">
</script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments)};
  gtag('js', new Date());
   gtag('set', 'developer_id.<developer ID>', true); // Replace with your Google tag Developer ID
  gtag('config', 'AW-GOOGLE_CONVERSION_ID');
</script>

Google 代码段在每个网页上应仅出现一次。如果存在 gtag.js 的现有实例,则应将新代码 ID 添加到现有代码中。要将数据发送到多个帐号,您可以为使用的每个帐号添加对“config”命令的调用,并指定每个帐号的转化 ID,如以下示例所示:

<!-- Google Tag (gtag.js) - Google Ads: GOOGLE_CONVERSION_ID_1 -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-GOOGLE_CONVERSION_ID_1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments)};
  gtag('js', new Date());
  gtag('config', 'AW-GOOGLE_CONVERSION_ID_1');
  gtag('config', 'AW-GOOGLE_CONVERSION_ID_2');
</script>

详细了解事件代码段及其添加位置

为了让购买转化跟踪正常运行,应在转化页上添加购买事件代码段。这通常是订单确认页面。您可以将事件代码段放置在代码中全局代码段之后的任意位置。次要转化操作(例如“添加到购物车”)的事件代码段应放置在相应的网页中。

在下面的示例代码段中,AW-CONVERSION_IDgTag_developer_ID 代表您的 Google Ads 帐号和 Google 代码开发者帐号的唯一转化 ID,AW-CONVERSION_LABEL 代表转化标签,每项转化操作的转化标签都是唯一的:

<!-- Event snippet for a purchase conversion page -->
<script>
  gtag('event', 'conversion', {
       'send_to':'AW-CONVERSION_ID/CONVERSION_LABEL',
       'developer_id.<gTag developer ID>': true,
       'transaction_id': '<transaction_id (string)>' //unique ID for the transaction (e.g. an order ID); it's used for de-duplication purposes
       'value': 1.0,
       'currency': 'USD', //three-letter currency code, useful for advertisers who accept multiple currencies
       'country': 'US',
       'new_customer': false, //new customer acquisition goal
       'tax': 1.24, //tax cost-US only
       'shipping': 0.00, //shipping cost-US only
       'delivery_postal_code': '94043', //shipping data validation-US only
       'estimated_delivery_date': '2020-07-31', //shipping validation-US only
       'aw_merchant_id': 12345, //shipping validation-US only
       'aw_feed_country': 'US', //shipping validation-US only
       'aw_feed_language': 'EN', //shipping validation-US only
       'items': [
       {
             'id': 'P12345',
             'name': 'Android Warhol T-Shirt',
             'quantity': 2,
             'price': 12.04,
             'estimated_delivery_date': '2020-07-31', //shipping-US only
              'google_business_vertical': 'retail'
       }, …],
  });
</script>

虽然有些参数是可选的,但建议您尽可能多地为每个事件添加信息。详细了解每种事件类型可用的参数

参数可提供有关用户与您的网站或应用互动的方式的更多信息。

如果您想衡量基于点击的转化事件(例如,点击按钮或使用 AJAX 的网站获得动态响应),您也可以改用以下代码段:

<!-- Event snippet for test conversion click -->
In your html page, add the snippet and call gtag_report_conversion when someone clicks on the chosen link or button. -->
<script>
function gtag_report_conversion(url) {
  var callback = function () {
    if (typeof(url) != 'undefined') {
      window.location = url;
    }
  };
  gtag('event', 'conversion', {
      'send_to': 'AW-CONVERSION_ID/CONVERSION_LABEL',
      'value': 1.0,
      'event_callback': callback,
      //other parameters
  });
  return false;
}
</script>

Google 代码内置了 Consent API 来管理用户意见征求模式。它能够区分用户对于广告用途 Cookie 和分析用途 Cookie 的同意情况。

预期结果是客户至少集成了 gtag('consent', 'update' {...}) 调用,并且无需客户执行任何操作。这应确保 Google 代码(Google Ads、Floodlight、Google Analytics [分析]、转化链接器)能够读取最新的用户同意情况,并通过参数 &gcs 在向 Google 发送的网络请求中包括该状态。

其他实现步骤是部署或帮助广告客户部署(例如通过界面)gtag('consent', default' {...}) 状态并取消屏蔽 Google 代码(例如:不根据用户同意情况触发),以使意见征求模式能够以知晓用户意见的方式触发这些代码。

如需了解实现详情,请参阅管理用户意见征求设置(网站)

提示

在 Google Ads 经理帐号中,您可以使用一段转化跟踪代码来跟踪所有广告客户帐号的转化情况。请参阅跨帐号转化跟踪简介

若要测试您的转化跟踪实现是否有效,最佳方法是前往您的某个商家网站(或内部测试网站),然后进行真实的购买。然后,您可以在 Google Tag Assistant 工具中进行观察,按照此问题排查指南来验证 Google Ads 是否已检测到您的代码,以及是否在成功记录转化数据。如需排查其他问题,请访问对网站级代码植入进行问题排查

您可以在上述转化跟踪代码中添加增强型转化,以提高转化衡量的准确性,并提升出价优化效果。不妨详细了解如何设置增强型转化。 在实现增强型转化之前,您应该确保商家可以遵守 Google Ads 中的增强型转化客户数据政策