Adding recaptcha to Salesforce Marketing Cloud Page

in  Marketing Automation, Salesforce Marketing Cloud
3 minutes read

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
    }

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
in  Building the blog, Wordpress

Adding recaptcha v3 to wordpress page

4 minutes read

As owner of a blog that is around for a while with any traffic, you will find sooner or later annoying amount of spam comments taking your blog by storm. If the akismet is not your cup of tea and you do not want to pay for possible license (commercial use), then I can show […]

Continue reading