4.1.5 轉換追蹤

價值與業務影響


為了有效提供 Google 生態系統中強大的機器學習和 若要進行商家客戶廣告活動的數據分析 您需要在 Analytics 中 客戶網站上的追蹤和再行銷代碼。

Google Ads 中的轉換:使用者採取某些指定動作時 例如購買產品、安裝行動應用程式等 或註冊加入電子郵件名單轉換追蹤提供重要的深入分析 轉換為使用者以及使用者在瀏覽或點擊廣告後採取的動作,包括 計算並比較投資報酬率,進而協助客戶 決定廣告支出的優先順序。追蹤也有助於確保 這裡顯示的資料 可用於對帳訂單商品因 追蹤產品或類別 所以轉換追蹤也可協助您 特定商家資訊群組能轉換到銷售。

轉換目標是指包含相同內容的一組轉換動作 基本目標例如「購買」可以是設有 「網站購買」和「商店銷售」視為轉換動作

轉換動作仍會用於追蹤轉換及最佳化 廣告活動。您在「轉換」中建立轉換動作和 Google 群組 但縝密健全的倫理程序 也有助於達到產品開發目標

購物轉換動作

導入這裡描述的轉換追蹤,就能 Google Ads 帳戶,以便評估購物轉換次數和價值 。否則您將無法 以廣告投資報酬率評估廣告活動帶來的業務價值 (廣告投資報酬率) 廣告支出)。還會傳送其他資料信號,讓廣告活動 並獲得最佳成效

其他轉換動作

雖然只需完成購物轉換動作,但追蹤其他相關 轉換動作可提供額外的商家洞察資料。三 建議您盡可能記錄所有資訊,同時導入 核心轉換動作建議轉換動作的完整清單 當中列出「技術 API 指南」部分。

一般而言,建議擷取下列項目:

  • 與價值直接相關的任何成功事件
  • 促成核心轉換的成功事件,例如 add_to_cart 和 註冊。
  • 可幫助廣告客戶瞭解他們如何互動的參與和使用者互動 與自家使用者互動

次要轉換動作僅用於觀察和製作報表 影響出價。進一步瞭解主要和次要轉換動作

使用者體驗指南


為了盡可能降低發生錯誤的風險,建議您導入轉換功能 以程式輔助的方式進行追蹤,而不必輸入商家資料,但您必須確保 您的商家知道轉換追蹤已設定完成。

如果商家連結現有的 Google Ads 帳戶,建議您顯示 系統通知這位客戶帳戶可能已啟用轉換追蹤 設定,否則可能必須解決衝突問題。顯示範例 。

connect_your_google_ads_account

技術指南


以下是轉換追蹤的運作原理。本節將詳細說明 步驟:

  1. 您在商家的 Google Ads 帳戶中建立「ConversionAction」後, 追蹤他們在網站上完成的購買 (以及其他客戶動作)。

  2. 您將該轉換動作的代碼或程式碼片段,加到網站上,或是 行動應用程式詳情請參閱「為網站設定轉換追蹤」一文。

  3. 當客戶點擊廣告時,系統會在 客戶的電腦或行動裝置上

  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)

      

小茹

#!/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 轉換動作 (購買) 以提升銷售量為目標來最佳化廣告活動。 針對次要轉換動作 (例如將 Google 代碼加入購物車) 將值設為 false

  • 類別 - 針對每個轉換動作 (主要或 次要),請設定 ConversionActionCategory。 相關對話動作類別如下: 每種建議導入的 7 個轉換動作。 請注意,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_levelCAMPAIGN (而不是 CUSTOMER),因為這會引導該廣告活動使用 帳戶預設目標),但還是建議您再次檢查 。

擷取轉換動作的代碼

建立轉換動作後,請務必插入 對應的程式碼片段,稱為「標記」 廣告客戶的網站。為確保 Google Ads 能評估所有轉換 無論客戶的瀏覽器為何,請使用 新版 Google Ads 轉換追蹤代碼。這個廣告代碼包含 部分:

  • global_site_tag,必須安裝在 廣告客戶的網站。

  • event_snippet,應放置在以表示 轉換動作,例如結帳確認或待開發客戶提交頁面。

您可以使用 ConversionActionService 擷取這兩個部分。

這種代碼會設定 Cookie 來儲存客戶或廣告的專屬 ID 也就是將客戶帶往網站的點擊Cookie 收到廣告點擊 Google 點擊 ID (GCLID) 參數中的資訊 。您必須啟用廣告主的網站 待開發客戶追蹤系統,以擷取並儲存 Google 點擊 ID,也就是 Google Ads 會為 Google 廣告帶來每個曝光的次數。

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

Google 代碼 (gtag.js) 是代碼架構和 API,可讓您 將事件資料同時傳送到 Google Ads 和 Google Analytics。全域網站代碼 可與事件程式碼片段或電話程式碼片段共同追蹤 轉換。在每個網頁的 <head> 區段中加入 Google 代碼 並設定成與 Google Ads 搭配使用接著 使用 gtag() 指令擷取事件並將資料傳送至 Google Ads。 如要瞭解運作方式,請參閱: 使用全域網站代碼來追蹤 Google Ads 轉換

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

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

  • event:如要登錄轉換,請傳送下列事件: 購買 (建議) 或加入購物車 (次要轉換動作)。 建議您參閱 gtag.js 事件參考指南

  • set:設定網頁上所有事件通用的參數,例如貨幣。

以下範例是 JavaScript 程式碼片段,將全域網站代碼加到 將資料傳送給 Google Ads。GOOGLE_CONVERSION_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」欄每個 Pod 的 並指定每個帳戶的轉換 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 標記開發人員帳戶,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>

雖然部分參數為選用參數,但建議您盡可能加入大量參數 每事件的資訊進一步瞭解哪些參數 都可供不同活動類型使用

參數可額外提供有關使用者互動方式的額外資訊 互動情形

如果您想根據點擊評估轉換事件 (例如以 cat 顯示在按鈕的按鈕或動態回應中)。 但您也可以改用下列程式碼片段:

<!-- 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、轉換連接器) 能讀取最新的使用者同意聲明狀態,並將狀態納入聯播網 向 Google 提出要求 (透過參數 &gcs)。

額外的導入步驟是部署或協助廣告客戶 (例如透過使用者介面) gtag('consent', default' {...}) 狀態,然後 解除封鎖 Google 代碼 (例如:不根據同意聲明觸發條件式觸發) 讓同意聲明模式,以同意聲明相關方式觸發事件。

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

提示

您可以透過 Google Ads 管理員帳戶, 廣告客戶帳戶。詳情請見 關於跨帳戶轉換追蹤

測試轉換追蹤導入情況的最佳方式就是 工作是前往 網站 (或內部測試網站) 實際購物 接著,您就可以在 Google Tag Assistant 工具中觀察 請使用這份疑難排解指南 確認 Google Ads 已偵測到您的代碼 且正在記錄轉換。 如需其他疑難排解資訊,請參閱「排解全網站標記的問題」一文。

您可以使用強化轉換,補充先前的轉換標記。 進而提高轉換評估的準確度 並提高出價效益 進一步瞭解如何設定強化轉換。 導入強化轉換前, 請確保您的商家遵守 Google Ads 中的強化轉換客戶資料政策