4.1.5 轉換追蹤

價值與業務影響


為了有效地為商家客戶廣告活動提供 Google 生態系統強大的機器學習和分析功能,您需要在客戶網站上置入轉換追蹤和再行銷代碼。

Google Ads 中的轉換:使用者在點擊廣告後採取特定動作,例如購買產品、安裝行動應用程式或註冊電子郵件名單。轉換追蹤功能可提供重要深入分析資料,幫助您瞭解使用者查看或點擊廣告後採取的動作,包括計算及比較投資報酬率等資訊,協助客戶決定要將重心放在哪些廣告支出上。追蹤功能也能確保資料可用於對帳。訂單會因產品或類別而異,因此轉換追蹤也可用來瞭解特定商家資訊群組轉換成銷售的成效。

「轉換目標」是一組具有相同目標的轉換動作。舉例來說,「購買」的轉換目標可以是「網站購買」和「商店銷售」做為轉換動作。

轉換動作仍會用於追蹤轉換及最佳化廣告活動。您需要建立轉換動作,並在 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 設為 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,用於儲存客戶的專屬 ID,或是將客戶帶進網站的廣告點擊。這些 Cookie 會透過轉換追蹤代碼所含的 Google 點擊 ID (GCLID) 參數接收廣告點擊資訊。您必須啟用廣告主的網站和待開發客戶追蹤系統來擷取並儲存 GCLID,這是 Google Ads 為每次 Google 廣告曝光提供的專屬 ID。

進一步瞭解全域代碼和安裝位置

Google 代碼 (gtag.js) 是代碼架構和 API,可讓您將事件資料同時傳送到 Google Ads 和 Google Analytics (分析)。全域網站代碼會與事件程式碼片段或電話程式碼片段共同追蹤轉換。將 Google 代碼加進廣告客戶網站每個網頁的 <head> 部分,並設為與 Google Ads 搭配運作。接著,您就可以使用 gtag() 指令擷取事件並傳送資料至 Google Ads。如要瞭解這項功能的運作方式,請參閱「使用全域網站代碼進行 Google Ads 轉換追蹤」一文。

您可以搭配 Google 代碼使用下列指令:

  • config: 初始化 Google 產品 (Google Ads、Analytics (分析) 等)、進行設定,並準備將資料傳送至帳戶。

  • 事件:傳送購買等事件或加入購物車,即可登錄轉換 (次要轉換動作)。建議您查看 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 進行分析。

預期結果是,客戶至少會收到 gtag('consent', 'update' {...}) 呼叫,且無須採取任何行動。確保 Google 代碼 (Google Ads、Floodlight、Google Analytics (分析)、轉換連接器) 能讀取最新的使用者同意聲明狀態,並透過參數 &gcs,將狀態加進 Google 的網路要求中。

額外的導入步驟是部署或協助廣告客戶部署 (例如透過 UI) 部署 gtag('consent', default' {...}) 狀態,並解除封鎖 Google 代碼 (例如:未啟用以同意聲明為準的條件觸發條件),以便讓同意聲明模式以含同意聲明的方式觸發這些代碼。

如需導入詳情,請參閱「管理同意聲明設定 (網站)」一文。

提示

在 Google Ads 管理員帳戶中,只要使用一段轉換程式碼標記,即可跨所有廣告客戶追蹤轉換。請參閱「關於跨帳戶轉換追蹤」一文。

若想測試轉換追蹤導入作業是否正常運作,最好的方法就是前往任一商家網站 (或內部測試網站) 實際購買。接著,您便可在 Google Tag Assistant 工具中觀察這份疑難排解指南,確認 Google Ads 已偵測到代碼並順利記錄轉換。 如需其他疑難排解資訊,請參閱「排解全網站標記的問題」一文。

您可以使用強化轉換來補強上述轉換標記,進而提高轉換評估的準確度,並取得更強大的出價。 進一步瞭解如何設定強化轉換。 導入強化轉換前,您應確保商家遵守 Google Ads 的強化轉換客戶資料政策