En esta guía para desarrolladores se indican los pasos necesarios para ver, crear y gestionar entidades de cuentas de Google Tag Manager a través de la API de Tag Manager v2.
Introducción
Esta guía indica cómo acceder a una cuenta de Google Tag Manager y configurarla. Al finalizar, tendrás conocimientos básicos sobre cómo hacer lo siguiente:
- Crear un objeto de servicio de Tag Manager.
- Autenticar y autorizar a un usuario.
- Usar la API de Tag Manager para acceder a recursos y gestionarlos.
Antes de empezar
Antes de empezar con la guía, te recomendamos que visites el Centro de Ayuda de Google Tag Manager para familiarizarte con esta solución.
Usar una cuenta de prueba
Si quieres usar la API de Tag Manager para crear, configurar o eliminar entidades, te recomendamos que implementes y verifiques tu código con una cuenta de prueba. Así evitarás modificar accidentalmente tus cuentas activas. Después de haber probado y confirmado que tu código funciona del modo previsto con la cuenta de prueba, puedes implementarlo en las cuentas reales.
Elegir un lenguaje
Selecciona el lenguaje de programación que quieras usar. Consulta los siguientes ejemplos:
Python
En todos los fragmentos de código de esta guía se utiliza Python.
JavaScript
En todos los fragmentos de código de esta guía se utiliza JavaScript.
Descripción general del programa
El programa de ejemplo incluido en esta guía es una aplicación de línea de comandos. A partir de un ID de cuenta, la aplicación encuentra un contenedor llamado Saludos y crea una etiqueta de Universal Analytics dentro de él. 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 el entorno de desarrollo y el proyecto en la consola de APIs de Google.
- Crea un objeto de servicio de Tag Manager.
- Autoriza el acceso a una cuenta de Tag Manager.
- Crea un objeto de servicio de Tag Manager.
- Consulta la API, gestiona la respuesta y envía los resultados
- Obtén un objeto de servicio de Tag Manager inicializado.
- Usa el objeto de servicio de Tag Manager para consultar la API de Tag Manager a la hora de hacer las siguientes tareas:
- Recuperar el contenedor de Saludos de la cuenta de Google Tag Manager autenticada.
- Crear un área de trabajo.
- Crear la etiqueta de Universal Analytics.
- Crear el activador de la etiqueta.
- Actualizar la etiqueta para que la ejecute el activador.
Configurar el entorno de desarrollo y el proyecto
Crear el contenedor Saludos
En esta guía se da por hecho que tienes una cuenta de Google Tag Manager con un contenedor llamado Saludos. Sigue las instrucciones que se indican en el artículo Configurar e instalar Tag Manager para crear una cuenta y un contenedor llamado Saludos.
Instalar una biblioteca de cliente
Antes de empezar, instala y configura una biblioteca de cliente de las API de Google.
Crear y configurar un proyecto en la consola de APIs de Google
Para empezar a usar la API de Tag Manager, primero debes utilizar la herramienta de configuración, que te guiará por los pasos necesarios para crear un proyecto en la consola de APIs de Google, habilitar la API y crear las credenciales.
Esta guía usa un flujo de autenticación de aplicación instalada. Sigue las instrucciones que se indican más abajo para crear las credenciales del proyecto. Cuando se te solicite, selecciona el Installed Application
Installed Application y el Other
Other.
- En la página Credenciales, haz clic en Crear credenciales > ID de cliente de OAuth para crear tus credenciales de OAuth 2.0 o en Crear credenciales> Clave de cuenta de servicio para crear una cuenta de servicio.
- Si has creado un ID de cliente de OAuth, selecciona el tipo de aplicación.
- Rellena el formulario y haz clic en Crear.
Las claves de la cuenta de servicio y los ID de cliente de la aplicación se mostrarán en la página Credenciales. Para obtener más detalles, haz clic en un ID de cliente; los parámetros variarán según el tipo de ID, pero podrían incluir la dirección de correo electrónico, el secreto de cliente, los orígenes de JavaScript y las URI de redirección.
Descarga los detalles del cliente haciendo clic en el botón Descargar JSON. Cambia el nombre de este archivo a client_secrets.json
. Este archivo se utilizará más tarde durante la autenticación.
Crear un objeto de servicio de Tag Manager
Deberás usar el objeto service
de Tag Manager para hacer solicitudes a API.
Sigue estos pasos para crear un objeto de servicio de Tag Manager:
- Autoriza el acceso a una cuenta de Google Tag Manager.
- Crea una instancia del objeto de servicio de Tag Manager.
Autorizar el acceso a una cuenta de Google Tag Manager
Cuando un usuario inicie una aplicación creada con la API de Google Tag Manager, deberá darle 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 quieres obtener más información, consulta el artículo Configurar e instalar Tag Manager.
El código que aparece más abajo utiliza los detalles del proyecto y del cliente creados más arriba para autenticar al usuario de la aplicación y le pide permiso para acceder a Google Tag Manager en su nombre.
La aplicación intentará abrir el navegador predeterminado y mostrar al usuario una URL alojada en google.com. Se le pedirá que inicie sesión y que permita a la aplicación acceder a su cuenta de Tag Manager. Una vez concedido, la aplicación intentará leer un código de la ventana del navegador y, a continuación, la cerrará.
Nota: Si se produce algún error, la aplicación solicitará al usuario que introduzca 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>
Enviar consultas a la API de Tag Manager
El objeto de servicio de Tag Manager se puede utilizar para enviar consultas a la API de Tag Manager. Para implementar el programa de ejemplo, sigue estos pasos:
- Recupera el contenedor Saludos.
- Crea la etiqueta de Universal Analytics.
- Crea el activador de la etiqueta.
- Actualiza la etiqueta para que la ejecute el activador.
1. Recuperar el contenedor Saludos
La siguiente función indica cómo se puede usar un objeto de servicio de Tag Manager para solicitar a la API de Tag Manager una lista que contenga todos los contenedores de una cuenta y recuperar el contenedor llamado Saludos.
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 parte de ejecución principal del programa para que llame a la función findGreetingsContainer
a partir de 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. Crear un área de trabajo
El siguiente fragmento de código usa la API de Tag Manager para crear un área de trabajo que permite modificar los activadores y las etiquetas. Consulta la referencia del método de creación de áreas de trabajo si quieres ver la lista de propiedades obligatorias y opcionales que se pueden definir al crear áreas 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. Crear la etiqueta de Universal Analytics
El siguiente fragmento de código usa la API de Tag Manager para crear una etiqueta de Universal Analytics. Consulta la referencia del método de creación de etiquetas si quieres ver la lista de propiedades obligatorias y opcionales que se pueden definir al crear etiquetas y la referencia del diccionario del recurso Tag si quieres ver una lista de propiedades de 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. Crear el activador de la etiqueta
Ahora que has creado una etiqueta, el siguiente paso es crear un activador que la ejecute en cualquier página.
El activador se llamará Hello World Trigger y ejecutará la etiqueta en cualquier vista de página. 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. Actualizar la etiqueta para que la ejecute el activador
Ahora que se han creado una etiqueta y un activador, es necesario asociarlos entre sí. Para hacerlo, añade el triggerId
a la lista de firingTriggerIds
asociados 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 parte de ejecución principal del programa para llamar a las funciones de creación y actualización. 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
Abre 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>
Pasos siguientes
Ahora que ya sabes cómo funciona la API, puedes consultar estos recursos adicionales:
- Referencia de la API: obtén información sobre la interfaz de la API y las operaciones admitidas.
- Referencia de parámetros: obtén información sobre cómo configurar parámetros de las etiquetas y las variables.
- Revisa la referencia del diccionario del recurso Tag para ver la lista de etiquetas admitidas.
- Revisa la referencia del diccionario del recurso Variable para ver la lista de las variables que se pueden configurar.