Skip to content

Instantly share code, notes, and snippets.

@johnboker johnboker/ReCaptcha.cs
Last active Apr 4, 2016

Embed
What would you like to do?
Verify ReCaptcha responses server-side.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
namespace Antiyes
{
public class ReCaptcha
{
public static async System.Threading.Tasks.Task<SiteVerifyResponse> VerifyUserResponse(string secret, string response,
string remoteip = null, bool throwOnError = false, string verifyUrl = "https://www.google.com/recaptcha/api/siteverify")
{
using (var client = new HttpClient())
{
var values = new Dictionary<string, string> { { "secret", secret }, { "response", response } };
if (remoteip != null)
{
values.Add("remoteip", remoteip);
}
var postData = new FormUrlEncodedContent(values);
var postResponse = await client.PostAsync(verifyUrl, postData);
var responseString = await postResponse.Content.ReadAsStringAsync();
var verifyResponse = JsonConvert.DeserializeObject<SiteVerifyResponse>(responseString);
if (throwOnError)
{
if (verifyResponse.Errors != null && verifyResponse.Errors.Length > 0)
{
var errors = string.Join(", ", verifyResponse.Errors.Select(a => ErrorCodes[a]));
throw new ReCaptchaVerifyException(errors);
}
}
return verifyResponse;
}
}
public static Dictionary<string, string> ErrorCodes => new Dictionary<string, string> {
{ "missing-input-secret","The secret parameter is missing."},
{ "invalid-input-secret","The secret parameter is invalid or malformed."},
{ "missing-input-response","The response parameter is missing."},
{ "invalid-input-response", "The response parameter is invalid or malformed."}
};
public class ReCaptchaVerifyException : Exception
{
public ReCaptchaVerifyException() { }
public ReCaptchaVerifyException(string message) : base(message) { }
public ReCaptchaVerifyException(string message, Exception inner) : base(message, inner) { }
}
public class SiteVerifyResponse
{
[JsonProperty(PropertyName = "success")]
public bool Success { get; set; }
[JsonProperty(PropertyName = "challenge_ts")]
public DateTime ChallengeTimestamp { get; set; }
[JsonProperty(PropertyName = "hostname")]
public string Hostname { get; set; }
[JsonProperty(PropertyName = "error-codes")]
public string[] Errors { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.