API Tutorials

Building a PHP Composer Package for CaptchaAI

PHP powers a large share of web automation backends. A Composer package wraps the CaptchaAI API into a reusable library — $client->solveRecaptchaV2($sitekey, $url) instead of raw cURL calls and manual JSON parsing in every project.

Package Structure

captchaai-php/
├── src/
│   ├── CaptchaAI.php        # Main client class
│   ├── Exception/
│   │   ├── CaptchaAIException.php
│   │   ├── SubmitException.php
│   │   ├── SolveException.php
│   │   └── TimeoutException.php
│   └── Enum/
│       └── Method.php
├── composer.json
└── README.md

Composer Configuration

{
    "name": "your-vendor/captchaai",
    "description": "PHP client library for CaptchaAI API",
    "type": "library",
    "license": "MIT",
    "require": {
        "php": ">=8.1",
        "guzzlehttp/guzzle": "^7.0"
    },
    "autoload": {
        "psr-4": {
            "CaptchaAI\\": "src/"
        }
    }
}

Exception Classes

<?php
// src/Exception/CaptchaAIException.php
namespace CaptchaAI\Exception;

class CaptchaAIException extends \RuntimeException
{
    private ?string $errorCode;

    private const FATAL_CODES = [
        'ERROR_WRONG_USER_KEY',
        'ERROR_KEY_DOES_NOT_EXIST',
        'ERROR_ZERO_BALANCE',
        'ERROR_IP_NOT_ALLOWED',
    ];

    public function __construct(string $message, ?string $errorCode = null)
    {
        parent::__construct($message);
        $this->errorCode = $errorCode;
    }

    public function getErrorCode(): ?string
    {
        return $this->errorCode;
    }

    public function isFatal(): bool
    {
        return in_array($this->errorCode, self::FATAL_CODES, true);
    }
}
<?php
// src/Exception/SubmitException.php
namespace CaptchaAI\Exception;

class SubmitException extends CaptchaAIException
{
    public function __construct(string $code)
    {
        parent::__construct("Task submission failed: {$code}", $code);
    }
}
<?php
// src/Exception/SolveException.php
namespace CaptchaAI\Exception;

class SolveException extends CaptchaAIException
{
    public function __construct(string $code)
    {
        parent::__construct("Task solving failed: {$code}", $code);
    }
}
<?php
// src/Exception/TimeoutException.php
namespace CaptchaAI\Exception;

class TimeoutException extends CaptchaAIException
{
    private string $taskId;

    public function __construct(string $taskId, int $timeoutSeconds)
    {
        parent::__construct("Task {$taskId} timed out after {$timeoutSeconds}s");
        $this->taskId = $taskId;
    }

    public function getTaskId(): string
    {
        return $this->taskId;
    }
}

Main Client

<?php
// src/CaptchaAI.php
namespace CaptchaAI;

use GuzzleHttp\Client as HttpClient;
use CaptchaAI\Exception\SubmitException;
use CaptchaAI\Exception\SolveException;
use CaptchaAI\Exception\TimeoutException;

class CaptchaAI
{
    private const SUBMIT_URL = 'https://ocr.captchaai.com/in.php';
    private const RESULT_URL = 'https://ocr.captchaai.com/res.php';

    private string $apiKey;
    private HttpClient $http;
    private int $pollInterval;
    private int $timeout;

    public function __construct(
        string $apiKey,
        int $pollInterval = 5,
        int $timeout = 180,
        ?HttpClient $httpClient = null
    ) {
        $this->apiKey = $apiKey;
        $this->pollInterval = $pollInterval;
        $this->timeout = $timeout;
        $this->http = $httpClient ?? new HttpClient(['timeout' => 30]);
    }

    // --- Core methods ---

    private function submit(array $params): string
    {
        $params['key'] = $this->apiKey;
        $params['json'] = 1;

        $response = $this->http->post(self::SUBMIT_URL, [
            'form_params' => $params,
        ]);

        $result = json_decode($response->getBody()->getContents(), true);

        if (($result['status'] ?? 0) !== 1) {
            throw new SubmitException($result['request'] ?? 'unknown');
        }

        return $result['request']; // task ID
    }

    private function poll(string $taskId): string
    {
        $startTime = time();

        while (time() - $startTime < $this->timeout) {
            sleep($this->pollInterval);

            $response = $this->http->get(self::RESULT_URL, [
                'query' => [
                    'key' => $this->apiKey,
                    'action' => 'get',
                    'id' => $taskId,
                    'json' => 1,
                ],
            ]);

            $result = json_decode($response->getBody()->getContents(), true);

            if (($result['request'] ?? '') === 'CAPCHA_NOT_READY') {
                continue;
            }

            if (($result['status'] ?? 0) === 1) {
                return $result['request'];
            }

            throw new SolveException($result['request'] ?? 'unknown');
        }

        throw new TimeoutException($taskId, $this->timeout);
    }

    private function solve(array $params): string
    {
        $taskId = $this->submit($params);
        return $this->poll($taskId);
    }

    // --- Solver methods ---

    /**

     * Solve reCAPTCHA v2
     */
    public function solveRecaptchaV2(
        string $sitekey,
        string $pageurl,
        bool $invisible = false,
        ?string $cookies = null
    ): string {
        $params = [
            'method' => 'userrecaptcha',
            'googlekey' => $sitekey,
            'pageurl' => $pageurl,
        ];
        if ($invisible) $params['invisible'] = 1;
        if ($cookies) $params['cookies'] = $cookies;

        return $this->solve($params);
    }

    /**

     * Solve reCAPTCHA v3
     */
    public function solveRecaptchaV3(
        string $sitekey,
        string $pageurl,
        string $action = 'verify',
        float $minScore = 0.3
    ): string {
        return $this->solve([
            'method' => 'userrecaptcha',
            'version' => 'v3',
            'googlekey' => $sitekey,
            'pageurl' => $pageurl,
            'action' => $action,
            'min_score' => $minScore,
        ]);
    }

    /**

     * Solve Cloudflare Turnstile
     */
    public function solveTurnstile(
        string $sitekey,
        string $pageurl,
        ?string $action = null,
        ?string $cdata = null
    ): string {
        $params = [
            'method' => 'turnstile',
            'sitekey' => $sitekey,
            'pageurl' => $pageurl,
        ];
        if ($action) $params['action'] = $action;
        if ($cdata) $params['data'] = $cdata;

        return $this->solve($params);
    }

    /**

     * Solve hCaptcha
     */
    public function solveHCaptcha(string $sitekey, string $pageurl): string
    {
        return $this->solve([
            'method' => 'hcaptcha',
            'sitekey' => $sitekey,
            'pageurl' => $pageurl,
        ]);
    }

    /**

     * Solve image/text CAPTCHA from base64
     */
    public function solveImage(
        string $base64Image,
        bool $caseSensitive = false,
        ?int $minLength = null,
        ?int $maxLength = null
    ): string {
        $params = [
            'method' => 'base64',
            'body' => $base64Image,
        ];
        if ($caseSensitive) $params['regsense'] = 1;
        if ($minLength !== null) $params['min_len'] = $minLength;
        if ($maxLength !== null) $params['max_len'] = $maxLength;

        return $this->solve($params);
    }

    /**

     * Solve GeeTest v3
     */
    public function solveGeeTestV3(
        string $gt,
        string $challenge,
        string $pageurl
    ): string {
        return $this->solve([
            'method' => 'geetest',
            'gt' => $gt,
            'challenge' => $challenge,
            'pageurl' => $pageurl,
        ]);
    }

    // --- Utility methods ---

    /**

     * Get current account balance
     */
    public function getBalance(): float
    {
        $response = $this->http->get(self::RESULT_URL, [
            'query' => [
                'key' => $this->apiKey,
                'action' => 'getbalance',
                'json' => 1,
            ],
        ]);

        $result = json_decode($response->getBody()->getContents(), true);
        return (float) ($result['request'] ?? 0);
    }

    /**

     * Report a bad solution
     */
    public function reportBad(string $taskId): bool
    {
        $response = $this->http->get(self::RESULT_URL, [
            'query' => [
                'key' => $this->apiKey,
                'action' => 'reportbad',
                'id' => $taskId,
                'json' => 1,
            ],
        ]);

        $result = json_decode($response->getBody()->getContents(), true);
        return ($result['status'] ?? 0) === 1;
    }
}

Usage Examples

<?php
require_once 'vendor/autoload.php';

use CaptchaAI\CaptchaAI;
use CaptchaAI\Exception\SubmitException;
use CaptchaAI\Exception\TimeoutException;

$client = new CaptchaAI(
    apiKey: 'YOUR_API_KEY',
    pollInterval: 5,
    timeout: 120
);

// Check balance
$balance = $client->getBalance();
echo "Balance: \${$balance}\n";

// Solve reCAPTCHA v2
try {
    $token = $client->solveRecaptchaV2(
        sitekey: '6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-',
        pageurl: 'https://example.com/login'
    );
    echo "Token: " . substr($token, 0, 40) . "...\n";
} catch (TimeoutException $e) {
    echo "Timed out: {$e->getMessage()}\n";
} catch (SubmitException $e) {
    if ($e->isFatal()) {
        echo "Fatal: {$e->getErrorCode()}\n";
        exit(1);
    }
    echo "Retryable: {$e->getErrorCode()}\n";
}

// Solve Turnstile
$turnstileToken = $client->solveTurnstile(
    sitekey: '0x4AAAAAAADnPIDROrmt1Wwj',
    pageurl: 'https://example.com/checkout'
);

// Solve image CAPTCHA
$imageBase64 = base64_encode(file_get_contents('captcha.png'));
$text = $client->solveImage($imageBase64, caseSensitive: true);
echo "Text: {$text}\n";

Troubleshooting

Issue Cause Fix
SubmitException: ERROR_WRONG_USER_KEY Invalid API key Check key from dashboard
TimeoutException frequently Timeout too short Increase $timeout to 180+
Class not found Autoloader not configured Run composer dump-autoload
Guzzle connection error Network issue or firewall Check server can reach ocr.captchaai.com
json_decode returns null Invalid response body Check API URL; log raw response for debugging

FAQ

Why Guzzle instead of native cURL?

Guzzle provides PSR-7 message interfaces, automatic JSON handling, connection pooling, and middleware support. For projects already using Guzzle, the SDK integrates without adding dependencies. You can substitute any PSR-18 compatible client.

How do I use this in Laravel?

Register the client as a singleton in a service provider. Bind CaptchaAI::class with the API key from config/services.php. Inject it via constructor injection in controllers or jobs.

Should I publish to Packagist?

For internal use, reference via repositories in composer.json pointing to your Git repo. For public distribution, submit to Packagist with proper versioning and a README.

Next Steps

Build your PHP CAPTCHA package — get your CaptchaAI API key and create a Composer library.

Related guides:

Discussions (0)

No comments yet.

Related Posts

Tutorials Solve CAPTCHAs with PHP Using CaptchaAI
Complete PHP tutorial for solving re CAPTCHA, Turnstile, image CAPTCHAs and using the Captcha AI API with c URL.

Complete PHP tutorial for solving re CAPTCHA, Turnstile, image CAPTCHAs and more using the Captcha AI API with...

Automation All CAPTCHA Types PHP
Mar 03, 2026
DevOps & Scaling Ansible Playbooks for CaptchaAI Worker Deployment
Deploy and manage Captcha AI workers with Ansible — playbooks for provisioning, configuration, rolling updates, and health checks across your server fleet.

Deploy and manage Captcha AI workers with Ansible — playbooks for provisioning, configuration, rolling updates...

Automation Python All CAPTCHA Types
Apr 07, 2026
DevOps & Scaling Blue-Green Deployment for CAPTCHA Solving Infrastructure
Implement blue-green deployments for CAPTCHA solving infrastructure — zero-downtime upgrades, traffic switching, and rollback strategies with Captcha AI.

Implement blue-green deployments for CAPTCHA solving infrastructure — zero-downtime upgrades, traffic switchin...

Automation Python All CAPTCHA Types
Apr 07, 2026
Troubleshooting CaptchaAI API Error Handling: Complete Decision Tree
Complete decision tree for every Captcha AI API error.

Complete decision tree for every Captcha AI API error. Learn which errors are retryable, which need parameter...

Automation Python All CAPTCHA Types
Mar 17, 2026
Tutorials Using Fiddler to Inspect CaptchaAI API Traffic
How to use Fiddler Everywhere and Fiddler Classic to capture, inspect, and debug Captcha AI API requests and responses — filters, breakpoints, and replay for tr...

How to use Fiddler Everywhere and Fiddler Classic to capture, inspect, and debug Captcha AI API requests and r...

Automation Python All CAPTCHA Types
Mar 05, 2026
Tutorials CAPTCHA Handling in Mobile Apps with Appium
Handle CAPTCHAs in mobile app automation using Appium and Captcha AI — extract Web sitekeys, solve, and inject tokens on Android and i OS.

Handle CAPTCHAs in mobile app automation using Appium and Captcha AI — extract Web View sitekeys, solve, and i...

Automation Python All CAPTCHA Types
Feb 13, 2026
Tutorials Streaming Batch Results: Processing CAPTCHA Solutions as They Arrive
Process CAPTCHA solutions the moment they arrive instead of waiting for tasks to complete — use async generators, event emitters, and callback patterns for stre...

Process CAPTCHA solutions the moment they arrive instead of waiting for all tasks to complete — use async gene...

Automation Python All CAPTCHA Types
Apr 07, 2026
Reference CaptchaAI CLI Tool: Command-Line CAPTCHA Solving and Testing
A reference for building and using a Captcha AI command-line tool — solve CAPTCHAs, check balance, test parameters, and integrate with shell scripts and CI/CD p...

A reference for building and using a Captcha AI command-line tool — solve CAPTCHAs, check balance, test parame...

Automation Python All CAPTCHA Types
Feb 26, 2026
DevOps & Scaling Auto-Scaling CAPTCHA Solving Workers
Build auto-scaling CAPTCHA solving workers that adjust capacity based on queue depth, balance, and solve rates.

Build auto-scaling CAPTCHA solving workers that adjust capacity based on queue depth, balance, and solve rates...

Automation Python All CAPTCHA Types
Mar 23, 2026
API Tutorials How to Solve reCAPTCHA v2 Callback Using API
how to solve re CAPTCHA v 2 callback implementations using Captcha AI API.

Learn how to solve re CAPTCHA v 2 callback implementations using Captcha AI API. Detect the callback function,...

Automation reCAPTCHA v2 Webhooks
Mar 01, 2026
API Tutorials Solve GeeTest v3 CAPTCHA with Python and CaptchaAI
Step-by-step Python tutorial for solving Gee Test v 3 slide puzzle CAPTCHAs using the Captcha AI API.

Step-by-step Python tutorial for solving Gee Test v 3 slide puzzle CAPTCHAs using the Captcha AI API. Includes...

Automation Python Testing
Mar 23, 2026
API Tutorials Case-Sensitive CAPTCHA API Parameter Guide
How to use the regsense parameter for case-sensitive CAPTCHA solving with Captcha AI.

How to use the regsense parameter for case-sensitive CAPTCHA solving with Captcha AI. Covers when to use, comm...

Python Web Scraping Image OCR
Apr 09, 2026