API Trình quản lý thẻ của Google – Hướng dẫn cho nhà phát triển

Hướng dẫn dành cho nhà phát triển này sẽ hướng dẫn bạn các bước cần thiết để truy cập, tạo và quản lý các thực thể trong tài khoản Trình quản lý thẻ của Google thông qua API Trình quản lý thẻ phiên bản 2.

Giới thiệu

Hướng dẫn này sẽ chỉ cho bạn các bước để truy cập và định cấu hình tài khoản người quản lý Trình quản lý thẻ của Google. Sau khi hoàn tất, bạn sẽ nắm được kiến thức cơ bản về cách thực hiện các nhiệm vụ sau:

  • Tạo đối tượng dịch vụ Trình quản lý thẻ.
  • Xác thực và uỷ quyền cho người dùng.
  • Làm việc với API Trình quản lý thẻ để truy cập và quản lý tài nguyên.

Trước khi bắt đầu

Trước khi bắt đầu hướng dẫn, bạn nên làm quen với Trình quản lý thẻ của Google bằng cách truy cập vào Trung tâm trợ giúp của Trình quản lý thẻ của Google.

Sử dụng tài khoản thử nghiệm

Nếu dự định sử dụng API Trình quản lý thẻ để tạo, định cấu hình hoặc xoá các thực thể, bạn nên triển khai và xác minh mã của mình bằng một tài khoản thử nghiệm. Việc sử dụng tài khoản thử nghiệm sẽ giúp bạn tránh vô tình thay đổi một tài khoản đang hoạt động. Sau khi thử nghiệm và xác nhận rằng mã của bạn đang hoạt động như mong đợi bằng tài khoản thử nghiệm, bạn có thể bắt đầu sử dụng phương thức triển khai này với tài khoản thực của mình.

Chọn ngôn ngữ

Chọn ngôn ngữ lập trình mà bạn định làm theo ví dụ:

Python


Python được chọn cho tất cả đoạn mã trong hướng dẫn này.

JavaScript


JavaScript được chọn cho tất cả đoạn mã trong hướng dẫn này.

Tổng quan về chương trình

Chương trình mẫu trong hướng dẫn này là một ứng dụng dòng lệnh. Khi được cung cấp mã tài khoản, ứng dụng sẽ tìm một vùng chứa có tên là Greetings và tạo một thẻ Google trong vùng chứa đó để kích hoạt khi có lượt xem trang.

Để phát triển ứng dụng này, bạn cần làm theo các bước sau:

  1. Thiết lập môi trường phát triển và dự án trong Google API Console.
  2. Tạo đối tượng dịch vụ Trình quản lý thẻ.
    1. Uỷ quyền truy cập vào tài khoản người quản lý Trình quản lý thẻ.
    2. Tạo đối tượng dịch vụ Trình quản lý thẻ.
  3. Truy vấn API, xử lý phản hồi và xuất kết quả.
    1. Lấy đối tượng dịch vụ Trình quản lý thẻ đã khởi chạy.
    2. Sử dụng đối tượng dịch vụ Trình quản lý thẻ để truy vấn API Trình quản lý thẻ nhằm thực hiện các tác vụ sau:
      1. Truy xuất vùng chứa Greetings cho tài khoản người quản lý Trình quản lý thẻ của Google đã xác thực.
      2. Tạo không gian làm việc mới.
      3. Tạo thẻ Google.
      4. Tạo điều kiện kích hoạt để kích hoạt thẻ.
      5. Cập nhật thẻ để kích hoạt trên trình kích hoạt.

Thiết lập môi trường phát triển và dự án

Tạo vùng chứa Greetings

Hướng dẫn này giả định rằng bạn có một tài khoản Trình quản lý thẻ của Google với một vùng chứa có tên là Greetings. Làm theo hướng dẫn trong phần Thiết lập và quy trình làm việc (Web) để tạo một Tài khoản và một Vùng chứa có tên là Greetings.

Cài đặt thư viện ứng dụng

Trước khi bắt đầu, hãy cài đặt và định cấu hình thư viện ứng dụng API của Google.

Tạo và định cấu hình dự án trong Google API Console

Để bắt đầu sử dụng Trình quản lý thẻ API, trước tiên bạn cần sử dụng công cụ thiết lập. Công cụ này sẽ hướng dẫn bạn quy trình tạo dự án trong Google API Console và bật API.

Hướng dẫn này sử dụng quy trình xác thực Ứng dụng đã cài đặt. Hãy làm theo hướng dẫn bên dưới để tạo thông tin xác thực cho dự án của bạn. Khi được nhắc, hãy chọn Installed Application cho APPLICATION TYPE (LOẠI ỨNG DỤNG) và Other cho INSTALLED APPLICATION TYPE (LOẠI ỨNG DỤNG ĐÃ CÀI ĐẶT).

  1. Trên trang Thông tin xác thực, hãy nhấp vào Tạo thông tin xác thực > Mã ứng dụng OAuth để tạo thông tin xác thực OAuth 2.0 hoặc Tạo thông tin xác thực > Khoá tài khoản dịch vụ để tạo tài khoản dịch vụ.
  2. Nếu bạn đã tạo mã ứng dụng khách OAuth, hãy chọn loại ứng dụng.
  3. Điền thông tin vào biểu mẫu rồi nhấp vào Tạo.

Mã ứng dụng khách và khoá tài khoản dịch vụ của ứng dụng hiện đã được liệt kê trên trang Thông tin đăng nhập. Để biết thông tin chi tiết, hãy nhấp vào một mã ứng dụng khách; các tham số sẽ khác nhau tuỳ thuộc vào loại mã nhận dạng, nhưng có thể bao gồm địa chỉ email, khoá bí mật của ứng dụng khách, nguồn gốc JavaScript hoặc URI chuyển hướng.

Tải thông tin chi tiết về ứng dụng xuống bằng cách nhấp vào nút Tải tệp JSON xuống. Đổi tên tệp này thành client_secrets.json. Tệp này sẽ được dùng sau cho mục đích xác thực.

Tạo đối tượng dịch vụ Trình quản lý thẻ

Bạn sẽ sử dụng đối tượng service của Trình quản lý thẻ để gửi yêu cầu API.

Các bước cần thiết để tạo đối tượng dịch vụ Trình quản lý thẻ như sau:

  1. Uỷ quyền truy cập vào tài khoản Trình quản lý thẻ của Google.
  2. Tạo thực thể cho đối tượng dịch vụ Trình quản lý thẻ.

Uỷ quyền truy cập vào tài khoản Trình quản lý thẻ của Google

Khi bắt đầu một ứng dụng được xây dựng bằng API Trình quản lý thẻ của Google, người dùng sẽ phải cấp cho ứng dụng quyền truy cập vào tài khoản Trình quản lý thẻ của Google của họ. Quá trình này được gọi là uỷ quyền. Phương thức được đề xuất để uỷ quyền cho người dùng là OAuth 2.0. Nếu bạn muốn tìm hiểu thêm, hãy đọc bài viết Uỷ quyền API Trình quản lý thẻ.

Mã dưới đây sử dụng thông tin chi tiết về dự án và ứng dụng được tạo ở trên để xác thực người dùng của ứng dụng và yêu cầu họ cho phép truy cập vào Trình quản lý thẻ của Google thay mặt họ.

Ứng dụng sẽ cố gắng mở trình duyệt mặc định và chuyển người dùng đến một URL được lưu trữ trên google.com. Người dùng sẽ được nhắc đăng nhập và cấp cho ứng dụng quyền truy cập vào tài khoản người quản lý Trình quản lý thẻ của họ. Sau khi được cấp quyền, ứng dụng sẽ cố gắng đọc mã từ cửa sổ trình duyệt, sau đó đóng cửa sổ.

Lưu ý: Nếu xảy ra lỗi, ứng dụng sẽ nhắc người dùng nhập mã uỷ quyền trên dòng lệnh.

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>

    

Truy vấn API Trình quản lý thẻ

Bạn có thể sử dụng đối tượng dịch vụ Trình quản lý thẻ để truy vấn API Trình quản lý thẻ. Bạn cần thực hiện các bước sau để triển khai chương trình mẫu:

  1. Truy xuất vùng chứa Lời chào
  2. Tạo thẻ Google
  3. Tạo điều kiện kích hoạt để kích hoạt thẻ
  4. Cập nhật thẻ để kích hoạt theo trình kích hoạt

1. Truy xuất vùng chứa Greetings

Hàm sau đây minh hoạ cách sử dụng đối tượng dịch vụ Trình quản lý thẻ để truy vấn API Trình quản lý thẻ nhằm liệt kê tất cả vùng chứa của một tài khoản và truy xuất vùng chứa có tên là 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.');
      });
}
    

Tiếp theo, hãy cập nhật nhánh thực thi chính của chương trình để gọi hàm findGreetingsContainer dựa trên accountId của Trình quản lý thẻ. Ví dụ:

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. Tạo không gian làm việc mới

Đoạn mã sau đây sử dụng API Trình quản lý thẻ để tạo một không gian làm việc mới mà chúng ta dùng để quản lý các thay đổi đối với điều kiện kích hoạt và thẻ. Bạn có thể xem tài liệu tham khảo về phương thức tạo Workspace để biết danh sách các thuộc tính bắt buộc và không bắt buộc có thể đặt khi tạo không gian làm việc.

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. Tạo thẻ Google

Đoạn mã sau đây sử dụng API Trình quản lý thẻ để tạo thẻ Google. Bạn có thể xem Tài liệu tham khảo về phương thức tạo thẻ để biết danh sách các thuộc tính bắt buộc và không bắt buộc có thể được đặt khi tạo thẻ, cũng như Tài liệu tham khảo về từ điển thẻ để biết danh sách các thuộc tính cho từng loại thẻ.

Python

def CreateHelloWorldTag(service, workspace, tag_id):
  """Create the Google Tag Hello World tag.

  Args:
    service: the Tag Manager service object.
    workspace: the workspace to create a tag within.
    tag_id: the Google tag ID or Google Analytics 4 measurement ID to use.

  Returns:
    The created tag.
  """

  hello_world_tag = {
      'name': 'Google Tag Hello World',
      'type': 'googtag',
      'parameter': [{
          'key': 'tagId',
          'type': 'template',
          'value': str(tag_id),
      }],
  }

  return service.accounts().containers().workspaces().tags().create(
      parent=workspace['path'],
      body=hello_world_tag).execute()

    

JavaScript

/**
 * Creates a Google 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': 'Google Tag Hello World',
    'type': 'googtag',
    'parameter':
    [{ 'key': 'tagId', 'type': 'template', 'value': 'G-XXXXXXXXXX' }],
  };
  var request =
    gapi.client.tagmanager.accounts.containers.workspaces.tags.create(
      { 'parent': workspace.path }, helloWorldTag);
  return requestPromise(request);
}

    

4. Tạo điều kiện kích hoạt để kích hoạt thẻ

Sau khi tạo thẻ, bước tiếp theo là tạo một Điều kiện kích hoạt sẽ kích hoạt trên bất kỳ trang nào.

Trình kích hoạt này sẽ có tên là Hello World Trigger và sẽ kích hoạt cho mọi lượt xem trang. Ví dụ:

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. Cập nhật thẻ để kích hoạt theo trình kích hoạt

Bây giờ, bạn đã tạo thẻ và trình kích hoạt, bạn cần liên kết chúng với nhau. Để thực hiện việc này, hãy thêm triggerId vào danh sách firingTriggerIds liên kết với thẻ. Ví dụ:

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

Tiếp theo, hãy cập nhật nhánh thực thi chính của chương trình để gọi các hàm tạo và cập nhật. Ví dụ:

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, 'G-XXXXXXXXXX')

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

    

Ví dụ hoàn chỉnh

Mở rộng phần này để xem ví dụ về mã hoàn chỉnh của tất cả các bước trong hướng dẫn.

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, tag_id):
  """Create the Google Tag Hello World tag.

  Args:
    service: the Tag Manager service object.
    workspace: the workspace to create a tag within.
    tag_id: the Google tag ID or Google Analytics 4 measurement ID to use.

  Returns:
    The created tag.
  """

  hello_world_tag = {
      'name': 'Google Tag Hello World',
      'type': 'googtag',
      'parameter': [{
          'key': 'tagId',
          'type': 'template',
          'value': str(tag_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, 'G-XXXXXXXXXX')

  # 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 Google 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': 'Google Tag Hello World',
        'type': 'googtag',
        'parameter':
        [{ 'key': 'tagId', 'type': 'template', 'value': 'G-XXXXXXXXXX' }],
      };
      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>

    

Các bước tiếp theo

Giờ đây, khi đã quen với cách hoạt động của API, bạn có thể tham khảo thêm một số tài nguyên sau: