این راهنمای توسعهدهندگان، شما را با مراحل مورد نیاز برای دسترسی، ایجاد و مدیریت موجودیتها در یک حساب Google Tag Manager از طریق Tag Manager API نسخه ۲ آشنا میکند.
مقدمه
این راهنما شما را در مراحل مختلف دسترسی و پیکربندی حساب کاربری گوگل تگ منیجر راهنمایی میکند. پس از اتمام، درک اولیهای از نحوه انجام کارهای زیر خواهید داشت:
- یک شیء سرویس Tag Manager ایجاد کنید.
- احراز هویت و اعطای مجوز به یک کاربر.
- برای دسترسی و مدیریت منابع، با API مدیریت برچسب (Tag Manager) کار کنید.
قبل از اینکه شروع کنی
قبل از شروع راهنما، توصیه میکنیم با مراجعه به مرکز راهنمای Google Tag Manager با Google Tag Manager آشنا شوید.
استفاده از حساب آزمایشی
اگر قصد دارید از API تگ منیجر برای ایجاد، پیکربندی یا حذف موجودیتها استفاده کنید، توصیه میکنیم کد خود را با یک حساب آزمایشی پیادهسازی و تأیید کنید. استفاده از یک حساب آزمایشی به شما کمک میکند تا از ایجاد تغییرات تصادفی در یک حساب فعال جلوگیری کنید. پس از اینکه کد خود را با استفاده از حساب آزمایشی آزمایش و تأیید کردید که مطابق انتظار کار میکند، میتوانید پیادهسازی را با حسابهای واقعی خود شروع کنید.
یک زبان انتخاب کنید
زبان برنامهنویسی مورد نظر خود را انتخاب کنید، برای این کار از مثالهای زیر استفاده کنید:
پایتون
پایتون برای تمام قطعه کدهای این راهنما انتخاب شده است.
جاوا اسکریپت
جاوا اسکریپت برای تمام قطعه کدهای این راهنما انتخاب شده است.
مرور کلی برنامه
برنامهی نمونهای که در این راهنما گنجانده شده است، یک برنامهی خط فرمان است. با دریافت شناسهی حساب کاربری، برنامه یک کانتینر به نام Greetings پیدا میکند و یک تگ Universal Analytics در آن کانتینر ایجاد میکند. وقتی کاربری از hello-world.html بازدید میکند، این تگ یک پیام بازدید از صفحه ارسال میکند.
برای توسعه این اپلیکیشن، باید مراحل زیر را دنبال کنید:
- محیط توسعه و پروژه خود را در کنسول API گوگل تنظیم کنید.
- یک شیء سرویس Tag Manager ایجاد کنید.
- دسترسی به حساب کاربری Tag Manager را مجاز کنید.
- یک شیء سرویس Tag Manager ایجاد کنید.
- از API کوئری بگیرید، پاسخ را مدیریت کنید و نتایج را خروجی دهید.
- یک شیء سرویس Tag Manager مقداردهی اولیه شده دریافت کنید.
- از شیء سرویس Tag Manager برای پرسوجو از API Tag Manager جهت انجام وظایف زیر استفاده کنید:
- کانتینر Greetings را برای حساب کاربری احراز هویت شدهی گوگل تگ منیجر بازیابی کنید.
- یک فضای کاری جدید ایجاد کنید.
- تگ Universal Analytics را ایجاد کنید.
- تریگر (عامل) را برای فعال کردن تگ ایجاد کنید.
- تگ را بهروزرسانی کنید تا روی ماشه فعال شود.
محیط توسعه و پروژه خود را تنظیم کنید
ایجاد کانتینر تبریک
این راهنما فرض میکند که شما یک حساب کاربری گوگل تگ منیجر با یک کانتینر به نام Greetings دارید. دستورالعملهای مربوط به راهاندازی و گردش کار (وب) را برای ایجاد یک حساب کاربری و یک کانتینر به نام Greetings دنبال کنید.
نصب کتابخانه کلاینت
قبل از شروع، یک کتابخانه کلاینت Google APIs نصب و پیکربندی کنید.
ایجاد و پیکربندی یک پروژه در کنسول API گوگل
برای شروع استفاده از API تگ منیجر، ابتدا باید از ابزار راهاندازی استفاده کنید که شما را در ایجاد یک پروژه در کنسول API گوگل و فعال کردن API راهنمایی میکند.
این راهنما از یک جریان احراز هویت برنامه نصبشده استفاده میکند. برای ایجاد اعتبارنامههای پروژه خود، دستورالعملهای زیر را دنبال کنید. در صورت درخواست، برای نوع برنامه، Installed Application و برای نوع برنامه نصبشده، Other را انتخاب کنید.
- از صفحه اعتبارنامهها، برای ایجاد اعتبارنامههای OAuth 2.0 خود ، روی ایجاد اعتبارنامهها > شناسه کلاینت OAuth کلیک کنید یا برای ایجاد یک حساب سرویس، روی ایجاد اعتبارنامهها > کلید حساب سرویس کلیک کنید.
- اگر یک شناسه کلاینت OAuth ایجاد کردهاید، نوع برنامه خود را انتخاب کنید.
- فرم را پر کنید و روی ایجاد کلیک کنید.
شناسههای کلاینت برنامه شما و کلیدهای حساب سرویس اکنون در صفحه اعتبارنامهها فهرست شدهاند. برای جزئیات، روی یک شناسه کلاینت کلیک کنید؛ پارامترها بسته به نوع شناسه متفاوت هستند، اما ممکن است شامل آدرس ایمیل، رمز کلاینت، ریشههای جاوا اسکریپت یا URI های تغییر مسیر باشند.
با کلیک روی دکمهی «دانلود JSON» ، جزئیات کلاینت را دانلود کنید. نام این فایل را به client_secrets.json تغییر دهید. این فایل بعداً برای اهداف احراز هویت استفاده خواهد شد.
ایجاد یک شیء سرویس Tag Manager
شیء service Tag Manager چیزی است که شما برای ارسال درخواستهای API از آن استفاده خواهید کرد.
مراحل مورد نیاز برای ایجاد یک شیء سرویس Tag Manager به شرح زیر است:
- دسترسی به حساب کاربری گوگل تگ منیجر را مجاز کنید.
- شیء سرویس Tag Manager را نمونهسازی کنید.
دسترسی به حساب کاربری گوگل تگ منیجر را مجاز کنید
وقتی کاربری برنامهای را که با API گوگل تگ منیجر ساخته شده است، اجرا میکند، باید به برنامه اجازه دسترسی به حساب گوگل تگ منیجر خود را بدهد. این فرآیند، مجوزدهی نامیده میشود. روش پیشنهادی برای مجوزدهی به کاربران، OAuth 2.0 است. اگر میخواهید اطلاعات بیشتری کسب کنید، بخش مجوزدهی به API تگ منیجر را مطالعه کنید.
کد زیر از جزئیات پروژه و مشتری ایجاد شده در بالا برای احراز هویت کاربر برنامه استفاده میکند و از آنها اجازه دسترسی به گوگل تگ منیجر را از طرف خود درخواست میکند.
برنامه سعی میکند مرورگر پیشفرض را باز کند و کاربر را به آدرس اینترنتی (URL) میزبانی شده در google.com هدایت کند. از کاربر خواسته میشود که وارد سیستم شود و به برنامه اجازه دسترسی به حساب کاربری Tag Manager خود را بدهد. پس از اعطای دسترسی، برنامه سعی میکند کدی را از پنجره مرورگر بخواند، سپس پنجره را ببندد.
توجه : در صورت بروز خطا، برنامه از کاربر میخواهد که کد مجوز خود را در خط فرمان وارد کند.
پایتون
"""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)
جاوا اسکریپت
<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>
کوئری گرفتن از API تگ منیجر
شیء سرویس Tag Manager میتواند برای پرسوجو از API Tag Manager استفاده شود. مراحل زیر برای پیادهسازی برنامه نمونه مورد نیاز است:
- بازیابی کانتینر تبریکات
- تگ Universal Analytics را ایجاد کنید
- ایجاد تریگر برای فعال کردن تگ
- تگ را برای فعال شدن روی ماشه بهروزرسانی کنید
۱. دریافت کانتینر Greetings
تابع زیر نشان میدهد که چگونه میتوان از یک شیء سرویس Tag Manager برای پرسوجو از API Tag Manager جهت فهرست کردن تمام کانتینرهای یک حساب کاربری و بازیابی کانتینری به نام Greetings استفاده کرد.
پایتون
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
جاوا اسکریپت
/** * 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 با توجه به accountId Tag Manager فراخوانی شود. برای مثال:
پایتون
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)
جاوا اسکریپت
/** * 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(); }); }
۲. یک فضای کاری جدید ایجاد کنید
قطعه کد زیر از API مدیریت تگ برای ایجاد یک فضای کاری جدید استفاده میکند که ما از آن برای مدیریت تغییرات خود در تریگرها و تگها استفاده میکنیم. میتوانید مرجع متد ایجاد فضای کاری را برای فهرست ویژگیهای مورد نیاز و اختیاری که میتوانند هنگام ایجاد یک فضای کاری تنظیم شوند، بررسی کنید.
پایتون
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()
جاوا اسکریپت
/** * 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); }
۳. تگ Universal Analytics را ایجاد کنید
قطعه کد زیر از API مدیریت تگ برای ایجاد یک تگ Universal Analytics استفاده میکند. میتوانید برای مشاهده فهرست ویژگیهای الزامی و اختیاری که میتوانند هنگام ایجاد یک تگ تنظیم شوند، به مرجع متد ایجاد تگ و برای مشاهده فهرست ویژگیهای هر نوع تگ ، به مرجع دیکشنری تگ مراجعه کنید.
پایتون
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()
جاوا اسکریپت
/** * 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); }
۴. تریگر (عامل) را برای فعال کردن تگ ایجاد کنید
حالا که یک تگ ایجاد شده است، مرحله بعدی ایجاد یک Trigger است که در هر صفحهای فعال شود.
این تریگر، Hello World Trigger نام خواهد داشت و برای هر بار مشاهده صفحه فعال میشود. برای مثال:
پایتون
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()
جاوا اسکریپت
/** * 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); }
۵. تگ را برای فعال شدن روی ماشه بهروزرسانی کنید
حالا که یک تگ و تریگر ایجاد شدهاند، باید به یکدیگر مرتبط شوند. برای انجام این کار، triggerId به لیست firingTriggerIds مرتبط با تگ اضافه کنید. برای مثال:
پایتون
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()
جاوا اسکریپت
/** * 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 را فراخوانی کند. برای مثال:
پایتون
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)
جاوا اسکریپت
/** * 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(); }); }
مثال کامل
برای مشاهده نمونه کد کامل تمام مراحل موجود در راهنما، این بخش را باز کنید.
پایتون
"""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)
جاوا اسکریپت
<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 و عملیات پشتیبانی شده اطلاعات کسب کنید.
- مرجع پارامترها - درباره تنظیم پارامترها برای برچسبها و متغیرها بیاموزید.
- برای مشاهده فهرستی از تگهای پشتیبانیشده ، به مرجع دیکشنری تگها مراجعه کنید.
- برای مشاهدهی فهرستی از متغیرهای قابل پیکربندی، به مرجع فرهنگ لغت متغیرها مراجعه کنید.