AI4CAP.COM

AI4CAP.COM Code Examples

Production-ready code examples in multiple programming languages. Copy, paste, and start solving CAPTCHAs in minutes.

Get API Key - $15 FreeView on GitHub

Quick Start

Get started in 5 minutes

SDKs Available

Official libraries for all languages

REST API

Simple HTTP endpoints

99.9% Uptime

Enterprise reliability

Python Examples

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}")

JavaScript Examples

// 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); } });

PHP Examples

<?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"; } ?>

C# Examples

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}"); } } }

Go Examples

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) }

Ruby Examples

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

Additional Resources

GitHub Repository

Complete examples with error handling, retry logic, and best practices

View Repository →

SDKs & Libraries

Official SDKs with full type support and documentation

Browse SDKs →

API Documentation

Complete API reference with all endpoints and parameters

Read Docs →

Ready to Integrate AI4CAP.COM?

Get your API key and start solving CAPTCHAs in minutes

Get Started - $15 FreeAPI Documentation