Perl captcha solver: an API client with HTTP::Tiny
A Perl captcha solver is a script that posts a challenge to a solver API and decodes the answer with modules shipped with Perl itself: HTTP::Tiny, JSON::PP and MIME::Base64. With ilovecaptcha it makes two HTTPS calls, createTask then getTaskResult. This page explains the request, the one module that HTTPS requires, the polling loop and the errors, then gives the complete file.
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 Perl?
With HTTP: and JSON:, both in the Perl core since version 5.14. The sub post merges the key into the body under clientKey, encodes it with a JSON: object created in utf8 mode, sends it with the post method of HTTP: and decodes the content of the reply. One client serves the whole script, with a timeout of 30 seconds.
| Item | Value |
|---|---|
| Runs on | Perl 5.14 or newer |
| Module to install | IO:, for HTTPS |
| File | solve.pl |
| Command | perl solve.pl |
| HTTP client | HTTP: |
How do you send the captcha image and wait for the answer in Perl?
The image is opened with the : layer, read in one piece and encoded by encode_base64 with an empty second argument, which removes the line breaks the function adds by default. solve posts the task to createTask, keeps taskId, then polls getTaskResult.
POLL_SECONDSis 1.5:sleepcomes fromTime:, which accepts fractions of a second.: HiRes TIMEOUT_SECONDSis 120: past that,solvedies with the task identifier.timealso comes fromTime:.: HiRes - A reply already
readyatcreateTaskis returned at once.
How do you handle the API key and errors in Perl?
Read the key from the hash %ENV, under a name such as ILOVECAPTCHA_KEY, and stop with die when it is empty. The sub post dies in two cases: when HTTP: reports a failure, with the status and the reason, and when errorId is not 0, with errorCode and errorDescription. A missing IO: shows up there too, as status 599 with an explanatory message. Wrap the call to solve in an eval block to handle these errors.
What does a complete Perl captcha solver client look like?
The file below is the whole client, in 50 lines. Under strict and warnings, it defines the subs post, solve and get_balance, then reads captcha.png, submits it as an aws-waf task and prints the solution as JSON. Replace YOUR_API_KEY and YOUR_API_URL with your own values and adapt the task hash to your captcha before you run it.
solve.pl · Complete Perl client: one createTask call, then getTaskResult until the task is ready (preview format).use strict;
use warnings;
use HTTP::Tiny;
use JSON::PP;
use MIME::Base64 qw(encode_base64);
use Time::HiRes qw(sleep time);
my $API_KEY = "YOUR_API_KEY";
my $BASE_URL = "YOUR_API_URL";
my $POLL_SECONDS = 1.5;
my $TIMEOUT_SECONDS = 120;
my $http = HTTP::Tiny->new(timeout => 30);
my $json = JSON::PP->new->utf8;
sub post {
my ($route, $body) = @_;
my $response = $http->post($BASE_URL . $route, {
headers => { "Content-Type" => "application/json" },
content => $json->encode({ clientKey => $API_KEY, %$body }),
});
die "HTTP $response->{status} $response->{reason}\n" unless $response->{success};
my $result = $json->decode($response->{content});
die "$result->{errorCode}: $result->{errorDescription}\n" if ($result->{errorId} // 0) != 0;
return $result;
}
sub solve {
my ($task) = @_;
my $result = post("/createTask", { task => $task });
return $result->{solution} if ($result->{status} // "") eq "ready";
my $task_id = $result->{taskId};
my $deadline = time() + $TIMEOUT_SECONDS;
while (time() < $deadline) {
sleep($POLL_SECONDS);
$result = post("/getTaskResult", { taskId => $task_id });
return $result->{solution} if ($result->{status} // "") eq "ready";
}
die "task $task_id not ready after $TIMEOUT_SECONDS s\n";
}
sub get_balance {
return post("/getBalance", {})->{balance};
}
open(my $fh, "<:raw", "captcha.png") or die "captcha.png: $!\n";
my $image = encode_base64(do { local $/; <$fh> }, "");
close($fh);
print $json->encode(solve({ type => "aws-waf", image => $image })), "\n";
print get_balance(), "\n";
Perl captcha solver: frequently asked questions
Do I need a CPAN distribution or an SDK to solve captchas in Perl?
No SDK, and one CPAN module at most. HTTP::Tiny, JSON::PP, MIME::Base64 and Time::HiRes come with Perl 5.14 or newer. HTTPS is the exception: HTTP::Tiny delegates it to IO::Socket::SSL, which many systems already provide as a package and which the cpan command installs otherwise. The file on this page is the complete client, to keep as a script or to turn into a small module.
Can I use LWP::UserAgent or Mojo::UserAgent instead of HTTP::Tiny?
Yes. Only the sub post changes: it must send a POST request with the Content-Type application/json and a JSON body that contains clientKey, then return the decoded reply. LWP::UserAgent needs LWP::Protocol::https for HTTPS; Mojo::UserAgent encodes the body itself when it receives the json argument. The sub solve does not change, since it only calls post and reads status, taskId and solution.
What does solve return in Perl, and how do you read it?
A hash reference: the solution object decoded by JSON::PP. Dereference it with the arrow 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. Points is a reference to an array of two-element array references, in pixels of the image you submitted. The example encodes the whole reference again to print it.
Sources
The facts and figures quoted on this page come from these sources.
- Perl 5 Porters, HTTP::Tiny, a small, simple, correct HTTP/1.1 client, Perl documentation (post, SSL support, status 599).
- Perl 5 Porters, JSON::PP, JSON::XS compatible pure-Perl module, Perl documentation (encode, decode, utf8).