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 memandu Anda melalui berbagai langkah untuk mengakses dan mengonfigurasi Akun Tag Manager. Setelah menyelesaikan materi ini, Anda akan memiliki pemahaman dasar tentang bagaimana untuk melakukan tugas berikut:
- Buat objek layanan Tag Manager.
- Mengautentikasi dan memberi otorisasi kepada pengguna.
- Menggunakan Tag Manager API untuk mengakses dan mengelola resource.
Sebelum memulai
Sebelum memulai panduan, 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 Google, sebaiknya terapkan dan verifikasi kode Anda dengan menggunakan akun layanan. Menggunakan akun pengujian akan membantu mencegah Anda melakukan perubahan pada akun yang aktif. Setelah Anda menguji dan mengonfirmasi bahwa kode telah berfungsi seperti yang diharapkan dengan akun pengujian, maka Anda dapat mulai menggunakan penerapan dengan akun Anda yang sebenarnya.
Pilih bahasa
Pilih bahasa pemrograman yang ingin Anda gunakan contohnya:
Python
Python dipilih untuk semua cuplikan kode di kami.
JavaScript
JavaScript dipilih untuk semua cuplikan kode di kami.
Ringkasan program
Program contoh yang disertakan dalam panduan ini adalah aplikasi baris perintah. Jika ID akun, aplikasi akan menemukan penampung bernama Greetings dan membuat dari Universal Analytics di penampung tersebut. Saat pengguna mengunjungi hello-world.html, tag mengirim klik kunjungan halaman.
Untuk mengembangkan aplikasi ini, Anda harus mengikuti langkah-langkah berikut:
- Siapkan lingkungan pengembangan dan project Anda di Konsol API Google.
- Buat objek layanan Tag Manager.
- Izinkan akses ke akun Tag Manager.
- Buat objek layanan Tag Manager.
- Buat kueri API, tangani respons, dan output hasilnya.
- Mendapatkan objek layanan Tag Manager yang diinisialisasi.
- Gunakan objek layanan Tag Manager untuk membuat kueri
API Tag Manager untuk melakukan tugas berikut:
- Ambil penampung Greetings 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 project dan lingkungan pengembangan
Membuat penampung Greetings
Panduan ini mengasumsikan bahwa Anda memiliki akun Google Tag Manager dengan penampung yang bernama Salam. Ikuti petunjuk untuk Penyiapan dan Alur Kerja (Web) untuk membuat Akun dan Penampung bernama Salam.
Menginstal library klien
Sebelum memulai, instal dan konfigurasikan Library klien Google API.
Membuat dan mengonfigurasi project di Konsol API Google
Untuk mulai menggunakan Tag Manager API, Anda harus terlebih dahulu penggunaan alat penyiapan, yang akan memandu Anda membuat project di Konsol API Google, mengaktifkan API, dan membuat kredensial.
Panduan ini menggunakan autentikasi Aplikasi Terinstal
alur kerja. Ikuti petunjuk di bawah untuk membuat kredensial project Anda. Kapan
diminta, pilih Installed Application
untuk APPLICATION
TYPE dan Other
untuk APLIKASI TERINSTAL
JENIS.
- Dari halaman Credentials, klik Create credentials > Klien OAuth ID untuk membuat kredensial OAuth 2.0 atau Buat kredensial > Layanan kunci akun 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 Credentials. Untuk mengetahui detailnya, klik client ID; parameter bervariasi tergantung pada jenis ID, tetapi mungkin termasuk alamat email, rahasia klien, Asal JavaScript, atau URI pengalihan.
Download detail klien dengan mengklik Download JSON
tombol. Ganti nama file ini menjadi client_secrets.json
. File ini akan
digunakan nanti untuk
tujuan otentikasi.
Membuat objek layanan Tag Manager
Objek service
Tag Manager adalah elemen yang akan Anda gunakan untuk membuat
Permintaan API.
Langkah-langkah yang diperlukan untuk membuat objek layanan Tag Manager adalah sebagai berikut:
- Izinkan 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, klien harus memberi aplikasi akses ke Google Tag Manager mereka menggunakan akun layanan. Proses ini disebut otorisasi. Metode yang disarankan untuk memberi otorisasi pengguna adalah OAuth 2.0. Jika Anda ingin mempelajari lebih lanjut, baca Otorisasi Tag Manager API.
Kode di bawah menggunakan detail project dan klien yang dibuat di atas untuk mengautentikasi pengguna aplikasi dan meminta izin untuk mengakses Google Tag Manager atas nama mereka.
Aplikasi akan mencoba membuka browser default dan menavigasi pengguna ke URL yang dihosting di google.com. Pengguna akan diminta untuk login dan memberi aplikasi akses ke akun Tag Manager mereka. Setelah disetujui, aplikasi akan mencoba membaca kode dari jendela {i>browser<i}, lalu menutup jendela.
Catatan: Jika terjadi error, aplikasi akan sebagai gantinya akan meminta pengguna untuk memasukkan kode otorisasi mereka pada perintah garis.
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>
Mengkueri Tag Manager API
Objek layanan Tag Manager dapat digunakan untuk membuat kueri API Tag Manager. Langkah-langkah berikut diperlukan untuk menerapkan program contoh:
- Mengambil penampung Salam
- Membuat tag Universal Analytics
- Membuat pemicu untuk mengaktifkan tag
- Memperbarui 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 untuk mencantumkan semua penampung akun dan mengambil penampung yang 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.'); }); }
Berikutnya, perbarui cabang eksekusi utama program untuk memanggil
Fungsi findGreetingsContainer
dengan Tag Manager
accountId
. 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 kami gunakan untuk mengelola perubahan pada pemicu dan tag. Anda dapat meninjau pembuatan ruang kerja referensi metode untuk 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 Tag Analytics. Anda dapat meninjau langkah Pembuatan tag referensi metode 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. Membuat pemicu untuk mengaktifkan tag
Setelah tag dibuat, langkah selanjutnya adalah membuat Pemicu yang akan diaktifkan di halaman mana pun.
Pemicu akan diberi nama Hello World Trigger dan akan diaktifkan untuk setiap tayangan 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. Memperbarui tag untuk diaktifkan berdasarkan pemicu
Setelah tag dan pemicu dibuat, keduanya harus dikaitkan dengan
lainnya. Untuk melakukannya, tambahkan triggerId
ke daftar
firingTriggerIds
yang dikaitkan 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 perbarui cabang eksekusi utama program untuk memanggil {i>create<i} dan fungsi pembaruan. 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 kode lengkapnya untuk semua langkah dalam panduan ini.
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 Anda memahami cara kerja API, ada beberapa referensi untuk Anda:
- Referensi API – pelajari API dan operasi yang didukung.
- Parameter Referensi – mempelajari cara menetapkan parameter untuk tag dan variabel.
- Tinjau Tag Referensi Kamus untuk daftar tag yang didukung.
- Tinjau Kamus Variabel Referensi untuk daftar Variabel yang dapat dikonfigurasi.