Working Code

Integration Examples

Real-world examples showing how to integrate okID verification into different types of applications.

JavaScript SDK Examples

Hotel Check-in System

Popular

Streamline guest verification for faster, secure check-in processes.

HTML Integration:

<script src="verification-sdk.js"></script>
<script>
  const hotelSDK = new VerificationSDK({
    baseUrl: 'https://verify.test.okid.io',
    onSuccess: function(data) {
      updateGuestStatus(data.verification_id, 'verified');
      redirectToRoomAssignment();
    },
    onError: function(error) {
      showGuestError('Verification failed. Please try again.');
    }
  });
  
  async function startGuestVerification() {
    const response = await fetch('/api/generate-verification', {
      method: 'POST'
    });
    const { verification_id } = await response.json();
    hotelSDK.openWithVerificationId(verification_id);
  }
</script>

E-commerce Age Verification

Age Restricted

Verify customer age for restricted products and account protection.

E-commerce Integration:

const ecommerceSDK = new VerificationSDK({
  baseUrl: 'https://verify.test.okid.io',
  onSuccess: function(data) {
    enableRestrictedProducts(data.user_id);
    updateCustomerProfile(data.user_id, 'age_verified');
    showSuccessMessage('Age verification completed!');
  },
  onError: function(error) {
    showAgeVerificationError(error.message);
  }
});

function verifyCustomerAge() {
  document.getElementById('age-gate').style.display = 'block';
  ecommerceSDK.startDirectVerification();
}

Banking KYC Onboarding

Compliance

Secure customer onboarding with KYC compliance requirements.

Banking Integration:

const bankingSDK = new VerificationSDK({
  baseUrl: 'https://verify.test.okid.io',
  onSuccess: function(data) {
    completeKYCProcess(data.user_id, data.verification_id);
    enableBankingFeatures(data.user_id);
    sendWelcomeEmail(data.user_id);
  },
  onError: function(error) {
    logKYCFailure(error);
    showKYCRetryOptions();
  }
});

async function startKYCVerification(customerId) {
  try {
    const response = await fetch('/api/banking/kyc-verification', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ customer_id: customerId })
    });
    const { verification_id } = await response.json();
    bankingSDK.openWithVerificationId(verification_id);
  } catch (error) {
    handleKYCError(error);
  }
}

Server-Side Examples

Node.js/Express

Popular
const express = require('express');
const app = express();

// Configure v2client
const config = {
  apiKey: process.env.API_KEY,
  baseUrl: process.env.V2CLIENT_BASE_URL || 'https://verify.test.okid.io'
};

// Save configuration to v2client
app.post('/setup', async (req, res) => {
  await fetch(`${config.baseUrl}/api/save-config`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(config)
  });
  res.json({ success: true });
});

// Generate verification endpoint
app.post('/api/generate-verification', async (req, res) => {
  try {
    const response = await fetch(`${config.baseUrl}/api/generate-verification`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    });
    const data = await response.json();
    res.json({ verification_id: data.verificationId });
  } catch (error) {
    res.status(500).json({ error: 'Failed to generate verification' });
  }
});

Next.js API Routes

React
// pages/api/generate-verification.js
import { NextResponse } from 'next/server';

export async function POST(request) {
  try {
    const V2CLIENT_BASE_URL = process.env.V2CLIENT_BASE_URL;
    
    const response = await fetch(`${V2CLIENT_BASE_URL}/api/generate-verification`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    });
    
    if (!response.ok) {
      throw new Error('Failed to generate verification');
    }
    
    const data = await response.json();
    return NextResponse.json({ 
      verification_id: data.verificationId,
      expires_at: data.expiresAt 
    });
  } catch (error) {
    return NextResponse.json(
      { error: 'Server error' }, 
      { status: 500 }
    );
  }
}

Python/Flask

Python
from flask import Flask, request, jsonify
import requests
import os

app = Flask(__name__)

# Configuration
V2CLIENT_BASE_URL = os.getenv('V2CLIENT_BASE_URL', 'https://verify.test.okid.io')
API_KEY = os.getenv('API_KEY')

@app.route('/api/generate-verification', methods=['POST'])
def generate_verification():
    try:
        # Call v2client to generate verification
        response = requests.post(
            f'{V2CLIENT_BASE_URL}/api/generate-verification',
            headers={'Content-Type': 'application/json'}
        )
        
        if response.status_code != 200:
            raise Exception('Failed to generate verification')
        
        data = response.json()
        return jsonify({
            'verification_id': data['verificationId'],
            'expires_at': data.get('expiresAt')
        })
    
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)

PHP

PHP
<?php
// generate-verification.php
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$baseUrl = getenv('V2CLIENT_BASE_URL') ?: 'https://verify.test.okid.io';

$postData = json_encode(['locale' => 'en']);

$context = stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => 'Content-Type: application/json',
        'content' => $postData
    ]
]);

try {
    $response = file_get_contents($baseUrl . '/api/generate-verification', false, $context);
    
    if ($response === false) {
        throw new Exception('API request failed');
    }
    
    $data = json_decode($response, true);
    
    echo json_encode([
        'verification_id' => $data['verificationId'],
        'expires_at' => $data['expiresAt'] ?? null
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
}
?>

Error Handling Examples

Comprehensive Error Handling

class VerificationErrorHandler {
  constructor() {
    this.retryCount = 0;
    this.maxRetries = 3;
  }
  
  async handleError(error, context) {
    const errorMap = {
      'NETWORK_ERROR': 'Connection lost. Please check your internet.',
      'VERIFICATION_EXPIRED': 'Session expired. Starting fresh verification.',
      'INVALID_DOCUMENT': 'Document not recognized. Please try another.',
      'CAMERA_DENIED': 'Camera access required for verification.',
      'USER_CANCELLED': 'Verification cancelled by user.'
    };
    
    const userMessage = errorMap[error.code] || 'Verification failed. Please try again.';
    
    // Log error for debugging
    console.error('Verification error:', {
      code: error.code,
      message: error.message,
      context: context,
      timestamp: new Date().toISOString()
    });
    
    // Show user-friendly message
    this.showErrorMessage(userMessage);
    
    // Determine if retry is possible
    if (this.shouldRetry(error.code)) {
      this.showRetryOption(context);
    } else {
      this.showAlternativeOptions();
    }
  }
  
  shouldRetry(errorCode) {
    const retryableErrors = ['NETWORK_ERROR', 'VERIFICATION_EXPIRED'];
    return retryableErrors.includes(errorCode) && this.retryCount < this.maxRetries;
  }
  
  async retry(context) {
    this.retryCount++;
    await new Promise(resolve => setTimeout(resolve, 1000 * this.retryCount));
    
    try {
      await context.startVerification();
    } catch (error) {
      this.handleError(error, context);
    }
  }
}

User-Friendly Error Messages

function showUserFriendlyError(error) {
  const errorUI = {
    'NETWORK_ERROR': {
      title: 'Connection Problem',
      message: 'Please check your internet connection and try again.',
      icon: '🌐',
      actions: ['Retry', 'Help']
    },
    'CAMERA_DENIED': {
      title: 'Camera Access Needed',
      message: 'Please allow camera access to continue with verification.',
      icon: '📷',
      actions: ['Grant Access', 'Help']
    },
    'DOCUMENT_INVALID': {
      title: 'Document Not Recognized',
      message: 'Please ensure your document is clear and try again.',
      icon: '📄',
      actions: ['Try Again', 'Use Different Document']
    }
  };
  
  const config = errorUI[error.code] || {
    title: 'Verification Error',
    message: 'Something went wrong. Please try again.',
    icon: '⚠️',
    actions: ['Try Again', 'Contact Support']
  };
  
  displayErrorModal(config);
}

Download Complete Examples

Get the complete source code for all examples, including HTML, CSS, and JavaScript files.

📦 SDK Integration Examples

Complete working examples with HTML, CSS, and JavaScript

🔧 Server Examples

Ready-to-use server implementations in multiple languages