MTCaptcha in C#: Solve It in Playwright With MtCaptchaAsync

mtcaptcha in c# - MTCaptcha in C#: Solve It in Playwright With MtCaptchaAsync

To solve MTCaptcha in C# with a real browser, open the page in Playwright for .NET, read the sitekey from the page’s mtcaptchaConfig object, and pass it to MtCaptchaAsync from the CapSkip NuGet package. The token that comes back goes into the hidden mtcaptcha-verifiedtoken field, and a click posts the form. The call goes to the CapSkip MTCaptcha solver on your own Windows PC. CapSkip reads the distorted text itself, with no fee per token.

What you need

  • CapSkip 4.3.0 or newer on a Windows PC, since that release is where MTCaptcha arrived. Get it running first with the setup guide.
  • The .NET 8 SDK or later, plus two NuGet packages: Microsoft.Playwright and CapSkip 1.7.0 or later, which introduced MtCaptchaAsync. Only SDK 10.0.100 is installed here, so I built for net10.0 and net8.0 with it, using CapSkip 1.7.0 and Playwright 1.64.1. A machine with only the 8 SDK is untested.
  • Windows PowerShell 5.1 or newer and a page you may automate with an MTCaptcha widget.
  • An address for CapSkip. Local mode answers on 127.0.0.1 only. In Server mode the API is also reachable on your network or public IP, from other machines. Which you get depends on the connection settings.

Three things stand behind the results. The real CapSkip app on this PC got three tasks: two for the public values of the 2Captcha demo page and one for that sitekey on another domain. Its Release build folder reads 4.3.0, but I could not confirm the answering instance was that build. Chromium loaded the demo page read-only, and no token went to any site. A mock of mine plays in.php, res.php and a login site, with form rules of my own. No real site was tested.

Step 1: set up the project and fetch the browser

The NuGet package holds no browser. The build writes playwright.ps1 into the output folder, so build once, then run the script. For installing browsers, the Playwright docs write the command with pwsh, which is PowerShell 7. My PC has only Windows PowerShell 5.1, and the script ran there under an execution policy bypass.

dotnet new console -o mtcaptcha-demo
cd mtcaptcha-demo
dotnet add package CapSkip
dotnet add package Microsoft.Playwright
dotnet build
powershell -ExecutionPolicy Bypass -Command "& (Get-ChildItem bin\Debug\net*\playwright.ps1 | Select-Object -First 1).FullName install chromium"

The install took 33.5 seconds and fetched Chrome for Testing 156.0.8078.4 (197.5 MiB) and a headless shell (118.1 MiB). Without a browser for your Playwright version, launching fails with an unhandled PlaywrightException, Executable doesn’t exist.

Delete everything in Program.cs, including the template’s Console.WriteLine line. Then paste the Step 2, Step 3 and Step 4 blocks in that order, and leave out the Proxy snippet. Only the first block carries using lines, so the program works once the last block is in.

Step 2: read the page’s config and call MtCaptchaAsync

A page sets its sitekey in a script variable named mtcaptchaConfig, and the same object can carry an action. A classic script variable is a property of window, so Playwright can read it from the loaded page without parsing HTML.

On the 2Captcha demo page, window.mtcaptchaConfig was undefined when GotoAsync returned in 16 of 16 loads (two read-only runs) and appeared 0.3 to 1.8 seconds later, so the code waits for it. My mock page builds it 1.5 seconds after load, and with the wait line deleted the program stopped with a PlaywrightException saying Cannot read properties of undefined. The code reads two keys, sitekey and action, and falls back to an empty action. The demo page object had a sitekey, no action and a renderQueue array the widget adds.

using CapSkip;
using Microsoft.Playwright;
// Implicit usings import System, which has a TimeoutException too (a bare one fails with CS0104).
using SolverTimeout = CapSkip.TimeoutException;

static class Solve
{
    // Local mode. In Server mode, use your server's address instead. If API Key
    // Validation is on in CapSkip, also pass apiKey: "YOUR_KEY" here.
    static readonly CapSkipClient Client = new(host: "127.0.0.1", port: 8080);

    // The page's own script sets window.mtcaptchaConfig, and the widget reads the same object.
    public static async Task<SolveResult> Token(IPage page, CancellationToken ct)
    {
        await page.WaitForFunctionAsync("() => window.mtcaptchaConfig?.sitekey");
        var config = await page.EvaluateAsync<string[]>(
            "() => [window.mtcaptchaConfig.sitekey, window.mtcaptchaConfig.action || '']");
        // The SDK leaves out an empty option, so a page that sets no action sends none.
        var options = new Dictionary<string, object?> { ["action"] = config[1] };
        // page.Url is where the browser is now, after any redirect.
        return await Client.MtCaptchaAsync(config[0], page.Url, options, ct);
    }
}

Use page.Url for the address, since it is where the browser stands after any redirect. The SDK drops an empty option, and the mock saw no action field for a page that sets none. The check reply in the MTCaptcha validate token guide carries the action the captcha started with, so a site can compare it: send the one your page sets. A leading sk= is stripped. The userAgent option sets the User-Agent CapSkip presents to MTCaptcha, and the API docs say it uses a Chrome for Windows one when you send none. The proxy option is in the snippet below.

// Snippet, not part of Program.cs. In Solve.Token, replace the options line with this one.
// CapSkip and Microsoft.Playwright both define a Proxy class, so write CapSkip's out in full.
var options = new Dictionary<string, object?>
{
    ["action"] = config[1],
    ["proxy"] = new CapSkip.Proxy("HTTP", "login:[email protected]:8080"),
};

The result puts the token in both Token and Code. Against the real app it began with v1( and was 394 characters, with UserAgent and RespKey null. Timed from the call to its return, the real app (Release build 4.3.0, running version unconfirmed, Windows, 2 runs) took 3.85 and 3.88 seconds. The SDK polls at 0, 0.25, 0.75, 1.75 and 3.75 seconds, then doubles the gap. So the token arrived on the fifth poll (inferred from the times, not logged) and the solve finished between about 1.8 and 3.8 seconds.

Before sending anything, the SDK validates what you passed. Nine bad calls (a blank, unprefixed, spaced or 65 character sitekey, a relative, ftp or missing page address, an unsupported option and a proxytype of GOPHER) were refused with a ValidationException and sent nothing to the mock. The real app refused the same kinds of input in my raw requests with ERROR_BAD_PARAMETERS, ERROR_PAGEURL and ERROR_PROXY_FORMAT.

MTCaptcha uses defaultTimeout, 120 seconds, because no browser runs for the solve. The 300 second recaptchaTimeout does not apply: set to 3 against a mock with no token ready, it did nothing, and my 8 second budget ended the wait. With defaultTimeout at 5, the CapSkip TimeoutException arrived about 8 seconds after the call (7.86 on net10.0, 7.88 and 8.42 in two net8.0 runs), because the SDK sleeps to the next poll and throws once that poll falls due after the deadline.

All SDK exceptions extend CapSkipError. ApiException carries the whole reply as its message, for example {"status":0,"request":"ERROR_RECAPTCHA_INVALID_DOMAIN"}, which the real app returned after 0.33 seconds for the demo sitekey on example.com. NetworkException means the request itself failed: nothing answered at that host and port, the reply was not HTTP 200, or the call was cancelled. Polling retries it, so with the mock killed mid-poll the call ended in the TimeoutException, not a NetworkException. Playwright adds three traps. Implicit usings import System, which has a TimeoutException too, so a bare one next to using CapSkip fails with CS0104, and the first block aliases the SDK class as SolverTimeout. Playwright reports its own timeouts as System.TimeoutException, caught under its full name in Step 4. Both libraries also define a Proxy class, hence CapSkip.Proxy in the snippet.

No Playwright .NET method takes a CancellationToken, and each waits 30 seconds by default, so the token covers only the CapSkip calls. In the mock, a 2 second budget that fired while in.php hung surfaced as a NetworkException wrapping a TaskCanceledException, and one that fired while polling as a plain TaskCanceledException, both after about 2 seconds.

Step 3: fill the hidden field and submit

The token field is hidden, and FillAsync waits for a visible one: on my mock page it waited the full 30 seconds and threw System.TimeoutException. So the block sets the value inside the page with EvaluateAsync, and RunAndWaitForResponseAsync returns the form post’s status.

static class Submit
{
    // Returns the status of the form post and the text the page shows afterwards.
    public static async Task<(int Status, string Text)> Run(IPage page, string token)
    {
        await page.FillAsync("input[name=user]", "alice");  // your form's own fields go here
        await page.FillAsync("input[name=password]", "YOUR_PASSWORD");
        // The token field is hidden and FillAsync waits for a visible one, so set it in the page.
        await page.EvaluateAsync(
            "t => { document.querySelector('input[name=\"mtcaptcha-verifiedtoken\"]').value = t; }", token);
        var response = await page.RunAndWaitForResponseAsync(
            () => page.ClickAsync("button[type=submit]"), r => r.Request.Method == "POST");
        return (response.Status, await page.InnerTextAsync("#result"));
    }
}

What does the widget do about a field you set yourself? On the 2Captcha demo page, Chromium 156.0.8078.4 found one hidden input named mtcaptcha-verifiedtoken in a form, empty until a visitor solves the challenge. I set it to a placeholder and waited 8 seconds. The value stayed, and the widget sent no request to MTCaptcha. Its getVerifiedToken method still returned an empty string, so the widget does not read the field back. I did not click Check or put a real token on that page, so what its server does with such a value is untested. MTCaptcha documents a verified-callback that runs when the widget verifies a visitor, and the demo page registers none, so a page whose button waits for it is untested.

Step 4: run MTCaptcha in C# end to end

Main comes last. Change PageUrl (as pasted it requests example.com, which has no widget), then start the program with dotnet run. Each attempt gets its own browser context, so the site sees a new session. A form answer below 400 ends the run, a refused form or ERROR_CAPTCHA_UNSOLVABLE costs a new attempt, and any other CapSkip error ends it.

static class Program
{
    const string PageUrl = "https://example.com/login";  // the page that shows the MTCaptcha widget

    static async Task<int> Main()
    {
        // One budget for the CapSkip calls. Playwright calls keep their own 30 second default.
        using var budget = new CancellationTokenSource(TimeSpan.FromMinutes(3));
        using var playwright = await Playwright.CreateAsync();
        await using var browser = await playwright.Chromium.LaunchAsync(new() { Headless = true });
        try
        {
            for (var attempt = 1; attempt <= 3; attempt++)
            {
                // A new context per attempt gives the site a fresh session and a fresh form.
                await using var context = await browser.NewContextAsync();
                var page = await context.NewPageAsync();
                await page.GotoAsync(PageUrl);

                SolveResult solved;
                try { solved = await Solve.Token(page, budget.Token); }
                catch (ApiException ex) when (ex.Message.Contains("ERROR_CAPTCHA_UNSOLVABLE"))
                {
                    Console.WriteLine($"attempt {attempt}: CapSkip could not pass the challenge");
                    continue;
                }

                var (status, text) = await Submit.Run(page, solved.Token!);
                Console.WriteLine($"attempt {attempt}: {status} {text}");
                if (status < 400) return 0;
            }
            Console.WriteLine("no accepted form after 3 attempts");
        }
        // A cancelled submit surfaces as a NetworkException and a cancelled poll as a
        // TaskCanceledException, so test the budget itself.
        catch (Exception) when (budget.IsCancellationRequested) { Console.WriteLine("the 3 minute budget ran out"); }
        catch (ValidationException ex) { Console.WriteLine($"CapSkip refused the arguments: {ex.Message}"); }
        catch (ApiException ex) { Console.WriteLine($"CapSkip answered {ex.Message}"); }
        catch (SolverTimeout ex) { Console.WriteLine($"no token in time: {ex.Message}"); }
        catch (CapSkipError ex) { Console.WriteLine($"{ex.GetType().Name}: {ex.Message}"); }
        // Playwright reports its own timeouts as System.TimeoutException.
        catch (System.TimeoutException ex) { Console.WriteLine($"the page was too slow: {ex.Message.Split('\n')[0]}"); }
        catch (PlaywrightException ex) { Console.WriteLine($"the browser failed: {ex.Message.Split('\n')[0]}"); }
        return 1;
    }
}

These rows are mock results, which say nothing about a real site, and were identical on net10.0 and net8.0.

Mock settingWhat the program did
Defaults, page sets the action login200 Signed in, with the action in in.php. A page with no action sent none
First form post answered 403 by the siteSecond attempt in a new context with a new task, then 200
Token expired when the form arrivesThree 403 lines, exit code 1
ERROR_RECAPTCHA_INVALID_SITEKEY, or ERROR_RECAPTCHA_INVALID_DOMAINThe reply, exit code 1, one task, no retry

Common errors

What you seeCauseFix
ValidationExceptionThe SDK refused the call locally: a bad sitekey, a page address that is not an absolute http or https URL, or an option the MTCaptcha API lacksFix the argument. Retrying cannot help
ERROR_RECAPTCHA_INVALID_SITEKEY or ERROR_RECAPTCHA_INVALID_DOMAINMTCaptcha does not know the sitekey (mock only), or it is not allowed on that page’s domain (real app, example.com)Re-read the sitekey and page address from the page. Do not retry
ERROR_CAPTCHA_UNSOLVABLECapSkip did not pass the challenge (API docs; I could not provoke it against the real app)Main submits a new task
CapSkip TimeoutExceptionNo token within defaultTimeout. It is raised when the first poll after the deadline is due, so a 5 second deadline ends at about 8 secondsRaise defaultTimeout
The form refuses a tokenThe validate token guide lists token-expired (commonly 120 seconds), token-duplicate-cal and privatekey-mismatch-token (another sitekey)Request the token just before the post, use it once, and keep the page’s sitekey and action

Server mode: CapSkip on a different PC

In Server mode CapSkip listens on your network address or a public IP, so this program can run on another PC while the solver stays on a Windows machine you control. Swap the server’s address in for the host in the CapSkipClient line, and nothing else moves.

Starting Server mode opens the CapSkip port to every address. Add a Windows Firewall block rule for the addresses you do not expect, and turn on API Key Validation with an apiKey in the CapSkipClient line.

FAQ

Where is the sitekey if the page has no mtcaptchaConfig?

In the address of the widget iframe, from service.mtcaptcha.com. On the demo page it carried a sitekey parameter with the config value.

Do I need Playwright to solve MTCaptcha in C#?

No. CapSkip runs no browser for the solve, and Playwright is here because the example page builds its config in script. A plain form post carries the same mtcaptcha-verifiedtoken field, and the hCaptcha in C# post shows that route with HttpClient.

Why would a site refuse the token I got?

The three refusals in the validate token guide are a token that was already checked, one that expired (commonly after 120 seconds) and one that came from another sitekey. A site should also compare the action. I had no real site, so I cannot rank these reasons.

MTCaptcha in C# comes down to reading mtcaptchaConfig, one MtCaptchaAsync call and a hidden field filled just before the click. CapSkip is a flat-license captcha solver on your own PC, so a refused form costs only another attempt. For other CAPTCHA types in .NET, see the C# CAPTCHA solver page. To watch a widget get passed, open the MTCaptcha demo, and for the raw request format read the API docs.