Google Tag Manager API - 개발자 가이드

이 개발자 가이드에서는 Tag Manager API v2를 통해 Google 태그 관리자 계정 내에서 항목을 액세스, 생성, 관리하는 데 필요한 단계를 안내합니다.

소개

이 가이드에서는 Google 태그 관리자 계정에 액세스하고 구성하는 다양한 단계를 설명합니다. 완료하면 다음 작업을 실행하는 방법을 기본적으로 이해하게 됩니다.

  • 태그 관리자 서비스 객체를 만듭니다.
  • 사용자를 인증하고 승인합니다.
  • Tag Manager API를 이용해 리소스에 액세스하고 관리하세요.

시작하기 전에

가이드를 시작하기 전에 Google 태그 관리자 고객센터를 방문하여 Google 태그 관리자를 숙지하는 것이 좋습니다.

테스트 계정 사용

Tag Manager API를 사용하여 항목을 생성, 구성 또는 삭제하려면 테스트 계정으로 코드를 구현하고 확인하는 것이 좋습니다. 테스트 계정을 사용하면 활성 계정을 실수로 변경하는 것을 방지할 수 있습니다. 테스트 계정을 사용하여 코드를 테스트하고 확인한 후 코드가 예상대로 작동하는지 확인한 후 실제 계정으로 구현을 사용할 수 있습니다.

언어 선택

예시를 따를 프로그래밍 언어를 선택하세요.

Python


이 가이드의 모든 코드 스니펫에는 Python이 선택되어 있습니다.

JavaScript


이 가이드의 모든 코드 스니펫에 JavaScript가 선택되어 있는지 확인합니다.

프로그램 개요

이 가이드에 포함된 프로그램 예는 명령줄 앱입니다. 계정 ID가 주어지면 앱은 Greetings라는 컨테이너를 찾아 해당 컨테이너에 유니버설 애널리틱스 태그를 만듭니다. 사용자가 hello-world.html을 방문하면 태그에서 페이지 조회를 전송합니다.

이 애플리케이션을 개발하려면 다음 단계를 따라야 합니다.

  1. Google API 콘솔에서 개발 환경 및 프로젝트를 설정합니다.
  2. 태그 관리자 서비스 객체를 만듭니다.
    1. 태그 관리자 계정에 대한 액세스를 승인합니다.
    2. 태그 관리자 서비스 객체를 만듭니다.
  3. API를 쿼리하고 응답을 처리하고 결과를 출력합니다.
    1. 초기화된 태그 관리자 서비스 객체를 가져옵니다.
    2. 태그 관리자 서비스 객체를 사용하여 Tag Manager API에 쿼리하여 다음 작업을 실행합니다.
      1. 인증된 Google 태그 관리자 계정의 Greetings 컨테이너를 가져옵니다.
      2. 새 작업공간을 만듭니다.
      3. 유니버설 애널리틱스 태그를 만듭니다.
      4. 태그를 실행할 트리거를 만듭니다.
      5. 트리거에서 실행되도록 태그를 업데이트합니다.

개발 환경 및 프로젝트 설정

Greetings 컨테이너 만들기

이 가이드에서는 Greetings라는 컨테이너가 포함된 Google 태그 관리자 계정이 있다고 가정합니다. 설정 및 워크플로(웹)에 대한 안내에 따라 계정Greetings라는 컨테이너를 만듭니다.

클라이언트 라이브러리 설치

시작하기 전에 Google API 클라이언트 라이브러리를 설치하고 구성합니다.

Google API 콘솔에서 프로젝트 만들기 및 구성

Tag Manager API를 사용하려면 먼저 Google API 콘솔에서 프로젝트를 만들고, API를 사용 설정하고, 사용자 인증 정보를 만드는 과정을 안내하는 설정 도구를 사용해야 합니다.

이 가이드에서는 설치된 애플리케이션 인증 흐름을 사용합니다. 아래 안내에 따라 프로젝트 사용자 인증 정보를 만드세요. 메시지가 표시되면 애플리케이션 유형Installed Application를 선택하고 설치된 애플리케이션 유형Other를 선택합니다.

  1. 사용자 인증 정보 페이지에서 사용자 인증 정보 만들기 > OAuth 클라이언트 ID를 클릭하여 OAuth 2.0 사용자 인증 정보를 만들거나 사용자 인증 정보 만들기 > 서비스 계정 키를 클릭하여 서비스 계정을 만듭니다.
  2. OAuth 클라이언트 ID를 만든 경우 애플리케이션 유형을 선택합니다.
  3. 양식을 작성한 다음 만들기를 클릭합니다.

이제 애플리케이션의 클라이언트 ID와 서비스 계정 키가 사용자 인증 정보 페이지에 나열됩니다. 자세한 내용을 보려면 클라이언트 ID를 클릭하세요. 매개변수는 ID 유형에 따라 다르지만 이메일 주소, 클라이언트 보안 비밀번호, 자바스크립트 출처 또는 리디렉션 URI가 포함될 수 있습니다.

JSON 다운로드 버튼을 클릭하여 클라이언트 세부정보를 다운로드합니다. 이 파일의 이름을 client_secrets.json로 바꿉니다. 이 파일은 나중에 인증 목적으로 사용됩니다.

태그 관리자 서비스 객체 만들기

태그 관리자 service 객체를 사용하여 API 요청을 만듭니다.

태그 관리자 서비스 객체를 만드는 데 필요한 단계는 다음과 같습니다.

  1. Google 태그 관리자 계정에 대한 액세스를 승인합니다.
  2. 태그 관리자 서비스 객체를 인스턴스화합니다.

Google 태그 관리자 계정에 대한 액세스 승인

사용자가 Google Tag Manager API로 빌드된 애플리케이션을 시작할 때 Google 태그 관리자 계정에 대한 액세스 권한을 애플리케이션에 부여해야 합니다. 이 프로세스를 승인이라고 합니다. 권장되는 사용자 승인 방법은 OAuth 2.0입니다. 자세한 내용은 태그 관리자 API 승인을 참고하세요.

아래 코드는 위에서 만든 프로젝트 및 클라이언트 세부정보를 사용하여 애플리케이션의 사용자를 인증하고 사용자를 대신하여 Google 태그 관리자에 액세스할 수 있는 권한을 요청합니다.

애플리케이션은 기본 브라우저를 열고 사용자를 google.com에서 호스팅되는 URL로 이동하려고 시도합니다. 사용자에게 로그인하여 애플리케이션에 태그 관리자 계정에 대한 액세스 권한을 부여하라는 메시지가 표시됩니다. 권한이 부여되면 애플리케이션이 브라우저 창에서 코드를 읽으려고 시도한 후 창을 닫습니다.

참고: 오류가 발생하면 애플리케이션에서 명령줄에 승인 코드를 입력하라는 메시지를 표시합니다.

Python

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

import argparse
import sys

import httplib2

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


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

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

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

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

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

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

  return service

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

  # Authenticate and construct service.
  service = GetService('tagmanager', '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>

    

Tag Manager API 쿼리하기

태그 관리자 서비스 객체는 태그 관리자 API를 쿼리하는 데 사용할 수 있습니다. 샘플 프로그램을 구현하려면 다음 단계가 필요합니다.

  1. Greetings 컨테이너를 가져옵니다.
  2. 유니버설 애널리틱스 태그 만들기
  3. 태그를 실행하는 트리거 만들기
  4. 트리거에서 실행되도록 태그 업데이트

1. Greetings 컨테이너를 가져옵니다.

다음 함수는 태그 관리자 서비스 객체를 사용하여 계정의 모든 컨테이너를 나열하고 Greetings라는 컨테이너를 검색하는 데 Tag Manager API를 쿼리하는 방법을 보여줍니다.

Python

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

다음으로 태그 관리자 accountId이 지정된 경우 findGreetingsContainer 함수를 호출하도록 프로그램의 기본 실행 브랜치를 업데이트합니다. 예를 들면 다음과 같습니다.

Python

def main(argv):
  # Get tag manager account ID from command line.
  assert len(argv) == 2 and 'usage: gtm-api-hello-world.py <account_id>'
  account_id = str(argv[1])
  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. 새 작업공간 만들기

다음 코드 스니펫은 Tag Manager API를 사용하여 새 작업공간을 만듭니다. 이 작업공간은 트리거 및 태그의 변경사항을 관리하는 데 사용됩니다. 작업공간을 만들 때 설정할 수 있는 필수 및 선택 속성 목록은 작업공간 만들기 메서드 참조를 확인하세요.

Python

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. 유니버설 애널리틱스 태그 만들기

다음 코드 스니펫은 Tag Manager API를 사용하여 유니버설 애널리틱스 태그를 만듭니다. 태그를 만들 때 설정할 수 있는 필수 및 선택 속성 목록은 태그 만들기 메서드 참조를, 각 태그 유형의 속성 목록은 태그 사전 참조를 참고하세요.

Python

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이며 페이지 조회 시 실행됩니다. 예를 들면 다음과 같습니다.

Python

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. 트리거에서 실행되도록 태그 업데이트

이제 태그와 트리거가 생성되었으므로 서로 연결해야 합니다. 이렇게 하려면 태그와 연결된 firingTriggerIds 목록에 triggerId를 추가합니다. 예를 들면 다음과 같습니다.

Python

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

다음으로 프로그램의 기본 실행 브랜치를 업데이트하여 생성 및 업데이트 함수를 호출합니다. 예를 들면 다음과 같습니다.

Python


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

    

전체 예

이 섹션을 펼쳐 가이드에 있는 모든 단계의 전체 코드 예를 확인하세요.

Python

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

import argparse
import sys

import httplib2

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


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

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

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

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

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

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

  return service

def 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의 작동 방식에 익숙해졌으므로 몇 가지 추가 리소스를 살펴보겠습니다.