I previously wrote about Google’s reCAPTCHA v3.that is Validation APIanalyze the signal supplied to the bot scorebased on how “bot-like” the hit is.
This is a great way to validate whether you collect data from a particular source that exhibits bot-like behavior. For example, they tend to add a lot of (unrealistic) noise to datasets, so analytical tools should ignore them.
You can read more about how reCAPTCHA v3 works here.
In the previous article, you had to build your own server endpoint to handle reCAPTCHA requests. As you know, reCAPTCHA requires a custom-built API endpoint to handle verification requests.
Luckily, with the advent of Google Tag Manager server containers, it’s now easy to build a “local” API yourself using the power of custom templates.
In this guide, the new client template I created it to do the legwork for you. It’s designed to proxy reCAPTCHA client-side library When To process verification request.
At the time of writing, the client template is still Community template galleryso you have to do a few things manual import instead.
X
shimmer newsletter
Subscribe to our Simmer newsletter to receive the latest news and content from Simo Ahava right in your email inbox!
prerequisite
At this point, we’re assuming you already have a Google Tag Manager server container.If not, please check this video For information on how to get started with deployment, see .
If you want to write a score for your bot With first-party cookiesI’m also assuming you already have Mapped a custom domain to a server-side endpoint. Currently, the template is that’s all Create a same-site cookie.
Import client template
The first thing you need to do is Import client template into the server container.
Open this link In a new browser tab, then Save Page As template.tpl
The . file extension is .tpl
nothing else.
next, server container,refer templateClick new in the client template section.
of template editor opens. In the template editor, open it by clicking on the overflow he menu in the top right corner, import.
on the computer, template.tpl
Edit the downloaded file and import the file into your editor.
The template editor should change to reflect the contents of the reCAPTCHA v3 template.
Finally click blue keep Close the editor by clicking the button in the upper right corner of the template editor.
Now that you’ve imported the client template into your container, it’s time to configure it.
Generate a secret for reCAPTCHA v3
To use reCAPTCHA v3, site key and private key.
browse https://www.google.com/recaptcha/admin/create Register a new site.
It’s completely free!
Fill in the fields as suggested.Please make sure you have selected reCAPTCHA v3 As the service version, the domain that communicates with the API domain Department.This is what the configuration looks like https://www.teamsimmer.com/:
when you click sendyou will see your screen site key and your private key.
Please do not close this tab. You will need this information soon. The reCAPTCHA site is admin panel likewise.
Create a client in the server container
Go back to your Google Tag Manager server container and browse to: client Click to create a new client.
choose reCAPTCHA v3 client template from custom Client type category. You should now see a client ready for configuration.
Add key to client
Open the reCAPTCHA v3 site configuration tab.
Even if you accidentally close the tab, reCAPTCHA admin page,Selection site then click the Settings cog on the top bar.
copy and paste site key and the private key reCAPTCHA from the site config to the respective fields on the client.
Configure remaining settings
For example, if you want to write the bot score to a browser cookie to access the bot score on the GTM server (enhance other hits with information), Write the bot’s score to a cookie I checked the option.
If you also want to return the bot score in the HTTP response itself for client-side processing, Return bot score in HTTP response option.
if you conduct You can further customize your cookies by choosing your cookie preferences. nameits expiration time (in seconds), and that it is Http Only cookie.
Note!if you choose Http Only optional, cookies do not do Make it accessible using JavaScript in your browser.
In the screenshot below, the cookie name is set as follows: __r_b_s
I set it to session cookie (lifetime 0
), and I changed it to HttpOnly
cookie.
Once satisfied with the configuration, keep client.
Configure browser-side code
Your Google Tag Manager server container is now configured to listen for requests from both the reCAPTCHA library and the bot verification itself. Here’s how it works:
- the browser client-side library is used to generate verification token.
- Once the token is generated, the browser will send the token to Validation API Receive the bot score in response.
Both the library fetch and validation APIs are reCAPTCHA v3 A client added to the server container.
In this example, the browser-side code is Google Tag Manager web containerBut you can also run it directly in your page template or other linked JavaScript files.
Solution configuration 2 Custom HTML tag. The first one is script loaderis executed only once per page, the second is confirmation requestrun whenever an action occurs that you want to contribute to the bot score calculation.
Create a script loader
Simple to build custom template Load the reCAPTCHA v3 library if needed.
Before you start using tags variable In your Google Tag Manager container, configuration, setting for built-in variables.
Make sure to enable Container ID When HTML ID.
Then go to tagcreate a new custom HTML tag and copy and paste the following code into the tag.
<script>
(function() {
// Replace with the Site Key you got when registering the site for reCAPTCHA v3
var siteKey = 'aaaabbbbccccdddd';
// Replace with your server-side origin (just the https and domain name).
var serverSideOrigin = 'https://sgtm.mydomain.com';
var script = document.createElement('script');
script.src = serverSideOrigin + '/recaptcha/api.js?render=' + siteKey;
script.async = true;
script.addEventListener('load', function() {
window.google_tag_manager[{{Container ID}}].onHtmlSuccess({{HTML ID}});
});
document.head.appendChild(script);
})();
</script>
Update
siteKey
WhenserverSideOrigin
variables as instructed in the code.
This tag loads the library from the endpoint, adds a listener for script loading, and emits a signal. success Once the library is fully loaded.
Once done, Do not add triggers to this tag. Instead, keep Ignore the warning that the trigger is not set.
Create a validation tag
Then create a new custom HTML tag and copy and paste the following code.
<script>
(function() {
// Replace with the Site Key you got when registering the site for reCAPTCHA v3
var siteKey = 'aaaabbbbccccdddd';
// Replace with your server-side origin (just the https and domain name).
var serverSideOrigin = 'https://sgtm.mydomain.com';
// Replace this with the action type
// See: https://developers.google.com/recaptcha/docs/v3#actions
var action = 'page';
// The following callback is invoked with the bot score as a function argument.
// Feel free to change the dataLayer.push() to your liking.
// Note! The callback is only invoked if you've configured the Server container
// Client template to return a response back to the browser.
var callback = function(score) {
window.dataLayer.push({
event: 'recaptcha',
recaptchaScore: score
});
};
if (window.grecaptcha && typeof window.grecaptcha.ready === 'function') {
window.grecaptcha.ready(function() {
window.grecaptcha.execute(siteKey, {action: action}).then(function(token) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', serverSideOrigin + '/recaptcha?token=' + token, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
if (response.score) callback(response.score);
}
};
xhr.send();
});
});
}
})();
</script>
Update
siteKey
WhenserverSideOrigin
variables as instructed in the code.
Then go to Advanced settings -> Ordering of tagsset. Tag settings It will be the script loader created in the previous section.
Finally, set up this custom HTML tag to trigger whenever an interaction occurs that contributes to your bot score. These interactions are:
- Page load (
action
for examplepage
) - Form Submission (Settings
action
for examplesubmit
) - purchase (set
action
for examplepurchase
)
etc.Optionally use separate custom HTML tags for each action type or use a lookup table action
For example, dynamically change variable values based on trigger events.
test everything
After creating the script loader and also running the validation tag, enter preview mode on both the server and web containers.
Load the page (or do something else that should fire the validation tag).
The web container preview should fire both the script loader and the validation tag.
The server container preview initially shows the following requests: api.jswill be responded with a status code of 200
.
Then when I expand the validation API request to the server container (the request to the path recaptcha
), which can be expanded Outgoing HTTP request Check the response from the Google reCAPTCHA server.
This indicates that the validation request worked and returned a valid bot score.
Finally, the web container shows a new data layer message with the event name. recaptcha
(assuming you used the default callback) and recaptchaScore
A key containing the bot score for this particular request.
If you set a cookie, it will also appear in your browser’s cookie list.
Overview
Once you have the reCAPTCHA system up and running, you can use the bot score to selectively launch tags in either web or server containers.
again, __r_b_s
A cookie value to send with the server container tag, in case you want to add additional metadata about the user’s “bottness”. For example, it can be useful information in the GA4 custom dimension.
As you collect more and more bot score data, be sure to visit: reCAPTCHA management site See metrics about bot score distribution for your site visitors.If you set it up in earnest action
If you add variables to your request, you can also see the distribution split by action type.
Let me know what you think of this solution in the comments. It’s interesting to hear what use cases you have in mind for bot scores. block request or annotate them and why?