In questo articolo abbiamo cercato di rispondere a tutte le domande principali. Il primo passo per risolvere il problema è capire quale sistema di protezione viene utilizzato. A questo scopo puoi consultare l’elenco dei captcha e dei sistemi di protezione antibot più diffusi, dove trovi esempi visivi e caratteristiche chiave che ti aiutano a identificare rapidamente con cosa hai a che fare.
Se scopri che sul tuo sito viene utilizzato Cloudflare Turnstile, il passo successivo è analizzarne più nel dettaglio le proprietà e il funzionamento. In questo stesso articolo puoi anche studiare la guida all’integrazione di Cloudflare Turnstile, per comprendere a fondo come opera sul tuo sito. Questo ti permetterà non solo di capire la protezione attuale, ma anche di pianificarne correttamente la manutenzione.
Quando testi form che includono Cloudflare Turnstile devi spesso verificare che la captcha funzioni e sia integrata correttamente.
Puoi verificare manualmente la captcha inserita nel tuo sito.
Per la risoluzione automatica puoi usare strumenti come CapMonster Cloud, che accetta i parametri della captcha, li elabora sui propri server e restituisce un token pronto all'uso. Inserisci quel token nel form per superare il controllo senza intervento dell'utente.
Lavorare con CapMonster Cloud via API di solito prevede i seguenti passaggi:
Nella richiesta per risolvere Cloudflare Turnstile è necessario specificare i seguenti parametri:
type - TurnstileTask;
websiteURL - indirizzo della pagina dove viene risolto il CAPTCHA;
websiteKey - chiave Turnstile.
https://api.capmonster.cloud/createTask{
"clientKey": "API_KEY",
"task": {
"type": "TurnstileTask",
"websiteURL": "http://tsmanaged.zlsupport.com",
"websiteKey": "0x4AAAAAAABUYP0XeMJF0xoy"
}
}{
"errorId":0,
"taskId":407533072
}https://api.capmonster.cloud/getTaskResult{
"clientKey":"API_KEY",
"taskId": 407533072
}{
"errorId": 0,
"status": "ready",
"solution": {
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
"token": "0.iGX3xsyFCkbGePM3jP4P4khLo6TrLukt8ZzBvwuQOvbC...f61f3082"
}
}// npm install playwright @zennolab_com/capmonstercloud-client
import { chromium } from "playwright";
import { CapMonsterCloudClientFactory, ClientOptions, TurnstileRequest } from "@zennolab_com/capmonstercloud-client";
async function main() {
// 1. Risoluzione Turnstile tramite CapMonster Cloud
const cmcClient = CapMonsterCloudClientFactory.Create(
new ClientOptions({ clientKey: 'YOUR_CAPMONSTER_API_KEY' })
);
const turnstileRequest = new TurnstileRequest({
websiteURL: 'http://tsmanaged.zlsupport.com',
websiteKey: '0x4AAAAAAABUYP0XeMJF0xoy',
});
const result = await cmcClient.Solve(turnstileRequest);
const token = result.solution.token;
console.log('Token Turnstile ricevuto:', token);
// 2. Avvio di Playwright
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('http://tsmanaged.zlsupport.com');
// 3. Compilazione di login e password
await page.fill('#username', 'your_username');
await page.fill('#password', 'your_password');
// 4. Attesa della comparsa del campo token nascosto
await page.waitForSelector('#token', { state: 'attached', timeout: 60000 });
// 5. Inserimento del token e rendere visibile il campo
await page.evaluate((t) => {
const tokenInput = document.querySelector('#token');
if (tokenInput) {
tokenInput.type = 'text'; // rendi visibile il campo
tokenInput.value = t; // inserisci il token
console.log('Token inserito nel campo token');
} else {
console.error('Campo #token non trovato');
}
}, token);
// 6. Verifica che il token sia stato effettivamente inserito
const checkValue = await page.$eval('#token', el => el.value);
console.log('Verifica del valore del token:', checkValue);
// 7. Invio del modulo
await page.click('button[type="submit"]');
console.log('Modulo inviato con token Turnstile');
// await browser.close();
}
main().catch(err => console.error(err));1. Vai alla pagina Cloudflare Turnstile, fai clic su Inizia ora.
2. Registrati al servizio.
3. In Turnstile Widgets, fai clic sul pulsante blu Add Widget.

4. Configura Cloudflare Turnstile, specifica:
5. Dopo aver creato il widget, riceverai due chiavi: Site Key e Secret Key.

6. Connetti la parte client
1) Connetti lo script Turnstile
Rendering automatico (il widget viene creato automaticamente al caricamento della pagina):
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>Controllo programmatico (crei tu stesso il widget tramite JavaScript):
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit" defer></script>Importante: lo script deve essere caricato dall'URL esatto. Proxy o cache possono causare malfunzionamenti.
2) Crea un contenitore per il widget
Automatico:
<div class="cf-turnstile" data-sitekey="<YOUR_SITEKEY>"></div>Programmaticamente:
<div id="turnstile-container"></div>3) Configurazione del widget
Tramite attributi data:
<div class="cf-turnstile"
data-sitekey="<YOUR_SITEKEY>"
data-theme="light"
data-size="normal"
data-callback="onSuccess">
</div>Tramite JavaScript:
const widgetId = turnstile.render("#turnstile-container", {
sitekey: "<YOUR_SITEKEY>",
theme: "light",
size: "normal",
callback: token => console.log("Token:", token)
});4) Lavorare con i token
const token = turnstile.getResponse(widgetId); // ottieni il token
const isExpired = turnstile.isExpired(widgetId); // verifica la scadenza
turnstile.reset(widgetId); // reimposta
turnstile.remove(widgetId); // rimuovi
turnstile.execute("#turnstile-container"); // esecuzione manuale
5) Integrazione con il modulo
<form id="my-form" method="POST">
<input type="hidden" name="cf-turnstile-response" id="cf-turnstile-response">
<button type="submit">Invia</button>
</form>
<script>
function onSuccess(token) {
document.getElementById("cf-turnstile-response").value = token;
}
</script>
<title>Turnstile Example</title>
<!-- Connetti lo script Turnstile -->
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
</head>
<body>
<h1>Esempio di modulo con Turnstile</h1>
<form id="my-form">
<label for="username">Nome:</label>
<input type="text" name="username" id="username" required>
<!-- Contenitore per Turnstile -->
<div class="cf-turnstile" data-sitekey="<YOUR_SITEKEY>" data-callback="onTurnstileSuccess"></div>
<button type="submit">Invia</button>
</form>
<script>
// Callback chiamato dopo il superamento del CAPTCHA
function onTurnstileSuccess(token) {
console.log("Token Turnstile ricevuto:", token);
// Salva il token nel campo modulo nascosto (facoltativo)
document.getElementById("cf-turnstile-token")?.remove();
const input = document.createElement("input");
input.type = "hidden";
input.name = "cf-turnstile-response";
input.id = "cf-turnstile-token";
input.value = token;
document.getElementById("my-form").appendChild(input);
}
// Invio del modulo
document.getElementById("my-form").addEventListener("submit", async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const response = await fetch("/submit-form", {
method: "POST",
body: formData
});
const result = await response.json();
if(result.success){
alert("Modulo inviato con successo e token verificato!");
} else {
alert("Errore di verifica del token Turnstile. Riprova.");
// Reimposta il widget in modo che l'utente possa completare nuovamente il CAPTCHA
turnstile.reset();
}
});
</script>
</body>
</html>
6) Configura la parte server
Processo di verifica lato server:
API Siteverify:
https://challenges.cloudflare.com/turnstile/v0/siteverifyParametri della richiesta:
Proprietà del token:
<?php
function validateTurnstile($token, $secret, $remoteip = null) {
$url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
$data = ['secret' => $secret, 'response' => $token];
if ($remoteip) $data['remoteip'] = $remoteip;
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded
",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$response = file_get_contents($url, false, stream_context_create($options));
if ($response === FALSE) {
return ['success' => false, 'error-codes' => ['internal-error']];
}
return json_decode($response, true);
}
// Utilizzo
$secret_key = 'YOUR_SECRET_KEY';
$token = $_POST['cf-turnstile-response'] ?? '';
$remoteip = $_SERVER['REMOTE_ADDR'];
$result = validateTurnstile($token, $secret_key, $remoteip);
if($result['success']){
echo "Modulo inviato con successo!";
} else {
echo "Errore di verifica: " . implode(', ', $result['error-codes']);
}
?>
Se ti è capitato un sito con un captcha o un altro sistema di protezione già installato e senza accesso al codice, nessun problema! È piuttosto facile capire quale tecnologia viene utilizzata. Per verificare che tutto funzioni correttamente, puoi usare il servizio di riconoscimento CapMonster Cloud in un ambiente di test isolato, così da assicurarti che il meccanismo di elaborazione dei token e la logica di verifica funzionino correttamente.
Nel caso di Cloudflare Turnstile, è sufficiente individuare il sistema, analizzarne il comportamento e assicurarsi che la protezione funzioni correttamente. Nell’articolo abbiamo mostrato come riconoscere Cloudflare Turnstile e dove trovare le istruzioni per la sua integrazione o riconfigurazione, in modo da poter mantenere la protezione in modo affidabile e controllarne il funzionamento.