Skip to the content

Adding Google reCAPTCHA in D365 Marketing Forms Part 2

Adding Google reCAPTCHA in D365 Marketing Forms Part 2

This blog is about adding the Google reCAPTCHA on the Marketing forms. The first part of this blog is in here: https://www.oasystems.co.nz/blogs/posts/2019/june/adding-google-recaptcha-in-d365-marketing-forms/

Once the reCAPTCHA has been setup on the form, we need to do some server-side validation to validate the user. When the user ticks the box, a response token will be sent the user. We then need to validate this token against Google’s reCAPTCHA verification system.

Going back to the onloadCallback function we previously had, we can state a callback function that will be triggered once the response token has been received. In this example, the function 'recaptchaCallback' will be called.

var onloadCallback = function() {

                setTimeout(function(){

                    grecaptcha.render('html_element', {

                                      'sitekey' : 'your_site_key',

                                      'callback' : 'recaptchaCallback'

                                    });

                    $("#submitbutton").attr("disabled", true);

                }, 3000);

              };

 

In this callback method, we will now send a POST message to Google’s verification API for reCAPTCHA. You need to send it to the URL below with the required parameters.

To know more how this works, please see Google’s article in here: https://developers.google.com/recaptcha/docs/verify

For our example, we created a custom Umbraco API and the server will then send the POST message to Google and it will give us back a ‘Success’ message once the token has been verified. We did this as we did not want the secret to be exposed on the JavaScript code. To know how to create a custom Umbraco API, see this article: https://www.jondjones.com/learn-umbraco-cms/umbraco-7-tutorials/umbraco-web-api/how-to-create-a-web-api-in-umbraco-in-less-than-5-minutes/ .

Our custom Umbraco controller: GoogleRecaptchaApiController

[Route("api/[controller]")]

    public class GoogleRecaptchaApiController : UmbracoApiController

    {

        [HttpGet]

        public string Validate(string token)

        {

            if (String.IsNullOrWhiteSpace(token))

                return "Token is null";

            var secretKey = System.Configuration.ConfigurationManager.AppSettings["RecaptchaSecretKey"];

            if (String.IsNullOrWhiteSpace(secretKey))

                return "Secret Key is null";

            var url = string.Format(

                        "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",

                        secretKey,

                        token);

            var isSuccess = false;

            var errorCodes = new List<string>();

            using (var client = new WebClient())

            {

                var response = client.DownloadString(url);

                JObject responseParsed = JObject.Parse(response);

                //Get Success Status

                JToken sucessToken;

                var sucessFound = responseParsed.TryGetValue("success", out sucessToken);

                if (sucessFound)

                {

                    isSuccess = sucessToken.Value<bool>();

                }

                //Get Error codes

                JToken errorsToken;

                var errorsFound = responseParsed.TryGetValue("error-codes", out errorsToken);

                if (errorsFound)

                {

                    var errorsChildren = errorsToken.Children();

                    foreach (var child in errorsChildren)

                    {

                        errorCodes.Add(child.Value<string>());

                    }

                }

                else

                {

                    errorCodes.Add("unknown-error");

                }

            }

            if (!isSuccess)

            {

                var compiledErrors = ",";

 

                foreach (var code in errorCodes)

                {

                    //TODO: Use Dictionary Keys to return error message text

                    compiledErrors += ", " + code;

                }

                compiledErrors = compiledErrors.Replace(",,", "");

 

                //Add errors to Form Model

                var errorMsg = string.Format("Fail: {0}", compiledErrors);

 

                return errorMsg;

            }

            return "Success";

        }

    }

 

To summarize, our overall client-side code looks like this including the marketing form and the reCAPTCHA script. Note that we moved the reCAPTCHA script on the Umbraco side, rather than within the D365 Marketing Form.

To talk to the team at OA Systems about how you can use the feature of Dynamics Marketing connect with up:

Need more Information?

Check our Case Studies for examples of how we've helped various companies realise the benefits of Customer Engagement...

OA Systems did a brilliant job of updating our Microsoft CRM4.0 to Dynamics 365. The process was smooth from start to finish and they completed on time and on budget.
Highly recommended.

Brendon Reid, Managing Director, Automation Associates Ltd

The OA Systems development team has a really detailed understanding of every layer of our business

Ayla Hutton, Technology and Projects Manager at Safety ‘n Action

OA Systems

Building C
Level 1/95 Ascot Avenue
Greenlane
Auckland 1051

Careers at OA

We are always looking for people who are excellent and passionate at what they do to join our team. If this sounds like you then we'd love to hear from you!

Need some help?

Customer Engagement can help improve customer relations, increase customer revenues, maximise cross and up-selling, create better communications and optimise your marketing.  Get in touch for a chat about how Customer Engagement 365 can help you...