CAPTCHA Result Validation (Legacy v1 / v2)
Here we explain how you call up and evaluate the CAPTCHA result in your backend from our server.
Preparation
Section titled “Preparation”You should have already completed the following steps before you start with CAPTCHA validation in your Node.js backend.
Read the basic Information: For a basic overview, please read the get started guide. We also recommend that you familiarize yourself with the technical concept of TrustCaptcha.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.
Existing Node.js project: You need a Node.js project in which you want to integrate TrustCaptcha.
Verification token: You need the verification token from your frontend, which you receive every time you successfully solve the CAPTCHA.
You should have already completed the following steps before you start with CAPTCHA validation in your PHP backend.
Read the basic Information: For a basic overview, please read the get started guide. We also recommend that you familiarize yourself with the technical concept of TrustCaptcha.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.
Existing PHP project: You need a PHP project in which you want to integrate TrustCaptcha.
Verification token: You need the verification token from your frontend, which you receive every time you successfully solve the CAPTCHA.
You should have already completed the following steps before you start with CAPTCHA validation in your Python backend.
Read the basic Information: For a basic overview, please read the get started guide. We also recommend that you familiarize yourself with the technical concept of TrustCaptcha.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.
Existing Python project: You need a Python project in which you want to integrate TrustCaptcha.
Verification token: You need the verification token from your frontend, which you receive every time you successfully solve the CAPTCHA.
You should have already completed the following steps before you start with CAPTCHA validation in your JVM backend.
Read the basic Information: For a basic overview, please read the get started guide. We also recommend that you familiarize yourself with the technical concept of TrustCaptcha.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.
Existing JVM project: You need a JVM project in which you want to integrate TrustCaptcha.
Verification token: You need the verification token from your frontend, which you receive every time you successfully solve the CAPTCHA.
You should have already completed the following steps before you start with CAPTCHA validation in your DotNet backend.
Read the basic Information: For a basic overview, please read the get started guide. We also recommend that you familiarize yourself with the technical concept of TrustCaptcha.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.
Existing DotNet project: You need a DotNet project in which you want to integrate TrustCaptcha.
Verification token: You need the verification token from your frontend, which you receive every time you successfully solve the CAPTCHA.
You should have already completed the following steps before you start with CAPTCHA validation in your Go backend.
Read the basic Information: For a basic overview, please read the get started guide. We also recommend that you familiarize yourself with the technical concept of TrustCaptcha.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.
Existing Go project: You need a Go project in which you want to integrate TrustCaptcha.
Verification token: You need the verification token from your frontend, which you receive every time you successfully solve the CAPTCHA.
You should have already completed the following steps before you start with CAPTCHA validation in your Ruby backend.
Read the basic Information: For a basic overview, please read the get started guide. We also recommend that you familiarize yourself with the technical concept of TrustCaptcha.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.
Existing Ruby project: You need a Ruby project in which you want to integrate TrustCaptcha.
Verification token: You need the verification token from your frontend, which you receive every time you successfully solve the CAPTCHA.
You should have already completed the following steps before you start with CAPTCHA validation in your Rust backend.
Read the basic Information: For a basic overview, please read the get started guide. We also recommend that you familiarize yourself with the technical concept of TrustCaptcha.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.
Existing Rust project: You need a Rust project in which you want to integrate TrustCaptcha.
Verification token: You need the verification token from your frontend, which you receive every time you successfully solve the CAPTCHA.
How the integration works
Section titled “How the integration works”Follow the three steps below to retrieve and evaluate the CAPTCHA verification result in your Node.js backend.
You can find the source code of our Node.js CAPTCHA integration on Github.
Follow the three steps below to retrieve and evaluate the CAPTCHA verification result in your PHP backend.
You can find the source code of our PHP CAPTCHA integration on Github.
Follow the three steps below to retrieve and evaluate the CAPTCHA verification result in your Python backend.
You can find the source code of our Python CAPTCHA integration on Github.
Follow the three steps below to retrieve and evaluate the CAPTCHA verification result in your JVM backend.
You can find the source code of our JVM CAPTCHA integration on Github.
Follow the three steps below to retrieve and evaluate the CAPTCHA verification result in your DotNet backend.
You can find the source code of our DotNet CAPTCHA integration on Github.
Follow the three steps below to retrieve and evaluate the CAPTCHA verification result in your Go backend.
You can find the source code of our Go CAPTCHA integration on Github.
Follow the three steps below to retrieve and evaluate the CAPTCHA verification result in your Ruby backend.
You can find the source code of our Ruby CAPTCHA integration on Github.
Follow the three steps below to retrieve and evaluate the CAPTCHA verification result in your Rust backend.
You can find the source code of our Rust CAPTCHA integration on Github.
1. Add dependency
Section titled “1. Add dependency”To use the TrustCaptcha Node.js library, you first need to add the corresponding dependencies to your project.
npm i @trustcomponent/trustcaptcha-nodejsYou can find our TrustCaptcha Node.js package on npmjs.com.
To use the TrustCaptcha PHP library, you first need to add the corresponding dependencies to your project.
composer require trustcomponent/trustcaptcha-phpYou can find our TrustCaptcha PHP package on Packagist.
To use the TrustCaptcha Python library, you first need to add the corresponding dependencies to your project.
pip install trustcaptchaYou can find our TrustCaptcha Python package on PyPI.
To use the TrustCaptcha JVM library, you first need to add the corresponding dependencies to your project.
<dependency> <groupId>com.trustcomponent</groupId> <artifactId>trustcaptcha</artifactId> <version>2.0.1</version></dependency>You can find our TrustCaptcha JVM package on Maven Central.
To use the TrustCaptcha DotNet library, you first need to add the corresponding dependencies to your project.
dotnet add package TrustComponent.TrustCaptcha --version 2.0.1You can find our TrustCaptcha DotNet package on Nuget.org.
To use the TrustCaptcha Go library, you first need to add the corresponding dependencies to your project.
go get github.com/trustcomponent/trustcaptcha-go/v2@v2.0.2You can find our TrustCaptcha Go package on https://pkg.go.dev/.
To use the TrustCaptcha Ruby library, you first need to add the corresponding dependencies to your project.
gem install trustcaptchaYou can find our TrustCaptcha Ruby package on Rubygems.
To use the TrustCaptcha Rust library, you first need to add the corresponding dependencies to your project.
cargo add trustcaptchaYou can find our TrustCaptcha Rust package on crates.io.
2. Fetch result
Section titled “2. Fetch result”In the next step, retrieve the CAPTCHA result from our servers.
If the CAPTCHA widget has been successfully solved in the frontend, you will receive a so-called verification token. Send this to your backend. You will also need an api-key. You can manage your API keys in the dashboard of your CAPTCHA.
Now use the CaptchaManager class of our Node.js integration to retrieve the verification result from our servers.
// Retrieving the verification resultlet verificationResult;try { verificationResult = await CaptchaManager.getVerificationResult("<your_api_or_secret_key>", "<verification_token_from_your_client>");} catch (error) { // Fetch verification result failed - handle error}In the next step, retrieve the CAPTCHA result from our servers.
If the CAPTCHA widget has been successfully solved in the frontend, you will receive a so-called verification token. Send this to your backend. You will also need an api-key. You can manage your API keys in the dashboard of your CAPTCHA.
Now use the CaptchaManager class of our PHP integration to retrieve the verification result from our servers.
// Retrieving the verification result$verificationResult = null;try { $verificationResult = CaptchaManager::getVerificationResult("<your_api_or_secret_key>", $verificationToken);} catch (Exception $e) { // Fetch verification result failed - handle error}In the next step, retrieve the CAPTCHA result from our servers.
If the CAPTCHA widget has been successfully solved in the frontend, you will receive a so-called verification token. Send this to your backend. You will also need an api-key. You can manage your API keys in the dashboard of your CAPTCHA.
Now use the CaptchaManager class of our Python integration to retrieve the verification result from our servers.
# Retrieving the verification resulttry: verification_result = CaptchaManager.get_verification_result("<your_api_or_secret_key>", "<verification_token_from_your_client>")except Exception as e: # Fetch verification result failed - handle error print(f"Failed to fetch verification result: {e}") return jsonify({'error': 'Captcha verification failed'}), 500In the next step, retrieve the CAPTCHA result from our servers.
If the CAPTCHA widget has been successfully solved in the frontend, you will receive a so-called verification token. Send this to your backend. You will also need an api-key. You can manage your API keys in the dashboard of your CAPTCHA.
Now use the CaptchaManager class of our JVM integration to retrieve the verification result from our servers.
// Retrieving the verification resultVerificationResult verificationResult;try { verificationResult = CaptchaManager.getVerificationResult("<your_api_or_secret_key>", "<verification_token_from_your_client>");} catch (CaptchaFailureException e) { // Fetch verification result failed - handle error}In the next step, retrieve the CAPTCHA result from our servers.
If the CAPTCHA widget has been successfully solved in the frontend, you will receive a so-called verification token. Send this to your backend. You will also need an api-key. You can manage your API keys in the dashboard of your CAPTCHA.
Now use the CaptchaManager class of our DotNet integration to retrieve the verification result from our servers.
// Retrieving the verification resultVerificationResult verificationResult;try{ verificationResult = await CaptchaManager.GetVerificationResult("<your_api_or_secret_key>", "<verification_token_from_your_client>");}catch (Exception ex){ // Fetch verification result failed - handle error}In the next step, retrieve the CAPTCHA result from our servers.
If the CAPTCHA widget has been successfully solved in the frontend, you will receive a so-called verification token. Send this to your backend. You will also need an api-key. You can manage your API keys in the dashboard of your CAPTCHA.
Now use the CaptchaManager class of our Go integration to retrieve the verification result from our servers.
// Retrieving the verification resultverificationResult, err := trustcaptcha.GetVerificationResult("<your_api_or_secret_key>", "<verification_token_from_your_client>")if err != nil { log.Printf("Failed to fetch verification result: %v", err) http.Error(w, "Captcha verification failed", http.StatusInternalServerError) return}In the next step, retrieve the CAPTCHA result from our servers.
If the CAPTCHA widget has been successfully solved in the frontend, you will receive a so-called verification token. Send this to your backend. You will also need an api-key. You can manage your API keys in the dashboard of your CAPTCHA.
Now use the CaptchaManager class of our Ruby integration to retrieve the verification result from our servers.
# Retrieving the verification resultbegin verification_result = CaptchaManager.get_verification_result('<your_api_or_secret_key>', verification_token)rescue StandardError => e # Fetch verification result failed - handle error puts "Failed to fetch verification result: #{e.class} - #{e.message}" status 500 return { error: 'Captcha verification failed', message: e.message }.to_jsonendIn the next step, retrieve the CAPTCHA result from our servers.
If the CAPTCHA widget has been successfully solved in the frontend, you will receive a so-called verification token. Send this to your backend. You will also need an api-key. You can manage your API keys in the dashboard of your CAPTCHA.
Now use the CaptchaManager class of our Rust integration to retrieve the verification result from our servers.
// Retrieving the verification resultlet verification_result = match CaptchaManager::get_verification_result("<your_api_or_secret_key>", "<verification_token_from_your_client>").await { Ok(result) => result, Err(e) => { // Fetch verification result failed - handle error error!("Failed to fetch verification result: {}", e); return Ok(HttpResponse::InternalServerError().json(json!({"error": "Captcha verification failed"}))); }};3. Evaluate the result
Section titled “3. Evaluate the result”Once you have successfully fetched the verification result, you can plan your next steps based on it. A concrete overview of all the information contained in the verification result and their respective meanings can be found in the legacy result validation overview.
// Act on the verification resultif (!verificationResult.verificationPassed || verificationResult.score > 0.5) { console.log("Verification failed or bot score > 0.5 – possible automated request.");}Once you have successfully fetched the verification result, you can plan your next steps based on it. A concrete overview of all the information contained in the verification result and their respective meanings can be found in the legacy result validation overview.
// Act on the verification resultif (!$verificationResult->verificationPassed || $verificationResult->score > 0.5) { echo "Verification failed or bot score > 0.5 – possible automated request.";}Once you have successfully fetched the verification result, you can plan your next steps based on it. A concrete overview of all the information contained in the verification result and their respective meanings can be found in the legacy result validation overview.
# Act on the verification resultif verification_result.verificationPassed is not True or verification_result.score > 0.5: print("Verification failed or bot score > 0.5 – possible automated request.")Once you have successfully fetched the verification result, you can plan your next steps based on it. A concrete overview of all the information contained in the verification result and their respective meanings can be found in the legacy result validation overview.
// Act on the verification resultif (!verificationResult.isVerificationPassed() || verificationResult.getScore() > 0.5) { logger.warn("Verification failed or bot score > 0.5 – possible automated request.");}Once you have successfully fetched the verification result, you can plan your next steps based on it. A concrete overview of all the information contained in the verification result and their respective meanings can be found in the legacy result validation overview.
// Act on the verification resultif (!verificationResult.VerificationPassed || verificationResult.Score > 0.5){ Console.WriteLine("Verification failed or bot score > 0.5 – possible automated request.");}Once you have successfully fetched the verification result, you can plan your next steps based on it. A concrete overview of all the information contained in the verification result and their respective meanings can be found in the legacy result validation overview.
// Act on the verification resultif !verificationResult.VerificationPassed || verificationResult.Score > 0.5 { log.Println("Verification failed or bot score > 0.5 – possible automated request.")}Once you have successfully fetched the verification result, you can plan your next steps based on it. A concrete overview of all the information contained in the verification result and their respective meanings can be found in the legacy result validation overview.
# Act on the verification resultif !verification_result.verification_passed || verification_result.score > 0.5 puts 'Verification failed or bot score > 0.5 – possible automated request.'endOnce you have successfully fetched the verification result, you can plan your next steps based on it. A concrete overview of all the information contained in the verification result and their respective meanings can be found in the legacy result validation overview.
// Act on the verification resultif !verification_result.verification_passed || verification_result.score > 0.5 { info!("Verification failed or bot score > 0.5 – possible automated request.");}Example implementation
Section titled “Example implementation”The following example shows a possible implementation of TrustCaptcha in a Node.js backend.
In this example: When a POST request is sent to /api/example, the CAPTCHA verification token is sent to the Node.js backend in the request body. In the backend, our library is used to retrieve the CAPTCHA verification result from our servers and evaluate it. If the verification fails or the bot score exceeds 0.5, a warning is displayed. In addition, the entire verification result is returned to the client.
Hint: The steps and thresholds shown are examples and should be adapted to your individual requirements in your specific use case.
The complete example including source code can be found on Github.
import express from 'express';import cors from 'cors';import { json } from 'body-parser';import {CaptchaManager} from "@trustcomponent/trustcaptcha-nodejs";
const app = express();app.use(cors({ origin: '*' }));app.use(json());
app.post('/api/example', async (req, res) => {
const verificationToken = req.body.verificationToken;
// Retrieving the verification result let verificationResult; try { verificationResult = await CaptchaManager.getVerificationResult("<your_api_or_secret_key>", verificationToken); } catch (error) { // Fetch verification result failed - handle error console.error(error) res.status(500).send('Internal Server Error'); return }
// Act on the verification result if (!verificationResult.verificationPassed || verificationResult.score > 0.5) { console.log("Verification failed or bot score > 0.5 – possible automated request."); }
res.json(verificationResult);});
app.listen(8080, () => { console.log('Server is running on http://localhost:8080');});The following example shows a possible implementation of TrustCaptcha in a PHP backend.
In this example: When a POST request is sent to /api/example, the CAPTCHA verification token is sent to the PHP backend in the request body. In the backend, our library is used to retrieve the CAPTCHA verification result from our servers and evaluate it. If the verification fails or the bot score exceeds 0.5, a warning is displayed. In addition, the entire verification result is returned to the client.
Hint: The steps and thresholds shown are examples and should be adapted to your individual requirements in your specific use case.
The complete example including source code can be found on Github.
<?php
require_once __DIR__ . '/vendor/autoload.php';
use TrustComponent\TrustCaptcha\CaptchaManager;
$message = "";$verificationResult = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') { $message = $_POST['message'] ?? ''; $verificationToken = $_POST['tc-verification-token'] ?? '';
// Retrieving the verification result try { $verificationResult = CaptchaManager::getVerificationResult("<your_api_or_secret_key>", $verificationToken); } catch (Exception $e) { // Fetch verification result failed - handle error throw new RuntimeException($e); }
// Act on the verification result if (!$verificationResult->verificationPassed || $verificationResult->score > 0.5) { $message = "Verification failed or bot score > 0.5 – possible automated request."; }}
?>
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>Trustcaptcha Testsystem</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous"> <script src="https://cdn.trustcomponent.com/trustcaptcha/2.2.x/trustcaptcha.umd.min.js"></script> </head> <body class="py-5"> <div class="d-flex justify-content-center"> <div class="w-100" style="max-width: 640px;"> <h1>PHP</h1> Try PHP<br /> <form action="/" method="post"> <div class="mb-3"> <label for="messageInput" class="form-label">Message</label> <textarea class="form-control" id="messageInput" name="message" placeholder="Write a message" rows="3"><?= htmlspecialchars($message) ?></textarea> </div> <div class="mb-3"> <trustcaptcha-component id="trustcaptchaComponent" sitekey="<your_site_key>" language="en" theme="light" ></trustcaptcha-component> </div> <div class="d-grid gap-2"> <button class="btn btn-success" id="submitButton" disabled>Post new message</button> </div> </form> <?php if ($verificationResult): ?> <div class="alert alert-success mt-3" role="alert"> <strong>Message: </strong><?= htmlspecialchars($message) ?><br> <strong>Passed: </strong><?= $verificationResult->verificationPassed ? 'true' : 'false' ?><br> <strong>Reason: </strong><?= htmlspecialchars($verificationResult->reason) ?><br> <strong>Score: </strong><?= htmlspecialchars($verificationResult->score) ?> </div> <?php endif; ?> </div> </div> </body>
<script>
<!-- example, unused in this sample --> function resetCaptcha() { const trustcaptchaComponent = document.getElementById('trustcaptchaComponent'); trustcaptchaComponent.reset(); }
const trustcaptchaComponent = document.getElementById('trustcaptchaComponent'); trustcaptchaComponent.addEventListener('captchaSolved', (event) => { console.log('Verification token:', event.detail); const submitButton = document.getElementById('submitButton'); submitButton.disabled = false; }); trustcaptchaComponent.addEventListener('captchaFailed', (event) => { console.error(event.detail); }); </script>
</html>The following example shows a possible implementation of TrustCaptcha in a Python backend.
In this example: When a POST request is sent to /api/example, the CAPTCHA verification token is sent to the Python backend in the request body. In the backend, our library is used to retrieve the CAPTCHA verification result from our servers and evaluate it. If the verification fails or the bot score exceeds 0.5, a warning is displayed. In addition, the entire verification result is returned to the client.
Hint: The steps and thresholds shown are examples and should be adapted to your individual requirements in your specific use case.
The complete example including source code can be found on Github.
from flask import Flask, request, jsonifyfrom flask_cors import cross_originfrom trustcaptcha.captcha_manager import CaptchaManager
app = Flask(__name__)
@app.route('/api/example', methods=['POST'])@cross_origin(origins=["http://localhost:*", "http://127.0.0.1:*"])def post_api_example():
verification_token = request.get_json()['verificationToken']
# Retrieving the verification result try: verification_result = CaptchaManager.get_verification_result("<your_api_or_secret_key>", verification_token) except Exception as e: # Fetch verification result failed - handle error print(f"Failed to fetch verification result: {e}") return jsonify({'error': 'Captcha verification failed'}), 500
# Act on the verification result if verification_result.verificationPassed is not True or verification_result.score > 0.5: print("Verification failed or bot score > 0.5 – possible automated request.")
return verification_result.to_json()
if __name__ == '__main__': app.run(debug=True, port=8080)The following example shows a possible implementation of TrustCaptcha in a JVM backend.
In this example: When a POST request is sent to /api/example, the CAPTCHA verification token is sent to the JVM backend in the request body. In the backend, our library is used to retrieve the CAPTCHA verification result from our servers and evaluate it. If the verification fails or the bot score exceeds 0.5, a warning is displayed. In addition, the entire verification result is returned to the client.
Hint: The steps and thresholds shown are examples and should be adapted to your individual requirements in your specific use case.
The complete example including source code can be found on Github.
import com.trustcomponent.trustcaptcha.CaptchaManager;import com.trustcomponent.trustcaptcha.exception.CaptchaFailureException;import com.trustcomponent.trustcaptcha.model.VerificationResult;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.*;
@RestController@CrossOrigin(originPatterns = {"http://localhost:[*]", "http://127.0.0.1:[*]"})public class ApiController {
private static final Logger logger = LoggerFactory.getLogger(ApiController.class);
@PostMapping("/api/example") public ResponseEntity<VerificationResult> postApiExample(@RequestBody VerificationRequest verificationRequest) {
// Retrieving the verification result VerificationResult verificationResult; try { verificationResult = CaptchaManager.getVerificationResult("<your_api_or_secret_key>", verificationRequest.getVerificationToken()); } catch (CaptchaFailureException e) { // Fetch verification result failed - handle error throw new RuntimeException(e); }
// Act on the verification result if (!verificationResult.isVerificationPassed() || verificationResult.getScore() > 0.5) { logger.warn("Verification failed or bot score > 0.5 – possible automated request."); }
return ResponseEntity.ok(verificationResult); }}The following example shows a possible implementation of TrustCaptcha in a DotNet backend.
In this example: When a POST request is sent to /api/example, the CAPTCHA verification token is sent to the DotNet backend in the request body. In the backend, our library is used to retrieve the CAPTCHA verification result from our servers and evaluate it. If the verification fails or the bot score exceeds 0.5, a warning is displayed. In addition, the entire verification result is returned to the client.
Hint: The steps and thresholds shown are examples and should be adapted to your individual requirements in your specific use case.
The complete example including source code can be found on Github.
using Microsoft.AspNetCore.Mvc;using csharp_sample.Models;using TrustComponent.TrustCaptcha;using TrustComponent.TrustCaptcha.Model;
namespace csharp_sample.Controllers;
[ApiController][Route("api/example")]public class CaptchaController : ControllerBase{ [HttpPost] public async Task<IActionResult> PostApiExample([FromBody] VerificationRequest verificationRequest) { // Retrieving the verification result VerificationResult verificationResult; try { verificationResult = await CaptchaManager.GetVerificationResult("<your_api_or_secret_key>", verificationRequest.VerificationToken); Console.WriteLine(verificationResult.VerificationPassed); } catch (Exception ex) { // Fetch verification result failed - handle error Console.WriteLine($"Error: {ex.Message}"); return StatusCode(500, new { error = "Captcha verification failed", details = ex.Message }); }
// Act on the verification result if (!verificationResult.VerificationPassed || verificationResult.Score > 0.5) { Console.WriteLine("Verification failed or bot score > 0.5 – possible automated request."); }
return Ok(verificationResult); }}The following example shows a possible implementation of TrustCaptcha in a Go backend.
In this example: When a POST request is sent to /api/example, the CAPTCHA verification token is sent to the Go backend in the request body. In the backend, our library is used to retrieve the CAPTCHA verification result from our servers and evaluate it. If the verification fails or the bot score exceeds 0.5, a warning is displayed. In addition, the entire verification result is returned to the client.
Hint: The steps and thresholds shown are examples and should be adapted to your individual requirements in your specific use case.
The complete example including source code can be found on Github.
package main
import ( "encoding/json" "fmt" "github.com/trustcomponent/trustcaptcha-go/v2" "log" "net/http")
type VerificationRequest struct { VerificationToken string `json:"verificationToken"`}
func postApiExample(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK) return }
var req VerificationRequest
// Parse the request body if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return }
// Retrieving the verification result verificationResult, err := trustcaptcha.GetVerificationResult("<your_api_or_secret_key>", req.VerificationToken) if err != nil { log.Printf("Failed to fetch verification result: %v", err) http.Error(w, "Captcha verification failed", http.StatusInternalServerError) return }
// Act on the verification result if !verificationResult.VerificationPassed || verificationResult.Score > 0.5 { log.Println("Verification failed or bot score > 0.5 – possible automated request.") }
// Send the verification result as response if err := json.NewEncoder(w).Encode(verificationResult); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) }}
func main() { http.HandleFunc("/api/example", postApiExample) fmt.Println("Server is running on http://localhost:8080") if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatalf("could not listen on port 8080 %v", err) }}The following example shows a possible implementation of TrustCaptcha in a Ruby backend.
In this example: When a POST request is sent to /api/example, the CAPTCHA verification token is sent to the Ruby backend in the request body. In the backend, our library is used to retrieve the CAPTCHA verification result from our servers and evaluate it. If the verification fails or the bot score exceeds 0.5, a warning is displayed. In addition, the entire verification result is returned to the client.
Hint: The steps and thresholds shown are examples and should be adapted to your individual requirements in your specific use case.
The complete example including source code can be found on Github.
require 'sinatra'require 'json'require 'sinatra/cross_origin'require 'trustcaptcha/captcha_manager'
set :port, 8080set :bind, '0.0.0.0'
configure do enable :cross_originend
options '*' do response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, PATCH, DELETE, OPTIONS' response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-Requested-With, Origin, Accept' 200end
post '/api/example' do content_type :json response.headers['Access-Control-Allow-Origin'] = '*' verification_token = JSON.parse(request.body.read)['verificationToken']
# Retrieving the verification result begin verification_result = CaptchaManager.get_verification_result('<your_api_or_secret_key>', verification_token) rescue StandardError => e # Fetch verification result failed - handle error puts "Failed to fetch verification result: #{e.class} - #{e.message}" status 500 return { error: 'Captcha verification failed', message: e.message }.to_json end
# Act on the verification result if !verification_result.verification_passed || verification_result.score > 0.5 puts 'Verification failed or bot score > 0.5 – possible automated request.' end
verification_result.to_jsonendThe following example shows a possible implementation of TrustCaptcha in a Rust backend.
In this example: When a POST request is sent to /api/example, the CAPTCHA verification token is sent to the Rust backend in the request body. In the backend, our library is used to retrieve the CAPTCHA verification result from our servers and evaluate it. If the verification fails or the bot score exceeds 0.5, a warning is displayed. In addition, the entire verification result is returned to the client.
Hint: The steps and thresholds shown are examples and should be adapted to your individual requirements in your specific use case.
The complete example including source code can be found on Github.
use actix_cors::Cors;use actix_web::{web, App, HttpServer, HttpResponse, Error, middleware::Logger};use serde::Deserialize;use serde_json::json;use log::{info, error};use trustcaptcha::captcha_manager::CaptchaManager;
#[derive(Deserialize, Debug)]struct VerificationRequest { #[serde(rename = "verificationToken")] verification_token: String,}
async fn post_api_example(verification_request: web::Json<VerificationRequest>) -> Result<HttpResponse, Error> { info!("Received request: {:?}", verification_request);
let verification_token = &verification_request.verification_token;
// Retrieving the verification result let verification_result = match CaptchaManager::get_verification_result("<your_api_or_secret_key>", verification_token).await { Ok(result) => result, Err(e) => { // Fetch verification result failed - handle error error!("Failed to fetch verification result: {}", e); return Ok(HttpResponse::InternalServerError().json(json!({"error": "Captcha verification failed"}))); } };
// Act on the verification result if !verification_result.verification_passed || verification_result.score > 0.5 { info!("Verification failed or bot score > 0.5 – possible automated request."); }
Ok(HttpResponse::Ok().json(verification_result))}
#[actix_web::main]async fn main() -> std::io::Result<()> { env_logger::init();
HttpServer::new(|| { let cors = Cors::default() .allow_any_origin() .allow_any_method() .allow_any_header() .max_age(3600);
App::new() .wrap(cors) .wrap(Logger::default()) .route("/api/example", web::post().to(post_api_example)) }) .bind("127.0.0.1:8080")? .run() .await}Using a proxy (optional)
Section titled “Using a proxy (optional)”If your PHP application is running behind an HTTP proxy, you can configure the TrustCaptcha PHP library to send the verification request through that proxy. The CaptchaManager::getVerificationResult() method accepts an optional third parameter $proxyOptions.
Supported proxy options:
proxyFull proxy URL, for example: http://proxy.example.com:8080 (required when using a proxy)usernameProxy username (optional, only needed if your proxy requires authentication)passwordProxy password (optional, only needed if your proxy requires authentication)
If you do not use a proxy, simply call getVerificationResult($apiKey, $verificationToken) as shown in the basic example.
Example: proxy without authentication
$apiKey = '<your_api_or_secret_key>';$verificationToken = '<verification_token_from_the_widget>';
$proxyOptions = [ 'proxy' => 'http://proxy.example.com:8080',];
try { $verificationResult = CaptchaManager::getVerificationResult( $apiKey, $verificationToken, $proxyOptions );} catch (Exception $e) { // Fetch verification result failed - handle error}Example: proxy with username/password
$apiKey = '<your_api_or_secret_key>';$verificationToken = '<verification_token_from_the_widget>';
$proxyOptions = [ 'proxy' => 'http://proxy.example.com:8080', 'username' => 'myProxyUser', 'password' => 'myProxyPassword',];
try { $verificationResult = CaptchaManager::getVerificationResult( $apiKey, $verificationToken, $proxyOptions );} catch (Exception $e) { // Fetch verification result failed - handle error}You can reuse the same evaluation logic as in the example above ($verificationResult->verificationPassed, $verificationResult->score, etc.); only the way the result is fetched changes when a proxy is used.
The Verification Token
Section titled “The Verification Token”When the CAPTCHA widget is completely solved, the CAPTCHA returns a so-called verification token. This is a simple text/string. It is available in a hidden input field called tc-verification-token and is also propagated by the trustcaptcha component with the captchaSolved JavaScript event. You can find out more about this in the CAPTCHA widget overview.
Send this token to your backend. For example, when the form containing the CAPTCHA is submitted, or independently via an API interface. With the help of the verification token, you can now retrieve the CAPTCHA verification result from our servers on the server side. Either via an API interface or with the help of one of our ready-made integrations.
Structure of the token
Section titled “Structure of the token”The verification token returned by the TrustCaptcha widget is encoded in Base64.
eyJhcGlFbmRwb2ludCI6Imh0dHBzOi8vYXBpLmNhcHRjaGEudHJ1c3RjYXB0Y2hhLmNvbSIsInZlcmlmaWNhdGlvbklkIjoiMDdiMDE5MjItM2ZhYS00NjY3LWE0YTYtOTEwYTc2Y2I4YWI3IiwiZW5jcnlwdGVkQWNjZXNzVG9rZW4iOiJtQ2JCZldTS0V5bWQxYjN0cW5ycXZCYURZMER2TkgwK29acHlYdTdSN1pkTUNMcjhhU202TURlM2ltckVPTTVDaFZOeUkvbkFSUFJCalNvV1N1NnNMNVlpUjhlUXU4dDZ3eUVBVDNRc3NwQT0ifQ0=When you decode the verification token, you get back a JSON object. This contains the verificationId you need to fetch the verification result via the REST-API.
{ "verificationId": "07b01922-3faa-4667-a4a6-910a76cb8ab7", "apiEndpoint": "https://api.trustcomponent.com", // deprecated "encryptedAccessToken": "mCbBfWSKEymd1b3t..." // deprecated}Overview of the properties of the token:
| Key | Value | Description |
|---|---|---|
verificationId | UUID | Unique identifier (ID) of the verification. |
apiEndpoint | Text | Deprecated: Please use https://api.trustcomponent.com as the API endpoint. |
encryptedAccessToken | Text | Deprecated: Encrypted access token for retrieving the verification result. |
Verification Result / API-Call
Section titled “Verification Result / API-Call”Below you will be explained how to retrieve the CAPTCHA verification result, what information it contains, and how you can work with it.
Retrieving the Result
Section titled “Retrieving the Result”You can retrieve the verification result from our servers using the following URL.
curl -X GET "https://api.trustcomponent.com/verifications/{verificationId}/assessments" \ -H "Content-Type: application/json" \ -H "tc-authorization: {api-key}"Overview of request properties:
| Parameter | Type | Description |
|---|---|---|
verificationId | Path | Unique identifier (ID) of the verification. Can be taken from the verification token. |
api-key | Header | API key of the CAPTCHA (or, for legacy customers, the deprecated secret-key). You can manage your API keys in the CAPTCHA administration. |
Processing the Result
Section titled “Processing the Result”The returned verification result looks like this:
{ "captchaId": "cc2e2d5e-d1ef-4a7f-a7bd-dec5b37df47a", "verificationId": "cc2e2d5e-d1ef-4a7f-a7bd-dec5b37df47a", "verificationPassed": true, "score": 0.5, "reason": "CALCULATED", "mode": "STANDARD", "origin": "https://www.your-website.com/sub-page", "ipAddress": "2a01:123:33bb:1a1a:0:0:0:1", "deviceFamily": "Other", "operatingSystem": "Windows 10", "browser": "Chrome 119.0.0", "creationTimestamp": "2020-01-01T13:30:05.941", "releaseTimestamp": "2020-01-01T13:30:05.941", "retrievalTimestamp": "2020-01-01T13:30:05.941"}Overview of the result properties:
| Parameter | Value | Description |
|---|---|---|
captchaId | UUID | Unique identifier (ID) of the respective CAPTCHA. |
verificationId | UUID | Unique identifier (ID) of the verification. |
verificationPassed | Boolean | Statement on whether the CAPTCHA was fundamentally passed or not. |
score | Number | Probability level that the client is a bot. |
reason | Text | Rationale for calculating verificationPassed and score. |
mode | Text | Selected captcha mode. |
origin | Text | The page where the captcha was solved. |
ipAddress | Text | IP address (IPv4 or IPv6) of the client. |
deviceFamily | Text | Name of the device family used by the client. |
operatingSystem | Text | Name and version of the operating system used by the client. |
browser | Text | Name and version of the browser used by the client. |
creationTimestamp | Timestamp (UTC) | Moment when the verification process (the CAPTCHA) was started by the client. |
releaseTimestamp | Timestamp (UTC) | Moment when the verification process (the CAPTCHA) was completed by the client. |
retrievalTimestamp | Timestamp (UTC) | Moment when the verification result was called up by the website operator. |
Evaluate CAPTCHA result
Section titled “Evaluate CAPTCHA result”The CAPTCHA verification result contains two important pieces of information: verificationPassed and score. Based on this information, you can define your individual rules and determine how to proceed.
verificationPassed: Provides information on whether the CAPTCHA has been completed and passedscore: The bot score indicates how likely a request is to originate from a bot. The value always ranges between 0 and 1, and the higher the value, the higher the bot risk.
Human or not?
Section titled “Human or not?”As a starting point for your individual CAPTCHA validation, we recommend checking whether verificationPassed is true and whether the bot score value is below 0.5.
if (!verificationResult.verificationPassed || verificationResult.score > 0.5) { console.log("Verification failed or bot score > 0.5 – possible automated request.");} else { console.log("Everything looks good - probably a human.");}Advanced check
Section titled “Advanced check”We recommend always checking expressions to see if verificationPassed is true. If you don’t want to check for bot probability but only the dynamic proof-of-work, you can skip the bot score check.
if (!verificationResult.verificationPassed) { console.log("Verification failed");} else { console.log("Verification passed.");}The score threshold of 0.5 is not suitable for everyone. Everyone has different security needs or a higher tolerance for false positives detected as bots or spam messages. So experiment with the threshold value of 0.5 and adjust it to your individual needs. Note: 0 = probably human, 1 = probably bot/automated.
const threshold = 0.75; // allow more false positivesif (!verificationResult.verificationPassed || verificationResult.score > threshold) { console.log("Verification failed or bot score > "+threshold+" – possible automated request.");} else { console.log("Everything looks good - probably a human.");}A multi-stage process is also possible. For example, you could take different approaches based on the score and thus based on individual risk. This means that a user does not have to be excluded immediately or a message blocked; instead, you could simply add an additional security check in the event of an increased risk.
if (!verificationResult.verificationPassed) { console.log("Captcha failed → reject.");} else if (verificationResult.score >= 0.8) { console.log("High bot risk → reject.");} else if (verificationResult.score >= 0.4) { console.log("Elevated risk → e.g. require email verification or 2FA.");} else { console.log("Low risk → allow / proceed.");}The Reason
Section titled “The Reason”The reason provides insight into why the bot score and the statement about verificationPassed were made accordingly.
| Reason | Passed | Score | Description |
|---|---|---|---|
ONLY_PROOF_OF_WORK | true | 0 | Verification passed without bot-score (e.g. minimal data mode). |
CALCULATED | true | Individual | The bot score was calculated based on data analysis. |
BYPASS_KEY | true | 0 | The captcha was solved using a bypass token. |
CUSTOM_ALLOW_LIST | true | 0 | The client’s IP address is on the custom allow list. |
CUSTOM_BLOCK_LIST | false | 1 | The client’s IP address is on the custom block list. |
GLOBAL_ALLOW_LIST | true | 0 | The client’s IP address is on TrustCaptcha’s global allow list. |
GLOBAL_BLOCK_LIST | false | 1 | The client’s IP address is on TrustCaptcha’s global block list. |
GEOBLOCKING | false | 1 | The client’s region is blocked on the country list. |
REQUEST_REJECTED | false | 1 | The verification attempt was rejected by TrustCaptcha. |
CHALLENGES_NOT_SOLVED_CORRECTLY | false | 1 | The client did not correctly calculate the Proof-of-Work challenges. |
CHALLENGES_NOT_SOLVED_IN_SPECIFIED_TIME | false | 1 | The client did not submit the Proof-of-Work challenges within the specified time. |
FAILOVER | true | 0.3 | There is a malfunction on our servers and the failover mechanism is active. |
FAILOVER_TOLERANCE | true | 0.3 | There was a malfunction and the aftereffects of the failover are temporarily accepted. |
Error Handling
Section titled “Error Handling”Errors can occur when retrieving the “erification result`. Below you will find an overview of all status codes along with a description of what went wrong and what you should consider.
| Status Code | Status Name | Description |
|---|---|---|
400 | Bad Request | The request was made under false assumptions. Possibly the verification ID (verificationId) is not a UUID or the access token (accessToken) does not match the specified format. |
403 | Forbidden | The API key in the header (old versions the access token as query parameter) is missing in the HTTP request or is invalid. Please check the request and access data. |
404 | Not Found | The verification does not exist. Please check the verification ID. It is also possible that the verification has already been retrieved a while ago and is now deleted. |
410 | Gone | The verification result has either already been retrieved or has expired. The CAPTCHA must be solved again. Unless otherwise specified, each verification result can be retrieved exactly once within 15 minutes after solving the CAPTCHA. |
423 | Locked | The verification result has not yet been released. Please wait until the verification is complete. |
422 | Unprocessable Content | The set captcha mode of the TrustCaptcha component does not match the set mode in the captcha settings. |
500 | Internal Server Error | An internal server error has occurred. If this happens repeatedly and persists over time, please contact support. |
Next steps
Section titled “Next steps”Once you have integrated the TrustCaptcha widget into your frontend and the CAPTCHA result validation into your backend, you can use TrustCaptcha to its full extent. However, we still recommend the following additional technical and organizational measures:
Security rules: You can find many security settings for your CAPTCHA in the CAPTCHA settings. These include, for example, authorized websites, CAPTCHA bypass for specific IP addresses, bypass keys, IP based blocking, geoblocking, individual difficulty and duration of the CAPTCHA, and much more. Learn more about the security rules.
Privacy & GDPR compliance: Include a passage in your privacy policy that refers to the use of TrustCaptcha. We also recommend that you enter into a data processing agreement with us to stay GDPR-compliant. Learn more about data protection.
Accessibility & UX: Customize TrustCaptcha to your website so that your website is as accessible as possible and offers the best possible user experience. More about accessibility.
Testing: If you use automated testing, make sure that the CAPTCHA does not block it. Learn more about testing.