import time, requests
class UnlockAPI:
def __init__(self, key, base="https://unlock-api.com"):
self.key, self.base = key, base
def _post(self, method, **body):
r = requests.post(f"{self.base}/{method}", json={"clientKey": self.key, **body}, timeout=30).json()
if r.get("errorId"):
raise RuntimeError(r.get("errorCode")) # failed tasks are refunded
return r
def balance(self):
return self._post("getBalance")["balance"]
def solve(self, task, timeout=300):
task_id = self._post("createTask", task=task)["taskId"]
end = time.time() + timeout
while time.time() < end:
time.sleep(5)
r = self._post("getTaskResult", taskId=task_id)
if r["status"] == "ready":
return r["solution"]
raise TimeoutError(task_id)export class UnlockAPI {
constructor(key, base = "https://unlock-api.com") { this.key = key; this.base = base; }
async post(method, body = {}) {
const r = await fetch(`${this.base}/${method}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ clientKey: this.key, ...body }) }).then((x) => x.json());
if (r.errorId) throw new Error(r.errorCode); // failed tasks are refunded
return r;
}
async balance() { return (await this.post("getBalance")).balance; }
async solve(task, timeoutMs = 300_000) {
const { taskId } = await this.post("createTask", { task });
const end = Date.now() + timeoutMs;
while (Date.now() < end) {
await new Promise((r) => setTimeout(r, 5000));
const r = await this.post("getTaskResult", { taskId });
if (r.status === "ready") return r.solution;
}
throw new Error("timeout " + taskId);
}
}<?php
class UnlockAPI {
public function __construct(private string $key, private string $base = "https://unlock-api.com") {}
private function post(string $method, array $body = []): array {
$c = curl_init("$this->base/$method");
curl_setopt_array($c, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
CURLOPT_POSTFIELDS => json_encode(["clientKey" => $this->key] + $body)]);
$r = json_decode(curl_exec($c), true);
if (!empty($r["errorId"])) throw new RuntimeException($r["errorCode"]); // failed tasks are refunded
return $r;
}
public function balance(): float { return $this->post("getBalance")["balance"]; }
public function solve(array $task, int $timeout = 300): array {
$id = $this->post("createTask", ["task" => $task])["taskId"];
for ($end = time() + $timeout; time() < $end;) {
sleep(5);
$r = $this->post("getTaskResult", ["taskId" => $id]);
if ($r["status"] === "ready") return $r["solution"];
}
throw new RuntimeException("timeout $id");
}
}package unlockapi
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"time"
)
type Client struct{ Key, Base string }
func New(key string) *Client { return &Client{Key: key, Base: "https://unlock-api.com"} }
func (c *Client) post(method string, body map[string]any) (map[string]any, error) {
body["clientKey"] = c.Key
b, _ := json.Marshal(body)
res, err := http.Post(c.Base+"/"+method, "application/json", bytes.NewReader(b))
if err != nil {
return nil, err
}
defer res.Body.Close()
var r map[string]any
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
return nil, err
}
if id, _ := r["errorId"].(float64); id != 0 {
return nil, errors.New(r["errorCode"].(string)) // failed tasks are refunded
}
return r, nil
}
func (c *Client) Solve(task map[string]any, timeout time.Duration) (map[string]any, error) {
r, err := c.post("createTask", map[string]any{"task": task})
if err != nil {
return nil, err
}
id := r["taskId"]
for end := time.Now().Add(timeout); time.Now().Before(end); {
time.Sleep(5 * time.Second)
r, err := c.post("getTaskResult", map[string]any{"taskId": id})
if err != nil {
return nil, err
}
if r["status"] == "ready" {
return r["solution"].(map[string]any), nil
}
}
return nil, errors.New("timeout")
}import java.net.URI;
import java.net.http.*;
import java.util.regex.*;
/** UNLOCK API client with only the Java standard library (Java 11+). Tasks and solutions are JSON text. */
public class UnlockAPI {
private final String key, base;
private final HttpClient http = HttpClient.newHttpClient();
public UnlockAPI(String key) { this.key = key; this.base = "https://unlock-api.com"; }
/** POST {"clientKey": ..., fields} and return the reply. errorId 1 throws (failed tasks are refunded). */
private String post(String method, String fields) throws Exception {
String body = "{\"clientKey\":\"" + key + "\"" + (fields.isEmpty() ? "" : "," + fields) + "}";
var req = HttpRequest.newBuilder(URI.create(base + "/" + method))
.header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body)).build();
String r = http.send(req, HttpResponse.BodyHandlers.ofString()).body();
if (!"0".equals(field(r, "errorId"))) throw new RuntimeException(field(r, "errorCode"));
return r;
}
/** Value of a string or number field, or null */
public static String field(String json, String name) {
Matcher m = Pattern.compile("\"" + Pattern.quote(name) + "\"\\s*:\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|(-?[0-9.]+))").matcher(json);
return m.find() ? (m.group(1) != null ? m.group(1) : m.group(2)) : null;
}
/** An object field as JSON text, or null */
public static String object(String json, String name) {
int i = json.indexOf("\"" + name + "\"");
if (i < 0 || (i = json.indexOf('{', i)) < 0) return null;
boolean inString = false;
for (int j = i, depth = 0; j < json.length(); j++) {
char c = json.charAt(j);
if (inString) { if (c == '\\') j++; else if (c == '"') inString = false; }
else if (c == '"') inString = true;
else if (c == '{') depth++;
else if (c == '}' && --depth == 0) return json.substring(i, j + 1);
}
return null;
}
public double balance() throws Exception {
return Double.parseDouble(field(post("getBalance", ""), "balance"));
}
/** task: the task object as JSON text. Returns the solution object as JSON text. */
public String solve(String task) throws Exception {
String id = field(post("createTask", "\"task\":" + task), "taskId");
for (long end = System.currentTimeMillis() + 300_000; System.currentTimeMillis() < end;) {
Thread.sleep(5000);
String r = post("getTaskResult", "\"taskId\":" + id);
if ("ready".equals(field(r, "status"))) return object(r, "solution");
}
throw new RuntimeException("timeout " + id);
}
}using System.Net.Http.Json;
using System.Text.Json.Nodes;
public class UnlockApi(string key, string baseUrl = "https://unlock-api.com")
{
private readonly HttpClient http = new();
private async Task<JsonNode> Post(string method, JsonObject body)
{
body["clientKey"] = key;
var res = await http.PostAsJsonAsync($"{baseUrl}/{method}", body);
var r = JsonNode.Parse(await res.Content.ReadAsStringAsync())!;
if ((int?)r["errorId"] != 0) throw new Exception((string?)r["errorCode"]); // failed tasks are refunded
return r;
}
public async Task<JsonNode> Solve(JsonObject task)
{
var id = (long)(await Post("createTask", new JsonObject { ["task"] = task }))["taskId"]!;
var end = DateTime.UtcNow.AddMinutes(5);
while (DateTime.UtcNow < end)
{
await Task.Delay(5000);
var r = await Post("getTaskResult", new JsonObject { ["taskId"] = id });
if ((string?)r["status"] == "ready") return r["solution"]!;
}
throw new TimeoutException(id.ToString());
}
}使い方
api = UnlockAPI("YOUR_API_KEY")
sol = api.solve({"type": "TurnstileTaskProxyless", "websiteURL": "https://example.com", "websiteKey": "0x4AAAA..."})
print(sol["token"])const api = new UnlockAPI("YOUR_API_KEY");
const sol = await api.solve({ type: "RecaptchaV2TaskProxyless", websiteURL: "https://example.com", websiteKey: "6Lc..." });
console.log(sol.gRecaptchaResponse);$api = new UnlockAPI("YOUR_API_KEY");
$sol = $api->solve(["type" => "HCaptchaTaskProxyless", "websiteURL" => "https://example.com", "websiteKey" => "a5f74b19-..."]);
echo $sol["gRecaptchaResponse"];api := unlockapi.New("YOUR_API_KEY")
sol, err := api.Solve(map[string]any{"type": "TurnstileTaskProxyless", "websiteURL": "https://example.com", "websiteKey": "0x4AAAA..."}, 5*time.Minute)
fmt.Println(sol["token"], err)var api = new UnlockAPI("YOUR_API_KEY");
String solution = api.solve("{\"type\":\"RecaptchaV2TaskProxyless\",\"websiteURL\":\"https://example.com\",\"websiteKey\":\"6Lc...\"}");
System.out.println(UnlockAPI.field(solution, "gRecaptchaResponse"));using System.Text.Json.Nodes;
var api = new UnlockApi("YOUR_API_KEY");
var sol = await api.Solve(new JsonObject { ["type"] = "TurnstileTaskProxyless", ["websiteURL"] = "https://example.com", ["websiteKey"] = "0x4AAAA..." });
Console.WriteLine(sol["token"]);既存のライブラリを使う
多くのソルバーライブラリはサーバーアドレスを変更できます。unlock-api.com(フォームAPIの場合はhttps://unlock-api.com/in.php)に設定し、UNLOCK APIのキーを使ってください。タスク名と回答は同じです。