Google Tag Manager API - คู่มือสำหรับนักพัฒนาซอฟต์แวร์

คู่มือสำหรับนักพัฒนาซอฟต์แวร์นี้จะแนะนำขั้นตอนที่จำเป็นในการเข้าถึง สร้าง และจัดการเอนทิตีภายในบัญชี Google Tag Manager ผ่าน Tag Manager API v2

บทนำ

คู่มือนี้จะแนะนําขั้นตอนต่างๆ ในการเข้าถึงและกําหนดค่าบัญชี Google Tag Manager เมื่ออ่านจบ คุณจะมีความเข้าใจพื้นฐานเกี่ยวกับวิธี ทำงานต่อไปนี้

  • สร้างออบเจ็กต์บริการ Tag Manager
  • ตรวจสอบสิทธิ์และให้สิทธิ์ผู้ใช้
  • ใช้ Tag Manager API เพื่อเข้าถึงและจัดการทรัพยากร

ก่อนเริ่มต้น

ก่อนที่จะเริ่มอ่านคำแนะนำนี้ เราขอแนะนำให้คุณทำความคุ้นเคยกับ Google Tag Manager โดยไปที่ ศูนย์ช่วยเหลือของ Google Tag Manager

การใช้บัญชีทดสอบ

หากคุณต้องการใช้ Tag Manager API เพื่อสร้าง กำหนดค่า หรือลบ เอนทิตี เราขอแนะนำให้คุณใช้และยืนยันโค้ดด้วยบัญชีทดสอบ การใช้บัญชีทดสอบจะช่วยป้องกันไม่ให้คุณทำการเปลี่ยนแปลงบัญชีที่ใช้งานอยู่โดยไม่ตั้งใจ เมื่อทดสอบและยืนยันว่าโค้ด ทํางานได้ตามที่คาดไว้โดยใช้บัญชีทดสอบแล้ว คุณจะเริ่ม ใช้การติดตั้งใช้งานกับบัญชีจริงได้

เลือกภาษา

เลือกภาษาการเขียนโปรแกรมที่คุณต้องการใช้ตามตัวอย่าง

Python


เราเลือกใช้ Python สำหรับโค้ดที่ตัดตอนมาทั้งหมดในคำแนะนำนี้

JavaScript


เราเลือกใช้ JavaScript สำหรับข้อมูลโค้ดทั้งหมดในคำแนะนำนี้

ภาพรวมของโปรแกรม

โปรแกรมตัวอย่างที่รวมอยู่ในคู่มือนี้เป็นแอปบรรทัดคำสั่ง เมื่อระบุรหัสบัญชี แอปจะค้นหาคอนเทนเนอร์ชื่อ Greetings และสร้างแท็ก Universal Analytics ในคอนเทนเนอร์นั้น เมื่อผู้ใช้เข้าชม hello-world.html แท็กจะส่ง Hit การดูหน้าเว็บ

หากต้องการพัฒนาแอปพลิเคชันนี้ คุณต้องทำตามขั้นตอนต่อไปนี้

  1. ตั้งค่าสภาพแวดล้อมการพัฒนาและโปรเจ็กต์ในคอนโซล Google API
  2. สร้างออบเจ็กต์บริการ Tag Manager
    1. ให้สิทธิ์เข้าถึงบัญชี Tag Manager
    2. สร้างออบเจ็กต์บริการ Tag Manager
  3. ค้นหา API จัดการการตอบกลับ และแสดงผลลัพธ์
    1. รับออบเจ็กต์บริการ Tag Manager ที่เริ่มต้นแล้ว
    2. ใช้ออบเจ็กต์บริการของ Tag Manager เพื่อค้นหา Tag Manager API เพื่อทํางานต่อไปนี้
      1. เรียกข้อมูลคอนเทนเนอร์ Greetings สำหรับ บัญชี Google Tag Manager ที่ตรวจสอบสิทธิ์แล้ว
      2. สร้างพื้นที่ทำงานใหม่
      3. สร้างแท็ก Universal Analytics
      4. สร้างทริกเกอร์เพื่อเริ่มการทํางานของแท็ก
      5. อัปเดตแท็กให้เริ่มทํางานในทริกเกอร์

ตั้งค่าสภาพแวดล้อมในการพัฒนาและโปรเจ็กต์

สร้างคอนเทนเนอร์ Greetings

คู่มือนี้ถือว่าคุณมีบัญชี Google Tag Manager ที่มีคอนเทนเนอร์ชื่อ Greetings ทำตามวิธีการสำหรับการตั้งค่าและเวิร์กโฟลว์ (เว็บ) เพื่อสร้างบัญชีและคอนเทนเนอร์ ชื่อ Greetings

ติดตั้งไลบรารีของไคลเอ็นต์

ก่อนที่จะเริ่มต้น ให้ติดตั้งและกำหนดค่าไลบรารีของไคลเอ็นต์ Google APIs

สร้างและกำหนดค่าโปรเจ็กต์ในคอนโซล Google API

ในการเริ่มต้นใช้งาน Tag Manager API ก่อนอื่นคุณต้องใช้เครื่องมือการตั้งค่า ซึ่งจะนำทางคุณในการสร้างโปรเจ็กต์ในคอนโซล Google API และเปิดใช้ API ดังกล่าว

คู่มือนี้ใช้ขั้นตอนการตรวจสอบสิทธิ์แอปพลิเคชันที่ติดตั้ง ทำตามวิธีการด้านล่างเพื่อสร้างข้อมูลเข้าสู่ระบบของโปรเจ็กต์ เมื่อระบบแจ้ง ให้เลือก Installed Application สำหรับประเภทแอปพลิเคชัน และ Other สำหรับประเภทแอปพลิเคชันที่ติดตั้ง

  1. จากหน้าข้อมูลเข้าสู่ระบบ ให้คลิกสร้างข้อมูลเข้าสู่ระบบ > รหัสไคลเอ็นต์ OAuth เพื่อสร้างข้อมูลเข้าสู่ระบบ OAuth 2.0 หรือคลิกสร้างข้อมูลเข้าสู่ระบบ > คีย์บัญชีบริการเพื่อสร้างบัญชีบริการ
  2. หากสร้างรหัสไคลเอ็นต์ OAuth ให้เลือกประเภทแอปพลิเคชัน
  3. กรอกแบบฟอร์ม แล้วคลิกสร้าง

ตอนนี้รหัสไคลเอ็นต์และคีย์บัญชีบริการของแอปพลิเคชันจะแสดงในหน้าข้อมูลเข้าสู่ระบบ ดูรายละเอียดได้โดยคลิกรหัสไคลเอ็นต์ พารามิเตอร์จะแตกต่างกันไป ขึ้นอยู่กับประเภทรหัส แต่อาจรวมถึงอีเมล ข้อมูลลับของไคลเอ็นต์ ต้นทางของ JavaScript หรือ URI การเปลี่ยนเส้นทาง

ดาวน์โหลดรายละเอียดไคลเอ็นต์โดยคลิกปุ่มดาวน์โหลด JSON เปลี่ยนชื่อไฟล์นี้เป็น client_secrets.json ระบบจะใช้ไฟล์นี้ในภายหลังเพื่อวัตถุประสงค์ในการตรวจสอบสิทธิ์

สร้างออบเจ็กต์บริการ Tag Manager

ออบเจ็กต์ service ของ Tag Manager คือสิ่งที่คุณจะใช้เพื่อส่งคำขอ API

ขั้นตอนที่จำเป็นในการสร้างออบเจ็กต์บริการ Tag Manager มีดังนี้

  1. ให้สิทธิ์เข้าถึงบัญชี Google Tag Manager
  2. สร้างออบเจ็กต์บริการของ Tag Manager

ให้สิทธิ์เข้าถึงบัญชี Google Tag Manager

เมื่อผู้ใช้เริ่มแอปพลิเคชันที่สร้างด้วย Google Tag Manager API ผู้ใช้จะต้องให้สิทธิ์การเข้าถึงบัญชี Google Tag Manager แก่แอปพลิเคชัน กระบวนการนี้เรียกว่าการให้สิทธิ์ วิธีที่แนะนำสำหรับการให้สิทธิ์ผู้ใช้คือ OAuth 2.0 หากต้องการดูข้อมูลเพิ่มเติม โปรดอ่านการให้สิทธิ์ API ของ Tag Manager

โค้ดด้านล่างใช้รายละเอียดโปรเจ็กต์และไคลเอ็นต์ ที่สร้างไว้ข้างต้นเพื่อตรวจสอบสิทธิ์ผู้ใช้แอปพลิเคชัน และขอ สิทธิ์ในการเข้าถึง Google Tag Manager ในนามของผู้ใช้

แอปพลิเคชันจะพยายามเปิดเบราว์เซอร์เริ่มต้นและนำผู้ใช้ไปยัง URL ที่โฮสต์ใน google.com จากนั้นระบบจะแจ้งให้ผู้ใช้ลงชื่อเข้าใช้และให้สิทธิ์เข้าถึงบัญชี Tag Manager แก่แอปพลิเคชัน เมื่อได้รับสิทธิ์แล้ว แอปพลิเคชันจะพยายามอ่านรหัสจากหน้าต่างเบราว์เซอร์ แล้วปิดหน้าต่าง

หมายเหตุ: หากเกิดข้อผิดพลาด แอปพลิเคชัน จะแจ้งให้ผู้ใช้ป้อนรหัสการให้สิทธิ์ในบรรทัดคำสั่งแทน

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 เพื่อค้นหา Tag Manager API ได้ คุณต้องทำตามขั้นตอนต่อไปนี้เพื่อติดตั้งใช้งาน โปรแกรมตัวอย่าง

  1. เรียกข้อมูลคอนเทนเนอร์คำทักทาย
  2. สร้างแท็ก Universal Analytics
  3. สร้างทริกเกอร์เพื่อเริ่มการทํางานของแท็ก
  4. อัปเดตแท็กให้เริ่มทำงานเมื่อทริกเกอร์

1. เรียกข้อมูลคอนเทนเนอร์คำทักทาย

ฟังก์ชันต่อไปนี้แสดงให้เห็นว่าออบเจ็กต์บริการ Tag Manager สามารถใช้เพื่อค้นหา 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.');
      });
}
    

จากนั้นอัปเดตสาขาการดำเนินการหลักของโปรแกรมเพื่อเรียกใช้ฟังก์ชัน findGreetingsContainer เมื่อระบุ Tag Manager accountId เช่น

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 create

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. สร้างแท็ก Universal Analytics

ข้อมูลโค้ดต่อไปนี้ใช้ Tag Manager API เพื่อสร้างแท็ก Universal Analytics คุณสามารถดูข้อมูลอ้างอิงเกี่ยวกับเมธอด Tag create เพื่อดูรายการพร็อพเพอร์ตี้ที่ต้องระบุและพร็อพเพอร์ตี้ที่ไม่บังคับซึ่งตั้งค่าได้เมื่อสร้างแท็ก และข้อมูลอ้างอิงพจนานุกรมแท็ก เพื่อดูรายการพร็อพเพอร์ตี้สำหรับแท็กแต่ละประเภท

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 แล้ว เรามีแหล่งข้อมูลเพิ่มเติมสำหรับคุณดังนี้