January 2025 • 15 min read
Complete Guide to Integrating CAPTCHA Solver API
Step-by-step tutorial on integrating AI4CAP.COM API into your applications. Learn authentication, error handling, best practices, and see working examples in Python, JavaScript, PHP, and more.
Whether you're building a web scraper, automating tests, or creating a bot, integrating a reliable CAPTCHA solver is crucial. This comprehensive guide will walk you through everything you need to know about integrating AI4CAP.COM's API into your application.
Quick Start Bonus
New users get $5 free credits instantly + $10 bonus on first deposit. That's enough for 1,500+ CAPTCHA solves!
Getting Started: Initial Setup
Step 1: Create Your Account
Sign up at AI4CAP.COM to get your API key. You'll receive $5 in credits immediately upon registration.
Create Free Account →Step 2: Get Your API Key
After registration, you'll see your API key on the dashboard. It looks like:
ai4cap_k_1234567890abcdef1234567890abcdef
Step 3: Choose Your Integration Method
API Overview and Authentication
Base URL and Headers
Base URL: https://api.ai4cap.com
Required Headers:
X-API-KEY: your-api-key-here
Content-Type: application/json
Optional Headers:
X-Client-ID: your-app-name
X-Request-ID: unique-request-id
Endpoint | Method | Description |
---|---|---|
/api/captcha/solve | POST | Create a new CAPTCHA solving task |
/api/captcha/result/:taskId | GET | Get task result |
/api/auth/profile | GET | Get account info and balance |
/api/captcha/report/:taskId | POST | Report incorrect solution |
Implementation Examples
import requests
import time
class AI4CAPClient:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://api.ai4cap.com"
def solve_captcha(self, captcha_type, **params):
"""Universal method for solving any CAPTCHA type"""
headers = {"X-API-KEY": self.api_key}
# Create task
response = requests.post(
f"{self.base_url}/api/captcha/solve",
headers=headers,
json={"type": captcha_type, **params}
)
response.raise_for_status()
task_id = response.json()["taskId"]
# Poll for result
return self._wait_for_result(task_id)
def _wait_for_result(self, task_id, timeout=120):
"""Poll for CAPTCHA solution with timeout"""
headers = {"X-API-KEY": self.api_key}
start_time = time.time()
while time.time() - start_time < timeout:
response = requests.get(
f"{self.base_url}/api/captcha/result/{task_id}",
headers=headers
)
data = response.json()
if data["status"] == "completed":
return data["solution"]
elif data["status"] == "failed":
raise Exception(f"Task failed: {data.get('error')}")
time.sleep(2) # Poll every 2 seconds
raise TimeoutError(f"Task {task_id} timed out")
# Usage example
client = AI4CAPClient("your-api-key")
# Solve reCAPTCHA v2
solution = client.solve_captcha(
"recaptcha_v2",
siteKey="6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
pageUrl="https://example.com"
)
print(f"Token: {solution['gRecaptchaResponse']}")
class AI4CAPClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.ai4cap.com';
}
async solveCaptcha(type, params) {
// Create task
const createResponse = await fetch(`${this.baseUrl}/api/captcha/solve`, {
method: 'POST',
headers: {
'X-API-KEY': this.apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({ type, ...params })
});
if (!createResponse.ok) {
throw new Error(`HTTP error! status: ${createResponse.status}`);
}
const { taskId } = await createResponse.json();
// Wait for solution
return await this.waitForResult(taskId);
}
async waitForResult(taskId, timeout = 120000) {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
const response = await fetch(
`${this.baseUrl}/api/captcha/result/${taskId}`,
{ headers: { 'X-API-KEY': this.apiKey } }
);
const data = await response.json();
if (data.status === 'completed') {
return data.solution;
} else if (data.status === 'failed') {
throw new Error(`Task failed: ${data.error || 'Unknown error'}`);
}
// Wait 2 seconds before next poll
await new Promise(resolve => setTimeout(resolve, 2000));
}
throw new Error(`Task ${taskId} timed out`);
}
}
// Usage with async/await
async function solveCaptchaExample() {
const client = new AI4CAPClient('your-api-key');
try {
const solution = await client.solveCaptcha('recaptcha_v2', {
siteKey: '6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-',
pageUrl: 'https://example.com'
});
console.log('Token:', solution.gRecaptchaResponse);
// Use the token in your form submission
document.getElementById('g-recaptcha-response').value = solution.gRecaptchaResponse;
} catch (error) {
console.error('Error solving CAPTCHA:', error);
}
}
<?php
class AI4CAPClient {
private $apiKey;
private $baseUrl = 'https://api.ai4cap.com';
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
public function solveCaptcha($type, $params) {
// Create task
$ch = curl_init($this->baseUrl . '/api/captcha/solve');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(
array_merge(['type' => $type], $params)
));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-API-KEY: ' . $this->apiKey,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception('API request failed with code: ' . $httpCode);
}
$data = json_decode($response, true);
$taskId = $data['taskId'];
// Wait for result
return $this->waitForResult($taskId);
}
private function waitForResult($taskId, $timeout = 120) {
$startTime = time();
while (time() - $startTime < $timeout) {
$ch = curl_init($this->baseUrl . '/api/captcha/result/' . $taskId);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-KEY: ' . $this->apiKey]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if ($data['status'] === 'completed') {
return $data['solution'];
} elseif ($data['status'] === 'failed') {
throw new Exception('Task failed: ' . ($data['error'] ?? 'Unknown error'));
}
sleep(2); // Wait 2 seconds
}
throw new Exception('Task timeout');
}
}
// Usage example
$client = new AI4CAPClient('your-api-key');
try {
$solution = $client->solveCaptcha('recaptcha_v2', [
'siteKey' => '6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-',
'pageUrl' => 'https://example.com'
]);
echo "Token: " . $solution['gRecaptchaResponse'];
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
Error Handling and Edge Cases
Common Error Codes
Code | Message | Solution |
---|---|---|
401 | Invalid API key | Check your API key is correct |
402 | Insufficient balance | Add credits to your account |
429 | Rate limit exceeded | Implement exponential backoff |
500 | Internal server error | Retry after a few seconds |
Robust Error Handling Example
async function solveCaptchaWithRetry(client, type, params, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await client.solveCaptcha(type, params);
} catch (error) {
console.error(`Attempt ${attempt} failed:`, error.message);
// Don't retry on client errors (4xx)
if (error.message.includes('4')) {
throw error;
}
// Exponential backoff for server errors
if (attempt < maxRetries) {
const delay = Math.pow(2, attempt) * 1000;
console.log(`Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
throw new Error('Max retries exceeded');
}
Best Practices for Production
Performance Optimization
- • Use connection pooling for HTTP requests
- • Implement request queuing for bulk operations
- • Cache solutions when appropriate
- • Use webhooks instead of polling when possible
Security Considerations
- • Never expose API keys in client-side code
- • Use environment variables for credentials
- • Implement request signing for added security
- • Monitor API usage for anomalies
Cost Optimization
- • Set up usage alerts in your dashboard
- • Use appropriate CAPTCHA types (v2 is cheaper)
- • Implement smart retry logic
- • Report failed solutions for credits
Monitoring & Debugging
- • Log all API requests and responses
- • Track success rates by CAPTCHA type
- • Monitor solving times
- • Set up alerts for failures
Advanced Features
Proxy Support
For geo-restricted CAPTCHAs, you can specify proxy settings:
{
"type": "recaptcha_v2",
"siteKey": "...",
"pageUrl": "...",
"proxy": {
"type": "http",
"address": "proxy.example.com:8080",
"login": "username",
"password": "password"
}
}
Cookie Handling
Some sites require specific cookies for CAPTCHA solving:
{
"type": "recaptcha_v2",
"siteKey": "...",
"pageUrl": "...",
"cookies": "session_id=abc123; user_pref=xyz"
}
Webhook Notifications
Get instant notifications when CAPTCHAs are solved:
// Configure webhook in dashboard or via API
POST /api/webhooks
{
"url": "https://your-app.com/webhook",
"events": ["captcha.solved", "captcha.failed"],
"secret": "your-webhook-secret"
}
Testing Your Integration
Pro Tip: Use our test site keys for development. They always return successful solutions without consuming credits.
Test Site Keys
TEST-RECAPTCHA-V2-SITE-KEY
- Always succeeds for v2TEST-RECAPTCHA-V3-SITE-KEY
- Returns score 0.9 for v3TEST-HCAPTCHA-SITE-KEY
- Always succeeds for hCaptcha
Common Integration Issues
CORS Errors
The API doesn't support direct browser calls. Use a backend proxy or our JavaScript SDK which handles CORS.
Timeout Errors
Some CAPTCHAs take longer. Set your timeout to at least 120 seconds and implement proper retry logic.
Rate Limiting
Default limit is 100 requests/minute. Contact support for higher limits if needed for your use case.
Next Steps
Join Community
Get help from other developers
Written by AI4CAP Developer Relations Team