Panduan developer ini memandu Anda melalui langkah-langkah yang diperlukan untuk mengakses, membuat, dan mengelola entitas dalam akun Google Tag Manager melalui Tag Manager API v2.
Pengantar
Panduan ini akan menuntun Anda melakukan berbagai langkah untuk mengakses dan mengonfigurasi akun Google Tag Manager. Setelah selesai, Anda akan memiliki pemahaman dasar tentang cara melakukan tugas-tugas berikut:
- Buat objek layanan Tag Manager.
- Mengautentikasi dan memberikan otorisasi kepada pengguna.
- Gunakan Tag Manager API untuk mengakses dan mengelola resource.
Sebelum memulai
Sebelum memulai panduan ini, sebaiknya Anda memahami Google Tag Manager dengan mengunjungi pusat bantuan Google Tag Manager.
Menggunakan akun pengujian
Jika Anda ingin menggunakan Tag Manager API untuk membuat, mengonfigurasi, atau menghapus entity, sebaiknya terapkan dan verifikasi kode Anda dengan akun pengujian. Menggunakan akun pengujian akan membantu mencegah Anda melakukan perubahan yang tidak disengaja pada akun aktif. Setelah menguji dan mengonfirmasi bahwa kode Anda berfungsi seperti yang diharapkan menggunakan akun pengujian, Anda dapat mulai menggunakan implementasi dengan akun Anda yang sebenarnya.
Pilih bahasa
Pilih bahasa pemrograman yang ingin Anda ikuti contohnya:
Python
Python dipilih untuk semua cuplikan kode dalam panduan ini.
JavaScript
JavaScript dipilih untuk semua cuplikan kode dalam panduan ini.
Ringkasan program
Contoh program yang disertakan dalam panduan ini adalah aplikasi command line. Dengan ID akun, aplikasi akan menemukan penampung bernama Salam dan membuat tag Universal Analytics di penampung tersebut. Saat pengguna mengunjungi hello-world.html, tag tersebut mengirim klik kunjungan halaman.
Untuk mengembangkan aplikasi ini, Anda perlu mengikuti langkah-langkah berikut:
- Siapkan lingkungan pengembangan dan project Anda di Konsol API Google.
- Buat objek layanan Tag Manager.
- Mengizinkan akses ke akun Tag Manager.
- Buat objek layanan Tag Manager.
- Membuat kueri API, menangani respons, dan mengeluarkan hasilnya.
- Dapatkan objek layanan Tag Manager yang diinisialisasi.
- Gunakan objek layanan Tag Manager untuk membuat kueri
Tag Manager API guna melakukan tugas berikut:
- Ambil penampung Salam untuk akun Google Tag Manager yang diautentikasi.
- Buat ruang kerja baru.
- Buat tag Universal Analytics.
- Buat pemicu untuk mengaktifkan tag.
- Perbarui tag untuk diaktifkan berdasarkan pemicu.
Menyiapkan lingkungan pengembangan dan project Anda
Buat penampung Salam
Panduan ini mengasumsikan bahwa Anda memiliki akun Google Tag Manager dengan penampung bernama Greetings. Ikuti petunjuk untuk Penyiapan dan Alur Kerja (Web) guna membuat Akun dan Penampung bernama Greetings.
Menginstal library klien
Sebelum memulai, instal dan konfigurasi library klien Google API.
Membuat dan mengonfigurasi project di Konsol API Google
Untuk mulai menggunakan Tag Manager API, Anda harus terlebih dahulu menggunakan alat penyiapan, yang memandu Anda menyelesaikan pembuatan project di Konsol API Google, mengaktifkan API, dan membuat kredensial.
Panduan ini menggunakan alur autentikasi Aplikasi Terinstal. Ikuti petunjuk di bawah ini untuk membuat kredensial project Anda. Saat diminta, pilih Installed Application
untuk APPLICATION
TYPE dan Other
untuk INSTALLED APPLICATION
TYPE.
- Dari halaman Kredensial, klik Create credentials > OAuth client ID untuk membuat kredensial OAuth 2.0 Anda, atau Create credentials > Service account key untuk membuat akun layanan.
- Jika Anda membuat client ID OAuth, pilih jenis aplikasi Anda.
- Isi formulir lalu klik Buat.
Client ID dan kunci akun layanan aplikasi Anda kini tercantum di halaman Kredensial. Untuk mengetahui detailnya, klik client ID; parameternya bervariasi bergantung pada jenis ID, tetapi dapat mencakup alamat email, rahasia klien, asal JavaScript, atau URI pengalihan.
Download detail klien dengan mengklik tombol Download JSON. Ganti nama file ini menjadi client_secrets.json
. File ini akan
digunakan nanti untuk tujuan autentikasi.
Membuat objek layanan Tag Manager
Objek service
Tag Manager adalah yang akan Anda gunakan untuk membuat permintaan API.
Langkah-langkah yang diperlukan untuk membuat objek layanan Tag Manager adalah sebagai berikut:
- Mengizinkan akses ke akun Google Tag Manager.
- Buat instance objek layanan Tag Manager.
Mengizinkan akses ke akun Google Tag Manager
Saat pengguna memulai aplikasi yang dibuat dengan Google Tag Manager API, mereka harus memberi aplikasi akses ke akun Google Tag Manager miliknya. Proses ini disebut otorisasi. Metode yang direkomendasikan untuk memberi otorisasi kepada pengguna adalah OAuth 2.0. Jika Anda ingin mempelajari lebih lanjut, baca Otorisasi API Tag Manager.
Kode di bawah ini menggunakan detail project dan klien yang dibuat di atas untuk mengautentikasi pengguna aplikasi dan meminta izin mereka untuk mengakses Google Tag Manager atas nama mereka.
Aplikasi akan mencoba membuka browser default dan mengarahkan pengguna ke URL yang dihosting di google.com. Pengguna akan diminta untuk login dan memberi aplikasi akses ke akun Tag Manager mereka. Setelah diberikan, aplikasi akan mencoba membaca kode dari jendela browser, lalu menutup jendela tersebut.
Catatan: Jika terjadi error, aplikasi akan meminta pengguna untuk memasukkan kode otorisasi pada command line.
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>
Membuat kueri Tag Manager API
Objek layanan Tag Manager dapat digunakan untuk membuat kueri Tag Manager API. Langkah-langkah berikut diperlukan untuk menerapkan program contoh:
- Mengambil penampung Salam
- Membuat tag Universal Analytics
- Buat pemicu untuk mengaktifkan tag
- Perbarui tag untuk diaktifkan berdasarkan pemicu
1. Mengambil penampung Greetings
Fungsi berikut menggambarkan cara objek layanan Tag Manager dapat digunakan untuk membuat kueri Tag Manager API guna mencantumkan semua penampung akun dan mengambil penampung bernama 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.'); }); }
Selanjutnya, perbarui cabang eksekusi utama program untuk memanggil fungsi findGreetingsContainer
dengan accountId
Tag Manager. Contoh:
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. Buat Ruang Kerja Baru
Cuplikan kode berikut menggunakan Tag Manager API untuk membuat ruang kerja baru, yang akan kita gunakan untuk mengelola perubahan pada pemicu dan tag. Anda dapat meninjau referensi metode pembuatan Workspace untuk mengetahui daftar properti wajib dan opsional yang dapat ditetapkan saat membuat ruang kerja.
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. Membuat tag Universal Analytics
Cuplikan kode berikut menggunakan Tag Manager API untuk membuat tag Universal Analytics. Anda dapat meninjau Referensi metode pembuatan tag untuk daftar properti wajib dan opsional yang dapat ditetapkan saat membuat tag dan Referensi Kamus Tag untuk daftar properti setiap jenis tag.
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. Buat pemicu untuk mengaktifkan tag
Setelah tag dibuat, langkah berikutnya adalah membuat Pemicu yang akan diaktifkan di halaman mana pun.
Pemicu akan diberi nama Pemicu Halo Dunia dan akan diaktifkan untuk setiap kunjungan halaman. Contoh:
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. Perbarui tag untuk diaktifkan berdasarkan pemicu
Setelah dibuat, tag dan pemicu harus dikaitkan satu sama lain. Untuk melakukannya, tambahkan triggerId
ke daftar
firingTriggerIds
yang terkait dengan tag. Contoh:
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); }
Selanjutnya, update cabang eksekusi utama program untuk memanggil fungsi buat dan perbarui. Contoh:
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(); }); }
Contoh Lengkap
Luaskan bagian ini untuk melihat contoh kode lengkap dari semua langkah dalam panduan.
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>
Langkah Berikutnya
Setelah memahami cara kerja API, ada beberapa referensi tambahan untuk Anda:
- Referensi API – pelajari antarmuka API dan operasi yang didukung.
- Referensi Parameter – pelajari cara menetapkan parameter untuk tag dan variabel.
- Tinjau Referensi Kamus Tag untuk melihat daftar tag yang didukung.
- Tinjau Referensi Kamus Variabel untuk melihat daftar Variabel yang dapat dikonfigurasi.