• About TrustVision
  • Android SDK
  • Flutter SDK
  • React Native SDK
  • iOS SDK
  • Web SDK
  • API Client Libraries
  • Integration Case Studies
  • TS eKYC/FA App
  • eKYC Platform
TrustVision API Documentation

Android v3.3.x UI Only

OVERVIEW

TrustVision SDK is the android SDK for TrustVision Engine. This document is for Clients who only use the UI of the SDK. It provides these features:

  • Refactor code: merge full and uionly in a SDK version
  • Separate the QR code scanning
  • Scan QR while capturing front card
  • Allow certain card types
  • Cache SOD NFC
  • Modify UI while reading NFC
  • Face authentication

Specifications

  • Gradle Version 7.3.3
  • Tested with Gradle Plugin for Android Studio - version 7.2.2
  • minSdkVersion 21
  • targetSdkVersion 32
  • Support Kotlin version 1.5.0 - 1.8.0

Integration Steps

1. Adding the SDK to your project

  • Get library file tv_sdk_client.zip, extract and put all files into a folder in android project. Example: folder ${project.rootDir}/repo

Note : tv_sdk_client Each client will have a SDK name. That SDK name will contain the name of the client

app
root
repo
    +--com
        +--trustvision
            +--tv_api_sdk
                +--3.x.x
                    +--tv_api_sdk-3.x.x.aar
                    +--tv_api_sdk-3.x.x.pom
                maven-metadata.xml
            +--tv_core_sdk
            +--tv_sdk_client
...
  • Add the following set of lines to the Project (top-level) build.gradle
groovy
buildscript {
    ext.kotlin_version = '1.6.21' // or any version that >= 1.5 and < 1.8

    repositories {
        maven {
            url 'https://maven.google.com'
        }
        mavenCentral()
        google()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        maven { url "https://maven.google.com" }
        maven { url "https://jitpack.io" }
        maven { url "path/to/tvsdk/folder" }  // example : maven { url "${project.rootDir}/repo" }
        ...
    }
}

Note : If your project uses the new way to define repositories (central declaration of repositories), you must change repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) to repositoriesMode.set(RepositoriesMode.PREFER_PROJECT)

groovy
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.PREFER_PROJECT)
    repositories {
        google()
        mavenCentral()
    }
}
  • Add the following set of lines to your app/build.gradle
groovy
android {
    ...
    aaptOptions {
        noCompress "tflite"
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation('com.trustvision:tv_sdk_client:3.x.x@aar') {
        transitive = true
    }
    testImplementation 'junit:junit:4.12'

}

2. Initialize and config SDK

2.0. Initialize SDK

To initialize the SDK, add the following lines to your app, and it needs to be completed successfully before calling any other SDK functionalities.

kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    TrustVisionSDK.init(context, jsonConfigurationByServer, languageCode, object : TVInitializeListener {
        override fun onInitSuccess(result: TVInitResult) {
            super.onInitSuccess(result)
        }

        override fun onInitError(error: TVDetectionError) {

        }
    })
}

Please note: The SDK requires Camera permissions to capture images. Camera permissions will be handled by the SDK if not already handled by the app.

where:

  • jsonConfigurationByServer: String. The jsonConfigurationByServer is optional but recommended. It's the setting specialized for each client from TS server. It's the response json string get by API https://ekyc.trustingsocial.com/api-reference/customer-api/#get-client-settings. When it's null or unmatched with the expected type then the default setting in the SDK will be used.
  • languageCode: String the code of the language that will show and sound to user. E.g Vietnamese (vi), English ( en).

2.1. Config

2.1.0 Language code

2.1.0.0 Get supported language codes list
Kotlin
TrustVisionSdk.supportedLanguages
2.1.1.1

Allow user to change the sdk language after initialization

Kotlin
TrustVisionSdk.changeLanguageCode(languageCode)

wherer:

  • languageCode:String the code of the language that will show and sound to user. E.g Vietnamese (vi), English ( en).

2.2. Dynamic feature

2.2.0 Prerequisites

Need to have background of Dynamic Feature. Practice guideline reference

2.2.1 Configuration

Add placeholder placeholder_missing_resources.xml for missing resources, these values will be override from SDK:

xml
<resources>
    <string name="tv_title_activity_main" />
    <integer name="google_play_services_version">1</integer>
    <style name="tvAppTheme.NoActionBar" parent="AppTheme.NoActionBar" />
</resources>

Please execute this code before starting SDK if we're using Dynamic Feature in host app

kotlin
TrustVisionSDK.installDynamicFeature {
    // We often execute this code to install some necessary resources for dynamic feature
    SplitCompat.installActivity(it)
}

3. Start the SDK

The SDK provides some built in Activities example activity to capture id, selfie, liveness...

3.0. Capture the ID

The id capturing activity will show the camera to capture image, preview the image. To start the id capturing activity.

3.0.1. Set config parameters

Kotlin
val builder = TVIDConfiguration.Builder()
    .setCardTypes(selectedCards)
    .setCardSide(TVSDKConfiguration.TVCardSide.FRONT)
    .setReadBothSide(false)
    .setEnableSound(false)
    .setEnablePhotoGalleryPicker(false)
    .setEnableTiltChecking(false)
    .setSkipConfirmScreen(false)
    .setEnableScanNFC(true)
    .setEnableScanQr(true)

val configuration = builder.build()

Options:

  • setCardTypes: List<TVCardType>. List of supported cards can be found by TrustVisionSDK.cardTypes after you initialize the SDK with the jsonConfigurationByServer. If not, use :
Kotlin
listOf(
    TVCardType(
        "vn.national_id",
        "CMND cũ / CMND mới / CCCD",
        true,
        TVCardType.TVCardOrientation.HORIZONTAL
    )
)
  • setCardSide: TVCardSide. Card side to capture.
  • setReadBothSide boolean. If true then the sdk will capture both side if possible; otherwise, then the card side defined in cardSide will be used.
  • setEnableSound: boolean. Sound should be played or not.
  • setEnablePhotoGalleryPicker: boolean. Allow user select id card image from phone gallery.
  • setEnableTiltChecking: boolean. Check if the phone is parallel to the ground before taking the id card photo or not.
  • setSkipConfirmScreen: boolean. Control whether the SDK should skip the confirmation screen.
  • setEnableScanNFC: boolean. scan NFC chip of the id card or not.
  • setEnableScanQr: boolean. scan QR code of the id card or not.

3.0.2. Start id capturing activity from configuration

Kotlin
TrustVisionSDK.startIDCapturing(activity, configuration, object : TVCapturingCallBack() {
    override fun onNewFrameBatch(frameBatch: FrameBatch) {

    }
    override fun onError(error: TVDetectionError) {

    }
    override fun onSuccess(result: TVDetectionResult) {

    }
    override fun onCanceled() {

    }
    override fun readIdCardNumber(image: TVImageClass): String? {

    }
})

where:

  • activity: is the current Activity being displayed
  • configuration: the configuration would like to pass to id capturing activity
  • callback: is an object of type TVCapturingCallBack . It is an interface that has 3 methods
    • onNewFrameBatch: NewFrameBatchCallback. can be called multiple times during the capturing to return frame data.
      • frameBatch: FrameBatch
        • getId(): String. batch id generated by TV SDK
        • getFrames(): List<TVFrameClass>. batch frame to push
        • getMetadata(): Map<String, String>. batch metadata to push
        • getValidVideoIds() Set<String>. For debugging purpose only
    • onSuccess method that will be called in case of success. The onSuccess method has one parameter.
      • result : TVDetectionResult. has the following methods:
        • getFrontCardImage(): TVImageClass
        • getBackCardImage(): TVImageClass
        • getFrontIdQr(): TVCardQr
        • getBackIdQr(): TVCardQr
        • getNfcInfoResult()
    • onError: ErrorCallback. Will be called when an error has occurred during the capturing.
      • error: TVDetectionError
    • onCanceled: CancellationCallback. Will be called when the journey has been cancelled (e.g user clicked on back button...)
    • readIdCardNumber: method that will be called in case of scan NFC to read SDK Id number from the image. The readIdCardNumber method has a parameter and return a string which is the id number of the card.
      • image: TVImageClass. image of back id card

3.0.3. Handle onNewFrameBatch callback

With each batch that returned by onNewFrameBatch(FrameBatch) callback, call the below api to upload the data to server, and store the frame batch id that responses from the API, keep it corresponding with frameBatch.getId() - local id https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-frame-batch

For example:

Kotlin
// this dictionary will be used for ID Tampering Verification
val frontCardFrameBatchIdsDictionary: MutableMap<String, String> = mutableMapOf()
val backCardFrameBatchIdsDictionary: MutableMap<String, String> = mutableMapOf()
// frameBatchIdsDictionary.put(
//    key = <id_returned_from_sdk>,
//    value = <id_responded_from_server>
// )

override fun onNewFrameBatch(frameBatch: FrameBatch) {
    val gson = Gson()
    val framesStr = gson.toJson(frameBatch.frames)
    val params: MutableMap<String, Any> = HashMap()
    params["frames"] = framesStr
    params["metadata"] = frameBatch.metadata
    params["label"] = "video"
    val jsonToBeUploaded = gson.toJson(params)
    // upload frame batch to server using this api:
    // https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-videoaudioframes
    val uploadingResult: YourResponseObject = yourMethodToUploadFrameBatch(jsonToBeUploaded)

    // Keep the id that generated by the SDK corresponding with the one responded from server
    if (cardSide === TVSDKConfiguration.TVCardSide.FRONT) {
        frontCardFrameBatchIdsDictionary[frameBatch.id] = uploadingResult.fileId
    } else {
        backCardFrameBatchIdsDictionary[frameBatch.id] = uploadingResult.fileId
    }
}

3.0.4. Handle ID capturing results

3.0.4.1 Remove redundant frame batch ids
Kotlin
// These lists contain all valid frame batch ids that responded by server
var validFrontCardServerFrameBatchIds: List<String>? = null
var validBackCardServerFrameBatchIds: List<String>? = null

override fun onSuccess(result: TVDetectionResult) {
// the batch id list is null when Frame Recording feature is disabled by client settings.
// Wait until every Frame batch has been uploaded to server before calling this
    if (everyFrameBatchUploadingCompleted) {
        result.frontCardFrameBatchIds?.also {
            validFrontCardServerFrameBatchIds = removeRedundantFrameBatchIds(
                frontCardFrameBatchIdsDictionary,
                it
            )
        }
        result.backCardFrameBatchIds?.also {
            validBackCardServerFrameBatchIds = removeRedundantFrameBatchIds(
                backCardFrameBatchIdsDictionary,
                it
            )
        }
    }
}

private fun removeRedundantFrameBatchIds(
    batchIdsDictionary: MutableMap<String, String>,
    validIdsFromSDK: Collection<String>
): List<String> {
    val iter: MutableIterator<Map.Entry<String, String>> = batchIdsDictionary.entries.iterator()
    while (iter.hasNext()) {
        val (key1) = iter.next()
        if (!validIdsFromSDK.contains(key1)) {
            iter.remove()
        }
    }
    return batchIdsDictionary.values.toList()
}
3.0.4.2. Get Image Ids to be used in a particular use case

Use this API https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-image The images should be uploaded as JPEG data with 100% quality. For example:

Kotlin
var frontCardId: String? = null
var backCardId: String? = null
var frontQrId: String? = null
var backQrId: String? = null

fun onSuccess(result: TVDetectionResult) {
    // With front side
    frontCardId = result.frontCardImage?.imageByteArray?.let {
        yourMethodToUploadImage(it)
    }
    // With back side
    backCardId = result.backCardImage?.imageByteArray?.let {
        yourMethodToUploadImage(it)
    }

    // In case the QR capturing feature is enabled, and `result.getCardQrImage()` is null then
    // the user will be notified, so they can choose to re-capture their ID card.
    frontQrId = result.frontIdQr?.images?.getOrNull(i)?.imageByteArray?.let {
        yourMethodToUploadImage(it)
    }
    backQrId = result.backIdQr?.images?.getOrNull(i)?.imageByteArray?.let {
        yourMethodToUploadImage(it)
    }
}
3.0.4.3. Check ID Tampering

Call this API https://ekyc.trustingsocial.com/api-reference/customer-api/#request-detect-id-card-tampering with params:

json
{
  "image": {
    "id": "<frontCardId>"
  },
  "image2": {
    "id": "<backCardId>"
  },
  "qr1_images": [
    {
      "id": "<qrId>"
    }
  ],
  "card_type": "<result.cardType.getCardId()>",
  "videos": [
    {
      "id": "<validFrontCardServerFrameBatchIds.get(index)>"
    },
    {
      "id": "<validFrontCardServerFrameBatchIds.get(index + 1)>"
    },
    ...
    {
      "id": "<validBackCardServerFrameBatchIds.get(index)>"
    },
    {
      "id": "<validBackCardServerFrameBatchIds.get(index + 1)>"
    },
    ...
  ]
}
3.0.4.4 Upload QR images

if result.getFrontIdQr().isRequired() is true then result.getFrontIdQr().getImages() array should be non-empty. Otherwise, clients should be warned to re-capture id card photos.

QR images will be uploaded with this api: https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-image

kotlin
val frontQrImage = result.frontIdQr?.images?.getOrNull(i)
val metadata: Map<String,String>? = frontQrImage?.metadata
val label: String? = frontQrImage?.label
val data: ByteArray? = frontQrImage?.imageByteArray

*The same logic will be applied to result.getBackIdQr()

3.0.5 Scan NFC in back ID card capturing step

After capture the back card, if the card has nfc chip, SDK will call readIdCardNumber method in background thread. With image that returned by readIdCardNumber, call api to detect id number of the card then return id number to start flow scan NFC. If id number is null or empty, SDK skip flow scan NFC and continue

Kotlin
override fun readIdCardNumber(image: TVImageClass): String? {
  var idNumber: String? = null;
  // call api or do any thing to read and return id number
  // TODO
  return idNumber;
}

3.1. Capture the selfie

The selfie capturing activity will show the camera to capture image, preview the image, verify liveness. To start the selfie capturing activity.

3.1.1. Set config parameters

kotlin
val builder = TVSelfieConfiguration.Builder()
    .setCameraOption(TVSDKConfiguration.TVCameraOption.FRONT)
    .setEnableSound(false)
    .setLivenessMode(TVLivenessMode.PASSIVE)
    .setSkipConfirmScreen(false)

val configuration = builder.build()

Options:

  • setCameraOption: TVCameraOption. Camera mode
  • setEnableSound: boolean. Sound should be played or not
  • setLivenessMode: TVLivenessMode. Liveness verification mode
  • setSkipConfirmScreen: boolean. Control whether the SDK should skip the confirmation screen.

3.1.2. Start selfie capturing activity from configuration

Kotlin
TrustVisionSDK.startSelfieCapturing(activity, configuration, object : TVCapturingCallBack() {
    override fun onNewFrameBatch(frameBatch: FrameBatch) {

    }
    override fun onError(error: TVDetectionError) {

    }
    override fun onSuccess(result: TVDetectionResult) {

    }
    override fun onCanceled() {

    }
})

where:

  • activity: is the current Activity being displayed
  • configuration: the configuration would like to pass to selfie capturing activity
  • callback: is an object of type TVCapturingCallBack . It is an interface that has 3 methods
    • onNewFrameBatch: NewFrameBatchCallback. can be called multiple times during the capturing to return frame data.
      • frameBatch: FrameBatch
      • getId(): String. batch id generated by TV SDK
      • getFrames(): List<TVFrameClass>. batch frame to push
      • getMetadata(): Map<String, String>. batch metadata to push
      • getValidVideoIds() Set<String>. For debugging purpose only
    • onSuccess method that will be called in case of success. The onSuccess method has one parameter.
      • result : TVDetectionResult. has the following methods:
        • getSelfieImages(): List<SelfieImage>
        • getLivenessFrameBatchIds(): Collection<String>
        • getLivenessMetadata(): JSONObject
    • onError: ErrorCallback. Will be called when an error has occurred during the capturing.
      • error: TVDetectionError
    • onCanceled: CancellationCallback. Will be called when the journey has been cancelled (e.g user clicked on back button...)

3.1.3. Handle onNewFrameBatch callback

With each batch that returned by onNewFrameBatch(FrameBatch) callback, call the below api to upload the data to server, and store the frame batch id that responses from the API, keep it corresponding with frameBatch.getId() - local id https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-frame-batch

For example:

Kotlin
// this dictionary will be used for ID Tampering Verification
val selfieFrameBatchIdsDictionary: MutableMap<String, String> = mutableMapOf()
// frameBatchIdsDictionary.put(
//    key = <id_returned_from_sdk>,
//    value = <id_responded_from_server>
// )

override fun onNewFrameBatch(frameBatch: FrameBatch) {
    val gson = Gson()
    val framesStr = gson.toJson(frameBatch.frames)
    val params: MutableMap<String, Any> = HashMap()
    params["frames"] = framesStr
    params["metadata"] = frameBatch.metadata
    params["label"] = "video"
    val jsonToBeUploaded = gson.toJson(params)
    // upload frame batch to server using this api:
    // https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-videoaudioframes
    val uploadingResult: YourResponseObject = yourMethodToUploadFrameBatch(jsonToBeUploaded)

    // Keep the id that generated by the SDK corresponding with the one responded from server
    selfieFrameBatchIdsDictionary[frameBatch.id] = uploadingResult.fileId
}

3.1.4. Handle selfie results

3.1.4.1 Remove redundant frame batch ids
Kotlin
// These lists contain all valid frame batch ids that responded by server
var validServerFrameBatchIds: List<String>? = null

override fun onSuccess(result: TVDetectionResult) {
    // the batch id list is null when Frame Recording feature is disabled by client settings.
    // Wait until every Frame batch has been uploaded to server before calling this
    if (everyFrameBatchUploadingCompleted) {
        result.livenessFrameBatchIds?.also {
            validServerFrameBatchIds = removeRedundantFrameBatchIds(
                selfieFrameBatchIdsDictionary,
                it
            )
        }
    }
}

private fun removeRedundantFrameBatchIds(
    batchIdsDictionary: MutableMap<String, String>,
    validIdsFromSDK: Collection<String>
): List<String> {
    val iter: MutableIterator<Map.Entry<String, String>> = batchIdsDictionary.entries.iterator()
    while (iter.hasNext()) {
        val (key1) = iter.next()
        if (!validIdsFromSDK.contains(key1)) {
            iter.remove()
        }
    }
    return batchIdsDictionary.values.toList()
}

3.1.4.2. Get Image Ids

Use this api https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-image to get image ids with the inputs are the elements of result.getSelfieImages() The images should be uploaded as JPEG data with 100% quality.

For example:

Kotlin
// These lists of image ids will be used in Liveness Verification
val frontalImageIds = mutableListOf<String>()
val gestureImageIds = mutableListOf<String>()

override fun onSuccess(result: TVDetectionResult) {
    handleSelfieImages(result.selfieImages)
}

private fun handleSelfieImages(selfieImages: List<SelfieImage>?) {
    selfieImages?.forEach { selfieImage ->
        // Handle frontal images
        selfieImage.frontalImage?.imageByteArray?.also {
            // frontalImageId is the id of the image, returned from server when the uploading API is completed successfully
            val frontalImageId = yourUploadImageMethod(it)
            frontalImageIds.add(frontalImageId)
        }

        // Handle gesture images
        selfieImage.gestureImage?.imageByteArray?.also {
            // gestureImageId is the id of the image, returned from server when the uploading API is completed successfully
            val gestureImageId = yourUploadImageMethod(it)
            gestureImageIds.add(gestureImageId)
        }
    }
}

Upload Image API request, parameters:

json
{
  "file": "<byte[] dataToUpload>",
  "label": "<proper label, check the API document for detail>"
}
3.1.4.3. Liveness Verification

API document: https://ekyc.trustingsocial.com/api-reference/customer-api/#verify-face-liveness

Call the above api with below parameters:

  1. images field
json
{
  "images": [
    {
      "id": "<frontalImageIds.get(index)>"
    },
    {
      "id": "<frontalImageIds.get(index + 1)>"
    },
    ...
  ]
}
  1. gesture_images field
json
{
  "gesture_images": [
    {
      "gesture": "<result.getSelfieImages().get(index).getGestureType().toGestureType().toLowerCase()>",
      "images": [
        {
          "id": "<gestureImageIds.get(index)>"
        }
      ]
    },
    {
      "gesture": "<result.getSelfieImages().get(index + 1).getGestureType().toGestureType().toLowerCase()>",
      "images": [
        {
          "id": "<gestureImageIds.get(index + 1)>"
        }
      ]
    },
    ...
  ]
}
  1. videos field
json
{
  "videos": [
    {
      "id": "<validServerFrameBatchIds.get(index)>"
    },
    {
      "id": "<validServerFrameBatchIds.get(index + 1)>"
    },
    ...
  ]
}
  1. metadata field
json
{
  "metadata": "<result.getLivenessMetadata()>"
}

3.2. Scan QR

The QR scanner activity will show the camera to scan image, preview the image. To start the QR scanner activity.

3.2.1. Set config parameters

Kotlin
val builder = TVQRConfiguration.Builder()
    .setCardType(selectedCard)
    .setCardSide(TVSDKConfiguration.TVCardSide.FRONT)
    .setEnableSound(false)
    .setSkipConfirmScreen(false)

val configuration = builder.build()

Options:

  • setCardType: TVCardType. List of supported cards can be found by TrustVisionSDK.getCardTypes() if you set jsonConfigurationByServer when init SDK. If not, use :
Kotlin
TVCardType(
    "vn.national_id",
    "CMND cũ / CMND mới / CCCD",
    true,
    TVCardType.TVCardOrientation.HORIZONTAL
)
  • setCardSide: TVCardSide. Card side to capture.
  • setEnableSound: boolean. Sound should be played or not.
  • setSkipConfirmScreen: boolean. Control whether the SDK should skip the confirmation screen.

3.2.2. Start QR Scanning activity from configuration

Kotlin
TrustVisionSDK.startQRScanning(activity, configuration, object : TVCapturingCallBack() {
    override fun onError(error: TVDetectionError) {

    }

    override fun onSuccess(result: TVDetectionResult) {

    }

    override fun onCanceled() {

    }

})

where:

  • activity: is the current Activity being displayed
  • configuration: the configuration would like to pass to QR scanning activity
  • callback: is an object of type TVCapturingCallBack . It is an interface that has 3 methods
    • onSuccess method that will be called in case of success. The onSuccess method has one parameter.
      • result : TVDetectionResult. has the following methods:
        • getFrontIdQr(): TVCardQr
        • getBackIdQr(): TVCardQr
    • onError: ErrorCallback. Will be called when an error has occurred during the capturing.
      • error: TVDetectionError
    • onCanceled: CancellationCallback. Will be called when the journey has been cancelled (e.g user clicked on back button...)
3.2.3 Upload QR images

if result.getFrontIdQr().isRequired() is true then result.getFrontIdQr().getImages() array should be non-empty. Otherwise, clients should be warned to re-capture id card photos.

QR images will be uploaded with this api: https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-image

kotlin
val frontQrImage = result.frontIdQr?.images?.getOrNull(i)
val metadata: Map<String,String>? = frontQrImage?.metadata
val label: String? = frontQrImage?.label
val data: ByteArray? = frontQrImage?.imageByteArray

*The same logic will be applied to result.getBackIdQr()

3.3. Scan NFC

The NFC scanner activity will show the guideline screen, the scanner popup. To start the NFC scanner activity.

3.3.1. Set config parameters

Kotlin
val builder = TVNfcConfiguration.Builder()
    .setNfcCode(nfcCode)
    .setSOD(sod)
    .setRequestReadImageNfc(true)
    .setRequestIntegrityCheckNfc(true)
    .setRequestCloneDetectionNfc(true)
    .setNfcMaxRetries(5)

val configuration = builder.build()

Options:

  • setNfcCode: String is the id number of ID card
  • setSOD: String (optional) is the sod of ID card (MM/DD/YYYY)
  • setRequestReadImageNfc: boolean read image in the chip when scan nfc or not
  • setRequestIntegrityCheckNfc: boolean check integrity of the chip when scanning nfc or not
  • setRequestCloneDetectionNfc: boolean check clone of the chip when scanning nfc or not
  • setNfcMaxRetries: Int. The maximum number of times the SDK retries an NFC scanning before giving up

3.0.2. Start nfc scanning activity from configuration

Kotlin
TrustVisionSDK.startNfcScanning(activity, configuration, object : TVCapturingCallBack() {
    override fun onError(error: TVDetectionError) {

    }

    override fun onSuccess(result: TVDetectionResult) {

    }

    override fun onCanceled() {

    }

})

where:

  • activity: is the current Activity being displayed
  • configuration: the configuration would like to pass to nfc scanning activity
  • callback: is an object of type TVCapturingCallBack . It is an interface that has 3 methods
    • onSuccess method that will be called in case of success. The onSuccess method has one parameter.
      • result : TVDetectionResult. has the following methods:
        • getNfcInfoResult(): TVNfcInfoResult
    • onError: ErrorCallback. Will be called when an error has occurred during the capturing.
      • error: TVDetectionError
    • onCanceled: CancellationCallback. Will be called when the journey has been cancelled (e.g user clicked on back button...)

3.4. Error handling:

Kotlin
// [FlowStartingFunc]: startIdCapturing, startSelfieCapturing, startQRScanning, startNfcScanning
TrustVisionSDK.[FlowStartingFunc](activity, configuration, object : TVCapturingCallBack() {
    override fun onError(error: TVDetectionError) {
        val message = error.errorDescription
        Log.d("", message)
        showToast(message)

        ///////////////////////////////////////
        // ERROR HANDLER
        val code = error.errorCode
        val description = error.errorDescription

        when (code) {
            TVDetectionError.CONFIGURATION_ERROR -> {
                // Invalid configuration
            }
            TVDetectionError.DETECTION_ERROR_PERMISSION_MISSING -> {
                // No camera permission.
            }
            TVDetectionError.DETECTION_ERROR_CAMERA_ERROR -> {
                // The camera can't be opened.
            }
            TVDetectionError.DETECTION_ERROR_SDK_INTERNAL -> {
                // The SDK has an unexpected error.
            }
            TVDetectionError.DETECTION_ERROR_NFC -> {
                // The SDK has an unexpected error when scanning NFC
            }
        }
    }

    override fun onSuccess(result: TVDetectionResult) {

    }

    override fun onCanceled() {

    }

})

4. Additional built-in API

The SDK provides some built-in API for quick detection

4.0. Detect if device support NFC

Allow users to quick check if device support NFC so that they can determine for their next step

Kotlin
TrustVisionSDK.isNfcSupport(Context): Boolean

API Interface

1. TVLivenessResult

MethodTypedescription
isLiveBooleanDetermines whether the selfie is live or not
getScore()floatThe score from 0 to 1

2. TVDetectionResult

MethodTypedescription
getSelfieImages()List<SelfieImage>List of images that each item contains the bitmap of the selfie image
getSelfieFrameBatchIds()Final list of Selfie's local frame batch IDs. Local batch ids that not in this list are invalid and their corresponding server IDs shouldn't be used
getLivenessMetadata()JSONObjectCollected data during liveness checking process
MethodTypedescription
getFrontCardImage()TVImageClassContains bitmap of the front image
getBackCardImage()TVImageClassContains bitmap of the back image
getQRImage()TVImageClassContains bitmap of the QR image
getFrontCardFrameBatchIds()Set<String>Final list of front side's local frame batch IDs. Local batch ids that not in this list are invalid and their corresponding server IDs shouldn't be used
getBackCardFrameBatchIds()Set<String>Final list of back side's local frame batch IDs. Local batch ids that not in this list are invalid and their corresponding server IDs shouldn't be used
getNfcInfoResult()TVNfcInfoResultContains info from nfc chip. Use it to call api verify NFC
MethodTypedescription
getError()TVDetectionErrorThe error found when doing any detection

3. SelfieImage

MethodTypedescription
getGestureType()FaceDetectionTypeGesture type of the selfie image
getFrontalImage()TVImageClassFrontal image of the selfie image
getGestureImage()TVImageClassGesture image of the selfie image

4. FaceDetectionType

MethodTypedescription
getType()intRepresent a gesture type
java
int NEUTRAL = 1
int TURN_LEFT = 5
int TURN_RIGHT = 6
int FACE_UP = 7
int FACE_DOWN = 8

5. TVImageClass

MethodTypedescription
getLabel()StringLabel of the Image class.
getImage()BitmapCaptured Bitmap

6. TVDetectionError

MethodTypedescription
getErrorCode()intError code
getErrorDescription()StringError description

Error code is one of the below list

java
int TVDetectionError.DETECTION_ERROR_PERMISSION_MISSING = 1004
int TVDetectionError.DETECTION_ERROR_CAMERA_ERROR = 1005
int TVDetectionError.DETECTION_ERROR_SDK_INTERNAL = 1007

7. TVCameraOption (Enum)

  • TVCameraOption.FRONT: Use front camera
  • TVCameraOption.BACK: Use back camera
  • TVCameraOption.BOTH: The screen will have a button to switch between front & back camera

8. TVLivenessMode (Enum)

  • TVLivenessMode.NONE: no liveness verification. Just capture the selfie.
  • TVLivenessMode.PASSIVE: Use texture-based approach.
  • TVLivenessMode.ACTIVE: Use challenge-response approach. User needs to follow and finish all steps when capturing selfie such as turn left, right, up, smile, open mouth...

9. TVDefaultCameraSide (Enum)

  • TVDefaultCameraSide.FRONT
  • TVDefaultCameraSide.BACK

10. FrameBatch

MethodTypedescription
getFrames()List<TVFrameClass>Recorded frames during the capturing
getId()StringLocal ID of the batch, to be corresponds with the ID responded from server after the frame batch is pushed
getMetadata()Map<String, String>Metadata of the batch
getValidVideoIds()Set <String>For debugging purpose only

11. TVFrameClass

MethodTypedescription
getFramesBase64()StringThe data of the frame as a base64 String
getIndex()StringIndex of this frame in the list of recorded frames
getLabel()StringLabel of this frame

11. ErrorCallback (Callback)

Will be called in case failed. Parameters:

  • error: TVDetectionError.

12. CancellationCallback (Callback)

Will be called in case the sdk is cancelled. No parameters.

13. TVNfcInfoResult

MethodTypeDescription
getCom()String
getSod()String
getDg1()String
getDg2()String
getDg13()String
getDg14()String
getDg15()String
getCloneStatus()TVNfcVerificationStatus

14. TVNfcVerificationStatus

MethodTypeDescription
getError()TVDetectionError
getVerdict()TVNfcVerdictTVNfcVerdict.NOT_CHECKED
TVNfcVerdict.ALERT
TVNfcVerdict.GOOD
TVNfcVerdict.ERROR

UI Customization

This document introduces how to enable the ability to customize UI components of TrustingVision SDK.

Default UI prototypes

Check out the default UI of TrustingVision SDK. We provide you the ability to change and modify many UI components: background colors, font interfaces, font sizes, icons, buttons.

Before initialize the SDK

Initialize and change properties of TVTheme class. If any of which is not set, it will get default value.

After that, input the instance of TVTheme as a parameter of the TV SDK's initialization method. See Initialize TV SDK

TVTheme let you custom and override attributes, which includes:

Properties/FunctionsTypeDescription
idCapturingThemeTVIdCapturingThemeAttributes that change the UI of ID Card Detection screen.
idConfirmationThemeTVIdConfirmationThemeAttributes that change the UI of ID Confirmation screen.
selfieCapturingThemeTVSelfieCapturingThemeAttributes that change the UI of Selfie Capturing screen.
selfieConfirmationThemeTVSelfieConfirmationThemeAttributes that change the UI of Selfie Confirmation screen.
qrGuidelinePopupThemeTVQrPopupThemeModifying UI of QR guideline popup.
qrRetryPopupThemeTVQrPopupThemeModifying UI of QR retry popup.
clone()() -> TVThemeA function that returns a deep copy of TVTheme's instance itself.

Common UI components

Object TVThemeDefaultValues helps you to quickly change some common UI components that will be used across the whole SDK.

In case a specific Screen's theme is set, it will override TVThemeDefaultValues's properties.

PropertiesTypeDescription
normalLabelThemeTVLabelThemeNormal text of SDK.
titleLabelThemeTVLabelThemeThe title of every screen (located on the top-most, centered of screen).
errorLabelThemeTVLabelThemeThis text is shown as if any user misconduction or system failure occurred during the detection process.
instructionLabelThemeTVLabelThemeInstruction text.
timeoutLabelThemeTVLabelThemeThe count down text.

The object TVLabelTheme can be described in this table below:

Properties/FunctionsTypeLabel's
fontTypefacefont family and style
textSizeFloattext size
textColor@ColorInt Inttext color
textGravityInttext alignment of its frame. E.g Gravity.Center, Gravity.Start...
backgroundColors[@ColorInt Int]background colors. If total elements of this array is >= 2, the background color is gradient, else it'd be solid.
isBackgroundGradientHorizontalBooleanbackground gradient direction
cornerRadiusFloatrounded corner
isHiddenBooleanhide the label
borderWidthFloatborder width
borderColor@ColorInt Intborder color
clone()() -> TVLabelThemeA function that returns a deep copy of TVLabelTheme's instance itself.

Here is a snipped code example:

Kotlin
private fun customizeTVCommonThemes() {
    // Common Title label theme
    val titleLabelThemeDefault = titleLabelTheme
    titleLabelThemeDefault.font = your_font
    // there are more to be customized...

    // Common Normal label theme
    val normalLabelThemeDefault = normalLabelTheme
    normalLabelThemeDefault.textSize = your_text_size
    // there are more to be customized...

    // Common Instruction label theme
    val instructionLabelTheme = instructionLabelTheme
    instructionLabelTheme.textColor = your_text_color
    // there are more to be customized...

    // Common Error label theme
    val errorLabelThemeDefault = errorLabelTheme
    errorLabelThemeDefault.cornerRadius = your_corner_radius
    // there are more to be customized...

    // Common Timeout label theme
    val timeoutLabelThemeDefault = timeoutLabelTheme
    timeoutLabelThemeDefault.backgroundColors = your_background_colors
    // there are more to be customized...
}

ID Card Detection: UI customization

all text

Class TVIdCapturingTheme

If a property is not set then the default value will be used.

Properties/FunctionsTypeDescription
titleLabelThemeTVLabelThemeSee Common UI components section.
instructionLabelThemeTVLabelTheme
errorLabelThemeTVLabelTheme
timeoutLabelThemeTVLabelTheme
normalLabelThemeTVLabelTheme
qrInstructionLabelThemeTVLabelThemeThe instruction text that show during QR scanning process.
closeButtonLocationenumTVButtonLocationThe position of close button to device orientation:
.TOP_LEFT: to the left of the title
.TOP_RIGHT: to the right of the title
.NONE: hide the button
showTrademarkBooleanShow the trademark text or not.
backgroundColor@ColorInt IntBackground color of the screen. Default value is black with 60% opacity.
captureButtonImageBitmapThe image of the capture button.
captureButtonDisableImageBitmapThe image of the disabled capture button.
closeButtonImageBitmapThe image of the close view button.
maskViewNeutralImageBitmapThe mask image of camera view when start the ID Capture flow.
maskViewSuccessImageBitmapThe mask image of camera view when detected a valid ID card.
maskViewErrorImageBitmapThe mask image of camera view when cannot detect any ID card.
qrInstructionBackgroundImageBitmapThe image behind the QR instruction text.
qrMaskViewNeutralImageBitmapThe mask image of camera view when start QR detection or not detected any QR code.
qrMaskViewSuccessImageBitmapThe mask image of camera view when detected a valid QR code.
qrMaskViewErrorImageBitmapThe mask image of camera view when detected an invalid QR code.
loadingImageBitmapLoading indicator in image.
clone()() -> TVIdCapturingThemeA function that returns a deep copy of TVIdCapturingTheme's instance itself.

ID Card Confirmation: UI customization

alt text

Class TVIdConfirmationTheme

If a property is not set then the default value will be used.

Properties/FunctionsTypeDescription
titleLabelThemeTVLabelThemeSee Common UI components section.
errorLabelThemeTVLabelTheme
normalLabelThemeTVLabelTheme
closeButtonLocationenumTVButtonLocationThe position of close button to device orientation:
.TOP_LEFT: to the left of the title
.TOP_RIGHT: to the right of the title
.NONE: hide the button
showTrademarkBooleanShow the trademark text or not.
backgroundColor@ColorInt IntBackground color of the screen. Default value is black with 60% opacity.
closeButtonImageBitmapThe image of the close view button.
confirmButtonImageBitmapThe image of the "Look good" button.
retryButtonImageBitmapThe image of the "Try again" button.
icQrResultSuccessImageBitmapIcon before text that scanned QR successfully.
icQrResultErrorImageBitmapIcon before text that scanned QR failed.
maskViewImageBitmapThe mask image of camera view showing captured image.
loadingImageBitmapLoading indicator in image.
clone()() -> TVIdConfirmationThemeA function that returns a deep copy of TVIdConfirmationTheme's instance itself.

Selfie Capturing: UI customization

alt text

Class TVSelfieCapturingTheme

If a property is not set then the default value will be used.

Properties/FunctionsTypeDescription
titleLabelThemeTVLabelThemeSee Common UI components section.
instructionLabelThemeTVLabelTheme
errorLabelThemeTVLabelTheme
timeoutLabelThemeTVLabelTheme
normalLabelThemeTVLabelTheme
closeButtonLocationenumTVButtonLocationThe position of close button to device orientation:
.TOP_LEFT: to the left of the title
.TOP_RIGHT: to the right of the title
.NONE: hide the button
showTrademarkBooleanShow the trademark text or not.
backgroundColor@ColorInt IntBackground color of the screen. Default value is black with 60% opacity.
captureButtonImageBitmapThe image of the capture button.
captureButtonDisableImageBitmapThe image of the disabled capture button.
closeButtonImageBitmapThe image of the close view button.
switchCameraSideImage BitmapThe image of switch camera button.
maskViewNeutralImageBitmapThe mask image of camera view when start the selfie flow.
maskViewSuccessImage BitmapThe mask image of camera view when detected a valid face.
maskViewErrorImageBitmapThe mask image of camera view when cannot detect any valid face.
progressTheme.isHiddenBooleanHide the current 4 steps view.
progressTheme.backgroundColor@ColorInt IntBackground color of the circle progress theme.
progressTheme.progressColor@ColorInt IntBackground color of the progress steps.
gestureTheme.isHiddenBooleanWhether of not should hide selfie steps' group view.
gestureTheme.turnLeftActiveImageBitmapImage for turn left step gesture when active.
gestureTheme.turnRightActiveImageBitmapImage for turn right step gesture when active.
gestureTheme.turnUpActiveImageBitmapImage for turn up step gesture when active.
gestureTheme.turnDownActiveImageBitmapImage for turn down step gesture when active.
gestureTheme.lookStraightActiveImageBitmapImage for look straight step gesture when active.
gestureTheme.turnLeftInactiveImageBitmapImage for turn left step gesture when inactive.
gestureTheme.turnRightInactiveImageBitmapImage for turn right step gesture when inactive.
gestureTheme.turnUpInactiveImageBitmapImage for turn up step gesture when inactive.
gestureTheme.turnDownInactiveImageBitmapImage for turn down step gesture when inactive.
gestureTheme.lookStraightInactiveImageBitmapImage for look straight step gesture when inactive.
gestureTheme.finishedGestureBackgroundImageBitmapBackground for every step that completed.
gestureTheme.currentStepFocusImageBitmapImage overlay for current step indicator.
maskViewErrorImageBitmapThe mask image of camera view when cannot detect any valid face.
maskViewErrorImageBitmapThe mask image of camera view when cannot detect any valid face.
loadingImageBitmapLoading indicator in image.
clone()() -> TVSelfieCapturingThemeA function that returns a deep copy of TVSelfieCapturingTheme's instance itself.

Selfie Confirmation: UI customization

alt text

Class TVSelfieConfirmationTheme

If a property is not set then the default value will be used.

Properties/FunctionsTypeDescription
titleLabelThemeTVLabelThemeSee Common UI components section.
normalLabelThemeTVLabelTheme
closeButtonLocationenumTVButtonLocationThe position of close button to device orientation:
.TOP_LEFT: to the left of the title
.TOP_RIGHT: to the right of the title
.NONE: hide the button
showTrademarkBooleanShow the trademark text or not.
backgroundColor@ColorInt IntBackground color of the screen. Default value is black with 60% opacity.
closeButtonImageBitmapThe image of the close view button.
maskViewImage BitmapThe mask image of selfie captured image.
loadingImageBitmapLoading indicator in image.
clone()() -> TVSelfieConfirmationThemeA function that returns a deep copy of TVSelfieConfirmationTheme's instance itself.

QR Popup: UI customization

alt text

Class TVQrPopupTheme

If a property is not set then the default value will be used.

Properties/FunctionsTypeDescription
titleLabelThemeTVLabelThemeSee Common UI components section.
descriptionThemeTVLabelThemeTheme of description text.
primaryButtonThemeTVLabelThemeTheme of the main button of popup.
secondaryButtonThemeTVLabelThemeTheme of sub-button of popup.
timeoutLabelThemeTVLabelThemeTheme of timeout-warning text.
backgroundColor@ColorInt IntBackground color of the view.
clone()() -> TVQrPopupThemeA function that returns a deep copy of TVQrPopupTheme's instance itself.

Here is a snipped code example:

Kotlin
private fun initTVTheme(): TVTheme {
    val customizedTheme = TVTheme()

    // Selfie capturing screen
    customizedTheme.selfieCapturingTheme.gestureTheme.lookStraightActiveImage = your_image
    // there are more to be customized...

    // Selfie confirmation screen
    customizedTheme.selfieConfirmationTheme.retryButtonImage = your_image
    // there are more to be customized...

    // Id capturing screen
    customizedTheme.idCapturingTheme.maskViewNeutralImage = your_image
    // there are more to be customized...

    // Id confirmation screen
    customizedTheme.idConfirmationTheme.closeButtonImage = your_image
    // there are more to be customized...

    // QR guideline popup
    customizedTheme.qrGuidelinePopupTheme.headerImage = your_image
    // there are more to be customized...

    // QR guideline popup
    customizedTheme.qrRetryPopupTheme.backgroundColor = your_color
    // there are more to be customized...
    return customizedTheme
}