API Диспетчера тегов Google — Руководство разработчика

В этом руководстве разработчика описаны шаги, необходимые для доступа, создания и управления объектами в учетной записи Диспетчера тегов Google с помощью API диспетчера тегов версии 2.

Введение

В этом руководстве описаны различные этапы доступа и настройки учетной записи Диспетчера тегов Google. По завершении вы получите базовое представление о том, как выполнять следующие задачи:

  • Создайте объект службы Диспетчера тегов.
  • Аутентификация и авторизация пользователя.
  • Используйте API Диспетчера тегов для доступа к ресурсам и управления ими.

Прежде чем вы начнете

Прежде чем приступить к работе с руководством, мы рекомендуем вам ознакомиться с Диспетчером тегов Google, посетив справочный центр Диспетчера тегов Google .

Использование тестовой учетной записи

Если вы собираетесь использовать API Диспетчера тегов для создания, настройки или удаления объектов, мы рекомендуем вам внедрить и проверить свой код с помощью тестового аккаунта. Использование тестовой учетной записи поможет предотвратить случайное внесение изменений в активную учетную запись. После того как вы протестировали и подтвердили, что ваш код работает должным образом с использованием тестовой учетной записи, вы можете начать использовать реализацию на своих реальных учетных записях.

Выберите язык

Выберите язык программирования, на котором вы хотите следовать примерам:

Питон


Python выбран для всех фрагментов кода в этом руководстве.

JavaScript


В этом руководстве для всех фрагментов кода выбран JavaScript .

Обзор программы

Пример программы, включенный в это руководство, представляет собой приложение командной строки. Учитывая идентификатор учетной записи, приложение находит контейнер с именем Greetings и создает в нем тег Universal Analytics. Когда пользователь посещает hello-world.html, тег отправляет сообщение о просмотре страницы.

Чтобы разработать это приложение, вам необходимо выполнить следующие шаги:

  1. Настройте среду разработки и проект в консоли Google API.
  2. Создайте объект службы Диспетчера тегов.
    1. Разрешите доступ к аккаунту Менеджера тегов.
    2. Создайте объект службы Диспетчера тегов.
  3. Запросите API, обработайте ответ и выведите результаты.
    1. Получите инициализированный объект службы Диспетчера тегов.
    2. Используйте объект службы Диспетчера тегов, чтобы запросить API Диспетчера тегов для выполнения следующих задач:
      1. Получите контейнер приветствий для аутентифицированной учетной записи Диспетчера тегов Google.
      2. Создайте новое рабочее пространство.
      3. Создайте тег Universal Analytics.
      4. Создайте триггер для активации тега.
      5. Обновите тег, чтобы он срабатывал по триггеру.

Настройте среду разработки и проект

Создайте контейнер приветствий .

В этом руководстве предполагается, что у вас есть учетная запись Диспетчера тегов Google с контейнером Greetings . Следуйте инструкциям по настройке и рабочему процессу (Интернет) , чтобы создать учетную запись и контейнер с именем Greetings .

Установить клиентскую библиотеку

Прежде чем начать, установите и настройте клиентскую библиотеку API Google .

Создайте и настройте проект в консоли Google API.

Чтобы начать использовать API Диспетчера тегов, вам необходимо сначала воспользоваться инструментом настройки , который поможет вам создать проект в консоли Google API, включить API и создать учетные данные.

В этом руководстве используется поток аутентификации установленного приложения . Следуйте инструкциям ниже, чтобы создать учетные данные проекта. При появлении запроса выберите Installed Application для ТИПА ПРИЛОЖЕНИЯ и Other для УСТАНОВЛЕННОГО ТИПА ПРИЛОЖЕНИЯ .

  1. На странице «Учетные данные» нажмите «Создать учетные данные» > «Идентификатор клиента OAuth» , чтобы создать учетные данные OAuth 2.0, или «Создать учетные данные» > «Ключ учетной записи службы» , чтобы создать учетную запись службы.
  2. Если вы создали идентификатор клиента OAuth, выберите тип приложения.
  3. Заполните форму и нажмите «Создать» .

Идентификаторы клиента вашего приложения и ключи учетной записи службы теперь указаны на странице «Учетные данные». Для получения подробной информации щелкните идентификатор клиента; параметры различаются в зависимости от типа идентификатора, но могут включать адрес электронной почты, секрет клиента, происхождение JavaScript или URI перенаправления.

Загрузите сведения о клиенте, нажав кнопку «Загрузить JSON» . Переименуйте этот файл в client_secrets.json . Этот файл будет использоваться позже для целей аутентификации.

Создайте объект службы Диспетчера тегов.

service объект Диспетчера тегов – это то, что вы будете использовать для выполнения запросов API.

Для создания объекта службы Диспетчера тегов необходимо выполнить следующие шаги:

  1. Разрешите доступ к учетной записи Диспетчера тегов Google.
  2. Создайте экземпляр объекта службы Диспетчера тегов.

Разрешите доступ к учетной записи Диспетчера тегов Google.

Когда пользователь запускает приложение, созданное с помощью API Диспетчера тегов Google, ему необходимо предоставить приложению доступ к своей учетной записи Диспетчера тегов Google. Этот процесс называется авторизацией. Рекомендуемый метод авторизации пользователей — OAuth 2.0. Если вы хотите узнать больше, прочитайте статью «Авторизация API Менеджера тегов» .

Код ниже использует созданные выше данные проекта и клиента для аутентификации пользователя приложения и запрашивает у него разрешение на доступ к Диспетчеру тегов Google от его имени.

Приложение попытается открыть браузер по умолчанию и направить пользователя по URL-адресу, размещенному на 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)
    

JavaScript

<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 Диспетчера тегов

Объект службы Диспетчера тегов можно использовать для запроса API Диспетчера тегов. Для реализации примера программы необходимо выполнить следующие шаги:

  1. Получение контейнера приветствий
  2. Создайте тег Universal Analytics.
  3. Создайте триггер для активации тега
  4. Обновите тег, чтобы он срабатывал по триггеру.

1. Получите контейнер приветствий.

Следующая функция показывает, как объект службы Диспетчера тегов можно использовать для запроса 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
    

JavaScript

/**
 * 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.');
      });
}
    

Затем обновите основную ветвь выполнения программы, чтобы она вызывала функцию findGreetingsContainer с учетом accountId Менеджера тегов. Например:

Питон

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)
    

JavaScript

/**
 * 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 диспетчера тегов используется для создания новой рабочей области, которую мы используем для управления изменениями триггеров и тегов. Вы можете просмотреть справочник по методу создания рабочей области, чтобы узнать список обязательных и дополнительных свойств, которые можно установить при создании рабочей области.

Питон

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()
    

JavaScript

/**
 * 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. Вы можете просмотреть справочник по методу создания тега, чтобы получить список обязательных и необязательных свойств, которые можно установить при создании тега, и справочник словаря тегов, где приведен список свойств для каждого типа тега.

Питон

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()

    

JavaScript

/**
 * 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()
    

JavaScript

/**
 * 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()
    

JavaScript

/**
 * 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);
}
    

Затем обновите основную ветвь выполнения программы, чтобы вызвать функции создания и обновления. Например:

Питон


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)
    

JavaScript

/**
 * 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)

    

JavaScript

<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, для вас есть несколько дополнительных ресурсов: