### Complete TrustCaptcha Component Example Source: https://docs.trustcomponent.com/captcha/widget/overview This example demonstrates a comprehensive setup of the TrustCaptcha component with most available properties and event handlers. ```html
``` -------------------------------- ### Add TrustCaptcha dependency Source: https://docs.trustcomponent.com/captcha/server/go Install the required Go package using the go get command. ```bash go get github.com/trustcomponent/trustcaptcha-go/v2@v2.0.2 ``` -------------------------------- ### Full Flask Implementation Example Source: https://docs.trustcomponent.com/captcha/server/python A complete example showing how to handle a POST request containing a verification token in a Flask application. ```python from flask import Flask, request, jsonify from flask_cors import cross_origin from trustcaptcha.captcha_manager import CaptchaManager app = Flask(__name__) @app.route('/api/example', methods=['POST']) @cross_origin(origins=["http://localhost:*", "http://127.0.0.1:*"]) def post_api_example(): verification_token = request.get_json()['verificationToken'] # Retrieving the verification result try: verification_result = CaptchaManager.get_verification_result("", verification_token) except Exception as e: # Fetch verification result failed - handle error print(f"Failed to fetch verification result: {e}") return jsonify({'error': 'Captcha verification failed'}), 500 # Act on the verification result if verification_result.verificationPassed is not True or verification_result.score > 0.5: print("Verification failed or bot score > 0.5 – possible automated request.") return verification_result.to_json() if __name__ == '__main__': app.run(debug=True, port=8080) ``` -------------------------------- ### Install TrustCaptcha Dependency Source: https://docs.trustcomponent.com/captcha/server/python Install the required package via pip. ```bash pip install trustcaptcha ``` -------------------------------- ### Install TrustCaptcha CraftCMS Plugin Source: https://docs.trustcomponent.com/captcha/platforms/craftcms Install the TrustCaptcha CraftCMS package using Composer. Ensure you have Composer installed and configured for your project. ```bash composer require trustcaptcha/trustcaptcha-craftcms ``` -------------------------------- ### Install TrustCaptcha TYPO3 Extension (Composer v12+) Source: https://docs.trustcomponent.com/captcha/platforms/typo3 Install the TrustCaptcha TYPO3 extension using Composer for TYPO3 versions 12 and above. This command includes dependencies and sets up the extension. ```bash composer require trustcomponent/trustcaptcha-typo3:^2.0 --with-all-dependencies php vendor/bin/typo3 extension:setup --no-interaction php vendor/bin/typo3 cache:flush php vendor/bin/typo3 cache:warmup ``` -------------------------------- ### Install TrustCaptcha Dependency Source: https://docs.trustcomponent.com/captcha/server/ruby Add the required gem to your Ruby project. ```bash gem install trustcaptcha ``` -------------------------------- ### Install TrustCaptcha TYPO3 Extension (Composer v11) Source: https://docs.trustcomponent.com/captcha/platforms/typo3 Install the TrustCaptcha TYPO3 extension using Composer for TYPO3 version 11. This command includes dependencies and flushes the cache. ```bash composer require trustcomponent/trustcaptcha-typo3:^2.0 --with-all-dependencies php vendor/bin/typo3cms cache:flush ``` -------------------------------- ### Install TrustCaptcha Magento2 Extension Source: https://docs.trustcomponent.com/captcha/platforms/magento2 Install the TrustCaptcha Magento2 extension using Composer and enable it. Then, run Magento commands to upgrade, compile, deploy static content, and flush the cache. ```bash composer require trustcomponent/trustcaptcha-magento2:2.1.0 bin/magento module:enable TrustComponent_TrustCaptchaMagento2 bin/magento setup:upgrade bin/magento setup:di:compile bin/magento setup:static-content:deploy -f bin/magento cache:flush ``` -------------------------------- ### Install TrustCaptcha PHP dependency Source: https://docs.trustcomponent.com/captcha/server/php Use Composer to add the TrustCaptcha library to your project. ```bash composer require trustcomponent/trustcaptcha-php ``` -------------------------------- ### Install TrustCaptcha dependency Source: https://docs.trustcomponent.com/captcha/widget/vuejs Add the required package to your Vue.js project using npm. ```bash npm i @trustcomponent/trustcaptcha-vue ``` -------------------------------- ### TrustCaptcha Backend Integration Example (Java) Source: https://docs.trustcomponent.com/captcha/server/jvm This Java Spring Boot controller demonstrates how to integrate TrustCaptcha into a backend. It retrieves the verification result using the secret key and verification token, then acts upon it. ```java import com.trustcomponent.trustcaptcha.CaptchaManager; import com.trustcomponent.trustcaptcha.exception.CaptchaFailureException; import com.trustcomponent.trustcaptcha.model.VerificationResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @CrossOrigin(originPatterns = {"http://localhost:[*]", "http://127.0.0.1:[*]"}) public class ApiController { private static final Logger logger = LoggerFactory.getLogger(ApiController.class); @PostMapping("/api/example") public ResponseEntity postApiExample(@RequestBody VerificationRequest verificationRequest) { // Retrieving the verification result VerificationResult verificationResult; try { verificationResult = CaptchaManager.getVerificationResult("", 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); } } ``` ```java public class VerificationRequest { private String verificationToken; public String getVerificationToken() { return verificationToken; } public void setVerificationToken(String verificationToken) { this.verificationToken = verificationToken; } } ``` -------------------------------- ### Install TrustCaptcha Dependency Source: https://docs.trustcomponent.com/captcha/widget/angular Add the required package to your Angular project using npm. ```bash npm i @trustcomponent/trustcaptcha-angular ``` -------------------------------- ### Full Node.js CAPTCHA Integration Example Source: https://docs.trustcomponent.com/captcha/server/nodejs An example Node.js backend implementation using Express to handle CAPTCHA verification. It sets up an API endpoint that receives a verification token, fetches the result, evaluates it, and returns the result. ```javascript import express from 'express'; import cors from 'cors'; import { json } from 'body-parser'; import {CaptchaManager} from "@trustcomponent/trustcaptcha-nodejs"; const app = express(); app.use(cors({ origin: '*' })); app.use(json()); app.post('/api/example', async (req, res) => { const verificationToken = req.body.verificationToken; // Retrieving the verification result let verificationResult; try { verificationResult = await CaptchaManager.getVerificationResult("", 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'); }); ``` -------------------------------- ### Install TrustCaptcha React Dependency Source: https://docs.trustcomponent.com/captcha/widget/react Use npm to add the TrustCaptcha React package to your project. ```bash npm i @trustcomponent/trustcaptcha-react ``` -------------------------------- ### Install TrustCaptcha Svelte Package Source: https://docs.trustcomponent.com/captcha/widget/svelte Add the trustcaptcha-svelte package to your Svelte project using npm. ```bash npm i trustcaptcha-svelte ``` -------------------------------- ### Implement TrustCaptcha verification in Actix Web Source: https://docs.trustcomponent.com/captcha/server/rust This example demonstrates a POST endpoint that receives a verification token, validates it against TrustCaptcha servers, and evaluates the bot score. ```rust use actix_cors::Cors; use actix_web::{web, App, HttpServer, HttpResponse, Error, middleware::Logger}; use serde::Deserialize; use serde_json::json; use log::{info, error}; use trustcaptcha::captcha_manager::CaptchaManager; #[derive(Deserialize, Debug)] struct VerificationRequest { #[serde(rename = "verificationToken")] verification_token: String, } async fn post_api_example(verification_request: web::Json) -> Result { info!("Received request: {:?}", verification_request); let verification_token = &verification_request.verification_token; // Retrieving the verification result let verification_result = match CaptchaManager::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 } ``` -------------------------------- ### Add TrustCaptcha Node.js Dependency Source: https://docs.trustcomponent.com/captcha/server/nodejs Install the TrustCaptcha Node.js library using npm. This is the first step to enable CAPTCHA validation in your backend. ```bash npm i @trustcomponent/trustcaptcha-nodejs ``` -------------------------------- ### Base64 Encoded Verification Token Source: https://docs.trustcomponent.com/captcha/server/overview Example of the Base64 encoded string returned by the TrustCaptcha widget upon successful completion. ```text eyJhcGlFbmRwb2ludCI6Imh0dHBzOi8vYXBpLmNhcHRjaGEudHJ1c3RjYXB0Y2hhLmNvbSIsInZlcmlmaWNhdGlvbklkIjoiMDdiMDE5MjItM2ZhYS00NjY3LWE0YTYtOTEwYTc2Y2I4YWI3IiwiZW5jcnlwdGVkQWNjZXNzVG9rZW4iOiJtQ2JCZldTS0V5bWQxYjN0cW5ycXZCYURZMER2TkgwK29acHlYdTdSN1pkTUNMcjhhU202TURlM2ltckVPTTVDaFZOeUkvbkFSUFJCalNvV1N1NnNMNVlpUjhlUXU4dDZ3eUVBVDNRc3NwQT0ifQ0= ``` -------------------------------- ### Disable Autostart in TrustCaptcha Component Source: https://docs.trustcomponent.com/captcha/widget/overview Set `autostart="false"` on the TrustCaptcha component to prevent the verification process from starting automatically upon user interaction with form input fields. ```html
``` -------------------------------- ### PHP Backend Verification with TrustCaptcha Source: https://docs.trustcomponent.com/captcha/server/php Implement TrustCaptcha verification in your PHP backend. This code retrieves the verification token from a POST request, uses the CaptchaManager to get the verification result from TrustCaptcha servers, and checks if the verification passed and the score is within acceptable limits. Adapt the secret key and thresholds to your needs. ```php ", $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."; } } ?> ``` -------------------------------- ### Validate CAPTCHA Result in NodeJS Source: https://docs.trustcomponent.com/captcha/platforms/webflow Validates the CAPTCHA result using the NodeJS library. Ensure 'express' and '@trustcomponent/trustcaptcha-nodejs' are installed via npm. This example sets up an Express server to handle POST requests for verification. ```javascript /** * Install: * npm i express @trustcomponent/trustcaptcha-nodejs */ import express from "express"; import { CaptchaManager } from "@trustcomponent/trustcaptcha-nodejs"; const SECRET = "YOUR_SECRET_HERE"; const THRESHOLD = 0.50; // score ≤ threshold → likely human (0 ≈ human, 1 ≈ bot) const app = express(); app.use(express.urlencoded({ extended: false })); // Webflow posts urlencoded by default app.post("/verify", async (req, res) => { res.type("text"); // plain text responses for this demo const token = req.body["tc-verification-token"]; // update this string if you renamed the field if (!token) return res.status(400).send("Missing verification token\n"); let result; try { result = await CaptchaManager.getVerificationResult(SECRET, token); } catch (err) { // TODO: network/config error return res.status(500).send(`Captcha verification error: ${(err).message}\n`); } const isHuman = result.verificationPassed === true && result.score <= THRESHOLD; if (isHuman) { return res.send(`OK: CAPTCHA passed (score=${result.score})\n`); // TODO: continue your logic } else { return res.status(403).send(`FAIL: CAPTCHA failed or score too high (score=${result.score})\n`); // TODO: handle failure } }); app.listen(8080, () => console.log("Listening on http://localhost:8080")); ``` -------------------------------- ### Add TrustCaptcha .NET Dependency Source: https://docs.trustcomponent.com/captcha/server/dotnet Use this command to add the TrustCaptcha .NET library to your project. Ensure you specify the correct version. ```bash dotnet add package TrustComponent.TrustCaptcha --version 2.0.1 ``` -------------------------------- ### GET /verifications/{verificationId}/assessments Source: https://docs.trustcomponent.com/captcha/server/overview Retrieves the CAPTCHA verification result from TrustComponent servers using the verification ID. ```APIDOC ## GET /verifications/{verificationId}/assessments ### Description Retrieves the CAPTCHA verification result from TrustComponent servers using the verification ID. ### Method GET ### Endpoint https://api.trustcomponent.com/verifications/{verificationId}/assessments ### Parameters #### Path Parameters - **verificationId** (string) - Required - Unique identifier (ID) of the verification. Can be taken from the verification token. #### Header Parameters - **tc-authorization** (string) - Required - Secret key / API key of the CAPTCHA. This can be taken from the CAPTCHA administration. ### Request Example ```bash curl -X GET "https://api.trustcomponent.com/verifications/{verificationId}/assessments" \ -H "Content-Type: application/json" \ -H "tc-authorization: {secret-key}" ``` ### Response #### Success Response (200) - **Example Response Body**: ```json { "example": "response body" } ``` ``` -------------------------------- ### Configure proxy for verification Source: https://docs.trustcomponent.com/captcha/server/php Pass proxy options to the getVerificationResult method when running behind an HTTP proxy. ```php $secretKey = ''; $verificationToken = ''; $proxyOptions = [ 'proxy' => 'http://proxy.example.com:8080', ]; try { $verificationResult = CaptchaManager::getVerificationResult( $secretKey, $verificationToken, $proxyOptions ); } catch (Exception $e) { // Fetch verification result failed - handle error } ``` ```php $secretKey = ''; $verificationToken = ''; $proxyOptions = [ 'proxy' => 'http://proxy.example.com:8080', 'username' => 'myProxyUser', 'password' => 'myProxyPassword', ]; try { $verificationResult = CaptchaManager::getVerificationResult( $secretKey, $verificationToken, $proxyOptions ); } catch (Exception $e) { // Fetch verification result failed - handle error } ``` -------------------------------- ### Handle CAPTCHA Events in JavaScript Source: https://docs.trustcomponent.com/captcha/widget/javascript Listen for 'captchaSolved' and 'captchaFailed' events on the trustcaptcha-component to get the verification token or error details. ```javascript const trustcaptchaComponent = document.getElementsByTagName('trustcaptcha-component')[0]; trustcaptchaComponent.addEventListener('captchaSolved', (event) => { console.log('Verification token:', event.detail); }); trustcaptchaComponent.addEventListener('captchaFailed', (event) => { console.error(event.detail); }); ``` -------------------------------- ### Implement API Service for Token Verification Source: https://docs.trustcomponent.com/captcha/widget/react This snippet defines an API service module for posting verification tokens to a server. Ensure the fetch API is available in your environment. ```javascript body: JSON.stringify({ verificationToken }), }; try { const response = await fetch(url, options); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.json(); } catch (error) { console.error('Error posting data', error); throw error; } }, }; export default apiService; ``` -------------------------------- ### Register TrustcaptchaComponent Source: https://docs.trustcomponent.com/captcha/widget/vuejs Import and register the component in your main application entry point. ```javascript import {TrustcaptchaComponent} from "@trustcomponent/trustcaptcha-vue"; createApp(App).use(TrustcaptchaComponent).mount('#app') ``` -------------------------------- ### Basic Human Check Source: https://docs.trustcomponent.com/captcha/server/overview Use this snippet to perform a basic check for CAPTCHA verification success and a bot score below 0.5. This is a recommended starting point for CAPTCHA validation. ```javascript 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."); } ``` -------------------------------- ### Add TrustCaptcha Dependency Source: https://docs.trustcomponent.com/captcha/server/jvm Configuration snippets for adding the TrustCaptcha library to various JVM build systems. ```xml com.trustcomponent trustcaptcha 2.0.1 ``` ```groovy dependencies { // Other dependencies implementation 'com.trustcomponent:trustcaptcha:2.0.1' } ``` ```kotlin dependencies { // Other dependencies implementation("com.trustcomponent:trustcaptcha:2.0.1") } ``` ```scala libraryDependencies ++= Seq( // Other dependencies "com.trustcomponent" % "trustcaptcha" % "2.0.1", ) ``` -------------------------------- ### Validate CAPTCHA Result in PHP Source: https://docs.trustcomponent.com/captcha/platforms/webflow Validates the CAPTCHA result using the PHP library. Ensure the 'trustcomponent/trustcaptcha-php' package is installed via Composer. This script checks if the verification passed and the score is below the defined threshold. ```php getMessage() . "\n"); } $isHuman = ($result->verificationPassed === true) && ((float)$result->score <= THRESHOLD); if ($isHuman) { echo "OK: CAPTCHA passed (score={$result->score})\n"; // TODO: continue your logic } else { http_response_code(403); echo "FAIL: CAPTCHA failed or score too high (score={$result->score})\n"; // TODO: handle failure } ``` -------------------------------- ### Disable Autostart for Specific Input Fields Source: https://docs.trustcomponent.com/captcha/widget/overview Use the `data-autostart="false"` attribute on specific input fields to disable autostart only for those elements, while allowing it for others. ```html
``` -------------------------------- ### HTML Structure with TrustCaptcha Component Source: https://docs.trustcomponent.com/captcha/server/php This HTML structure sets up a form for user input and integrates the TrustCaptcha component. It includes Bootstrap for styling and the TrustCaptcha JavaScript SDK. The form submits data via POST, and the TrustCaptcha component is configured with a site key and language. ```html Trustcaptcha Testsystem

PHP

Try PHP
``` -------------------------------- ### Validate CAPTCHA Result in Python Source: https://docs.trustcomponent.com/captcha/platforms/webflow Validates the CAPTCHA result using the Python library. Ensure 'flask' and 'trustcaptcha' are installed via pip. This Flask application defines a POST endpoint to handle verification requests. ```python """ Install: pip install flask trustcaptcha """ from flask import Flask, request, Response from trustcaptcha.captcha_manager import CaptchaManager SECRET = "YOUR_SECRET_HERE" THRESHOLD = 0.50 # score ≤ threshold → likely human (0 ≈ human, 1 ≈ bot) app = Flask(__name__) @app.post("/verify") def verify(): token = request.form.get("tc-verification-token") # update this string if you renamed the field if not token: return Response("Missing verification token\n", status=400, mimetype="text/plain") try: result = CaptchaManager.get_verification_result(SECRET, token) except Exception as e: # TODO: network/config error return Response(f"Captcha verification error: {e}\n", status=500, mimetype="text/plain") is_human = (result.verificationPassed is True) and (result.score <= THRESHOLD) if is_human: return Response(f"OK: CAPTCHA passed (score={result.score})\n", mimetype="text/plain") # TODO: continue your logic else: return Response(f"FAIL: CAPTCHA failed or score too high (score={result.score})\n", status=403, mimetype="text/plain") # TODO: handle failure if __name__ == "__main__": app.run(port=8080, debug=True) ``` -------------------------------- ### Integrate TrustCaptcha Widget in React Source: https://docs.trustcomponent.com/captcha/widget/react Insert the TrustcaptchaComponent into your form and provide your site key. Handle verification tokens using the onCaptchaSolved and onCaptchaFailed events. ```javascript import {TrustcaptchaComponent} from "@trustcomponent/trustcaptcha-react"; function App() { function handleSuccess(verificationToken) { // handle success } function handleError(error) { // handle error } return (
handleSuccess(event.detail)} onCaptchaFailed={event => handleError(event.detail)} >
); } export default App; ``` -------------------------------- ### Apply Custom Design to TrustCaptcha (HTML) Source: https://docs.trustcomponent.com/captcha/widget/overview Demonstrates how to apply custom design properties to the TrustCaptcha component directly within HTML using the `custom-design` attribute. This is useful for static configurations. ```html ``` -------------------------------- ### Go Backend TrustCaptcha Verification Source: https://docs.trustcomponent.com/captcha/server/go Implement a Go HTTP server endpoint to receive CAPTCHA verification tokens, verify them using the TrustCaptcha Go SDK, and return the verification result. Ensure your secret key is securely managed. ```go package main import ( "encoding/json" "fmt" "github.com/trustcomponent/trustcaptcha-go/v2" "log" "net/http" ) type VerificationRequest struct { VerificationToken string `json:"verificationToken"` } func postApiExample(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK) return } var req VerificationRequest // Parse the request body if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Retrieving the verification result verificationResult, err := trustcaptcha.GetVerificationResult("", 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) } } ``` -------------------------------- ### Define API Service for Verification Source: https://docs.trustcomponent.com/captcha/widget/react Defines an asynchronous service to post the verification token to the backend. ```javascript const apiService = { postApi: async (verificationToken) => { const url = 'http://localhost:8080/api/example'; const options = { method: 'POST', headers: { 'Content-Type': 'application/json', }, ``` -------------------------------- ### Add TrustCaptcha Frontend Component Source: https://docs.trustcomponent.com/captcha/migration/cloudflare-turnstile Include the TrustCaptcha JavaScript library and add the trustcaptcha-component web component within a form. It requires a sitekey and automatically generates a hidden input field for the verification token. ```html
``` -------------------------------- ### Add TrustCaptcha Dependency Source: https://docs.trustcomponent.com/captcha/server/rust Add the TrustCaptcha Rust library to your project's dependencies using Cargo. ```bash cargo add trustcaptcha ``` -------------------------------- ### Multi-Stage Risk Assessment Source: https://docs.trustcomponent.com/captcha/server/overview Implement a multi-stage process to handle different risk levels based on the bot score. This allows for nuanced responses, such as requiring additional verification for elevated risk. ```javascript 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."); } ``` -------------------------------- ### Verify CAPTCHA in .NET Backend Source: https://docs.trustcomponent.com/captcha/server/dotnet Use this controller to handle CAPTCHA verification requests. It retrieves the verification result from TrustCaptcha servers and checks if verification passed or if the bot score exceeds a threshold. Ensure you replace '' with your actual secret key. ```csharp 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 PostApiExample([FromBody] VerificationRequest verificationRequest) { // Retrieving the verification result VerificationResult verificationResult; try { verificationResult = await CaptchaManager.GetVerificationResult("", 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); } } ``` -------------------------------- ### Integrate TrustCaptcha Component Source: https://docs.trustcomponent.com/captcha/widget/overview The component must be placed inside a form element and requires a valid site-key to function. ```html
``` -------------------------------- ### Apply Custom Design to TrustCaptcha (Angular) Source: https://docs.trustcomponent.com/captcha/widget/overview Shows how to bind custom design properties to the TrustCaptcha component in Angular applications using property binding. This allows for dynamic design changes. ```typescript public customDesign = JSON.stringify({ theme: { light: { boxDefaultBackground: "#eab308" } } }); ``` ```html ``` -------------------------------- ### Add TrustCaptcha CJS Dependency Source: https://docs.trustcomponent.com/captcha/widget/javascript Add this script tag to your HTML file to include the CommonJS (CJS) version of the TrustCaptcha library. ```html ``` -------------------------------- ### Add TrustCaptcha UMD Dependency Source: https://docs.trustcomponent.com/captcha/widget/javascript Include this script tag in your HTML file to add the Universal Module Definition (UMD) version of the TrustCaptcha library. ```html ``` -------------------------------- ### Evaluate verification result Source: https://docs.trustcomponent.com/captcha/server/go Check the verification status and bot score to determine if the request should be processed. ```go // Act on the verification result if !verificationResult.VerificationPassed || verificationResult.Score > 0.5 { log.Println("Verification failed or bot score > 0.5 – possible automated request.") } ``` -------------------------------- ### Integrate TrustCaptcha Widget in Svelte Source: https://docs.trustcomponent.com/captcha/widget/svelte Insert the TrustCaptcha widget into your HTML form and handle CAPTCHA solved or failed events. The verification token is available via the `captchaSolved` event detail. ```svelte
``` -------------------------------- ### Implement TrustCaptcha in React App Source: https://docs.trustcomponent.com/captcha/widget/react Integrates the TrustcaptchaComponent into a React form, handling captcha success and failure callbacks. ```javascript import logo from './logo.svg'; import './App.css'; import {TrustcaptchaComponent} from "@trustcomponent/trustcaptcha-react"; import {useRef, useState} from "react"; import apiService from './apiService'; function App() { const trustcaptchaRef = useRef(null); const [verificationResult, setVerificationResult] = useState(null); const [form, setForm] = useState({ message: '', verificationToken: null }); const handleInput = (e) => { const { name, value } = e.target; setForm(prevForm => ({ ...prevForm, [name]: value })); }; function solved(verificationToken) { console.log(`Verification-token: ${verificationToken}`); setForm(prevForm => ({ ...prevForm, verificationToken: verificationToken })); } function failed(error) { console.error(error); } const handleSubmit = (e) => { e.preventDefault(); apiService.postApi(form.verificationToken).then(verificationResult => setVerificationResult(verificationResult)); }; const resetCaptcha = () => { trustcaptchaRef.current.reset(); setForm({ message: '', verificationToken: null }); setVerificationResult(null); }; return (
logo

React Sample

Try TrustCaptcha.
solved(event.detail)} onCaptchaFailed={event => failed(event.detail)} >
{verificationResult &&
Message: {form.message}
Passed: {verificationResult.verificationPassed.toString()}
Reason: {verificationResult.reason}
Score: {verificationResult.score}
}
); } export default App; ```