KYC Overview
KYC Features
Additional features that can be used together with basic identity verification functions. To consult regarding these features:
- Some of these features might need change in contract, so if you consider activating them - contact sales@idenfy.com
- If you already have the feature, but have questions or problems integrating - contact techsupport

Identity Verification Solution
- Verify 3000+ global ID documents automatically.
- Prevent fraud using biometrics and 3D liveness.
- Boost accuracy with 24/7 expert human review.
- Choose flexible pricing (pay per approved/completed).
- Ensure compliance with secure, customizable, scalable flows.
Locals & Document types
Documents
Physical Documents
DRIVER_LICENSE
- Driver LicenseRESIDENCE_PERMIT
- Residence PermitID_CARD
- ID CardPASSPORT
- PassportNATIONAL_PASSPORT
- National PassportVISA
- VisaPROVISIONAL_DRIVER_LICENSE
- Provisional Driver LicensePAN_CARD
- Pan CardOLD_ID_CARD
- Old ID CardMILITARY_CARD
- Military CardADDRESS_CARD
- Address CardAADHAAR
- Aadhaar
Digital IDs and Verification Systems
SMART_ID
- Smart IDCLEAR
- CLEARONE_ID
- OneIDBANK_ID_SE
- BankID (Sweden)BANK_ID_NO
- BankID (Norway)BANK_ID_CZ
- Bank ID (Czech Republic)FTN
- Finnish Trust Network (FTN)MIT_ID
- MitIDVERIMI
- VerimiSPID
- SPID
Locales
Supported locales
LT
- LithuanianEN
- EnglishPL
- PolishRU
- RussianLV
- LatvianIT
- ItalianDE
- GermanFR
- FrenchSV
- SwedishET
- EstonianES
- SpanishHU
- HungarianJA
- JapaneseBG
- BulgarianRO
- RomanianCS
- CzechNL
- DutchPT
- PortugueseUK
- UkrainianVI
- VietnameseSK
- SlovakID
- IndonesianTH
- ThaiHI
- HindiDA
- DanishEL
- GreekHR
- CroatianNO
- NorwegianSR
- SerbianFI
- FinnishTR
- TurkishZH
- ChineseSI
- Slovenian
Quick start
For a quick start and to see KYC integration, below you can find sequences of code for different languages.
know your language
Keep in mind, that different languages might require a bit different approach, dependency and package handling.
- Python - Django
- Python - Flask
- Java - Springboot
- C#
- Rust
- Javascript
- Ruby
- Php
- Curl
# This is a minimal Django setup for a quick iDenfy test.
# It assumes you have a Django project and an app.
# Place the views content in your app's views.py
# Place the urls content in your project's urls.py
# my_app/views.py
# -------------------------------------------------
import requests
from django.http import HttpRequest, HttpResponse, HttpResponseServerError
from django.shortcuts import redirect
# Hardcoded values for a quick test.
# In a real app, manage these securely (e.g., environment variables, Django settings).
MY_API_KEY = 'YOUR_API_KEY' # Replace with your actual API key
MY_API_SECRET = 'YOUR_API_SECRET' # Replace with your actual API secret
IDENFY_GENERATE_TOKEN_URL = 'https://ivs.idenfy.com/api/v2/token'
IDENFY_REDIRECT_URL = 'https://ivs.idenfy.com/api/v2/redirect'
def create_minimal_identification_token() -> str | None:
"""
Minimal function to create an iDenfy identification token.
"""
try:
payload = {"clientId": "your_client_id_from_idenfy"} # Replace with your iDenfy client ID
response = requests.post(
url=IDENFY_GENERATE_TOKEN_URL,
json=payload,
auth=(MY_API_KEY, MY_API_SECRET),
timeout=10
)
response.raise_for_status()
response_data = response.json()
return response_data.get('authToken')
except Exception as e:
print(f"Error creating token: {e}") # Basic error logging to console
return None
def minimal_launch_identification_view(request: HttpRequest) -> HttpResponse:
"""
Minimal view to generate a token and redirect.
"""
auth_token = create_minimal_identification_token()
if auth_token:
redirect_url_with_token = f"{IDENFY_REDIRECT_URL}?authToken={auth_token}"
return redirect(redirect_url_with_token)
else:
return HttpResponseServerError("Failed to generate iDenfy token.")
# -------------------------------------------------
# my_project/urls.py
# -------------------------------------------------
# from django.contrib import admin # Optional, if you use admin
from django.urls import path
# Assuming your views.py is in an app named 'my_app'
# from my_app import views as my_app_views
# For simplicity, if you were to put views.py in the same directory as project urls.py (not standard):
from .views import minimal_launch_identification_view # Adjust import based on your structure
urlpatterns = [
# path('admin/', admin.site.urls), # Optional
# This makes the view accessible at /idenfy-test/
path('idenfy-test/', minimal_launch_identification_view, name='minimal_idenfy_launch'),
]
# -------------------------------------------------
# To run (assuming 'my_project' and 'my_app' are set up):
# 1. Replace 'YOUR_API_KEY', 'YOUR_API_SECRET', and 'your_client_id_from_idenfy'.
# 2. Ensure 'requests' is installed (pip install requests django).
# 3. Add 'my_app' to INSTALLED_APPS in your project's settings.py.
# 4. Run: python manage.py runserver
# 5. Access: http://127.0.0.1:8000/idenfy-test/
# We are using this library to send HTTP requests.
import requests
# For this example we are using python Flask web-development framework.
from flask import Flask, redirect
# Init framework.
app = Flask(**name**)
# Your iDenfy account has an api key and api secret (credentials were provided for you by email).
MY_API_KEY = 'API_KEY'
MY_API_SECRET = 'API_SECRET'
# Endpoint to call when generating verification token.
IDENFY_GENERATE_TOKEN_URL = 'https://ivs.idenfy.com/api/v2/token'
# Endpoint to redirect a user to with a generated token.
IDENFY_REDIRECT_URL = 'https://ivs.idenfy.com/api/v2/redirect'
# When a user comes to https://your-website/idenfy/kyc - he will be redirected to iDenfy platform.
@app.route('/idenfy/kyc')
def launch_identification() -> str:
return redirect_to_idenfy()
def create_identification_token() -> str: # Create a verification token for your customer by sending a HTTP POST request to iDenfy platform.
response = requests.post(
url=IDENFY_GENERATE_TOKEN_URL,
json=dict(clientId=1),
auth=(MY_API_KEY, MY_API_SECRET)
)
response = response.json()
return response['authToken']
def redirect_to_idenfy(): # Redirect user to iDenfy platform with a newly generated verification token.
return redirect(f'{IDENFY_REDIRECT_URL}?authToken={create_identification_token()}', code=301)
if **name** == '**main**':
app.run(host='127.0.0.1', port=10000)
package com.example.idenfydemo;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.RedirectView;
import jakarta.servlet.http.HttpServletResponse; // For Spring Boot 3+
// For Spring Boot 2.x, use: import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
@SpringBootApplication
public class IdenfyDemoSingleFileApplication {
private static final Logger loggerApp = LoggerFactory.getLogger(IdenfyDemoSingleFileApplication.class);
// --- Configuration (Hardcoded for single-file simplicity) ---
// In a real Spring Boot app, these would be in application.properties
private static final String MY_API_KEY = "YOUR_API_KEY"; // Replace
private static final String MY_API_SECRET = "YOUR_API_SECRET"; // Replace
private static final String IDENFY_GENERATE_TOKEN_URL = "https://ivs.idenfy.com/api/v2/token";
private static final String IDENFY_REDIRECT_URL = "https://ivs.idenfy.com/api/v2/redirect";
private static final String YOUR_CLIENT_ID_FROM_IDENFY = "your_client_id_from_idenfy"; // Replace
// --- End Configuration ---
// Define beans for inner classes if needed, or rely on @Component scanning for static inner classes
// Spring Boot should pick up static inner classes annotated with @Component, @Service, @Controller
@Component
public static class IdenfyHardcodedProperties {
public String getApiKey() { return MY_API_KEY; }
public String getApiSecret() { return MY_API_SECRET; }
public String getGenerateTokenUrl() { return IDENFY_GENERATE_TOKEN_URL; }
public String getRedirectUrl() { return IDENFY_REDIRECT_URL; }
public String getClientId() { return YOUR_CLIENT_ID_FROM_IDENFY; }
}
@Service
public static class IdenfyTokenService {
private static final Logger logger = LoggerFactory.getLogger(IdenfyTokenService.class);
private final IdenfyHardcodedProperties idenfyProperties;
private final HttpClient httpClient;
public IdenfyTokenService(IdenfyHardcodedProperties idenfyProperties) {
this.idenfyProperties = idenfyProperties;
this.httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
}
public String createIdentificationToken() {
JSONObject payload = new JSONObject();
payload.put("clientId", idenfyProperties.getClientId());
// e.g., payload.put("scanRef", "someUniqueUserReference");
String auth = idenfyProperties.getApiKey() + ":" + idenfyProperties.getApiSecret();
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
String authHeader = "Basic " + encodedAuth;
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(idenfyProperties.getGenerateTokenUrl()))
.header("Content-Type", "application/json")
.header("Authorization", authHeader)
.POST(HttpRequest.BodyPublishers.ofString(payload.toString()))
.build();
try {
logger.info("Requesting iDenfy token from: {}", idenfyProperties.getGenerateTokenUrl());
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 200 && response.statusCode() < 300) {
logger.info("Received successful response from iDenfy token endpoint.");
JSONObject jsonResponse = new JSONObject(response.body());
if (jsonResponse.has("authToken")) {
String token = jsonResponse.getString("authToken");
logger.info("Auth token successfully retrieved.");
return token;
} else {
logger.error("Error: 'authToken' not found in iDenfy response. Body: {}", response.body());
return null;
}
} else {
logger.error("Error creating token. Status: {}, Body: {}", response.statusCode(), response.body());
return null;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("Request interrupted: {}", e.getMessage(), e);
return null;
} catch (JSONException e) {
logger.error("Error parsing JSON response: {}", e.getMessage(), e);
return null;
} catch (IOException e) {
logger.error("IO Exception during HTTP request: {}", e.getMessage(), e);
return null;
} catch (Exception e) {
logger.error("Generic error creating token: {}", e.getMessage(), e);
return null;
}
}
}
@Controller
public static class IdenfyController {
private static final Logger logger = LoggerFactory.getLogger(IdenfyController.class);
private final IdenfyTokenService idenfyTokenService;
private final IdenfyHardcodedProperties idenfyProperties;
public IdenfyController(IdenfyTokenService idenfyTokenService, IdenfyHardcodedProperties idenfyProperties) {
this.idenfyTokenService = idenfyTokenService;
this.idenfyProperties = idenfyProperties;
}
@GetMapping("/idenfy-test-spring-singlefile")
public RedirectView launchIdentification(HttpServletResponse httpServletResponse) {
logger.info("Received request for /idenfy-test-spring-singlefile");
String authToken = idenfyTokenService.createIdentificationToken();
if (authToken != null) {
String redirectUrlWithToken = idenfyProperties.getRedirectUrl() + "?authToken=" + authToken;
logger.info("Redirecting to: {}", redirectUrlWithToken);
RedirectView redirectView = new RedirectView(redirectUrlWithToken);
redirectView.setStatusCode(org.springframework.http.HttpStatus.FOUND); // 302
return redirectView;
} else {
logger.error("Failed to generate iDenfy token. Cannot redirect.");
RedirectView errorRedirect = new RedirectView("/idenfy-error-page-singlefile");
errorRedirect.setStatusCode(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR);
return errorRedirect;
}
}
@GetMapping("/idenfy-error-page-singlefile")
@ResponseBody
public String idenfyError() {
return "<html><body><h1>Error Generating iDenfy Token</h1><p>Sorry, we could not start the identification process. Please try again later.</p></body></html>";
}
@GetMapping("/singlefile")
@ResponseBody
public String home() {
return "Minimal iDenfy Spring Boot Single File Test App is running. Try /idenfy-test-spring-singlefile";
}
}
public static void main(String[] args) {
loggerApp.info("Starting Spring Boot Single File Application...");
// You might need to explicitly tell Spring where to scan for components if they are not picked up automatically.
// However, static inner classes annotated with @Component, @Service, @Controller in the main app class
// are usually picked up by Spring Boot's default component scan.
SpringApplication.run(IdenfyDemoSingleFileApplication.class, args);
loggerApp.info("Spring Boot Single File Application started. Access at http://localhost:8080/singlefile or http://localhost:8080/idenfy-test-spring-singlefile");
}
}
// C# - Using .NET 6+ minimal APIs and HttpClient
// Add to your .csproj:
// <ItemGroup>
// <FrameworkReference Include="Microsoft.AspNetCore.App" />
// </ItemGroup>
// Also, ensure you have a JSON library, e.g., System.Text.Json (built-in)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// --- iDenfy Configuration ---
const string MY_API_KEY = "YOUR_API_KEY"; // Replace
const string MY_API_SECRET = "YOUR_API_SECRET"; // Replace
const string IDENFY_GENERATE_TOKEN_URL = "https://ivs.idenfy.com/api/v2/token";
const string IDENFY_REDIRECT_URL = "https://ivs.idenfy.com/api/v2/redirect";
const string YOUR_CLIENT_ID_FROM_IDENFY = "your_client_id_from_idenfy"; // Replace
// --- End iDenfy Configuration ---
async Task<string?> CreateIdenfyTokenAsync()
{
using var httpClient = new HttpClient();
var payload = new { clientId = YOUR_CLIENT_ID_FROM_IDENFY };
var jsonPayload = JsonSerializer.Serialize(payload);
var httpContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
var authToken = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{MY_API_KEY}:{MY_API_SECRET}"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authToken);
try
{
var response = await httpClient.PostAsync(IDENFY_GENERATE_TOKEN_URL, httpContent);
response.EnsureSuccessStatusCode(); // Throws if not 2xx
var responseBody = await response.Content.ReadAsStringAsync();
using var jsonDoc = JsonDocument.Parse(responseBody);
return jsonDoc.RootElement.TryGetProperty("authToken", out var tokenElement) ? tokenElement.GetString() : null;
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
return null;
}
catch (JsonException e)
{
Console.WriteLine($"JSON parsing error: {e.Message}");
return null;
}
}
app.MapGet("/idenfy-test-csharp", async (HttpContext context) =>
{
var token = await CreateIdenfyTokenAsync();
if (!string.IsNullOrEmpty(token))
{
context.Response.Redirect($"{IDENFY_REDIRECT_URL}?authToken={token}");
}
else
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync("Failed to generate iDenfy token.");
}
});
Console.WriteLine("C# minimal API server running on http://localhost:5000 (or https://localhost:5001)");
Console.WriteLine("Access iDenfy test at: /idenfy-test-csharp");
app.Run();
// Rust - Using reqwest for HTTP and serde for JSON
// Add to your Cargo.toml:
// [dependencies]
// reqwest = { version = "0.11", features = ["json", "blocking"] } // Use "blocking" for simplicity here
// serde = { version = "1.0", features = ["derive"] }
// serde_json = "1.0"
// tokio = { version = "1", features = ["macros", "rt-multi-thread"] } // For async main if not using blocking
use reqwest::blocking::Client; // For simplicity, using blocking client
use reqwest::header::{HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::fmt;
// --- iDenfy Configuration ---
const MY_API_KEY: &str = "YOUR_API_KEY"; // Replace
const MY_API_SECRET: &str = "YOUR_API_SECRET"; // Replace
const IDENFY_GENERATE_TOKEN_URL: &str = "[https://ivs.idenfy.com/api/v2/token](https://ivs.idenfy.com/api/v2/token)";
const IDENFY_REDIRECT_URL: &str = "[https://ivs.idenfy.com/api/v2/redirect](https://ivs.idenfy.com/api/v2/redirect)";
const YOUR_CLIENT_ID_FROM_IDENFY: &str = "your_client_id_from_idenfy"; // Replace
// --- End iDenfy Configuration ---
#[derive(Serialize)]
struct TokenRequestPayload<'a> {
#[serde(rename = "clientId")]
client_id: &'a str,
}
#[derive(Deserialize, Debug)]
struct TokenResponse {
#[serde(rename = "authToken")]
auth_token: String,
// Add other fields if needed, e.g., expiresIn
}
#[derive(Debug)]
struct AppError(String);
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Error for AppError {}
fn create_idenfy_token() -> Result<String, Box<dyn Error>> {
let client = Client::new();
let payload = TokenRequestPayload {
client_id: YOUR_CLIENT_ID_FROM_IDENFY,
};
let auth_string = format!("{}:{}", MY_API_KEY, MY_API_SECRET);
let encoded_auth = base64::encode(auth_string);
let auth_header_value = format!("Basic {}", encoded_auth);
let response = client
.post(IDENFY_GENERATE_TOKEN_URL)
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
.header(AUTHORIZATION, HeaderValue::from_str(&auth_header_value)?)
.json(&payload)
.send()?;
if response.status().is_success() {
let token_response: TokenResponse = response.json()?;
Ok(token_response.auth_token)
} else {
let error_body = response.text()?;
Err(Box::new(AppError(format!(
"Failed to generate token. Status: {}, Body: {}",
response.status(),
error_body
))))
}
}
// A full web server in Rust (e.g. with Actix or Axum) is more involved for a "minimal" example.
// This main function demonstrates token generation and constructing the redirect URL.
fn main() {
println!("Attempting to generate iDenfy token...");
match create_idenfy_token() {
Ok(token) => {
let redirect_url = format!("{}?authToken={}", IDENFY_REDIRECT_URL, token);
println!("Successfully generated token.");
println!("Redirect URL: {}", redirect_url);
// In a web server context, you would redirect the user to this URL.
}
Err(e) => {
eprintln!("Error: {}", e);
}
}
}
// To run:
// 1. Ensure you have Rust installed.
// 2. Add dependencies to Cargo.toml (reqwest, serde, serde_json, base64).
// `base64 = "0.13"` (or a newer version)
// 3. Replace placeholder API keys and client ID.
// 4. `cargo run`
// JavaScript (Node.js) - Using built-in https module or a library like 'axios'
// To run: node script_name.js
// If using axios: npm install axios express
const http = require('http'); // Or 'https' for actual HTTPS calls
const https = require('https'); // For iDenfy API call
const { URL } = require('url'); // For parsing redirect URL parts if needed
// --- iDenfy Configuration ---
const MY_API_KEY = 'YOUR_API_KEY'; // Replace
const MY_API_SECRET = 'YOUR_API_SECRET'; // Replace
const IDENFY_GENERATE_TOKEN_URL = 'https://ivs.idenfy.com/api/v2/token';
const IDENFY_REDIRECT_URL = 'https://ivs.idenfy.com/api/v2/redirect';
const YOUR_CLIENT_ID_FROM_IDENFY = 'your_client_id_from_idenfy'; // Replace
// --- End iDenfy Configuration ---
function createIdenfyToken() {
return new Promise((resolve, reject) => {
const payload = JSON.stringify({
clientId: YOUR_CLIENT_ID_FROM_IDENFY,
});
const auth = 'Basic ' + Buffer.from(MY_API_KEY + ':' + MY_API_SECRET).toString('base64');
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload),
Authorization: auth,
},
};
const req = https.request(IDENFY_GENERATE_TOKEN_URL, options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
try {
const responseJson = JSON.parse(data);
if (responseJson.authToken) {
resolve(responseJson.authToken);
} else {
reject(new Error('authToken not found in response: ' + data));
}
} catch (e) {
reject(new Error('Failed to parse JSON response: ' + e.message));
}
} else {
reject(new Error(`Failed to get token. Status: ${res.statusCode}, Body: ${data}`));
}
});
});
req.on('error', (e) => {
reject(new Error('Problem with request: ' + e.message));
});
req.write(payload);
req.end();
});
}
// Minimal HTTP server to demonstrate redirect
const server = http.createServer(async (req, res) => {
if (req.url === '/idenfy-test-node') {
try {
const token = await createIdenfyToken();
if (token) {
const redirectUrl = `${IDENFY_REDIRECT_URL}?authToken=${token}`;
res.writeHead(302, { Location: redirectUrl });
res.end('Redirecting to iDenfy...');
} else {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Failed to generate iDenfy token.');
}
} catch (error) {
console.error('Server error:', error.message);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal server error: ' + error.message);
}
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found. Try /idenfy-test-node');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Node.js server running on http://localhost:${PORT}`);
console.log(`Access iDenfy test at: /idenfy-test-node`);
});
# Ruby - Using net/http and json standard libraries
# You might want to use a gem like 'httparty' or 'faraday' for more complex scenarios.
# To run: ruby script_name.rb
# If you want a web server, you might use Sinatra or Rails. This example uses 'webrick' for simplicity.
require 'net/http'
require 'uri'
require 'json'
require 'base64'
require 'webrick' # For a minimal web server
# --- iDenfy Configuration ---
MY_API_KEY = 'YOUR_API_KEY' # Replace
MY_API_SECRET = 'YOUR_API_SECRET' # Replace
IDENFY_GENERATE_TOKEN_URL = '[https://ivs.idenfy.com/api/v2/token](https://ivs.idenfy.com/api/v2/token)'
IDENFY_REDIRECT_URL = '[https://ivs.idenfy.com/api/v2/redirect](https://ivs.idenfy.com/api/v2/redirect)'
YOUR_CLIENT_ID_FROM_IDENFY = 'your_client_id_from_idenfy' # Replace
# --- End iDenfy Configuration ---
def create_idenfy_token
uri = URI.parse(IDENFY_GENERATE_TOKEN_URL)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == 'https')
request = Net::HTTP::Post.new(uri.request_uri)
request.content_type = 'application/json'
request.basic_auth(MY_API_KEY, MY_API_SECRET)
payload = { clientId: YOUR_CLIENT_ID_FROM_IDENFY }
request.body = payload.to_json
begin
response = http.request(request)
if response.is_a?(Net::HTTPSuccess)
json_response = JSON.parse(response.body)
return json_response['authToken'] if json_response && json_response['authToken']
puts "Error: 'authToken' not found in response: #{response.body}"
nil
else
puts "Error creating token. Status: #{response.code}, Body: #{response.body}"
nil
end
rescue StandardError => e
puts "Request failed: #{e.message}"
nil
end
end
# Minimal WEBrick server
port = 8080
puts "Ruby WEBrick server starting on http://localhost:#{port}"
puts "Access iDenfy test at: /idenfy-test-ruby"
server = WEBrick::HTTPServer.new(Port: port)
server.mount_proc '/idenfy-test-ruby' do |req, res|
token = create_idenfy_token
if token
redirect_url = "#{IDENFY_REDIRECT_URL}?authToken=#{token}"
res.status = 302 # Found (Temporary Redirect)
res['Location'] = redirect_url
res.body = "Redirecting to iDenfy..."
else
res.status = 500
res.content_type = 'text/plain'
res.body = 'Failed to generate iDenfy token.'
end
end
trap('INT') { server.shutdown } # Graceful shutdown on Ctrl+C
server.start
<?php
// PHP - Using cURL extension
// Ensure cURL extension is enabled in your php.ini
// --- iDenfy Configuration ---
define('MY_API_KEY', 'YOUR_API_KEY'); // Replace
define('MY_API_SECRET', 'YOUR_API_SECRET'); // Replace
define('IDENFY_GENERATE_TOKEN_URL', 'https://ivs.idenfy.com/api/v2/token');
define('IDENFY_REDIRECT_URL', 'https://ivs.idenfy.com/api/v2/redirect');
define('YOUR_CLIENT_ID_FROM_IDENFY', 'your_client_id_from_idenfy'); // Replace
// --- End iDenfy Configuration ---
function createIdenfyToken() {
$payload = json_encode(['clientId' => YOUR_CLIENT_ID_FROM_IDENFY]);
$ch = curl_init(IDENFY_GENERATE_TOKEN_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($payload)
]);
curl_setopt($ch, CURLOPT_USERPWD, MY_API_KEY . ':' . MY_API_SECRET); // Basic Auth
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Timeout in seconds
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
error_log("cURL Error: " . $curlError);
return null;
}
if ($httpCode >= 200 && $httpCode < 300) {
$responseData = json_decode($response, true);
if (isset($responseData['authToken'])) {
return $responseData['authToken'];
} else {
error_log("Error: 'authToken' not found in iDenfy response. Body: " . $response);
return null;
}
} else {
error_log("Error creating token. Status: " . $httpCode . ", Body: " . $response);
return null;
}
}
// This part demonstrates how you might use it in a script that serves a web request.
// For a minimal server, you'd typically use PHP's built-in server for development:
// php -S localhost:8001 name_of_this_script.php
// Then access http://localhost:8001/ (or a specific path if you add routing)
// Example: if this script is accessed directly via a path like /idenfy-test-php
if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '/idenfy-test-php') !== false) {
$token = createIdenfyToken();
if ($token) {
$redirectUrl = IDENFY_REDIRECT_URL . '?authToken=' . urlencode($token);
header('Location: ' . $redirectUrl, true, 302); // 302 Found
exit("Redirecting to iDenfy...");
} else {
http_response_code(500);
exit("Failed to generate iDenfy token.");
}
} else {
// Default output if not the specific path
echo "PHP iDenfy Test Script. Try accessing /idenfy-test-php (if using PHP's built-in server and this script is the entry point).";
echo "<br>To run with PHP built-in server: php -S localhost:8001 " . __FILE__;
echo "<br>Then access http://localhost:8001/idenfy-test-php";
}
?>
# cURL - Command Line Example
# Replace placeholders directly in the command.
# 1. Define variables (optional, for clarity, or use directly)
MY_API_KEY="YOUR_API_KEY" # Replace
MY_API_SECRET="YOUR_API_SECRET" # Replace
IDENFY_GENERATE_TOKEN_URL="[https://ivs.idenfy.com/api/v2/token](https://ivs.idenfy.com/api/v2/token)"
IDENFY_REDIRECT_URL="[https://ivs.idenfy.com/api/v2/redirect](https://ivs.idenfy.com/api/v2/redirect)"
YOUR_CLIENT_ID_FROM_IDENFY="your_client_id_from_idenfy" # Replace
# 2. Make the POST request to generate the token
# The response will be JSON. You can parse it with 'jq' if installed.
echo "Attempting to generate token with cURL..."
TOKEN_RESPONSE=$(curl -s -X POST "${IDENFY_GENERATE_TOKEN_URL}" \
-H "Content-Type: application/json" \
-u "${MY_API_KEY}:${MY_API_SECRET}" \
-d "{\"clientId\": \"${YOUR_CLIENT_ID_FROM_IDENFY}\"}")
# 3. Extract authToken (using jq, or manually parse if jq is not available)
# Ensure jq is installed: sudo apt-get install jq (or brew install jq on macOS)
AUTH_TOKEN=$(echo "${TOKEN_RESPONSE}" | jq -r '.authToken')
# Check if AUTH_TOKEN was extracted successfully
if [ "$AUTH_TOKEN" != "null" ] && [ ! -z "$AUTH_TOKEN" ]; then
echo "Successfully generated authToken: ${AUTH_TOKEN}"
# 4. Construct the redirect URL
REDIRECT_URL_WITH_TOKEN="${IDENFY_REDIRECT_URL}?authToken=${AUTH_TOKEN}"
echo "Constructed Redirect URL: ${REDIRECT_URL_WITH_TOKEN}"
echo ""
echo "You would typically redirect a user's browser to this URL."
else
echo "Failed to generate or extract authToken."
echo "Raw response from iDenfy:"
echo "${TOKEN_RESPONSE}"
fi
# To run this:
# 1. Save as a .sh file (e.g., idenfy_curl_test.sh)
# 2. Make it executable: chmod +x idenfy_curl_test.sh
# 3. Replace YOUR_API_KEY, YOUR_API_SECRET, and your_client_id_from_idenfy.
# 4. Run: ./idenfy_curl_test.sh
# 5. Ensure 'jq' is installed for easy JSON parsing, or adapt the parsing method.
Overview UML
Below is high-level overview of KYC process. Depending on setup and additional features, your flow might have additional steps or skip steps.
