4.1.5 转化跟踪

价值和业务影响


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

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

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

转化操作仍可用于跟踪转化和优化广告系列。您创建转化操作,Google 会将这些转化操作归入转化目标中。

“购买”转化操作

通过实现本文所述的转化跟踪,商家的 Google Ads 账号便可衡量购买转化次数和这些转化的价值。如果不启用转化跟踪,您将无法衡量广告系列在广告支出回报率 (ROAS) 方面的业务价值。它还会发送额外的数据信号,以便广告系列优化效果。

其他转化操作

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

一般来说,建议捕获以下内容:

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

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

用户体验指南


为最大限度地降低出错风险,我们建议您以程序化方式(无需商家输入)实现转化跟踪,但您应确保商家知道已设置转化跟踪。

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

connect_your_google_ads_account

技术指南


转化跟踪的运作方式如下。本部分将详细介绍每个步骤:

  1. 您需要在商家的 Google Ads 账号中创建 “ConversionAction”,以跟踪客户在其网站上进行的购买交易(以及可选的其他客户操作)。

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

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

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

前提条件

开始之前,请确保您拥有 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.v21.enums.ConversionActionCategoryEnum.ConversionActionCategory;
import com.google.ads.googleads.v21.enums.ConversionActionStatusEnum.ConversionActionStatus;
import com.google.ads.googleads.v21.enums.ConversionActionTypeEnum.ConversionActionType;
import com.google.ads.googleads.v21.errors.GoogleAdsError;
import com.google.ads.googleads.v21.errors.GoogleAdsException;
import com.google.ads.googleads.v21.resources.ConversionAction;
import com.google.ads.googleads.v21.resources.ConversionAction.ValueSettings;
import com.google.ads.googleads.v21.services.ConversionActionOperation;
import com.google.ads.googleads.v21.services.ConversionActionServiceClient;
import com.google.ads.googleads.v21.services.MutateConversionActionResult;
import com.google.ads.googleads.v21.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.V21.Errors;
using Google.Ads.GoogleAds.V21.Resources;
using Google.Ads.GoogleAds.V21.Services;
using System;
using static Google.Ads.GoogleAds.V21.Enums.ConversionActionCategoryEnum.Types;
using static Google.Ads.GoogleAds.V21.Enums.ConversionActionStatusEnum.Types;
using static Google.Ads.GoogleAds.V21.Enums.ConversionActionTypeEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V21
{
    /// <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.V21.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\V21\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V21\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V21\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\V21\Enums\ConversionActionCategoryEnum\ConversionActionCategory;
use Google\Ads\GoogleAds\V21\Enums\ConversionActionStatusEnum\ConversionActionStatus;
use Google\Ads\GoogleAds\V21\Enums\ConversionActionTypeEnum\ConversionActionType;
use Google\Ads\GoogleAds\V21\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V21\Resources\ConversionAction;
use Google\Ads\GoogleAds\V21\Resources\ConversionAction\ValueSettings;
use Google\Ads\GoogleAds\V21\Services\ConversionActionOperation;
use Google\Ads\GoogleAds\V21\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)
            ->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
from google.ads.googleads.v21.resources.types.conversion_action import (
    ConversionAction,
)
from google.ads.googleads.v21.services.services.conversion_action_service import (
    ConversionActionServiceClient,
)
from google.ads.googleads.v21.services.types.conversion_action_service import (
    ConversionActionOperation,
    MutateConversionActionsResponse,
)


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


if __name__ == "__main__":
    parser: argparse.ArgumentParser = 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: argparse.Namespace = parser.parse_args()

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

    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'
require_relative '../shared/error_handler.rb'

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
    GoogleAdsErrorHandler.handle_google_ads_error(e)
    raise # Re-raise the error to maintain original script behavior.
  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::V21::Resources::ConversionAction;
use Google::Ads::GoogleAds::V21::Resources::ValueSettings;
use Google::Ads::GoogleAds::V21::Enums::ConversionActionCategoryEnum
  qw(DEFAULT);
use Google::Ads::GoogleAds::V21::Enums::ConversionActionTypeEnum   qw(WEBPAGE);
use Google::Ads::GoogleAds::V21::Enums::ConversionActionStatusEnum qw(ENABLED);
use
  Google::Ads::GoogleAds::V21::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::V21::Resources::ConversionAction->new({
      name                          => $conversion_action_name,
      category                      => DEFAULT,
      type                          => WEBPAGE,
      status                        => ENABLED,
      viewThroughLookbackWindowDays => 15,
      valueSettings                 =>
        Google::Ads::GoogleAds::V21::Resources::ValueSettings->new({
          defaultValue          => 23.41,
          alwaysUseDefaultValue => "true"
        })});

  # Create a conversion action operation.
  my $conversion_action_operation =
    Google::Ads::GoogleAds::V21::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 设置为 WEBPAGE,因为这些购买事件发生在网站上。

  • 可出价 - 将主要转化操作(购买)设置为 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。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:设置网页上所有事件共有的参数,例如币种。

以下示例是用于向 Google Ads 发送数据的全局网站代码的 JavaScript 代码段。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 中的增强型转化客户数据政策