Skip to main content

SDK Integration

This guide shows how to integrate TrustGate identity verification into your application using our SDK.

Integration Overview​

TrustGate provides two integration approaches:

ApproachBest ForDescription
Hosted SDKSimplest integrationRedirect users to our hosted verification page
Embedded SDKCustom UXEmbed the verification flow directly in your React app

Authentication Flow​

┌─────────────────┐      ┌─────────────────┐      ┌─────────────────┐
│ Your App │ │ Your Server │ │ TrustGate │
│ (Frontend) │ │ (Backend) │ │ API │
└────────┬────────┘ └────────┬────────┘ └────────┬────────┘
│ │ │
│ 1. User clicks │ │
│ "Verify Identity" │ │
│ ──────────────────────>│ │
│ │ │
│ │ 2. Create access token │
│ │ POST /sdk/access-token
│ │ ──────────────────────>│
│ │ │
│ │ 3. Returns token + │
│ │ applicant_id │
│ │ <──────────────────────│
│ │ │
│ 4. Return token │ │
│ to frontend │ │
│ <──────────────────────│ │
│ │ │
│ 5. Initialize SDK │
│ with access token │
│ ───────────────────────────────────────────────>│
│ │ │

Server-Side: Create Access Token​

Your backend server creates an access token when a user needs to verify their identity.

API Key Setup​

  1. Go to Integrations → API Keys (or Dev Workbench → API Keys) in the TrustGate dashboard
  2. Click + Create API Key to create an API key
  3. Store the key securely (it's only shown once)

Create Access Token Endpoint​

// Node.js / Express example
const express = require('express');
const app = express();

// Store your API key securely (environment variable)
const TRUSTGATE_API_KEY = process.env.TRUSTGATE_API_KEY;
const TRUSTGATE_API_URL = 'https://api.bytrustgate.com/api/v1';

app.post('/api/start-verification', async (req, res) => {
const { userId, email, firstName, lastName } = req.body;

try {
const response = await fetch(`${TRUSTGATE_API_URL}/sdk/access-token`, {
method: 'POST',
headers: {
'X-API-Key': TRUSTGATE_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
external_user_id: userId, // Your unique identifier for this user
email: email,
first_name: firstName,
last_name: lastName,
flow_name: 'default', // Or specify a workflow name
redirect_url: 'https://yourapp.com/verification-complete',
expires_in: 3600, // Token valid for 1 hour (300-86400 seconds)
}),
});

if (!response.ok) {
throw new Error('Failed to create access token');
}

const data = await response.json();

// Return token info to frontend
res.json({
accessToken: data.access_token,
applicantId: data.applicant_id,
sdkUrl: data.sdk_url, // Hosted SDK URL for redirect approach
});

} catch (error) {
console.error('Error creating access token:', error);
res.status(500).json({ error: 'Failed to start verification' });
}
});

Python Example​

import os
import httpx
from fastapi import FastAPI, HTTPException

app = FastAPI()

TRUSTGATE_API_KEY = os.environ['TRUSTGATE_API_KEY']
TRUSTGATE_API_URL = 'https://api.bytrustgate.com/api/v1'

@app.post('/api/start-verification')
async def start_verification(user_id: str, email: str = None):
async with httpx.AsyncClient() as client:
response = await client.post(
f'{TRUSTGATE_API_URL}/sdk/access-token',
headers={
'X-API-Key': TRUSTGATE_API_KEY,
'Content-Type': 'application/json',
},
json={
'external_user_id': user_id,
'email': email,
'flow_name': 'default',
'expires_in': 3600,
}
)

if response.status_code != 200:
raise HTTPException(status_code=500, detail='Failed to create token')

return response.json()

Java / Spring Boot Example​

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
@RequestMapping("/api")
public class VerificationController {

@Value("${trustgate.api-key}")
private String apiKey;

private static final String TRUSTGATE_API_URL = "https://api.bytrustgate.com/api/v1";

private final RestTemplate restTemplate = new RestTemplate();

@PostMapping("/start-verification")
public ResponseEntity<?> startVerification(@RequestBody VerificationRequest request) {
HttpHeaders headers = new HttpHeaders();
headers.set("X-API-Key", apiKey);
headers.setContentType(MediaType.APPLICATION_JSON);

Map<String, Object> body = Map.of(
"external_user_id", request.getUserId(),
"email", request.getEmail(),
"first_name", request.getFirstName(),
"last_name", request.getLastName(),
"flow_name", "default",
"redirect_url", "https://yourapp.com/verification-complete",
"expires_in", 3600
);

HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);

try {
ResponseEntity<Map> response = restTemplate.exchange(
TRUSTGATE_API_URL + "/sdk/access-token",
HttpMethod.POST,
entity,
Map.class
);

return ResponseEntity.ok(response.getBody());
} catch (Exception e) {
return ResponseEntity.status(500)
.body(Map.of("error", "Failed to create access token"));
}
}

// Handle callback after user completes verification
@GetMapping("/verification-complete")
public String handleVerificationComplete(
@RequestParam("session_id") String sessionId,
@RequestParam("status") String status) {

if ("completed".equals(status)) {
// Fetch attestation for the completed session
HttpHeaders headers = new HttpHeaders();
headers.set("X-API-Key", apiKey);

HttpEntity<?> entity = new HttpEntity<>(headers);

ResponseEntity<Map> attestation = restTemplate.exchange(
TRUSTGATE_API_URL + "/verifications/" + sessionId + "/attestation",
HttpMethod.GET,
entity,
Map.class
);

// attestation.getBody().get("attestation_id") - embed in your documents
// attestation.getBody().get("verify_url") - public verification URL

return "redirect:/success?attestation=" + attestation.getBody().get("attestation_id");
}

return "redirect:/verification-failed";
}
}

// Request DTO
class VerificationRequest {
private String userId;
private String email;
private String firstName;
private String lastName;

// Getters and setters
public String getUserId() { return userId; }
public void setUserId(String userId) { this.userId = userId; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
}

application.properties:

trustgate.api-key=${TRUSTGATE_API_KEY}

Access Token Response​

{
"access_token": "sdk_abc123...",
"applicant_id": "550e8400-e29b-41d4-a716-446655440000",
"expires_at": "2026-01-21T12:00:00Z",
"flow_name": "default",
"sdk_url": "https://app.bytrustgate.com/sdk/verify?token=sdk_abc123..."
}

Option 1: Hosted SDK (Redirect)​

The simplest integration - redirect users to our hosted verification page.

Frontend Implementation​

// React example
function VerifyButton() {
const handleVerify = async () => {
// 1. Get access token from your backend
const response = await fetch('/api/start-verification', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: currentUser.id,
email: currentUser.email,
}),
});

const { sdkUrl } = await response.json();

// 2. Redirect to hosted SDK
window.location.href = sdkUrl;
};

return (
<button onClick={handleVerify}>
Verify Your Identity
</button>
);
}

Open in Modal/Popup​

function VerifyButton() {
const handleVerify = async () => {
const response = await fetch('/api/start-verification', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: currentUser.id }),
});

const { sdkUrl } = await response.json();

// Open in popup window
const popup = window.open(
sdkUrl,
'verification',
'width=500,height=700,scrollbars=yes'
);

// Listen for completion
window.addEventListener('message', (event) => {
if (event.data.type === 'verification_complete') {
popup.close();
handleVerificationComplete(event.data.result);
}
});
};
}

Option 2: Embedded SDK (React)​

Embed the verification flow directly in your React application for full control over the UX.

Installation​

The SDK component is available as part of the TrustGate React package:

# Coming soon to npm
# For now, copy the VerificationSDK component from the docs

Basic Usage​

import { useState } from 'react';
import VerificationSDK from './VerificationSDK';

function VerificationPage() {
const [accessToken, setAccessToken] = useState(null);
const [loading, setLoading] = useState(false);

const startVerification = async () => {
setLoading(true);

const response = await fetch('/api/start-verification', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: currentUser.id }),
});

const { accessToken } = await response.json();
setAccessToken(accessToken);
setLoading(false);
};

const handleComplete = (result) => {
console.log('Verification complete:', result);
// Navigate to success page or update UI
};

const handleError = (error) => {
console.error('Verification error:', error);
// Show error message to user
};

if (!accessToken) {
return (
<button onClick={startVerification} disabled={loading}>
{loading ? 'Starting...' : 'Start Verification'}
</button>
);
}

return (
<VerificationSDK
accessToken={accessToken}
baseUrl="https://api.bytrustgate.com/api/v1/sdk"
onComplete={handleComplete}
onError={handleError}
theme="light"
/>
);
}

SDK Props​

PropTypeRequiredDescription
accessTokenstringYesThe SDK access token from /sdk/access-token
baseUrlstringNoAPI base URL (default: /api/v1/sdk)
onCompletefunctionNoCalled when verification completes successfully
onErrorfunctionNoCalled when an error occurs
themestringNo'light' or 'dark' (default: 'light')

Multiple Workflows​

If you have multiple verification workflows (e.g., different flows for different user types), you can:

1. List Available Workflows​

const response = await fetch(`${API_URL}/sdk/workflows`, {
headers: { 'X-API-Key': API_KEY },
});

const { items, default_workflow } = await response.json();
// items: [{ id, name, description, is_default }, ...]

2. Specify Workflow When Creating Token​

const response = await fetch(`${API_URL}/sdk/access-token`, {
method: 'POST',
headers: {
'X-API-Key': API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
external_user_id: userId,
flow_name: 'premium_kyc', // Specify workflow name
}),
});

Handling Results​

Configure webhooks to receive real-time notifications when verification completes.

// Your webhook endpoint
app.post('/webhooks/trustgate', (req, res) => {
const event = req.body;

switch (event.event_type) {
case 'applicant.submitted':
console.log('User submitted verification:', event.data.applicant_id);
break;

case 'applicant.verification_complete':
const { applicant_id, status, biometrics_verified } = event.data;
// Update your database with verification status
break;

case 'applicant.approved':
// User was approved - grant access
break;

case 'applicant.rejected':
// User was rejected - handle accordingly
break;
}

res.json({ received: true });
});

See Webhook Events for the complete event reference.

Polling (Alternative)​

If webhooks aren't suitable, you can poll the applicant status:

const checkStatus = async (applicantId) => {
const response = await fetch(`${API_URL}/applicants/${applicantId}`, {
headers: { 'X-API-Key': API_KEY },
});

const applicant = await response.json();
return applicant.status; // pending, in_progress, review, approved, rejected
};

Development & Testing​

Test Environment​

Use sandbox API keys (sk_test_xxx) for development. Test verifications don't affect production data.

Dev Test Token​

For quick testing without creating access tokens:

// Use this token in development only
const DEV_TOKEN = 'sdk_dev_test_token_trustgate_2026';

<VerificationSDK
accessToken={DEV_TOKEN}
baseUrl="/api/v1/sdk?reset=true" // Add ?reset=true to start fresh
onComplete={handleComplete}
/>

SDK Demo​

The TrustGate dashboard includes an SDK demo at Dev Workbench → SDK Demo where you can test the verification flow with your workflows.

Error Handling​

Common error responses:

StatusErrorCause
401Invalid API keyCheck your API key
401Invalid or expired SDK tokenToken expired or invalid
400Missing required stepsUser skipped required verification steps
404Applicant not foundInvalid applicant ID
// Handle errors gracefully
try {
const response = await fetch('/api/start-verification', ...);
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Verification failed');
}
} catch (error) {
// Show user-friendly error message
showError('Unable to start verification. Please try again.');
}

Security Best Practices​

  1. Never expose API keys - Only use API keys on your backend server
  2. Use HTTPS - All API calls should use HTTPS
  3. Validate webhooks - Verify webhook signatures before processing
  4. Set short token expiry - Use the minimum expiry time needed (default: 1 hour)
  5. Use external_user_id - Always pass your user ID to link verifications to your users

Next Steps​