Marketing Automation, Salesforce Marketing Cloud

Add reCAPTCHA to landing page form in salesforce marketing cloud

Last time we implemented recaptcha for this blog that is build on WordPress CMS. You can read the article here. Today I will show you, how to implement same recaptcha from google but on Salesforce Marketing Cloud Pages.

To register your cloud page, you will need to register each domain separately, visit  google recaptcha and follow the registration process there.

When all done you will receive two keys:

  • site key – for client side integration
  • secret key – for backend integration

Cloud page

Somebody likes to split data processing page to two separate pages but you can also do the form and processing in one cloud page. What I am used to to is to create both form and data processing on one page and after the form is processed I tend to redirect customer to thank you page. This is due to that page to which you send form to can be refreshed and form is resubmitted.

“Front end” part of cloud page

On the front end we build our form that we want to protect from spam. When this has been done, we need to hook recaptcha into our form. In the official documentation is explained how to add recaptcha with different option. We will choose the very basic one that will suffice for our needs.

  • Load the JavaScript API.
 <script src="https://www.google.com/recaptcha/api.js"></script>
  • Add a callback function to handle the token.
 <script>   function onSubmit(token) {     document.getElementById("form").submit();   } </script>
  • Add attributes to your html button.
  <button  class="g-recaptcha button" 
        data-sitekey="SITE_KET" 
        data-callback="onSubmit" 
        data-action="submit">

DO NOT USE ANY: of input type=”submit” or add role=”submit” or add class=”submit” as it cause recaptcha not trigger in this setup

“Back end” part of cloud page

As back end we will use combination of SSJS and AMPScript to handle submitted form.

AMPScript part to check if the request is POST so we do not trigger this section when we send data via GET request. And also we collect our form data and with it also the recaptcha token that we will validate with google API.

IF NOT EMPTY(@email) AND @request == "POST" THEN
    /* Retrieve recaptcha */
    SET @recaptchaResp = RequestParameter("g-recaptcha-response")
    
    /* no recaptcha */
    IF EMPTY(@recaptchaResp) THEN Redirect(CloudPagesURL(@errorPage)) ENDIF
]%%
<script runat="server">
    var error = false
    //validate recaptcha
    if ( !validateRecaptcha( Variable.GetValue( "@recaptchaResp" ) ) ) Redirect( Variable.GetValue( "@errorPageUrl" ), true);
    //do something in case we have valid response
   	//after do not forget to redirect customer do thank you page so the form will not be triggered multiple times
</script>

You can notice we call function validateRecaptcha that its function is to send post request to google API. You can read the documentation that will explain the server side validation of the recaptcha token

var validateRecaptcha =  function (token){
        try{
                var req = new Script.Util.HttpRequest('https://www.google.com/recaptcha/api/siteverify');
                req.emptyContentHandling = 0;
                req.retries = 2;
                req.continueOnError = true;
                req.contentType = "Application/x-www-form-urlencoded";
              
                req.method = "POST";
                req.postData = 'secret=YOUR_SECRET&response=' + token + '&remoteip=' + Platform.Request.ClientIP;

                var resp = req.send();


                var contentObj = Platform.Function.ParseJSON( String( resp.content ) );

                
                if ( resp.statusCode != 200 && !contentObj.success ) return false
        }catch(e){
  	        //log your error somewhere if needed for debugging
            return false
        }
        return true
    }

Same reCAPTCHA validation but in AMPScript

%%[ 
/* reCaptcha verification upon submission */

SET @Token = RequestParameter("g-recaptcha-response") 
SET @Secret = " <secret>"
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
     // good human
ELSE
   // bad robot

ENDIF

]%%

API Request

API request are made to URL: https://www.google.com/recaptcha/api/siteverify METHOD: POST

POST ParameterDescription
secretRequired. The shared key between your site and reCAPTCHA.
responseRequired. The user response token provided by the reCAPTCHA client-side integration on your site.
remoteipOptional. The user’s IP address.
Parameters for google recaptcha validation API

API response

Response is retrieved as json object and can look something like:

{  
  "success": true|false,  
  "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)  
  "hostname": string,         // the hostname of the site where the reCAPTCHA was solved 
  "error-codes": [...]        // optional
}

If all is correct you should be able to see floating recaptcha thumbnail on the bottom of your page. Next you can watch recaptcha do the work for you by looking at statistics in the admin console.

Recaptcha admin view

Oh hi there 👋
I have a FREE e-book for you.

Sign up now to get an in-depth analysis of Adobe and Salesforce Marketing Clouds!

We don’t spam! Read our privacy policy for more info.

Marcel Szimonisz
Marcel Szimonisz
MarTech consultant As a marketing automation consultant, I specialize in solving problems, automating processes, and driving innovation in my clients' marketing platforms.

I hold certifications in Adobe Campaign v6 (3x certified) and Salesforce Marketing Cloud (5x certified).

Additionally, I serve as a community advisor for Adobe Campaign, offering expert insights and guidance.

In addition to my professional pursuits, I also enjoy exploring various programming languages, CMSs, and frameworks, further enhancing my technical expertise and staying at the forefront of industry advancements.
Take a look at our subscription offering in case you are looking for a Marketing Automation Consultant.

Leave a comment

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

Similar posts that you may find useful

Adobe Campaign Classic tips
ACC Tips & Tricks, Adobe Campaign, Marketing Automation

Troubleshooting web applications

1 minute read

When building any web application (webapp), you may have experienced a syntax error on, for example, line 200. This can be perplexing, especially when your custom JavaScript code does not even have 200 lines. Why is that? The reason for this discrepancy is that the web applications you create in the visual editor are compiled […]

Continue reading
Salesforce Marketing Cloud Tips
Marketing Automation, Salesforce Marketing Cloud, SFMC Tips & Tricks

Cannot add attributes to data extension

less than a minute read

Occasionally, as a Salesforce Marketing Cloud administrator, lurker, practitioner, or bystander, you encounter a seemingly simple yet potentially time-consuming task—adding attributes to a data extension. While it may sound straightforward, the process is not always as simple as it appears. When adding or editing data extension attributes in Salesforce Marketing Cloud, you may face a […]

Continue reading
Salesforce Marketing Cloud Tips
Marketing Automation, Salesforce Marketing Cloud, SFMC Tips & Tricks

How to utilize polyfill functions in SFMC

1 minute read

Development in Salesforce Marketing Cloud’s SSJS can be very restrictive, especially when you’re already familiar with the latest EcmaScript6 JavaScript features. We can’t use object spreading or curly bracket functions {}=>() and many, many more. However, we can introduce certain very helpful functions that don’t exist in older versions of JavaScript. The way we do […]

Continue reading
Adobe Campaign Classic OOP concepts in ES5
ACC Tips & Tricks, Adobe Campaign, Marketing Automation

Using OOP techniques in ES5: A Guide

3 minutes read

In this blog I will be exploring object-oriented programming (OOP) and Adobe Campaign Classic in ES5. As you may already know, Adobe Campaign Classic relies on ES5, the version of JavaScript specifically used by the platform. In ES5, there are a few limitations in terms of what you cannot do compared to newer versions of […]

Continue reading
SFMC tips and tricks
Marketing Automation, Salesforce Marketing Cloud, SFMC Tips & Tricks

SFMC TIP – Double quotes in AMPScript break email template

less than a minute read

Very recently I have found that when I add any AMPScript function to eg. button URL field SFMC will just ignore everything that follows after the first occurrence of the double quote. Simple fix is to use single quotes instead.

Continue reading