Search code examples
kenticorecaptcha-v3

How to implement Recaptcha V3 for Kentico?


We are going to apply the Recaptcha V3 for our sites. But Kentico is supporting the V2 only.

So are there any documents or guides to do it?

Or should we keep using the V2?

Thanks, Duc Huynh


Solution

  • Here is the Steps:

    1. Create a Class > Function for Validate ReCaptcha - see attached code;
    2. Call the Function Validate in this Event: viewBiz_OnBeforeSave once submitting a form;
    3. If Valid then Store the info

    You can use it via Ajax or Submit Directly.

    public static GooogleRecaptchaResponse ValidateGgRecaptchaToken(string responseToken, Action InvalidHandler) {
        if (string.IsNullOrEmpty(responseToken)) {
            EventLogProvider.LogInformation("ValidateGgRecaptchaToken", "Invalid", "Recaptcha was empty");
            InvalidHandler?.Invoke();
            return null;
        }
        string secretKey = SettingsKeyInfoProvider.GetValue(WebUtils.CaptchaSecretKeyName);
        var request = (HttpWebRequest) WebRequest.Create("https://www.google.com/recaptcha/api/siteverify");
    
        var postData = "response=" + responseToken;
        postData += "&secret=" + secretKey;
        var data = Encoding.ASCII.GetBytes(postData);
    
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;
    
        using(var stream = request.GetRequestStream()) {
            stream.Write(data, 0, data.Length);
        }
    
        var response = (HttpWebResponse) request.GetResponse();
    
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        var res = JsonConvert.DeserializeObject < GooogleRecaptchaResponse > (responseString);
        if (res == null || !res.success || res.score < 0.5) {
            EventLogProvider.LogInformation("ValidateGgRecaptchaToken", "Invalid", JsonConvert.SerializeObject(res));
            InvalidHandler?.Invoke();
        }
    
        return res;
    }