How to implement Google reCAPTCHA on Salesforce Marketing Cloud pages with forms

How to implement Google reCAPTCHA on Salesforce Marketing Cloud pages with forms

This article explains how to successfully implement Google reCAPTCHA v2 (invisible) on Salesforce Marketing Cloud forms.

Why do it?

Because security is everything when it comes to processing customer’s data.

Google reCAPTCHA v2 (invisible) provides a seamless security layer against abusive form submissions and spam attacks.

You may notice that there is also a version 3 of reCAPTCHA. But for our use case, where a single form needs to be submitted by the customer, v2 is more than sufficient.

Before we start

As obvious as it seems, in order to start implementing Google reCAPTCHA, we need to create a Google account.

Once you have it, please proceed to the official reCAPTCHA page and register a new website.

Add your Marketing Cloud domain in the domain list and choose reCAPTCHA version 2 (invisible badge) as the reCAPTCHA type.

After the registration is complete, you will be presented with 2 access keys:
site key and secret key. Please make sure to take note them down for later use.

How does it work?

In order to successfully implement reCAPTCHA, we need to validate it twice: first on the front-end (the form page) and then the back-end (the form handler page).

Here is how the flow works:

  1. Customer clicks on the submit button, which triggers reCAPTCHA, instead of classical form submission.
  2. If the behaviour wasn’t suspicious, reCAPTCHA sends a request for a token key from Google servers, otherwise, a verification question is displayed and only if answered correctly reCAPTCHA sends for a token.
  3. Once the token key is received, the form submission can proceed and the token is sent along with other values to the Form Handler page.
  4. The Form Handler receives the token and sends another request to the Google servers to verify that the token was generated within the last couple of minutes coming from your domain.
  5. If successful, the Form Handler page can proceed, otherwise an error message is displayed or sent as a response.

Now, let’s have a look how to make it work using HTML and JavaScript.

Form page

The implementation is simple but requires some knowledge of HTML and plain JavaScript to be executed.

We first need to call the reCAPTCHA script in the header, then put a div tag somewhere in our form with a specific class and data attributes.

Please make sure to replace {{ YOUR SITE KEY }} in the code below with the site key you received on the reCAPTCHA website earlier, and {{ FORM HANDLER URL }} with your Marketing Cloud Form Handler page URL.

The JavaScript below will prevent the form to be submitted unless reCAPTCHA is a pass and the token is received from Google servers.

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
    <form id="form" action="{{ FORM HANDLER URL }}" method="post">
        <label>Email: </label>
        <input type="email" name="EmailAddress">
        <div 
            class="g-recaptcha" 
            data-sitekey="{{ YOUR SITE KEY }}" 
            data-callback="grecaptchaCallback" 
            data-size="invisible"
        ></div>
        <br>
        <button>Send</button>
    </form>
    <script>
        var form = document.getElementById('form');

        form.addEventListener('submit', grecaptchaValidate);

        function grecaptchaCallback() {
            return new Promise(function (resolve, reject) {
                if (grecaptcha.getResponse() !== '') {
                    form.submit();
                }
                grecaptcha.reset();
            })
        }

        function grecaptchaValidate(e) {
            e.preventDefault();
            grecaptcha.execute();
        }
    </script>
</body>
</html>

Form Handler page

When it comes to the Form Handler, you have a choice of language: AMPscript or server-side JavaScript. One is not better than the other, but please make sure to account for the error handling with the method of your choice.

Please make sure to replace {{ YOUR SECRET KEY }} in the code below with the site key you received on the reCAPTCHA website earlier.

AMPscript solution

%%[
	
    SET @Token = RequestParameter("g-recaptcha-response")

    SET @Secret = "{{ YOUR SECRET KEY }}"
    SET @ContentType = "application/x-www-form-urlencoded"
    SET @Endpoint = "https://www.google.com/recaptcha/api/siteverify"
    SET @Payload = CONCAT("secret=", @Secret, "&response=", @Token)

    SET @Request = HTTPPost(@Endpoint, @ContentType, @Payload, @Response)
	
	IF @Request == 200 AND indexOf(@Response, '"success": true') > 0 THEN
	
		/// DO SOMETHING
	
	ELSE
		OUTPUTLINE(CONCAT("Wrong reCAPTCHA: ", @Response))
	ENDIF

]%%

Server-side JavaScript solution

<script runat="server">
	
    Platform.Load("core", "1.1.1");

    try {

        var g_recaptcha_response = Request.GetFormField("g-recaptcha-response");
        var secret = "{{ YOUR SECRET KEY }}";
        var payload = "secret=" + secret + "&response=" + g_recaptcha_response;
		var contentType = "application/x-www-form-urlencoded";
		var endpoint = "https://www.google.com/recaptcha/api/siteverify";
        var req = HTTP.Post(endpoint, contentType, payload);

        if (req.StatusCode == 200) {

            var resp = Platform.Function.ParseJSON(String(req.Response));

            if (!resp.success) throw "Wrong reCAPTCHA";

        } else {
            throw "reCAPTCHA API error";
        }

        /// DO SOMETHING

        Write(Stringify(resp));

    } catch (error) {
        Write(Stringify({ status: "Error", message: error }));
    }

</script>

Changing the language

In order to change the language, simply add a language code parameter in source attribute of the script tag.

<script src="https://www.google.com/recaptcha/api.js?hl={{ LANGUAGE CODE }}"></script>
<!-- Example: https://www.google.com/recaptcha/api.js?hl=en -->

Have I missed anything?

Please poke me with a sharp comment below or use theΒ contact form.

Pay me a coffee

Want to say thanks? Pay me a coffee! Remember, I turn coffee into code.

  1. Can we implement reCAPTCHA for Smart Capture form? If yes where should I add the div tag in the Smart Capture block.

  2. Firstly thank for creating such useful blog especially to create a level of security using reCaptcha.

    I was successfully able to implement to for my personal domain [sfmc-ninja.tech].
    But what is the domain to be used for the cloudpage hosted on SFMC? In this step [https://i.imgur.com/S81cvB0.png]

    I get the error as “ERROR for site owner:
    Invalid domain for site key”

  3. The short answer is yes, but no πŸ™‚ You can use it, but you will not have a server-side validation for your reCAPTCHA.

Leave a Reply

Your email address will not be published. Required fields are marked *

Salesforce Marketing Cloud
Up Next:

How to build HTML forms without Smart Capture in Salesforce Marketing Cloud

How to build HTML forms without Smart Capture in Salesforce Marketing Cloud