Google Tag Manager API - Developer's Guide

این راهنمای توسعه‌دهنده شما را با مراحل لازم برای دسترسی، ایجاد، و مدیریت نهادها در حساب «مدیر برچسب Google» ازطریق 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 پیدا می‌کند و یک برچسب Google در آن ظرف ایجاد می‌کند که در نمای صفحه فعال می‌شود.

برای توسعه این برنامه، باید این مراحل را دنبال کنید:

  1. محیط توسعه و پروژه خود را در «کنسول Google API» راه‌اندازی کنید.
  2. یک شیء سرویس Tag Manager ایجاد کنید.
    1. دسترسی به حساب Tag Manager را مجاز کنید.
    2. یک شیء سرویس Tag Manager ایجاد کنید.
  3. از میانای برنامه‌سازی کاربردی پرسمان کنید، پاسخ را مدیریت کنید، و نتایج را خروجی بگیرید.
    1. یک شیء سرویس Tag Manager مقداردهی‌شده دریافت کنید.
    2. از شیء سرویس Tag Manager برای پُرسمان Tag Manager API برای انجام کارهای زیر استفاده کنید:
      1. بازیابی محتوی Greetings برای حساب Google Tag Manager اصالت‌سنجی‌شده.
      2. فضای کاری جدیدی ایجاد کنید.
      3. برچسب Google را ایجاد کنید.
      4. راه‌انداز را برای فعال کردن برچسب ایجاد کنید.
      5. برچسب را به‌روز کنید تا با راه‌انداز فعال شود.

راه‌اندازی محیط توسعه نرم‌افزار و پروژه

ایجاد محفظه تبریک

این راهنما فرض می‌کند که شما یک حساب «مدیریت برچسب Google» با یک ظرف به‌نام Greetings دارید. دستورالعمل‌های راه‌اندازی و گردش کار (وب) را برای ایجاد حساب و محفظه با نام Greetings دنبال کنید.

نصب کتابخانه کارخواه

قبل‌از شروع، کتابخانه کارخواه Google APIs را نصب و پیکربندی کنید.

ایجاد و پیکربندی پروژه در «کنسول Google API»

برای شروع استفاده از Tag Manager API، ابتدا باید از ابزار راه‌اندازی استفاده کنید، که شما را در ایجاد پروژه در Google API Console و فعال کردن API راهنمایی می‌کند.

این راهنما از جریان اصالت‌سنجی برنامه نصب‌شده استفاده می‌کند. برای ایجاد اعتبارنامه پروژه، دستورالعمل‌های زیر را دنبال کنید. وقتی درخواست شد، Installed Application را برای نوع برنامه و Other را برای نوع برنامه نصب‌شده انتخاب کنید.

  1. از صفحه «اطلاعات کاربری»، روی ایجاد اطلاعات کاربری > شناسه کارخواه OAuth کلیک کنید تا اطلاعات کاربری OAuth 2.0 خود را ایجاد کنید یا روی ایجاد اطلاعات کاربری > کلید حساب سرویس کلیک کنید تا حساب سرویس ایجاد کنید.
  2. اگر شناسه کارخواه OAuth ایجاد کرده‌اید، نوع برنامه‌تان را انتخاب کنید.
  3. فرم را تکمیل کنید و روی ایجاد کلیک کنید.

شناسه‌های کارخواه و کلیدهای حساب سرویس برنامه شما اکنون در صفحه «اطلاعات کاربری» فهرست شده است. برای جزئیات، روی شناسه کارخواه کلیک کنید؛ پارامترها بسته به نوع شناسه متفاوت است، اما ممکن است شامل نشانی ایمیل، رمز کارخواه، مبدأ جاوا اسکریپت، یا 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 است. اگر می‌خواهید بیشتر بدانید، مجوز Tag Manager API را بخوانید.

کد زیر از جزئیات پروژه و کارخواه ایجادشده در بالا برای اصالت‌سنجی کاربر برنامه استفاده می‌کند و از او اجازه می‌خواهد تا ازطرف او به Google Tag Manager دسترسی پیدا کند.

برنامه تلاش می‌کند مرورگر پیش‌فرض را باز کند و کاربر را به نشانی وبی که در 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 می‌توان برای پُرسمان Tag Manager API استفاده کرد. مراحل زیر برای پیاده‌سازی برنامه نمونه الزامی است:

  1. بازیابی محتوای «خوشامدگویی‌ها»
  2. ایجاد برچسب Google
  3. راه‌انداز را برای فعال کردن برچسب ایجاد کنید
  4. به‌روزرسانی برچسب برای فعال شدن در راه‌انداز

۱. بازیابی محتوای خوشامدگویی‌ها

تابع زیر نشان می‌دهد که چگونه می‌توان از شیء سرویس «مدیر برچسب» برای پُرسمان 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();
  });
}
    

۲. ایجاد فضای کاری جدید

تکه‌کد زیر از 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);
}

    

۳. ایجاد برچسب Google

تکه‌کد زیر از Tag Manager API برای ایجاد برچسب Google استفاده می‌کند. می‌توانید مرجع روش ایجاد برچسب را برای فهرست ویژگی‌های الزامی و اختیاری که می‌توان هنگام ایجاد برچسب تنظیم کرد و مرجع فرهنگ لغت برچسب را برای فهرست ویژگی‌های هر نوع برچسب مرور کنید.

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

    

۴. راه‌انداز را برای فعال کردن برچسب ایجاد کنید

اکنون که برچسب ایجاد شده است، مرحله بعدی ایجاد «راه‌اندازی» است که در هر صفحه‌ای فعال می‌شود.

نام راه‌انداز 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);
}

    

۵. به‌روزرسانی برچسب برای فعال شدن در راه‌انداز

اکنون که برچسب و راه‌انداز ایجاد شده‌اند، باید با یکدیگر مرتبط شوند. برای انجام این کار، 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, '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();
  });
}

    

نمونه کامل‌شده

این بخش را ازهم باز کنید تا نمونه کد کامل همه مراحل راهنما را ببینید.

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>

    

مراحل بعدی

اکنون که با نحوه عملکرد API آشنا شدید، چند منبع دیگر برای شما وجود دارد: