このデベロッパー ガイドでは、Tag Manager API v2 を使用して、Google タグ マネージャー アカウント内のエンティティにアクセスしたり、エンティティを作成、管理したりするための手順について説明します。
概要
このガイドでは、Google タグ マネージャー アカウントにアクセスして設定するためのさまざまな手順について説明します。このガイドを読むことで、次のタスクに関する基礎知識を身に付けることができます。
- タグ マネージャーのサービス オブジェクトを作成する。
- ユーザーの認証と承認を行う。
- Tag Manager API を使用してリソースにアクセスし、管理する。
はじめに
このガイドを読む前に、Google タグ マネージャー ヘルプセンターで Google タグ マネージャーの知識を深めておくことをおすすめします。
テスト アカウントを使用する
Tag Manager API を使ってエンティティを作成、設定、削除する場合は、テスト アカウントでコードを実装して検証することをおすすめします。テスト アカウントを使うことで、アクティブなアカウントに誤って変更が加えられる事態を防ぐことができます。テスト アカウントを使ってコードをテストし、コードが期待どおりに機能していることを確認できたら、実際のアカウントでコードを実装できるようになります。
言語を選択する
以下の中から、使用するプログラミング言語を選択します。
このガイド内のすべてのコード例で、Python のサンプルを紹介しています。
このガイド内のすべてのコード例で、JavaScript のサンプルを紹介しています。
プログラムの概要
このガイドに含まれているサンプル プログラムは、コマンドライン アプリです。アカウント ID が指定されると、アプリは Greeting という名前のコンテナを見つけ、そのコンテナ内にユニバーサル アナリティクス タグを作成します。ユーザーが hello-world.html にアクセスしたときに、タグはページビュー ヒットを送信します。
このアプリケーションを開発する手順は次のとおりです。
- Google API Console で開発環境とプロジェクトを設定します。
- タグ マネージャーのサービス オブジェクトを作成します。
- タグ マネージャー アカウントへのアクセスを許可します。
- タグ マネージャーのサービス オブジェクトを作成します。
- API へのクエリの実行、レスポンスの処理、結果の出力を行います。
- 初期化されたタグ マネージャー サービス オブジェクトを取得します。
- タグ マネージャー サービス オブジェクトを使用して Tag Manager API にクエリを実行し、次のタスクを行います。
- 認証済みの Google タグ マネージャー アカウントの Greetings コンテナを取得します。
- 新しいワークスペースを作成します。
- ユニバーサル アナリティクス タグを作成します。
- タグを配信するトリガーを作成します。
- タグを更新し、トリガーで配信するようにします。
開発環境とプロジェクトを設定する
Greetings コンテナを作成する
このガイドでは、Greetings という名前のコンテナを含む Google タグ マネージャー アカウントを使用します。設定とワークフロー(Web)の手順に沿って、アカウントと、Greetings という名前のコンテナを作成しておいてください。
クライアント ライブラリをインストールする
始める前に、Google API クライアント ライブラリをインストールして設定します。
Google API Console でプロジェクトを作成して設定する
Tag Manager API を使用するには、最初に設定ツールを使用して Google API Console でプロジェクトを作成し、API を有効にして認証情報を作成する必要があります。
このガイドでは、インストール済みアプリケーションの認証フローを使用します。プロジェクトの認証情報を作成する手順は次のとおりです。プロンプトが表示されたら、[APPLICATION TYPE] には [Installed Application
] を選択し、[INSTALLED APPLICATION TYPE] には [Other
] を選択します。
- [Credentials] ページで、[Create credentials] > [OAuth client ID] の順にクリックして OAuth 2.0 の認証情報を作成するか、[Create credentials] > [Service account key] の順にクリックしてサービス アカウントを作成します。
- OAuth クライアント ID を作成した場合は、アプリケーション タイプを選択します。
- フォームに記入し、[Create] をクリックします。
アプリケーションのクライアント ID とサービス アカウント キーが [Credentials] ページに表示されます。クライアント ID をクリックすると詳細を表示できます。パラメータは ID の種類によって異なりますが、メールアドレス、クライアント シークレット、JavaScript のオリジン(生成元)、リダイレクト URI などが含まれる場合があります。
[Download JSON] ボタンをクリックして、クライアントの詳細情報をダウンロードします。ファイル名を「client_secrets.json
」に変更します。このファイルは後で認証目的で使用されます。
タグ マネージャー サービス オブジェクトを作成する
タグ マネージャーの service
オブジェクトは、API リクエストを行うために使用するものです。
タグ マネージャーのサービス オブジェクトを作成する手順は次のとおりです。
- Google タグ マネージャー アカウントへのアクセスを許可します。
- タグ マネージャー サービス オブジェクトをインスタンス化します。
Google タグ マネージャー アカウントへのアクセスを許可する
Google Tag Manager API で構築されたアプリケーションを起動する際は、アプリケーションによる Google タグ マネージャー アカウントへのアクセスを許可する必要があります。このプロセスは認証と呼ばれます。ユーザーの認証メソッドには OAuth 2.0 を使用することをおすすめします。詳細については、Tag Manager API の認証をご覧ください。
以下のコードでは、上記で作成したプロジェクトとクライアントの詳細情報を使用して、アプリケーションのユーザーを認証し、そのユーザーのための Google タグ マネージャーへのアクセス権を要求しています。
このアプリケーションでは、デフォルトのブラウザが開かれ、Google.com でホストされる URL にユーザーを誘導します。ユーザーは、ログインしてアプリケーションによるタグ マネージャー アカウントへのアクセスを許可するよう求められます。ユーザーがアクセスを許可すると、アプリケーションはブラウザ ウィンドウからコードを読み取り、ウィンドウを閉じます。
注: エラーが発生すると、アプリケーションはユーザーにコマンドラインで認証コードを入力するように求めます。
"""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>
Tag Manager API にクエリを実行する
タグ マネージャー サービス オブジェクトを使用して Tag Manager API にクエリを実行し、次の手順に沿ってサンプルのプログラムを実装します。
- Greetings コンテナを取得する
- ユニバーサル アナリティクス タグを作成する
- タグを配信するトリガーを作成する
- タグを更新し、トリガーで配信するようにする
1. Greetings コンテナを取得する
以下の関数では、タグ マネージャー サービス オブジェクトを使用して Tag Manager 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. 新しいワークスペースを作成する
次のコードでは、Tag Manager 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. ユニバーサル アナリティクス タグを作成する
次のコードでは、Tag Manager API を使用してユニバーサル アナリティクス タグを作成しています。タグの作成時に設定できる必須プロパティとオプションのプロパティの一覧については、タグの 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. タグを更新し、トリガーで配信するようにする
タグとトリガーを作成したら、それらを相互に関連付ける必要があります。そのためには、タグに関連付けられた firingTriggerIds
のリストに triggerId
を追加します。例は次のとおりです。
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 の仕組みを理解したら、次の関連資料もご覧ください。
- API リファレンス - API インターフェースとサポートされている操作の詳細を解説しています。
- パラメータ リファレンス - タグと変数のパラメータを設定する方法を解説しています。
- サポートされているタグのリストについては、タグ辞書リファレンスをご覧ください。
- 設定可能な変数のリストについては、変数辞書リファレンスをご覧ください。