More languages
How to solve reCAPTCHA v3 in PHP
This guide is for PHP code that submits a v3 protected form from the server side, for example a scheduled job that sends your own data to a partner portal. It uses Guzzle, a small provider class and a cookie jar; tokens cost $0.70 per 1,000.
The situation
A PHP application, a cron script or a queue worker needs to post a form on another site that runs reCAPTCHA v3. In a browser the page would fetch a token silently and add it to the form. Your PHP code has no browser, so it gets a token from the API and adds it itself. The site's back end cannot tell the difference as long as the token matches the site key and action and arrives in the expected field.
You need PHP 8.1 or newer and Guzzle 7 (composer require guzzlehttp/guzzle). The examples use readonly properties and enums from PHP 8.1.
Read the site key, action and field names
Open the form in a desktop browser with developer tools. The site key is in the script tag recaptcha/api.js?render=.... The action is the action value passed to grecaptcha.execute in the page scripts. Then submit the form once and look at the request in the Network tab: note every field, including hidden ones such as _token or csrf, and the name of the field that holds the reCAPTCHA token. For plain forms it is usually g-recaptcha-response, but v3 sites often choose their own name. The article on identifying the reCAPTCHA version helps if you are not sure it is v3.
A token provider class
Wrapping the API in a class with one public method keeps the rest of your code simple and makes the provider easy to replace with a fake in tests.
<?php
declare(strict_types=1);
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
enum TaskState: string { case Processing = 'processing'; case Ready = 'ready'; case Failed = 'failed'; }
final class ScoreTokenProvider
{
private readonly Client $api;
public function __construct(private readonly string $apiKey, ?Client $api = null)
{
$this->api = $api ?? new Client(['base_uri' => 'https://gatesolver.com', 'timeout' => 25]);
}
/** Returns [token, userAgent]. */
public function forAction(string $pageUrl, string $siteKey, string $action): array
{
$created = $this->call('/createTask', ['task' => [
'type' => 'ReCaptchaV3TaskProxyLess', 'websiteURL' => $pageUrl,
'websiteKey' => $siteKey, 'pageAction' => $action,
]]);
$until = microtime(true) + 125;
while (microtime(true) < $until) {
usleep(3_000_000);
$r = $this->call('/getTaskResult', ['taskId' => $created['taskId']]);
$state = TaskState::tryFrom($r['status'] ?? '') ?? TaskState::Processing;
if ($state === TaskState::Ready) {
return [$r['solution']['gRecaptchaResponse'], $r['solution']['userAgent'] ?? ''];
}
if ($state === TaskState::Failed) {
throw new RuntimeException('v3 task failed, not charged');
}
}
throw new RuntimeException('v3 token not ready in time');
}
private function call(string $path, array $payload): array
{
$payload['clientKey'] = $this->apiKey;
$res = $this->api->post($path, [RequestOptions::JSON => $payload]);
$data = json_decode((string) $res->getBody(), true, 512, JSON_THROW_ON_ERROR);
if (($data['errorId'] ?? 0) !== 0) {
$code = $data['errorCode'] ?? 'ERROR';
$detail = (string) ($data['errorDescription'] ?? '');
throw new RuntimeException(trim($code . ' ' . $detail));
}
return $data;
}
}
The error branch carries the errorCode into the exception message, so a log line such as ERROR_ZERO_BALANCE or ERROR_INVALID_TASK_DATA tells you immediately what to fix.
Post the form with its session
Many forms reject a post that does not come from the session that loaded them, usually through a CSRF field tied to a cookie. Load the page first with a Guzzle cookie jar, read the hidden fields, then ask for the token and post everything together.
use GuzzleHttp\Cookie\CookieJar;
$portal = new Client(['cookies' => new CookieJar(), 'timeout' => 20,
'headers' => ['Accept-Language' => 'en-GB,en;q=0.8']]);
$formUrl = 'https://partner.example.com/orders/new';
$html = (string) $portal->get($formUrl)->getBody();
$doc = new DOMDocument();
@$doc->loadHTML($html);
$fields = [];
foreach ((new DOMXPath($doc))->query('//form[@id="order"]//input[@type="hidden"]') as $in) {
$fields[$in->getAttribute('name')] = $in->getAttribute('value');
}
$provider = new ScoreTokenProvider(getenv('GATESOLVER_KEY') ?: 'YOUR_API_KEY');
[$token, $agent] = $provider->forAction($formUrl, '6Lc_PARTNER_KEY', 'submit_order');
$reply = $portal->post($formUrl, [
'form_params' => $fields + ['sku' => 'A-1002', 'qty' => '4', 'g-recaptcha-response' => $token],
'headers' => ['User-Agent' => $agent, 'Referer' => $formUrl],
'http_errors' => false,
]);
echo $reply->getStatusCode(), PHP_EOL;
The XPath query picks hidden inputs from one form only, which avoids mixing in fields from a search box elsewhere on the page. Replace the form id, the visible fields and the token field name with the ones you saw in the Network tab.
Matching the action
The pageAction you send becomes part of the token. If the page runs grecaptcha.execute(key, {action: 'submit_order'}) before posting, send exactly submit_order. Sites that check the action reject a mismatch even when the token is fresh. If the page does not pass an action at all, leave the field out. The page action entry explains how the value is used in scoring.
Timing in queue workers
A v3 token is valid for about two minutes and only once. In a queue worker, request the token inside the job, right before the post, not when the job is enqueued. If a job is retried, it must request a fresh token. A typical solve finishes under 3 seconds, so this adds a few seconds per job and fits comfortably inside the default timeouts of common PHP queue systems.
Retrying sensibly
| Error | Retry? | Why |
|---|---|---|
| ERROR_CAPTCHA_UNSOLVABLE, failed status | Once | Free, and a new task often succeeds |
| ERROR_SERVICE_UNAVAILABLE on either call | After a pause | Temporary, free |
| ERROR_RATE_LIMIT | After a pause | Over 600 requests a minute on the key |
| ERROR_ZERO_BALANCE, ERROR_KEY_DENIED_ACCESS | No | Needs a top-up or a new key |
| ERROR_INVALID_TASK_DATA | No | A field is missing; read the description |
Guzzle middleware can handle network level retries; keep API level retries in your job logic, where you can tell the codes apart.
Testing without spending balance
Guzzle's MockHandler lets you queue canned responses. Build a client with a handler stack holding a createTask reply and two getTaskResult replies (processing, then ready), pass it as the second constructor argument, and assert the token comes back. Lower the usleep through a constructor parameter if you want the test to run instantly.
Plugging the provider into a framework
In Laravel or Symfony, register ScoreTokenProvider as a service with the key read from configuration, and inject it into the job or command that posts the form. Keep the Guzzle client for the target site separate from the one the provider uses for the API: the site client carries cookies and site headers, while the API client should stay clean. In a plain script, two new Client(...) calls achieve the same separation.
If your application already has a central HTTP client with logging middleware, you can pass it as the provider's second constructor argument, as long as its base URI is not set to the target site. That way API calls show up in the same logs as the rest of your outgoing traffic.
A note on scores
The site decides what to do with the score Google returns for your token, and the threshold is its own setting. A token obtained through the API is scored like any other. If a site still refuses after the action and fields match, check whether it also expects a recent page view from the same session, which the cookie jar above provides when you load the form first.
Common questions
Which PHP and Guzzle versions does this need?
PHP 8.1 or newer for enums and readonly properties, and Guzzle 7. Older PHP can use class constants and plain properties instead.
Why load the form page before posting?
The site may tie a CSRF field to a session cookie. Loading the page with a cookie jar gives you both.
What if the site uses its own token field name?
Use that name in form_params. The token is the same; only the field the back end reads changes.
Can I fetch tokens in advance for a batch?
No. Tokens expire after about two minutes and work once, so fetch each one right before its post.
Does a failed task cost anything?
No. Failed, unsolvable and expired tasks are free; only ready tokens are charged.
Keep reading
- reCAPTCHA v3 solver$0.70 per 1,000 tasks, answers under 3 seconds.
- pageAction (reCAPTCHA action)The action label a page passes to grecaptcha.execute, how to locate it, and why a wrong label sinks good tokens.
- Identify which reCAPTCHA version a site usesCheckbox, badge or silent score: read the script URL, iframe size and execute calls to name the exact reCAPTCHA variant.
- API docscreateTask, getTaskResult, getBalance, error codes and the in.php format.