Skip to content

Instantly share code, notes, and snippets.

@faridprogrammer
Last active August 24, 2019 08:26
Show Gist options
  • Save faridprogrammer/61f510ed673e0846669100dd88e59adf to your computer and use it in GitHub Desktop.
Save faridprogrammer/61f510ed673e0846669100dd88e59adf to your computer and use it in GitHub Desktop.
Google recaptch validator and code snippets

Google Recaptcha Snippets

Reference Parts

Place this link in HEAD tag of index.html

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Angular Parts

  1. Declare global variable

declare var grecaptcha: any;

  1. Initiate in ngAfterInit

     ngAfterViewInit(): void {
     // Export reCAPTCHACallback to global scope.
     window['reCAPTCHACallback2'] = this.reCAPTCHACallback2.bind(this);
    
     this.widgetId = grecaptcha.render('register-captcha', {
         'sitekey': '6Lf3qKcUAAAAALK8wDotoLQ5no2xc_zeWP1uoLee',
         'callback': 'reCAPTCHACallback2'
     });
     // in component class
     reCAPTCHACallback2(response): void {
         this.model.captchaResponse = response;
     }
    

C# class for server side validation

public class ReCaptchaClass
{
    public static string Validate(string EncodedResponse)
    {
        var client = new System.Net.WebClient();

        string PrivateKey = "PRIVATE KEY";

        var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, EncodedResponse));

        var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ReCaptchaClass>(GoogleReply);

        return captchaResponse.Success.ToLower();
    }

    [JsonProperty("success")]
    public string Success
    {
        get { return m_Success; }
        set { m_Success = value; }
    }

    private string m_Success;
    [JsonProperty("error-codes")]
    public List<string> ErrorCodes
    {
        get { return m_ErrorCodes; }
        set { m_ErrorCodes = value; }
    }


    private List<string> m_ErrorCodes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment