Android v4.0.4.x
OVERVIEW
TrustVision SDK is the android SDK for TrustVision Engine. It provides these features:
Specifications
- Gradle Version 8.11.1
- Tested with Gradle Plugin for Android Studio - version 8.14.3
- minSdkVersion 21
- targetSdkVersion 35
- Support Kotlin version 1.5.0 - 1.8.20
Integration Steps
1. Adding the SDK to your project
- Get library file
tv_sdk.zip, extract and put all files into a folder in android project. Example: folder${project.rootDir}/repo
Note : tv_sdk 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
+--4.0.x
+--tv_api_sdk-4.0.x.aar
+--tv_api_sdk-4.0.x.pom
maven-metadata.xml
+--tv_core_sdk
+--tv_sdk
...
- Add the following set of lines to the Project (top-level)
build.gradle
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)
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
android {
...
aaptOptions {
noCompress "tflite"
}
// Support 16KB https://developer.android.com/guide/practices/page-sizes
ndk {
abiFilters "arm64-v8a", "armeabi-v7a"
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation('com.trustvision:tv_sdk:4.x.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.
TVInitializeConfiguration config = new TVInitializeConfiguration.Build()
.setJsonConfigurationByServer(jsonConfigurationByServer)
.setEndpoint(endpoint)
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret)
.setEndpointLogger(endpointLogger)
.setAccessKeyIdLogger(accessKeyIdLogger)
.setAccessKeySecretLogger(accessKeySecretLogger)
.setLanguageCode(languageCode)
.setTheme(theme)
.setImageEncryptionKey(imageEncryptionKey)
.setSecurityPublicKey(securityPublicKey)
.setXRequestId(xRequestId)
.setXRequestId2(xRequestId2)
.setTvCertificate(tvCertificate)
.setHeaders(headers)
.build();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TrustVisionSDK.INSTANCE.init(context, config, new BaseTrustVisionSDK.TVInitializeListener() {
@Override
public void onInitSuccess() {
}
@Override
public void onInitError(@NonNull TVDetectionError error) {
}
});
}
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.
Options:
- setLanguageCode:
Stringthe code of the language that will show and sound to user. E.g Vietnamese (vi), English ( en). - setImageEncryptionKey:
String(optional). the key to encrypt image data. It's optional. If it's null or empty then the image data will not be encrypted. - setSecurityPublicKey:
String(optional). the key to encrypt exif data. It's optional. If it's null or empty then the exif data will be encrypted by the default key. - setTheme:
TVTheme(optional). The theme of the SDK. If it's null then the sdk will use the default theme or the theme that we customized for the client.
To call the APIs in the SDK, the host app needs to set the following parameters:
- endpoint:
String. The endpoint of the server. - accessKeyId:
String. The access key id of the server. - accessKeySecret:
String. The secret key of the server. - xRequestId:
String(optional) https://ekyc.trustingsocial.com/api-reference/customer-api#api-reconciliation - xRequestId2:
String(optional) - flowId:
String(optional). Allow these values:- facce_authen
- onboarding
- tvCertificate:
Int(optional). It is the raw resource ID (@RawRes) of the SSL certificates file - setHeaders:
Map<String, String>(optional). The headers to be added to the request. - setFlowId:
String(optional). The flow id of the API - setSSLCertificates:
List<Int>(optional). The list of resource IDs (@RawRes) corresponds to the SSL certificates that should be added to the request.
The host app will call the APIs itself, set the following parameters:
- enableGetClientSetting:
Boolean(optional).true(default) for calling api getClientSettings from SDK full mode.falsefor otherwise.
- setJsonConfigurationByServer:
String. set this parameter if the host app will call the APIs itself. The jsonConfigurationByServer is 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.
If the log event feature is used, set the following parameters:
- endpointLogger:
String. The endpoint of the log event server. - accessKeyIdLogger:
String. The access key id of the log event server. - accessKeySecretLogger:
String. The secret key of the log event server.
2.1. Config
2.1.0 Language code
2.1.0.0 Get supported language codes list
TrustVisionSdk.INSTANCE.getSupportedLanguages();
2.1.0.1 Change language code
Allow user to change the sdk language after initialization
TrustVisionSdk.INSTANCE.changeLanguageCode(languageCode);
wherer:
- languageCode:
Stringthe 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:
<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
TrustVisionSDK.INSTANCE.installDynamicFeature(it -> {
// We often execute this code to install some necessary resources for dynamic feature
SplitCompat.installActivity(it);
return Unit.INSTANCE;
});
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
TVIDConfiguration.Builder builder= new TVIDConfiguration.Builder()
.setEnableSound(true)
.setCardType(selectedCard)
.setCardSide(TVSDKConfiguration.TVCardSide.FRONT)
.setReadBothSide(false)
.setEnableScanNfc(true)
.setEnableScanQr(true)
.setEnablePhotoGalleryPicker(false)
.setEnableTiltChecking(false)
.setSkipConfirmScreen(true)
.setEnableUploadFrames(true)
.setEnableUploadImages(true)
.setEnableSanityCheck(true)
.setEnableDetectIdCardTampering(true)
.setEnableReadCardInfo(true)
.setEnableCheckNfcData(true)
.setEnableVerifyNfc(true);
TVIDConfiguration configuration=builder.build();
Options:
- setCardTypes: List<TVCardType>. Card types is allowed capture.
| card_type | description | supported countries |
|---|---|---|
TVCardType.default(Country.VIETNAM) | Any of Vietnam national ID versions | vietnam |
TVCardType.cmnd() | Chứng minh nhân dân cũ | vietnam |
TVCardType.cmndNew() | Chứng minh nhân dân mới | vietnam |
TVCardType.cccd() | Căn cước công dân | vietnam |
TVCardType.cccdNew() | Căn cước công dân gắn chip | vietnam |
TVCardType.passport() | Vietnam passport | vietnam |
TVCardType.tcc() | Thẻ căn cước | vietnam |
- setEnableSound:
boolean. Sound should be played or not. - 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. - setEnableScanNfc
boolean. scan NFC chip of the id card or not. - setEnableScanQr
boolean. scan QR code of the id card 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. - setEnableUploadFrames:
boolean. Enable upload video frames or not. If it's false then the SDK won't call the API to upload the frames and the APIs that need the video frames will be skipped or called with empty frames data. - setEnableUploadImages:
boolean. Enable upload images or not. If it's false then the SDK won't call the API to upload the images and the APIs that need the image will be skipped. - setEnableSanityCheck:
boolean. Enable sanity check or not. If it's true then the SDK will call the API to check the sanity of the id card. - setEnableDetectIdCardTampering:
boolean. Enable ID Tampering Verification or not. If it's true then the SDK will call the API to check the tampering of the id card. - setEnableReadCardInfo:
boolean. Enable read card info or not. If it's true then the SDK will call the API to read the card info. - setEnableCheckNfcData:
boolean. Enable check NFC data or not. If it's true then the SDK will call the API to get sod and cached fields of the NFC data. - setEnableVerifyNfc:
boolean. Enable verify NFC or not. If it's true then the SDK will call the API to verify the NFC.
3.0.2. Start id capturing activity from configuration
TrustVisionSDK.INSTANCE.startIDCapturing(activity, configuration, new TVCapturingCallBack(){
@Override
public void onNewFrameBatch(FrameBatch frameBatch){
}
@Override
public void onError(TVDetectionError error){
}
@Override
public void onSuccess(TVDetectionResult result){
}
@Override
public void onCanceled(TVCancelReason reason){
}
@Override
public TVNfcParams readIdCardImage(@NonNull TVImageClass image) {
}
});
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
- getId():
- frameBatch:
- onSuccess method that will be called in case of success. The
onSuccessmethod has one parameter.- result :
TVDetectionResult. has the following methods:- getFrontCardImage():
TVImageClass - getBackCardImage():
TVImageClass - getFrontIdQr():
TVCardQr - getBackIdQr():
TVCardQr - getNfcInfoResult():
TVNfcInfoResult - getIdSanityResult():
TVSanityResult - getIdTamperingResult():
TVSanityResult - getCardInfoResult():
TVCardInfoResult
- getFrontCardImage():
- result :
- onError:
ErrorCallback. Will be called when an error has occurred during the capturing.- error:
TVDetectionError
- error:
- onCanceled:
CancellationCallback. Will be called when the journey has been cancelled (e.g user clicked on back button...) - readIdCardImage: method that will be called in case of scan NFC to read SDK Id number from the image. The readIdCardImage method has a parameter and return tvNfcParams.
- image:
TVImageClass. image of back id card - tvNfcParams:
TVNfcParamshas the following params:- idNumber:
String. The id number of the card. If it's null or empty then the SDK will skip flow scan NFC and continue. - issueDate:
String(optional). The issue date of the card - hashSod:
String(optional). The hash of the SOD NFC - cachedFields:
List<String>(optional). The cached fields of the card
- idNumber:
- image:
- onNewFrameBatch:
3.0.3. Handle onNewFrameBatch callback
If the APIs is called by the SDK, please skip this step.
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-videoaudioframes
For example:
// this dictionary will be used for ID Tampering Verification
Map frontCardFrameBatchIdsDictionary = new HashMap<String, String>();
Map backCardFrameBatchIdsDictionary = new HashMap<String, String>();
// frameBatchIdsDictionary.put(
// key = <id_returned_from_sdk>,
// value = <id_responded_from_server>
// );
@Override
public void onNewFrameBatch(FrameBatch frameBatch) {
Gson gson = new Gson();
String framesStr = gson.toJson(frameBatch.getFrames());
Map<String, Object> params = new HashMap<>();
params.put("frames", framesStr);
params.put("metadata", frameBatch.getMetadata());
params.put("label", "video");
String jsonToBeUploaded=gson.toJson(map);
// upload frame batch to server using this api:
// https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-videoaudioframes
YourResponseObject uploadingResult = yourMethodToUploadFrameBatch(jsonToBeUploaded);
// Keep the id that generated by the SDK corresponding with the one responded from server
if (cardSide == TVSDKConfiguration.TVCardSide.FRONT) {
frontCardFrameBatchIdsDictionary.put(
key = frameBatch.batchId,
value = uploadingResult.fileId
);
} else {
backCardFrameBatchIdsDictionary.put(
key = frameBatch.batchId,
value = uploadingResult.fileId
);
}
}
3.0.4. Handle ID capturing results
3.0.4.1 Remove redundant frame batch ids
If the APIs is called by the SDK, please skip this step.
// 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
If the APIs is called by the SDK, please skip the image upload step.
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:
{
"file": "<byte[] dataToUpload>",
"label": "proper label, check the API document for detail"
}
3.0.4.3. Check ID Tampering
If the APIs is called by the SDK, please skip this step.
Call this API https://ekyc.trustingsocial.com/api-reference/customer-api/#request-detect-id-card-tampering with params:
{
"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 the APIs is called by the SDK, please skip this step.
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
TVImageClass frontQrImage = result.getFrontIdQr().getImages().get(i);
Map<String, String> metadata = frontQrImage.getMetadata();
String label = frontQrImage.getLabel();
byte[] data = frontQrImage.getImageByteArray();
*The same logic will be applied to result.getBackIdQr()
3.0.5 Scan NFC in back ID card capturing step
If the APIs is called by the SDK, please skip this step.
After capture the back card, if the card has nfc chip, SDK will call readIdCardImage method in background thread. With image that returned by readIdCardImage,
call api or do anything to detect id number of the card then return tvNfcParams to start flow scan NFC. If id number is null or empty, SDK skip flow scan NFC and continue
override fun readIdCardImage(image: TVImageClass): TVNfcParams? {
var idNumber: String? = null;
// call api or do any thing to read and return id number
// TODO
return TVNfcParams(idNumber, null, null, null)
}
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
TVSelfieConfiguration configuration = new TVSelfieConfiguration.Builder()
.setCameraOption(TVSDKConfiguration.TVCameraOption.FRONT)
.setEnableSound(false)
.setLivenessMode(TVLivenessMode.PASSIVE)
.setEnableVerticalChecking(false)
.setSkipConfirmScreen(false)
.setEnableUploadFrames(true)
.setEnableUploadImages(true)
.setEnableSanityCheck(true)
.setEnableVerifyLiveness(true)
.build();
Options:
- setCameraOption:
TVCameraOption. Camera mode - setEnableSound:
boolean. Sound should be played or not - setLivenessMode:
TVLivenessMode. Liveness verification mode - setEnableVerticalChecking:
boolean. Check if the phone is vertical or not before - setSkipConfirmScreen:
boolean. Control whether the SDK should skip the confirmation screen. - setEnableUploadFrames:
boolean. Enable upload video frames or not. If it's false then the SDK won't call the API to upload the frames and the APIs that need the video frames will be skipped or called with empty frames data. - setEnableUploadImages:
boolean. Enable upload images or not. If it's false then the SDK won't call the API to upload the images and the APIs that need the image will be skipped. - setEnableSanityCheck:
boolean. Enable sanity check or not. If it's true then the SDK will call the API to check the sanity of the selfie. - setEnableVerifyLiveness:
boolean. Enable liveness verification or not. If it's true then the SDK will call the API to verify the liveness of the selfie.
3.1.2. Start selfie capturing activity from configuration
TrustVisionSDK.INSTANCE.startSelfieCapturing(activity, configuration, new TVCapturingCallBack() {
@Override
public void onNewFrameBatch(FrameBatch frameBatch) {
}
@Override
public void onError(TVDetectionError error) {
}
@Override
public void onSuccess(TVDetectionResult result) {
}
@Override
public void onCanceled(TVCancelReason reason){
}
});
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
- getId():
- frameBatch:
- onSuccess method that will be called in case of success. The
onSuccessmethod has one parameter.- result :
TVDetectionResult. has the following methods:- getFaces():
List<TVImageClass> - getGestureFaces():
List<TVGestureFace> - getLivenessFrameBatchIds():
Collection<String> - getLivenessMetadata():
JSONObject
- getFaces():
- result :
- onError:
ErrorCallback. Will be called when an error has occurred during the capturing.- error:
TVDetectionError
- error:
- onCanceled:
CancellationCallback. Will be called when the journey has been cancelled (e.g user clicked on back button...)
- onNewFrameBatch:
3.1.3. Handle onNewFrameBatch callback
If the APIs is called by the SDK, please skip this step.
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-videoaudioframes
For example:
// this dictionary will be used for Liveness verification
Map selfieFrameBatchIdsDictionary = new HashMap<String, String>();
// frameBatchIdsDictionary.put(
// key = <id_returned_from_sdk>,
// value = <id_responded_from_server>
// );
@Override
public void onNewFrameBatch(FrameBatch frameBatch) {
Gson gson = new Gson();
String framesStr = gson.toJson(frameBatch.getFrames());
Map<String, Object> params = new HashMap<>();
params.put("frames", framesStr);
params.put("metadata", frameBatch.getMetadata());
params.put("label", "video");
String jsonToBeUploaded = gson.toJson(map);
// upload frame batch to server using this api:
// https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-videoaudioframes
YourResponseObject uploadingResult = yourMethodToUploadFrameBatch(jsonToBeUploaded);
// Keep the id that generated by the SDK corresponding with the one responded from server
selfieFrameBatchIdsDictionary.put(
key = frameBatch.getId(),
value = uploadingResult.fileId
);
}
3.1.4. Handle selfie results
3.1.4.1 Remove redundant frame batch ids
If the APIs is called by the SDK, please skip this step.
// 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 The images should be uploaded as JPEG data with 100% quality.
For example:
// These lists of image ids will be used in Liveness Verification
List<String> frontalImageIds = new ArrayList<>();
List<String> gestureImageIds = new ArrayList<>();
@Override
public void onSuccess(TVDetectionResult result) {
handleSelfieImages(result.getFaces(), result.getGestureFaces();
}
private void handleSelfieImages(List<TVImageClass> faces, List<TVGestureFace> gestureFaces) {
for (face: faces) {
// Handle frontal images
if (face.getImageByteArray() != null){
byte[] frontalImageByteArray = face.getImageByteArray();
// frontalImageId is the id of the image, returned from server when the uploading API is completed successfully
String frontalImageId = yourUploadImageMethod(frontalImageByteArray);
frontalImageIds.add(frontalImageId);
}
}
for (face: gestureFaces) {
for (image: face.getImages) {
// Handle gesture images
if (image.getImageByteArray() != null){
byte[] gestureImageByteArray = image.getImageByteArray();
// gestureImageId is the id of the image, returned from server when the uploading API is completed successfully
String gestureImageId = yourUploadImageMethod(gestureImageByteArray);
gestureImageIds.add(gestureImageId);
}
}
}
}
Upload Image API request, parameters:
{
"file": "<byte[] dataToUpload>",
"label": "<proper label, check the API document for detail>"
}
3.1.4.3. Liveness Verification
If the APIs is called by the SDK, please skip this step.
API document: https://ekyc.trustingsocial.com/api-reference/customer-api/#verify-face-liveness
Call the above api with below parameters:
imagesfield
{
"images": [
{
"id": "<frontalImageIds.get(index)>"
},
{
"id": "<frontalImageIds.get(index + 1)>"
},
...
]
}
gesture_imagesfield
{
"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)>"
}
]
},
...
]
}
videosfield
{
"videos": [
{
"id": "<validServerFrameBatchIds.get(index)>"
},
{
"id": "<validServerFrameBatchIds.get(index + 1)>"
},
...
]
}
metadatafield
{
"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
TVQRConfiguration.Builder builder= new TVQRConfiguration.Builder()
.setCardTypes(cards)
.setCardSide(TVSDKConfiguration.TVCardSide.FRONT)
.setEnableSound(false)
.setSkipConfirmScreen(false)
.setEnableUploadFrames(true)
.setEnableUploadImages(true);
TVQRConfiguration configuration=builder.build();
Options:
- setCardTypes:
List<TVCardType>. List of supported cards can be found byTrustVisionSDK.getCardTypes()if you set jsonConfigurationByServer when init SDK. If not, use :
new TVCardType(
"vn.national_id",
"CMND cũ / CMND mới / CCCD",
true,
TVCardType.TVCardOrientation.HORIZONTAL,
null,
null
);
- 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. - setEnableUploadFrames:
boolean. Enable upload video frames or not - setEnableUploadImages:
boolean. Enable upload images or not
3.2.2. Start QR Scanning activity from configuration
TrustVisionSDK.INSTANCE.startQRScanning(activity, configuration, new TVCapturingCallBack(){
@Override
public void onError(TVDetectionError error){
}
@Override
public void onSuccess(TVDetectionResult result){
}
@Override
public void onCanceled(TVCancelReason reason){
}
});
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
onSuccessmethod has one parameter.- result :
TVDetectionResult. has the following methods:- getFrontIdQr():
TVCardQr - getBackIdQr():
TVCardQr
- getFrontIdQr():
- result :
- onError:
ErrorCallback. Will be called when an error has occurred during the capturing.- error:
TVDetectionError
- error:
- onCanceled:
CancellationCallback. Will be called when the journey has been cancelled (e.g user clicked on back button...)
- onSuccess method that will be called in case of success. The
3.2.3 Upload QR images
If the APIs is called by the SDK, please skip this step.
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
TVImageClass frontQrImage = result.getFrontIdQr().getImages().get(i);
Map<String, String> metadata = frontQrImage.getMetadata();
String label = frontQrImage.getLabel();
byte[] data = frontQrImage.getImageByteArray();
*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
TVNfcConfiguration.Builder builder = TVNfcConfiguration.builder()
.setNfcCode(nfcCode)
.setHashSod(sod)
.setIssueDate(issueDate)
.setCachedFields(cachedFields)
.setRequestReadImageNfc(true)
.setRequestIntegrityCheckNfc(true)
.setRequestCloneDetectionNfc(true)
.setNfcMaxRetries(5)
.setEnableCheckNfcData(true)
.setEnableVerifyNfc(true);
TVNfcConfiguration configuration = builder.build();
Options:
- setNfcCode:
Stringis the id number of ID card - setHashSod:
String(optional) is the hash of SOD - setIssueDate:
String(optional) is the issue date of ID card (DD/MM/YYYY) - setCachedFields:
List<String>(optional) is the list of fields that was cached from previous scanning - setRequestReadImageNfc:
boolean(optional) read image in the chip when scan nfc or not - setRequestIntegrityCheckNfc:
boolean(optional) check integrity of the chip when scanning nfc or not - setRequestCloneDetectionNfc:
boolean(optional) check clone of the chip when scanning nfc or not - setNfcMaxRetries:
Int. (optional) The maximum number of times the SDK retries an NFC scanning before giving up - setEnableCheckNfcData:
boolean. Enable check NFC data or not. If it's true then the SDK will call the API to get sod and cached fields of the NFC data. - setEnableVerifyNfc:
boolean. Enable verify NFC or not. If it's true then the SDK will call the API to verify the NFC data.
3.3.2. Start nfc scanning activity from configuration
TrustVisionSDK.INSTANCE.startNfcScanning(activity, configuration, new TVCapturingCallBack() {
@Override
public void onCanceled(TVCancelReason reason) {
}
@Override
public void onSuccess(@NonNull TVDetectionResult result) {
}
@Override
public void onError(@NonNull TVDetectionError error) {
}
});
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
onSuccessmethod has one parameter.- result :
TVDetectionResult. has the following methods:- getNfcInfoResult():
TVNfcInfoResult
- getNfcInfoResult():
- result :
- onError:
ErrorCallback. Will be called when an error has occurred during the capturing.- error:
TVDetectionError
- error:
- onCanceled:
CancellationCallback. Will be called when the journey has been cancelled (e.g user clicked on back button...)
- onSuccess method that will be called in case of success. The
3.4. Face authentication
The Face Authentication activity will show the guideline screen. To start the Face Authentication activity.
3.4.1. Set config parameters
TVFaceAuthenticationConfiguration configuration = TVFaceAuthenticationConfiguration.builder()
.setCusUserId("1")
.setAuthType(AuthType.AUTH)
.setAuthMode(TVAuthMode.flashEdge())
.setEnableFaceAuthentication(true)
.setEnableFaceRegistration(true)
.build();
Options:
- cusUserId:
String. The customer user id - authType:
AuthType. Type of authentication,AUTHorREGISTRATION - authMode:
TVAuthMode. The source of authentication process, it might beNfcorSelfie - isEnableFaceAuthentication:
boolean. Enable call API face authentication or not - isEnableFaceRegistration:
boolean. Enable call API face registration or not
3.4.2. Start face authentication with configuration
TrustVisionSDK.INSTANCE.startFaceAuthentication(activity, configuration, new TVCapturingCallBack() {
@Override
public void onNewFrameBatch(FrameBatch frameBatch) {
}
@Override
public void onError(TVDetectionError error) {
}
@Override
public void onSuccess(TVDetectionResult result) {
}
@Override
public void onCanceled(TVCancelReason reason){
}
});
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- 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
- getId():
- frameBatch:
- onSuccess method that will be called in case of success. The
onSuccessmethod has one parameter.- result :
TVDetectionResult. has the following methods:- getFaceAuthenticationResult():
TVFaceAuthenticationResult - getFaces():
List<TVImageClass> - getGestureFaces():
List<TVGestureFace>
- getFaceAuthenticationResult():
- result :
- onError:
ErrorCallback. Will be called when an error has occurred during the capturing.- error:
TVDetectionError
- error:
- onCanceled:
CancellationCallback. Will be called when the journey has been cancelled (e.g user clicked on back button...)
- onNewFrameBatch:
3.4.3 Sample code
Note: Sample code for face authentication in the case of initializing the SDK with the parameters endpoint, accessKeyId, and accessKeySecret.
TVFaceAuthenticationConfiguration configuration = TVFaceAuthenticationConfiguration.builder()
.setCusUserId("1")
.setAuthType(AuthType.AUTH)
.setAuthMode(TVAuthMode.FlashEdge())
.setEnableFaceAuthentication(false)
.setEnableFaceRegistration(false)
.build();
TrustVisionSDK.INSTANCE.startFaceAuthentication(activity, configuration, new TVCapturingCallBack() {
@Override
public void onError(TVDetectionError error) {
}
@Override
public void onSuccess(TVDetectionResult result) {
List<TVSyncFile> faceIds = new ArrayList();
List<TVGestureImage> gestureFaces = new ArrayList();
List<TVVideoFile> videoIds = new ArrayList();
String cusUserId = "1";
String selfieType = "selfie";
String authType = "transfer";
for (TVImageClass face: result.getFaces()) {
faceIds.add(TVSyncFile.createById(face.getImageId());
}
for (TVGestureFace gesture: result.getGestureFaces()) {
String gestureName = gesture.getGesture();
List<TVSyncFile> ids = new ArrayList();
for (TVImageClass img: gesture.getImages()) {
ids.add(TVSyncFile.createById(img.getImageId()));
}
gestureFaces.add(new TVGestureImage(gesture, ids));
}
for (String id: result.getLivenessFrameBatchIds()) {
videoIds.add(TVVideoFile.createById(id));
}
// SDK uploads images to the server and returns the image IDs to the host app
// call api to verify face authentication
// /api-docs/face-authentication-api/authenticate/
yourMethodToCallFaceAuthenticationAPI(
cusUserId,
faceIds,
gestureFaces,
videoIds,
selfieType,
authType
);
}
@Override
public void onCanceled(TVCancelReason reason){
}
});
3.5. Error handling
// [FlowStartingFunc]: startIdCapturing, startSelfieCapturing, startQRScanning, startNfcScanning
TrustVisionSDK.INSTANCE.[FlowStartingFunc](..., builder.build(), new TVCapturingCallBack() {
@Override
public void onError(TVDetectionError error) {
String message = error.getErrorDescription();
Log.d("", message);
showToast(message);
///////////////////////////////////////
// ERROR HANDLER
int code = error.getErrorCode();
String description = error.getErrorDescription();
switch code {
case TVDetectionError.CONFIGURATION_ERROR:
// Invalid configuration
case TVDetectionError.DETECTION_ERROR_PERMISSION_MISSING:
// No camera permission.
case TVDetectionError.DETECTION_ERROR_CAMERA_ERROR:
// The camera can't be opened.
case TVDetectionError.DETECTION_ERROR_SDK_INTERNAL:
// The SDK has an unexpected error.
case TVDetectionError.DETECTION_ERROR_NFC:
// The SDK has an unexpected error when scanning NFC
}
}
@Override
public void onSuccess(TVDetectionResult result) {
}
@Override
public void onCanceled(TVCancelReason reason) {
}
});
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
boolean isNfcSupport = BooleanTrustVisionSDK.INSTANCE.isNfcSupport(Context);
4.1. Get Device Info
Allow users to get device information: DeviceInfo
DeviceInfo info = TrustVisionSDK.INSTANCE.getDeviceInfo(Context);
DeviceInfo contains following properties (will return empty string if SDK cannot get information of that property)
| Property | Type | Description |
|---|---|---|
id | String | Device Id |
udid | String | Same as above, Unique Device Id |
sn | String | Serial Number |
imei | String | IMEI |
manufacturer | String | Manufacturer |
deviceName | String | Device name |
wlanMac | String | Wireless mac address |
phoneNumber | String | Current Phone Number |
location | Location | Location information {longitude, latitude} |
Location contains following properties (will return empty string if SDK cannot get information of that property)
| Property | Type |
|---|---|
longitude | String |
latitude | String |
API Interface
1. TVLivenessResult
| Method | Type | description |
|---|---|---|
isLive | Boolean | Determines whether the selfie is live or not |
getScore() | float | The score from 0 to 1 |
2. TVDetectionResult
| Method | Type | description |
|---|---|---|
getFaces() | List<TVImageClass> | List of images that each item contains the bitmap of the selfie image |
getGestureFaces() | List<TVGestureFace> | 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() | JSONObject | Collected data during liveness checking process |
| Method | Type | description |
|---|---|---|
getFrontCardImage() | TVImageClass | Contains bitmap of the front image |
getBackCardImage() | TVImageClass | Contains bitmap of the back image |
getQRImage() | TVImageClass | Contains 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() | TVNfcInfoResult | Contains info from nfc chip. Use it to call api verify NFC |
| Method | Type | description |
|---|---|---|
getError() | TVDetectionError | The error found when doing any detection |
3. TVGestureFace
| Method | Type | description |
|---|---|---|
gesture | String | Gesture type of images |
images | List<TVImageClass> | Gesture images |
4. FaceDetectionType
| Method | Type | description |
|---|---|---|
getType() | int | Represent a gesture type |
int NEUTRAL = 1
int TURN_LEFT = 5
int TURN_RIGHT = 6
int FACE_UP = 7
int FACE_DOWN = 8
5. TVImageClass
| Method | Type | description |
|---|---|---|
getLabel() | String | Label of the Image class. |
getImage() | Bitmap | Captured Bitmap |
getImageByteArray() | byte[] | Captured image as byte array |
getImageId() | String | The image id |
getEncryptedHexString() | String | Encrypted image as hex string |
getMetadata() | Map<String, String> | Metadata of the image |
6. TVDetectionError
| Method | Type | description |
|---|---|---|
getErrorCode() | int | Error code |
getErrorDescription() | String | Error description |
Error code is one of the below list
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...
- TVLivenessMode.FLASH: Use challenge-response approach (advanced). User needs to follow and finish all steps when capturing selfie like far, close, flash.
We have different mechanisms for flash:
- TVLivenessMode.FLASH_EDGE: less frames for detecting than advanced.
- TVLivenessMode.FLASH_ADVANCED: full frames, highest quality for liveness detection.
- TVLivenessMode.FLASH_8: use around 8 frames for liveness detection.
- TVLivenessMode.FLASH_16: use around 16 frames for liveness detection.
- TVLivenessMode.FLASH_32: use around 32 frames for liveness detection.
9. TVDefaultCameraSide (Enum)
- TVDefaultCameraSide.FRONT
- TVDefaultCameraSide.BACK
10. FrameBatch
| Method | Type | description |
|---|---|---|
getFrames() | List<TVFrameClass> | Recorded frames during the capturing |
getId() | String | Local 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
| Method | Type | description |
|---|---|---|
getFramesBase64() | String | The data of the frame as a base64 String |
getIndex() | String | Index of this frame in the list of recorded frames |
getLabel() | String | Label of this frame |
getMetadata() | Map<String, String> | Metadata 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
| Method | Type | Description |
|---|---|---|
getCom() | String | |
getSod() | String | |
getDg1() | String | |
getDg2() | String | |
getDg13() | String | |
getDg14() | String | |
getDg15() | String | |
getVerificationResult() | TVNfcVerificationResult |
14. TVNfcVerificationResult
| Method | Type | Description |
|---|---|---|
getCloneStatus() | TVNfcVerificationStatus | |
getIntegrityStatus() | TVNfcVerificationStatus | |
getBcaStatus() | TVNfcVerificationStatus |
14. TVNfcVerificationStatus
| Method | Type | Description |
|---|---|---|
getError() | TVDetectionError | |
getVerdict() | TVNfcVerdict | TVNfcVerdict.NOT_CHECKED TVNfcVerdict.ALERT TVNfcVerdict.GOOD TVNfcVerdict.ERROR |
15. TVAuthMode (Sealed)
- TVAuthMode.Nfc: process face authentication from IDCard with Nfc Chip.
- config: [
TVIDConfiguration] ID Card configuration
- config: [
- TVAuthMode.Selfie: process face authentication from front side camera. This is an abstract mode, it has many implementation modes.
- config: [
TVSelfieConfiguration] Selfie configuration - livenessMode: [
TVLivenessMode] selfie liveness mode - TVAuthMode.Passive: implementation of
TVAuthMode.Selfiethat usingPASSIVElivenessMode - TVAuthMode.Active: implementation of
TVAuthMode.Selfiethat usingACTIVElivenessMode - TVAuthMode.Flash: implementation of
TVAuthMode.Selfiethat usingFLASHlivenessMode - TVAuthMode.FlashEdge: implementation of
TVAuthMode.Selfiethat usingFLASH_EDGElivenessMode - TVAuthMode.FlashAdvanced: implementation of
TVAuthMode.Selfiethat usingFLASH_ADVANCEDlivenessMode - TVAuthMode.Flash8: implementation of
TVAuthMode.Selfiethat usingFLASH_8livenessMode - TVAuthMode.Flash16: implementation of
TVAuthMode.Selfiethat usingFLASH_16livenessMode - TVAuthMode.Flash32: implementation of
TVAuthMode.Selfiethat usingFLASH_32livenessMode
- config: [
16. TVFaceAuthenticationResult
| Method | Type | Description |
|---|---|---|
| getRequestId() | String | |
| getStatus() | String | |
| getScore() | Double | |
| getMatchResult() | MatchResult | MATCHED, UNMATCHED, UNSURE |