Tutorials

CAPTCHA Chains: Solving Sequential Challenges in Multi-Step Forms

Some forms don't ask for one CAPTCHA — they ask for two or three across different steps. Account registration might show reCAPTCHA v2 on the email step, then Turnstile on the payment step. Each CAPTCHA depends on the session state from the previous step, so solving them out of order or without carrying cookies forward causes failures.

Common CAPTCHA Chain Patterns

Pattern Example Complexity
Same type, multiple steps reCAPTCHA on step 1 and step 3 Low — same solving logic, just repeat
Mixed types across steps reCAPTCHA on login, Turnstile on checkout Medium — different solver configs per step
Conditional CAPTCHA CAPTCHA only appears after suspicious input High — detection logic required
Progressive difficulty Simple image CAPTCHA, then Enterprise reCAPTCHA High — different cost/time per step

Python: Sequential CAPTCHA Chain Solver

import requests
import time
from dataclasses import dataclass

API_KEY = "YOUR_API_KEY"
SUBMIT_URL = "https://ocr.captchaai.com/in.php"
RESULT_URL = "https://ocr.captchaai.com/res.php"


@dataclass
class CaptchaStep:
    step_name: str
    method: str          # userrecaptcha, turnstile, etc.
    sitekey: str
    pageurl: str
    extra_params: dict = None  # Additional solver params

    def __post_init__(self):
        if self.extra_params is None:
            self.extra_params = {}


def solve_captcha(step, cookies=None):
    """Solve a single CAPTCHA step, optionally with session cookies."""
    params = {
        "key": API_KEY,
        "method": step.method,
        "json": 1,
    }

    if step.method == "userrecaptcha":
        params["googlekey"] = step.sitekey
        params["pageurl"] = step.pageurl
    elif step.method == "turnstile":
        params["sitekey"] = step.sitekey
        params["pageurl"] = step.pageurl

    # Pass cookies for session-aware solving
    if cookies:
        cookie_str = "; ".join(f"{k}={v}" for k, v in cookies.items())
        params["cookies"] = cookie_str

    params.update(step.extra_params)

    resp = requests.post(SUBMIT_URL, data=params, timeout=30).json()
    if resp.get("status") != 1:
        raise RuntimeError(f"[{step.step_name}] Submit failed: {resp.get('request')}")

    task_id = resp["request"]

    for _ in range(60):
        time.sleep(5)
        poll = requests.get(RESULT_URL, params={
            "key": API_KEY, "action": "get",
            "id": task_id, "json": 1,
        }, timeout=15).json()

        if poll.get("request") == "CAPCHA_NOT_READY":
            continue
        if poll.get("status") == 1:
            return poll["request"]
        raise RuntimeError(f"[{step.step_name}] Solve failed: {poll.get('request')}")

    raise RuntimeError(f"[{step.step_name}] Timeout waiting for solution")


def solve_chain(steps, session=None):
    """
    Solve a chain of CAPTCHAs across form steps.
    Maintains session cookies between steps.
    """
    if session is None:
        session = requests.Session()

    results = {}

    for i, step in enumerate(steps):
        print(f"Step {i + 1}/{len(steps)}: {step.step_name}")

        # Get the page to collect fresh cookies and detect the CAPTCHA
        page_resp = session.get(step.pageurl)
        cookies = dict(session.cookies)

        # Solve the CAPTCHA
        start = time.monotonic()
        token = solve_captcha(step, cookies=cookies)
        elapsed = time.monotonic() - start
        print(f"  Solved in {elapsed:.1f}s")

        results[step.step_name] = {
            "token": token,
            "solve_time": round(elapsed, 1),
        }

        # Submit the form step with the token
        form_data = build_form_data(step, token)
        submit_resp = session.post(step.pageurl, data=form_data)

        if submit_resp.status_code != 200:
            raise RuntimeError(
                f"[{step.step_name}] Form submission failed: {submit_resp.status_code}"
            )

        print(f"  Form submitted — moving to next step")

        # Brief pause between steps (mimics human behavior)
        if i < len(steps) - 1:
            time.sleep(2)

    return results


def build_form_data(step, token):
    """Build form data for a given step. Customize per your target site."""
    data = {}

    if step.method == "userrecaptcha":
        data["g-recaptcha-response"] = token
    elif step.method == "turnstile":
        data["cf-turnstile-response"] = token

    return data


# Example: 3-step registration form
steps = [
    CaptchaStep(
        step_name="email_verification",
        method="userrecaptcha",
        sitekey="RECAPTCHA_SITEKEY_STEP1",
        pageurl="https://example.com/register/step1",
    ),
    CaptchaStep(
        step_name="phone_verification",
        method="userrecaptcha",
        sitekey="RECAPTCHA_SITEKEY_STEP2",
        pageurl="https://example.com/register/step2",
    ),
    CaptchaStep(
        step_name="payment_confirmation",
        method="turnstile",
        sitekey="TURNSTILE_SITEKEY_STEP3",
        pageurl="https://example.com/register/step3",
    ),
]

results = solve_chain(steps)
for step_name, result in results.items():
    print(f"{step_name}: solved in {result['solve_time']}s")

JavaScript: Sequential Chain with Session Persistence

const API_KEY = "YOUR_API_KEY";
const SUBMIT_URL = "https://ocr.captchaai.com/in.php";
const RESULT_URL = "https://ocr.captchaai.com/res.php";

async function solveCaptcha(step, cookies = "") {
  const params = new URLSearchParams({
    key: API_KEY,
    method: step.method,
    json: "1",
  });

  if (step.method === "userrecaptcha") {
    params.set("googlekey", step.sitekey);
    params.set("pageurl", step.pageurl);
  } else if (step.method === "turnstile") {
    params.set("sitekey", step.sitekey);
    params.set("pageurl", step.pageurl);
  }

  if (cookies) params.set("cookies", cookies);

  const submit = await (await fetch(SUBMIT_URL, { method: "POST", body: params })).json();
  if (submit.status !== 1) throw new Error(`[${step.name}] Submit: ${submit.request}`);

  const taskId = submit.request;
  for (let i = 0; i < 60; i++) {
    await new Promise((r) => setTimeout(r, 5000));
    const url = `${RESULT_URL}?key=${API_KEY}&action=get&id=${taskId}&json=1`;
    const poll = await (await fetch(url)).json();
    if (poll.request === "CAPCHA_NOT_READY") continue;
    if (poll.status === 1) return poll.request;
    throw new Error(`[${step.name}] Solve: ${poll.request}`);
  }
  throw new Error(`[${step.name}] Timeout`);
}

async function solveChain(steps) {
  const results = {};
  let sessionCookies = "";

  for (let i = 0; i < steps.length; i++) {
    const step = steps[i];
    console.log(`Step ${i + 1}/${steps.length}: ${step.name}`);

    const start = Date.now();
    const token = await solveCaptcha(step, sessionCookies);
    const elapsed = ((Date.now() - start) / 1000).toFixed(1);
    console.log(`  Solved in ${elapsed}s`);

    results[step.name] = { token, solveTime: elapsed };

    // Submit form with token (pseudo-code — adapt to your site)
    // const response = await submitForm(step.pageurl, token, sessionCookies);
    // sessionCookies = extractCookies(response);

    // Pause between steps
    if (i < steps.length - 1) {
      await new Promise((r) => setTimeout(r, 2000));
    }
  }

  return results;
}

// Usage
const steps = [
  { name: "login", method: "userrecaptcha", sitekey: "SITEKEY_1", pageurl: "https://example.com/login" },
  { name: "verify", method: "userrecaptcha", sitekey: "SITEKEY_2", pageurl: "https://example.com/verify" },
  { name: "checkout", method: "turnstile", sitekey: "SITEKEY_3", pageurl: "https://example.com/checkout" },
];

solveChain(steps).then((results) => {
  console.log("Chain complete:", Object.keys(results));
});

Token Timing Across Steps

CAPTCHA tokens expire — typically 120 seconds for reCAPTCHA, 300 seconds for Turnstile. In a chain, don't pre-solve all steps at once:

Approach Risk Recommendation
Pre-solve all steps simultaneously Early tokens expire before use Don't do this
Solve step N only after step N-1 succeeds Slower but reliable Recommended for 2–3 step chains
Pre-solve next step during current form fill Token may expire if form takes long Only if form fill is fast (<60s)

Troubleshooting

Issue Cause Fix
Step 2 CAPTCHA gives different sitekey than expected Page changed based on step 1 response Re-extract sitekey from the live page at each step
Token rejected at step 2 Session cookies not carried forward Use a persistent session (requests.Session / cookie jar)
Chain fails at conditional step CAPTCHA only appears on certain paths Add detection: check if CAPTCHA element exists before solving
All tokens expire by final step Chain takes too long Solve each step's CAPTCHA only when you're ready to submit that step
Different CAPTCHA type than expected Site A/B tests CAPTCHA providers Detect CAPTCHA type dynamically from page source

FAQ

Can I parallelize CAPTCHA solving across chain steps?

Only if the steps are independent (no session dependency). Most chains require sequential processing because step 2's URL or parameters depend on step 1's submission response.

What if a step fails midway through the chain?

Save progress at each step. On retry, start from the failed step rather than the beginning. If previous steps created server-side state (like partially registered accounts), you may need to start a fresh session.

How do I detect which CAPTCHA type each step uses?

Parse the page HTML at each step. Look for data-sitekey attributes on div.g-recaptcha (reCAPTCHA), div.cf-turnstile (Turnstile), or div.h-captcha (hCaptcha) elements.

Next Steps

Handle multi-step CAPTCHA chains confidently — get your CaptchaAI API key and implement sequential solving.

Related guides:

Discussions (0)

No comments yet.

Related Posts

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
DevOps & Scaling CaptchaAI Monitoring with Datadog: Metrics and Alerts
Monitor Captcha AI performance with Datadog — custom metrics, dashboards, anomaly detection alerts, and solve rate tracking for CAPTCHA solving pipelines.

Monitor Captcha AI performance with Datadog — custom metrics, dashboards, anomaly detection alerts, and solve...

Automation Python All CAPTCHA Types
Feb 19, 2026
Tutorials Pytest Fixtures for CaptchaAI API Testing
Build reusable pytest fixtures to test CAPTCHA-solving workflows with Captcha AI.

Build reusable pytest fixtures to test CAPTCHA-solving workflows with Captcha AI. Covers mocking, live integra...

Automation Python reCAPTCHA v2
Apr 08, 2026
Tutorials GeeTest Token Injection in Browser Automation Frameworks
how to inject Gee Test v 3 solution tokens into Playwright, Puppeteer, and Selenium — including the three-value response, callback triggering, and form submissi...

Learn how to inject Gee Test v 3 solution tokens into Playwright, Puppeteer, and Selenium — including the thre...

Automation Python Testing
Jan 18, 2026