C++ captcha solver: an API client with libcurl and nlohmann/json

A C++ captcha solver is a program that sends a challenge to a solver API and reads the answer as JSON. This example uses two widespread libraries, libcurl for HTTPS and nlohmann/json for the body and the reply, and standard C++17 for the rest. With ilovecaptcha it makes two calls, createTask then getTaskResult. The complete file follows the explanations.

Updated on · Written and maintained by the ilovecaptcha team

Preview: the API described here is in public beta. Endpoint names, fields and codes can still change until the end of the beta, and no API key is distributed yet.

How do you call a captcha solver API from C++?

With libcurl for the transport and nlohmann/json for the data. The function post takes a json object, adds clientKey, serialises it with dump and sends it through the easy interface of libcurl, with CURLOPT_POSTFIELDS and a CURLOPT_TIMEOUT of 30 seconds. The callback onData appends the reply to a std::string, which json::parse turns back into an object.

The C++ example at a glance
Item Value
Language level C++17
Dependencies libcurl and nlohmann/json
File solve.cpp
Build and run g++ -std=c++17 solve.cpp -o solve -lcurl && ./solve
Install both vcpkg install curl nlohmann-json

How do you send the captcha image and wait for the answer in C++?

The image is read from a std::ifstream opened in binary mode into a std::vector of bytes, then encoded by the function base64 written in the file, since the standard library has none. solve posts the task to createTask, keeps taskId and polls getTaskResult.

  • POLL_INTERVAL is std::chrono::milliseconds(1500), passed to std::this_thread::sleep_for.
  • TIMEOUT is 120 seconds, measured on std::chrono::steady_clock.
  • taskId is kept as a json value and sent back unchanged.
  • result.value reads status with a default, so a missing field does not throw.

How do you handle the API key and errors in C++?

Read the key with std::getenv from a variable such as ILOVECAPTCHA_KEY instead of the constant API_KEY, and check that it is set before building the string. Errors are exceptions: post throws std::runtime_error when libcurl fails, with the text of curl_easy_strerror, and when errorId is not 0, with errorCode and errorDescription. main wraps the calls in a try block, prints the message and calls curl_global_cleanup on both paths.

What does a complete C++ captcha solver client look like?

The file below is the whole client, in 99 lines. It defines onData, post, solve, getBalance and base64, and its main reads captcha.png, submits it as an aws-waf task and prints the solution with dump. Replace YOUR_API_KEY and YOUR_API_URL with your own values and adapt the task object to your captcha before you build it.

solve.cpp · Complete C++ client: one createTask call, then getTaskResult until the task is ready (preview format).
#include <chrono>
#include <fstream>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
#include <curl/curl.h>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

const std::string API_KEY = "YOUR_API_KEY";
const std::string BASE_URL = "YOUR_API_URL";
const auto POLL_INTERVAL = std::chrono::milliseconds(1500);
const auto TIMEOUT = std::chrono::seconds(120);

static size_t onData(char* chunk, size_t size, size_t count, std::string* out) {
    out->append(chunk, size * count);
    return size * count;
}

json post(const std::string& route, json body) {
    body["clientKey"] = API_KEY;
    const std::string payload = body.dump();
    std::string raw;
    CURL* curl = curl_easy_init();
    if (!curl) throw std::runtime_error("curl_easy_init failed");
    curl_slist* headers = curl_slist_append(nullptr, "Content-Type: application/json");
    curl_easy_setopt(curl, CURLOPT_URL, (BASE_URL + route).c_str());
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload.c_str());
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(payload.size()));
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, onData);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &raw);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
    const CURLcode code = curl_easy_perform(curl);
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    if (code != CURLE_OK) throw std::runtime_error(curl_easy_strerror(code));
    json result = json::parse(raw);
    if (result.value("errorId", 0) != 0) {
        throw std::runtime_error(result.value("errorCode", "?") + ": " + result.value("errorDescription", ""));
    }
    return result;
}

json solve(const json& task) {
    json result = post("/createTask", json{{"task", task}});
    if (result.value("status", "") == "ready") return result["solution"];
    const json taskId = result["taskId"];
    const auto deadline = std::chrono::steady_clock::now() + TIMEOUT;
    while (std::chrono::steady_clock::now() < deadline) {
        std::this_thread::sleep_for(POLL_INTERVAL);
        result = post("/getTaskResult", json{{"taskId", taskId}});
        if (result.value("status", "") == "ready") return result["solution"];
    }
    throw std::runtime_error("task " + taskId.dump() + " not ready after " + std::to_string(TIMEOUT.count()) + " s");
}

double getBalance() {
    return post("/getBalance", json::object()).value("balance", 0.0);
}

std::string base64(const std::vector<unsigned char>& data) {
    static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    std::string out;
    for (size_t i = 0; i < data.size(); i += 3) {
        unsigned v = data[i] << 16;
        if (i + 1 < data.size()) v |= data[i + 1] << 8;
        if (i + 2 < data.size()) v |= data[i + 2];
        out += table[(v >> 18) & 63];
        out += table[(v >> 12) & 63];
        out += i + 1 < data.size() ? table[(v >> 6) & 63] : '=';
        out += i + 2 < data.size() ? table[v & 63] : '=';
    }
    return out;
}

int main() {
    std::ifstream file("captcha.png", std::ios::binary);
    if (!file) {
        std::cerr << "captcha.png not found\n";
        return 1;
    }
    const std::vector<unsigned char> data((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
    curl_global_init(CURL_GLOBAL_DEFAULT);
    try {
        std::cout << solve(json{{"type", "aws-waf"}, {"image", base64(data)}}).dump() << "\n";
        std::cout << getBalance() << "\n";
    } catch (const std::exception& e) {
        std::cerr << e.what() << "\n";
        curl_global_cleanup();
        return 1;
    }
    curl_global_cleanup();
    return 0;
}

C++ captcha solver: frequently asked questions

Do I need an SDK to solve captchas in C++?

No SDK, but two libraries that most C++ projects already know: libcurl for the HTTPS request and nlohmann/json, a header-only library, for the body and the reply. Both install with the package manager of your system or with vcpkg. The file on this page is the complete client: add it to your build, link libcurl, and call solve with a json object that describes the task.

Can I use another JSON library or another HTTP client in C++?

Yes. The API only expects a POST request with a JSON body and answers in JSON, so any pair of libraries that does this fits. Keep the shape of the example: one post function that adds clientKey and throws on errorId, and one solve function that loops on getTaskResult. With cpr, Boost.Beast or Qt Network, only the inside of post changes; with RapidJSON or Boost.JSON, only the way fields are read.

What does solve return in C++, and how do you read it?

A nlohmann json object: the solution of the API. Read it with the at method or the value method and the key your task type returns: token for a token widget, points for an image grid, offset for a slider, text for characters to type. For points, iterate over the array and read each pair as two integers, in pixels of the image you submitted. The example prints the object with dump.

Sources

The facts and figures quoted on this page come from these sources.