Skip to content

CAPTCHA Result Validation (Legacy v3)

Here we explain how you call up and evaluate the CAPTCHA result in your backend from our server.

If you only need the simple case, the static shortcut is the shortest path:

Quick start
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.


Quick start
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.


Quick start
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
pass

For 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:

Quick start
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.


Quick start
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:

Quick start
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.


Quick start
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 request
end

For custom timeouts, a proxy, or a custom API host see configured usage below.


Quick start
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.


You should have already completed the following steps before you start with CAPTCHA validation in your Node.js backend.

  1. 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.

  2. Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.

  3. A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.

  4. Existing Node.js project: You need a Node.js project in which you want to integrate TrustCaptcha.

  5. 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.

  1. 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.

  2. Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.

  3. A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.

  4. Existing PHP project: You need a PHP project in which you want to integrate TrustCaptcha.

  5. 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.

  1. 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.

  2. Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.

  3. A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.

  4. Existing Python project: You need a Python project in which you want to integrate TrustCaptcha.

  5. 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.

  1. 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.

  2. Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.

  3. A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.

  4. Existing JVM project: You need a JVM project in which you want to integrate TrustCaptcha.

  5. 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.

  1. 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.

  2. Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.

  3. A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.

  4. Existing DotNet project: You need a DotNet project in which you want to integrate TrustCaptcha.

  5. 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.

  1. 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.

  2. Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.

  3. A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.

  4. Existing Go project: You need a Go project in which you want to integrate TrustCaptcha.

  5. 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.

  1. 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.

  2. Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.

  3. A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.

  4. Existing Ruby project: You need a Ruby project in which you want to integrate TrustCaptcha.

  5. 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.

  1. 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.

  2. Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.

  3. A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.

  4. Existing Rust project: You need a Rust project in which you want to integrate TrustCaptcha.

  5. 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.

To use the TrustCaptcha Node.js library, you first need to add the corresponding dependencies to your project.

1. Add dependency
Terminal window
npm i @trustcomponent/trustcaptcha-nodejs@^3.0.0

You 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.

1. Add dependency
Terminal window
composer require trustcomponent/trustcaptcha-php:^3.0

You 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.

1. Add dependency
Terminal window
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.

1. Add dependency
<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.

1. Add dependency
Terminal window
dotnet add package TrustComponent.TrustCaptcha --version 3.0.0

You 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.

1. Add dependency
Terminal window
go get github.com/trustcomponent/trustcaptcha-go/v3@v3.0.0

You 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.

1. Add dependency
Terminal window
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.

1. Add dependency
Terminal window
cargo add trustcaptcha@^3.0

You can find our TrustCaptcha Rust package on crates.io.

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.

2. Fetch result
// Retrieving the verification result
let 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.

2. Fetch result
// 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.

2. Fetch result
# Retrieving the verification result
try:
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'}), 500

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 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.

2. Fetch result
// Retrieving the verification result
VerificationResult 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.

2. Fetch result
// Retrieving the verification result
VerificationResult 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.

2. Fetch result
// Retrieving the verification result
verificationResult, 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.

2. Fetch result
# 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

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 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.

2. Fetch result
// Retrieving the verification result
let 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"})));
}
};

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.

3. Evaluate the result
// Act on the verification result
if (!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.

3. Evaluate the result
// Act on the verification result
if (!$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.

3. Evaluate the result
# 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.")

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.

3. Evaluate the result
// Act on the verification result
if (!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.

3. Evaluate the result
// Act on the verification result
if (!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.

3. Evaluate the result
// Act on the verification result
if !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.

3. Evaluate the result
# 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

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.

3. Evaluate the result
// 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.");
}

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.

Configured usage
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.

Configured usage
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.

Configured usage
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.

Configured usage
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.

Configured usage
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.

Configured usage
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.

Configured usage
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.

Configured usage
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.

FieldTypeDefaultDescription
apiKeystring (required)—Your API key. Must not be empty.
apiHoststringhttps://api.trustcomponent.comOverride the API host. Useful for staging environments.
connectTimeoutMsnumber3000Connect timeout in milliseconds. (Used as part of axios’ timeout.)
readTimeoutMsnumber5000Total request timeout in milliseconds.
proxyAxiosProxyConfig | falsenoneAn axios proxy configuration object, or false to disable proxies.

KeyTypeDefaultDescription
1st argumentstring (required)—Your API key. Must not be empty.
apiHoststringhttps://api.trustcomponent.comOverride the API host. Useful for staging environments.
connectTimeoutMsint3000Connect timeout in milliseconds.
readTimeoutMsint5000Total request timeout in milliseconds.
proxyarray{proxy: string, username?: string, password?: string}noneHTTP proxy configuration. username and password are only required if your proxy needs authentication.

ArgumentTypeDefaultDescription
1st positionalstr (required)—Your API key. Must not be empty.
api_hoststrhttps://api.trustcomponent.comOverride the API host. Useful for staging environments.
connect_timeout_sfloat3.0Connect timeout in seconds.
read_timeout_sfloat5.0Read timeout in seconds.
proxystr | dict[str, str]noneEither a single URL string (used for both http and https), or a dict like {"http": "...", "https": "..."}.

MethodTypeDefaultDescription
builder(apiKey)String (required)—Your API key. Must not be null or empty.
.apiHost(...)Stringhttps://api.trustcomponent.comOverride the API host. Useful for staging environments.
.connectTimeoutMs(...)int3000Connect timeout in milliseconds.
.readTimeoutMs(...)int5000Read timeout in milliseconds.
.proxy(host, port)String, intnoneConvenience overload — configures an HTTP proxy at host:port.
.proxy(java.net.Proxy)java.net.ProxynonePass a fully built java.net.Proxy instance for advanced setups.
.build()——Returns the configured TrustCaptcha instance.

MethodTypeDefaultDescription
NewBuilder(apiKey)string (required)—Your API key. Must not be null or empty.
.WithApiHost(...)stringhttps://api.trustcomponent.comOverride the API host. Useful for staging environments.
.WithConnectTimeoutMs(...)int3000Connect timeout in milliseconds.
.WithReadTimeoutMs(...)int5000Read timeout in milliseconds.
.WithProxy(string proxyUrl)stringnoneConvenience overload — configures an HTTP proxy from a URL string.
.WithProxy(IWebProxy)System.Net.IWebProxynonePass a fully configured IWebProxy instance (e.g. WebProxy with credentials).
.Build()——Returns the configured TrustCaptcha instance.

OptionTypeDefaultDescription
1st argument of New(...)string (required)—Your API key. Must not be empty.
WithApiHost(host)stringhttps://api.trustcomponent.comOverride the API host. Useful for staging environments.
WithConnectTimeout(d)time.Duration3 * time.SecondConnect timeout.
WithReadTimeout(d)time.Duration5 * time.SecondRead timeout (response header timeout).
WithProxy(url)stringhttp.ProxyFromEnvironmentOverride the HTTP proxy URL. If unset, the default Go behaviour (HTTP_PROXY/HTTPS_PROXY env variables) is used.

ArgumentTypeDefaultDescription
1st positionalString (required)—Your API key. Must not be empty.
api_host:Stringhttps://api.trustcomponent.comOverride the API host. Useful for staging environments.
connect_timeout_s:Integer3Connect timeout in seconds.
read_timeout_s:Integer5Read timeout in seconds.
proxy:String or nilnilA proxy URI string, optionally with credentials, e.g. http://user:pass@host:port.

MethodTypeDefaultDescription
TrustCaptcha::builder(api_key)&str (required)—Your API key. Must not be empty.
.api_host(host)&strhttps://api.trustcomponent.comOverride the API host. Useful for staging environments.
.connect_timeout(d)Duration3sConnect timeout.
.read_timeout(d)Duration5sRead timeout (total request timeout).
.proxy(url)&strnoneHTTP proxy URL.
.build()——Returns the configured TrustCaptcha instance.

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 (HTTP 412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
Failover
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 (HTTP 412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
Failover
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 (HTTP 412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
Failover
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 (HTTP 412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
Failover
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 (HTTP 412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
Failover
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 (HTTP 412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
Failover
result, err := trustCaptcha.GetVerificationResult(token)
var serverUnreachable *trustcaptcha.ServerUnreachableError
var 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 (HTTP 412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
Failover
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.
end

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:

  • ServerUnreachableError — high-trust (your backend cannot reach our servers). For example: allow the request and log the incident.
  • ClientReportedServerUnreachableError (HTTP 412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
Failover
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.
}
}

When the result cannot be retrieved successfully the library raises a typed exception.

ExceptionWhen it is thrown
ApiKeyInvalidExceptionThe API key was rejected (HTTP 403).
VerificationTokenInvalidExceptionThe verification token could not be parsed (malformed base64 / missing verificationId).
VerificationNotFoundExceptionNo verification was found for the given verification token (HTTP 404).
VerificationNotFinishedExceptionThe verification has not yet been completed by the user (HTTP 423).
VerificationResultExpiredExceptionThe result has expired and can no longer be retrieved (HTTP 410).
VerificationResultRetrievalLimitReachedExceptionThe result has reached its maximum retrieval count (HTTP 429).
ServerUnreachableExceptionThe TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of FailoverException. See Failover behavior.
ClientReportedServerUnreachableExceptionThe 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.

ExceptionWhen it is thrown
ApiKeyInvalidExceptionThe API key was rejected (HTTP 403).
VerificationTokenInvalidExceptionThe verification token could not be parsed (malformed base64 / missing verificationId).
VerificationNotFoundExceptionNo verification was found for the given verification token (HTTP 404).
VerificationNotFinishedExceptionThe verification has not yet been completed by the user (HTTP 423).
VerificationResultExpiredExceptionThe result has expired and can no longer be retrieved (HTTP 410).
VerificationResultRetrievalLimitReachedExceptionThe result has reached its maximum retrieval count (HTTP 429).
ServerUnreachableExceptionThe TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of FailoverException. See Failover behavior.
ClientReportedServerUnreachableExceptionThe 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.

ExceptionWhen it is raised
ApiKeyInvalidExceptionThe API key was rejected (HTTP 403).
VerificationTokenInvalidExceptionThe verification token could not be parsed (malformed base64 / missing verificationId).
VerificationNotFoundExceptionNo verification was found for the given verification token (HTTP 404).
VerificationNotFinishedExceptionThe verification has not yet been completed by the user (HTTP 423).
VerificationResultExpiredExceptionThe result has expired and can no longer be retrieved (HTTP 410).
VerificationResultRetrievalLimitReachedExceptionThe result has reached its maximum retrieval count (HTTP 429).
ServerUnreachableExceptionThe TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of FailoverException. See Failover behavior.
ClientReportedServerUnreachableExceptionThe 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.

ExceptionWhen it is thrown
ApiKeyInvalidExceptionThe API key was rejected (HTTP 403).
VerificationTokenInvalidExceptionThe verification token could not be parsed (malformed base64 / missing verificationId).
VerificationNotFoundExceptionNo verification was found for the given verification token (HTTP 404).
VerificationNotFinishedExceptionThe verification has not yet been completed by the user (HTTP 423).
VerificationResultExpiredExceptionThe result has expired and can no longer be retrieved (HTTP 410).
VerificationResultRetrievalLimitReachedExceptionThe result has reached its maximum retrieval count (HTTP 429).
ServerUnreachableExceptionThe TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of FailoverException. See Failover behavior.
ClientReportedServerUnreachableExceptionThe 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.

ExceptionWhen it is thrown
ApiKeyInvalidExceptionThe API key was rejected (HTTP 403).
VerificationTokenInvalidExceptionThe verification token could not be parsed (malformed base64 / missing verificationId).
VerificationNotFoundExceptionNo verification was found for the given verification token (HTTP 404).
VerificationNotFinishedExceptionThe verification has not yet been completed by the user (HTTP 423).
VerificationResultExpiredExceptionThe result has expired and can no longer be retrieved (HTTP 410).
VerificationResultRetrievalLimitReachedExceptionThe result has reached its maximum retrieval count (HTTP 429).
ServerUnreachableExceptionThe TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of FailoverException. See Failover behavior.
ClientReportedServerUnreachableExceptionThe 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 typeWhen it is returned
*ApiKeyInvalidErrorThe API key was rejected (HTTP 403).
*VerificationTokenInvalidErrorThe verification token could not be parsed (malformed base64 / missing verificationId).
*VerificationNotFoundErrorNo verification was found for the given verification token (HTTP 404).
*VerificationNotFinishedErrorThe verification has not yet been completed by the user (HTTP 423).
*VerificationResultExpiredErrorThe result has expired and can no longer be retrieved (HTTP 410).
*VerificationResultRetrievalLimitReachedErrorThe result has reached its maximum retrieval count (HTTP 429).
*ServerUnreachableErrorThe TrustCaptcha server could not be reached at all (connection error / timeout). Implements the FailoverError marker. See Failover behavior.
*ClientReportedServerUnreachableErrorThe 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.

ExceptionWhen it is raised
TrustCaptcha::ApiKeyInvalidExceptionThe API key was rejected (HTTP 403).
TrustCaptcha::VerificationTokenInvalidExceptionThe verification token could not be parsed (malformed base64 / missing verificationId).
TrustCaptcha::VerificationNotFoundExceptionNo verification was found for the given verification token (HTTP 404).
TrustCaptcha::VerificationNotFinishedExceptionThe verification has not yet been completed by the user (HTTP 423).
TrustCaptcha::VerificationResultExpiredExceptionThe result has expired and can no longer be retrieved (HTTP 410).
TrustCaptcha::VerificationResultRetrievalLimitReachedExceptionThe result has reached its maximum retrieval count (HTTP 429).
TrustCaptcha::ServerUnreachableExceptionThe TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of TrustCaptcha::FailoverException. See Failover behavior.
TrustCaptcha::ClientReportedServerUnreachableExceptionThe 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 typeWhen it is returned
ApiKeyInvalidErrorThe API key was rejected (HTTP 403).
VerificationTokenInvalidErrorThe verification token could not be parsed (malformed base64 / missing verificationId).
VerificationNotFoundErrorNo verification was found for the given verification token (HTTP 404).
VerificationNotFinishedErrorThe verification has not yet been completed by the user (HTTP 423).
VerificationResultExpiredErrorThe result has expired and can no longer be retrieved (HTTP 410).
VerificationResultRetrievalLimitReachedErrorThe result has reached its maximum retrieval count (HTTP 429).
ServerUnreachableErrorThe TrustCaptcha server could not be reached at all (connection error / timeout). See Failover behavior.
ClientReportedServerUnreachableErrorThe widget claimed a failover, but the gateway has no record of a recent outage (HTTP 412). See Failover behavior.
UnknownErrorAny other unexpected HTTP status code.

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.

Example implementation
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.

Example implementation
<?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.

Example implementation
from flask import Flask, request, jsonify
from flask_cors import cross_origin
from 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.

Example implementation
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.

Example implementation
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.

Example implementation
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.

Example implementation
require 'sinatra'
require 'json'
require 'sinatra/cross_origin'
require 'trustcaptcha/trust_captcha'
set :port, 8080
set :bind, '0.0.0.0'
configure do
enable :cross_origin
end
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'
200
end
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_json
end

The 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.

Example implementation
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
}


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.

The verification token returned by the TrustCaptcha widget is encoded in Base64.

Sample Verification Token (encoded)
eyJ2ZXJpZmljYXRpb25JZCI6IjA3YjAxOTIyLTNmYWEtNDY2Ny1hNGE2LTkxMGE3NmNiOGFiNyIsImV4cGlyZXNBdCI6IjIwMjYtMDUtMDNUMTM6NDU6MDguMjE0WiJ9

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, plus an expiresAt timestamp telling you when the token (and therefore the result) will no longer be retrievable.

Decoded Sample Token
{
"verificationId": "07b01922-3faa-4667-a4a6-910a76cb8ab7",
"expiresAt": "2026-05-03T13:45:08.214Z"
}

Overview of the properties of the token:

KeyValueDescription
verificationIdUUIDUnique identifier (ID) of the verification.
expiresAtTimestamp (UTC)When the token (and therefore the verification result) will expire and can no longer be retrieved.
clientFailoverBooleanOptional. 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.

Below you will be explained how to retrieve the CAPTCHA verification result, what information it contains, and how you can work with it.

You can retrieve the verification result from our servers using the following URL.

REST API call
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:

ParameterTypeDescription
verificationIdPathUnique identifier (ID) of the verification. Can be taken from the verification token.
api-keyHeaderAPI key of the CAPTCHA, sent as Authorization: Bearer <apiKey>. You can manage your API keys in the CAPTCHA administration.

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:

ParameterValueDescription
captchaIdUUIDUnique identifier (ID) of the respective CAPTCHA.
verificationIdUUIDUnique identifier (ID) of the verification.
verificationPassedBooleanWhether the CAPTCHA was passed (the request can be allowed) or not.
scoreNumberBot probability score between 0 (likely human) and 1 (likely bot).
decisionTypeTextHow the verification outcome was determined. See the Decision section below.
decisionActionTextThe recommended action for this verification. See the Decision section below.
gatewayFailoverActiveBooleantrue when the gateway synthesized this result during a captcha-service outage. See Failover behavior.
riskScoringEnabledBooleanWhether risk scoring was enabled for the captcha environment that issued this verification.
minimalDataModeEnabledBooleanWhether the captcha environment runs in minimal-data mode.
originTextThe page where the captcha was solved.
ipAddressTextIP address (IPv4 or IPv6) of the client.
countryCodeTextTwo-letter ISO 3166-1 alpha-2 country code derived from the client IP. Empty string if not resolvable.
deviceFamilyTextName of the device family used by the client.
operatingSystemTextName and version of the operating system used by the client.
browserTextName and version of the browser used by the client.
verificationStartedAtTimestamp (UTC)When the verification process (the CAPTCHA) was started by the client.
verificationFinishedAtTimestamp (UTC)When the verification process (the CAPTCHA) was completed by the client.
resultExpiresAtTimestamp (UTC)When the result will expire and can no longer be retrieved.
resultFirstFetchedAtTimestamp (UTC)When the result was first fetched. Equal to resultLastFetchedAt on the first fetch.
resultLastFetchedAtTimestamp (UTC)When the result was most recently fetched (i.e. on this very call).

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 passed

  • score: 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.

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.

Simple decision example (typescript)
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.");
}

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.

Simple check without score (typescript)
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.

Individual threshold value (typescript)
const threshold = 0.75; // allow more false positives
if (!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.

Multi level decision (typescript)
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.");
}

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:

ValueDescription
STANDARDOutcome was calculated by the regular CAPTCHA validation logic (proof-of-work + risk score).
BYPASS_KEYThe CAPTCHA was solved using a configured bypass key.
CUSTOM_ACCESS_RULEA custom access rule (e.g. allow- or block-list) configured for this CAPTCHA matched.
GLOBAL_IP_ACCESS_RULEA global TrustCaptcha access rule (e.g. global allow- or block-list) matched.
FAILOVERThe upstream CAPTCHA service was temporarily unreachable; the gateway returned a tolerant fallback result.
FAILOVER_TOLERANCEThe 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:

ValueDescription
ALLOWThe request should be allowed.
BLOCKThe request should be blocked.
CUSTOMA custom rule with a custom action was applied. Inspect your CAPTCHA settings for context.

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 CodeStatus NameDescription
403ForbiddenThe Authorization header is missing/malformed, or the API key is invalid. Please check the request and your API key.
404Not FoundThe verification does not exist for the given verificationId. Please check the verification ID.
410GoneThe verification result has expired and can no longer be retrieved.
412Precondition FailedA client-claimed failover (?clientFailover=true) was rejected because our gateway has no record of a recent outage. See Failover behavior.
423LockedThe verification result has not yet been released. Please wait until the verification is complete.
429Too Many RequestsThe verification result has reached its maximum retrieval count and can no longer be retrieved.
500Internal Server ErrorAn internal server error has occurred. If this happens repeatedly and persists over time, please contact support.

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.