DocumentDetector

The @caf.io/react-native-document-detector library is responsible for capturing identity documents, such as the ID (Brazilian General Registry - RG), Drivers License (CNH), National Foreigner Registry

Requirements

The libraries are compatible only with React Native versions that are 0.66.5 or later.

Android

SettingsMinimum version

minSdkVersion

21

compileSdkVersion

33

Java version

8

iOS

SettingsMinimum version

Target

12

Xcode

14.3.1

Swift

5.5

Installation

yarn add @caf.io/react-native-document-detector
# or 
npm install @caf.io/react-native-document-detector

Android

Inside the android folder in app/build.gradle add the following code:

android {
  ...
  buildFeatures {
    dataBinding = true
  }
}

If you're utilizing Expo for your project, be sure to include that line in android/build.gradle.

allprojects { 
  repositories { 
    ... 
    maven { url "https://repo.combateafraude.com/android/release" } 
  } 
}

iOS

In the Podfile in the iOS folder, add this following sources:

source 'https://github.com/combateafraude/iOS.git'
source 'https://cdn.cocoapods.org'

Too add the use_frameworks! in the Podfile:

target 'App' do
  use_frameworks!
  ...
end

If you're using Flipper, comment out the following line in your Podfile:

:flipper_configuration => flipper_config

This is because Flipper does not support the use_frameworks! directive.

After editing your Podfile, save it and install the SDK along with its dependencies by running the following command:

pod install

Usage

import React from 'react';
import { View, Button, StyleSheet, Image } from 'react-native';
import {
  startDocumentDetector,
  useDocumentDetector,
  DocumentDetectorSettings,
  Stage,
  Document,
} from '@caf.io/react-native-document-detector';

export default function App() {
  const mobileToken: string = "";
  const personId: string = "";

  const uri = Image.resolveAssetSource(require('../assets/image.png')).uri;

  const options: DocumentDetectorSettings = {
    documentSteps: [
      {
        document: Document.RG_FRONT,
        showStepLabel: true,
        illustration: uri,
        stepLabel: 'Step Label',
      }
    ], // required
    cafStage: Stage.PROD // optional
  }

  const { 
    result, 
    error, 
    cancelled, 
  } = useDocumentDetector(options);

  return (
    <View style={styles.container}>
      <Button 
        title="Start" 
        onPress={() => startDocumentDetector(mobileToken, personId)} 
      />
    </View>
  );
} 

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Methods

startDocumentDetector

This method inicialize the document detector.

Params

ParamTypeRequiredDescription

mobileToken

string

Yes

Usage token associated with your Identity account

personId

string

Yes

User CPF

Hooks

useDocumentDetector

This hook provides the responses of method startDocumentDetector and make the settings for document detector.

Params

ParamTypeDefaultDescription

settings

Optional

Settings for the document detector

Responses

DocumentDetectorResponse

Types

DocumentDetectorResult

NameTypeDescription

captures

The array with the respective captures of the parameterized documents

trackingId

string

Identifier of this run on our servers. If possible, save this field and send it along to our API. This way we will have more data about how the user behaved during the execution

type

string

The class of the read document stream. This parameter is useful in an integration with our OCR route. The existing types are: ["blank", "cnh", "cnh_new", "generic", "rg", "rg_new", "rne", "rnm", "ctps", "passport, crlv, crlv_new"]

DocumentDetectorCapture

NameTypeDescription

imagePath

string

Where the image is located locally

imageUrl

string

URL of the document on CAF's server. If you want this URL, keep enabled the parameter that checks the image quality

label

string

Label of the respective document within the following possibilities: ["blank", "cnh_back", "cnh_front", "cnh_full", "new_cnh_back", "new_cnh_front", "new_cnh_full", "crlv", "crlv_new", "generic", "rg_back", "rg_front", "rg_full", "rg_new_back", "rg_new_front", "rg_new_full", "rne_back", "rne_front", "rnm_back", "rnm_front", "ctps_back", "ctps_front", "passport"]

quality

number

Quality inferred by the document quality algorithm, when enabled. Varies between 1.0 and 5.0

DocumentDetectorError

NameTypeDescription

statusCode

string

Https code status

message

string

Error message

error

Error

Error enum

DocumentDetectorResponse

NameTypeDescription

result

Shows when face authenticator returns a successful capture

error

Shows when the face authenticator return some error

cancelled

boolean

Shows when user cancel the face authenticator

DocumentDetectorSettings

NameTypeDescriptionAndroidiOSRequerid

documentSteps

Defines the document capture flow

Yes

captureStages

Configures the requirements for each capture stage. Designed to make capture more flexible in cases where the user is unable to capture with all checks active, preventing them from getting stuck at this stage in their registration flow.

No

cafStage

Change the development environment

No

analyticsSettings

boolean

Enables/disables data gathering for analytics.

No

popupSettings

boolean

Enables/disables the popups displayed before each document capture.

No

networkSettings

number

Defines SDK's requests timeout.

No

sensorSettings

Object of the configuration for define the sensors of the SDK.

No

proxySettings

Defines your proxy to make requests

No

previewSettings

Enables/disables and allows the configuration of the visualization of the capture performed, requesting the user's confirmation to proceed.

No

compressSettings

number

Allows you to configure the quality in the compression process. By default, all captures go through compression. The method expects values between 80 and 100 as a parameter, where 100 is the best quality compression.

No

manualCaptureSettings

number

Enables/disables manual capture.

No

imageUrlExpireTime

string

Sets the time the image URL will last on the server until it is expired. Expect to receive a time interval between "30m" to "30d". Examples: "30m": To set minutes only "24h": To set only hour(s) "1h 10m": To set hour(s) and minute(s) "10d": To set day(s)

No

currentStepDoneDelay

number

Delays the activity after the completion of each step.

No

resolutionSettings

Allows you to set the capture resolution.

No

allowedPassportList

Enables the option to allow passports from only a certain issuing country, or, a list of countries.

No

messageSettings

To custom messages use this object

No

uploadSettings

To enable the document upload functionality it is necessary to use this object

No

style

Defines the primary color and feedback colors of the SDK.

No

securitySettings

The SDK has some blocks that may prevent its execution in certain contexts. To disable them, you can use the methods as shown in the example below

No

DocumentDetectorStep

NameTypeDescription

document

Defines the document capture flow.

stepLabel

string

Defines text to be shown in the lower part of the layout.

showStepLabel

boolean

Present the text to be displayed at the top of the layout.

illustration

string

Defines illustration to be shown in the popup prior to capture.

DocumentDetectorCaptureStage

NameTypeDescription

captureMode

Defines the capture mode.

durationMillis

number

Duration of the stage, in milliseconds.

wantSensorCheck

boolean

Enables/Disables the use of sensors for capturing the photo.

DocumentDetectorSensorSettings

NameTypeDescription

luminositySensor

number

Defines threshold between acceptable/unacceptable ambient brightness.

orientationSensor

number

Defines threshold between correct/incorrect device orientation. Higher the value more flexible it will be.

stabilitySensor

Changes the default settings of the stability sensor. The threshold of this sensor is in the range of the last two accelerations collected from the device.

DocumentDetectorSensorSettingsStabilitySensor

NameTypeDescriptionAndroidiOS

stabledMillis

number

Defines stability sensor settings.

threshold

number

The threshold of this sensor is in the range of the last two accelerations collected from the device.

DocumentDetectorProxySettings

NameTypeDescription

hostname

string

Sets the domain or IP address of the proxy service.

port

number

Sets the port to be used.

authentication

Enables/Disables the use of sensors for capturing the photo.

DocumentDetectorProxySettingsAuthentication

NameTypeDescription

user

string

Username to be used for authentication.

password

number

Password to be used for authentication.

DocumentDetectorPreviewSettings

NameTypeDescription

show

boolean

Enables/disables and allows the configuration of the visualization of the capture performed, requesting the user's confirmation to proceed.

title

string

Sets the title shown on the screen.

subtitle

string

Sets the subtitle displayed on the screen.

confirmLabel

string

Sets the message displayed on the confirmation button.

retryLabel

string

Sets the message displayed on the button to perform a new capture.

DocumentDetectorMessageSettings

NameTypeDescriptionAndroidiOS

waitMessage

string

Message displayed when you start the camera

fitTheDocumentMessage

string

Message telling you to fit the document to the mask

holdItMessage

string

Message displayed at the moment the capture is being performed

verifyingQualityMessage

string

Message displayed when the SDK makes a request to the backend, checking for quality

lowQualityDocumentMessage

string

Message displayed when the capture quality fails

uploadingImageMessage

string

Message displayed when there is no quality check and the capture is being saved on the servers

openDocumentWrongMessage

string

Message displayed when displaying an open document, the message will be displayed together with the error message on the document being used, example: if the user displays an open CNH(Brazilian drive’s license), the standard error message "Essa é uma CNH Aberta" + the defined message will be displayed.

popupDocumentSubtitleMessage

string

Message displayed in the subtitle of the pop-up that brings the illustration of the document that is being requested for capture.

wrongDocumentMessage

string

Message displayed when the document is displayed in a different stream than expected.

unsupportedDocumentMessage

string

Message displayed when a unexpected type of document is displayed for capture

documentNotFoundMessage

string

Message displayed when a document is unknown

sensorLuminosityMessage

string

Message displayed when the brightness threshold is lower than expected

sensorOrientationMessage

string

Message displayed when the orientation threshold is lower than expected

sensorStabilityMessage

string

Message displayed when the orientation threshold is lower than expected

positiveButtonMessage

string

Allows for customization of the confirmation button message

predictorScanDocumentMessage

string

Message displayed to request a document to be present on the camera.

predictorGetCloserMessage

string

Message displayed to request to get closer to the document.

predictorCentralizeMessage

string

Message displayed to request to center the document.

predictorMoveAwayMessage

string

Message displayed to request to move away from the document.

predictorAlignDocumentMessage

string

Message displayed to request to align the document.

predictorTurnDocumentMessage

string

Message displayed to request to turn document 90 degrees.

predictorCapturedMessage

string

Message displayed to alert that the document was captured.

DocumentDetectorUploadSettings

NameTypeDescription

enable

boolean

Enables/disables this feature

compress

boolean

Enables/disables file compression before uploading

fileFormats

Defines the file format(s) that will be accepted for upload

maxFileSize

number

Sets the maximum KB limit of the file to upload

DocumentDetectorStyle

NameTypeDescriptionAndroidiOS

primaryColor

string

Define the principal color of the SDK.

Use hexadecimal colors. Example: #34d690

feedbackColors

Colors of the feedback area.

Use hexadecimal colors. Example: #34d690

DocumentFeedbackColors

NameTypeDescription

defaultColor

string

Defines the default coolor for default feedback.

errorColor

string

defines the error color when there is an error capturing the document.

successColor

string

Sets the success color when the document is captured.

DocumentDetectorSecuritySettings

NameTypeDescription

useEmulator

boolean

Enables the use of emulator

useRoot

boolean

Enables the use of rooted devices

useDevelopmentMode

boolean

Enable developer mode on the physical device

useAdb

boolean

Enable the Android Debug Bridge (ADB)

useDebug

boolean

Enable debug mode for Android

Enums

Document

EnumDescription

RG_FRONT

Front of the RG, part where the photo is

RG_BACK

Back of the RG, where the data is

RG_FULL

RG open, showing both the front and back

CNH_FRONT

Front of the CNH, part where the photo is

CNH_BACK

Back of the CNH, part where the signature is

CNH_FULL

CNH open, showing both the front and back

CRLV

CRLV

RNE_FRONT

Front of RNE and RNM, where are the data

RNE_BACK

Back of RNE and RNM, where is the photo

PASSPORT

Passport, one side only, showing all data

CTPS_FRONT

Front of CTPS, where the photo is located

CTPS_BACK

Back of the CTPS, where it contains the data

OTHERS

Other identification documents in general, such as RNE, Military Identity, OAB and CRLV

ANY

Allows the sending of any type of document, all those mentioned above, including any other document, as no typifications are made

CaptureMode

EnumDescription

AUTOMATIC

Automatically scans the document

MANUAL

Scan the document manually

Stage

EnumDescription

BETA

Beta environment

PROD

Production environment

Resolution

EnumDescriptionAndroidiOS

FULL_HD

1920 x 1080

QUAD_HD

2560 x 1440

ULTRA_HD

3840 x 2160

CountryCodes

See the complete list at: ISO 3166-1 alpha-3. Example: CountryCodes.BRA

FileFormat

EnumDescriptionAndroidiOS

PNG

image/png

JPG

image/jpg

JPEG

image/jpeg

PDF

image/pdf

HEIF

image/heif

Error

EnumDescription

ServerReason

A server-side error/token invalidation occurred. The associated string (if available) will contain further information about the error

NetworkReason

An error occurred with the video streaming process. The associated string (if available) will contain further information about the error

InvalidTokenReason

The token entered is not valid for the corresponding product

PermissionReason

You are missing some mandatory permission to run the SDK

SecurityReason

When the SDK cannot be started due to a security reason

StorageReason

There is no space on the user device's internal storage

LibraryReason

When an SDK internal library cannot be started

UnexpectedReason

An unxpected error has occurred

Customizing Style

Android

On Android, to be able to customize the style, you need to have access to the react native android folder

Primary Color

Inside the android folder in android/app/src/main/res/styles.xml, add the following code:

...
<style name="primaryColorStyle" parent="Theme.MaterialComponents.DayNight.NoActionBar">
  <item name="colorPrimary">#f43d2f</item>
</style>

Feedback Colors

Inside the android folder in android/app/src/main/res/colors.xml, add the following code:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  ...
  <color name="defaultFeedbackStyle">#80FF6E</color>
  <color name="successFeedbackStyle">#B0F1FF</color>
  <color name="errorFeedbackStyle">#667818</color>
</resources>

How to use

import React from 'react';
import { Platform } from 'react-native';
import {
  useDocumentDetector,
} from '@caf.io/react-native-document-detector';

export default function App() {
  const { 
    result, 
    error, 
    cancelled, 
  } = useDocumentDetector({
    style: {
      primaryColor: Platform.OS === 'android' ? 'primaryColorStyle' : '#f43d2f',
      feedbackColors: {
        defaultColor: Platform.OS === 'android' ? 'defaultFeedbackStyle' : '#80FF6E',
        successColor: Platform.OS === 'android' ? 'successFeedbackStyle' : '#B0F1FF',
        errorColor: Platform.OS === 'android' ? 'errorFeedbackStyle' : '#667818',
      },
    },
  });

  return (
    ...
  );
} 

Last updated

Logo

2023 © Caf. - All rights reserved