ข้ามไปยังเนื้อหา
สถานะแดชบอร์ด

โค้ดตัวอย่าง

หน้านี้แปลด้วยเครื่องจากเวอร์ชันภาษาจีน อาจมีข้อผิดพลาด โปรดยึดเวอร์ชันภาษาจีนเป็นหลัก

สภาพแวดล้อมที่ใช้งาน: .NET 6 ขึ้นไป ใช้เฉพาะไลบรารีมาตรฐาน (HttpClient, System.Text.Json)

dotnet new console -o YesCaptchaDemo
cd YesCaptchaDemo
# replace Program.cs with the code below
export YESCAPTCHA_CLIENT_KEY=your_client_key
dotnet run
Program.cs
// YesCaptcha C# sample (.NET 6+): check the balance, then solve a reCAPTCHA v2.
// Run: dotnet new console -o YesCaptchaDemo, replace Program.cs with this file, set YESCAPTCHA_CLIENT_KEY, then dotnet run
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
class Program
{
const string Api = "https://api.yescaptcha.com";
static readonly HttpClient Http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
static readonly string ClientKey = Environment.GetEnvironmentVariable("YESCAPTCHA_CLIENT_KEY") ?? "";
static async Task<JsonNode> Call(string method, JsonObject payload)
{
payload["clientKey"] = ClientKey;
var res = await Http.PostAsJsonAsync($"{Api}/{method}", payload);
var data = JsonNode.Parse(await res.Content.ReadAsStringAsync())!;
if ((int?)data["errorId"] != 0)
throw new Exception($"{data["errorCode"]}: {data["errorDescription"]}");
return data;
}
static async Task<JsonNode> Solve(JsonObject task)
{
var created = await Call("createTask", new JsonObject { ["task"] = task });
if ((string?)created["status"] == "ready") return created["solution"]!; // synchronous types
var taskId = (string)created["taskId"]!;
for (var i = 0; i < 36; i++) // poll every 5 seconds, for up to about 3 minutes
{
await Task.Delay(5000);
var result = await Call("getTaskResult", new JsonObject { ["taskId"] = taskId });
if ((string?)result["status"] == "ready") return result["solution"]!;
}
throw new TimeoutException(taskId);
}
static async Task Main()
{
var balance = await Call("getBalance", new JsonObject());
Console.WriteLine($"balance (points): {balance["balance"]}");
var solution = await Solve(new JsonObject
{
["type"] = "NoCaptchaTaskProxyless",
["websiteURL"] = "https://www.google.com/recaptcha/api2/demo",
["websiteKey"] = "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
});
Console.WriteLine(solution["gRecaptchaResponse"]);
}
}

หากเปลี่ยนเป็นประเภทงานอื่น ให้แก้เฉพาะออบเจ็กต์งานใน Solve โดยดูฟิลด์ได้ในหน้า ประเภทงาน แต่ละหน้า ประเภทแบบซิงโครนัส (การจดจำภาพ, ImageToTextTaskOcrBase) จะคืนผลลัพธ์ทันทีใน createTask ซึ่ง Solve รองรับกรณีนี้อยู่แล้ว