Cloudflare Challenge

CapMonster Cloud can return the solution result as either a token or a cf_clearance cookie. Before getting started, review both options and choose the one that best fits your use case.
Request parameters
IMPORTANT: some parameter values are dynamic — they change with each render of the page using Cloudflare Challenge.
Extract them immediately before creating the task to avoid errors during solving.
See examples of automatic parameter extraction in the section How to find all required parameters for task creation.
Option 1. Challenge (token)
-
CapMonster Cloud uses built-in proxies by default — their cost is already included in the service. You only need to specify your own proxies in cases where the website does not accept the token or access to the built-in services is restricted.
-
If you are using a proxy with IP authorization, make sure to whitelist the address 65.21.190.34.
-
After solving, you will receive a token to confirm captcha completion.
- RecaptchaV2EnterpriseTaskProxyless (without proxy)
type<string>requiredTurnstileTask
websiteURL<string>requiredThe URL of the page where the captcha is solved
websiteKey<string>requiredTurnstile site key (see section How to find all required parameters for task creation)
cloudflareTaskType<string>requiredtoken
pageAction<string>requiredThe action field found in the callback function. If using cloudflareTaskType, action is usually “managed” or “non-interactive”.
userAgent<string>requiredBrowser User-Agent.
Pass only a valid UA from Windows OS. Currently it is: userAgentPlaceholder
data<string>requiredThe value of the data field, taken from cData.
pageData<string>requiredThe value of pageData, taken from chlPageData.
apiJsUrl<string>optionalString containing the captcha script URL.
proxyType<string>optionalhttp - standard http/https proxy;
https - try this if "http" doesn't work (needed for some custom proxies);
socks4 - socks4 proxy;
socks5 - socks5 proxy.
proxyAddress<string>optionalIP address of the proxy (IPv4/IPv6). Not allowed:
- using transparent proxies (those exposing the client IP);
- using local machine proxies.
proxyPort<integer>optionalProxy port.
proxyLogin<string>optionalProxy login.
proxyPassword<string>optionalProxy password.
These parameters are in the object passed to window.turnstile.render(el, paramsObj) when creating the captcha. You can retrieve them, for example, by executing JavaScript before loading other scripts:
(function () {
const obj = {
render: function () {
const { action, cData, chlPageData } = arguments[1];
const params = [
["action", action],
["data", cData],
["pageData", chlPageData],
];
console.table(params)
}
};
Object.defineProperty(window, "turnstile", {
get: () => {
return obj;
},
});
})();
When window.turnstile.render(el, paramsObj) is called, the captcha loads on the page, and upon successful solving, the callback function passes the solution information.
window.turnstile.render(el, paramsObj):
el: DOM element to insert the captcha.paramsObj: Object containing captcha information and solving instructions. Usually includes sitekey, action, cData, chlPageData, callback.callback: Function called after captcha is successfully solved.
Option 2. Challenge (cookie)
-
Use your own proxies for this task.
-
After solving, you will receive special cookies to add to your browser.
- RecaptchaV2EnterpriseTaskProxyless (without proxy)
type<string>requiredTurnstileTask
websiteURL<string>requiredThe URL of the page where the captcha is solved
websiteKey<string>requiredTurnstile site key (any string is acceptable)
cloudflareTaskType<string>requiredcf_clearance
htmlPageBase64<string>requiredBase64-encoded HTML page of "Just a moment" shown with 403 response.
Example to get htmlPageBase64:
var serializer = new XMLSerializer();
var fullHtml = serializer.serializeToString(document);
var htmlBase64 = btoa(unescape(encodeURIComponent(fullHtml)));
console.log(htmlBase64);
userAgent<string>requiredBrowser User-Agent.
Provide only the current Windows UA: userAgentPlaceholder
proxyType<string>requiredhttp - regular HTTP/HTTPS proxy;
https - use if http doesn’t work (required for some custom proxies);
socks4 - SOCKS4 proxy;
socks5 - SOCKS5 proxy.
proxyAddress<string>requiredProxy IP address (IPv4/IPv6). Not allowed:
- Transparent proxies
- Local machine proxies
proxyPort<integer>requiredProxy port.
proxyLogin<string>requiredProxy login.
proxyPassword<string>requiredProxy password.
Create task method
Option 1. Challenge (token)
- TurnstileTask (without proxy)
- TurnstileTask (with proxy)
https://api.capmonster.cloud/createTask
Request
{
"clientKey": "API_KEY",
"task": {
"type": "TurnstileTask",
"websiteURL": "https://example.com",
"websiteKey": "YOUR_WEBSITE_KEY_HERE",
"cloudflareTaskType": "token",
"userAgent": "userAgentPlaceholder",
"pageAction": "managed",
"pageData": "HUHDWUHuhuwfiweh32..uh2uhuhyugYUG=",
"data": "874291f4retD1366"
}
}
Response
{
"errorId": 0,
"taskId": 407533072
}
https://api.capmonster.cloud/createTask
Request
{
"clientKey": "API_KEY",
"task": {
"type": "TurnstileTask",
"websiteURL": "https://example.com",
"websiteKey": "YOUR_WEBSITE_KEY_HERE",
"cloudflareTaskType": "token",
"userAgent": "userAgentPlaceholder",
"pageAction": "managed",
"pageData": "HUHDWUHuhuwfiweh32..uh2uhuhyugYUG=",
"data": "874291f4retD1366",
"proxyType": "http",
"proxyAddress": "8.8.8.8",
"proxyPort": 8080,
"proxyLogin": "proxyLoginHere",
"proxyPassword": "proxyPasswordHere"
}
}
Response
{
"errorId": 0,
"taskId": 407533072
}
Option 2. Challenge (cookie)
- TurnstileTask (without proxy)
https://api.capmonster.cloud/createTask
Request
{
"clientKey": "API_KEY",
"task": {
"type": "TurnstileTask",
"websiteURL": "https://example.com",
"websiteKey": "xxxxxxxxxx",
"cloudflareTaskType": "cf_clearance",
"htmlPageBase64": "PCFET0NUWVBFIGh0...vYm9keT48L2h0bWw+",
"userAgent": "userAgentPlaceholder",
"proxyType": "http",
"proxyAddress": "8.8.8.8",
"proxyPort": 8080,
"proxyLogin": "proxyLoginHere",
"proxyPassword": "proxyPasswordHere"
}
}
Response
{
"errorId":0,
"taskId":407533072
}
Get task result method
Option 1. Challenge (token)
- TurnstileTask (proxyless)
https://api.capmonster.cloud/getTaskResult
Request
{
"clientKey": "API_KEY",
"taskId": 407533072
}
Response
{
"errorId": 0,
"status": "ready",
"solution": {
"userAgent": "userAgentPlaceholder",
"token": "0.iGX3xsyFCkbGePM3jP4P4khLo6TrLukt8ZzBvwuQOvbC...f61f3082"
}
}
Use the getTaskResult method to retrieve the Challenge solution. Depending on system load, the response can take between 5 and 20 seconds.
| Property | Type | Description |
|---|---|---|
| token | String | Use this token when calling the callback function |
Option 2. Challenge (cookie)
- TurnstileTask (без прокси)
https://api.capmonster.cloud/getTaskResult
Request
{
"clientKey": "API_KEY",
"taskId": 407533072
}
Response
{
"errorId": 0,
"status": "ready",
"solution": {
"cf_clearance": "1tarGvbY2_ZhQdYxpSBloao.FoOn9VtcJtmb_IQ_hCE-1761217338-1.2.1.1-vyVPoLYIGX0VCJomVuLjF7n0kdM0PXaPjpDsRcohxGr7hb2CE7WfcHpmQZ70goqEjdWxPsDhSVaKNTz9opxWguiNdWEEq_.SceWXIqfP7tnEb69f3bP0mixNqcWy_5P_9INpoAEqr1k7aYU0r45PT4gPr5pwHxedVySyLRdoBXIJasdTE52YOQ3NPdGWTwQ_3h2n_wYqqIvf0kCSAvimRrmsgZxomlyejwqPI6ZHi.w"
}
}
| Property | Type | Description |
|---|---|---|
| cf_clearance | String | Special Cloudflare cookies that you can set in your browser |
How to differentiate Challenge from Turnstile
Differences between Challenge and Turnstile
Cloudflare verification types can appear in different ways.
Standard Turnstile:

Stylized variants:
To confirm Challenge presence, open developer tools, inspect network traffic, and check the page source for typical signs:
- The first request to the site returns a 403 status code:

- The form with id challenge-form has an action attribute (not to be confused with Turnstile captcha action) containing the parameter
__cf_chl_f_tk=:

- The page contains two similar
<script>tags that create new values in thewindowobject:

How to find all required parameters for task creation
Automatically
To automate parameter extraction, you can retrieve them via a browser (regular or headless, e.g., using Playwright) or directly from HTTP requests. Since dynamic parameter values are short-lived, it is recommended to use them immediately after retrieval.
The provided code snippets are basic examples for learning how to extract the required parameters. The exact implementation will depend on your captcha page, its structure, and the HTML elements and selectors used.
- JavaScript
- Python
- C#
For Option 1: Challenge (token) – Node.js
import { chromium } from "playwright";
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
let params = null;
try {
while (!params) {
await page.goto("https://example.com");
await page.evaluate(() => {
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === "render") {
return function (a, b) {
const p = {
websiteKey: b.sitekey,
websiteURL: window.location.href,
data: b.cData,
pagedata: b.chlPageData,
action: b.action,
userAgent: navigator.userAgent,
};
window.params = p;
return target.render.apply(this, arguments);
};
}
return target[prop];
},
});
});
params = await page.evaluate(() => {
return new Promise((resolve) => {
setTimeout(() => resolve(window.params || null), 5000);
});
});
if (!params) {
await page.waitForTimeout(3000);
}
}
console.log("Turnstile Params:", params);
} finally {
await browser.close();
}
})();
For Option 2: Challenge (cookie cf_clearance) – Node.js
import { chromium } from "playwright";
import { Buffer } from "buffer";
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
let websiteKey = null;
while (!websiteKey) {
await page.goto("https://example.com");
await page.evaluate(() => {
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === "render") {
return function (a, b) {
window.websiteKey = b.sitekey;
return target.render.apply(this, arguments);
};
}
return target[prop];
},
});
});
websiteKey = await page.evaluate(() => {
return new Promise((resolve) => {
setTimeout(() => resolve(window.websiteKey || null), 5000);
});
});
if (!websiteKey) {
await page.waitForTimeout(3000);
}
}
const html = await page.content();
const htmlPageBase64 = Buffer.from(html).toString("base64");
const result = {
websiteKey,
htmlPageBase64,
};
console.log(result);
await browser.close();
})();
For Option 1: Challenge (token)
import asyncio
from playwright.async_api import async_playwright
async def extract_turnstile_params():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
page = await browser.new_page()
params = None
while not params:
await page.goto("https://example.com")
await page.evaluate("""
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === "render") {
return function(a, b) {
const p = {
websiteKey: b.sitekey,
websiteURL: window.location.href,
data: b.cData,
pagedata: b.chlPageData,
action: b.action,
userAgent: navigator.userAgent
};
window.params = p;
return target.render.apply(this, arguments);
};
}
return target[prop];
}
});
""")
await page.wait_for_timeout(5000)
params = await page.evaluate("window.params || null")
if not params:
await page.wait_for_timeout(3000)
print("Turnstile Params:", params)
await browser.close()
asyncio.run(extract_turnstile_params())
For Option 2: Challenge (cookie cf_clearance)
import asyncio
import base64
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
page = await browser.new_page()
website_key = None
while not website_key:
await page.goto("https://example.com")
await page.evaluate("""
() => {
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === 'render') {
return function(a, b) {
window.websiteKey = b.sitekey;
return target.render.apply(this, arguments);
};
}
return target[prop];
}
});
}
""")
website_key = await page.evaluate("""
() => new Promise(resolve => {
setTimeout(() => resolve(window.websiteKey || null), 5000);
})
""")
if not website_key:
await page.wait_for_timeout(3000)
html = await page.content()
html_base64 = base64.b64encode(html.encode("utf-8")).decode("utf-8")
result = {
"websiteKey": website_key,
"htmlPageBase64": html_base64
}
print(result)
await browser.close()
asyncio.run(main())
For Option 1: Challenge (token)
using Microsoft.Playwright;
using System.Text.Json;
class Program
{
public static async Task Main()
{
using var playwright = await Playwright.CreateAsync();
var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
Headless = false
});
var page = await browser.NewPageAsync();
object? parameters = null;
while (parameters == null)
{
await page.GotoAsync("https://example.com");
await page.EvaluateAsync(@"() => {
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === 'render') {
return function(a, b) {
const p = {
websiteKey: b.sitekey,
websiteURL: window.location.href,
data: b.cData,
pagedata: b.chlPageData,
action: b.action,
userAgent: navigator.userAgent
};
window.params = p;
return target.render.apply(this, arguments);
};
}
return target[prop];
}
});
}");
parameters = await page.EvaluateAsync(@"() => new Promise(resolve => {
setTimeout(() => resolve(window.params || null), 5000);
})");
if (parameters == null)
{
await page.WaitForTimeoutAsync(3000);
}
}
Console.WriteLine("Turnstile Params:");
Console.WriteLine(JsonSerializer.Serialize(parameters, new JsonSerializerOptions { WriteIndented = true }));
await browser.CloseAsync();
}
}
For Option 2: Challenge (cookie cf_clearance)
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Playwright;
class Program
{
public static async Task Main()
{
using var playwright = await Playwright.CreateAsync();
var browser = await playwright.Chromium.LaunchAsync(
new BrowserTypeLaunchOptions { Headless = false });
var page = await browser.NewPageAsync();
string websiteKey = null;
while (websiteKey == null)
{
await page.GotoAsync("https://example.com");
await page.EvaluateAsync(@"() => {
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === 'render') {
return function(a, b) {
window.websiteKey = b.sitekey;
return target.render.apply(this, arguments);
};
}
return target[prop];
}
});
}");
websiteKey = await page.EvaluateAsync<string>(@"() =>
new Promise(resolve => {
setTimeout(() => resolve(window.websiteKey || null), 5000);
})");
if (websiteKey == null)
{
await page.WaitForTimeoutAsync(3000);
}
}
var html = await page.ContentAsync();
var htmlBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(html));
Console.WriteLine($"websiteKey: {websiteKey}");
Console.WriteLine($"htmlPageBase64: {htmlBase64}");
await browser.CloseAsync();
}
}
Use the SDK Library
- JavaScript
- Node.js
- Python
- C#
Option 1. Challenge (token)
// https://github.com/ZennoLab/capmonstercloud-client-js
import {
CapMonsterCloudClientFactory,
ClientOptions,
TurnstileRequest
} from '@zennolab_com/capmonstercloud-client';
const API_KEY = "YOUR_API_KEY"; // Specify your CapMonster Cloud API key
document.addEventListener("DOMContentLoaded", async () => {
const client = CapMonsterCloudClientFactory.Create(
new ClientOptions({ clientKey: API_KEY })
);
// Basic example without proxy
// CapMonster Cloud automatically uses its own proxies
let turnstileRequest = new TurnstileRequest({
websiteURL: "https://example.com", // URL of the captcha page
websiteKey: "YOUR_WEBSITE_KEY_HERE", // Replace with the correct value
data: "YOUR_DATA_HERE",
pageAction: "managed",
cloudflareTaskType: "token",
pageData: "YOUR_PAGE_DATA_HERE",
userAgent: "userAgentPlaceholder"
});
// Example of using your own proxy
// Uncomment this block if you want to use your own proxy
/*
const proxy = {
proxyType: "http",
proxyAddress: "123.45.67.89",
proxyPort: 8080,
proxyLogin: "username",
proxyPassword: "password"
};
turnstileRequest = new TurnstileRequest({
websiteURL: "https://example.com",
websiteKey: "YOUR_WEBSITE_KEY_HERE",
proxy,
data: "YOUR_DATA_HERE",
pageAction: "managed",
cloudflareTaskType: "token",
pageData: "YOUR_PAGE_DATA_HERE",
userAgent: "userAgentPlaceholder"
});
*/
// Optionally, you can check the balance
const balance = await client.getBalance();
console.log("Balance:", balance);
const result = await client.Solve(turnstileRequest);
console.log("Solution:", result);
});
Option 2. Challenge (cookie cf_clearance)
// https://github.com/ZennoLab/capmonstercloud-client-js
import {
CapMonsterCloudClientFactory,
ClientOptions,
TurnstileRequest
} from '@zennolab_com/capmonstercloud-client';
document.addEventListener("DOMContentLoaded", async () => {
const cmcClient = CapMonsterCloudClientFactory.Create(
new ClientOptions({ clientKey: 'YOUR_API_KEY' }) // Specify your CapMonster Cloud API key
);
// Optionally, you can check the balance
const balance = await cmcClient.getBalance();
console.log('Balance:', balance);
const proxy = {
proxyType: "http",
proxyAddress: '123.45.67.89',
proxyPort: 8080,
proxyLogin: 'username',
proxyPassword: 'password'
};
// Cloudflare cf_clearance can only be solved with your own proxy
const turnstileRequest = new TurnstileRequest({
websiteURL: 'https://example.com/',
websiteKey: 'xxxxx',
cloudflareTaskType: 'cf_clearance',
proxy,
htmlPageBase64: 'PGh0bW...h0bWw+',
userAgent: 'userAgentPlaceholder'
});
const result = await cmcClient.Solve(turnstileRequest);
console.log('Solution:', result.solution);
});
Option 1. Challenge (token)
// https://github.com/ZennoLab/capmonstercloud-client-js
import {
CapMonsterCloudClientFactory,
ClientOptions,
TurnstileRequest
} from '@zennolab_com/capmonstercloud-client';
const API_KEY = "YOUR_API_KEY"; // Specify your CapMonster Cloud API key
(async () => {
const client = CapMonsterCloudClientFactory.Create(
new ClientOptions({ clientKey: API_KEY })
);
// Basic example without proxy
// CapMonster Cloud automatically uses its own proxies
let turnstileRequest = new TurnstileRequest({
websiteURL: "https://example.com", // URL of the captcha page
websiteKey: "YOUR_WEBSITE_KEY_HERE", // Replace with the correct value
data: "YOUR_DATA_HERE",
pageAction: "managed",
cloudflareTaskType: "token",
pageData: "YOUR_PAGE_DATA_HERE",
userAgent: "userAgentPlaceholder"
});
// Example of using your own proxy
// Uncomment this block if you want to use your own proxy
/*
const proxy = {
proxyType: "http",
proxyAddress: "123.45.67.89",
proxyPort: 8080,
proxyLogin: "username",
proxyPassword: "password"
};
turnstileRequest = new TurnstileRequest({
websiteURL: "https://example.com",
websiteKey: "YOUR_WEBSITE_KEY_HERE",
proxy,
data: "YOUR_DATA_HERE",
pageAction: "managed",
cloudflareTaskType: "token",
pageData: "YOUR_PAGE_DATA_HERE",
userAgent: "userAgentPlaceholder"
});
*/
// Optionally, you can check the balance
const balance = await client.getBalance();
console.log("Balance:", balance);
const result = await client.Solve(turnstileRequest);
console.log("Solution:", result);
})();
Option 2. Challenge (cookie cf_clearance)
// https://github.com/ZennoLab/capmonstercloud-client-js
import { CapMonsterCloudClientFactory, ClientOptions, TurnstileRequest } from '@zennolab_com/capmonstercloud-client';
async function main() {
const cmcClient = CapMonsterCloudClientFactory.Create(
new ClientOptions({ clientKey: 'YOUR_API_KEY' }) // Specify your CapMonster Cloud API key
);
// Optionally, you can check the balance
const balance = await cmcClient.getBalance();
console.log('Balance:', balance);
const proxy = {
proxyType: "http",
proxyAddress: '123.45.67.89',
proxyPort: 8080,
proxyLogin: 'username',
proxyPassword: 'password'
};
// Cloudflare cf_clearance can only be solved with your own proxy
const turnstileRequest = new TurnstileRequest({
websiteURL: 'https://example.com/',
websiteKey: 'xxxxx',
cloudflareTaskType: 'cf_clearance',
proxy,
htmlPageBase64: 'PGh0bW...h0bWw+',
userAgent: 'userAgentPlaceholder'
});
// Sending the task for solving
const result = await cmcClient.Solve(turnstileRequest);
console.log('Solution:', result.solution);
}
main().catch(console.error);
Option 1. Challenge (token)
# https://github.com/ZennoLab/capmonstercloud-client-python
import asyncio
from capmonstercloudclient import CapMonsterClient, ClientOptions
from capmonstercloudclient.requests import TurnstileRequest
# from capmonstercloudclient.requests.baseRequestWithProxy import ProxyInfo # Uncomment if you plan to use a proxy
API_KEY = "YOUR_API_KEY" # Specify your CapMonster Cloud API key
async def solve_turnstile_token():
client_options = ClientOptions(api_key=API_KEY)
cap_monster_client = CapMonsterClient(options=client_options)
# Basic example without proxy
# CapMonster Cloud automatically uses its own proxies
turnstile_request = TurnstileRequest(
websiteURL="http://example.com", # URL of the captcha page
websiteKey="YOUR_WEBSITE_KEY_HERE", # Replace with the correct value
data="YOUR_DATA_HERE",
pageAction="managed",
cloudflareTaskType="token",
pageData="YOUR_PAGE_DATA_HERE",
userAgent="userAgentPlaceholder"
)
# Example of using your own proxy
# Uncomment this block if you want to use your own proxy
#
# proxy = ProxyInfo(
# proxyType="http",
# proxyAddress="123.45.67.89",
# proxyPort=8080,
# proxyLogin="username",
# proxyPassword="password"
# )
#
# turnstile_request = TurnstileRequest(
# websiteURL="http://tsmanaged.zlsupport.com",
# websiteKey="YOUR_WEBSITE_KEY_HERE",
# proxy=proxy,
# data="YOUR_DATA_HERE",
# pageAction="managed",
# cloudflareTaskType="token",
# pageData="YOUR_PAGE_DATA_HERE",
# userAgent="userAgentPlaceholder"
# )
# Optionally, you can check the balance
balance = await cap_monster_client.get_balance()
print("Balance:", balance)
result = await cap_monster_client.solve_captcha(turnstile_request)
print("Solution:", result)
asyncio.run(solve_turnstile_token())
Option 2. Challenge (cookie cf_clearance)
# https://github.com/ZennoLab/capmonstercloud-client-python
import asyncio
from capmonstercloudclient import CapMonsterClient, ClientOptions
from capmonstercloudclient.requests import TurnstileRequest
from capmonstercloudclient.requests.baseRequestWithProxy import ProxyInfo # Using ProxyInfo
API_KEY = "YOUR_API_KEY" # Specify your CapMonster Cloud API key
async def solve_cf_clearance():
client_options = ClientOptions(api_key=API_KEY)
cap_monster_client = CapMonsterClient(options=client_options)
# Example of setting up a proxy
proxy = ProxyInfo(
proxyType="http",
proxyAddress="123.45.67.89",
proxyPort=8080,
proxyLogin="username",
proxyPassword="password"
)
# Cloudflare cf_clearance can only be solved with your own proxy
turnstile_request = TurnstileRequest(
websiteURL="https://example.com",
websiteKey="xxxxx",
cloudflareTaskType="cf_clearance",
htmlPageBase64="BASE64_HTML_PAGE_HERE",
userAgent="userAgentPlaceholder",
proxy=proxy
)
# Optionally, you can check the balance
balance = await cap_monster_client.get_balance()
print("Balance:", balance)
result = await cap_monster_client.solve_captcha(turnstile_request)
print("Solution:", result)
asyncio.run(solve_cf_clearance())
Option 1. Challenge (token)
// https://github.com/ZennoLab/capmonstercloud-client-dotnet
using System;
using System.Threading.Tasks;
using Zennolab.CapMonsterCloud;
using Zennolab.CapMonsterCloud.Requests;
class Program
{
static async Task Main(string[] args)
{
// Specify your CapMonster Cloud API key
var clientOptions = new ClientOptions
{
ClientKey = "YOUR_API_KEY"
};
var cmCloudClient = CapMonsterCloudClientFactory.Create(clientOptions);
// Basic example without proxy
// CapMonster Cloud automatically uses its own proxies
var turnstileRequest = new TurnstileRequest
{
WebsiteUrl = "https://example.com", // URL of the captcha page
WebsiteKey = "YOUR_WEBSITE_KEY_HERE", // Replace with the correct value
Data = "data_here",
PageAction = "managed",
CloudflareTaskType = "token",
PageData = "pagedata_here",
UserAgent = "userAgentPlaceholder"
};
// Example of using your own proxy
// Uncomment this block if you want to use your own proxy
/*
var turnstileRequest = new TurnstileRequest
{
WebsiteUrl = "https://example.com",
WebsiteKey = "YOUR_WEBSITE_KEY_HERE",
Data = "data_here",
PageAction = "managed",
CloudflareTaskType = "token",
PageData = "pagedata_here",
UserAgent = "userAgentPlaceholder",
Proxy = new ProxyContainer(
"123.45.67.89",
8080,
ProxyType.Http,
"username",
"password"
)
};
*/
// Optionally, you can check the balance
var balance = await cmCloudClient.GetBalanceAsync();
Console.WriteLine("Balance: " + balance);
var turnstileResult = await cmCloudClient.SolveAsync(turnstileRequest);
Console.WriteLine("Solution: " + turnstileResult.Solution.Value);
}
}
Option 2. Challenge (cookie cf_clearance)
// https://github.com/ZennoLab/capmonstercloud-client-dotnet
using Zennolab.CapMonsterCloud;
using Zennolab.CapMonsterCloud.Requests;
class Program
{
static async Task Main(string[] args)
{
var clientOptions = new ClientOptions
{
ClientKey = "YOUR_API_KEY" // Specify your CapMonster Cloud API key
};
var cmCloudClient = CapMonsterCloudClientFactory.Create(clientOptions);
// Cloudflare cf_clearance can only be solved with your own proxy
var turnstileRequest = new TurnstileRequest
{
WebsiteUrl = "https://example.com", // URL of the captcha page
WebsiteKey = "xxxxx",
CloudflareTaskType = "cf_clearance",
HtmlPageBase64 = "htmlPageBase64Here",
UserAgent = "userAgentPlaceholder",
Proxy = new ProxyContainer(
"123.45.67.89",
8080,
ProxyType.Http,
"username",
"password"
)
};
var turnstileResult = await cmCloudClient.SolveAsync(turnstileRequest);
Console.WriteLine("Solution: " + turnstileResult.Solution.Clearance);
}
}
Examples of solving Cloudflare Challenge (cf_clearance)
The examples below demonstrate the general workflow for solving Cloudflare Challenge: obtaining the required parameters, creating a task in CapMonster Cloud, and using the cf_clearance cookie in subsequent requests. You can use the official SDK or work directly with the API — choose the integration method that best fits your needs.
- Node.js
- Python
- C#
Show code
import { ProxyAgent, setGlobalDispatcher } from "undici";
// ================= CONFIG (OR USE .ENV) =================
const API_KEY = "YOUR_API_KEY"; // Replace with your CapMonster Cloud API key
const URL = "https://www.example.com"; // Replace with the target URL
const SITEKEY = "xxxxxx";
const UA =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36";
// ================= PROXY (REPLACE WITH YOUR PROXY CREDENTIALS) =================
const PROXY_HOST = "PROXY_HOST";
const PROXY_PORT = 1234;
const PROXY_USER = "PROXY_USER";
const PROXY_PASS = "PROXY_PASS";
const proxy = new ProxyAgent(
`http://${PROXY_USER}:${PROXY_PASS}@${PROXY_HOST}:${PROXY_PORT}`,
);
setGlobalDispatcher(proxy);
// ================= SESSION =================
let cookieHeader = "";
const headers = {
"User-Agent": UA,
Accept:
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
Connection: "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
"sec-ch-ua":
'"Chromium";v="149", "Google Chrome";v="149", "Not:A-Brand";v="99"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
};
// ================= FETCH PAGE =================
async function fetchPage(url) {
const response = await fetch(url, {
method: "GET",
headers: {
...headers,
...(cookieHeader && {
Cookie: cookieHeader,
}),
},
});
const buffer = Buffer.from(await response.arrayBuffer());
return {
status: response.status,
body: buffer,
};
}
// ================= SEND JSON POST REQUEST =================
async function postJson(url, data) {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
return await response.json();
}
// ================= SOLVE CHALLENGE =================
async function solveTurnstile(htmlBase64) {
const create = await postJson("https://api.capmonster.cloud/createTask", {
clientKey: API_KEY,
task: {
type: "TurnstileTask",
websiteURL: URL,
websiteKey: SITEKEY,
cloudflareTaskType: "cf_clearance",
htmlPageBase64: htmlBase64,
userAgent: UA,
proxyType: "http",
proxyAddress: PROXY_HOST,
proxyPort: PROXY_PORT,
proxyLogin: PROXY_USER,
proxyPassword: PROXY_PASS,
},
});
if (create.errorId) {
throw new Error(JSON.stringify(create));
}
const taskId = create.taskId;
console.log("Task ID:", taskId);
while (true) {
await new Promise((resolve) => setTimeout(resolve, 5000));
const result = await postJson(
"https://api.capmonster.cloud/getTaskResult",
{
clientKey: API_KEY,
taskId,
},
);
if (result.errorId) {
throw new Error(JSON.stringify(result));
}
if (result.status === "ready") {
return result.solution.cf_clearance;
}
console.log("Waiting...");
}
}
// ================= MAIN FUNCTION =================
async function main() {
// FIRST REQUEST
const first = await fetchPage(URL);
console.log("Initial status:", first.status);
console.log(first.body.toString("utf8").substring(0, 800));
// SOLVE CHALLENGE
const htmlBase64 = first.body.toString("base64");
const cfClearance = await solveTurnstile(htmlBase64);
console.log("cf_clearance:", cfClearance);
cookieHeader = `cf_clearance=${cfClearance}`;
// SECOND REQUEST
const second = await fetchPage(URL);
console.log("Final status:", second.status);
console.log(second.body.toString("utf8").substring(0, 800));
}
main().catch(console.error);
Show code (SDK)
import { ProxyAgent, setGlobalDispatcher } from "undici";
import {
CapMonsterCloudClientFactory,
ClientOptions,
TurnstileRequest,
} from "@zennolab_com/capmonstercloud-client";
// ================= CONFIG (OR USE .ENV) =================
const API_KEY = "YOUR_API_KEY"; // Replace with your CapMonster Cloud API key
const URL = "https://www.example.com"; // Replace with your target URL
const SITEKEY = "xxxxxx";
const UA =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36";
// ================= PROXY (REPLACE WITH YOUR PROXY CREDENTIALS) =================
const PROXY_HOST = "PROXY_HOST";
const PROXY_PORT = 1234;
const PROXY_USER = "PROXY_USER";
const PROXY_PASS = "PROXY_PASSWORD";
const proxy = new ProxyAgent(
`http://${PROXY_USER}:${PROXY_PASS}@${PROXY_HOST}:${PROXY_PORT}`,
);
setGlobalDispatcher(proxy);
// ================= INITIALIZE CAPMONSTER CLOUD SDK =================
const cmcClient = CapMonsterCloudClientFactory.Create(
new ClientOptions({ clientKey: API_KEY }),
);
// ================= SESSION =================
let cookieHeader = "";
const headers = {
"User-Agent": UA,
Accept:
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
Connection: "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
"sec-ch-ua":
'"Chromium";v="149", "Google Chrome";v="149", "Not:A-Brand";v="99"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
};
// ================= FETCH PAGE =================
async function fetchPage(url) {
const response = await fetch(url, {
method: "GET",
headers: {
...headers,
...(cookieHeader && {
Cookie: cookieHeader,
}),
},
});
const buffer = Buffer.from(await response.arrayBuffer());
return {
status: response.status,
body: buffer,
};
}
// ================= SOLVE USING SDK =================
async function solveTurnstile(htmlBase64) {
try {
// Check account balance (optional)
const balance = await cmcClient.getBalance();
console.log("Balance:", balance);
// Create solve request
const turnstileRequest = new TurnstileRequest({
websiteURL: URL,
websiteKey: SITEKEY,
cloudflareTaskType: "cf_clearance",
htmlPageBase64: htmlBase64,
userAgent: UA,
proxy: {
proxyType: "http",
proxyAddress: PROXY_HOST,
proxyPort: PROXY_PORT,
proxyLogin: PROXY_USER,
proxyPassword: PROXY_PASS,
},
});
console.log("Submitting task...");
const result = await cmcClient.Solve(turnstileRequest);
console.log("Task solved!");
return result.solution.cf_clearance;
} catch (error) {
throw new Error(`CapMonster Cloud SDK error: ${error.message}`);
}
}
// ================= MAIN FUNCTION =================
async function main() {
// FIRST REQUEST
const first = await fetchPage(URL);
console.log("Initial status:", first.status);
console.log(first.body.toString("utf8").substring(0, 800));
// SOLVE CHALLENGE
const htmlBase64 = first.body.toString("base64");
const cfClearance = await solveTurnstile(htmlBase64);
console.log("cf_clearance:", cfClearance);
cookieHeader = `cf_clearance=${cfClearance}`;
// SECOND REQUEST
const second = await fetchPage(URL);
console.log("Final status:", second.status);
console.log(second.body.toString("utf8").substring(0, 800));
}
main().catch(console.error);
Show code
import time, base64, requests
# ================= CONFIG (OR USE .ENV) =================
API_KEY = "YOUR_API_KEY" # Replace with your CapMonster Cloud API key
URL = "https://www.example.com" # Replace with the target URL
SITEKEY = "xxxxxx"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36"
# ================= PROXY (REPLACE WITH YOUR PROXY CREDENTIALS) =================
PROXY_HOST = "PROXY_HOST"
PROXY_PORT = 1234
PROXY_USER = "PROXY_USER"
PROXY_PASS = "PROXY_PASSWORD"
PROXY_URL = f"http://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}:{PROXY_PORT}"
PROXY = {
"http": PROXY_URL,
"https": PROXY_URL
}
# ================= SESSION =================
session = requests.Session()
session.proxies.update(PROXY)
session.headers.update({
"User-Agent": UA,
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
"sec-ch-ua": '"Chromium";v="149", "Google Chrome";v="149", "Not:A-Brand";v="99"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"'
})
# ================= FETCH PAGE =================
def fetch(url):
return session.get(url, verify=True, timeout=30)
# ================= SEND JSON POST REQUEST =================
def solve_turnstile(html):
task = {
"clientKey": API_KEY,
"task": {
"type": "TurnstileTask",
"websiteURL": URL,
"websiteKey": SITEKEY,
"cloudflareTaskType": "cf_clearance",
"htmlPageBase64": html,
"userAgent": UA,
"proxyType": "http",
"proxyAddress": PROXY_HOST,
"proxyPort": PROXY_PORT,
"proxyLogin": PROXY_USER,
"proxyPassword": PROXY_PASS
}
}
create = requests.post(
"https://api.capmonster.cloud/createTask",
json=task
).json()
if create.get("errorId"):
raise Exception(create)
task_id = create["taskId"]
print("Task ID:", task_id)
while True:
time.sleep(5)
result = requests.post(
"https://api.capmonster.cloud/getTaskResult",
json={
"clientKey": API_KEY,
"taskId": task_id
}
).json()
if result.get("errorId"):
raise Exception(result)
if result.get("status") == "ready":
return result["solution"]["cf_clearance"]
print("Waiting...")
# ================= MAIN FUNCTION =================
# FIRST REQUEST
resp = fetch(URL)
print("Initial status:", resp.status_code)
print("\n--- Initial page snippet ---")
print(resp.text[:800])
print("\n----------------------------\n")
# SOLVE CHALLENGE
cookie = solve_turnstile(
base64.b64encode(resp.content).decode()
)
print("cf_clearance:", cookie)
session.cookies.set(
"cf_clearance",
cookie
)
# SECOND REQUEST
resp2 = fetch(URL)
print("Final status:", resp2.status_code)
print("\n--- Final page snippet ---")
print(resp2.text[:800])
Show code (SDK)
import base64, requests
import asyncio
from capmonstercloudclient import CapMonsterClient, ClientOptions
from capmonstercloudclient.requests import TurnstileRequest
from capmonstercloudclient.requests.baseRequestWithProxy import ProxyInfo
# ================= CONFIG (OR USE .ENV) =================
API_KEY = "YOUR_API_KEY" # Replace with your CapMonster Cloud API key
URL = "https://www.example.com" # Replace with the target URL
SITEKEY = "xxxxxx"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36"
# ================= PROXY (REPLACE WITH YOUR PROXY CREDENTIALS) =================
PROXY_HOST = "PROXY_HOST"
PROXY_PORT = 1234
PROXY_USER = "PROXY_USER"
PROXY_PASS = "PROXY_PASSWORD"
PROXY_URL = f"http://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}:{PROXY_PORT}"
PROXY = {
"http": PROXY_URL,
"https": PROXY_URL
}
# ================= SESSION =================
session = requests.Session()
session.proxies.update(PROXY)
session.headers.update({
"User-Agent": UA,
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
"sec-ch-ua": '"Chromium";v="149", "Google Chrome";v="149", "Not:A-Brand";v="99"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"'
})
# ================= FETCH PAGE =================
def fetch(url):
return session.get(url, verify=True, timeout=30)
# ================= SOLVE USING SDK =================
async def solve_turnstile(html_base64):
# Initialize the CapMonster Cloud client using the API key
client_options = ClientOptions(api_key=API_KEY)
cap_monster_client = CapMonsterClient(options=client_options)
# Check account balance (optional)
try:
balance = await cap_monster_client.get_balance()
print(f"Balance: {balance}")
except Exception as e:
print(f"Failed to get balance: {e}")
# Configure the proxy for CapMonster Cloud
proxy = ProxyInfo(
proxyType="http",
proxyAddress=PROXY_HOST,
proxyPort=PROXY_PORT,
proxyLogin=PROXY_USER,
proxyPassword=PROXY_PASS
)
# Create the solve request
turnstile_request = TurnstileRequest(
websiteURL=URL,
websiteKey=SITEKEY,
cloudflareTaskType="cf_clearance",
htmlPageBase64=html_base64,
userAgent=UA,
proxy=proxy
)
print("Submitting task...")
result = await cap_monster_client.solve_captcha(turnstile_request)
print("Task solved!")
# Extract cf_clearance from the result
return result.get('cf_clearance')
# ================= MAIN FUNCTION =================
async def main():
# FIRST REQUEST
resp = fetch(URL)
print("Initial status:", resp.status_code)
print("\n--- Initial page snippet ---")
print(resp.text[:800])
print("\n----------------------------\n")
# SOLVE USING SDK
html_base64 = base64.b64encode(resp.content).decode()
cf_clearance = await solve_turnstile(html_base64)
print("cf_clearance:", cf_clearance)
# Set the cookie for the session
if cf_clearance:
session.cookies.set("cf_clearance", str(cf_clearance))
else:
print("Error: failed to obtain cf_clearance")
return
# SECOND REQUEST
resp2 = fetch(URL)
print("Final status:", resp2.status_code)
print("\n--- Final page snippet ---")
print(resp2.text[:800])
# ================= RUN =================
if __name__ == "__main__":
asyncio.run(main())
Show code
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
class Program
{
// ================= CONFIG (OR USE .ENV) =================
const string API_KEY = "YOUR_API_KEY";
const string URL = "https://www.example.com";
const string SITEKEY = "xxxxxx";
const string UA =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36";
// ================= PROXY (REPLACE WITH YOUR PROXY CREDENTIALS) =================
const string PROXY_HOST = "PROXY_HOST";
const int PROXY_PORT = 1234;
const string PROXY_USER = "PROXY_USER";
const string PROXY_PASS = "PROXY_PASSWORD";
// ================= SESSION =================
static readonly CookieContainer Cookies = new();
static readonly HttpClient Client;
static readonly HttpClient Api = new();
static Program()
{
var handler = new HttpClientHandler
{
Proxy = new WebProxy(PROXY_HOST, PROXY_PORT)
{
Credentials = new NetworkCredential(PROXY_USER, PROXY_PASS)
},
UseProxy = true,
CookieContainer = Cookies,
AutomaticDecompression =
DecompressionMethods.GZip |
DecompressionMethods.Deflate
};
Client = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(30)
};
Client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", UA);
Client.DefaultRequestHeaders.TryAddWithoutValidation("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8");
Client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.9");
Client.DefaultRequestHeaders.TryAddWithoutValidation("Upgrade-Insecure-Requests", "1");
Client.DefaultRequestHeaders.TryAddWithoutValidation("Sec-Fetch-Dest", "document");
Client.DefaultRequestHeaders.TryAddWithoutValidation("Sec-Fetch-Mode", "navigate");
Client.DefaultRequestHeaders.TryAddWithoutValidation("Sec-Fetch-Site", "none");
Client.DefaultRequestHeaders.TryAddWithoutValidation("Sec-Fetch-User", "?1");
Client.DefaultRequestHeaders.TryAddWithoutValidation("sec-ch-ua",
"\"Chromium\";v=\"149\", \"Google Chrome\";v=\"149\", \"Not:A-Brand\";v=\"99\"");
Client.DefaultRequestHeaders.TryAddWithoutValidation("sec-ch-ua-mobile", "?0");
Client.DefaultRequestHeaders.TryAddWithoutValidation("sec-ch-ua-platform",
"\"Windows\"");
}
// ================= FETCH PAGE =================
static async Task<(HttpStatusCode Status, byte[] Body)> Fetch()
{
var response = await Client.GetAsync(URL);
return (
response.StatusCode,
await response.Content.ReadAsByteArrayAsync()
);
}
// ================= SEND JSON POST REQUEST =================
static async Task<JsonNode> PostJson(string url, object body)
{
var response = await Api.PostAsync(
url,
new StringContent(
JsonSerializer.Serialize(body),
Encoding.UTF8,
"application/json"));
var json = await response.Content.ReadAsStringAsync();
return JsonNode.Parse(json)!;
}
static async Task<string> SolveTurnstile(string html)
{
var task = new
{
clientKey = API_KEY,
task = new
{
type = "TurnstileTask",
websiteURL = URL,
websiteKey = SITEKEY,
cloudflareTaskType = "cf_clearance",
htmlPageBase64 = html,
userAgent = UA,
proxyType = "http",
proxyAddress = PROXY_HOST,
proxyPort = PROXY_PORT,
proxyLogin = PROXY_USER,
proxyPassword = PROXY_PASS
}
};
var create = await PostJson(
"https://api.capmonster.cloud/createTask",
task);
if (create["errorId"] != null)
throw new Exception(create.ToString());
int taskId = create["taskId"]!.GetValue<int>();
Console.WriteLine("Task ID: " + taskId);
while (true)
{
await Task.Delay(5000);
var result = await PostJson(
"https://api.capmonster.cloud/getTaskResult",
new
{
clientKey = API_KEY,
taskId
});
if (result["errorId"] != null)
throw new Exception(result.ToString());
if (result["status"]!.GetValue<string>() == "ready")
{
return result["solution"]!["cf_clearance"]!
.GetValue<string>();
}
Console.WriteLine("Waiting...");
}
}
// ================= MAIN FUNCTION =================
static async Task Main()
{
// FIRST REQUEST
var resp = await Fetch();
Console.WriteLine("Initial status: " + (int)resp.Status);
Console.WriteLine("\n--- Initial page snippet ---");
Console.WriteLine(
Encoding.UTF8.GetString(resp.Body)
.Substring(0, Math.Min(800, resp.Body.Length))
);
Console.WriteLine("\n----------------------------\n");
// SOLVE CHALLENGE
string cookie = await SolveTurnstile(
Convert.ToBase64String(resp.Body)
);
Console.WriteLine("cf_clearance: " + cookie);
Cookies.Add(
new Uri(URL),
new Cookie("cf_clearance", cookie)
);
// SECOND REQUEST
var resp2 = await Fetch();
Console.WriteLine("Final status: " + (int)resp2.Status);
Console.WriteLine("\n--- Final page snippet ---");
Console.WriteLine(
Encoding.UTF8.GetString(resp2.Body)
.Substring(0, Math.Min(800, resp2.Body.Length))
);
}
}
Show code (SDK)
using System.Net;
using System.Text;
using Zennolab.CapMonsterCloud;
using Zennolab.CapMonsterCloud.Requests;
using Zennolab.CapMonsterCloud.Responses;
class Program
{
// ================= CONFIG (OR USE .ENV) =================
const string API_KEY = "YOUR_API_KEY"; // Replace with your CapMonster Cloud API key
const string URL = "https://www.example.com"; // Replace with the target URL
const string SITEKEY = "xxxxxx";
const string UA =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36";
// ================= PROXY (REPLACE WITH YOUR PROXY CREDENTIALS) =================
const string PROXY_HOST = "PROXY_HOST";
const int PROXY_PORT = 1234;
const string PROXY_USER = "PROXY_USER";
const string PROXY_PASS = "PROXY_PASSWORD";
// ================= SESSION =================
static readonly CookieContainer Cookies = new();
static readonly HttpClient Client;
static readonly ICapMonsterCloudClient CmCloudClient;
static Program()
{
// Configure the proxy for the HTTP client
var handler = new HttpClientHandler
{
Proxy = new WebProxy(PROXY_HOST, PROXY_PORT)
{
Credentials = new NetworkCredential(PROXY_USER, PROXY_PASS)
},
UseProxy = true,
CookieContainer = Cookies,
AutomaticDecompression =
DecompressionMethods.GZip |
DecompressionMethods.Deflate
};
Client = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(30)
};
// Configure request headers
Client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", UA);
Client.DefaultRequestHeaders.TryAddWithoutValidation("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8");
Client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.9");
Client.DefaultRequestHeaders.TryAddWithoutValidation("Upgrade-Insecure-Requests", "1");
Client.DefaultRequestHeaders.TryAddWithoutValidation("Sec-Fetch-Dest", "document");
Client.DefaultRequestHeaders.TryAddWithoutValidation("Sec-Fetch-Mode", "navigate");
Client.DefaultRequestHeaders.TryAddWithoutValidation("Sec-Fetch-Site", "none");
Client.DefaultRequestHeaders.TryAddWithoutValidation("Sec-Fetch-User", "?1");
Client.DefaultRequestHeaders.TryAddWithoutValidation("sec-ch-ua",
"\"Chromium\";v=\"149\", \"Google Chrome\";v=\"149\", \"Not:A-Brand\";v=\"99\"");
Client.DefaultRequestHeaders.TryAddWithoutValidation("sec-ch-ua-mobile", "?0");
Client.DefaultRequestHeaders.TryAddWithoutValidation("sec-ch-ua-platform",
"\"Windows\"");
// Initialize the CapMonster Cloud client
var clientOptions = new ClientOptions
{
ClientKey = API_KEY
};
CmCloudClient = CapMonsterCloudClientFactory.Create(clientOptions);
}
// ================= FETCH PAGE =================
static async Task<(HttpStatusCode Status, byte[] Body)> Fetch()
{
var response = await Client.GetAsync(URL);
return (
response.StatusCode,
await response.Content.ReadAsByteArrayAsync()
);
}
// ================= SOLVE USING SDK =================
static async Task<string> SolveTurnstile(string htmlBase64)
{
try
{
// Check account balance (optional)
try
{
var balance = await CmCloudClient.GetBalanceAsync(CancellationToken.None);
Console.WriteLine($"Balance: {balance}");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to get balance: {ex.Message}");
}
// Create the solve request
var turnstileRequest = new TurnstileRequest
{
WebsiteUrl = URL,
WebsiteKey = SITEKEY,
CloudflareTaskType = "cf_clearance",
HtmlPageBase64 = htmlBase64,
UserAgent = UA,
Proxy = new ProxyContainer(
PROXY_HOST,
PROXY_PORT,
ProxyType.Http,
PROXY_USER,
PROXY_PASS
)
};
Console.WriteLine("Submitting task...");
// Solve the challenge
var result = await CmCloudClient.SolveAsync(turnstileRequest, CancellationToken.None);
Console.WriteLine("Task solved!");
// Extract cf_clearance from the result
if (result.Solution != null)
{
// Try to get the clearance value
var clearance = result.Solution.Clearance;
if (!string.IsNullOrEmpty(clearance))
{
return clearance;
}
}
return string.Empty;
}
catch (Exception ex)
{
throw new Exception($"CapMonster SDK error: {ex.Message}", ex);
}
}
// ================= MAIN FUNCTION =================
static async Task Main()
{
try
{
// FIRST REQUEST
var resp = await Fetch();
Console.WriteLine($"Initial status: {(int)resp.Status}");
Console.WriteLine("\n--- Initial page snippet ---");
var bodyText = Encoding.UTF8.GetString(resp.Body);
Console.WriteLine(bodyText.Length > 800 ? bodyText[..800] : bodyText);
Console.WriteLine("\n----------------------------\n");
// SOLVE USING SDK
var htmlBase64 = Convert.ToBase64String(resp.Body);
var cfClearance = await SolveTurnstile(htmlBase64);
if (string.IsNullOrEmpty(cfClearance))
{
Console.WriteLine("Error: failed to obtain cf_clearance");
return;
}
Console.WriteLine($"cf_clearance: {cfClearance}");
// Set the cookie for the session
Cookies.Add(
new Uri(URL),
new Cookie("cf_clearance", cfClearance)
);
// SECOND REQUEST
var resp2 = await Fetch();
Console.WriteLine($"Final status: {(int)resp2.Status}");
Console.WriteLine("\n--- Final page snippet ---");
var bodyText2 = Encoding.UTF8.GetString(resp2.Body);
Console.WriteLine(bodyText2.Length > 800 ? bodyText2[..800] : bodyText2);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
