Step-by-step instructions and best practices for integrating AI4CAP.COM into your applications, with examples in multiple programming languages.
By Integration Team
•
December 28, 2023
•
25 min read
Get API Key
Sign up and get your API key
2 minInstall SDK
Choose and install language SDK
5 minConfigure Client
Initialize with your API key
3 minImplement Logic
Add CAPTCHA solving to your flow
10 minTest & Deploy
Verify and go to production
5 minTotal Integration Time: ~25 minutes
Most developers complete their first integration in under 30 minutes
# 1. Install SDK
pip install ai4cap
# 2. Basic usage
from ai4cap import Client
# Initialize client
client = Client('your_api_key_here')
# Solve image CAPTCHA
with open('captcha.png', 'rb') as f:
image_data = f.read()
result = client.solve({
'type': 'image',
'image': base64.b64encode(image_data).decode()
})
print(f"Solution: {result['solution']}")
# Solve reCAPTCHA v2
result = client.solve({
'type': 'recaptcha_v2',
'sitekey': '6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-',
'pageurl': 'https://example.com'
})
print(f"Token: {result['solution']}")
Key Features:
// 1. Install SDK
npm install @ai4cap/sdk
// 2. Basic usage
const { AI4CAP } = require('@ai4cap/sdk');
// Initialize client
const client = new AI4CAP('your_api_key_here');
// Solve image CAPTCHA
const fs = require('fs');
const imageBase64 = fs.readFileSync('captcha.png', 'base64');
const result = await client.solve({
type: 'image',
image: imageBase64
});
console.log('Solution:', result.solution);
// Solve reCAPTCHA v2
const recaptchaResult = await client.solve({
type: 'recaptcha_v2',
sitekey: '6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-',
pageurl: 'https://example.com'
});
console.log('Token:', recaptchaResult.solution);
Key Features:
# Robust error handling with retry logic
import time
from typing import Optional, Dict, Any
import logging
class CaptchaSolverWithRetry:
def __init__(self, api_key: str, max_retries: int = 3):
self.client = Client(api_key)
self.max_retries = max_retries
self.logger = logging.getLogger(__name__)
def solve_with_retry(
self,
captcha_params: Dict[str, Any],
retry_delay: float = 2.0
) -> Optional[str]:
"""Solve CAPTCHA with automatic retry on failure"""
last_error = None
for attempt in range(self.max_retries):
try:
# Log attempt
self.logger.info(f"Solving CAPTCHA (attempt {attempt + 1}/{self.max_retries})")
# Submit CAPTCHA
result = self.client.solve(captcha_params)
# Validate solution
if self.validate_solution(result):
self.logger.info("CAPTCHA solved successfully")
return result['solution']
else:
raise ValueError("Invalid solution format")
except RateLimitError as e:
# Handle rate limiting
self.logger.warning(f"Rate limited: {e}")
wait_time = e.retry_after or (retry_delay * (2 ** attempt))
time.sleep(wait_time)
except NetworkError as e:
# Handle network issues
self.logger.error(f"Network error: {e}")
last_error = e
time.sleep(retry_delay)
except InsufficientBalanceError as e:
# Handle billing issues
self.logger.error(f"Insufficient balance: {e}")
self.notify_admin("Low balance alert", str(e))
raise
except Exception as e:
# Handle unexpected errors
self.logger.error(f"Unexpected error: {e}")
last_error = e
if attempt < self.max_retries - 1:
time.sleep(retry_delay)
# All retries failed
self.logger.error(f"Failed to solve CAPTCHA after {self.max_retries} attempts")
raise last_error or Exception("Max retries exceeded")
// Performance monitoring and alerting
const prometheus = require('prom-client');
class CaptchaMetrics {
constructor() {
// Define metrics
this.solveDuration = new prometheus.Histogram({
name: 'captcha_solve_duration_seconds',
help: 'Duration of CAPTCHA solving in seconds',
labelNames: ['type', 'status'],
buckets: [0.1, 0.5, 1, 2, 5, 10, 30]
});
this.solveCounter = new prometheus.Counter({
name: 'captcha_solve_total',
help: 'Total number of CAPTCHA solve attempts',
labelNames: ['type', 'status']
});
this.balanceGauge = new prometheus.Gauge({
name: 'captcha_account_balance',
help: 'Current account balance'
});
this.errorRate = new prometheus.Counter({
name: 'captcha_errors_total',
help: 'Total number of CAPTCHA solving errors',
labelNames: ['type', 'error_type']
});
}
async trackSolve(captchaType, solveFunction) {
const timer = this.solveDuration.startTimer({ type: captchaType });
try {
const result = await solveFunction();
timer({ status: 'success' });
this.solveCounter.inc({ type: captchaType, status: 'success' });
return result;
} catch (error) {
timer({ status: 'error' });
this.solveCounter.inc({ type: captchaType, status: 'error' });
this.errorRate.inc({
type: captchaType,
error_type: error.constructor.name
});
throw error;
}
}
updateBalance(balance) {
this.balanceGauge.set(balance);
// Alert if balance is low
if (balance < 10) {
this.sendAlert('Low balance warning', `Balance: $${balance}`);
}
}
}
Issue | Cause | Solution |
---|---|---|
401 Unauthorized | Invalid API key | Verify API key in dashboard |
402 Payment Required | Insufficient balance | Add credits to account |
429 Too Many Requests | Rate limit exceeded | Implement request throttling |
Timeout errors | Network issues or complex CAPTCHA | Increase timeout, retry request |
Invalid solution | CAPTCHA expired or changed | Refresh and retry solving |
Integrating AI4CAP.COM into your application is straightforward with our comprehensive SDKs and documentation. Whether you're building a web scraper, automating forms, or protecting your own services, our API provides reliable CAPTCHA solving that scales with your needs.
Follow this guide to implement a robust integration that handles errors gracefully, monitors performance, and provides a seamless experience for your users. With proper implementation, you can focus on your core business logic while we handle the complexity of CAPTCHA solving.