Production-ready code examples in multiple programming languages. Copy, paste, and start solving CAPTCHAs in minutes.
Quick Start
Get started in 5 minutes
SDKs Available
Official libraries for all languages
REST API
Simple HTTP endpoints
99.9% Uptime
Enterprise reliability
import requests
import time
# AI4CAP.COM Python Example
CLIENT_KEY = "your_api_key_here"
BASE_URL = "https://api.ai4cap.com"
def create_task(task_data):
"""Create a new CAPTCHA solving task"""
response = requests.post(
f"{BASE_URL}/createTask",
headers={"Content-Type": "application/json"},
json={
"clientKey": CLIENT_KEY,
"task": task_data
}
)
return response.json()
def get_task_result(task_id):
"""Get the result of a CAPTCHA solving task"""
response = requests.post(
f"{BASE_URL}/getTaskResult",
headers={"Content-Type": "application/json"},
json={
"clientKey": CLIENT_KEY,
"taskId": task_id
}
)
return response.json()
def solve_recaptcha_v2(website_url, website_key):
"""Solve reCAPTCHA v2"""
# Create task
result = create_task({
"type": "ReCaptchaV2TaskProxyless",
"websiteURL": website_url,
"websiteKey": website_key
})
if result["errorId"] != 0:
raise Exception(f"Error: {result['errorDescription']}")
task_id = result["taskId"]
# Poll for solution
while True:
result = get_task_result(task_id)
if result["errorId"] != 0:
raise Exception(f"Error: {result['errorDescription']}")
if result["status"] == "ready":
return result["solution"]["gRecaptchaResponse"]
time.sleep(2)
# Example usage
solution = solve_recaptcha_v2("https://example.com", "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-")
print(f"Solution: {solution}")
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import json
# AI4CAP.COM reCAPTCHA v2 Example with Selenium
CLIENT_KEY = "your_api_key_here"
BASE_URL = "https://api.ai4cap.com"
class CaptchaSolver:
def __init__(self, client_key):
self.client_key = client_key
def solve_recaptcha_v2(self, website_url, website_key, proxy=None):
"""Solve reCAPTCHA v2 using AI4CAP API"""
task_type = "ReCaptchaV2Task" if proxy else "ReCaptchaV2TaskProxyless"
task_data = {
"type": task_type,
"websiteURL": website_url,
"websiteKey": website_key
}
if proxy:
task_data["proxy"] = proxy["proxy"]
task_data["proxyType"] = proxy.get("proxyType", "http")
# Create task
response = requests.post(
f"{BASE_URL}/createTask",
json={
"clientKey": self.client_key,
"task": task_data
}
)
result = response.json()
if result["errorId"] != 0:
raise Exception(f"Error: {result['errorDescription']}")
task_id = result["taskId"]
# Poll for solution
while True:
response = requests.post(
f"{BASE_URL}/getTaskResult",
json={
"clientKey": self.client_key,
"taskId": task_id
}
)
result = response.json()
if result["errorId"] != 0:
raise Exception(f"Error: {result['errorDescription']}")
if result["status"] == "ready":
return result["solution"]["gRecaptchaResponse"]
time.sleep(2)
# Selenium integration example
solver = CaptchaSolver(CLIENT_KEY)
driver = webdriver.Chrome()
driver.get("https://example.com/form")
# Get sitekey from page
sitekey = driver.find_element(By.CLASS_NAME, "g-recaptcha").get_attribute("data-sitekey")
pageurl = driver.current_url
# Solve reCAPTCHA
token = solver.solve_recaptcha_v2(pageurl, sitekey)
# Inject solution
driver.execute_script(f'document.getElementById("g-recaptcha-response").innerHTML="{token}";')
driver.execute_script(f'document.getElementById("g-recaptcha-response").style.display="";')
# Submit form
driver.find_element(By.ID, "submit-button").click()
import asyncio
import aiohttp
import json
# AI4CAP.COM Async Python Example
CLIENT_KEY = "your_api_key_here"
BASE_URL = "https://api.ai4cap.com"
class AsyncCaptchaSolver:
def __init__(self, client_key):
self.client_key = client_key
async def create_task(self, session, task_data):
"""Create a new CAPTCHA solving task"""
async with session.post(
f"{BASE_URL}/createTask",
json={
"clientKey": self.client_key,
"task": task_data
}
) as response:
return await response.json()
async def get_task_result(self, session, task_id):
"""Get task result"""
async with session.post(
f"{BASE_URL}/getTaskResult",
json={
"clientKey": self.client_key,
"taskId": task_id
}
) as response:
return await response.json()
async def solve_recaptcha_async(self, session, website_url, website_key):
"""Asynchronously solve reCAPTCHA"""
# Create task
result = await self.create_task(session, {
"type": "ReCaptchaV2TaskProxyless",
"websiteURL": website_url,
"websiteKey": website_key
})
if result["errorId"] != 0:
raise Exception(f"Error: {result['errorDescription']}")
task_id = result["taskId"]
# Poll for solution
while True:
result = await self.get_task_result(session, task_id)
if result["errorId"] != 0:
raise Exception(f"Error: {result['errorDescription']}")
if result["status"] == "ready":
return result["solution"]["gRecaptchaResponse"]
await asyncio.sleep(2)
async def solve_multiple_captchas(captcha_configs):
"""Solve multiple CAPTCHAs concurrently"""
solver = AsyncCaptchaSolver(CLIENT_KEY)
async with aiohttp.ClientSession() as session:
tasks = []
for config in captcha_configs:
task = solver.solve_recaptcha_async(
session,
config["url"],
config["key"]
)
tasks.append(task)
solutions = await asyncio.gather(*tasks)
return solutions
# Example usage
async def main():
captchas = [
{"url": "https://example1.com", "key": "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-"},
{"url": "https://example2.com", "key": "6LfD3PIbAAAAAJS7rVDxGxOghA9sD2Nt-uO3glVj"},
{"url": "https://example3.com", "key": "6LddGoYgAAAAAHD275rVBjuOYXiofr1u4pFS5lHn"}
]
solutions = await solve_multiple_captchas(captchas)
for i, solution in enumerate(solutions):
print(f"CAPTCHA {i+1}: {solution[:50]}...")
asyncio.run(main())
// AI4CAP.COM JavaScript Example
const CLIENT_KEY = 'your_api_key_here';
const BASE_URL = 'https://api.ai4cap.com';
async function solveImageCaptcha(imageBase64) {
// Create task
const createResponse = await fetch(`${BASE_URL}/createTask`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
clientKey: CLIENT_KEY,
task: {
type: 'ImageToTextTask',
body: imageBase64
}
})
});
const createResult = await createResponse.json();
if (createResult.errorId !== 0) {
throw new Error(createResult.errorDescription);
}
const taskId = createResult.taskId;
// Poll for solution
while (true) {
const resultResponse = await fetch(`${BASE_URL}/getTaskResult`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
clientKey: CLIENT_KEY,
taskId: taskId
})
});
const result = await resultResponse.json();
if (result.errorId !== 0) {
throw new Error(result.errorDescription);
}
if (result.status === 'ready') {
return result.solution.text;
}
// Wait 2 seconds before retry
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
// Convert file to base64
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const base64 = reader.result.split(',')[1];
resolve(base64);
};
reader.onerror = error => reject(error);
});
}
// Example usage with file input
document.getElementById('captcha-input').addEventListener('change', async (e) => {
const file = e.target.files[0];
try {
const base64 = await fileToBase64(file);
const solution = await solveImageCaptcha(base64);
console.log('CAPTCHA solved:', solution);
// Fill solution into form
document.getElementById('captcha-solution').value = solution;
} catch (error) {
console.error('Error solving CAPTCHA:', error);
}
});
// AI4CAP.COM Node.js Example with Express
const express = require('express');
const axios = require('axios');
const multer = require('multer');
const fs = require('fs').promises;
const app = express();
const upload = multer({ dest: 'uploads/' });
const CLIENT_KEY = process.env.AI4CAP_CLIENT_KEY;
const BASE_URL = 'https://api.ai4cap.com';
// CAPTCHA solving service
class AI4CAPService {
constructor(clientKey) {
this.clientKey = clientKey;
this.client = axios.create({
baseURL: BASE_URL,
headers: {
'Content-Type': 'application/json'
}
});
}
async solveCaptcha(imageBase64) {
// Create task
const { data } = await this.client.post('/createTask', {
clientKey: this.clientKey,
task: {
type: 'ImageToTextTask',
body: imageBase64
}
});
if (data.errorId !== 0) {
throw new Error(data.errorDescription);
}
const taskId = data.taskId;
// Poll for solution
return this.pollForSolution(taskId);
}
async pollForSolution(taskId) {
while (true) {
const { data } = await this.client.post('/getTaskResult', {
clientKey: this.clientKey,
taskId: taskId
});
if (data.errorId !== 0) {
throw new Error(data.errorDescription);
}
if (data.status === 'ready') {
return data.solution;
}
// Wait before retry
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
async solveReCaptchaV2(websiteKey, websiteURL) {
const { data } = await this.client.post('/createTask', {
clientKey: this.clientKey,
task: {
type: 'ReCaptchaV2TaskProxyless',
websiteURL: websiteURL,
websiteKey: websiteKey
}
});
if (data.errorId !== 0) {
throw new Error(data.errorDescription);
}
return this.pollForSolution(data.taskId);
}
}
// Initialize service
const captchaSolver = new AI4CAPService(CLIENT_KEY);
// API endpoint to solve uploaded CAPTCHA
app.post('/api/solve-captcha', upload.single('captcha'), async (req, res) => {
try {
// Read uploaded file
const imageBuffer = await fs.readFile(req.file.path);
const imageBase64 = imageBuffer.toString('base64');
// Solve CAPTCHA
const solution = await captchaSolver.solveCaptcha(imageBase64);
// Clean up uploaded file
await fs.unlink(req.file.path);
res.json({
success: true,
solution: solution.text,
confidence: solution.confidence
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
// API endpoint for reCAPTCHA v2
app.post('/api/solve-recaptcha', express.json(), async (req, res) => {
try {
const { sitekey, pageurl } = req.body;
const solution = await captchaSolver.solveReCaptchaV2(sitekey, pageurl);
res.json({
success: true,
token: solution.gRecaptchaResponse
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
// AI4CAP.COM React Hook Example
import { useState, useCallback } from 'react';
import axios from 'axios';
const CLIENT_KEY = process.env.REACT_APP_AI4CAP_CLIENT_KEY;
const BASE_URL = 'https://api.ai4cap.com';
// Custom hook for CAPTCHA solving
export const useAI4CAP = () => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const solveCaptcha = useCallback(async (imageBase64) => {
setIsLoading(true);
setError(null);
try {
// Create task
const createResponse = await axios.post(
`${BASE_URL}/createTask`,
{
clientKey: CLIENT_KEY,
task: {
type: 'ImageToTextTask',
body: imageBase64
}
}
);
if (createResponse.data.errorId !== 0) {
throw new Error(createResponse.data.errorDescription);
}
const taskId = createResponse.data.taskId;
// Poll for solution
while (true) {
const resultResponse = await axios.post(
`${BASE_URL}/getTaskResult`,
{
clientKey: CLIENT_KEY,
taskId: taskId
}
);
const result = resultResponse.data;
if (result.errorId !== 0) {
throw new Error(result.errorDescription);
}
if (result.status === 'ready') {
setIsLoading(false);
return result.solution;
}
// Wait before retry
await new Promise(resolve => setTimeout(resolve, 2000));
}
} catch (err) {
setError(err.message);
setIsLoading(false);
throw err;
}
}, []);
const solveReCaptchaV2 = useCallback(async (websiteKey, websiteURL) => {
setIsLoading(true);
setError(null);
try {
// Create task
const createResponse = await axios.post(
`${BASE_URL}/createTask`,
{
clientKey: CLIENT_KEY,
task: {
type: 'ReCaptchaV2TaskProxyless',
websiteURL: websiteURL,
websiteKey: websiteKey
}
}
);
if (createResponse.data.errorId !== 0) {
throw new Error(createResponse.data.errorDescription);
}
const taskId = createResponse.data.taskId;
// Poll for solution
while (true) {
const resultResponse = await axios.post(
`${BASE_URL}/getTaskResult`,
{
clientKey: CLIENT_KEY,
taskId: taskId
}
);
const result = resultResponse.data;
if (result.errorId !== 0) {
throw new Error(result.errorDescription);
}
if (result.status === 'ready') {
setIsLoading(false);
return result.solution.gRecaptchaResponse;
}
// Wait before retry
await new Promise(resolve => setTimeout(resolve, 2000));
}
} catch (err) {
setError(err.message);
setIsLoading(false);
throw err;
}
}, []);
return {
solveCaptcha,
solveReCaptchaV2,
isLoading,
error
};
};
// React component example
import React, { useState } from 'react';
import { useAI4CAP } from './useAI4CAP';
function CaptchaForm() {
const [captchaImage, setCaptchaImage] = useState('');
const [solution, setSolution] = useState('');
const { solveCaptcha, isLoading, error } = useAI4CAP();
const handleFileChange = (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onloadend = () => {
setCaptchaImage(reader.result.split(',')[1]);
};
reader.readAsDataURL(file);
};
const handleSolve = async () => {
try {
const result = await solveCaptcha(captchaImage);
setSolution(result.text);
} catch (err) {
console.error('Failed to solve CAPTCHA:', err);
}
};
return (
<div className="captcha-form">
<h2>AI4CAP.COM CAPTCHA Solver</h2>
<input
type="file"
accept="image/*"
onChange={handleFileChange}
disabled={isLoading}
/>
<button
onClick={handleSolve}
disabled={!captchaImage || isLoading}
>
{isLoading ? 'Solving...' : 'Solve CAPTCHA'}
</button>
{error && (
<div className="error">Error: {error}</div>
)}
{solution && (
<div className="solution">
<h3>Solution:</h3>
<input
type="text"
value={solution}
readOnly
/>
</div>
)}
</div>
);
}
export default CaptchaForm;
<?php
// AI4CAP.COM PHP Example
class AI4CAPClient {
private $clientKey;
private $baseUrl = 'https://api.ai4cap.com';
public function __construct($clientKey) {
$this->clientKey = $clientKey;
}
public function solveImageCaptcha($imagePath) {
// Read and encode image
$imageData = file_get_contents($imagePath);
$imageBase64 = base64_encode($imageData);
// Create task
$taskId = $this->createTask([
'type' => 'ImageToTextTask',
'body' => $imageBase64
]);
// Poll for solution
$solution = $this->getTaskResult($taskId);
return $solution['text'];
}
public function solveReCaptchaV2($websiteKey, $websiteURL) {
// Create reCAPTCHA task
$taskId = $this->createTask([
'type' => 'ReCaptchaV2TaskProxyless',
'websiteKey' => $websiteKey,
'websiteURL' => $websiteURL
]);
// Poll for solution
$solution = $this->getTaskResult($taskId);
return $solution['gRecaptchaResponse'];
}
private function createTask($task) {
$ch = curl_init($this->baseUrl . '/createTask');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'clientKey' => $this->clientKey,
'task' => $task
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
if ($result['errorId'] !== 0) {
throw new Exception('Failed to create task: ' . $result['errorDescription']);
}
return $result['taskId'];
}
private function getTaskResult($taskId) {
while (true) {
$ch = curl_init($this->baseUrl . '/getTaskResult');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'clientKey' => $this->clientKey,
'taskId' => $taskId
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
if ($result['errorId'] !== 0) {
throw new Exception('Failed to get task result: ' . $result['errorDescription']);
}
if ($result['status'] == 'ready') {
return $result['solution'];
}
// Wait 2 seconds before retry
sleep(2);
}
}
}
// Example usage
try {
$client = new AI4CAPClient('your_api_key_here');
// Solve image CAPTCHA
$solution = $client->solveImageCaptcha('captcha.png');
echo "CAPTCHA solution: " . $solution . "\n";
// Solve reCAPTCHA v2
$token = $client->solveReCaptchaV2(
'6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-',
'https://example.com/form'
);
echo "reCAPTCHA token: " . $token . "\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>
<?php
// AI4CAP.COM Laravel Service Provider
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
class AI4CAPService
{
protected $clientKey;
protected $baseUrl = 'https://api.ai4cap.com';
public function __construct()
{
$this->clientKey = config('services.ai4cap.client_key');
}
/**
* Solve an image CAPTCHA
*/
public function solveImage($imagePath)
{
$imageBase64 = base64_encode(file_get_contents($imagePath));
$response = Http::post($this->baseUrl . '/createTask', [
'clientKey' => $this->clientKey,
'task' => [
'type' => 'ImageToTextTask',
'body' => $imageBase64
]
]);
if (!$response->successful() || $response->json()['errorId'] !== 0) {
throw new \Exception('Failed to create task: ' . $response->json()['errorDescription']);
}
$taskId = $response->json()['taskId'];
return $this->pollForSolution($taskId);
}
/**
* Solve reCAPTCHA v2
*/
public function solveReCaptchaV2($websiteKey, $websiteURL)
{
$response = Http::post($this->baseUrl . '/createTask', [
'clientKey' => $this->clientKey,
'task' => [
'type' => 'ReCaptchaV2TaskProxyless',
'websiteKey' => $websiteKey,
'websiteURL' => $websiteURL
]
]);
if (!$response->successful() || $response->json()['errorId'] !== 0) {
throw new \Exception('Failed to create reCAPTCHA task: ' . $response->json()['errorDescription']);
}
$taskId = $response->json()['taskId'];
$solution = $this->pollForSolution($taskId);
return $solution['gRecaptchaResponse'];
}
/**
* Poll for CAPTCHA solution
*/
protected function pollForSolution($taskId)
{
$attempts = 0;
$maxAttempts = 30; // 60 seconds timeout
while ($attempts < $maxAttempts) {
$response = Http::post($this->baseUrl . '/getTaskResult', [
'clientKey' => $this->clientKey,
'taskId' => $taskId
]);
$result = $response->json();
if ($result['errorId'] !== 0) {
throw new \Exception('Failed to get task result: ' . $result['errorDescription']);
}
if ($result['status'] === 'ready') {
return $result['solution'];
}
sleep(2);
$attempts++;
}
throw new \Exception('CAPTCHA solving timeout');
}
/**
* Get account balance
*/
public function getBalance()
{
return Cache::remember('ai4cap_balance', 300, function () {
$response = Http::post($this->baseUrl . '/getBalance', [
'clientKey' => $this->clientKey
]);
if ($response->json()['errorId'] !== 0) {
throw new \Exception('Failed to get balance: ' . $response->json()['errorDescription']);
}
return $response->json()['balance'];
});
}
}
// Laravel Controller Example
namespace App\Http\Controllers;
use App\Services\AI4CAPService;
use Illuminate\Http\Request;
class CaptchaController extends Controller
{
protected $captchaService;
public function __construct(AI4CAPService $captchaService)
{
$this->captchaService = $captchaService;
}
public function solve(Request $request)
{
$request->validate([
'captcha' => 'required|image|max:2048'
]);
try {
$path = $request->file('captcha')->getRealPath();
$solution = $this->captchaService->solveImage($path);
return response()->json([
'success' => true,
'solution' => $solution
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'error' => $e->getMessage()
], 500);
}
}
public function solveReCaptcha(Request $request)
{
$request->validate([
'sitekey' => 'required|string',
'pageurl' => 'required|url'
]);
try {
$token = $this->captchaService->solveReCaptchaV2(
$request->sitekey,
$request->pageurl
);
return response()->json([
'success' => true,
'token' => $token
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'error' => $e->getMessage()
], 500);
}
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text;
using Newtonsoft.Json;
// AI4CAP.COM C# Client
public class AI4CAPClient
{
private readonly HttpClient _httpClient;
private readonly string _clientKey;
private const string BaseUrl = "https://api.ai4cap.com";
public AI4CAPClient(string clientKey)
{
_clientKey = clientKey;
_httpClient = new HttpClient();
}
public async Task<string> SolveImageCaptchaAsync(string imagePath)
{
// Read and encode image
byte[] imageBytes = await File.ReadAllBytesAsync(imagePath);
string imageBase64 = Convert.ToBase64String(imageBytes);
// Create task
var createRequest = new
{
clientKey = _clientKey,
task = new
{
type = "ImageToTextTask",
body = imageBase64
}
};
var createResponse = await _httpClient.PostAsync(
$"{BaseUrl}/createTask",
new StringContent(JsonConvert.SerializeObject(createRequest), Encoding.UTF8, "application/json")
);
var createResult = JsonConvert.DeserializeObject<dynamic>(
await createResponse.Content.ReadAsStringAsync()
);
if (createResult.errorId != 0)
{
throw new Exception($"Failed to create task: {createResult.errorDescription}");
}
string taskId = createResult.taskId;
// Poll for solution
var solution = await GetTaskResultAsync(taskId);
return solution.text;
}
public async Task<string> SolveReCaptchaV2Async(string websiteKey, string websiteURL)
{
var createRequest = new
{
clientKey = _clientKey,
task = new
{
type = "ReCaptchaV2TaskProxyless",
websiteKey = websiteKey,
websiteURL = websiteURL
}
};
var createResponse = await _httpClient.PostAsync(
$"{BaseUrl}/createTask",
new StringContent(JsonConvert.SerializeObject(createRequest), Encoding.UTF8, "application/json")
);
var createResult = JsonConvert.DeserializeObject<dynamic>(
await createResponse.Content.ReadAsStringAsync()
);
if (createResult.errorId != 0)
{
throw new Exception($"Failed to create task: {createResult.errorDescription}");
}
string taskId = createResult.taskId;
var solution = await GetTaskResultAsync(taskId);
return solution.gRecaptchaResponse;
}
private async Task<dynamic> GetTaskResultAsync(string taskId)
{
while (true)
{
var resultRequest = new
{
clientKey = _clientKey,
taskId = taskId
};
var response = await _httpClient.PostAsync(
$"{BaseUrl}/getTaskResult",
new StringContent(JsonConvert.SerializeObject(resultRequest), Encoding.UTF8, "application/json")
);
var result = JsonConvert.DeserializeObject<dynamic>(
await response.Content.ReadAsStringAsync()
);
if (result.errorId != 0)
{
throw new Exception($"Failed to get task result: {result.errorDescription}");
}
if (result.status == "ready")
{
return result.solution;
}
// Wait 2 seconds before retry
await Task.Delay(2000);
}
}
}
// Example usage
class Program
{
static async Task Main(string[] args)
{
var client = new AI4CAPClient("your_api_key_here");
try
{
// Solve image CAPTCHA
string solution = await client.SolveImageCaptchaAsync("captcha.png");
Console.WriteLine($"CAPTCHA solution: {solution}");
// Solve reCAPTCHA v2
string token = await client.SolveReCaptchaV2Async(
"6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
"https://example.com/form"
);
Console.WriteLine($"reCAPTCHA token: {token}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
// AI4CAP.COM ASP.NET Core Integration
namespace YourApp.Services
{
public interface IAI4CAPService
{
Task<string> SolveImageAsync(IFormFile image);
Task<string> SolveReCaptchaV2Async(string websiteKey, string websiteURL);
Task<decimal> GetBalanceAsync();
}
public class AI4CAPService : IAI4CAPService
{
private readonly HttpClient _httpClient;
private readonly IConfiguration _configuration;
private readonly ILogger<AI4CAPService> _logger;
private readonly string _clientKey;
public AI4CAPService(
HttpClient httpClient,
IConfiguration configuration,
ILogger<AI4CAPService> logger)
{
_httpClient = httpClient;
_configuration = configuration;
_logger = logger;
_clientKey = _configuration["AI4CAP:ClientKey"];
_httpClient.BaseAddress = new Uri("https://api.ai4cap.com/");
}
public async Task<string> SolveImageAsync(IFormFile image)
{
using var memoryStream = new MemoryStream();
await image.CopyToAsync(memoryStream);
var imageBase64 = Convert.ToBase64String(memoryStream.ToArray());
var response = await _httpClient.PostAsJsonAsync("createTask", new
{
clientKey = _clientKey,
task = new
{
type = "ImageToTextTask",
body = imageBase64
}
});
var result = await response.Content.ReadFromJsonAsync<CreateTaskResponse>();
if (result.ErrorId != 0)
{
throw new Exception($"Failed to create task: {result.ErrorDescription}");
}
var solution = await GetTaskResultAsync(result.TaskId);
return solution.Text;
}
public async Task<string> SolveReCaptchaV2Async(string websiteKey, string websiteURL)
{
var response = await _httpClient.PostAsJsonAsync("createTask", new
{
clientKey = _clientKey,
task = new
{
type = "ReCaptchaV2TaskProxyless",
websiteKey,
websiteURL
}
});
var result = await response.Content.ReadFromJsonAsync<CreateTaskResponse>();
if (result.ErrorId != 0)
{
throw new Exception($"Failed to create task: {result.ErrorDescription}");
}
var solution = await GetTaskResultAsync(result.TaskId);
return solution.GRecaptchaResponse;
}
public async Task<decimal> GetBalanceAsync()
{
var response = await _httpClient.PostAsJsonAsync("getBalance", new
{
clientKey = _clientKey
});
var result = await response.Content.ReadFromJsonAsync<BalanceResponse>();
if (result.ErrorId != 0)
{
throw new Exception($"Failed to get balance: {result.ErrorDescription}");
}
return result.Balance;
}
private async Task<CaptchaSolution> GetTaskResultAsync(string taskId)
{
var attempts = 0;
const int maxAttempts = 30;
while (attempts < maxAttempts)
{
var response = await _httpClient.PostAsJsonAsync("getTaskResult", new
{
clientKey = _clientKey,
taskId = taskId
});
var result = await response.Content.ReadFromJsonAsync<TaskResultResponse>();
if (result.ErrorId != 0)
{
throw new Exception($"Failed to get task result: {result.ErrorDescription}");
}
if (result.Status == "ready")
{
return result.Solution;
}
await Task.Delay(2000);
attempts++;
}
throw new TimeoutException("CAPTCHA solving timeout");
}
}
// DTOs
public class CaptchaSolution
{
public string Text { get; set; }
public string GRecaptchaResponse { get; set; }
}
public class CreateTaskResponse
{
public int ErrorId { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
public string TaskId { get; set; }
}
public class TaskResultResponse
{
public int ErrorId { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
public string Status { get; set; }
public CaptchaSolution Solution { get; set; }
}
public class BalanceResponse
{
public int ErrorId { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
public decimal Balance { get; set; }
}
}
// Controller
[ApiController]
[Route("api/[controller]")]
public class CaptchaController : ControllerBase
{
private readonly IAI4CAPService _captchaService;
public CaptchaController(IAI4CAPService captchaService)
{
_captchaService = captchaService;
}
[HttpPost("solve")]
public async Task<IActionResult> SolveCaptcha([Required] IFormFile captcha)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
try
{
var solution = await _captchaService.SolveImageAsync(captcha);
return Ok(new
{
success = true,
solution = solution
});
}
catch (Exception ex)
{
return StatusCode(500, new
{
success = false,
error = ex.Message
});
}
}
[HttpPost("solve-recaptcha")]
public async Task<IActionResult> SolveReCaptcha([FromBody] ReCaptchaRequest request)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
try
{
var token = await _captchaService.SolveReCaptchaV2Async(
request.WebsiteKey,
request.WebsiteURL
);
return Ok(new
{
success = true,
token
});
}
catch (Exception ex)
{
return StatusCode(500, new
{
success = false,
error = ex.Message
});
}
}
}
// Startup configuration
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient<IAI4CAPService, AI4CAPService>();
services.AddControllers();
}
}
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
// AI4CAP.COM Go Client
const (
ClientKey = "your_api_key_here"
BaseURL = "https://api.ai4cap.com"
)
type AI4CAPClient struct {
clientKey string
httpClient *http.Client
}
type CreateTaskRequest struct {
ClientKey string `json:"clientKey"`
Task map[string]interface{} `json:"task"`
}
type CreateTaskResponse struct {
ErrorId int `json:"errorId"`
ErrorCode string `json:"errorCode"`
ErrorDescription string `json:"errorDescription"`
TaskId string `json:"taskId"`
}
type GetTaskResultRequest struct {
ClientKey string `json:"clientKey"`
TaskId string `json:"taskId"`
}
type TaskResultResponse struct {
ErrorId int `json:"errorId"`
ErrorCode string `json:"errorCode"`
ErrorDescription string `json:"errorDescription"`
Status string `json:"status"`
Solution map[string]interface{} `json:"solution"`
}
func NewAI4CAPClient(clientKey string) *AI4CAPClient {
return &AI4CAPClient{
clientKey: clientKey,
httpClient: &http.Client{Timeout: 30 * time.Second},
}
}
func (c *AI4CAPClient) SolveImageCaptcha(imagePath string) (string, error) {
// Read and encode image
imageData, err := os.ReadFile(imagePath)
if err != nil {
return "", fmt.Errorf("failed to read image: %w", err)
}
imageBase64 := base64.StdEncoding.EncodeToString(imageData)
// Create task
task := map[string]interface{}{
"type": "ImageToTextTask",
"body": imageBase64,
}
taskID, err := c.createTask(task)
if err != nil {
return "", err
}
// Get task result
solution, err := c.getTaskResult(taskID)
if err != nil {
return "", err
}
return solution["text"].(string), nil
}
func (c *AI4CAPClient) SolveReCaptchaV2(websiteKey, websiteURL string) (string, error) {
// Create task
task := map[string]interface{}{
"type": "ReCaptchaV2TaskProxyless",
"websiteKey": websiteKey,
"websiteURL": websiteURL,
}
taskID, err := c.createTask(task)
if err != nil {
return "", err
}
// Get task result
solution, err := c.getTaskResult(taskID)
if err != nil {
return "", err
}
return solution["gRecaptchaResponse"].(string), nil
}
func (c *AI4CAPClient) createTask(task map[string]interface{}) (string, error) {
reqBody := CreateTaskRequest{
ClientKey: c.clientKey,
Task: task,
}
jsonData, err := json.Marshal(reqBody)
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", BaseURL+"/createTask", bytes.NewBuffer(jsonData))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
var result CreateTaskResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", err
}
if result.ErrorId != 0 {
return "", fmt.Errorf("failed to create task: %s", result.ErrorDescription)
}
return result.TaskId, nil
}
func (c *AI4CAPClient) getTaskResult(taskID string) (map[string]interface{}, error) {
reqBody := GetTaskResultRequest{
ClientKey: c.clientKey,
TaskId: taskID,
}
for {
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", BaseURL+"/getTaskResult", bytes.NewBuffer(jsonData))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result TaskResultResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
if result.ErrorId != 0 {
return nil, fmt.Errorf("failed to get task result: %s", result.ErrorDescription)
}
if result.Status == "ready" {
return result.Solution, nil
}
time.Sleep(2 * time.Second)
}
}
// Example usage
func main() {
client := NewAI4CAPClient(ClientKey)
// Solve image CAPTCHA
solution, err := client.SolveImageCaptcha("captcha.png")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("CAPTCHA solution: %s\n", solution)
// Solve reCAPTCHA v2
token, err := client.SolveReCaptchaV2(
"6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
"https://example.com/form",
)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("reCAPTCHA token: %s\n", token)
}
package main
import (
"context"
"fmt"
"sync"
)
// AI4CAP.COM Concurrent Go Example
type ConcurrentSolver struct {
client *AI4CAPClient
workerPool chan struct{}
resultCache sync.Map
}
func NewConcurrentSolver(apiKey string, maxWorkers int) *ConcurrentSolver {
return &ConcurrentSolver{
client: NewAI4CAPClient(apiKey),
workerPool: make(chan struct{}, maxWorkers),
}
}
func (cs *ConcurrentSolver) SolveMultiple(imagePaths []string) ([]string, error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
results := make([]string, len(imagePaths))
errors := make([]error, len(imagePaths))
var wg sync.WaitGroup
for i, path := range imagePaths {
wg.Add(1)
go func(index int, imagePath string) {
defer wg.Done()
// Acquire worker slot
cs.workerPool <- struct{}{}
defer func() { <-cs.workerPool }()
// Check cache
if cached, ok := cs.resultCache.Load(imagePath); ok {
results[index] = cached.(string)
return
}
// Solve CAPTCHA
solution, err := cs.client.SolveImageCaptcha(imagePath)
if err != nil {
errors[index] = err
return
}
results[index] = solution
cs.resultCache.Store(imagePath, solution)
}(i, path)
}
wg.Wait()
// Check for errors
for _, err := range errors {
if err != nil {
return nil, err
}
}
return results, nil
}
// Batch processing with rate limiting
type BatchProcessor struct {
solver *ConcurrentSolver
rateLimiter *time.Ticker
}
func NewBatchProcessor(apiKey string) *BatchProcessor {
return &BatchProcessor{
solver: NewConcurrentSolver(apiKey, 10),
rateLimiter: time.NewTicker(100 * time.Millisecond), // 10 requests/second
}
}
func (bp *BatchProcessor) ProcessBatch(imagePaths []string, batchSize int) ([]string, error) {
var allResults []string
for i := 0; i < len(imagePaths); i += batchSize {
<-bp.rateLimiter.C // Rate limiting
end := i + batchSize
if end > len(imagePaths) {
end = len(imagePaths)
}
batch := imagePaths[i:end]
results, err := bp.solver.SolveMultiple(batch)
if err != nil {
return nil, fmt.Errorf("batch %d failed: %w", i/batchSize, err)
}
allResults = append(allResults, results...)
fmt.Printf("Processed batch %d/%d\n", i/batchSize+1, (len(imagePaths)+batchSize-1)/batchSize)
}
return allResults, nil
}
// Example usage
func main() {
processor := NewBatchProcessor(APIKey)
// Process 100 CAPTCHAs in batches of 10
imagePaths := make([]string, 100)
for i := range imagePaths {
imagePaths[i] = fmt.Sprintf("captcha_%d.png", i+1)
}
results, err := processor.ProcessBatch(imagePaths, 10)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Successfully solved %d CAPTCHAs\n", len(results))
}
require 'net/http'
require 'json'
require 'base64'
# AI4CAP.COM Ruby Client
class AI4CAPClient
CLIENT_KEY = 'your_api_key_here'
BASE_URL = 'https://api.ai4cap.com'
def initialize(client_key = CLIENT_KEY)
@client_key = client_key
end
def solve_image_captcha(image_path)
# Read and encode image
image_data = File.read(image_path)
image_base64 = Base64.encode64(image_data).strip
# Create task
task_id = create_task({
type: 'ImageToTextTask',
body: image_base64
})
# Poll for solution
solution = get_task_result(task_id)
solution['text']
end
def solve_recaptcha_v2(website_key, website_url)
# Create reCAPTCHA task
task_id = create_task({
type: 'ReCaptchaV2TaskProxyless',
websiteKey: website_key,
websiteURL: website_url
})
# Poll for solution
solution = get_task_result(task_id)
solution['gRecaptchaResponse']
end
private
def create_task(task)
uri = URI("#{BASE_URL}/createTask")
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/json'
request.body = {
clientKey: @client_key,
task: task
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
result = JSON.parse(response.body)
if result['errorId'] != 0
raise "Failed to create task: #{result['errorDescription']}"
end
result['taskId']
end
def get_task_result(task_id)
uri = URI("#{BASE_URL}/getTaskResult")
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/json'
loop do
request.body = {
clientKey: @client_key,
taskId: task_id
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
result = JSON.parse(response.body)
if result['errorId'] != 0
raise "Failed to get task result: #{result['errorDescription']}"
end
return result['solution'] if result['status'] == 'ready'
# Wait 2 seconds before retry
sleep 2
end
end
end
# Example usage
begin
client = AI4CAPClient.new
# Solve image CAPTCHA
solution = client.solve_image_captcha('captcha.png')
puts "CAPTCHA solution: #{solution}"
# Solve reCAPTCHA v2
token = client.solve_recaptcha_v2(
'6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-',
'https://example.com/form'
)
puts "reCAPTCHA token: #{token}"
rescue => e
puts "Error: #{e.message}"
end
# AI4CAP.COM Rails Integration
# app/services/ai4cap_service.rb
require 'net/http'
require 'json'
require 'base64'
class AI4CAPService
include ActiveSupport::Configurable
config_accessor :client_key
self.client_key = Rails.application.credentials.ai4cap[:client_key]
BASE_URL = 'https://api.ai4cap.com'
def initialize
@client_key = self.class.client_key
end
def solve_image(image_file)
image_base64 = if image_file.is_a?(String)
Base64.encode64(File.read(image_file)).strip
else
Base64.encode64(image_file.read).strip
end
task_id = create_task({
type: 'ImageToTextTask',
body: image_base64
})
poll_for_solution(task_id)['text']
end
def solve_recaptcha_v2(website_key, website_url, proxy: nil)
task = {
type: proxy ? 'ReCaptchaV2Task' : 'ReCaptchaV2TaskProxyless',
websiteKey: website_key,
websiteURL: website_url
}
if proxy
task[:proxy] = proxy[:proxy]
task[:proxyType] = proxy[:proxyType] || 'http'
end
task_id = create_task(task)
poll_for_solution(task_id)['gRecaptchaResponse']
end
def get_balance
Rails.cache.fetch('ai4cap_balance', expires_in: 5.minutes) do
uri = URI("#{BASE_URL}/getBalance")
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/json'
request.body = { clientKey: @client_key }.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
result = JSON.parse(response.body)
if result['errorId'] != 0
raise "Failed to get balance: #{result['errorDescription']}"
end
result['balance']
end
end
private
def create_task(task)
uri = URI("#{BASE_URL}/createTask")
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/json'
request.body = {
clientKey: @client_key,
task: task
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
result = JSON.parse(response.body)
if result['errorId'] != 0
raise "Failed to create task: #{result['errorDescription']}"
end
result['taskId']
end
def poll_for_solution(task_id)
uri = URI("#{BASE_URL}/getTaskResult")
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/json'
attempts = 0
max_attempts = 30
while attempts < max_attempts
request.body = {
clientKey: @client_key,
taskId: task_id
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
result = JSON.parse(response.body)
if result['errorId'] != 0
raise "Failed to get task result: #{result['errorDescription']}"
end
return result['solution'] if result['status'] == 'ready'
sleep 2
attempts += 1
end
raise 'CAPTCHA solving timeout'
end
end
# app/controllers/captcha_controller.rb
class CaptchaController < ApplicationController
def solve
service = AI4CAPService.new
if params[:captcha_image]
solution = service.solve_image(params[:captcha_image])
render json: { success: true, solution: solution }
else
render json: { success: false, error: 'No image provided' }, status: 400
end
rescue => e
render json: { success: false, error: e.message }, status: 500
end
def solve_recaptcha
service = AI4CAPService.new
token = service.solve_recaptcha_v2(
params[:sitekey],
params[:pageurl]
)
render json: { success: true, token: token }
rescue => e
render json: { success: false, error: e.message }, status: 500
end
end
# config/routes.rb
Rails.application.routes.draw do
post 'captcha/solve', to: 'captcha#solve'
post 'captcha/solve_recaptcha', to: 'captcha#solve_recaptcha'
end
Complete examples with error handling, retry logic, and best practices
View Repository →Get your API key and start solving CAPTCHAs in minutes