Integration Architecture
Comprehensive guide to integrating botsKYC into your applications with best practices, patterns, and implementation strategies.
Integration Overview
Integration Patterns
. REST API Integration
Direct HTTP/HTTPS API calls - most common pattern.
When to Use:
- Server-to-server communication
- Synchronous verification flows
- Simple request-response needs
- Full control over implementation
Implementation:
// Example: Document verification
const FormData = require('form-data');
const axios = require('axios');
async function verifyDocument(filePath) {
const form = new FormData();
form.append('documents', fs.createReadStream(filePath));
const response = await axios.post(
'https://api.botskyc.com/api/v/kyc/verify/identity',
form,
{
headers: {
'Authorization': `Bearer ${process.env.BOTSKYC_API_KEY}`,
...form.getHeaders()
}
}
);
return response.data;
}
. SDK Integration
Pre-built libraries for popular languages.
When to Use:
- Faster development
- Type safety (TypeScript, Java)
- Built-in error handling
- Automatic retries
Available SDKs:
- JavaScript/TypeScript
- Python
- Java
- React Components
- Mobile (iOS, Android)
Implementation:
import { BotsKYC } from '@botskyc/sdk';
const client = new BotsKYC({
apiKey: process.env.BOTSKYC_API_KEY
});
// Verify identity document
const result = await client.identity.verify({
documents: [file, file]
});
// Create liveness session
const session = await client.liveness.createSession();
. Webhook Integration
Asynchronous event notifications.
When to Use:
- Batch processing
- Long-running operations
- Event-driven architecture
- Decoupled systems
Setup:
// . Configure webhook endpoint
const webhookUrl = 'https://your-app.com/webhooks/botskyc';
// . Handle webhook events
app.post('/webhooks/botskyc', (req, res) => {
const event = req.body;
// Verify signature
const signature = req.headers['x-botskyc-signature'];
if (!verifySignature(event, signature)) {
return res.status(40).send('Invalid signature');
}
// Process event
switch (event.type) {
case 'verification.completed':
handleVerificationCompleted(event.data);
break;
case 'verification.failed':
handleVerificationFailed(event.data);
break;
}
res.status(00).send('OK');
});
4. Monitoring and Observability
Track key metrics
---
### 4. Monitoring and Observability
**Track key metrics**
```javascript
**When to Use:**
- Real-time updates
- Live verification status
- Interactive flows
- Mobile applications
**Implementation:**
```javascript
const WebSocket = require('ws');
const ws = new WebSocket('wss://api.botskyc.com/ws');
ws.on('open', () => {
// Authenticate
ws.send(JSON.stringify({
type: 'auth',
token: process.env.BOTSKYC_API_KEY
}));
// Subscribe to verification updates
ws.send(JSON.stringify({
type: 'subscribe',
channel: 'verification.updates'
}));
});
ws.on('message', (data) => {
const event = JSON.parse(data);
console.log('Verification update:', event);
});
Architecture Patterns
Synchronous Flow
Direct request-response for real-time verification.
Best For:
- Interactive onboarding
- Real-time decisions
- User-facing flows
- Mobile apps
Example:
// User uploads document
async function handleDocumentUpload(file) {
try {
// Show loading state
setLoading(true);
// Verify document
const result = await botskyc.verify(file);
// Show result to user
if (result.status === 'success') {
showSuccess(result.extractedData);
} else {
showError(result.message);
}
} finally {
setLoading(false);
}
}
Asynchronous Flow
Background processing with webhook notifications.
Best For:
- Batch processing
- Backend workflows
- High-volume processing
- Non-interactive flows
Example:
// Submit for async processing
async function submitForVerification(files) {
// Create verification job
const job = await botskyc.verify.async({
documents: files,
webhookUrl: 'https://your-app.com/webhooks'
});
// Store job ID
await db.verifications.create({
jobId: job.id,
status: 'pending',
userId: currentUser.id
});
return { jobId: job.id, status: 'processing' };
}
// Handle webhook callback
app.post('/webhooks/botskyc', async (req, res) => {
const { jobId, status, data } = req.body;
// Update database
await db.verifications.update(jobId, {
status,
result: data
});
// Notify user
await notifyUser(jobId, status);
res.sendStatus(00);
});
Hybrid Flow
Combine sync and async for optimal UX.
async function smartVerification(file) {
// Start async job
const job = await botskyc.verify.async({documents: [file]});
// Poll for quick results (first 5 seconds)
const quickResult = await pollWithTimeout(job.id, 5000);
if (quickResult) {
// Got result quickly - show immediately
return quickResult;
} else {
// Still processing - show message and use webhook
showMessage('Processing... We\'ll notify you when complete');
return { status: 'pending', jobId: job.id };
}
}
Integration Architecture Diagrams
Web Application Integration
Implementation:
// Frontend (React)
import { BotsKYCProvider, DocumentUpload } from '@botskyc/react';
function App() {
return (
<BotsKYCProvider apiEndpoint="/api/kyc">
<DocumentUpload onComplete={handleComplete} />
</BotsKYCProvider>
);
}
// Backend (Node.js)
app.post('/api/kyc/verify', authenticate, async (req, res) => {
// Proxy to botsKYC with your API key
const result = await botskyc.verify({
documents: req.files,
userId: req.user.id
});
// Store result
await db.kyc.create({
userId: req.user.id,
result
});
res.json(result);
});
Mobile Application Integration
Implementation (React Native):
import { BotsKYC } from '@botskyc/react-native';
// Capture and verify
async function captureAndVerify() {
// Take photo
const photo = await Camera.takePicture();
// Verify immediately
const result = await BotsKYC.verify({
document: photo,
onProgress: (progress) => {
updateProgress(progress);
}
});
return result;
}
Microservices Integration
Implementation:
// KYC Microservice
class KYCService {
async processVerification(userId, documents) {
// Publish to queue
await queue.publish('kyc.verification.requested', {
userId,
documents
});
}
async handleVerificationComplete(event) {
// Update user service
await userService.updateKYCStatus(
event.userId,
event.status
);
// Emit event
await queue.publish('kyc.verification.completed', event);
}
}
// Worker
queue.subscribe('kyc.verification.requested', async (msg) => {
const result = await botskyc.verify(msg.documents);
await kycService.handleVerificationComplete({
userId: msg.userId,
...result
});
});
Best Practices
1. Authentication and Security
Store API keys securely
// Use environment variables
const apiKey = process.env.BOTSKYC_API_KEY;
// Never hardcode
// const apiKey = 'sk_live_abc'; // DON'T DO THIS
Use different keys per environment
const apiKey = process.env.NODE_ENV === 'production'
? process.env.BOTSKYC_LIVE_KEY
: process.env.BOTSKYC_TEST_KEY;
Rotate keys regularly
- Rotate every 90 days
- Immediately on suspected compromise
- After team member departure
. Error Handling
Implement retry logic
async function verifyWithRetry(file, maxRetries = ) {
for (let i = 0; i < maxRetries; i++) {
try {
return await botskyc.verify(file);
} catch (error) {
if (error.status === 49) {
// Rate limited - wait and retry
await sleep(error.retryAfter * 000);
} else if (error.status >= 500) {
// Server error - exponential backoff
await sleep(Math.pow(, i) * 000);
} else {
// Client error - don't retry
throw error;
}
}
}
throw new Error('Max retries exceeded');
}
Handle all error types
try {
const result = await botskyc.verify(file);
} catch (error) {
if (error.code === 'rate_limit_exceeded') {
// Handle rate limiting
} else if (error.code === 'invalid_file_format') {
// Handle bad file
} else if (error.code === 'service_unavailable') {
// Handle outage
} else {
// Handle unexpected error
}
}
. Performance Optimization
Use appropriate batch sizes
// Good: Process in optimal batches
const batchSize = 0;
for (let i = 0; i < documents.length; i += batchSize) {
const batch = documents.slice(i, i + batchSize);
await botskyc.verify(batch);
}
// Bad: One at a time
for (const doc of documents) {
await botskyc.verify(doc); // Slow
}
Implement caching
const cache = new Map();
async function verifyWithCache(fileHash) {
// Check cache
if (cache.has(fileHash)) {
return cache.get(fileHash);
}
// Verify
const result = await botskyc.verify(file);
// Cache result
cache.set(fileHash, result);
return result;
}
Use async for batch
// Use async mode for large batches
const job = await botskyc.verify.async({
documents: largeBatch,
webhookUrl: 'https://your-app.com/webhook'
});
4. Monitoring and Observability
Log all API calls
async function verifyWithLogging(file) {
const startTime = Date.now();
try {
const result = await botskyc.verify(file);
logger.info('Verification successful', {
duration: Date.now() - startTime,
status: result.status,
confidence: result.confidence
});
return result;
} catch (error) {
logger.error('Verification failed', {
duration: Date.now() - startTime,
error: error.message,
code: error.code
});
throw error;
}
}
Track metrics
metrics.increment('botskyc.verify.requests');
metrics.timing('botskyc.verify.duration', duration);
metrics.gauge('botskyc.verify.success_rate', successRate);
Integration Checklist
Pre-Integration
- Obtain API credentials
- Review documentation
- Understand rate limits
- Choose integration pattern
- Setup development environment
Development
- Implement authentication
- Add error handling
- Implement retry logic
- Add logging
- Write tests
- Handle webhooks (if using)
Testing
- Test with sample documents
- Test error scenarios
- Test rate limiting
- Load testing
- Security testing
Production
- Use production API keys
- Enable monitoring
- Setup alerts
- Document integration
- Train support team
Support and Resources
Documentation
- API Reference - Complete API documentation
- Quick Start - Get started quickly
- Security Guide - Security best practices
SDKs and Tools
Support
- Email: support@botskyc.com
- Response Time: < hour for urgent issues
- Documentation: Comprehensive guides and examples