En esta guía para desarrolladores, se explican los pasos necesarios para acceder, crear y administrar entidades en una cuenta de Google Tag Manager mediante la API de Tag Manager v2.
Introducción
En esta guía, se explican varios pasos para acceder a una cuenta de Google Tag Manager y configurarla. Cuando termines, tendrás conocimientos básicos sobre cómo realizar las siguientes tareas:
- Crea un objeto de servicio de Tag Manager.
- Autentica y autoriza a un usuario.
- Trabaje con la API de Tag Manager para acceder a los recursos y administrarlos.
Antes de comenzar
Antes de comenzar con la guía, te recomendamos que visites el Centro de ayuda de Google Tag Manager para familiarizarte con Google Tag Manager.
Usa una cuenta de prueba
Si deseas usar la API de Tag Manager para crear, configurar o borrar entidades, te recomendamos que implementes y verifiques tu código con una cuenta de prueba. Usar una cuenta de prueba te ayudará a evitar que realices cambios accidentales en una cuenta activa. Una vez que hayas probado y confirmado que tu código funciona como se espera con la cuenta de prueba, puedes comenzar a usar la implementación con tus cuentas reales.
Seleccionar un idioma
Seleccione el lenguaje de programación que desea seguir en los ejemplos:
Python
Python está seleccionado para todos los fragmentos de código de esta guía.
JavaScript
Se selecciona JavaScript para todos los fragmentos de código de esta guía.
Program overview
El programa de ejemplo incluido en esta guía es una app de línea de comandos. Con un ID de cuenta, la app encuentra un contenedor llamado Greetings y crea una etiqueta de Universal Analytics en ese contenedor. Cuando un usuario visita hello-world.html, la etiqueta envía un hit de página vista.
Para desarrollar esta aplicación, debes seguir estos pasos:
- Configura tu entorno de desarrollo y tu proyecto en la Consola de API de Google.
- Crea un objeto de servicio de Tag Manager.
- Autorice el acceso a una cuenta de Tag Manager.
- Crea un objeto de servicio de Tag Manager.
- Consulta la API, controla la respuesta y genera los resultados.
- Obtenga un objeto de servicio de Tag Manager inicializado.
- Usa el objeto de servicio de Tag Manager para consultar la API de Tag Manager a fin de realizar las siguientes tareas:
- Recupera el contenedor Greetings de la cuenta autenticada de Google Tag Manager.
- Crea un lugar de trabajo nuevo
- Cree la etiqueta de Universal Analytics.
- Crea el activador para activar la etiqueta.
- Actualice la etiqueta para que se active en el activador.
Configura tu entorno de desarrollo y proyecto
Cree el contenedor Greetings
En esta guía, se da por sentado que tienes una cuenta de Google Tag Manager con un contenedor llamado Greetings. Sigue las instrucciones para la configuración y el flujo de trabajo (Web) a fin de crear una cuenta y un contenedor llamado Greetings.
Instala una biblioteca cliente
Antes de comenzar, instala y configura una biblioteca cliente de las API de Google.
Crea y configura un proyecto en la Consola de API de Google
Para comenzar a usar la API de Tag Manager, primero debes usar la herramienta de configuración, que te guiará para crear un proyecto en Google API Console, habilitar la API y crear credenciales.
En esta guía, se usa un flujo de autenticación de aplicación instalada. Sigue las instrucciones que aparecen a continuación para crear las credenciales del proyecto. Cuando se te solicite, selecciona Installed Application
para APPLICATION_TYPE y Other
para INSTALLED APPLICATION
TYPE.
- En la página Credenciales, haz clic en Crear credenciales > ID de cliente de OAuth para crear tus credenciales de OAuth 2.0 o Crear credenciales > Clave de cuenta de servicio para crear una cuenta de servicio.
- Si creaste un ID de cliente de OAuth, selecciona tu tipo de aplicación.
- Complete el formulario y haga clic en Crear.
Los ID de cliente de tu aplicación y las claves de cuenta de servicio ahora se enumeran en la página Credenciales. Para obtener más información, haz clic en un ID de cliente. Los parámetros varían según el tipo de ID, pero pueden incluir la dirección de correo electrónico, el secreto del cliente, los orígenes de JavaScript o los URI de redireccionamiento.
Para descargar los detalles del cliente, haz clic en el botón Descargar JSON. Cambia el nombre de este archivo a client_secrets.json
. Este archivo se usará más adelante con fines de autenticación.
Crea un objeto de servicio de Tag Manager
El objeto service
de Tag Manager es lo que usarás para realizar solicitudes a la API.
Los pasos necesarios para crear un objeto de servicio de Tag Manager son los siguientes:
- Autorice el acceso a una cuenta de Google Tag Manager.
- Crea una instancia del objeto de servicio de Tag Manager.
Cómo autorizar el acceso a una cuenta de Google Tag Manager
Cuando un usuario inicia una aplicación compilada con la API de Google Tag Manager, debe otorgarle acceso a su cuenta de Google Tag Manager. Este proceso se llama autorización. El método recomendado para autorizar a los usuarios es OAuth 2.0. Si desea obtener más información, consulte el artículo Autorización de la API de Tag Manager.
El siguiente código usa los detalles del proyecto y el cliente que se crearon más arriba para autenticar al usuario de la aplicación y solicita su permiso para acceder a Google Tag Manager en su nombre.
La aplicación intentará abrir el navegador predeterminado y navegar al usuario a una URL alojada en google.com. Se le pedirá al usuario que acceda y le otorgue a la aplicación acceso a su cuenta de Tag Manager. Una vez otorgada, la aplicación intentará leer un código desde la ventana del navegador y luego cerrarla.
Nota: Si se produce un error, la aplicación le pedirá al usuario que ingrese su código de autorización en la línea de comandos.
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>
Cómo consultar la API de Tag Manager
El objeto de servicio de Tag Manager se puede usar para consultar la API de Tag Manager. Los siguientes pasos son necesarios para implementar el programa de muestra:
- Recupera el contenedor Greetings
- Cree la etiqueta de Universal Analytics
- Cree el activador para activar la etiqueta
- Actualiza la etiqueta para que se active en el activador
1. Recupera el contenedor Greetings.
La siguiente función ilustra cómo un objeto de servicio de Tag Manager se puede usar para consultar la API de Tag Manager a fin de enumerar todos los contenedores de una cuenta y recuperar el contenedor llamado 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.'); }); }
A continuación, actualiza la rama de ejecución principal del programa para llamar a la función findGreetingsContainer
con un accountId
de Tag Manager. Por ejemplo:
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. Crea un lugar de trabajo nuevo
En el siguiente fragmento de código, se usa la API de Tag Manager a fin de crear un nuevo lugar de trabajo, que usamos para administrar los cambios en los activadores y las etiquetas. Puedes revisar la referencia del método de creación del lugar de trabajo para ver la lista de propiedades opcionales y obligatorias que se pueden establecer cuando se crea un lugar de trabajo.
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. Cree la etiqueta de Universal Analytics
En el siguiente fragmento de código, se usa la API de Tag Manager para crear una etiqueta de Universal Analytics. Puedes revisar la referencia del método de creación de etiquetas a fin de obtener la lista de propiedades obligatorias y opcionales que se pueden establecer cuando creas una etiqueta, y la referencia del diccionario de etiquetas, que incluye una lista de propiedades para cada tipo de etiqueta.
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. Cree el activador para activar la etiqueta
Ahora que se creó una etiqueta, el siguiente paso es crear un activador que se activará en cualquier página.
El activador se llamará Hello World Trigger y se activará para cualquier página vista. Por ejemplo:
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. Actualiza la etiqueta para que se active en el activador
Ahora que se crearon una etiqueta y un activador, deben asociarse entre sí. Para ello, agrega triggerId
a la lista de firingTriggerIds
asociada con la etiqueta. Por ejemplo:
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); }
A continuación, actualiza la rama de ejecución principal del programa para llamar a las funciones create y update. Por ejemplo:
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(); }); }
Ejemplo completo
Expande esta sección para ver el ejemplo de código completo de todos los pasos de la guía.
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>
Próximos pasos
Ahora que estás familiarizado con el funcionamiento de la API, existen algunos recursos adicionales para ti:
- Referencia de la API: obtén información sobre la interfaz de la API y las operaciones compatibles.
- Referencia de parámetros: Obtén información sobre cómo configurar parámetros para etiquetas y variables.
- Revisa la referencia del diccionario de etiquetas para obtener una lista de las etiquetas admitidas.
- Revisa la Referencia de diccionario de variables para obtener una lista de las variables que se pueden configurar.