SDK Integration
This guide shows how to integrate TrustGate identity verification into your application using our SDK.
Integration Overview
TrustGate provides two integration approaches:
| Approach | Best For | Description |
|---|---|---|
| Hosted SDK | Simplest integration | Redirect users to our hosted verification page |
| Embedded SDK | Custom UX | Embed 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
- Go to Settings > API in the TrustGate dashboard
- Click Generate New Key to create an API key
- 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()
Access Token Response
{
"access_token": "sdk_abc123...",
"applicant_id": "550e8400-e29b-41d4-a716-446655440000",
"expires_at": "2024-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
| Prop | Type | Required | Description |
|---|---|---|---|
accessToken | string | Yes | The SDK access token from /sdk/access-token |
baseUrl | string | No | API base URL (default: /api/v1/sdk) |
onComplete | function | No | Called when verification completes successfully |
onError | function | No | Called when an error occurs |
theme | string | No | '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
Webhooks (Recommended)
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 (tg_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 Settings > API > Start Demo where you can test the verification flow with your workflows.
Error Handling
Common error responses:
| Status | Error | Cause |
|---|---|---|
| 401 | Invalid API key | Check your API key |
| 401 | Invalid or expired SDK token | Token expired or invalid |
| 400 | Missing required steps | User skipped required verification steps |
| 404 | Applicant not found | Invalid 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
- Never expose API keys - Only use API keys on your backend server
- Use HTTPS - All API calls should use HTTPS
- Validate webhooks - Verify webhook signatures before processing
- Set short token expiry - Use the minimum expiry time needed (default: 1 hour)
- Use external_user_id - Always pass your user ID to link verifications to your users
Next Steps
- Webhook Events - Complete event reference
- API Keys - Managing API keys
- Webhooks - Setting up webhook endpoints