NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

AWS WAF and other CAPTCHAs

How to solve CAPTCHAs from C++

Desktop automation tools, game launchers and embedded test rigs are often written in C++. This guide adds CAPTCHA tasks to such a program with two well known libraries: libcurl for HTTP and nlohmann/json for JSON.

What you build

A single class, GateClient, with one public method: solve(task, interval). It posts the task to /createTask, polls /getTaskResult and returns the solution as a JSON object, throwing an exception that carries the API's error code when something goes wrong. The task is a nlohmann::json object, so every supported type works with the same code.

Libraries and build

libcurl is available from every package manager (libcurl4-openssl-dev on Debian and Ubuntu, curl in vcpkg or Homebrew). nlohmann/json is a header only library, installable as nlohmann-json3-dev, through vcpkg, or by copying json.hpp into your project. A minimal CMake setup:

cmake_minimum_required(VERSION 3.16)
project(gate_demo CXX)
set(CMAKE_CXX_STANDARD 17)
find_package(CURL REQUIRED)
find_package(nlohmann_json 3 REQUIRED)
add_executable(gate_demo main.cpp)
target_link_libraries(gate_demo PRIVATE CURL::libcurl nlohmann_json::nlohmann_json)

Package names can differ slightly between platforms; check your package manager if find_package does not locate them.

Safe handles with RAII

libcurl's C API asks you to free every easy handle and header list. Wrapping them in std::unique_ptr with custom deleters means an exception thrown halfway through a request cannot leak them.

#include <curl/curl.h>
#include <nlohmann/json.hpp>
#include <chrono>
#include <memory>
#include <stdexcept>
#include <string>
#include <thread>

using json = nlohmann::json;
using EasyPtr = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>;
using ListPtr = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>;

struct ApiError : std::runtime_error {
    std::string code;
    ApiError(std::string c, const std::string& msg)
        : std::runtime_error(c + ": " + msg), code(std::move(c)) {}
};

static size_t collect(char* data, size_t size, size_t n, void* out) {
    static_cast<std::string*>(out)->append(data, size * n);
    return size * n;
}

The collect callback appends each chunk of the response body to a std::string. libcurl may call it many times for one response, so it must append rather than assign.

The client class

class GateClient {
public:
    explicit GateClient(std::string key) : key_(std::move(key)) {}

    json solve(json task, std::chrono::seconds every = std::chrono::seconds(3)) {
        json made = call("createTask", {{"task", std::move(task)}});
        const std::string id = made.at("taskId").get<std::string>();
        const auto stop = std::chrono::steady_clock::now() + std::chrono::seconds(125);
        while (std::chrono::steady_clock::now() < stop) {
            std::this_thread::sleep_for(every);
            json r = call("getTaskResult", {{"taskId", id}});
            const std::string st = r.value("status", "");
            if (st == "ready") return r.at("solution");
            if (st == "failed") throw ApiError("TASK_FAILED", "task " + id + " failed, not charged");
        }
        throw ApiError("TIMEOUT", "task " + id + " not ready in time");
    }

private:
    json call(const std::string& method, json body) {
        body["clientKey"] = key_;
        const std::string payload = body.dump();
        std::string reply;
        EasyPtr easy(curl_easy_init(), &curl_easy_cleanup);
        ListPtr headers(curl_slist_append(nullptr, "Content-Type: application/json"),
                        &curl_slist_free_all);
        const std::string url = "https://gatesolver.com/" + method;
        curl_easy_setopt(easy.get(), CURLOPT_URL, url.c_str());
        curl_easy_setopt(easy.get(), CURLOPT_HTTPHEADER, headers.get());
        curl_easy_setopt(easy.get(), CURLOPT_POSTFIELDS, payload.c_str());
        curl_easy_setopt(easy.get(), CURLOPT_TIMEOUT, 30L);
        curl_easy_setopt(easy.get(), CURLOPT_WRITEFUNCTION, collect);
        curl_easy_setopt(easy.get(), CURLOPT_WRITEDATA, &reply);
        if (CURLcode rc = curl_easy_perform(easy.get()); rc != CURLE_OK)
            throw ApiError("NETWORK", curl_easy_strerror(rc));
        json parsed = json::parse(reply);
        if (parsed.value("errorId", 0) != 0)
            throw ApiError(parsed.value("errorCode", "UNKNOWN"), parsed.value("errorDescription", ""));
        return parsed;
    }
    std::string key_;
};

Setting CURLOPT_POSTFIELDS makes the request a POST automatically. The payload string must stay alive until curl_easy_perform returns, which it does here because it is a local variable in the same scope. json::value returns a default when a key is missing, so error replies and success replies parse with the same code.

Using the client

int main() {
    curl_global_init(CURL_GLOBAL_DEFAULT);
    const char* env = std::getenv("GS_CPP_KEY");
    GateClient gate(env ? env : "YOUR_API_KEY");
    try {
        json solution = gate.solve({
            {"type", "ReCaptchaV2TaskProxyLess"},
            {"websiteURL", "https://accounts.example.org/register?step=2"},
            {"websiteKey", "6LcR_example_site_key_000000000000000"},
        });
        std::cout << solution.at("gRecaptchaResponse").get<std::string>().substr(0, 40) << "...\n";
    } catch (const ApiError& e) {
        std::cerr << "solve failed [" << e.code << "] " << e.what() << '\n';
    }
    curl_global_cleanup();
}

Add #include <iostream> and #include <cstdlib> for this file. curl_global_init should run once, before any threads start; curl_global_cleanup once at the end.

Why exceptions and not error codes

A C style API would return a status and fill an output parameter. Exceptions fit this client better because the failure cases are rare and varied: network trouble, a bad reply, an API error code, a failed task or a timeout. Each one carries a short code string, so the caller can still branch precisely, for example retrying ERROR_CAPTCHA_UNSOLVABLE and ERROR_SERVICE_UNAVAILABLE (both free) while stopping on ERROR_KEY_DENIED_ACCESS. If your code base forbids exceptions, change call to return a std::optional or a small result struct; the request logic itself does not change.

Image tasks

For ImageToTextTask, the image must be base64 encoded. Neither the standard library nor nlohmann/json includes an encoder, so use the one from your existing toolkit (OpenSSL's EVP_EncodeBlock, Qt's QByteArray::toBase64, or a small function of your own). Call solve with a one second interval:

json text = gate.solve({{"type", "ImageToTextTask"}, {"body", base64_png}},
                       std::chrono::seconds(1));
std::string typed = text.at("text").get<std::string>();

Threads and limits

A libcurl easy handle must not be used from two threads at once. The class above creates a new handle per call, so one GateClient can be shared between threads for simple programs. For heavy use, give each worker thread its own client and reuse one easy handle per thread to keep connections alive. Whatever the layout, keep total calls under 600 per minute per API key; with three second polling that leaves room for around 30 tasks in flight.

Asynchronous options

The client blocks its thread while it sleeps between polls, which is fine for a tool that solves one CAPTCHA at a time. For programs that must stay responsive, such as a GUI, run solve on a worker with std::async(std::launch::async, ...) and collect the result through the returned std::future, or post it back to the UI thread with your framework's own mechanism. Programs that manage many network transfers already can move the API calls onto libcurl's multi interface, which drives many transfers from one thread; the request bodies and reply handling stay exactly as shown here, only the transport changes.

Logging and configuration

Log three things for every solve: the task type, the task id and the outcome code. Those are enough to trace any problem later, and none of them is sensitive. Do not log the API key or full tokens. Read the key from an environment variable or a configuration file that the user controls, and if your tool is distributed to other people, let each of them enter their own key, since one key belongs to one account and creating a new key replaces the old one.

Troubleshooting

  • NETWORK with a TLS message: libcurl cannot find CA certificates. Install the system CA bundle or set CURLOPT_CAINFO.
  • json::parse_error: the reply was not JSON, often an HTML error page from a proxy in between. Log reply before parsing.
  • ERROR_INVALID_TASK_DATA: the description names the missing field; check the spelling of field names, which are case sensitive.
  • ERROR_ZERO_BALANCE: stop the worker and top up; retrying will not help.
C++ clients often live inside QA rigs and desktop RPA tools. Keep the API key out of shipped binaries and read it from the user's own configuration.

The API docs list every field, the Rust guide builds the same client in async style, and the cURL guide is handy for checking a task from the shell before you write C++.

Common questions

Which C++ standard does this code need?

C++17, for the if statement with an initializer used in the call method. It also builds as C++20.

Why create a new curl handle per call?

It keeps the class simple and safe to share. For high volume, reuse one handle per thread to keep connections open.

Does nlohmann/json need to be compiled?

No. It is header only; include json.hpp or install the package and link the CMake target.

How do I base64 encode an image in C++?

Use an encoder from a library you already have, such as OpenSSL EVP_EncodeBlock or Qt toBase64, then send the string in body.

Can I use this client on Windows?

Yes. Install libcurl and nlohmann/json through vcpkg and build with the same CMake file.

Keep reading