此开发者指南逐步介绍了如何通过跟踪代码管理器 API v2 访问、创建和管理 Google 跟踪代码管理器账号中的实体。
简介
本指南逐步介绍了如何访问和配置 Google 跟踪代码管理器账号。查看完本指南后,您将对执行以下任务有基本的了解:
- 创建跟踪代码管理器 service 对象。
- 对用户进行身份验证和授权。
- 使用跟踪代码管理器 API 访问和管理资源。
准备工作
在开始查看本指南之前,我们建议您访问 Google 跟踪代码管理器帮助中心,先熟悉一下 Google 跟踪代码管理器:
使用测试账号
如果您打算使用跟踪代码管理器 API 来创建、配置或删除实体,那么我们建议您使用测试账号对代码进行实现和验证,因为使用测试账号可帮助您避免意外地对有效账号进行任何更改。在使用测试账号完成测试并确认代码运行符合预期后,再通过真实账号开始进行实现。
选择语言
选择您希望了解下列哪种编程语言的示例:
本指南中的所有代码段都提供了 Python 版本。
本指南中的所有代码段都提供了 JavaScript 版本。
程序概览
本指南采用的示例程序是一个命令行应用。它在获取账号 ID 后,会查找名为“Greetings”的容器,并在该容器中创建 Universal Analytics 代码。该代码会在用户访问 hello-world.html 时,发送一次网页浏览命中。
要开发此应用,您需要执行以下步骤:
- 在 Google API 控制台中设置开发环境和项目。
- 创建跟踪代码管理器 service 对象。
- 授权访问跟踪代码管理器账号。
- 创建跟踪代码管理器 service 对象。
- 查询 API、处理响应并输出结果。
- 获取一个初始化的跟踪代码管理器 service 对象。
- 使用该跟踪代码管理器 service 对象查询跟踪代码管理器 API,以便执行下列任务:
- 为经过身份验证的 Google 跟踪代码管理器账号检索“Greetings”容器。
- 创建一个新工作区。
- 创建 Universal Analytics 代码。
- 创建用于触发代码的触发器。
- 更新要在触发器上触发的代码。
设置开发环境和项目
创建“Greetings”容器
本指南假设您已拥有 Google 跟踪代码管理器账号及名为“Greetings”的容器。当然,您可以按照设置和工作流程(网页)的说明,创建一个账号和一个名为“Greetings”的容器。
安装客户端库
在开始之前,请安装并配置 Google API 客户端库。
在 Google API 控制台中创建和配置项目
要开始使用跟踪代码管理器 API,首先需要使用设置工具,按该工具的引导在 Google API 控制台中创建项目、启用跟踪代码管理器 API 并创建凭据。
本指南使用已安装的应用身份验证流程。请按照以下说明创建项目凭据。看到系统提示后,请为 APPLICATION TYPE 选择 Installed Application
,并为 INSTALLED APPLICATION TYPE 选择 Other
。
- 在“凭据”页面上,请依次点击创建凭据 > OAuth 客户端 ID 创建 OAuth 2.0 凭据,或依次点击创建凭据 > 服务账号密钥创建服务账号。
- 如果创建的是 OAuth 客户端 ID,请选择应用类型。
- 填写表单并点击创建。
“凭据”页面现在会列出应用的客户端 ID 和服务账号密钥。您可以点击客户端 ID 查看详情,其中的具体参数会因 ID 类型而异,但可能包含电子邮件地址、客户端密钥、JavaScript 来源和重定向 URI。
点击下载 JSON 按钮下载客户端详细信息,将此文件重命名为 client_secrets.json
。稍后,我们将使用此文件进行身份验证。
创建跟踪代码管理器 service 对象
您将需要使用跟踪代码管理器 service
对象发出 API 请求。
要创建跟踪代码管理器 service 对象,请按以下步骤操作:
- 授权访问 Google 跟踪代码管理器账号。
- 实例化跟踪代码管理器 service 对象。
授权访问 Google 跟踪代码管理器账号
当用户启动使用 Google 跟踪代码管理器 API 构建的应用时,他们必须向该应用授予访问其 Google 跟踪代码管理器账号的权限。此过程称为授权。我们建议您采用 OAuth 2.0 对用户进行授权。如欲了解更多信息,请参阅跟踪代码管理器 API 授权。
通过使用上面创建的项目和客户端详细信息,以下代码对应用的用户进行身份验证,并代表他们请求访问 Google 跟踪代码管理器的权限。
该应用将尝试打开默认浏览器,并将用户导航到 google.com 上托管的网址。系统将提示用户登录,并向应用授予访问其跟踪代码管理器账号的权限。获得访问权限后,该应用会尝试读取浏览器窗口中的代码,然后关闭窗口。
注意:如果发生错误,应用将转而提示用户在命令行上输入其授权代码。
"""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', 'v2', scope, 'client_secrets.json')
if __name__ == '__main__':
main(sys.argv)
<html>
<head>
<script type="text/javascript">
// Your Client ID can be retrieved from your project in the Google
// Developer Console, https://console.developers.google.com
var CLIENT_ID = TODO;
var SCOPES = [
'https://www.googleapis.com/auth/tagmanager.manage.accounts',
'https://www.googleapis.com/auth/tagmanager.edit.containers',
'https://www.googleapis.com/auth/tagmanager.delete.containers',
'https://www.googleapis.com/auth/tagmanager.edit.containerversions',
'https://www.googleapis.com/auth/tagmanager.manage.users',
'https://www.googleapis.com/auth/tagmanager.publish'
];
// Parameter values used by the script
ACCOUNT_PATH = TODO; // such as: 'accounts/555555';
CONTAINER_NAME = 'Greetings';
WORKSPACE_NAME = 'Example workspace';
/**
* Check if current user has authorization for this application.
*
* @param {bool} immediate Whether login should use the "immediate mode", which
* causes the security token to be refreshed behind the scenes with no UI.
*/
function checkAuth(immediate) {
var authorizeCheckPromise = new Promise((resolve) => {
gapi.auth.authorize(
{ client_id: CLIENT_ID, scope: SCOPES.join(' '), immediate: immediate },
resolve);
});
authorizeCheckPromise
.then(handleAuthResult)
.then(loadTagManagerApi)
.then(runTagManagerExample)
.catch(() => {
console.log('You must authorize any access to the api.');
});
}
/**
* Check if current user has authorization for this application.
*/
function checkAuth() {
checkAuth(true);
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* @param {Event} event Button click event.
* @return {boolean} Returns false.
*/
function handleAuthClick(event) {
checkAuth();
return false;
}
/**
* Handle response from authorization server.
*
* @param {Object} authResult Authorization result.
* @return {Promise} A promise to call resolve if authorize or redirect to a
* login flow.
*/
function handleAuthResult(authResult) {
return new Promise((resolve, reject) => {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
resolve();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
reject();
}
});
}
/**
* Load Tag Manager API client library.
*
* @return {Promise} A promise the load the Tag Manager API library.
*/
function loadTagManagerApi() {
return new Promise((resolve, reject) => {
console.log('Load Tag Manager api');
gapi.client.load('tagmanager', 'v2', resolve);
});
}
/**
* Interacts with the tagmanager api v2 to create a container, workspace,
* trigger, and tag.
*
* @return {Promise} A promise to run the Tag Manager example.
*/
function runTagManagerExample() {
return new Promise((resolve, reject) => {
console.log('Running Tag Manager Example.');
resolve();
});
}
/**
* Logs an error message to the console.
*
* @param {string|Object} error The error to log to the console.
*/
function handleError(error) {
console.log('Error when interacting with GTM API');
console.log(error);
}
/**
* Wraps an API request into a promise.
*
* @param {Object} a request to the API.
* @return {Promise} A promise to execute the API request.
*/
function requestPromise(request) {
return new Promise((resolve, reject) => {
request.execute((response) => {
if (response.code) {
reject(response);
}
resolve(response);
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=checkAuth">
</script>
</head>
<body>
<div id="authorize-div" style="display: none">
<span>Authorize access to Tag Manager API</span>
<!--Button for the user to click to initiate auth sequence -->
<button id="authorize-button" onclick="handleAuthClick(event)">
Authorize
</button>
</div>
<pre id="output"></pre>
</body>
</html>
查询跟踪代码管理器 API
跟踪代码管理器 service 对象可用于查询跟踪代码管理器 API。要实现示例程序,请按以下步骤操作:
- 检索 Greetings 容器
- 创建 Universal Analytics 代码
- 创建用于触发代码的触发器
- 更新要在触发器上触发的代码
1. 检索“Greetings”容器
下面的函数说明了如何使用跟踪代码管理器 service 对象查询跟踪代码管理器 API,以列出账号的所有容器,并检索名为“Greetings”的容器。
def FindGreetingsContainer(service, account_path):
"""Find the greetings container.
Args:
service: the Tag Manager service object.
account_path: the path of the Tag Manager account from which to retrieve the
Greetings container.
Returns:
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(
parent=account_path).execute()
# Find and return the Greetings container if it exists.
for container in container_wrapper['container']:
if container['name'] == 'Greetings':
return container
return None
/**
* Returns the greetings container if it exists.
*
* @param {string} accountPath The account which contains the Greetings
* container.
* @return {Promise} A promise to find the greetings container.
*/
function findContainer(accountPath, containerName) {
console.log('Finding container in account:' + accountPath);
var request = gapi.client.tagmanager.accounts.containers.list({
'parent': accountPath
});
return requestPromise(request)
.then((response) => {
var containers = response.container || [];
var container =
containers.find((container) => container.name === containerName);
return container ||
Promise.reject('Unable to find ' + containerName +' container.');
});
}
接下来,根据给定的跟踪代码管理器 accountId
,更新程序的主执行分支以调用 findGreetingsContainer
函数。例如:
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])
account_path = 'accounts/%s' % account_id
# Define the auth scopes to request.
scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers']
# Authenticate and construct service.
service = GetService('tagmanager', 'v2', scope, 'client_secrets.json')
# Find the greetings container.
container = FindGreetingsContainer(service, account_path)
if __name__ == '__main__':
main(sys.argv)
/**
* Interacts with the tagmanager api v2 to create a container, workspace,
* trigger, and tag.
*
* @return {Promise} A promise to run the tag manager example.
*/
function runTagManagerExample() {
return new Promise((resolve, reject) => {
console.log('Running Tag Manager Example.');
var trigger = null;
var workspace = null;
findContainer(ACCOUNT_PATH, CONTAINER_NAME)
.catch(handleError);
resolve();
});
}
2. 创建一个新工作区
以下代码段使用跟踪代码管理器 API 创建新工作区,用于管理触发器和代码的各种更改。有关创建工作区时需要设置和可选择设置的属性列表,请查看工作区 create 方法参考。
def CreateWorkspace(service, container):
"""Creates a workspace named 'my workspace'.
Args:
service: the Tag Manager service object.
container: the container to insert the workspace within.
Returns:
The created workspace.
"""
return service.accounts().containers().workspaces().create(
parent=container['path'],
body={
'name': 'my workspace',
}).execute()
/**
* Creates a workspace in the Greetings container.
*
* @param {Object} container The container to create a new workspace.
* @return {Promise} A promise to create a workspace.
*/
function createWorkspace(container) {
console.log('Creating workspace in container:' + container.path);
var request = gapi.client.tagmanager.accounts.containers.workspaces.create(
{ 'parent': container.path },
{ name: WORKSPACE_NAME, description: 'my workspace created via api' });
return requestPromise(request);
}
3. 创建 Universal Analytics 代码
以下代码段使用跟踪代码管理器 API 创建 Universal Analytics 代码。有关创建代码时需要设置和可选择设置的属性列表,请查看代码 create 方法参考;如需了解每种代码类型的属性列表,请查看代码字典参考。
def CreateHelloWorldTag(service, workspace, tracking_id):
"""Create the Universal Analytics Hello World Tag.
Args:
service: the Tag Manager service object.
workspace: the workspace to create a tag within.
tracking_id: the Universal Analytics tracking ID to use.
Returns:
The created tag.
"""
hello_world_tag = {
'name': 'Universal Analytics Hello World',
'type': 'ua',
'parameter': [{
'key': 'trackingId',
'type': 'template',
'value': str(tracking_id),
}],
}
return service.accounts().containers().workspaces().tags().create(
parent=workspace['path'],
body=hello_world_tag).execute()
/**
* Creates a universal analytics tag.
*
* @param {Object} workspace The workspace to create the tag
* @return {Promise} A promise to create a hello world tag.
*/
function createHelloWorldTag(workspace) {
console.log('Creating hello world tag');
var helloWorldTag = {
'name': 'Universal Analytics Hello World',
'type': 'ua',
'parameter':
[{ 'key': 'trackingId', 'type': 'template', 'value': 'UA-1234-5' }],
};
var request =
gapi.client.tagmanager.accounts.containers.workspaces.tags.create(
{ 'parent': workspace.path }, helloWorldTag);
return requestPromise(request);
}
4. 创建用于触发代码的触发器
创建代码后,下一步是创建会在任何页面上触发的触发器。
触发器将命名为 Hello World Trigger,并将在出现任何网页浏览时触发。例如:
def CreateHelloWorldTrigger(service, workspace):
"""Create the Hello World Trigger.
Args:
service: the Tag Manager service object.
workspace: the workspace to create the trigger within.
Returns:
The created trigger.
"""
hello_world_trigger = {
'name': 'Hello World Rule',
'type': 'PAGEVIEW'
}
return service.accounts().containers().workspaces().triggers().create(
parent=workspace['path'],
body=hello_world_trigger).execute()
/**
* Creates a page view trigger.
*
* @param {Object} workspace The workspace to create the trigger in.
* @return {Promise} A promise to create a page view trigger.
*/
function createHelloWorldTrigger(workspace) {
console.log('Creating hello world trigger in workspace');
var helloWorldTrigger = { 'name': 'Hello World Trigger', 'type': 'PAGEVIEW' };
var request =
gapi.client.tagmanager.accounts.containers.workspaces.triggers.create(
{ 'parent': workspace.path }, helloWorldTrigger);
return requestPromise(request);
}
5. 更新要在触发器上触发的代码
在创建完代码和触发器后,需将两者关联起来。为此,请将 triggerId
添加到代码所关联的 firingTriggerIds
列表中。例如:
def UpdateHelloWorldTagWithTrigger(service, tag, trigger):
"""Update a Tag with a Trigger.
Args:
service: the Tag Manager service object.
tag: the tag to associate with the trigger.
trigger: the trigger to associate with the tag.
"""
# Get the tag to update.
tag = service.accounts().containers().workspaces().tags().get(
path=tag['path']).execute()
# Update the Firing Trigger for the Tag.
tag['firingTriggerId'] = [trigger['triggerId']]
# Update the Tag.
response = service.accounts().containers().workspaces().tags().update(
path=tag['path'],
body=tag).execute()
/**
* Updates a tag to fire on a particular trigger.
*
* @param {Object} tag The tag to update.
* @param {Object} trigger The trigger which causes the tag to fire.
* @return {Promise} A promise to update a tag to fire on a particular trigger.
*/
function updateHelloWorldTagWithTrigger(tag, trigger) {
console.log('Update hello world tag with trigger');
tag['firingTriggerId'] = [trigger.triggerId];
var request =
gapi.client.tagmanager.accounts.containers.workspaces.tags.update(
{ 'path': tag.path }, tag);
return requestPromise(request);
}
接下来,更新程序的主执行分支以调用 create 和 update 函数。例如:
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])
account_path = 'accounts/%s' % account_id
# Define the auth scopes to request.
scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers']
# Authenticate and construct service.
service = GetService('tagmanager', 'v2', scope, 'client_secrets.json')
# Find the greetings container.
container = FindGreetingsContainer(service, account_path)
# Create a new workspace.
workspace = CreateWorkspace(service, container)
# Create the hello world tag.
tag = CreateHelloWorldTag(
service, workspace, 'UA-1234-5')
# Create the hello world Trigger.
trigger = CreateHelloWorldTrigger(
service, workspace)
# Update the hello world tag to fire based on the hello world tag.
UpdateHelloWorldTagWithTrigger(service, tag, trigger)
if __name__ == '__main__':
main(sys.argv)
/**
* Interacts with the tagmanager api v2 to create a container, workspace,
* trigger, and tag.
*
* @return {Promise} A promise to run the tag manager example.
*/
function runTagManagerExample() {
return new Promise((resolve, reject) => {
console.log('Running Tag Manager Example.');
var trigger = null;
var workspace = null;
findContainer(ACCOUNT_PATH, CONTAINER_NAME)
.then(createWorkspace)
.then((createdWorkspace) => {
workspace = createdWorkspace;
return createHelloWorldTrigger(workspace);
})
.then((createdTrigger) => {
trigger = createdTrigger;
return createHelloWorldTag(workspace);
})
.then((createdTag) => {
return updateHelloWorldTagWithTrigger(createdTag, trigger);
})
.catch(handleError);
resolve();
});
}
完整示例
展开此部分可查看本指南中所有步骤的完整代码示例。
"""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 FindGreetingsContainer(service, account_path):
"""Find the greetings container.
Args:
service: the Tag Manager service object.
account_path: the path of the Tag Manager account from which to retrieve the
Greetings container.
Returns:
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(
parent=account_path).execute()
# Find and return the Greetings container if it exists.
for container in container_wrapper['container']:
if container['name'] == 'Greetings':
return container
return None
def CreateWorkspace(service, container):
"""Creates a workspace named 'my workspace'.
Args:
service: the Tag Manager service object.
container: the container to insert the workspace within.
Returns:
The created workspace.
"""
return service.accounts().containers().workspaces().create(
parent=container['path'],
body={
'name': 'my workspace',
}).execute()
def CreateHelloWorldTag(service, workspace, tracking_id):
"""Create the Universal Analytics Hello World Tag.
Args:
service: the Tag Manager service object.
workspace: the workspace to create a tag within.
tracking_id: the Universal Analytics tracking ID to use.
Returns:
The created tag.
"""
hello_world_tag = {
'name': 'Universal Analytics Hello World',
'type': 'ua',
'parameter': [{
'key': 'trackingId',
'type': 'template',
'value': str(tracking_id),
}],
}
return service.accounts().containers().workspaces().tags().create(
parent=workspace['path'],
body=hello_world_tag).execute()
def CreateHelloWorldTrigger(service, workspace):
"""Create the Hello World Trigger.
Args:
service: the Tag Manager service object.
workspace: the workspace to create the trigger within.
Returns:
The created trigger.
"""
hello_world_trigger = {
'name': 'Hello World Rule',
'type': 'PAGEVIEW'
}
return service.accounts().containers().workspaces().triggers().create(
parent=workspace['path'],
body=hello_world_trigger).execute()
def UpdateHelloWorldTagWithTrigger(service, tag, trigger):
"""Update a Tag with a Trigger.
Args:
service: the Tag Manager service object.
tag: the tag to associate with the trigger.
trigger: the trigger to associate with the tag.
"""
# Get the tag to update.
tag = service.accounts().containers().workspaces().tags().get(
path=tag['path']).execute()
# Update the Firing Trigger for the Tag.
tag['firingTriggerId'] = [trigger['triggerId']]
# Update the Tag.
response = service.accounts().containers().workspaces().tags().update(
path=tag['path'],
body=tag).execute()
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])
account_path = 'accounts/%s' % account_id
# Define the auth scopes to request.
scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers']
# Authenticate and construct service.
service = GetService('tagmanager', 'v2', scope, 'client_secrets.json')
# Find the greetings container.
container = FindGreetingsContainer(service, account_path)
# Create a new workspace.
workspace = CreateWorkspace(service, container)
# Create the hello world tag.
tag = CreateHelloWorldTag(
service, workspace, 'UA-1234-5')
# Create the hello world Trigger.
trigger = CreateHelloWorldTrigger(
service, workspace)
# Update the hello world tag to fire based on the hello world tag.
UpdateHelloWorldTagWithTrigger(service, tag, trigger)
if __name__ == '__main__':
main(sys.argv)
<html>
<head>
<script type="text/javascript">
// Your Client ID can be retrieved from your project in the Google
// Developer Console, https://console.developers.google.com
var CLIENT_ID = TODO;
var SCOPES = [
'https://www.googleapis.com/auth/tagmanager.manage.accounts',
'https://www.googleapis.com/auth/tagmanager.edit.containers',
'https://www.googleapis.com/auth/tagmanager.delete.containers',
'https://www.googleapis.com/auth/tagmanager.edit.containerversions',
'https://www.googleapis.com/auth/tagmanager.manage.users',
'https://www.googleapis.com/auth/tagmanager.publish'
];
// Parameter values used by the script
ACCOUNT_PATH = TODO; // such as: 'accounts/555555';
CONTAINER_NAME = 'Greetings';
WORKSPACE_NAME = 'Example workspace';
/**
* Check if current user has authorization for this application.
*
* @param {bool} immediate Whether login should use the "immediate mode",
* which causes the security token to be refreshed behind the scenes
* with no UI.
*/
function checkAuth(immediate) {
var authorizeCheckPromise = new Promise((resolve) => {
gapi.auth.authorize(
{ client_id: CLIENT_ID, scope: SCOPES.join(' '), immediate: immediate },
resolve);
});
authorizeCheckPromise
.then(handleAuthResult)
.then(loadTagManagerApi)
.then(runTagManagerExample)
.catch(() => {
console.log('You must authorize any access to the api.');
});
}
/**
* Check if current user has authorization for this application.
*/
function checkAuth() {
checkAuth(true);
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* @param {Event} event Button click event.
* @return {boolean} Returns false.
*/
function handleAuthClick(event) {
checkAuth();
return false;
}
/**
* Handle response from authorization server.
*
* @param {Object} authResult Authorization result.
* @return {Promise} A promise to call resolve if authorize or redirect to a
* login flow.
*/
function handleAuthResult(authResult) {
return new Promise((resolve, reject) => {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
resolve();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
reject();
}
});
}
/**
* Load Tag Manager API client library.
* @return {Promise} A promise to load the tag manager api library.
*/
function loadTagManagerApi() {
return new Promise((resolve, reject) => {
console.log('Load Tag Manager api');
gapi.client.load('tagmanager', 'v2', resolve);
});
}
/**
* Interacts with the tagmanager api v2 to create a container,
* workspace, trigger, and tag.
*
* @return {Promise} A promise to run the tag manager example.
*/
function runTagManagerExample() {
return new Promise((resolve, reject) => {
console.log('Running Tag Manager Example.');
var trigger = null;
var workspace = null;
findContainer(ACCOUNT_PATH, CONTAINER_NAME)
.then(createWorkspace)
.then((createdWorkspace) => {
workspace = createdWorkspace;
return createHelloWorldTrigger(workspace);
})
.then((createdTrigger) => {
trigger = createdTrigger;
return createHelloWorldTag(workspace);
})
.then((createdTag) => {
return updateHelloWorldTagWithTrigger(createdTag, trigger);
})
.catch(handleError);
resolve();
});
}
/**
* Returns the greetings container if it exists.
*
* @param {string} accountPath The account which contains the Greetings
* container.
* @param {string} containerName The name of the container to find.
* @return {Promise} A promise to find the greetings container.
*/
function findContainer(accountPath, containerName) {
console.log('Finding container in account:' + accountPath);
var request = gapi.client.tagmanager.accounts.containers.list({
'parent': accountPath
});
return requestPromise(request)
.then((response) => {
var containers = response.container || [];
var container = containers.find(
(container) => container.name === containerName);
return container || Promise.reject(
'Unable to find ' + containerName +' container.');
});
}
/**
* Creates a workspace in the Greetings container.
*
* @param {Object} container The container to create a new workspace.
* @return {Promise} A promise to create a workspace.
*/
function createWorkspace(container) {
console.log('Creating workspace in container:' + container.path);
var request = gapi.client.tagmanager.accounts.containers.workspaces.create(
{ 'parent': container.path },
{ name: WORKSPACE_NAME, description: 'my workspace created via api' });
return requestPromise(request);
}
/**
* Creates a page view trigger.
*
* @param {Object} workspace The workspace to create the trigger in.
* @return {Promise} A promise to create a page view trigger.
*/
function createHelloWorldTrigger(workspace) {
console.log('Creating hello world trigger in workspace');
var helloWorldTrigger =
{ 'name': 'Hello World Trigger', 'type': 'PAGEVIEW' };
var request =
gapi.client.tagmanager.accounts.containers.workspaces.triggers.create(
{ 'parent': workspace.path }, helloWorldTrigger);
return requestPromise(request);
}
/**
* Creates a universal analytics tag.
*
* @param {Object} workspace The workspace to create the tag
* @return {Promise} A promise to create a hello world tag.
*/
function createHelloWorldTag(workspace) {
console.log('Creating hello world tag');
var helloWorldTag = {
'name': 'Universal Analytics Hello World',
'type': 'ua',
'parameter':
[{ 'key': 'trackingId', 'type': 'template', 'value': 'UA-1234-5' }],
};
var request =
gapi.client.tagmanager.accounts.containers.workspaces.tags.create(
{ 'parent': workspace.path }, helloWorldTag);
return requestPromise(request);
}
/**
* Updates a tag to fire on a particular trigger.
*
* @param {Object} tag The tag to update.
* @param {Object} trigger The trigger which causes the tag to fire.
* @return {Promise} A promise to update a tag to fire on a particular
* trigger.
*/
function updateHelloWorldTagWithTrigger(tag, trigger) {
console.log('Update hello world tag with trigger');
tag['firingTriggerId'] = [trigger.triggerId];
var request =
gapi.client.tagmanager.accounts.containers.workspaces.tags.update(
{ 'path': tag.path }, tag);
return requestPromise(request);
}
/**
* Logs an error message to the console.
*
* @param {string|Object} error The error to log to the console.
*/
function handleError(error) {
console.log('Error when interacting with GTM API');
console.log(error);
}
/**
* Wraps an API request into a promise.
*
* @param {Object} request the API request.
* @return {Promise} A promise to execute the api request.
*/
function requestPromise(request) {
return new Promise((resolve, reject) => {
request.execute((response) => {
if (response.code) {
reject(response);
}
resolve(response);
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=checkAuth">
</script>
</head>
<body>
<div id="authorize-div" style="display: none">
<span>Authorize access to Tag Manager API</span>
<!--Button for the user to click to initiate auth sequence -->
<button id="authorize-button" onclick="handleAuthClick(event)">
Authorize
</button>
</div>
<pre id="output"></pre>
</body>
</html>
后续步骤
在熟悉了 API 的工作原理之后,您还可以浏览一些额外资源,包括: