CAPTCHA Result Validation (Legacy v3)
Here we explain how you call up and evaluate the CAPTCHA result in your backend from our server.
Quick start
Section titled “Quick start”If you only need the simple case, the static shortcut is the shortest path:
import { TrustCaptcha } from "@trustcomponent/trustcaptcha-nodejs";
const result = await TrustCaptcha.getVerificationResult("<your_api_key>", "<verification_token_from_the_client>");if (!result.verificationPassed || result.score > 0.5) { // possibly an automated request}For everything beyond that — custom timeouts, a proxy, a custom API host — use the configured constructor further down.
use TrustComponent\TrustCaptcha\TrustCaptcha;
$trustCaptcha = new TrustCaptcha("<your_api_key>");$result = $trustCaptcha->getVerificationResult("<verification_token_from_the_client>");if (!$result->verificationPassed || $result->score > 0.5) { // possibly an automated request}For custom timeouts, a proxy, or a custom API host see configured usage below.
from trustcaptcha.trust_captcha import TrustCaptcha
trust_captcha = TrustCaptcha("<your_api_key>")result = trust_captcha.get_verification_result("<verification_token_from_the_client>")if not result.verification_passed or result.score > 0.5: # possibly an automated request passFor custom timeouts, a proxy, or a custom API host see configured usage below.
If you only need the simple case, the static shortcut is the shortest path:
import com.trustcomponent.trustcaptcha.TrustCaptcha;import com.trustcomponent.trustcaptcha.model.VerificationResult;
VerificationResult result = TrustCaptcha.getVerificationResult("<your_api_key>", "<verification_token_from_the_client>");if (!result.isVerificationPassed() || result.getScore() > 0.5) { // possibly an automated request}For everything beyond that — custom timeouts, a proxy, a custom API host — use the builder further down.
using TrustComponent.TrustCaptcha;using TrustComponent.TrustCaptcha.Model;
VerificationResult result = await TrustCaptcha.GetVerificationResultAsync("<your_api_key>", "<verification_token_from_the_client>");if (!result.VerificationPassed || result.Score > 0.5){ // possibly an automated request}For custom timeouts, a proxy, or a custom API host see configured usage below.
If you only need the simple case, the package-level shortcut is the shortest path:
import "github.com/trustcomponent/trustcaptcha-go/v3"
result, err := trustcaptcha.GetVerificationResult("<your_api_key>", "<verification_token_from_the_client>")if err != nil { /* handle error */ }if !result.VerificationPassed || result.Score > 0.5 { // possibly an automated request}For everything beyond that — custom timeouts, a proxy, a custom API host — use the configured constructor further down.
require 'trustcaptcha/trust_captcha'
trust_captcha = TrustCaptcha.new('<your_api_key>')result = trust_captcha.get_verification_result('<verification_token_from_the_client>')if !result.verification_passed || result.score > 0.5 # possibly an automated requestendFor custom timeouts, a proxy, or a custom API host see configured usage below.
use trustcaptcha::trust_captcha::TrustCaptcha;
let trust_captcha = TrustCaptcha::builder("<your_api_key>").build()?;let result = trust_captcha.get_verification_result("<verification_token_from_the_client>").await?;if !result.verification_passed || result.score > 0.5 { // possibly an automated request}For custom timeouts, a proxy, or a custom API host see configured usage below.
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.
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-nodejs@^3.0.0You 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-php:^3.0You 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 "trustcaptcha>=3.0.0,<4.0.0"You 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>3.0.0</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 3.0.0You 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/v3@v3.0.0You 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 trustcaptcha -v '~> 3.0'You 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 trustcaptcha@^3.0You 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.
Use the TrustCaptcha class of our Node.js integration to retrieve the verification result from our servers. For the simple case use the static shortcut shown right below; for advanced configuration (custom API host, timeouts, proxy) use the builder/constructor variant further down on this page.
// Retrieving the verification resultlet verificationResult;try { verificationResult = await TrustCaptcha.getVerificationResult("<your_api_key>", "<verification_token_from_the_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.
Use the TrustCaptcha class of our PHP integration to retrieve the verification result from our servers. For the simple case use the static shortcut shown right below; for advanced configuration (custom API host, timeouts, proxy) use the builder/constructor variant further down on this page.
// Retrieving the verification result$verificationResult = null;try { $trustCaptcha = new TrustCaptcha("<your_api_key>"); $verificationResult = $trustCaptcha->getVerificationResult($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.
Use the TrustCaptcha class of our Python integration to retrieve the verification result from our servers. For the simple case use the static shortcut shown right below; for advanced configuration (custom API host, timeouts, proxy) use the builder/constructor variant further down on this page.
# Retrieving the verification resulttry: trust_captcha = TrustCaptcha("<your_api_key>") verification_result = trust_captcha.get_verification_result("<verification_token_from_the_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.
Use the TrustCaptcha class of our JVM integration to retrieve the verification result from our servers. For the simple case use the static shortcut shown right below; for advanced configuration (custom API host, timeouts, proxy) use the builder/constructor variant further down on this page.
// Retrieving the verification resultVerificationResult verificationResult;try { verificationResult = TrustCaptcha.getVerificationResult("<your_api_key>", "<verification_token_from_the_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.
Use the TrustCaptcha class of our DotNet integration to retrieve the verification result from our servers. For the simple case use the static shortcut shown right below; for advanced configuration (custom API host, timeouts, proxy) use the builder/constructor variant further down on this page.
// Retrieving the verification resultVerificationResult verificationResult;try{ verificationResult = await TrustCaptcha.GetVerificationResultAsync("<your_api_key>", "<verification_token_from_the_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.
Use the TrustCaptcha class of our Go integration to retrieve the verification result from our servers. For the simple case use the static shortcut shown right below; for advanced configuration (custom API host, timeouts, proxy) use the builder/constructor variant further down on this page.
// Retrieving the verification resultverificationResult, err := trustcaptcha.GetVerificationResult("<your_api_key>", "<verification_token_from_the_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.
Use the TrustCaptcha class of our Ruby integration to retrieve the verification result from our servers. For the simple case use the static shortcut shown right below; for advanced configuration (custom API host, timeouts, proxy) use the builder/constructor variant further down on this page.
# Retrieving the verification resultbegin trust_captcha = TrustCaptcha.new('<your_api_key>') verification_result = trust_captcha.get_verification_result(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.
Use the TrustCaptcha class of our Rust integration to retrieve the verification result from our servers. For the simple case use the static shortcut shown right below; for advanced configuration (custom API host, timeouts, proxy) use the builder/constructor variant further down on this page.
// Retrieving the verification resultlet trust_captcha = TrustCaptcha::builder("<your_api_key>").build()?;let verification_result = match trust_captcha.get_verification_result("<verification_token_from_the_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 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 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 result validation overview.
# Act on the verification resultif verification_result.verification_passed 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 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 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 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 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 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.");}Configured usage
Section titled “Configured usage”If you need more control — a different API host, custom timeouts, or a proxy — instantiate TrustCaptcha directly with an options object. The static shortcut always uses the defaults.
import { TrustCaptcha } from "@trustcomponent/trustcaptcha-nodejs";
const trustCaptcha = new TrustCaptcha({ apiKey: "<your_api_key>", apiHost: "https://api.trustcomponent.com", connectTimeoutMs: 3000, readTimeoutMs: 5000, proxy: { host: "proxy.example.com", port: 8080, auth: { username: "myProxyUser", password: "myProxyPassword" }, // optional },});
const result = await trustCaptcha.getVerificationResult("<verification_token_from_the_client>");A constructed TrustCaptcha instance is immutable and safe to share: build it once at application startup and reuse it for all requests.
If you need more control — a different API host, custom timeouts, or a proxy — pass an options array to the constructor.
use TrustComponent\TrustCaptcha\TrustCaptcha;
$trustCaptcha = new TrustCaptcha("<your_api_key>", [ "apiHost" => "https://api.trustcomponent.com", "connectTimeoutMs" => 3000, "readTimeoutMs" => 5000, "proxy" => [ "proxy" => "http://proxy.example.com:8080", "username" => "myProxyUser", // optional "password" => "myProxyPassword", // optional ],]);
$result = $trustCaptcha->getVerificationResult("<verification_token_from_the_client>");A constructed TrustCaptcha instance is immutable and safe to share: build it once and reuse it for all requests.
If you need more control — a different API host, custom timeouts, or a proxy — pass keyword arguments to the constructor.
from trustcaptcha.trust_captcha import TrustCaptcha
trust_captcha = TrustCaptcha( "<your_api_key>", api_host="https://api.trustcomponent.com", connect_timeout_s=3.0, read_timeout_s=5.0, proxy="http://proxy.example.com:8080",)
result = trust_captcha.get_verification_result("<verification_token_from_the_client>")A constructed TrustCaptcha instance is immutable and safe to share: build it once at startup and reuse it for all requests.
If you need more control — a different API host, custom timeouts, or a proxy — use the builder. The builder is the only way to configure these options; the static shortcut always uses the defaults.
import com.trustcomponent.trustcaptcha.TrustCaptcha;import java.net.InetSocketAddress;import java.net.Proxy;
TrustCaptcha trustCaptcha = TrustCaptcha.builder("<your_api_key>") .apiHost("https://api.trustcomponent.com") .connectTimeoutMs(3000) .readTimeoutMs(5000) .proxy("proxy.example.com", 8080) .build();
VerificationResult result = trustCaptcha.getVerificationResult("<verification_token_from_the_client>");A built TrustCaptcha instance is immutable and thread-safe: build it once at application startup and reuse it for as many requests as you like.
If you need more control — a different API host, custom timeouts, or a proxy — use the builder.
using System.Net;using TrustComponent.TrustCaptcha;using TrustComponent.TrustCaptcha.Model;
var trustCaptcha = TrustCaptcha.NewBuilder("<your_api_key>") .WithApiHost("https://api.trustcomponent.com") .WithConnectTimeoutMs(3000) .WithReadTimeoutMs(5000) .WithProxy("http://proxy.example.com:8080") .Build();
VerificationResult result = await trustCaptcha.GetVerificationResultAsync("<verification_token_from_the_client>");A built TrustCaptcha instance is immutable and thread-safe: build it once (e.g. as a singleton via DI) and reuse it for as many requests as you like.
If you need more control — a different API host, custom timeouts, or a proxy — construct a TrustCaptcha instance using New() with functional options. The package-level shortcut always uses the defaults.
import ( "time" "github.com/trustcomponent/trustcaptcha-go/v3")
trustCaptcha, err := trustcaptcha.New( "<your_api_key>", trustcaptcha.WithApiHost("https://api.trustcomponent.com"), trustcaptcha.WithConnectTimeout(3 * time.Second), trustcaptcha.WithReadTimeout(5 * time.Second), trustcaptcha.WithProxy("http://proxy.example.com:8080"),)if err != nil { /* handle error */ }
result, err := trustCaptcha.GetVerificationResult("<verification_token_from_the_client>")A constructed *TrustCaptcha is immutable and safe for concurrent use: build it once at startup and share it across goroutines.
If you need more control — a different API host, custom timeouts, or a proxy — pass keyword arguments to the constructor.
require 'trustcaptcha/trust_captcha'
trust_captcha = TrustCaptcha.new( '<your_api_key>', api_host: 'https://api.trustcomponent.com', connect_timeout_s: 3, read_timeout_s: 5, proxy: 'http://myProxyUser:myProxyPassword@proxy.example.com:8080',)
result = trust_captcha.get_verification_result('<verification_token_from_the_client>')A constructed TrustCaptcha instance is immutable and safe to share: build it once at startup and reuse it for all requests.
If you need more control — a different API host, custom timeouts, or a proxy — use the builder.
use std::time::Duration;use trustcaptcha::trust_captcha::TrustCaptcha;
let trust_captcha = TrustCaptcha::builder("<your_api_key>") .api_host("https://api.trustcomponent.com") .connect_timeout(Duration::from_secs(3)) .read_timeout(Duration::from_secs(5)) .proxy("http://proxy.example.com:8080") .build()?;
let result = trust_captcha.get_verification_result("<verification_token_from_the_client>").await?;A built TrustCaptcha is immutable and safe to share: build it once and reuse it across all requests.
Options
Section titled “Options”| Field | Type | Default | Description |
|---|---|---|---|
apiKey | string (required) | — | Your API key. Must not be empty. |
apiHost | string | https://api.trustcomponent.com | Override the API host. Useful for staging environments. |
connectTimeoutMs | number | 3000 | Connect timeout in milliseconds. (Used as part of axios’ timeout.) |
readTimeoutMs | number | 5000 | Total request timeout in milliseconds. |
proxy | AxiosProxyConfig | false | none | An axios proxy configuration object, or false to disable proxies. |
| Key | Type | Default | Description |
|---|---|---|---|
| 1st argument | string (required) | — | Your API key. Must not be empty. |
apiHost | string | https://api.trustcomponent.com | Override the API host. Useful for staging environments. |
connectTimeoutMs | int | 3000 | Connect timeout in milliseconds. |
readTimeoutMs | int | 5000 | Total request timeout in milliseconds. |
proxy | array{proxy: string, username?: string, password?: string} | none | HTTP proxy configuration. username and password are only required if your proxy needs authentication. |
| Argument | Type | Default | Description |
|---|---|---|---|
| 1st positional | str (required) | — | Your API key. Must not be empty. |
api_host | str | https://api.trustcomponent.com | Override the API host. Useful for staging environments. |
connect_timeout_s | float | 3.0 | Connect timeout in seconds. |
read_timeout_s | float | 5.0 | Read timeout in seconds. |
proxy | str | dict[str, str] | none | Either a single URL string (used for both http and https), or a dict like {"http": "...", "https": "..."}. |
| Method | Type | Default | Description |
|---|---|---|---|
builder(apiKey) | String (required) | — | Your API key. Must not be null or empty. |
.apiHost(...) | String | https://api.trustcomponent.com | Override the API host. Useful for staging environments. |
.connectTimeoutMs(...) | int | 3000 | Connect timeout in milliseconds. |
.readTimeoutMs(...) | int | 5000 | Read timeout in milliseconds. |
.proxy(host, port) | String, int | none | Convenience overload — configures an HTTP proxy at host:port. |
.proxy(java.net.Proxy) | java.net.Proxy | none | Pass a fully built java.net.Proxy instance for advanced setups. |
.build() | — | — | Returns the configured TrustCaptcha instance. |
| Method | Type | Default | Description |
|---|---|---|---|
NewBuilder(apiKey) | string (required) | — | Your API key. Must not be null or empty. |
.WithApiHost(...) | string | https://api.trustcomponent.com | Override the API host. Useful for staging environments. |
.WithConnectTimeoutMs(...) | int | 3000 | Connect timeout in milliseconds. |
.WithReadTimeoutMs(...) | int | 5000 | Read timeout in milliseconds. |
.WithProxy(string proxyUrl) | string | none | Convenience overload — configures an HTTP proxy from a URL string. |
.WithProxy(IWebProxy) | System.Net.IWebProxy | none | Pass a fully configured IWebProxy instance (e.g. WebProxy with credentials). |
.Build() | — | — | Returns the configured TrustCaptcha instance. |
| Option | Type | Default | Description |
|---|---|---|---|
1st argument of New(...) | string (required) | — | Your API key. Must not be empty. |
WithApiHost(host) | string | https://api.trustcomponent.com | Override the API host. Useful for staging environments. |
WithConnectTimeout(d) | time.Duration | 3 * time.Second | Connect timeout. |
WithReadTimeout(d) | time.Duration | 5 * time.Second | Read timeout (response header timeout). |
WithProxy(url) | string | http.ProxyFromEnvironment | Override the HTTP proxy URL. If unset, the default Go behaviour (HTTP_PROXY/HTTPS_PROXY env variables) is used. |
| Argument | Type | Default | Description |
|---|---|---|---|
| 1st positional | String (required) | — | Your API key. Must not be empty. |
api_host: | String | https://api.trustcomponent.com | Override the API host. Useful for staging environments. |
connect_timeout_s: | Integer | 3 | Connect timeout in seconds. |
read_timeout_s: | Integer | 5 | Read timeout in seconds. |
proxy: | String or nil | nil | A proxy URI string, optionally with credentials, e.g. http://user:pass@host:port. |
| Method | Type | Default | Description |
|---|---|---|---|
TrustCaptcha::builder(api_key) | &str (required) | — | Your API key. Must not be empty. |
.api_host(host) | &str | https://api.trustcomponent.com | Override the API host. Useful for staging environments. |
.connect_timeout(d) | Duration | 3s | Connect timeout. |
.read_timeout(d) | Duration | 5s | Read timeout (total request timeout). |
.proxy(url) | &str | none | HTTP proxy URL. |
.build() | — | — | Returns the configured TrustCaptcha instance. |
Failover
Section titled “Failover”Our service runs in a high-availability setup, so outages are rare in practice. If you want maximum availability — even for the unlikely case where our service is unreachable — you can decide upfront how your backend should react, so your forms and processes don’t block during such an event. Read the Failover behavior page first — it covers the concept, the required widget-side opt-in, the operational checklist, and how to filter failover-derived results in high-security flows.
Once you’ve decided on a policy, the library throws two typed exceptions that both extend FailoverException:
ServerUnreachableException— high-trust (your backend cannot reach our servers). For example: allow the request and log the incident.ClientReportedServerUnreachableException(HTTP412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
try { const result = await trustCaptcha.getVerificationResult(token); // Handle the result as you normally would (verificationPassed, score, your own policy).} catch (e) { if (e instanceof ServerUnreachableException) { // Example: our servers are unreachable. Allow + log. } else if (e instanceof ClientReportedServerUnreachableException) { // Example: widget claimed an outage but the backend reaches us. Reject or soft-challenge. } else { // Other error. }}Our service runs in a high-availability setup, so outages are rare in practice. If you want maximum availability — even for the unlikely case where our service is unreachable — you can decide upfront how your backend should react, so your forms and processes don’t block during such an event. Read the Failover behavior page first — it covers the concept, the required widget-side opt-in, the operational checklist, and how to filter failover-derived results in high-security flows.
Once you’ve decided on a policy, the library throws two typed exceptions that both extend FailoverException:
ServerUnreachableException— high-trust (your backend cannot reach our servers). For example: allow the request and log the incident.ClientReportedServerUnreachableException(HTTP412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
try { $result = $trustCaptcha->getVerificationResult($token); // Handle the result as you normally would (verificationPassed, score, your own policy).} catch (ServerUnreachableException $e) { // Example: our servers are unreachable. Allow + log.} catch (ClientReportedServerUnreachableException $e) { // Example: widget claimed an outage but the backend reaches us. Reject or soft-challenge.}Our service runs in a high-availability setup, so outages are rare in practice. If you want maximum availability — even for the unlikely case where our service is unreachable — you can decide upfront how your backend should react, so your forms and processes don’t block during such an event. Read the Failover behavior page first — it covers the concept, the required widget-side opt-in, the operational checklist, and how to filter failover-derived results in high-security flows.
Once you’ve decided on a policy, the library raises two typed exceptions that both extend FailoverException:
ServerUnreachableException— high-trust (your backend cannot reach our servers). For example: allow the request and log the incident.ClientReportedServerUnreachableException(HTTP412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
try: result = trust_captcha.get_verification_result(token) # Handle the result as you normally would (verification_passed, score, your own policy).except ServerUnreachableException: ... # Example: our servers are unreachable. Allow + log.except ClientReportedServerUnreachableException: ... # Example: widget claimed an outage but the backend reaches us. Reject or soft-challenge.Our service runs in a high-availability setup, so outages are rare in practice. If you want maximum availability — even for the unlikely case where our service is unreachable — you can decide upfront how your backend should react, so your forms and processes don’t block during such an event. Read the Failover behavior page first — it covers the concept, the required widget-side opt-in, the operational checklist, and how to filter failover-derived results in high-security flows.
Once you’ve decided on a policy, the library surfaces the two relevant cases as typed exceptions, both extending FailoverException:
ServerUnreachableException— high-trust (your backend cannot reach our servers). For example: allow the request and log the incident.ClientReportedServerUnreachableException(HTTP412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
try { VerificationResult result = trustCaptcha.getVerificationResult(token); // Handle the result as you normally would (isVerificationPassed(), getScore(), your own policy).} catch (ServerUnreachableException e) { // Example: our servers are unreachable. Allow + log.} catch (ClientReportedServerUnreachableException e) { // Example: widget claimed an outage but the backend reaches us. Reject or soft-challenge.}Our service runs in a high-availability setup, so outages are rare in practice. If you want maximum availability — even for the unlikely case where our service is unreachable — you can decide upfront how your backend should react, so your forms and processes don’t block during such an event. Read the Failover behavior page first — it covers the concept, the required widget-side opt-in, the operational checklist, and how to filter failover-derived results in high-security flows.
Once you’ve decided on a policy, the library surfaces the two relevant cases as typed exceptions, both extending FailoverException:
ServerUnreachableException— high-trust (your backend cannot reach our servers). For example: allow the request and log the incident.ClientReportedServerUnreachableException(HTTP412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
try{ var result = await trustCaptcha.GetVerificationResultAsync(token); // Handle the result as you normally would (VerificationPassed, Score, your own policy).}catch (ServerUnreachableException){ // Example: our servers are unreachable. Allow + log.}catch (ClientReportedServerUnreachableException){ // Example: widget claimed an outage but the backend reaches us. Reject or soft-challenge.}Our service runs in a high-availability setup, so outages are rare in practice. If you want maximum availability — even for the unlikely case where our service is unreachable — you can decide upfront how your backend should react, so your forms and processes don’t block during such an event. Read the Failover behavior page first — it covers the concept, the required widget-side opt-in, the operational checklist, and how to filter failover-derived results in high-security flows.
Once you’ve decided on a policy, the library returns two typed errors that both implement the FailoverError marker:
*ServerUnreachableError— high-trust (your backend cannot reach our servers). For example: allow the request and log the incident.*ClientReportedServerUnreachableError(HTTP412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
result, err := trustCaptcha.GetVerificationResult(token)
var serverUnreachable *trustcaptcha.ServerUnreachableErrorvar clientReported *trustcaptcha.ClientReportedServerUnreachableError
switch {case errors.As(err, &serverUnreachable): // Example: our servers are unreachable. Allow + log.case errors.As(err, &clientReported): // Example: widget claimed an outage but the backend reaches us. Reject or soft-challenge.case err != nil: // Other error.default: // Handle the result as you normally would (VerificationPassed, Score, your own policy).}Our service runs in a high-availability setup, so outages are rare in practice. If you want maximum availability — even for the unlikely case where our service is unreachable — you can decide upfront how your backend should react, so your forms and processes don’t block during such an event. Read the Failover behavior page first — it covers the concept, the required widget-side opt-in, the operational checklist, and how to filter failover-derived results in high-security flows.
Once you’ve decided on a policy, the library raises two typed exceptions that both extend TrustCaptcha::FailoverException:
TrustCaptcha::ServerUnreachableException— high-trust (your backend cannot reach our servers). For example: allow the request and log the incident.TrustCaptcha::ClientReportedServerUnreachableException(HTTP412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
begin result = trust_captcha.get_verification_result(token) # Handle the result as you normally would (verification_passed, score, your own policy).rescue TrustCaptcha::ServerUnreachableException => e # Example: our servers are unreachable. Allow + log.rescue TrustCaptcha::ClientReportedServerUnreachableException => e # Example: widget claimed an outage but the backend reaches us. Reject or soft-challenge.endOur service runs in a high-availability setup, so outages are rare in practice. If you want maximum availability — even for the unlikely case where our service is unreachable — you can decide upfront how your backend should react, so your forms and processes don’t block during such an event. Read the Failover behavior page first — it covers the concept, the required widget-side opt-in, the operational checklist, and how to filter failover-derived results in high-security flows.
Once you’ve decided on a policy, the library returns two typed errors:
ServerUnreachableError— high-trust (your backend cannot reach our servers). For example: allow the request and log the incident.ClientReportedServerUnreachableError(HTTP412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
match trust_captcha.get_verification_result(token).await { Ok(result) => { // Handle the result as you normally would (verification_passed, score, your own policy). } Err(e) if e.is::<ServerUnreachableError>() => { // Example: our servers are unreachable. Allow + log. } Err(e) if e.is::<ClientReportedServerUnreachableError>() => { // Example: widget claimed an outage but the backend reaches us. Reject or soft-challenge. } Err(_) => { // Other error. }}Exceptions and errors
Section titled “Exceptions and errors”When the result cannot be retrieved successfully the library raises a typed exception.
| Exception | When it is thrown |
|---|---|
ApiKeyInvalidException | The API key was rejected (HTTP 403). |
VerificationTokenInvalidException | The verification token could not be parsed (malformed base64 / missing verificationId). |
VerificationNotFoundException | No verification was found for the given verification token (HTTP 404). |
VerificationNotFinishedException | The verification has not yet been completed by the user (HTTP 423). |
VerificationResultExpiredException | The result has expired and can no longer be retrieved (HTTP 410). |
VerificationResultRetrievalLimitReachedException | The result has reached its maximum retrieval count (HTTP 429). |
ServerUnreachableException | The TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of FailoverException. See Failover behavior. |
ClientReportedServerUnreachableException | The widget claimed a failover, but the gateway has no record of a recent outage (HTTP 412). Subclass of FailoverException. See Failover behavior. |
When the result cannot be retrieved successfully the library raises a typed exception.
| Exception | When it is thrown |
|---|---|
ApiKeyInvalidException | The API key was rejected (HTTP 403). |
VerificationTokenInvalidException | The verification token could not be parsed (malformed base64 / missing verificationId). |
VerificationNotFoundException | No verification was found for the given verification token (HTTP 404). |
VerificationNotFinishedException | The verification has not yet been completed by the user (HTTP 423). |
VerificationResultExpiredException | The result has expired and can no longer be retrieved (HTTP 410). |
VerificationResultRetrievalLimitReachedException | The result has reached its maximum retrieval count (HTTP 429). |
ServerUnreachableException | The TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of FailoverException. See Failover behavior. |
ClientReportedServerUnreachableException | The widget claimed a failover, but the gateway has no record of a recent outage (HTTP 412). Subclass of FailoverException. See Failover behavior. |
When the result cannot be retrieved successfully the library raises a typed exception.
| Exception | When it is raised |
|---|---|
ApiKeyInvalidException | The API key was rejected (HTTP 403). |
VerificationTokenInvalidException | The verification token could not be parsed (malformed base64 / missing verificationId). |
VerificationNotFoundException | No verification was found for the given verification token (HTTP 404). |
VerificationNotFinishedException | The verification has not yet been completed by the user (HTTP 423). |
VerificationResultExpiredException | The result has expired and can no longer be retrieved (HTTP 410). |
VerificationResultRetrievalLimitReachedException | The result has reached its maximum retrieval count (HTTP 429). |
ServerUnreachableException | The TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of FailoverException. See Failover behavior. |
ClientReportedServerUnreachableException | The widget claimed a failover, but the gateway has no record of a recent outage (HTTP 412). Subclass of FailoverException. See Failover behavior. |
When the result cannot be retrieved successfully the library raises a typed exception. All exceptions extend CaptchaFailureException so they can be caught with a single catch clause.
| Exception | When it is thrown |
|---|---|
ApiKeyInvalidException | The API key was rejected (HTTP 403). |
VerificationTokenInvalidException | The verification token could not be parsed (malformed base64 / missing verificationId). |
VerificationNotFoundException | No verification was found for the given verification token (HTTP 404). |
VerificationNotFinishedException | The verification has not yet been completed by the user (HTTP 423). |
VerificationResultExpiredException | The result has expired and can no longer be retrieved (HTTP 410). |
VerificationResultRetrievalLimitReachedException | The result has reached its maximum retrieval count (HTTP 429). |
ServerUnreachableException | The TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of FailoverException. See Failover behavior. |
ClientReportedServerUnreachableException | The widget claimed a failover, but the gateway has no record of a recent outage (HTTP 412). Subclass of FailoverException. See Failover behavior. |
When the result cannot be retrieved successfully the library raises a typed exception.
| Exception | When it is thrown |
|---|---|
ApiKeyInvalidException | The API key was rejected (HTTP 403). |
VerificationTokenInvalidException | The verification token could not be parsed (malformed base64 / missing verificationId). |
VerificationNotFoundException | No verification was found for the given verification token (HTTP 404). |
VerificationNotFinishedException | The verification has not yet been completed by the user (HTTP 423). |
VerificationResultExpiredException | The result has expired and can no longer be retrieved (HTTP 410). |
VerificationResultRetrievalLimitReachedException | The result has reached its maximum retrieval count (HTTP 429). |
ServerUnreachableException | The TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of FailoverException. See Failover behavior. |
ClientReportedServerUnreachableException | The widget claimed a failover, but the gateway has no record of a recent outage (HTTP 412). Subclass of FailoverException. See Failover behavior. |
When the result cannot be retrieved successfully the library returns a typed error. Use errors.As to discriminate between them.
| Error type | When it is returned |
|---|---|
*ApiKeyInvalidError | The API key was rejected (HTTP 403). |
*VerificationTokenInvalidError | The verification token could not be parsed (malformed base64 / missing verificationId). |
*VerificationNotFoundError | No verification was found for the given verification token (HTTP 404). |
*VerificationNotFinishedError | The verification has not yet been completed by the user (HTTP 423). |
*VerificationResultExpiredError | The result has expired and can no longer be retrieved (HTTP 410). |
*VerificationResultRetrievalLimitReachedError | The result has reached its maximum retrieval count (HTTP 429). |
*ServerUnreachableError | The TrustCaptcha server could not be reached at all (connection error / timeout). Implements the FailoverError marker. See Failover behavior. |
*ClientReportedServerUnreachableError | The widget claimed a failover, but the gateway has no record of a recent outage (HTTP 412). Implements the FailoverError marker. See Failover behavior. |
When the result cannot be retrieved successfully the library raises a typed exception.
| Exception | When it is raised |
|---|---|
TrustCaptcha::ApiKeyInvalidException | The API key was rejected (HTTP 403). |
TrustCaptcha::VerificationTokenInvalidException | The verification token could not be parsed (malformed base64 / missing verificationId). |
TrustCaptcha::VerificationNotFoundException | No verification was found for the given verification token (HTTP 404). |
TrustCaptcha::VerificationNotFinishedException | The verification has not yet been completed by the user (HTTP 423). |
TrustCaptcha::VerificationResultExpiredException | The result has expired and can no longer be retrieved (HTTP 410). |
TrustCaptcha::VerificationResultRetrievalLimitReachedException | The result has reached its maximum retrieval count (HTTP 429). |
TrustCaptcha::ServerUnreachableException | The TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of TrustCaptcha::FailoverException. See Failover behavior. |
TrustCaptcha::ClientReportedServerUnreachableException | The widget claimed a failover, but the gateway has no record of a recent outage (HTTP 412). Subclass of TrustCaptcha::FailoverException. See Failover behavior. |
When the result cannot be retrieved successfully the library returns a boxed error. Downcast (downcast_ref::<...>()) to discriminate between them.
| Error type | When it is returned |
|---|---|
ApiKeyInvalidError | The API key was rejected (HTTP 403). |
VerificationTokenInvalidError | The verification token could not be parsed (malformed base64 / missing verificationId). |
VerificationNotFoundError | No verification was found for the given verification token (HTTP 404). |
VerificationNotFinishedError | The verification has not yet been completed by the user (HTTP 423). |
VerificationResultExpiredError | The result has expired and can no longer be retrieved (HTTP 410). |
VerificationResultRetrievalLimitReachedError | The result has reached its maximum retrieval count (HTTP 429). |
ServerUnreachableError | The TrustCaptcha server could not be reached at all (connection error / timeout). See Failover behavior. |
ClientReportedServerUnreachableError | The widget claimed a failover, but the gateway has no record of a recent outage (HTTP 412). See Failover behavior. |
UnknownError | Any other unexpected HTTP status code. |
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 { TrustCaptcha } 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 TrustCaptcha.getVerificationResult("<your_api_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\TrustCaptcha;
$message = "";$verificationResult = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') { $message = $_POST['message'] ?? ''; $verificationToken = $_POST['tc-verification-token'] ?? '';
// Retrieving the verification result try { $trustCaptcha = new TrustCaptcha("<your_api_key>"); $verificationResult = $trustCaptcha->getVerificationResult($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 type="module" src="https://cdn.trustcomponent.com/trustcaptcha/3.0.x/trustcaptcha.esm.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>Score: </strong><?= htmlspecialchars($verificationResult->score) ?> </div> <?php endif; ?> </div> </div> </body>
<script> 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.trust_captcha import TrustCaptcha
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: trust_captcha = TrustCaptcha("<your_api_key>") verification_result = trust_captcha.get_verification_result(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.verification_passed 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.TrustCaptcha;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 = TrustCaptcha.getVerificationResult("<your_api_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 TrustCaptcha.GetVerificationResultAsync("<your_api_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/v3" "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_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/trust_captcha'
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 trust_captcha = TrustCaptcha.new('<your_api_key>') verification_result = trust_captcha.get_verification_result(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::trust_captcha::TrustCaptcha;
#[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 trust_captcha = TrustCaptcha::builder("<your_api_key>").build() .map_err(|e| { error!("Builder failed: {}", e); actix_web::error::ErrorInternalServerError("captcha init failed") })?; let verification_result = match trust_captcha.get_verification_result(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}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.
eyJ2ZXJpZmljYXRpb25JZCI6IjA3YjAxOTIyLTNmYWEtNDY2Ny1hNGE2LTkxMGE3NmNiOGFiNyIsImV4cGlyZXNBdCI6IjIwMjYtMDUtMDNUMTM6NDU6MDguMjE0WiJ9When 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, plus an expiresAt timestamp telling you when the token (and therefore the result) will no longer be retrievable.
{ "verificationId": "07b01922-3faa-4667-a4a6-910a76cb8ab7", "expiresAt": "2026-05-03T13:45:08.214Z"}Overview of the properties of the token:
| Key | Value | Description |
|---|---|---|
verificationId | UUID | Unique identifier (ID) of the verification. |
expiresAt | Timestamp (UTC) | When the token (and therefore the verification result) will expire and can no longer be retrieved. |
clientFailover | Boolean | Optional. Present and set to true when the widget could not reach our servers and issued a self-built failover token. See the Failover behavior page for handling. |
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/v2/verifications/{verificationId}/results" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer {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, sent as Authorization: Bearer <apiKey>. 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": "07b01922-3faa-4667-a4a6-910a76cb8ab7", "verificationPassed": true, "score": 0.3, "decisionType": "STANDARD", "decisionAction": "ALLOW", "gatewayFailoverActive": false, "riskScoringEnabled": true, "minimalDataModeEnabled": false, "origin": "https://www.your-website.com/sub-page", "ipAddress": "2a01:123:33bb:1a1a:0:0:0:1", "countryCode": "DE", "deviceFamily": "Other", "operatingSystem": "Windows 10", "browser": "Chrome 119.0.0", "verificationStartedAt": "2026-05-03T13:30:05.941Z", "verificationFinishedAt": "2026-05-03T13:30:08.214Z", "resultExpiresAt": "2026-05-03T13:45:08.214Z", "resultFirstFetchedAt": "2026-05-03T13:30:09.001Z", "resultLastFetchedAt": "2026-05-03T13:30:09.001Z"}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 | Whether the CAPTCHA was passed (the request can be allowed) or not. |
score | Number | Bot probability score between 0 (likely human) and 1 (likely bot). |
decisionType | Text | How the verification outcome was determined. See the Decision section below. |
decisionAction | Text | The recommended action for this verification. See the Decision section below. |
gatewayFailoverActive | Boolean | true when the gateway synthesized this result during a captcha-service outage. See Failover behavior. |
riskScoringEnabled | Boolean | Whether risk scoring was enabled for the captcha environment that issued this verification. |
minimalDataModeEnabled | Boolean | Whether the captcha environment runs in minimal-data mode. |
origin | Text | The page where the captcha was solved. |
ipAddress | Text | IP address (IPv4 or IPv6) of the client. |
countryCode | Text | Two-letter ISO 3166-1 alpha-2 country code derived from the client IP. Empty string if not resolvable. |
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. |
verificationStartedAt | Timestamp (UTC) | When the verification process (the CAPTCHA) was started by the client. |
verificationFinishedAt | Timestamp (UTC) | When the verification process (the CAPTCHA) was completed by the client. |
resultExpiresAt | Timestamp (UTC) | When the result will expire and can no longer be retrieved. |
resultFirstFetchedAt | Timestamp (UTC) | When the result was first fetched. Equal to resultLastFetchedAt on the first fetch. |
resultLastFetchedAt | Timestamp (UTC) | When the result was most recently fetched (i.e. on this very call). |
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 Decision
Section titled “The Decision”In addition to verificationPassed and score, every result carries two fields that explain how the outcome was reached: decisionType describes which mechanism made the call, decisionAction describes what TrustCaptcha would recommend doing with the request.
decisionType — known values:
| Value | Description |
|---|---|
STANDARD | Outcome was calculated by the regular CAPTCHA validation logic (proof-of-work + risk score). |
BYPASS_KEY | The CAPTCHA was solved using a configured bypass key. |
CUSTOM_ACCESS_RULE | A custom access rule (e.g. allow- or block-list) configured for this CAPTCHA matched. |
GLOBAL_IP_ACCESS_RULE | A global TrustCaptcha access rule (e.g. global allow- or block-list) matched. |
FAILOVER | The upstream CAPTCHA service was temporarily unreachable; the gateway returned a tolerant fallback result. |
FAILOVER_TOLERANCE | The upstream returned a soft error (e.g. not yet released / not found) shortly after a recent outage; the gateway still serves a tolerant result within a short grace window. |
decisionAction — known values:
| Value | Description |
|---|---|
ALLOW | The request should be allowed. |
BLOCK | The request should be blocked. |
CUSTOM | A custom rule with a custom action was applied. Inspect your CAPTCHA settings for context. |
Error Handling
Section titled “Error Handling”Errors can occur when retrieving the verification result. Below you will find an overview of the relevant status codes along with a description of what went wrong and what you should consider.
| Status Code | Status Name | Description |
|---|---|---|
403 | Forbidden | The Authorization header is missing/malformed, or the API key is invalid. Please check the request and your API key. |
404 | Not Found | The verification does not exist for the given verificationId. Please check the verification ID. |
410 | Gone | The verification result has expired and can no longer be retrieved. |
412 | Precondition Failed | A client-claimed failover (?clientFailover=true) was rejected because our gateway has no record of a recent outage. See Failover behavior. |
423 | Locked | The verification result has not yet been released. Please wait until the verification is complete. |
429 | Too Many Requests | The verification result has reached its maximum retrieval count and can no longer be retrieved. |
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.
Failover behavior: Decide how your backend should behave when our service is temporarily unreachable. This is particularly important for high-availability flows where blocking real users during an outage is worse than letting through a small amount of unverified traffic. Learn more about failover behavior.
Testing: If you use automated testing, make sure that the CAPTCHA does not block it. Learn more about testing.