Google Tag Manager API - 開發人員指南

本開發人員指南將逐步引導您透過 Tag Manager API v2,存取、建立及管理 Google 代碼管理工具帳戶中的實體。

簡介

本指南將逐步引導您存取及設定 Google 代碼管理工具帳戶。完成後,您會對如何執行下列工作有基本瞭解:

  • 建立代碼管理工具服務物件。
  • 驗證與授權使用者。
  • 使用 Tag Manager API 存取及管理資源。

事前準備

開始本指南之前,建議您先前往 Google 代碼管理工具說明中心熟悉 Google 代碼管理工具。

使用測試帳戶

如果您打算使用 Tag Manager API 建立、設定或刪除實體,建議您使用測試帳戶導入及驗證程式碼。使用測試帳戶可避免意外變更有效帳戶的內容。使用測試帳戶完成測試,並確認程式碼運作正常後,即可開始透過實際帳戶使用導入作業。

選取語言

請選取您想要遵循範例的程式設計語言:

Python


本指南中的所有程式碼片段皆已選取 Python

JavaScript


已為本指南中的所有程式碼片段選取「JavaScript」JavaScript

計畫簡介

本指南中的範例程式是指令列應用程式。根據帳戶 ID,應用程式會找出名為「Greetings」的容器,並在該容器中建立通用 Analytics (分析) 代碼。當使用者造訪 hello-world.html 時,代碼會傳送網頁瀏覽命中。

如要開發這個應用程式,請執行下列步驟:

  1. 在 Google API 控制台中設定開發環境和專案。
  2. 建立代碼管理工具服務物件。
    1. 授予代碼管理工具帳戶存取權。
    2. 建立代碼管理工具服務物件。
  3. 查詢 API、處理回應並輸出結果。
    1. 取得初始化的代碼管理工具服務物件。
    2. 使用代碼管理工具服務物件查詢 Tag Manager API,以便執行下列工作:
      1. 擷取已驗證 Google 代碼管理工具帳戶的 Greetings 容器。
      2. 建立新工作區。
      3. 建立通用 Analytics (分析) 代碼。
      4. 建立觸發條件來啟動代碼。
      5. 更新代碼,讓觸發條件觸發。

設定開發環境和專案

建立 Greetings 容器

本指南假設您擁有 Google 代碼管理工具帳戶,且容器名為「Greetings」。按照設定和工作流程 (網頁) 的操作說明,建立帳戶和名為 Greetings容器

安裝用戶端程式庫

在開始之前,請先安裝並設定 Google API 用戶端程式庫

在 Google API 控制台中建立並設定專案

如要開始使用 Tag Manager API,請先使用設定工具;這項工具會逐步引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。

本指南使用「已安裝的應用程式」驗證流程。請按照以下操作說明建立專案憑證。系統提示時,請為「APPLICATION TYPE」選取 Installed Application,並將「INSTALLED APPLICATION TYPE」選取 Other

  1. 在「Credentials」(憑證) 頁面上,按一下「Create credentials」(建立憑證) >「OAuth client ID」(OAuth 用戶端 ID) 以建立 OAuth 2.0 憑證,或是依序點選「Create credentials」(建立憑證) >「Service account key」(服務帳戶金鑰) 建立服務帳戶。
  2. 如果您已建立 OAuth 用戶端 ID,請選取應用程式類型。
  3. 填寫表單並按一下「建立」

「憑證」頁面現在會列出應用程式的用戶端 ID 和服務帳戶金鑰。如需瞭解詳情,請按一下用戶端 ID;參數會因 ID 類型而異,但可能包含電子郵件地址、用戶端密鑰、JavaScript 來源或重新導向 URI。

按一下「Download JSON」(下載 JSON) 按鈕,下載用戶端詳細資料。將這個檔案重新命名為 client_secrets.json。這個檔案稍後會用於驗證。

建立代碼管理工具服務物件

代碼管理工具 service 物件是您用來發出 API 要求的工具。

建立代碼管理工具服務物件的步驟如下:

  1. 授權存取 Google 代碼管理工具帳戶。
  2. 將代碼管理工具服務物件例項化。

授權存取 Google 代碼管理工具帳戶

使用者啟動使用 Google Tag Manager API 建構的應用程式時,必須授予應用程式存取其 Google 代碼管理工具帳戶的權限。這項程序稱為授權。建議您使用 OAuth 2.0 來驗證使用者。詳情請參閱「Tag Manager API 授權」一文。

以下程式碼使用上述建立的專案和用戶端詳細資料來驗證應用程式使用者,並要求他們代表使用者存取 Google 代碼管理工具。

應用程式會嘗試開啟預設瀏覽器,並前往 google.com 代管的網址。系統會提示使用者登入,並授權應用程式存取其代碼管理工具帳戶。授予後,應用程式會嘗試讀取瀏覽器視窗中的程式碼,然後關閉視窗。

注意:如果發生錯誤,應用程式會改為提示使用者在指令列輸入授權碼。

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

代碼管理工具服務物件可用來查詢 Tag Manager API。如要實作範例程式,您必須執行下列步驟:

  1. 擷取 Greetings 容器
  2. 建立通用 Analytics (分析) 代碼
  3. 建立觸發條件來啟用代碼
  4. 更新要觸發觸發條件的代碼

1. 擷取 Greetings 容器

以下函式說明如何使用代碼管理工具服務物件查詢 Tag Manager API,列出帳戶的所有容器及擷取名為 Greetings 的容器。

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 建立新的工作區,用來管理觸發條件和代碼的變更。如需建立工作區時可設定的必要和選用屬性清單,請參閱「Workspace 建立方法參考資料」一文。

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. 建立通用 Analytics (分析) 代碼

下列程式碼片段使用 Tag Manager API 建立通用 Analytics (分析) 代碼。您可以參閱標記建立方法參考資料,瞭解建立代碼時可設定的必要和選用屬性清單;如需各個代碼類型的屬性清單,請參閱標記字典參考資料

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. 更新要觸發觸發條件的代碼

代碼和觸發條件已建立完成,現在需要彼此連結。為此,請將 triggerId 新增至與標記相關聯的 firingTriggerIds 清單。例如:

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 的運作方式,不妨參考以下額外資源: