Upgrade from the 3.x Libraries to the TrustComponent SDK
The TrustComponent SDK replaces the eight TrustCaptcha backend libraries 3.x. It is one SDK for TrustCaptcha and every other TrustComponent module, so the client you set up for the CAPTCHA also reaches TrustAnalytics, TrustMonitoring, the Trust VAT Checker and the platform. This guide lists only what a 3.x integration has to change; everything the SDK can do is on the Result Validation page.
What stays
Section titled “What stays”- Your API key. The key your 3.x integration uses works with the SDK unchanged.
- The widget and its token. Nothing changes in the frontend: the SDK reads the same
tc-verification-token, including the failover flag of the widget. - The result. The same fields with the same meaning, but the four booleans now start with
is(table under What changes):score,decisionTypeand the rest keep their names. PHP and Java also read every field through a getter now (see below).
The 3.x libraries call the earlier version of the result operation, which stays available, so you can move one backend at a time.
What changes
Section titled “What changes”- Package and import. A new package per language; each language below starts with the commands that swap it.
- A client instead of
TrustCaptcha. Create one client with your API key and callcaptcha.getVerificationResult(token)on it. There is no static shortcut any more; create the client once per application and reuse it. - Errors. One error type per kind of answer instead of one exception per situation, see Errors. Three situations answer with a different status now: a visitor who has not finished is
409(was423), a result fetched too often is410(was429), an unknown or revoked API key is401(was403). - Options.
apiHostis nowhost, the two timeouts become onetimeout(PHP and Java keep a separateconnectTimeout), see Options. - Retries. The SDK retries
502,503,504,429withRetry-Afterand a lost connection by itself, twice by default. Set the retries to 0 if your form has to answer within a tight time budget. - Boolean result fields. The four booleans of the result start with
is; every other field keeps its name:
| 3.x libraries | SDK | Example (TypeScript / PHP / Python) |
|---|---|---|
verificationPassed | isVerificationPassed | result.isVerificationPassed / $result->isVerificationPassed() / result.is_verification_passed |
gatewayFailoverActive | isGatewayFailoverActive | result.isGatewayFailoverActive / $result->isGatewayFailoverActive() / result.is_gateway_failover_active |
riskScoringEnabled | isRiskScoringEnabled | result.isRiskScoringEnabled / $result->isRiskScoringEnabled() / result.is_risk_scoring_enabled |
minimalDataModeEnabled | isMinimalDataModeEnabled | result.isMinimalDataModeEnabled / $result->isMinimalDataModeEnabled() / result.is_minimal_data_mode_enabled |
other fields (score, decisionType, …) | unchanged | Java isVerificationPassed(), .NET and Go IsVerificationPassed, Ruby and Rust is_verification_passed |
Step by step
Section titled “Step by step”Replace the package, then the call. The example keeps the usual starting point: accept a request only when it passed and its score is at most 0.5.
# Before (3.x libraries)curl "https://api.trustcomponent.com/captcha/v2/verifications/{verificationId}/results" \ -H "Authorization: Bearer <your_api_key>"
# Aftercurl "https://api.trustcomponent.com/captcha/v3/verifications/{verificationId}/results" \ -H "Authorization: Bearer <your_api_key>"If you call the REST API yourself, move to version 3 of the result operation. It takes the same Authorization: Bearer <apiKey> header and returns the same fields, except that the four booleans are renamed: verificationPassed is now isVerificationPassed, gatewayFailoverActive is isGatewayFailoverActive, riskScoringEnabled is isRiskScoringEnabled and minimalDataModeEnabled is isMinimalDataModeEnabled. Read isVerificationPassed after the switch; verificationPassed is no longer in the answer.
Branch on the new status codes listed under Errors; every error is a problem object with a stable code.
npm uninstall @trustcomponent/trustcaptcha-nodejsnpm install @trustcomponent/sdkimport { TrustCaptcha } from '@trustcomponent/trustcaptcha-nodejs';
try { const result = await TrustCaptcha.getVerificationResult('<your_api_key>', token); if (!result.verificationPassed || result.score > 0.5) { // reject }} catch (error) { // not verified: reject}import { TrustComponent, TrustComponentError } from '@trustcomponent/sdk';
const tc = new TrustComponent('<your_api_key>');
try { const result = await tc.captcha.getVerificationResult(token); if (!result.isVerificationPassed || result.score > 0.5) { // reject }} catch (error) { if (!(error instanceof TrustComponentError)) throw error; // not verified: reject}composer remove trustcomponent/trustcaptcha-phpcomposer require trustcomponent/trustcomponent-phpuse TrustComponent\TrustCaptcha\TrustCaptcha;
try { $trustCaptcha = new TrustCaptcha('<your_api_key>'); $result = $trustCaptcha->getVerificationResult($token); if (!$result->verificationPassed || $result->score > 0.5) { // reject }} catch (Exception $e) { // not verified: reject}use TrustComponent\Exception\TrustComponentException;use TrustComponent\TrustComponent;
$tc = new TrustComponent('<your_api_key>');
try { $result = $tc->captcha()->getVerificationResult($token); if (!$result->isVerificationPassed() || $result->getScore() > 0.5) { // reject }} catch (TrustComponentException $e) { // not verified: reject}The result fields are read with getters now: $result->verificationPassed becomes $result->isVerificationPassed(), $result->score becomes $result->getScore(): a boolean is read by its own name, every other field with get.
pip uninstall trustcaptchapip install trustcomponentfrom trustcaptcha.trust_captcha import TrustCaptcha
trust_captcha = TrustCaptcha("<your_api_key>")
try: result = trust_captcha.get_verification_result(token) if not result.verification_passed or result.score > 0.5: ... # rejectexcept Exception: ... # not verified: rejectfrom trustcomponent import TrustComponent, TrustComponentError
tc = TrustComponent("<your_api_key>")
try: result = tc.captcha.get_verification_result(token) if not result.is_verification_passed or result.score > 0.5: ... # rejectexcept TrustComponentError: ... # not verified: reject<!-- replaces com.trustcomponent:trustcaptcha; Gradle: implementation("com.trustcomponent:trustcomponent-java:1.0.1") --><dependency> <groupId>com.trustcomponent</groupId> <artifactId>trustcomponent-java</artifactId> <version>1.0.1</version></dependency>import com.trustcomponent.trustcaptcha.TrustCaptcha;import com.trustcomponent.trustcaptcha.exception.CaptchaFailureException;import com.trustcomponent.trustcaptcha.model.VerificationResult;
try { VerificationResult result = TrustCaptcha.getVerificationResult("<your_api_key>", token); if (!result.isVerificationPassed() || result.getScore() > 0.5) { // reject }} catch (CaptchaFailureException e) { // not verified: reject}import com.trustcomponent.sdk.TrustComponent;import com.trustcomponent.sdk.exception.TrustComponentException;import com.trustcomponent.sdk.model.CaptchaVerificationResult;
TrustComponent tc = new TrustComponent("<your_api_key>");
try { CaptchaVerificationResult result = tc.captcha().getVerificationResult(token); if (!result.isVerificationPassed() || result.getScore() > 0.5) { // reject }} catch (TrustComponentException e) { // not verified: reject}isVerificationPassed() keeps its name: a boolean is read by its own name, every other field with get (getScore()). The result class is CaptchaVerificationResult. Every SDK exception is unchecked and extends TrustComponentException. Kotlin, Groovy and Scala use the same classes.
dotnet remove package TrustComponent.TrustCaptchadotnet add package TrustComponentusing TrustComponent.TrustCaptcha;
try{ var result = await TrustCaptcha.GetVerificationResultAsync("<your_api_key>", token); if (!result.VerificationPassed || result.Score > 0.5) { // reject }}catch (Exception){ // not verified: reject}using TrustComponent;
using var tc = new TrustComponentClient("<your_api_key>");
try{ var result = await tc.Captcha.GetVerificationResultAsync(token); if (!result.IsVerificationPassed || result.Score > 0.5) { // reject }}catch (TrustComponentException){ // not verified: reject}In a web application register the client once as a singleton (builder.Services.AddSingleton(new TrustComponentClient(...))) instead of disposing it after each request.
go get github.com/trustcomponent/trustcomponent-goimport "github.com/trustcomponent/trustcaptcha-go/v3"
result, err := trustcaptcha.GetVerificationResult("<your_api_key>", token)if err != nil || !result.VerificationPassed || result.Score > 0.5 { // not verified or failed: reject}import trustcomponent "github.com/trustcomponent/trustcomponent-go"
tc := trustcomponent.New("<your_api_key>")
result, err := tc.Captcha.GetVerificationResult(ctx, token)if err != nil || !result.IsVerificationPassed || result.Score > 0.5 { // not verified or failed: reject}The call takes a context.Context now, usually r.Context() of the request. Remove the old module with go mod tidy once nothing imports it.
gem uninstall trustcaptchagem install trustcomponentrequire 'trustcaptcha/trust_captcha'
trust_captcha = TrustCaptcha.new('<your_api_key>')
begin result = trust_captcha.get_verification_result(token) # reject if !result.verification_passed || result.score > 0.5rescue StandardError # not verified: rejectendrequire 'trustcomponent'
tc = TrustComponent::Client.new('<your_api_key>')
begin result = tc.captcha.get_verification_result(token) # reject if !result.is_verification_passed || result.score > 0.5rescue TrustComponent::Error # not verified: rejectendcargo remove trustcaptchacargo add trustcomponentuse trustcaptcha::trust_captcha::TrustCaptcha;
let trust_captcha = TrustCaptcha::builder("<your_api_key>").build()?;
match trust_captcha.get_verification_result(&token).await { Ok(result) if result.verification_passed && result.score <= 0.5 => { /* proceed */ } _ => { /* not verified or failed: reject */ }}let tc = trustcomponent::TrustComponent::new("<your_api_key>");
match tc.captcha.get_verification_result(&token).await { Ok(result) if result.is_verification_passed && result.score <= 0.5 => { /* proceed */ } _ => { /* not verified or failed: reject */ }}TrustComponent::new returns the client directly; the builder (TrustComponent::builder(...).build()?) is for options.
Errors
Section titled “Errors”The 3.x libraries had one exception per situation; the SDK has one error type per kind of answer and carries the HTTP status and the stable code of the API, so a single type covers several situations. The 3.x names below end in Exception (Error in Go and Rust):
| 3.x (status) | SDK error, status, code |
|---|---|
ApiKeyInvalid (403) | Authentication, 401, credentials_invalid |
Permission, 403, access_denied | |
VerificationTokenInvalid | VerificationTokenInvalid, no request is sent |
VerificationNotFound (404) | NotFound, 404 |
VerificationNotFinished (423) | Conflict, 409, result_not_released |
VerificationResultExpired (410) | Gone, 410, result_expired |
VerificationResultRetrievalLimitReached (429) | Gone, 410, result_retrieval_limit_reached |
ServerUnreachable | Connection (no answer) or Server (5xx) |
ClientReportedServerUnreachable (412) | Conflict, 412, client_failover_rejected |
An API key that is valid but does not reach the project of the verification was 403 like an invalid key; it is now Permission, 403 with access_denied, while an unknown or revoked key is Authentication, 401.
The names follow each language:
| Language | Base type | Example |
|---|---|---|
| TypeScript | TrustComponentError | ConflictError, GoneError, ConnectionError |
| PHP | TrustComponentException | ConflictException, GoneException; the reason is $e->errorCode |
| Python | TrustComponentError | ConflictError, GoneError, PermissionDeniedError |
| Java | TrustComponentException | ConflictException, GoneException, ConnectionException |
| .NET | TrustComponentException | ConflictException, GoneException, ConnectionException |
| Go | *trustcomponent.Error, *ConnectionError | apiErr.IsConflict(), apiErr.IsGone(), apiErr.Code |
| Ruby | TrustComponent::Error | TrustComponent::ConflictError, TrustComponent::GoneError |
| Rust | trustcomponent::Error | Error::Api(e) with e.is_conflict(), e.code; Error::Connection(_) |
The base type covers every error answer of the API and every failed connection: TLS, DNS, a timeout or an answer that cannot be read arrive as the connection error, with the original error as its cause. A missing required argument is a mistake in the calling code and raises the language’s own error before any request is sent.
The 3.x failover pair maps onto two cases: TrustCaptcha unreachable (ServerUnreachableException) is now a connection or server error, a rejected failover claim (ClientReportedServerUnreachableException) is a conflict with code: client_failover_rejected. How to handle both is on the Failover behavior page.
Options
Section titled “Options”| 3.x option | SDK option |
|---|---|
apiHost | host |
connectTimeoutMs, readTimeoutMs | timeout for each attempt; PHP and Java also have connectTimeout |
proxy | proxy; in TypeScript pass an own fetch with a proxy agent |
| – | maxRetries, integration (the name and version of your plugin or shop), logger, deprecationWarnings |
The exact names and units of every language are listed under Configuration.
Checklist
Section titled “Checklist”- Replace the package and the import.
- Create one client with your existing API key and call
captcha.getVerificationResult(token)on it. - In PHP and Java, read the result fields through getters.
- Catch the SDK base error; branch on the error type or
codewhere you handled single 3.x exceptions before. - Move your options to the new names.
- Test with the test tokens, then deploy.