Google 跟踪代码管理器 API - 开发者指南

本开发者指南逐步介绍了如何通过跟踪代码管理器 API 访问 Google 跟踪代码管理器帐号以及创建和管理实体。

简介

本指南逐步介绍了如何访问和配置 Google 跟踪代码管理器帐号。在完成本指南后,您将对执行以下任务有基本的了解:

  • 创建跟踪代码管理器服务对象。
  • 对用户进行身份验证和授权。
  • 使用跟踪代码管理器 API 访问和管理资源。

准备工作

在开始学习本指南之前,我们建议您访问以下网站,先熟悉一下 Google 跟踪代码管理器:

  • 使用入门 - 本用户指南将让您了解如何开始使用 Google 跟踪代码管理器。
  • API 参考 - 了解 API 接口及其支持的操作。

使用测试帐号

如果您打算使用跟踪代码管理器 API 来创建、配置或删除实体,那么我们建议您使用测试帐号对代码进行实现和验证,因为使用测试帐号可帮助您避免意外地对有效帐号进行任何更改。在使用测试帐号完成测试并确认代码运行正常后,您再通过真实帐号开始进行实现。

选择语言

本指南包含多种编程语言。请选择您要使用的语言:

Java


本指南中的所有代码段都提供了 Java 版本。

Python


本指南中的所有代码段都提供了 Python 版本。

程序概览

本指南采用的示例程序是一个命令行应用。它在获取帐号 ID 后,会查找名为 Greetings 的容器,并在该容器中创建 Universal Analytics 代码。该代码会在用户访问 hello-world.html 时,发送一次网页浏览匹配。

要开发此应用,您需要执行以下步骤:

  1. 在 Google API 控制台中设置环境和项目。
  2. 创建跟踪代码管理器服务对象。
    1. 授权访问跟踪代码管理器帐号。
    2. 创建跟踪代码管理器服务对象。
  3. 查询 API、处理响应并输出结果。
    1. 获取一个初始化的跟踪代码管理器服务对象。
    2. 使用跟踪代码管理器服务对象查询跟踪代码管理器 API,以便执行下列任务:
      1. 检索经过身份验证的 Google 跟踪代码管理器帐号的 Greetings 容器。
      2. 创建 Universal Analytics 代码。
      3. 创建触发代码的规则。
      4. 更新要依据规则触发的代码。

设置您的环境和项目

创建 Greetings 容器

本指南假设您已拥有 Google 跟踪代码管理器帐号及名为 Greetings 的容器。当然,您可以按照设置和工作流程(网页)的说明,创建一个帐号和一个名为 Greetings容器

安装客户端库

在开始之前,请安装并配置 Google API 客户端库

在 Google API 控制台中创建和配置项目

要开始使用跟踪代码管理器 API,您先需要使用设置工具,按该工具的引导在 Google API 控制台中创建项目、启用 API 以及创建凭据。

本指南使用已安装的应用的身份验证流程。请按照以下说明创建项目凭据。看到系统提示时,请为 APPLICATION TYPE 选择 Installed Application,然后为 INSTALLED APPLICATION TYPE 选择 Other

  1. 在“凭据”页面上,请依次点击创建凭据 > OAuth 客户端 ID 创建 OAuth 2.0 凭据,或依次点击创建凭据 > 服务帐号密钥创建服务帐号。
  2. 如果创建的是 OAuth 客户端 ID,请选择应用类型。
  3. 填写表单并点击创建

“凭据”页面会列出应用的客户端 ID 和服务帐号密钥。您可以点击客户端 ID 查看详情,其中的具体参数会因 ID 类型而异,但通常会包含电子邮件地址、客户端密钥、JavaScript 来源和重定向 URI。

点击下载 JSON 按钮下载客户端详细信息,将此文件重命名为 client_secrets.json。稍后,我们将使用此文件进行身份验证。

创建跟踪代码管理器服务对象

您可以使用跟踪代码管理器 service 对象发出 API 请求。

要创建跟踪代码管理器服务对象,请按以下步骤操作:

  1. 授权访问 Google 跟踪代码管理器帐号。
  2. 实例化跟踪代码管理器服务对象。

授权访问 Google 跟踪代码管理器帐号

当用户启动使用 Google 跟踪代码管理器 API 构建的应用时,他们必须向该应用授予访问其 Google 跟踪代码管理器帐号的权限。此过程称为授权。我们建议您采用 OAuth 2.0 对用户进行授权。如需了解更多信息,请参阅跟踪代码管理器 API 授权

通过使用上面创建的项目和客户端详细信息,以下代码对应用的用户进行身份验证,并代表他们请求访问 Google 跟踪代码管理器的权限。

该应用将尝试打开默认浏览器,并将用户导航到 google.com 上托管的网址。系统将提示用户登录,并向应用授予访问其跟踪代码管理器帐号的权限。获得访问权限后,该应用会尝试读取浏览器窗口中的代码,然后关闭窗口。

注意:如果发生错误,应用将转而提示用户在命令行上输入其授权代码。

Java

/**
 * Access and manage a Google Tag Manager account.
 */

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.tagmanager.Tagmanager;
import com.google.api.services.tagmanager.TagmanagerScopes;
import com.google.api.services.tagmanager.model.Condition;
import com.google.api.services.tagmanager.model.Container;
import com.google.api.services.tagmanager.model.Parameter;
import com.google.api.services.tagmanager.model.Rule;
import com.google.api.services.tagmanager.model.Tag;

import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class HelloWorld {
  // Path to client_secrets.json file downloaded from the Developer's Console.
  // The path is relative to HelloWorld.java.
  private static final String CLIENT_SECRET_JSON_RESOURCE = "client_secrets.json";

  // The directory where the user's credentials will be stored for the application.
  private static final File DATA_STORE_DIR = new File("PATH_TO_DIRECTORY");

  private static final String APPLICATION_NAME = "HelloWorld";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static NetHttpTransport httpTransport;
  private static FileDataStoreFactory dataStoreFactory;

  public static void main(String[] args) {
    try {
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

      // Authorization flow.
      Credential credential = authorize();
      Tagmanager manager = new Tagmanager.Builder(httpTransport, JSON_FACTORY, credential)
          .setApplicationName(APPLICATION_NAME).build();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static Credential authorize() throws Exception {
    // Load client secrets.
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(HelloWorld.class.getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE)));

    // Set up authorization code flow for all auth scopes.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
        JSON_FACTORY, clientSecrets, TagmanagerScopes.all()).setDataStoreFactory(dataStoreFactory)
        .build();

    // Authorize.
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  }
}

    

Python

"""Access and manage a Google Tag Manager account."""

import argparse
import sys

import httplib2

from apiclient.discovery import build
from oauth2client import client
from oauth2client import file
from oauth2client import tools

def GetService(api_name, api_version, scope, client_secrets_path):
  """Get a service that communicates to a Google API.

  Args:
    api_name: string The name of the api to connect to.
    api_version: string The api version to connect to.
    scope: A list of strings representing the auth scopes to authorize for the
      connection.
    client_secrets_path: string A path to a valid client secrets file.

  Returns:
    A service that is connected to the specified API.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      client_secrets_path, scope=scope,
      message=tools.message_if_missing(client_secrets_path))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage(api_name + '.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  # Build the service object.
  service = build(api_name, api_version, http=http)

  return service

def main(argv):
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers']

  # Authenticate and construct service.
  service = GetService('tagmanager', 'v1', scope, 'client_secrets.json')

if __name__ == '__main__':
  main(sys.argv)
    

查询跟踪代码管理器 API

跟踪代码管理器服务对象可用于查询跟踪代码管理器 API。要实现示例程序,请按以下步骤操作:

  1. 检索 Greetings 容器
  2. 创建 Universal Analytics 代码
  3. 创建触发代码的规则
  4. 更新要依据规则触发的代码

1. 检索 Greetings 容器

下面的函数说明了如何使用跟踪代码管理器服务对象查询跟踪代码管理器 API,以列出帐号的所有容器,并检索名为 Greetings 的容器。

Java

  /*
   * Find the greetings container ID.
   *
   * @param service the Tag Manager service object.
   * @param accountId the ID of the Tag Manager account from which to retrieve the
   *    Greetings container.
   *
   * @return the greetings container if it exists.
   *
   */
  private static Container findGreetingsContainer(Tagmanager service, String accountId)
      throws Exception {
    for (Container container :
        service.accounts().containers().list(accountId).execute().getContainers()) {
      if (container.getName().equals("Greetings")) {
        return container;
      }
    }
    throw new IllegalArgumentException("No container named Greetings in given account");
  }
    

Python

def FindGreetingsContainerId(service, account_id):
  """Find the greetings container ID.

  Args:
    service: the Tag Manager service object.
    account_id: the ID of the Tag Manager account from which to retrieve the
      Greetings container.

  Returns:
    The dictionary that represents the greetings container if it exists, or None
    if it does not.
  """
  # Query the Tag Manager API to list all containers for the given account.
  container_wrapper = service.accounts().containers().list(
      accountId=account_id).execute()

  # Find and return the Greetings container if it exists.
  for container in container_wrapper['containers']:
    if container['name'] == 'Greetings':
      return container['containerId']
  return None
    

接下来,根据给定的跟踪代码管理器 accountId,更新程序的主执行分支以调用 findGreetingsContainer 函数。例如:

Java

  public static void main(String[] args) {
    try {
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

      // Authorization flow.
      Credential credential = authorize();
      Tagmanager manager = new Tagmanager.Builder(httpTransport, JSON_FACTORY, credential)
          .setApplicationName(APPLICATION_NAME).build();

      // Get tag manager account ID.
      String accountId = args[0];

      // Find the greetings container.
      Container greetings = findGreetingsContainer(manager, accountId);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
    

Python

def main(argv):
  # Get tag manager account ID from command line.
  assert len(argv) == 2 and 'usage: gtm-api-hello-world.py <account_id>'
  account_id = str(argv[1])

  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers']

  # Authenticate and construct service.
  service = GetService('tagmanager', 'v1', scope, 'client_secrets.json')

  # Find the greetings container.
  container_id = FindGreetingsContainerId(service, account_id)
    

2. 创建 Universal Analytics 代码

以下代码段使用跟踪代码管理器 API 创建 Universal Analytics 代码。有关创建工作区时可设置的必需属性和可选属性列表,请查看工作区创建方法参考;如需了解每种代码类型的属性列表,请查看代码字典参考

Java

  /**
   * Create the Universal Analytics Hello World Tag.
   *
   * @param accountId the ID of the account holding the container.
   * @param containerId the ID of the container to create the tag in.
   * @param service the Tag Manager service object.
   * @return the newly created Tag resource.
   */
  private static Tag createHelloWorldTag(String accountId, String containerId, Tagmanager service) {
    Tag ua = new Tag();
    ua.setName("Universal Analytics Hello World");
    ua.setType("ua");

    List<Parameter> uaParams = new ArrayList<Parameter>();
    Parameter trackingId = new Parameter();
    trackingId.setKey("trackingId").setValue(UA_TRACKING_ID).setType("template");
    uaParams.add(trackingId);

    ua.setParameter(uaParams);
    ua = service.accounts().containers().tags().create(accountId, containerId, ua)
        .execute();

    return ua;
  }

    

Python

def CreateHelloWorldTag(service, account_id, container_id, tracking_id):
  """Create the Universal Analytics Hello World Tag.

  Args:
    service: the Tag Manager service object.
    account_id: the ID of the account holding the container.
    container_id: the ID of the container to create the tag in.
    tracking_id: the Universal Analytics tracking ID to use.

  Returns:
    The API response as a dict representing the newly created Tag resource
    or an error.
  """

  hello_world_tag = {
      'name': 'Universal Analytics Hello World',
      'type': 'ua',
      'parameter': [{
          'key': 'trackingId',
          'type': 'template',
          'value': str(tracking_id),
      }],
  }

  response = service.accounts().containers().tags().create(
      accountId=account_id,
      containerId=container_id,
      body=hello_world_tag).execute()

  return response

    

3. 创建触发代码的规则

创建代码后,下一步是创建在以 hello-world.html 结束的任何页面上触发的规则。

该规则将命名为 Hello World Rule,并将在满足使用 endsWith 条件类型的一个条件时触发。例如:

Java

  /**
   * Create the Hello World Rule.
   *
   * @param accountId the ID of the account holding the container.
   * @param containerId the ID of the container to create the rule in.
   * @param service the Tag Manager service object.
   *
   * @return the newly created Rule resource.
   **/
  private static Rule createHelloWorldRule(String accountId, String containerId, Tagmanager service) {
    Rule helloWorld = new Rule();
    helloWorld.setName("Hello World");

    List<Condition> conditions = new ArrayList<Condition>();
    Condition endsWithHelloWorld = new Condition();
    endsWithHelloWorld.setType("endsWith");
    List<Parameter> params = new ArrayList<Parameter>();
    params.add(new Parameter().setKey("arg0").setValue("{{url}}").setType("template"));
    params.add(new Parameter().setKey("arg1").setValue("hello-world.html").setType("template"));
    endsWithHelloWorld.setParameter(params);
    conditions.add(endsWithHelloWorld);

    helloWorld.setCondition(conditions);
    helloWorld = service.accounts().containers().rules().create(accountId, containerId, helloWorld)
        .execute();

    return helloWorld;
  }

    

Python

def CreateHelloWorldRule(service, account_id, container_id):
  """Create the Hello World Rule.

  Args:
    service: the Tag Manager service object.
    account_id: the ID of the account holding the container.
    container_id: the ID of the container to create the rule in.

  Returns:
    The API response as a dict representing the newly created Rule resource
    or an error.
  """

  hello_world_rule = {
      'name': 'Hello World Rule',
      'condition': [{
          'parameter': [
              {'key': 'arg0', 'type': 'template', 'value': '{{url}}'},
              {'key': 'arg1', 'type': 'template', 'value': 'hello-world.html'},
          ],
          'type': 'endsWith',
      }]
  }

  response = service.accounts().containers().rules().create(
      accountId=account_id,
      containerId=container_id,
      body=hello_world_rule).execute()

  return response

    

4. 更新要依据规则触发的代码

在创建完代码和规则后,需将两者关联起来。为此,请将 ruleId 添加到代码所关联的 firingRuleIds 列表中。例如:

Java

  /**
   * Update a Tag with a Rule.
   *
   * @param tag the tag to associate with the rule.
   * @param rule the rule to associate with the tag.
   *
   */
  private static void fireTagOnRule(Tag tag, Rule rule) {
    List<String> firingRuleIds = new ArrayList<String>();
    firingRuleIds.add(rule.getRuleId());
    tag.setFiringRuleId(firingRuleIds);
  }
    

Python

def UpdateHelloWorldTagWithRule(service, account_id, container_id, tag_id,
                                rule_id):
  """Update a Tag with a Rule.

  Args:
    service: the Tag Manager service object.
    account_id:  the ID of the account holding the container.
    container_id: the ID of the container to create the rule in.
    tag_id: the ID of the tag to associate with the rule.
    rule_id: the ID of the rule to associate with the tag.
  """
  # Get the tag to update.
  tag = service.accounts().containers().tags().get(
      accountId=account_id,
      containerId=container_id,
      tagId=tag_id).execute()

  # Update the Firing Rule for the Tag.
  tag['firingRuleId'] = [rule_id]

  # Update the Tag.
  response = service.accounts().containers().tags().update(
      accountId=account_id,
      containerId=container_id,
      tagId=tag_id,
      body=tag).execute()
    

接下来,更新程序的主执行分支以调用 create 和 update 函数。例如:

Java

  public static void main(String[] args) {
    try {
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

      // Authorization flow.
      Credential credential = authorize();
      Tagmanager manager = new Tagmanager.Builder(httpTransport, JSON_FACTORY, credential)
          .setApplicationName(APPLICATION_NAME).build();

      // Get tag manager account ID.
      String accountId = args[0];

      // Find the greetings container.
      Container greetings = findGreetingsContainer(manager, accountId);
      String containerId = greetings.getContainerId();

      // Create the hello world tag.
      Tag ua = createUATag(accountId, containerId, manager);

      // Create the hello world rule.
      Rule hello = createHelloWorldRule(accountId, containerId, manager);

      // Update the hello world tag to fire based on the hello world tag.
      fireTagOnRule(ua, hello);
      ua = manager.accounts().containers().tags().update(accountId, containerId, ua.getTagId(), ua)
          .execute();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
    

Python

def main(argv):
  # Get tag manager account ID from command line.
  assert len(argv) == 2 and 'usage: gtm-api-hello-world.py <account_id>'
  account_id = str(argv[1])

  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers']

  # Authenticate and construct service.
  service = GetService('tagmanager', 'v1', scope, 'client_secrets.json')

  # Find the greetings container.
  container_id = FindGreetingsContainerId(service, account_id)

  # Create the hello world tag.
  tag = CreateHelloWorldTag(service, account_id, container_id, 'UA-1234-5')

  # Create the hello world rule.
  rule = CreateHelloWorldRule(service, account_id, container_id)

  # Update the hello world tag to fire based on the hello world tag.
  UpdateHelloWorldTagWithRule(service, account_id, container_id, tag['tagId'], rule['ruleId'])
    

后续步骤

在熟悉了 API 的工作原理之后,您还可以浏览一些额外资源,包括: