此页内容

【C#】 ReCaptchaV2协议提交

captchaRun

371字约1分钟

2024-05-21

重要

这段示例代码在 .NET6 正常工作,但其中的特性可能无法在旧版本的.NET上工作

需要安装Newtonsoft.Json依赖

dotnet add package Newtonsoft.Json
using Newtonsoft.Json.Linq;

class Program
{
    // 你的token
    private const string token = "xxxxxxx";
    // 任务参数
    private const string websiteKey = "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-";
    private const string websiteURL = "https://www.google.com/recaptcha/api2/demo";
    private const string task_type = "ReCaptchaV2";

    // API 地址
    private const string CREATE_TASK_ENDPOINT = "https://api.captcha.run/v2/tasks";
    private const string GET_TASK_ENDPOINT = "https://api.captcha.run/v2/tasks/{0}";

    static void Main(string[] args)
    {
        RunAsync().GetAwaiter().GetResult();
    }

    static async Task RunAsync()
    {
        string taskId = await CreateTask();
        Console.WriteLine("创建任务: " + taskId);
        if (!string.IsNullOrEmpty(taskId))
        {
            string response = await GetResponse(taskId);
            Console.WriteLine("识别结果: " + response);
            if (!string.IsNullOrEmpty(response))
            {
                string result = await VerifyWebsite(response);
                Console.WriteLine("验证结果: " + result);
            }
        }
    }

    static async Task<string> CreateTask()
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            var values = new JObject { { "captchaType", task_type }, { "siteKey", websiteKey }, { "siteReferer", websiteURL } };
            var content = new StringContent(values.ToString(), System.Text.Encoding.UTF8, "application/json");
            try
            {
                HttpResponseMessage response = await client.PostAsync(CREATE_TASK_ENDPOINT, content);
                response.EnsureSuccessStatusCode();
                string resultContent = await response.Content.ReadAsStringAsync();
                JObject result = JObject.Parse(resultContent);
                return (string)result["taskId"];
            }
            catch (Exception e)
            {
                Console.WriteLine("创建任务出错: " + e);
                return null;
            }
        }
    }

    static async Task<string> GetResponse(string taskId)
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            int timeout = 120;
            int interval = 3;

            DateTime startTime = DateTime.Now;
            while ((DateTime.Now - startTime).TotalSeconds < timeout)
            {
                try
                {
                    HttpResponseMessage response = await client.GetAsync(String.Format(GET_TASK_ENDPOINT, taskId));
                    response.EnsureSuccessStatusCode();
                    string resultContent = await response.Content.ReadAsStringAsync();
                    JObject result = JObject.Parse(resultContent);
                    JObject solution = (JObject)result["response"];
                    if (solution != null && solution["gRecaptchaResponse"] != null)
                    {
                        return (string)solution["gRecaptchaResponse"];
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(interval));
                }
                catch (Exception e)
                {
                    Console.WriteLine("获取任务结果出错: " + e);
                    Thread.Sleep(TimeSpan.FromSeconds(interval));
                }
            }

            Console.WriteLine("验证码识别超时!");
            return null;
        }
    }

    static async Task<string> VerifyWebsite(string response)
    {
        using (HttpClient client = new HttpClient())
        {
            var values = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("g-recaptcha-response", response) });
            try
            {
                HttpResponseMessage r = await client.PostAsync(websiteURL, values);
                r.EnsureSuccessStatusCode();
                if (r.IsSuccessStatusCode)
                {
                    return await r.Content.ReadAsStringAsync();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("验证网站出错: " + e);
            }
            return null;
        }
    }
}