### Run Tagging Server Setup Script
Source: https://developers.google.com/tag-platform/tag-manager/server-side/app-engine-setup
Execute the setup script to install or update the server-side tagging server. This script fetches the latest version and configures it with default settings.
```bash
bash -c "$(curl -fsSL https://googletagmanager.com/static/serverjs/setup.sh)"
```
--------------------------------
### Python: Complete Tag Manager Example
Source: https://developers.google.com/tag-platform/tag-manager/api/v2/devguide
This script demonstrates a full workflow for creating a workspace, a 'hello world' tag, and a trigger, then associating the tag with the trigger. It requires authentication and service setup.
```python
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)
```
--------------------------------
### Complete Example: Create Tag Manager Entities (Python)
Source: https://developers.google.com/tag-platform/tag-manager/api/v2/devguide
A comprehensive example demonstrating the creation of a workspace, a Universal Analytics tag, and a trigger, then linking the tag to the trigger. This showcases a common workflow for automating GTM setup.
```python
from googleapiclient.discovery import build
# Replace with your actual values
DEVELOPER_KEY = "YOUR_API_KEY"
ACCOUNT_ID = "YOUR_ACCOUNT_ID"
CONTAINER_ID = "YOUR_CONTAINER_ID"
# Construct the service object.
service = build("tagmanager", "v2", developerKey=DEVELOPER_KEY)
# 1. Retrieve the Greetings container
container = service.accounts().containers().get(name=ACCOUNT_ID + "/containers/" + CONTAINER_ID).execute()
print('Container: %s' % container.get('name'))
# 2. Create a New Workspace
workspace = service.accounts().containers().workspaces().create(parent=container.get('name'), body={'name': 'My New Workspace'}).execute()
print('Workspace: %s' % workspace.get('name'))
# 3. Create the Universal Analytics tag
tag_NAME = 'My Universal Analytics Tag'
TRACKING_ID = 'UA-XXXXX-Y' # Replace with your Tracking ID
tag = service.accounts().containers().workspaces().tags().create(parent=workspace.get('name'), body={'name': TAG_NAME, 'type': 'UNIVERSAL_ANALYTICS', 'universalAnalytics': {'trackingId': TRACKING_ID}}).execute()
print('Tag: %s' % tag.get('name'))
# 4. Create the trigger to fire the tag
TRIGGER_NAME = 'All Pages Trigger'
TRIGGER = service.accounts().containers().workspaces().triggers().create(parent=workspace.get('name'), body={'name': TRIGGER_NAME, 'type': 'PAGES_VIEW'}).execute()
print('Trigger: %s' % TRIGGER.get('name'))
# 5. Update the tag to fire on the trigger
tag['triggerId'] = [TRIGGER.get('triggerId')]
updated_tag = service.accounts().containers().workspaces().tags().update(body=ntag).execute()
print('Tag updated to fire on trigger: %s' % updated_tag.get('name'))
```
--------------------------------
### List Containers Request Example
Source: https://developers.google.com/tag-platform/tag-manager/api/reference/rest/v2/accounts.containers/list
This example demonstrates how to make a GET request to the `containers.list` endpoint to retrieve all containers for a GTM account. It includes the base URL and the required `parent` path parameter.
```HTTP
GET https://tagmanager.googleapis.com/tagmanager/v2/{parent}/containers
```
--------------------------------
### Provision Tagging Server with Setup Script
Source: https://developers.google.com/tag-platform/tag-manager/server-side/app-engine-setup
Execute the setup script to create your tagging server on App Engine. Set the deployment type to 'testing' for initial setup. Enter '?' at prompts for help.
```bash
bash -c "$(curl -fsSL https://googletagmanager.com/static/serverjs/setup.sh)"
```
--------------------------------
### Full Resource Response Example
Source: https://developers.google.com/tag-platform/tag-manager/api/v2/performance
Example of a full resource data response from the Demo API, including various fields and nested structures.
```JSON
{
"kind": "demo",
...
"items": [
{
"title": "First title",
"comment": "First comment.",
"characteristics": {
"length": "short",
"accuracy": "high",
"followers": ["Jo", "Will"],
},
"status": "active",
...
},
{
"title": "Second title",
"comment": "Second comment.",
"characteristics": {
"length": "long",
"accuracy": "medium"
"followers": [ ],
},
"status": "pending",
...
},
...
]
}
```
--------------------------------
### Run Tag Manager Example (JavaScript)
Source: https://developers.google.com/tag-platform/tag-manager/api/v2/devguide
Initializes a Tag Manager example by finding a container and logging a message. This is a placeholder function that needs further implementation to handle errors and resolve promises.
```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();
});
}
```
--------------------------------
### Run Tag Manager Example
Source: https://developers.google.com/tag-platform/tag-manager/api/v2/devguide
A placeholder function to initiate an example interaction with the Tag Manager API v2. It resolves a promise to signal completion.
```javascript
function runTagManagerExample() {
return new Promise((resolve, reject) => {
console.log('Running Tag Manager Example.');
resolve();
});
}
```
--------------------------------
### get
Source: https://developers.google.com/tag-platform/tag-manager/api/reference/rest/v2/accounts.containers.workspaces
Gets a Workspace.
```APIDOC
## get
### Description
Gets a Workspace.
### Method
GET
### Endpoint
`accounts.containers.workspaces.get`
```
--------------------------------
### Install Google Tag (gtag.js)
Source: https://developers.google.com/tag-platform/devguides/conversions
This snippet installs the Google tag (gtag.js) which establishes the data connection to your product. Replace DC-XXXXXX with your valid configuration ID.
```html
```
--------------------------------
### AMP Linker Format Example
Source: https://developers.google.com/tag-platform/gtagjs/amp
This example shows the format for passing linker parameters, including `_gl`, `_ga`, and `gclid`, via URL decoration for AMP pages. Ensure this format is used when redirecting from the Google CDN to the client website.
```text
**_Linker format: mydomain.com?_gl=1*1ie2jr6*_ga*WHFTa3JPckw2TGxZSzY5b3V1cVNVSmRIREI.*gclid*dGVzdA.._**
```
--------------------------------
### AMP Linker Format Example
Source: https://developers.google.com/tag-platform/tag-manager/amp
This example demonstrates the format for URL decoration when passing `cid` and `gclid` values between pages for AMP linker functionality. Ensure this format is used correctly to maintain consistent user tracking across redirects and domain changes.
```text
_Linker format: mydomain.com?_gl=1*1ie2jr6*_ga*WHFTa3JPckw2TGxZSzY5b3V1cVNVSmRIREI.*gclid*dGVzdA..
```
--------------------------------
### Main Function for GTM API Example
Source: https://developers.google.com/tag-platform/tag-manager/api/v2/devguide
The main entry point for the Google Tag Manager API example script. It parses the account ID and sets up the account path.
```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 = str(argv[1])
account_path = 'accounts/%s' % account_id
# Define the auth scopes to request.
```
--------------------------------
### Monitoring Pixel URL Example with Execution Times
Source: https://developers.google.com/tag-platform/tag-manager/templates/monitoring
This is an example URL structure for a monitoring pixel that includes tag execution times.
```plaintext
https://www.example.com/monitoring?ctid=GTM-XXXXXX&tag12=1200&tag50=400&tag1=6000
```
--------------------------------
### get
Source: https://developers.google.com/tag-platform/tag-manager/api/v2/reference/accounts/user_permissions
Gets a user's Account & Container access.
```APIDOC
### `get`
Gets a user's Account & Container access.
```
--------------------------------
### Retail Event Parameter Tag Example
Source: https://developers.google.com/tag-platform/devguides/dynamic-remarketing
This example demonstrates how to send a 'view_item' event with specific parameters for the retail business vertical. It includes item IDs and the 'google_business_vertical' field.
```javascript
```
--------------------------------
### Monitoring Pixel URL Example
Source: https://developers.google.com/tag-platform/tag-manager/templates/monitoring
This is an example URL structure for a monitoring pixel that includes tag status counts.
```plaintext
https://www.example.com/monitoring?ctid=GTM-XXXXXX&success=4&failure=1&exception=1&timeout=0
```
--------------------------------
### Example gtag.js Event Command
Source: https://developers.google.com/tag-platform/tag-manager/server-side/how-to-build-a-server-tag
This is an example of a gtag.js 'event' command that sends custom data. The parameters sent here can be anything the user defines.
```javascript
gtag('event', 'search', {
search_term: 'beets',
});
```
--------------------------------
### Assertion Examples
Source: https://developers.google.com/tag-platform/tag-manager/server-side/api
A collection of assertion examples demonstrating various checks for undefined, null, boolean, truthy/falsy, infinity, NaN, equality, array contents, and string length.
```javascript
assertThat(undefined).isUndefined();
assertThat(id, 'ID must be defined').isDefined();
assertThat(null).isNull();
assertThat(undefined).isNotNull();
assertThat(true).isTrue();
assertThat(false).isFalse();
assertThat(1).isTruthy();
assertThat('').isFalsy();
assertThat(1/0).isInfinity();
assertThat(0).isNotInfinity();
assertThat(-'foo').isNaN();
assertThat(100).isNotNaN();
assertThat(sentUrl).isEqualTo('https://endpoint.example.com/?account=12345');
assertThat(category).isNotEqualTo('premium');
assertThat(5).isAnyOf(1, 2, 3, 4, 5);
assertThat(42).isNoneOf('the question', undefined, 41.9);
assertThat('value').isStrictlyEqualTo('value');
assertThat('4').isNotStrictlyEqualTo(4);
assertThat(['a', 'b', 'c']).contains('a', 'c');
assertThat(['x', 'y', 'z']).doesNotContain('f');
assertThat(['1', '2', '3']).containsExactly('3', '2', '1');
assertThat(['4', '5']).doesNotContainExactly('4');
assertThat('a string').hasLength(8);
assertThat([]).isEmpty();
assertThat('another string').isNotEmpty();
```
--------------------------------
### Promise.create Example
Source: https://developers.google.com/tag-platform/tag-manager/server-side/api
Creates a new promise that can be controlled by resolve and reject functions. The resolver function must be provided.
```javascript
const Promise = require('Promise');
return Promise.create((resolve, reject) => {
// Do asynchronous work that eventually calls resolve() or reject()
});
```
--------------------------------
### environments.get
Source: https://developers.google.com/tag-platform/tag-manager/api/reference/rest/v1/accounts.containers.environments/get
Gets a GTM Environment by providing the account, container, and environment IDs.
```APIDOC
## GET accounts.containers.environments.get
### Description
Gets a GTM Environment.
### Method
GET
### Endpoint
`https://tagmanager.googleapis.com/tagmanager/v1/accounts/{accountId}/containers/{containerId}/environments/{environmentId}`
### Parameters
#### Path Parameters
- **accountId** (string) - Required - The GTM Account ID.
- **containerId** (string) - Required - The GTM Container ID.
- **environmentId** (string) - Required - The GTM Environment ID.
### Request Body
The request body must be empty.
### Response Body
If successful, the response body contains an instance of `Environment`.
```
--------------------------------
### Get Field Value from Target
Source: https://developers.google.com/tag-platform/gtagjs/reference
Use the get command to retrieve various values from gtag.js, including values set with the 'set' command. This example shows how to fetch the 'gclid' value into a Promise.
```javascript
const gclidPromise = new Promise(resolve => {
gtag('get', 'DC-XXXXXXXX', 'gclid', resolve)
});
gclidPromise.then((gclid) => {
// Do something with gclid...
})
```
--------------------------------
### Set up sign_up event
Source: https://developers.google.com/tag-platform/devguides/gtag-integration
Use the `sign_up` event to track user sign-ups, specifying the method used (e.g., 'web').
```javascript
gtag('event', 'sign_up', {method: 'web'});
```
--------------------------------
### AndroidManifest.xml Configuration for InstallReferrerReceiver
Source: https://developers.google.com/tag-platform/tag-manager/android/v3/reference/com/google/tagmanager/InstallReferrerReceiver
Add these entries to your AndroidManifest.xml to enable install referrer tracking. This setup is required for the InstallReferrerReceiver to function.
```xml
```
--------------------------------
### Sample Beacon Tag Implementation
Source: https://developers.google.com/tag-platform/tag-manager/templates/sandboxed-javascript
This example demonstrates building a beacon tag using the sandboxed JavaScript environment. It utilizes `require` for necessary functions and accesses configuration data through the `data` parameter.
```javascript
var url = require('urllib').addArgs(data.url, {
'id': data.id,
'value': data.value
});
require('log').log(url);
var image = document.createElement('img');
image.src = url;
// The tag will fire the beacon when the image is loaded.
// The image element will be added to the DOM.
image;
```
--------------------------------
### Get Client ID for Offline Event
Source: https://developers.google.com/tag-platform/gtagjs/reference
This example demonstrates retrieving the 'client_id' for a specific target and using it to send an offline event.
```javascript
gtag('get', 'G-XXXXXXXXXX', 'client_id', (clientID) => {
sendOfflineEvent(clientID, "tutorial_begin")
});
function sendOfflineEvent(clientID, eventName, eventData) {
// Send necessary data to your server...
}
```
--------------------------------
### Get Custom Set Value
Source: https://developers.google.com/tag-platform/gtagjs/reference
This example shows how to retrieve a custom parameter ('campaign_name') that was previously set using the 'gtag('set')' command.
```javascript
gtag('set', {campaign_name: 'Spring_Sale'});
gtag('get', 'G-XXXXXXXXXX', 'campaign_name', (campaign_name) => {
// Do something with currency value you set earlier.
})
```
--------------------------------
### onCreate
Source: https://developers.google.com/tag-platform/tag-manager/android/v3/reference/com/google/tagmanager/PreviewActivity.html
Prepares for previewing a non-published container and then launches the launch activity for this package.
```APIDOC
## onCreate
### Description
Prepares for previewing a non-published container and then launches the launch activity for this package.
### Method
public void
### Parameters
* **_savedInstanceState** (Bundle) - Description not available in source.
```
--------------------------------
### Provision a Preview Server Locally
Source: https://developers.google.com/tag-platform/tag-manager/server-side/manual-setup-guide
Run this Docker command to provision a local preview server. This requires setting the CONTAINER_CONFIG and RUN_AS_PREVIEW_SERVER environment variables.
```bash
docker run -p 8080:8080 -e CONTAINER_CONFIG='' -e RUN_AS_PREVIEW_SERVER=true gcr.io/cloud-tagging-10302018/gtm-cloud-image:stable
```
--------------------------------
### InstallReferrerReceiver Integration
Source: https://developers.google.com/tag-platform/tag-manager/android/v3/reference/com/google/tagmanager/InstallReferrerReceiver
To enable install referrer tracking, add the following service and receiver entries to your `AndroidManifest.xml` file. This setup allows the receiver to capture the `com.android.vending.INSTALL_REFERRER` intent and forward the data to Google Tag Manager and Google Analytics.
```APIDOC
## InstallReferrerReceiver Integration
### Description
This section provides the necessary XML configuration to integrate the `InstallReferrerReceiver` into your Android application. By adding these entries to your `AndroidManifest.xml`, you enable the automatic tracking of install referrer data from the Google Play Store.
### Manifest Configuration
```xml
```
### Usage Notes
- The `InstallReferrerReceiver` listens for the `com.android.vending.INSTALL_REFERRER` intent.
- Upon receiving this intent, it passes the install referrer data to Google Tag Manager and Google Analytics.
- This receiver automatically invokes the Google Analytics receiver to set campaign data, simplifying setup when using both SDKs.
- Ensure both the Google Analytics SDK and Google Tag Manager SDK are included in your project for full functionality.
```
--------------------------------
### Example Request Body for Bulk Update
Source: https://developers.google.com/tag-platform/tag-manager/api/reference/rest/v2/accounts.containers.workspaces/bulk_update
This snippet demonstrates the structure of the request body for the bulk_update method, showing how to add a new folder and a new tag within that folder. When creating new entities, their IDs must be unique and start with 'new_' followed by a number.
```json
"changes": [
{
"folder": {
"folderId": "new_1",
"name": "myNewFolder",
...
},
"changeStatus": "added"
},
{
"tag": {
"tagId": "new_2",
"name": "myNewTag",
"parentFolderId": "new_1",
...
},
"changeStatus": "added"
}
]
```
--------------------------------
### get(String _key_)
Source: https://developers.google.com/tag-platform/tag-manager/android/v3/reference/com/google/tagmanager/DataLayer
Returns the object in the model associated with the given key. If the key is not found, `null` is returned. The key can can have embedded periods. For example: a key of `"a.b.c"` returns a map with key `"c"` in a map with key `"b"` in a map with key `"a"` in the model.
```APIDOC
## Public Methods
#### public Object **get** (String _key_)
Returns the object in the model associated with the given key. If the key is not found, `null` is returned.
The key can can have embedded periods. For example: a key of `"a.b.c"` returns a map with key `"c"` in a map with key `"b"` in a map with key `"a"` in the model.
```
--------------------------------
### Set up purchase event
Source: https://developers.google.com/tag-platform/devguides/gtag-integration
Track the `purchase` event when a user completes a purchase. This is a simplified example showing value, currency, and item placeholders.
```javascript
gtag('event', 'purchase', {value: XX, currency: 'USD', items: [{xx},{xx}]});
```
--------------------------------
### get
Source: https://developers.google.com/tag-platform/tag-manager/api/reference/rest/v1/accounts.containers.versions
Gets a Container Version.
```APIDOC
## `get`
Gets a Container Version.
```
--------------------------------
### Firestore.query Example
Source: https://developers.google.com/tag-platform/tag-manager/server-side/api
Example of how to use Firestore.query to retrieve a document with specific conditions and options.
```javascript
const Firestore = require('Firestore');
const queries = const queries = [['id', '==', '5']];
return Firestore.query('collection', queries, {
projectId: 'gcp-cloud-project-id',
limit: 1,
}).then((documents) => documents[0].data.key, () => undefined);
```
--------------------------------
### quick_preview
Source: https://developers.google.com/tag-platform/tag-manager/api/reference/rest/v2/accounts.containers.workspaces
Quick previews a workspace by creating a fake container version from all entities in the provided workspace.
```APIDOC
## quick_preview
### Description
Quick previews a workspace by creating a fake container version from all entities in the provided workspace.
### Method
POST
### Endpoint
`accounts.containers.workspaces.quick_preview`
```
--------------------------------
### Get Request Method
Source: https://developers.google.com/tag-platform/tag-manager/server-side/api
Retrieves the HTTP request method (e.g., 'GET', 'POST') as a string. No specific permissions are required.
```javascript
const getRequestMethod = require('getRequestMethod');
if (getRequestMethod() === 'POST') {
// Handle the POST request here.
}
```
--------------------------------
### Promise.all Example
Source: https://developers.google.com/tag-platform/tag-manager/server-side/api
Creates a promise that resolves when all input promises resolve or rejects if any input rejects. Requires 'Promise' and 'sendHttpGet' modules.
```javascript
const Promise = require('Promise');
const sendHttpGet = require('sendHttpGet');
return Promise.all(['a', sendHttpGet('https://example.com')])
.then((results) => {
// results will equal: ['a', {statusCode: 200, headers: {}, body: ''}]
});
```
--------------------------------
### Simple GET Request to Demo API
Source: https://developers.google.com/tag-platform/tag-manager/api/v2/performance
This HTTP GET request omits the 'fields' parameter and returns the full resource.
```HTTP
https://www.googleapis.com/demo/v1
```
--------------------------------
### Set up begin_checkout event
Source: https://developers.google.com/tag-platform/devguides/gtag-integration
Implement the `begin_checkout` event when a user starts the checkout process. This snippet includes value, currency, and item details.
```javascript
gtag('event', 'begin_checkout') {
value: 99.0,
currency: "USD",
items: [{
item_id: "SKU_123",
item_name: "Test Product",
price: 99.0,
currency: ‘USD’,
quantity: 1,
item_category: "All Products"
}]
});
```
--------------------------------
### Install Tag Manager via CocoaPods
Source: https://developers.google.com/tag-platform/tag-manager/ios/v5
Use this command to install the Google Tag Manager package using CocoaPods.
```bash
$ sudo gem install cocoapods
```
```bash
$ pod init
```
```ruby
pod 'GoogleTagManager', '~> 6.0'
```
```bash
$ pod install
```
--------------------------------
### Template Data Storage Example
Source: https://developers.google.com/tag-platform/tag-manager/server-side/api
Demonstrates using template data storage to cache and retrieve data across template executions. Requires 'access_template_storage' permission.
```javascript
const sendHttpGet = require('sendHttpGet');
const setResponseBody = require('setResponseBody');
const setResponseStatus = require('setResponseStatus');
const templateDataStorage = require('templateDataStorage');
// Check to see if the item is in the cache.
const cachedBody = templateDataStorage.getItemCopy(data.key);
if (cachedBody) {
setResponseBody(cachedBody);
data.gtmOnSuccess();
return;
}
sendHttpGet(data.url).then((result) => {
if (result.statusCode >= 200 && result.statusCode < 300) {
setResponseBody(result.body);
templateDataStorage.setItemCopy(data.key, result.body);
data.gtmOnSuccess();
} else {
data.gtmOnFailure();
}
setResponseStatus(result.statusCode);
});
```
--------------------------------
### create
Source: https://developers.google.com/tag-platform/tag-manager/api/reference/rest/v2/accounts.containers.workspaces
Creates a Workspace.
```APIDOC
## create
### Description
Creates a Workspace.
### Method
POST
### Endpoint
`accounts.containers.workspaces.create`
```
--------------------------------
### Update AndroidManifest.xml for Install Referrer
Source: https://developers.google.com/tag-platform/tag-manager/android/v4/google-ads-conversions
Add the Google Tag Manager InstallReferrerService and InstallReferrerReceiver to your AndroidManifest.xml file to track app installs.
```xml
```
--------------------------------
### HTTP Request for Quick Preview
Source: https://developers.google.com/tag-platform/tag-manager/api/reference/rest/v2/accounts.containers.workspaces/quick_preview
This snippet shows the structure of an HTTP POST request to the `quick_preview` endpoint. It includes the base URL and the placeholder for the workspace path.
```HTTP
POST https://tagmanager.googleapis.com/tagmanager/v2/{path}:quick_preview
```
--------------------------------
### Set up book_appointment event
Source: https://developers.google.com/tag-platform/devguides/gtag-integration
Use the `book_appointment` event to track when a user books an appointment. Includes placeholders for value, currency, and coupon.
```javascript
gtag('event', 'book_appointment', {value: XX, currency: 'USD', coupon: 'XX'});
```
--------------------------------
### Get Referrer Query Parameters
Source: https://developers.google.com/tag-platform/tag-manager/templates/api
Retrieves query parameters from the referrer URL. Use `retrieveAll` set to true to get all values for a given key.
```javascript
getReferrerQueryParameters('var') == 'foo'
getReferrerQueryParameters('var', false) == 'foo'
getReferrerQueryParameters('var', null) == 'foo'
getReferrerQueryParameters('var', true) == ['foo', 'foo2', 'foo']
```
--------------------------------
### Set up view_item_list event
Source: https://developers.google.com/tag-platform/devguides/gtag-integration
Implement the `view_item_list` event when a user views a list of items. This snippet shows how to pass item list details and individual item information.
```javascript
gtag('event', 'view_item_list', {
item_list_id: "related_products",
item_list_name: "Related products",
items: [{
item_id: "SKU_123",
item_name: "Test Item",
currency: "USD",
discount: 2.22,
price: 99.9,
quantity: 1
}]
});
```
--------------------------------
### Initializing DataLayer
Source: https://developers.google.com/tag-platform/tag-manager/android/v3/reference/com/google/tagmanager/DataLayer
Initial state of the DataLayer.
```java
{
title: "Original screen title"
}
```
--------------------------------
### Set up generate_lead event
Source: https://developers.google.com/tag-platform/devguides/gtag-integration
Implement the `generate_lead` event when a user submits a form. This snippet includes placeholders for value and currency.
```javascript
gtag('event', 'generate_lead', {value: XX, currency: 'USD'});
```
--------------------------------
### create
Source: https://developers.google.com/tag-platform/tag-manager/api/v2/reference/accounts/user_permissions
Creates a user's Account & Container access.
```APIDOC
### `create`
Creates a user's Account & Container access.
```
--------------------------------
### View All Docker Image Settings
Source: https://developers.google.com/tag-platform/tag-manager/server-side/manual-setup-guide
Use this command to view all available settings and flags for the tagging server Docker image. This helps in understanding the configuration options for both the server-side tagging (SST) cluster and the preview server.
```bash
docker run gcr.io/cloud-tagging-10302018/gtm-cloud-image:stable server_bin.js --help
```
--------------------------------
### Get Container Snippet (REST)
Source: https://developers.google.com/tag-platform/tag-manager/api/reference/rest/v2/accounts.containers/snippet
This snippet demonstrates how to retrieve the tagging snippet for a Google Tag Manager container using a GET request to the REST API. Ensure you have the correct OAuth scopes for authorization.
```HTTP
GET https://tagmanager.googleapis.com/tagmanager/v2/{path}:snippet
```
--------------------------------
### create
Source: https://developers.google.com/tag-platform/tag-manager/api/reference/rest/v1/accounts.containers.versions
Creates a Container Version.
```APIDOC
## `create`
Creates a Container Version.
```
--------------------------------
### Get a Value from the Data Layer
Source: https://developers.google.com/tag-platform/devguides/datalayer
Use the `get` function to retrieve a previously set value from the data layer. This allows for conditional logic based on existing data. Ensure you are pushing directly to `window.dataLayer`.
```javascript
window.dataLayer.push(function() {
const existingTime = this.get('time');
if (existingTime !== null) {
// Change behavior based on whether or not this value exists...
} else {
// ...
}
})
```
--------------------------------
### Initialize Data Layer with Allowlist and Blocklist
Source: https://developers.google.com/tag-platform/tag-manager/restrict
Use this snippet to initialize the data layer with both an allowlist and a blocklist. Both lists are optional and must be of type Array with String values. Push these values before any tags fire.
```javascript
```
--------------------------------
### Standard Error Response Example
Source: https://developers.google.com/tag-platform/tag-manager/api/v2/errors
An example of a standard error response from the Tag Manager API, indicating an invalid parameter and providing detailed error information. Applications should not depend on the exact message text.
```json
400 invalidParameter
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured. Please use Google Developers Console to activate the API for your project."
}
],
"code": 403,
"message": "Access Not Configured. Please use Google Developers Console to activate the API for your project."
}
}
```
--------------------------------
### Log a Login Event
Source: https://developers.google.com/tag-platform/devguides/gtag-integration
Example of sending a 'login' event, specifying the method used for login. The Developer ID must be included.
```javascript
gtag('event', 'login', {
'developer_id.': true,
'method': 'Google'
});
```
--------------------------------
### get Command
Source: https://developers.google.com/tag-platform/gtagjs/reference
Retrieves the value of a parameter.
```APIDOC
## get Command
### Description
The `get` command is used to retrieve the current value of a specified parameter from the Google tag's configuration.
### Method
`get`
### Parameters
* **`parameter_name`** (string) - Required - The name of the parameter to retrieve.
* **`callback`** (function) - Required - A callback function that will be executed with the retrieved parameter value as its argument.
```
--------------------------------
### Main Execution Branch (Python)
Source: https://developers.google.com/tag-platform/tag-manager/api/v2/devguide
Sets up authentication and calls the FindGreetingsContainer function with the provided account ID. Requires the 'tagmanager.edit.containers' scope.
```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 = 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)
```
--------------------------------
### Make HTTP GET Request and Return Body
Source: https://developers.google.com/tag-platform/tag-manager/server-side/api
Performs an HTTP GET request to a specified URL with optional headers and timeout. It returns the response body if successful, or undefined if the request fails or times out. This is useful for fetching data from external resources.
```javascript
const sendHttpGet = require('sendHttpGet');
// Returns the response body as the value for a variable.
return sendHttpGet('https://example.com/item/' + data.itemId, {
headers: {key: 'value'},
timeout: 500,
}).then((result) => result.body, () => undefined);
```
--------------------------------
### `createQueue`
Source: https://developers.google.com/tag-platform/tag-manager/templates/api
Creates an array in the `window` object and returns a function to push values onto that array. Requires `access_globals` permission.
```APIDOC
## `createQueue`
### Description
Creates an array in `window` (if it doesn't already exist) and returns a function that will push values onto that array.
This function requires the read and write setting for `arrayKey` on the `access_globals` permission.
### Example:
```javascript
const dataLayerPush = createQueue('dataLayer');
dataLayerPush({'currency': 'USD'}, {'event': 'myConversion'});
```
### Syntax
`createQueue(arrayKey)`
### Parameters
#### Parameters
- **`arrayKey`** (_string_) - The key in `window` where the array is set, if it does not already exist. This argument supports standard dot notation. If the key's path does not exist, an exception is thrown. For example, if `arrayKey` is `'one.two'`, and there is no global object named `'one'`, it will throw an exception.
### Associated permissions
`access_globals`
```
--------------------------------
### getRequestMethod
Source: https://developers.google.com/tag-platform/tag-manager/server-side/api
Returns the request method, e.g. 'GET' or 'POST', as a string.
```APIDOC
## `getRequestMethod`
### Description
Returns the request method, e.g. `'GET'` or `'POST'`, as a string.
### Example
```javascript
const getRequestMethod = require('getRequestMethod');
if (getRequestMethod() === 'POST') {
// Handle the POST request here.
}
```
### Syntax
```
getRequestMethod();
```
### Associated permissions
None.
```
--------------------------------
### Parameter Precedence Example
Source: https://developers.google.com/tag-platform/gtagjs/reference
Illustrates how parameter values are prioritized based on their scope: event > config > global (set). Shows different currency values being used based on scope.
```javascript
// Set campaign information at the global scope
gtag('set', { 'campaign_name': 'Black Friday Sale' });
// Set currency for to 'USD'
gtag('config','', { 'currency': 'USD' });
// Process a conversion event with currency: 'GBP'
gtag('event','conversion', { 'currency': 'GBP', 'send_to': '' });
// Process a conversion event with currency: 'EUR'
gtag('event','conversion');
// Process a conversion event with currency: 'USD'
gtag('event','conversion', { 'send_to': '' });
```