Google Tag Manager API - डेवलपर के लिए गाइड

इस डेवलपर की गाइड में बताया गया है कि Tag Manager API v2 की मदद से, Google Tag Manager खाते में इकाइयां ऐक्सेस करने, बनाने, और मैनेज करने के लिए ज़रूरी चरणों के बारे में जानें.

शुरुआती जानकारी

इस गाइड में, 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 पर जाता है, तो टैग एक पेज व्यू हिट भेजता है.

इस ऐप्लिकेशन को डेवलप करने के लिए, आपको इन चरणों का पालन करना होगा:

  1. Google API कंसोल में अपना डेवलपमेंट एनवायरमेंट और प्रोजेक्ट सेट अप करें.
  2. Tag Manager सेवा ऑब्जेक्ट बनाएं.
    1. Tag Manager खाते के ऐक्सेस की अनुमति देना.
    2. Tag Manager सेवा ऑब्जेक्ट बनाएं.
  3. एपीआई पर क्वेरी करें, रिस्पॉन्स मैनेज करें, और नतीजे दें.
    1. शुरू किया गया Tag Manager सेवा ऑब्जेक्ट पाएं.
    2. Tag Manager सेवा ऑब्जेक्ट का इस्तेमाल करके, Tag Manager API की क्वेरी करने के लिए, ये टास्क करें:
      1. पुष्टि किए गए Google Tag Manager खाते के लिए ग्रीटिंग कंटेनर वापस पाएं.
      2. कोई नया फ़ाइल फ़ोल्डर बनाएं.
      3. Universal Analytics टैग बनाएं.
      4. टैग को सक्रिय करने के लिए ट्रिगर बनाएं.
      5. ट्रिगर पर सक्रिय करने के लिए टैग अपडेट करें.

अपना डेवलपमेंट एनवायरमेंट और प्रोजेक्ट सेट अप करें

Greeting कंटेनर बनाना

इस गाइड में यह माना गया है कि आपके पास एक Google Tag Manager खाता है, जिसका कंटेनर Greetings नाम का है. खाता और ग्रीटिंग नाम वाला कंटेनर बनाने के लिए, सेटअप और वर्कफ़्लो (वेब) के निर्देशों का पालन करें.

क्लाइंट लाइब्रेरी इंस्टॉल करना

शुरू करने से पहले, Google API क्लाइंट लाइब्रेरी को इंस्टॉल और कॉन्फ़िगर करें.

Google API (एपीआई) कंसोल में प्रोजेक्ट बनाना और कॉन्फ़िगर करना

Tag Manager API का इस्तेमाल शुरू करने से पहले, सेटअप टूल इस्तेमाल करना ज़रूरी है. यह आपको Google API Console में प्रोजेक्ट बनाने, एपीआई की सुविधा चालू करने, और क्रेडेंशियल बनाने के बारे में जानकारी देता है.

इस गाइड में इंस्टॉल किए गए ऐप्लिकेशन की पुष्टि करने के फ़्लो का इस्तेमाल किया जाता है. अपने प्रोजेक्ट के क्रेडेंशियल बनाने के लिए, नीचे दिए गए निर्देशों का पालन करें. निर्देश मिलने पर, APPLICATION TYPE के लिए Installed Application और INSTALLED APPLICATION TYPE के लिए Other चुनें.

  1. अपने OAuth 2.0 क्रेडेंशियल बनाने के लिए, क्रेडेंशियल पेज पर जाकर, क्रेडेंशियल > OAuth क्लाइंट आईडी पर क्लिक करें. इसके अलावा, सेवा खाता बनाने के लिए क्रेडेंशियल बनाएं > सेवा खाता कुंजी पर क्लिक करें.
  2. अगर आपने OAuth क्लाइंट आईडी बनाया है, तो अपने ऐप्लिकेशन का टाइप चुनें.
  3. फ़ॉर्म भरें और बनाएं पर क्लिक करें.

आपके ऐप्लिकेशन के क्लाइंट आईडी और सेवा खाते की कुंजियां अब क्रेडेंशियल पेज पर सूची में शामिल हैं. ज़्यादा जानकारी के लिए, किसी क्लाइंट आईडी पर क्लिक करें. आईडी के टाइप के आधार पर पैरामीटर अलग-अलग होते हैं. हालांकि, उनमें ईमेल पता, क्लाइंट सीक्रेट, JavaScript के ऑरिजिन या रीडायरेक्ट यूआरआई शामिल हो सकते हैं.

JSON डाउनलोड करें बटन पर क्लिक करके, क्लाइंट की जानकारी डाउनलोड करें. इस फ़ाइल का नाम बदलकर client_secrets.json करें. पुष्टि करने के लिए बाद में इस फ़ाइल का इस्तेमाल किया जाएगा.

Tag Manager सेवा ऑब्जेक्ट बनाना

Tag Manager service ऑब्जेक्ट का इस्तेमाल, एपीआई अनुरोध करने के लिए किया जाएगा.

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 पर होस्ट किए गए यूआरएल पर नेविगेट करने की कोशिश करेगा. उपयोगकर्ता को साइन इन करने और ऐप्लिकेशन को अपने 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 एपीआई के लिए क्वेरी करें

Tag Manager सेवा ऑब्जेक्ट का इस्तेमाल, Tag Manager API की क्वेरी करने के लिए किया जा सकता है. सैंपल प्रोग्राम लागू करने के लिए, इन चरणों को पूरा करना ज़रूरी है:

  1. ग्रीटिंग कंटेनर वापस लाएं
  2. Universal Analytics टैग बनाना
  3. टैग सक्रिय करने के लिए ट्रिगर बनाएं
  4. ट्रिगर पर सक्रिय करने के लिए टैग अपडेट करें

1. Greetings कंटेनर को वापस पाना

नीचे दिए गए फ़ंक्शन से पता चलता है कि Tag Manager सेवा ऑब्जेक्ट का इस्तेमाल करके, Tag Manager API से क्वेरी कैसे की जा सकती है, ताकि खाते के सभी कंटेनर को सूची में रखा जा सके और ग्रीटिंग नाम का कंटेनर वापस पाया जा सके.

Python

def FindGreetingsContainer(service, account_path):
  """Find the greetings container.

  Args:
    service: the Tag Manager service object.
    account_path: the path of the Tag Manager account from which to retrieve the
      Greetings container.

  Returns:
    The greetings container if it exists, or None if it does not.
  """
  # Query the Tag Manager API to list all containers for the given account.
  container_wrapper = service.accounts().containers().list(
      parent=account_path).execute()

  # Find and return the Greetings container if it exists.
  for container in container_wrapper['container']:
    if container['name'] == 'Greetings':
      return container
  return None
    

JavaScript

/**
 * Returns the greetings container if it exists.
 *
 * @param {string} accountPath The account which contains the Greetings
 * container.
 * @return {Promise} A promise to find the greetings container.
 */
function findContainer(accountPath, containerName) {
  console.log('Finding container in account:' + accountPath);
  var request = gapi.client.tagmanager.accounts.containers.list({
    'parent': accountPath
  });
  return requestPromise(request)
      .then((response) => {
        var containers = response.container || [];
        var container =
            containers.find((container) => container.name === containerName);
        return container ||
            Promise.reject('Unable to find ' + containerName +' container.');
      });
}
    

इसके बाद, प्रोग्राम की मुख्य स्क्रिप्ट को अपडेट करें, ताकि Tag Manager में दिए गए findGreetingsContainer फ़ंक्शन को कॉल किया जा सके 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 का इस्तेमाल करके एक नया फ़ाइल फ़ोल्डर बनाता है. इसका इस्तेमाल हम ट्रिगर और टैग में किए गए बदलावों को मैनेज करने के लिए करते हैं. ज़रूरी और वैकल्पिक प्रॉपर्टी की सूची देखने के लिए, फ़ाइल फ़ोल्डर बनाने के तरीके का रेफ़रंस देखें. इन प्रॉपर्टी को फ़ाइल फ़ोल्डर बनाते समय सेट किया जा सकता है.

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 टैग बनाना

नीचे दिया गया कोड स्निपेट, Universal Analytics टैग बनाने के लिए, Tag Manager API का इस्तेमाल करता है. टैग बनाते समय सेट की जा सकने वाली ज़रूरी और वैकल्पिक प्रॉपर्टी की सूची के लिए, टैग बनाने के तरीके का रेफ़रंस देखा जा सकता है. साथ ही, हर टैग टाइप की प्रॉपर्टी की सूची के लिए, टैग डिक्शनरी का रेफ़रंस भी देखा जा सकता है.

Python

def CreateHelloWorldTag(service, workspace, tracking_id):
  """Create the Universal Analytics Hello World Tag.

  Args:
    service: the Tag Manager service object.
    workspace: the workspace to create a tag within.
    tracking_id: the Universal Analytics tracking ID to use.

  Returns:
    The created tag.
  """

  hello_world_tag = {
      'name': 'Universal Analytics Hello World',
      'type': 'ua',
      'parameter': [{
          'key': 'trackingId',
          'type': 'template',
          'value': str(tracking_id),
      }],
  }

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

    

JavaScript

/**
 * Creates a universal analytics tag.
 *
 * @param {Object} workspace The workspace to create the tag
 * @return {Promise} A promise to create a hello world tag.
 */
function createHelloWorldTag(workspace) {
  console.log('Creating hello world tag');
  var helloWorldTag = {
    'name': 'Universal Analytics Hello World',
    'type': 'ua',
    'parameter':
    [{ 'key': 'trackingId', 'type': 'template', 'value': 'UA-1234-5' }],
  };
  var request =
    gapi.client.tagmanager.accounts.containers.workspaces.tags.create(
      { 'parent': workspace.path }, helloWorldTag);
  return requestPromise(request);
}

    

4. टैग सक्रिय करने के लिए ट्रिगर बनाएं

अब टैग बन गया है, तो अगला कदम है एक ऐसा ट्रिगर बनाना जो किसी भी पेज पर ट्रिगर होगा.

इस ट्रिगर को Hello World Trigger नाम दिया जाएगा और यह किसी भी पेज व्यू के लिए फ़ायर होगा. उदाहरण के लिए:

Python

def CreateHelloWorldTrigger(service, workspace):
  """Create the Hello World Trigger.

  Args:
    service: the Tag Manager service object.
    workspace: the workspace to create the trigger within.

  Returns:
    The created trigger.
  """

  hello_world_trigger = {
      'name': 'Hello World Rule',
      'type': 'PAGEVIEW'
  }

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

JavaScript

/**
 * Creates a page view trigger.
 *
 * @param {Object} workspace The workspace to create the trigger in.
 * @return {Promise} A promise to create a page view trigger.
 */
function createHelloWorldTrigger(workspace) {
  console.log('Creating hello world trigger in workspace');
  var helloWorldTrigger = { 'name': 'Hello World Trigger', 'type': 'PAGEVIEW' };
  var request =
    gapi.client.tagmanager.accounts.containers.workspaces.triggers.create(
      { 'parent': workspace.path }, helloWorldTrigger);
  return requestPromise(request);
}

    

5. ट्रिगर पर सक्रिय करने के लिए टैग अपडेट करें

अब जब एक टैग और ट्रिगर बन गया है, तो उन्हें एक-दूसरे से जुड़ना होगा. ऐसा करने के लिए, टैग से जुड़े firingTriggerIds की सूची में triggerId को जोड़ें. उदाहरण के लिए:

Python

def UpdateHelloWorldTagWithTrigger(service, tag, trigger):
  """Update a Tag with a Trigger.

  Args:
    service: the Tag Manager service object.
    tag: the tag to associate with the trigger.
    trigger: the trigger to associate with the tag.
  """
  # Get the tag to update.
  tag = service.accounts().containers().workspaces().tags().get(
      path=tag['path']).execute()

  # Update the Firing Trigger for the Tag.
  tag['firingTriggerId'] = [trigger['triggerId']]

  # Update the Tag.
  response = service.accounts().containers().workspaces().tags().update(
      path=tag['path'],
      body=tag).execute()
    

JavaScript

/**
 * Updates a tag to fire on a particular trigger.
 *
 * @param {Object} tag The tag to update.
 * @param {Object} trigger The trigger which causes the tag to fire.
 * @return {Promise} A promise to update a tag to fire on a particular trigger.
 */
function updateHelloWorldTagWithTrigger(tag, trigger) {
  console.log('Update hello world tag with trigger');
  tag['firingTriggerId'] = [trigger.triggerId];
  var request =
    gapi.client.tagmanager.accounts.containers.workspaces.tags.update(
      { 'path': tag.path }, tag);
  return requestPromise(request);
}
    

इसके बाद, 'बनाएं' और 'अपडेट करें' फ़ंक्शन को कॉल करने के लिए, प्रोग्राम की मुख्य स्क्रिप्ट अपडेट करें. उदाहरण के लिए:

Python


def main(argv):
  # Get tag manager account ID from command line.
  assert len(argv) == 2 and 'usage: gtm-api-hello-world.py <account_id>'
  account_id = str(argv[1])
  account_path = 'accounts/%s' % account_id

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

  # Authenticate and construct service.
  service = GetService('tagmanager', 'v2', scope, 'client_secrets.json')

  # Find the greetings container.
  container = FindGreetingsContainer(service, account_path)

  # Create a new workspace.
  workspace = CreateWorkspace(service, container)

  # Create the hello world tag.
  tag = CreateHelloWorldTag(
      service, workspace, 'UA-1234-5')

  # Create the hello world Trigger.
  trigger = CreateHelloWorldTrigger(
      service, workspace)

  # Update the hello world tag to fire based on the hello world tag.
  UpdateHelloWorldTagWithTrigger(service, tag, trigger)
if __name__ == '__main__':
  main(sys.argv)
    

JavaScript

/**
 * Interacts with the tagmanager api v2 to create a container, workspace,
 * trigger, and tag.
 *
 * @return {Promise} A promise to run the tag manager example.
 */
function runTagManagerExample() {
  return new Promise((resolve, reject) => {
    console.log('Running Tag Manager Example.');
    var trigger = null;
    var workspace = null;
    findContainer(ACCOUNT_PATH, CONTAINER_NAME)
        .then(createWorkspace)
        .then((createdWorkspace) => {
          workspace = createdWorkspace;
          return createHelloWorldTrigger(workspace);
        })
        .then((createdTrigger) => {
          trigger = createdTrigger;
          return createHelloWorldTag(workspace);
        })
        .then((createdTag) => {
          return updateHelloWorldTagWithTrigger(createdTag, trigger);
        })
        .catch(handleError);
    resolve();
  });
}

    

पूरा उदाहरण

गाइड में सभी चरणों का पूरा कोड उदाहरण देखने के लिए इस सेक्शन को बड़ा करें.

Python

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

import argparse
import sys

import httplib2

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


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

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

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

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

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

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

  return service

def FindGreetingsContainer(service, account_path):
  """Find the greetings container.

  Args:
    service: the Tag Manager service object.
    account_path: the path of the Tag Manager account from which to retrieve the
      Greetings container.

  Returns:
    The greetings container if it exists, or None if it does not.
  """
  # Query the Tag Manager API to list all containers for the given account.
  container_wrapper = service.accounts().containers().list(
      parent=account_path).execute()

  # Find and return the Greetings container if it exists.
  for container in container_wrapper['container']:
    if container['name'] == 'Greetings':
      return container
  return None

def CreateWorkspace(service, container):
    """Creates a workspace named 'my workspace'.

    Args:
      service: the Tag Manager service object.
      container: the container to insert the workspace within.

    Returns:
      The created workspace.
    """
    return service.accounts().containers().workspaces().create(
        parent=container['path'],
        body={
            'name': 'my workspace',
        }).execute()

def CreateHelloWorldTag(service, workspace, tracking_id):
  """Create the Universal Analytics Hello World Tag.

  Args:
    service: the Tag Manager service object.
    workspace: the workspace to create a tag within.
    tracking_id: the Universal Analytics tracking ID to use.

  Returns:
    The created tag.
  """

  hello_world_tag = {
      'name': 'Universal Analytics Hello World',
      'type': 'ua',
      'parameter': [{
          'key': 'trackingId',
          'type': 'template',
          'value': str(tracking_id),
      }],
  }

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


def CreateHelloWorldTrigger(service, workspace):
  """Create the Hello World Trigger.

  Args:
    service: the Tag Manager service object.
    workspace: the workspace to create the trigger within.

  Returns:
    The created trigger.
  """

  hello_world_trigger = {
      'name': 'Hello World Rule',
      'type': 'PAGEVIEW'
  }

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

def UpdateHelloWorldTagWithTrigger(service, tag, trigger):
  """Update a Tag with a Trigger.

  Args:
    service: the Tag Manager service object.
    tag: the tag to associate with the trigger.
    trigger: the trigger to associate with the tag.
  """
  # Get the tag to update.
  tag = service.accounts().containers().workspaces().tags().get(
      path=tag['path']).execute()

  # Update the Firing Trigger for the Tag.
  tag['firingTriggerId'] = [trigger['triggerId']]

  # Update the Tag.
  response = service.accounts().containers().workspaces().tags().update(
      path=tag['path'],
      body=tag).execute()

def main(argv):
  # Get tag manager account ID from command line.
  assert len(argv) == 2 and 'usage: gtm-api-hello-world.py <account_id>'
  account_id = str(argv[1])
  account_path = 'accounts/%s' % account_id

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

  # Authenticate and construct service.
  service = GetService('tagmanager', 'v2', scope, 'client_secrets.json')

  # Find the greetings container.
  container = FindGreetingsContainer(service, account_path)

  # Create a new workspace.
  workspace = CreateWorkspace(service, container)

  # Create the hello world tag.
  tag = CreateHelloWorldTag(
      service, workspace, 'UA-1234-5')

  # Create the hello world Trigger.
  trigger = CreateHelloWorldTrigger(
      service, workspace)

  # Update the hello world tag to fire based on the hello world tag.
  UpdateHelloWorldTagWithTrigger(service, tag, trigger)
  
if __name__ == '__main__':
  main(sys.argv)

    

JavaScript

<html>
  <head>
    <script type="text/javascript">

    // Your Client ID can be retrieved from your project in the Google
    // Developer Console, https://console.developers.google.com
    var CLIENT_ID = TODO;
    var SCOPES = [
      'https://www.googleapis.com/auth/tagmanager.manage.accounts',
      'https://www.googleapis.com/auth/tagmanager.edit.containers',
      'https://www.googleapis.com/auth/tagmanager.delete.containers',
      'https://www.googleapis.com/auth/tagmanager.edit.containerversions',
      'https://www.googleapis.com/auth/tagmanager.manage.users',
      'https://www.googleapis.com/auth/tagmanager.publish'
    ];

    // Parameter values used by the script
    ACCOUNT_PATH = TODO; // such as: 'accounts/555555';
    CONTAINER_NAME = 'Greetings';
    WORKSPACE_NAME = 'Example workspace';

    /**
     * Check if current user has authorization for this application.
     *
     * @param {bool} immediate Whether login should use the "immediate mode",
     *     which causes the security token to be refreshed behind the scenes
     *     with no UI.
     */
    function checkAuth(immediate) {
      var authorizeCheckPromise = new Promise((resolve) => {
        gapi.auth.authorize(
          { client_id: CLIENT_ID, scope: SCOPES.join(' '), immediate: immediate },
          resolve);
      });
      authorizeCheckPromise
          .then(handleAuthResult)
          .then(loadTagManagerApi)
          .then(runTagManagerExample)
          .catch(() => {
            console.log('You must authorize any access to the api.');
          });
    }

    /**
     * Check if current user has authorization for this application.
     */
    function checkAuth() {
      checkAuth(true);
    }

    /**
     * Initiate auth flow in response to user clicking authorize button.
     *
     * @param {Event} event Button click event.
     * @return {boolean} Returns false.
     */
    function handleAuthClick(event) {
      checkAuth();
      return false;
    }

    /**
     * Handle response from authorization server.
     *
     * @param {Object} authResult Authorization result.
     * @return {Promise} A promise to call resolve if authorize or redirect to a
     *   login flow.
     */
    function handleAuthResult(authResult) {
      return new Promise((resolve, reject) => {
        var authorizeDiv = document.getElementById('authorize-div');
        if (authResult && !authResult.error) {
          // Hide auth UI, then load client library.
          authorizeDiv.style.display = 'none';
          resolve();
        } else {
          // Show auth UI, allowing the user to initiate authorization by
          // clicking authorize button.
          authorizeDiv.style.display = 'inline';
          reject();
        }
      });
    }

    /**
     * Load Tag Manager API client library.

     * @return {Promise} A promise to load the tag manager api library.
     */
    function loadTagManagerApi() {
      return new Promise((resolve, reject) => {
        console.log('Load Tag Manager api');
        gapi.client.load('tagmanager', 'v2', resolve);
      });
    }

    /**
     * Interacts with the tagmanager api v2 to create a container,
     * workspace, trigger, and tag.
     *
     * @return {Promise} A promise to run the tag manager example.
     */
    function runTagManagerExample() {
      return new Promise((resolve, reject) => {
        console.log('Running Tag Manager Example.');
        var trigger = null;
        var workspace = null;
        findContainer(ACCOUNT_PATH, CONTAINER_NAME)
            .then(createWorkspace)
            .then((createdWorkspace) => {
              workspace = createdWorkspace;
              return createHelloWorldTrigger(workspace);
            })
            .then((createdTrigger) => {
              trigger = createdTrigger;
              return createHelloWorldTag(workspace);
            })
            .then((createdTag) => {
              return updateHelloWorldTagWithTrigger(createdTag, trigger);
            })
            .catch(handleError);
        resolve();
      });
    }

    /**
     * Returns the greetings container if it exists.
     *
     * @param {string} accountPath The account which contains the Greetings
     *     container.
     * @param {string} containerName The name of the container to find.
     * @return {Promise} A promise to find the greetings container.
     */
    function findContainer(accountPath, containerName) {
      console.log('Finding container in account:' + accountPath);
      var request = gapi.client.tagmanager.accounts.containers.list({
        'parent': accountPath
      });
      return requestPromise(request)
          .then((response) => {
            var containers = response.container || [];
            var container = containers.find(
                (container) => container.name === containerName);
            return container || Promise.reject(
                'Unable to find ' + containerName +' container.');
          });
    }

    /**
     * Creates a workspace in the Greetings container.
     *
     * @param {Object} container The container to create a new workspace.
     * @return {Promise} A promise to create a workspace.
     */
    function createWorkspace(container) {
      console.log('Creating workspace in container:' + container.path);
      var request = gapi.client.tagmanager.accounts.containers.workspaces.create(
        { 'parent': container.path },
        { name: WORKSPACE_NAME, description: 'my workspace created via api' });
      return requestPromise(request);
    }

    /**
     * Creates a page view trigger.
     *
     * @param {Object} workspace The workspace to create the trigger in.
     * @return {Promise} A promise to create a page view trigger.
     */
    function createHelloWorldTrigger(workspace) {
      console.log('Creating hello world trigger in workspace');
      var helloWorldTrigger =
          { 'name': 'Hello World Trigger', 'type': 'PAGEVIEW' };
      var request =
        gapi.client.tagmanager.accounts.containers.workspaces.triggers.create(
          { 'parent': workspace.path }, helloWorldTrigger);
      return requestPromise(request);
    }

    /**
    * Creates a universal analytics tag.
    *
    * @param {Object} workspace The workspace to create the tag
    * @return {Promise} A promise to create a hello world tag.
    */
    function createHelloWorldTag(workspace) {
      console.log('Creating hello world tag');
      var helloWorldTag = {
        'name': 'Universal Analytics Hello World',
        'type': 'ua',
        'parameter':
        [{ 'key': 'trackingId', 'type': 'template', 'value': 'UA-1234-5' }],
      };
      var request =
        gapi.client.tagmanager.accounts.containers.workspaces.tags.create(
          { 'parent': workspace.path }, helloWorldTag);
      return requestPromise(request);
    }

    /**
     * Updates a tag to fire on a particular trigger.
     *
     * @param {Object} tag The tag to update.
     * @param {Object} trigger The trigger which causes the tag to fire.
     * @return {Promise} A promise to update a tag to fire on a particular
     *    trigger.
     */
    function updateHelloWorldTagWithTrigger(tag, trigger) {
      console.log('Update hello world tag with trigger');
      tag['firingTriggerId'] = [trigger.triggerId];
      var request =
        gapi.client.tagmanager.accounts.containers.workspaces.tags.update(
          { 'path': tag.path }, tag);
      return requestPromise(request);
    }

    /**
     * Logs an error message to the console.
     *
     * @param {string|Object} error The error to log to the console.
     */
    function handleError(error) {
      console.log('Error when interacting with GTM API');
      console.log(error);
    }

    /**
     * Wraps an API request into a promise.
     *
     * @param {Object} request the API request.
     * @return {Promise} A promise to execute the api request.
     */
    function requestPromise(request) {
      return new Promise((resolve, reject) => {
        request.execute((response) => {
          if (response.code) {
            reject(response);
          }
          resolve(response);
        });
      });
    }
    </script>

    <script src="https://apis.google.com/js/client.js?onload=checkAuth">
    </script>
  </head>
  <body>
    <div id="authorize-div" style="display: none">
      <span>Authorize access to Tag Manager API</span>
      <!--Button for the user to click to initiate auth sequence -->
      <button id="authorize-button" onclick="handleAuthClick(event)">
        Authorize
      </button>
    </div>
    <pre id="output"></pre>
  </body>
</html>

    

अगले चरण

आपने एपीआई के काम करने के तरीके के बारे में जान लिया है, तो अब यहां कुछ और संसाधन हैं: