במדריך למפתחים הזה מוסבר איך לגשת לישויות בחשבון Google Tag Manager, ליצור אותן ולנהל אותן באמצעות Tag Manager API v2.
מבוא
במדריך הזה מוסבר איך לגשת לחשבון Google Tag Manager ולהגדיר אותו. בסיום הקורס תהיה לכם הבנה בסיסית של הפעולות הבאות:
- יוצרים אובייקט שירות של Tag Manager.
- אימות והרשאה של משתמש.
- אפשר להשתמש ב-Tag Manager API כדי לגשת למשאבים ולנהל אותם.
לפני שמתחילים
לפני שמתחילים להשתמש במדריך, מומלץ לעיין במרכז העזרה של Google Tag Manager כדי להכיר את הפלטפורמה.
שימוש בחשבון בדיקה
אם אתם מתכוונים להשתמש ב-Tag Manager API כדי ליצור, להגדיר או למחוק ישויות, מומלץ להטמיע את הקוד ולבדוק אותו באמצעות חשבון בדיקה. שימוש בחשבון בדיקה יעזור לכם להימנע מביצוע שינויים לא מכוונים בחשבון פעיל. אחרי שתבדקו ותאשרו שהקוד פועל כמצופה באמצעות חשבון הבדיקה, תוכלו להתחיל להשתמש בהטמעה עם החשבונות האמיתיים שלכם.
בחירת שפה
בוחרים את שפת התכנות שבה רוצים להשתמש בדוגמאות:
Python
השפה Python נבחרה לכל קטעי הקוד במדריך הזה.
JavaScript
במדריך הזה, JavaScript נבחר לכל קטעי הקוד.
סקירה כללית של התוכנית
תוכנית הדוגמה שכלולה במדריך הזה היא אפליקציה של שורת פקודה. בהינתן מזהה חשבון, האפליקציה מוצאת מאגר תגים בשם Greetings ויוצרת תג Universal Analytics במאגר התגים הזה. כשמשתמש מבקר בדף hello-world.html, התג שולח היט מסוג צפייה בדף.
כדי לפתח את האפליקציה הזו, צריך לפעול לפי השלבים הבאים:
- מגדירים את סביבת הפיתוח ואת הפרויקט ב-Google API Console.
- יוצרים אובייקט שירות של Tag Manager.
- מאשרים גישה לחשבון Tag Manager.
- יוצרים אובייקט שירות של Tag Manager.
- שליחת שאילתה ל-API, טיפול בתגובה והצגת התוצאות.
- קבלת אובייקט שירות מאותחל של Tag Manager.
- משתמשים באובייקט השירות Tag Manager כדי לשלוח שאילתה ל-Tag Manager API ולבצע את המשימות הבאות:
- מאחזרים את מאגר התגים Greetings עבור חשבון Google Tag Manager מאומת.
- יוצרים סביבת עבודה חדשה.
- יוצרים את תג Universal Analytics.
- יוצרים את הטריגר להפעלת התג.
- מעדכנים את התג כך שיופעל בטריגר.
הגדרת סביבת הפיתוח והפרויקט
יצירת מאגר התגים Greetings
במדריך הזה אנחנו מניחים שיש לכם חשבון Google Tag Manager עם מאגר תגים בשם Greetings. פועלים לפי ההוראות שבקטע הגדרה ותהליך עבודה (אינטרנט) כדי ליצור חשבון ומאגר תגים בשם Greetings.
התקנה של ספריית לקוח
לפני שמתחילים, צריך להתקין ולהגדיר ספריית לקוח של Google APIs.
יצירה והגדרה של פרויקט ב-Google API Console
כדי להתחיל להשתמש ב-Tag Manager API, קודם צריך להשתמש בכלי ההגדרה, שמדריך אתכם בתהליך של יצירת פרויקט ב-Google API Console והפעלת ה-API.
במדריך הזה נשתמש בתהליך אימות של אפליקציה מותקנת. כדי ליצור את פרטי הכניסה לפרויקט, פועלים לפי ההוראות הבאות. כשמוצגת בקשה, בוחרים באפשרות Installed Application בשדה סוג האפליקציה ובאפשרות Other בשדה סוג האפליקציה המותקנת.
- בדף Credentials (פרטי כניסה), לוחצים על Create credentials > OAuth client ID (יצירת פרטי כניסה > מזהה לקוח OAuth) כדי ליצור פרטי כניסה מסוג OAuth 2.0, או על Create credentials > Service account key (יצירת פרטי כניסה > מפתח לחשבון שירות) כדי ליצור חשבון שירות.
- אם יצרתם מזהה לקוח OAuth, בוחרים את סוג האפליקציה.
- ממלאים את הטופס ולוחצים על יצירה.
מזהי הלקוח ומפתחות חשבון השירות של האפליקציה מופיעים עכשיו בדף Credentials (פרטי כניסה). כדי לראות פרטים, לוחצים על מזהה לקוח. הפרמטרים משתנים בהתאם לסוג המזהה, אבל יכולים לכלול כתובת אימייל, סוד לקוח, מקורות JavaScript או כתובות URI להפניה אוטומטית.
מורידים את פרטי הלקוח בלחיצה על הלחצן Download JSON. שינוי השם של הקובץ הזה ל-client_secrets.json. הקובץ הזה ישמש בהמשך למטרות אימות.
יצירת אובייקט שירות של Tag Manager
אובייקט service של Tag Manager הוא מה שתשתמשו בו כדי לשלוח בקשות API.
כדי ליצור אובייקט שירות של Tag Manager:
- מאשרים גישה לחשבון Google Tag Manager.
- יוצרים מופע של אובייקט השירות Tag Manager.
איך מאשרים גישה לחשבון Google Tag Manager
כשמשתמש מפעיל אפליקציה שנבנתה באמצעות Google Tag Manager API, הוא צריך להעניק לאפליקציה גישה לחשבון שלו ב-Google Tag Manager. התהליך הזה נקרא אישור. השיטה המומלצת לאישור משתמשים היא OAuth 2.0. מידע נוסף זמין במאמר הרשאה לשימוש ב-Tag Manager API.
הקוד שבהמשך משתמש בפרטי הפרויקט והלקוח שנוצרו למעלה כדי לאמת את המשתמש באפליקציה ולבקש ממנו הרשאה לגשת ל-Google Tag Manager בשמו.
האפליקציה תנסה לפתוח את דפדפן ברירת המחדל ולהפנות את המשתמש לכתובת URL שמתארחת ב-google.com. המשתמש יתבקש להיכנס ולתת לאפליקציה גישה לחשבון Tag Manager שלו. אחרי שמאשרים את ההרשאה, האפליקציה מנסה לקרוא קוד מחלון הדפדפן ואז לסגור את החלון.
הערה: אם מתרחשת שגיאה, האפליקציה תבקש מהמשתמש להזין את קוד ההרשאה בשורת הפקודה.
Python
"""Access and manage a Google Tag Manager account.""" import argparse import sys import httplib2 from apiclient.discovery import build from oauth2client import client from oauth2client import file from oauth2client import tools def GetService(api_name, api_version, scope, client_secrets_path): """Get a service that communicates to a Google API. Args: api_name: string The name of the api to connect to. api_version: string The api version to connect to. scope: A list of strings representing the auth scopes to authorize for the connection. client_secrets_path: string A path to a valid client secrets file. Returns: A service that is connected to the specified API. """ # Parse command-line arguments. parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args([]) # Set up a Flow object to be used if we need to authenticate. flow = client.flow_from_clientsecrets( client_secrets_path, scope=scope, message=tools.message_if_missing(client_secrets_path)) # Prepare credentials, and authorize HTTP object with them. # If the credentials don't exist or are invalid run through the native client # flow. The Storage object will ensure that if successful the good # credentials will get written back to a file. storage = file.Storage(api_name + '.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) http = credentials.authorize(http=httplib2.Http()) # Build the service object. service = build(api_name, api_version, http=http) return service def main(argv): # Define the auth scopes to request. scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers'] # Authenticate and construct service. service = GetService('tagmanager', 'v2', scope, 'client_secrets.json') if __name__ == '__main__': main(sys.argv)
JavaScript
<html> <head> <script type="text/javascript"> // Your Client ID can be retrieved from your project in the Google // Developer Console, https://console.developers.google.com var CLIENT_ID = TODO; var SCOPES = [ 'https://www.googleapis.com/auth/tagmanager.manage.accounts', 'https://www.googleapis.com/auth/tagmanager.edit.containers', 'https://www.googleapis.com/auth/tagmanager.delete.containers', 'https://www.googleapis.com/auth/tagmanager.edit.containerversions', 'https://www.googleapis.com/auth/tagmanager.manage.users', 'https://www.googleapis.com/auth/tagmanager.publish' ]; // Parameter values used by the script ACCOUNT_PATH = TODO; // such as: 'accounts/555555'; CONTAINER_NAME = 'Greetings'; WORKSPACE_NAME = 'Example workspace'; /** * Check if current user has authorization for this application. * * @param {bool} immediate Whether login should use the "immediate mode", which * causes the security token to be refreshed behind the scenes with no UI. */ function checkAuth(immediate) { var authorizeCheckPromise = new Promise((resolve) => { gapi.auth.authorize( { client_id: CLIENT_ID, scope: SCOPES.join(' '), immediate: immediate }, resolve); }); authorizeCheckPromise .then(handleAuthResult) .then(loadTagManagerApi) .then(runTagManagerExample) .catch(() => { console.log('You must authorize any access to the api.'); }); } /** * Check if current user has authorization for this application. */ function checkAuth() { checkAuth(true); } /** * Initiate auth flow in response to user clicking authorize button. * * @param {Event} event Button click event. * @return {boolean} Returns false. */ function handleAuthClick(event) { checkAuth(); return false; } /** * Handle response from authorization server. * * @param {Object} authResult Authorization result. * @return {Promise} A promise to call resolve if authorize or redirect to a * login flow. */ function handleAuthResult(authResult) { return new Promise((resolve, reject) => { var authorizeDiv = document.getElementById('authorize-div'); if (authResult && !authResult.error) { // Hide auth UI, then load client library. authorizeDiv.style.display = 'none'; resolve(); } else { // Show auth UI, allowing the user to initiate authorization by // clicking authorize button. authorizeDiv.style.display = 'inline'; reject(); } }); } /** * Load Tag Manager API client library. * * @return {Promise} A promise the load the Tag Manager API library. */ function loadTagManagerApi() { return new Promise((resolve, reject) => { console.log('Load Tag Manager api'); gapi.client.load('tagmanager', 'v2', resolve); }); } /** * Interacts with the tagmanager api v2 to create a container, workspace, * trigger, and tag. * * @return {Promise} A promise to run the Tag Manager example. */ function runTagManagerExample() { return new Promise((resolve, reject) => { console.log('Running Tag Manager Example.'); resolve(); }); } /** * Logs an error message to the console. * * @param {string|Object} error The error to log to the console. */ function handleError(error) { console.log('Error when interacting with GTM API'); console.log(error); } /** * Wraps an API request into a promise. * * @param {Object} a request to the API. * @return {Promise} A promise to execute the API request. */ function requestPromise(request) { return new Promise((resolve, reject) => { request.execute((response) => { if (response.code) { reject(response); } resolve(response); }); }); } </script> <script src="https://apis.google.com/js/client.js?onload=checkAuth"> </script> </head> <body> <div id="authorize-div" style="display: none"> <span>Authorize access to Tag Manager API</span> <!--Button for the user to click to initiate auth sequence --> <button id="authorize-button" onclick="handleAuthClick(event)"> Authorize </button> </div> <pre id="output"></pre> </body> </html>
שליחת שאילתה אל Tag Manager API
אפשר להשתמש באובייקט השירות Tag Manager כדי לשלוח שאילתות ל-Tag Manager API. כדי להטמיע את תוכנית הדוגמה, צריך לבצע את השלבים הבאים:
- אחזור מאגר הודעות הפתיחה
- יצירת תג Universal Analytics
- יצירת הטריגר להפעלת התג
- מעדכנים את התג כך שיופעל בטריגר
1. אחזור הקונטיינר Greetings
הפונקציה הבאה ממחישה איך אפשר להשתמש באובייקט שירות של Tag Manager כדי לשלוח שאילתה ל-Tag Manager API ולקבל רשימה של כל מאגרי התגים בחשבון, וגם לאחזר את מאגר התגים שנקרא Greetings.
Python
def FindGreetingsContainer(service, account_path): """Find the greetings container. Args: service: the Tag Manager service object. account_path: the path of the Tag Manager account from which to retrieve the Greetings container. Returns: The greetings container if it exists, or None if it does not. """ # Query the Tag Manager API to list all containers for the given account. container_wrapper = service.accounts().containers().list( parent=account_path).execute() # Find and return the Greetings container if it exists. for container in container_wrapper['container']: if container['name'] == 'Greetings': return container return None
JavaScript
/** * Returns the greetings container if it exists. * * @param {string} accountPath The account which contains the Greetings * container. * @return {Promise} A promise to find the greetings container. */ function findContainer(accountPath, containerName) { console.log('Finding container in account:' + accountPath); var request = gapi.client.tagmanager.accounts.containers.list({ 'parent': accountPath }); return requestPromise(request) .then((response) => { var containers = response.container || []; var container = containers.find((container) => container.name === containerName); return container || Promise.reject('Unable to find ' + containerName +' container.'); }); }
לאחר מכן מעדכנים את ענף הביצוע הראשי של התוכנית כדי לקרוא לפונקציה findGreetingsContainer בהינתן Tag Manager accountId. לדוגמה:
Python
def main(argv): # Get tag manager account ID from command line. assert len(argv) == 2 and 'usage: gtm-api-hello-world.py <account_id>' account_id = str(argv[1]) account_path = 'accounts/%s' % account_id # Define the auth scopes to request. scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers'] # Authenticate and construct service. service = GetService('tagmanager', 'v2', scope, 'client_secrets.json') # Find the greetings container. container = FindGreetingsContainer(service, account_path) if __name__ == '__main__': main(sys.argv)
JavaScript
/** * Interacts with the tagmanager api v2 to create a container, workspace, * trigger, and tag. * * @return {Promise} A promise to run the tag manager example. */ function runTagManagerExample() { return new Promise((resolve, reject) => { console.log('Running Tag Manager Example.'); var trigger = null; var workspace = null; findContainer(ACCOUNT_PATH, CONTAINER_NAME) .catch(handleError); resolve(); }); }
2. יצירת סביבת עבודה חדשה
קטע הקוד הבא משתמש ב-Tag Manager API כדי ליצור סביבת עבודה חדשה, שבה אנחנו משתמשים כדי לנהל את השינויים בטריגרים ובתגים. במאמר הזה מפורטות כל המאפיינים הנדרשים והאופציונליים שאפשר להגדיר כשיוצרים סביבת עבודה.
Python
def CreateWorkspace(service, container): """Creates a workspace named 'my workspace'. Args: service: the Tag Manager service object. container: the container to insert the workspace within. Returns: The created workspace. """ return service.accounts().containers().workspaces().create( parent=container['path'], body={ 'name': 'my workspace', }).execute()
JavaScript
/** * Creates a workspace in the Greetings container. * * @param {Object} container The container to create a new workspace. * @return {Promise} A promise to create a workspace. */ function createWorkspace(container) { console.log('Creating workspace in container:' + container.path); var request = gapi.client.tagmanager.accounts.containers.workspaces.create( { 'parent': container.path }, { name: WORKSPACE_NAME, description: 'my workspace created via api' }); return requestPromise(request); }
3. יצירת תג Universal Analytics
בקטע הקוד הבא נעשה שימוש ב-Tag Manager API כדי ליצור תג Universal Analytics. אפשר לעיין בהפניה לשיטת יצירת תגים כדי לראות את רשימת המאפיינים הנדרשים והאופציונליים שאפשר להגדיר כשיוצרים תג, ובהפניה למילון התגים כדי לראות את רשימת המאפיינים של כל סוג תג.
Python
def CreateHelloWorldTag(service, workspace, tracking_id): """Create the Universal Analytics Hello World Tag. Args: service: the Tag Manager service object. workspace: the workspace to create a tag within. tracking_id: the Universal Analytics tracking ID to use. Returns: The created tag. """ hello_world_tag = { 'name': 'Universal Analytics Hello World', 'type': 'ua', 'parameter': [{ 'key': 'trackingId', 'type': 'template', 'value': str(tracking_id), }], } return service.accounts().containers().workspaces().tags().create( parent=workspace['path'], body=hello_world_tag).execute()
JavaScript
/** * Creates a universal analytics tag. * * @param {Object} workspace The workspace to create the tag * @return {Promise} A promise to create a hello world tag. */ function createHelloWorldTag(workspace) { console.log('Creating hello world tag'); var helloWorldTag = { 'name': 'Universal Analytics Hello World', 'type': 'ua', 'parameter': [{ 'key': 'trackingId', 'type': 'template', 'value': 'UA-1234-5' }], }; var request = gapi.client.tagmanager.accounts.containers.workspaces.tags.create( { 'parent': workspace.path }, helloWorldTag); return requestPromise(request); }
4. יצירת הטריגר להפעלת התג
אחרי שיצרתם תג, השלב הבא הוא ליצור טריגר שיופעל בכל דף.
הטריגר ייקרא Hello World Trigger והוא יופעל בכל צפייה בדף. לדוגמה:
Python
def CreateHelloWorldTrigger(service, workspace): """Create the Hello World Trigger. Args: service: the Tag Manager service object. workspace: the workspace to create the trigger within. Returns: The created trigger. """ hello_world_trigger = { 'name': 'Hello World Rule', 'type': 'PAGEVIEW' } return service.accounts().containers().workspaces().triggers().create( parent=workspace['path'], body=hello_world_trigger).execute()
JavaScript
/** * Creates a page view trigger. * * @param {Object} workspace The workspace to create the trigger in. * @return {Promise} A promise to create a page view trigger. */ function createHelloWorldTrigger(workspace) { console.log('Creating hello world trigger in workspace'); var helloWorldTrigger = { 'name': 'Hello World Trigger', 'type': 'PAGEVIEW' }; var request = gapi.client.tagmanager.accounts.containers.workspaces.triggers.create( { 'parent': workspace.path }, helloWorldTrigger); return requestPromise(request); }
5. מעדכנים את התג כך שיופעל בטריגר
אחרי שיצרתם תג וגורם הפעלה, צריך לשייך אותם זה לזה. כדי לעשות את זה, מוסיפים את triggerId לרשימה של firingTriggerIds שמשויכים לתג. לדוגמה:
Python
def UpdateHelloWorldTagWithTrigger(service, tag, trigger): """Update a Tag with a Trigger. Args: service: the Tag Manager service object. tag: the tag to associate with the trigger. trigger: the trigger to associate with the tag. """ # Get the tag to update. tag = service.accounts().containers().workspaces().tags().get( path=tag['path']).execute() # Update the Firing Trigger for the Tag. tag['firingTriggerId'] = [trigger['triggerId']] # Update the Tag. response = service.accounts().containers().workspaces().tags().update( path=tag['path'], body=tag).execute()
JavaScript
/** * Updates a tag to fire on a particular trigger. * * @param {Object} tag The tag to update. * @param {Object} trigger The trigger which causes the tag to fire. * @return {Promise} A promise to update a tag to fire on a particular trigger. */ function updateHelloWorldTagWithTrigger(tag, trigger) { console.log('Update hello world tag with trigger'); tag['firingTriggerId'] = [trigger.triggerId]; var request = gapi.client.tagmanager.accounts.containers.workspaces.tags.update( { 'path': tag.path }, tag); return requestPromise(request); }
לאחר מכן מעדכנים את הענף הראשי של התוכנית כדי לקרוא לפונקציות create ו-update. לדוגמה:
Python
def main(argv): # Get tag manager account ID from command line. assert len(argv) == 2 and 'usage: gtm-api-hello-world.py <account_id>' account_id = str(argv[1]) account_path = 'accounts/%s' % account_id # Define the auth scopes to request. scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers'] # Authenticate and construct service. service = GetService('tagmanager', 'v2', scope, 'client_secrets.json') # Find the greetings container. container = FindGreetingsContainer(service, account_path) # Create a new workspace. workspace = CreateWorkspace(service, container) # Create the hello world tag. tag = CreateHelloWorldTag( service, workspace, 'UA-1234-5') # Create the hello world Trigger. trigger = CreateHelloWorldTrigger( service, workspace) # Update the hello world tag to fire based on the hello world tag. UpdateHelloWorldTagWithTrigger(service, tag, trigger) if __name__ == '__main__': main(sys.argv)
JavaScript
/** * Interacts with the tagmanager api v2 to create a container, workspace, * trigger, and tag. * * @return {Promise} A promise to run the tag manager example. */ function runTagManagerExample() { return new Promise((resolve, reject) => { console.log('Running Tag Manager Example.'); var trigger = null; var workspace = null; findContainer(ACCOUNT_PATH, CONTAINER_NAME) .then(createWorkspace) .then((createdWorkspace) => { workspace = createdWorkspace; return createHelloWorldTrigger(workspace); }) .then((createdTrigger) => { trigger = createdTrigger; return createHelloWorldTag(workspace); }) .then((createdTag) => { return updateHelloWorldTagWithTrigger(createdTag, trigger); }) .catch(handleError); resolve(); }); }
דוגמה מלאה
כדי לראות את דוגמת הקוד המלאה של כל השלבים במדריך, אפשר להרחיב את הקטע הזה.
Python
"""Access and manage a Google Tag Manager account.""" import argparse import sys import httplib2 from apiclient.discovery import build from oauth2client import client from oauth2client import file from oauth2client import tools def GetService(api_name, api_version, scope, client_secrets_path): """Get a service that communicates to a Google API. Args: api_name: string The name of the api to connect to. api_version: string The api version to connect to. scope: A list of strings representing the auth scopes to authorize for the connection. client_secrets_path: string A path to a valid client secrets file. Returns: A service that is connected to the specified API. """ # Parse command-line arguments. parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args([]) # Set up a Flow object to be used if we need to authenticate. flow = client.flow_from_clientsecrets( client_secrets_path, scope=scope, message=tools.message_if_missing(client_secrets_path)) # Prepare credentials, and authorize HTTP object with them. # If the credentials don't exist or are invalid run through the native client # flow. The Storage object will ensure that if successful the good # credentials will get written back to a file. storage = file.Storage(api_name + '.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) http = credentials.authorize(http=httplib2.Http()) # Build the service object. service = build(api_name, api_version, http=http) return service def FindGreetingsContainer(service, account_path): """Find the greetings container. Args: service: the Tag Manager service object. account_path: the path of the Tag Manager account from which to retrieve the Greetings container. Returns: The greetings container if it exists, or None if it does not. """ # Query the Tag Manager API to list all containers for the given account. container_wrapper = service.accounts().containers().list( parent=account_path).execute() # Find and return the Greetings container if it exists. for container in container_wrapper['container']: if container['name'] == 'Greetings': return container return None def CreateWorkspace(service, container): """Creates a workspace named 'my workspace'. Args: service: the Tag Manager service object. container: the container to insert the workspace within. Returns: The created workspace. """ return service.accounts().containers().workspaces().create( parent=container['path'], body={ 'name': 'my workspace', }).execute() def CreateHelloWorldTag(service, workspace, tracking_id): """Create the Universal Analytics Hello World Tag. Args: service: the Tag Manager service object. workspace: the workspace to create a tag within. tracking_id: the Universal Analytics tracking ID to use. Returns: The created tag. """ hello_world_tag = { 'name': 'Universal Analytics Hello World', 'type': 'ua', 'parameter': [{ 'key': 'trackingId', 'type': 'template', 'value': str(tracking_id), }], } return service.accounts().containers().workspaces().tags().create( parent=workspace['path'], body=hello_world_tag).execute() def CreateHelloWorldTrigger(service, workspace): """Create the Hello World Trigger. Args: service: the Tag Manager service object. workspace: the workspace to create the trigger within. Returns: The created trigger. """ hello_world_trigger = { 'name': 'Hello World Rule', 'type': 'PAGEVIEW' } return service.accounts().containers().workspaces().triggers().create( parent=workspace['path'], body=hello_world_trigger).execute() def UpdateHelloWorldTagWithTrigger(service, tag, trigger): """Update a Tag with a Trigger. Args: service: the Tag Manager service object. tag: the tag to associate with the trigger. trigger: the trigger to associate with the tag. """ # Get the tag to update. tag = service.accounts().containers().workspaces().tags().get( path=tag['path']).execute() # Update the Firing Trigger for the Tag. tag['firingTriggerId'] = [trigger['triggerId']] # Update the Tag. response = service.accounts().containers().workspaces().tags().update( path=tag['path'], body=tag).execute() def main(argv): # Get tag manager account ID from command line. assert len(argv) == 2 and 'usage: gtm-api-hello-world.py <account_id>' account_id = str(argv[1]) account_path = 'accounts/%s' % account_id # Define the auth scopes to request. scope = ['https://www.googleapis.com/auth/tagmanager.edit.containers'] # Authenticate and construct service. service = GetService('tagmanager', 'v2', scope, 'client_secrets.json') # Find the greetings container. container = FindGreetingsContainer(service, account_path) # Create a new workspace. workspace = CreateWorkspace(service, container) # Create the hello world tag. tag = CreateHelloWorldTag( service, workspace, 'UA-1234-5') # Create the hello world Trigger. trigger = CreateHelloWorldTrigger( service, workspace) # Update the hello world tag to fire based on the hello world tag. UpdateHelloWorldTagWithTrigger(service, tag, trigger) if __name__ == '__main__': main(sys.argv)
JavaScript
<html> <head> <script type="text/javascript"> // Your Client ID can be retrieved from your project in the Google // Developer Console, https://console.developers.google.com var CLIENT_ID = TODO; var SCOPES = [ 'https://www.googleapis.com/auth/tagmanager.manage.accounts', 'https://www.googleapis.com/auth/tagmanager.edit.containers', 'https://www.googleapis.com/auth/tagmanager.delete.containers', 'https://www.googleapis.com/auth/tagmanager.edit.containerversions', 'https://www.googleapis.com/auth/tagmanager.manage.users', 'https://www.googleapis.com/auth/tagmanager.publish' ]; // Parameter values used by the script ACCOUNT_PATH = TODO; // such as: 'accounts/555555'; CONTAINER_NAME = 'Greetings'; WORKSPACE_NAME = 'Example workspace'; /** * Check if current user has authorization for this application. * * @param {bool} immediate Whether login should use the "immediate mode", * which causes the security token to be refreshed behind the scenes * with no UI. */ function checkAuth(immediate) { var authorizeCheckPromise = new Promise((resolve) => { gapi.auth.authorize( { client_id: CLIENT_ID, scope: SCOPES.join(' '), immediate: immediate }, resolve); }); authorizeCheckPromise .then(handleAuthResult) .then(loadTagManagerApi) .then(runTagManagerExample) .catch(() => { console.log('You must authorize any access to the api.'); }); } /** * Check if current user has authorization for this application. */ function checkAuth() { checkAuth(true); } /** * Initiate auth flow in response to user clicking authorize button. * * @param {Event} event Button click event. * @return {boolean} Returns false. */ function handleAuthClick(event) { checkAuth(); return false; } /** * Handle response from authorization server. * * @param {Object} authResult Authorization result. * @return {Promise} A promise to call resolve if authorize or redirect to a * login flow. */ function handleAuthResult(authResult) { return new Promise((resolve, reject) => { var authorizeDiv = document.getElementById('authorize-div'); if (authResult && !authResult.error) { // Hide auth UI, then load client library. authorizeDiv.style.display = 'none'; resolve(); } else { // Show auth UI, allowing the user to initiate authorization by // clicking authorize button. authorizeDiv.style.display = 'inline'; reject(); } }); } /** * Load Tag Manager API client library. * @return {Promise} A promise to load the tag manager api library. */ function loadTagManagerApi() { return new Promise((resolve, reject) => { console.log('Load Tag Manager api'); gapi.client.load('tagmanager', 'v2', resolve); }); } /** * Interacts with the tagmanager api v2 to create a container, * workspace, trigger, and tag. * * @return {Promise} A promise to run the tag manager example. */ function runTagManagerExample() { return new Promise((resolve, reject) => { console.log('Running Tag Manager Example.'); var trigger = null; var workspace = null; findContainer(ACCOUNT_PATH, CONTAINER_NAME) .then(createWorkspace) .then((createdWorkspace) => { workspace = createdWorkspace; return createHelloWorldTrigger(workspace); }) .then((createdTrigger) => { trigger = createdTrigger; return createHelloWorldTag(workspace); }) .then((createdTag) => { return updateHelloWorldTagWithTrigger(createdTag, trigger); }) .catch(handleError); resolve(); }); } /** * Returns the greetings container if it exists. * * @param {string} accountPath The account which contains the Greetings * container. * @param {string} containerName The name of the container to find. * @return {Promise} A promise to find the greetings container. */ function findContainer(accountPath, containerName) { console.log('Finding container in account:' + accountPath); var request = gapi.client.tagmanager.accounts.containers.list({ 'parent': accountPath }); return requestPromise(request) .then((response) => { var containers = response.container || []; var container = containers.find( (container) => container.name === containerName); return container || Promise.reject( 'Unable to find ' + containerName +' container.'); }); } /** * Creates a workspace in the Greetings container. * * @param {Object} container The container to create a new workspace. * @return {Promise} A promise to create a workspace. */ function createWorkspace(container) { console.log('Creating workspace in container:' + container.path); var request = gapi.client.tagmanager.accounts.containers.workspaces.create( { 'parent': container.path }, { name: WORKSPACE_NAME, description: 'my workspace created via api' }); return requestPromise(request); } /** * Creates a page view trigger. * * @param {Object} workspace The workspace to create the trigger in. * @return {Promise} A promise to create a page view trigger. */ function createHelloWorldTrigger(workspace) { console.log('Creating hello world trigger in workspace'); var helloWorldTrigger = { 'name': 'Hello World Trigger', 'type': 'PAGEVIEW' }; var request = gapi.client.tagmanager.accounts.containers.workspaces.triggers.create( { 'parent': workspace.path }, helloWorldTrigger); return requestPromise(request); } /** * Creates a universal analytics tag. * * @param {Object} workspace The workspace to create the tag * @return {Promise} A promise to create a hello world tag. */ function createHelloWorldTag(workspace) { console.log('Creating hello world tag'); var helloWorldTag = { 'name': 'Universal Analytics Hello World', 'type': 'ua', 'parameter': [{ 'key': 'trackingId', 'type': 'template', 'value': 'UA-1234-5' }], }; var request = gapi.client.tagmanager.accounts.containers.workspaces.tags.create( { 'parent': workspace.path }, helloWorldTag); return requestPromise(request); } /** * Updates a tag to fire on a particular trigger. * * @param {Object} tag The tag to update. * @param {Object} trigger The trigger which causes the tag to fire. * @return {Promise} A promise to update a tag to fire on a particular * trigger. */ function updateHelloWorldTagWithTrigger(tag, trigger) { console.log('Update hello world tag with trigger'); tag['firingTriggerId'] = [trigger.triggerId]; var request = gapi.client.tagmanager.accounts.containers.workspaces.tags.update( { 'path': tag.path }, tag); return requestPromise(request); } /** * Logs an error message to the console. * * @param {string|Object} error The error to log to the console. */ function handleError(error) { console.log('Error when interacting with GTM API'); console.log(error); } /** * Wraps an API request into a promise. * * @param {Object} request the API request. * @return {Promise} A promise to execute the api request. */ function requestPromise(request) { return new Promise((resolve, reject) => { request.execute((response) => { if (response.code) { reject(response); } resolve(response); }); }); } </script> <script src="https://apis.google.com/js/client.js?onload=checkAuth"> </script> </head> <body> <div id="authorize-div" style="display: none"> <span>Authorize access to Tag Manager API</span> <!--Button for the user to click to initiate auth sequence --> <button id="authorize-button" onclick="handleAuthClick(event)"> Authorize </button> </div> <pre id="output"></pre> </body> </html>
השלבים הבאים
אחרי שהבנתם איך ה-API פועל, הנה כמה מקורות מידע נוספים שיכולים לעזור לכם:
- הפניית API – מידע על ממשק ה-API והפעולות הנתמכות.
- הפניה לפרמטרים – מידע על הגדרת פרמטרים לתגים ולמשתנים.
- רשימה של תגים נתמכים מופיעה במילון התגים.
- רשימת המשתנים שאפשר להגדיר מופיעה במילון המשתנים.