# @trulioo/docv-capture

Trulioo DocVCapture SDK - React Native

## API Reference
https://docs.verification.trulioo.com/sdk/getting-started/index.html

## Installation

```bash
npm i @trulioo/docv-capture
cd ios && pod install
```

## Document Capture and Verification Flow Overview

### Starting a new document verification transaction

Create an instance of `TruliooCapture` and call the `initialize` function using the shortcode obtained from the Trulioo API endpoint: `/customer/handoff`.
This will create a new document verification transaction with a unique Transaction ID.

```typescript jsx showLineNumbers
const shortCode = "generatedFromTruliooAPI"

const truliooCapture = new TruliooCapture()

truliooCapture.initialize(shortCode).then((transactionId: string) => {
    console.log(`Successfully initialized with transaction ID: ${transactionId}`)
}).catch((error: any) => {
    console.log(`Error on initialize: ${error}`)
})
```



### Creating and rendering a camera component

Using the same created instance of `TruliooCapture`, we can get a camera component to be rendered later by calling the `getCameraComponent` function.
We can specify the camera detection type by providing a `TruliooCameraConfig` with the desired `DetectionType`.

```typescript jsx showLineNumbers

// Will get a document detection type camera by default.
const documentCamera = truliooCapture.getCameraComponent()


// To get a selfie detection type camera.
const selfieCamera = truliooCapture.getCameraComponent({
  detectionType: DetectionType.BIOMETRIC_SELFIE,
})
```

To render the camera component on the screen, we just need to render the View of the camera component. This will render a full screen camera on the screen.
The `onCaptureRegionChange` callback function is provided, which will return the current capture frame coordinates location (the location on the camera screen where the document/face should be located to do a capture).
We can utilize this coordinate information to render a custom UI overlay.
The camera View component also provides an option for a customizable background color for the camera mask overlay and a place to render a custom animation that will be rendered on top of the camera component.

```typescript jsx showLineNumbers
render() {
    return (
        <documentCamera.View
            backgroundColor={'#00000000'} // A custom background color for the camera mask overlay.
            onCaptureRegionChange={(captureRegion: CaptureRegion) => {
                // Utilize the given captureRegion data to render custom UI.
            }}
            animationComponent={
                // Custom animation component that will be render on top of the camera.
                <CustomAnimationExample />
            }
        />
    )
}
```

Additionally, if we want to resume the camera feed again after a successful auto or manual capture, we can call the `resumeCamera` function.

```typescript jsx showLineNumbers
documentCamera.resumeCamera()
```

### Starting the document capture flow

Once the camera component is loaded and ready, we can start the document capture experience by calling `startFeedbackWithVerify` from the previously created `TruliooCapture` instance.

To do an auto capture experience (a good document/selfie image criteria decided entirely by SDK), we can simply call `startFeedbackWithVerify` by just providing the camera id that refers to the
currently active/rendered camera component. The promise will only resolve when the SDK manages to capture a good image that is presented in front of the camera capture frame.

```typescript jsx showLineNumbers
truliooCapture.startFeedbackWithVerify(documentCamera.id).then((result: ITruliooCaptureResponse) => {
    console.log(`Successfully captured a good image with imageId: ${result.imageId}`)
})
```

We can also stop the feedback by calling the `stopFeedback` function. This will stop any ongoing feedback from the camera component.

```typescript jsx showLineNumbers
truliooCapture.stopFeedback(documentCamera.id)

```
Note that if the `stopFeedback` function is called during an ongoing `startFeedbackWithVerify` promise, the `startFeedbackWithVerify` promise is expected to be rejected with the specific `FeedbackStopped` error.
It is recommended to check this specific error to make sure it is not treated as an unexpected error.

```typescript jsx showLineNumbers
import { HandledError } from '@trulioo/docv-capture'

truliooCapture.startFeedbackWithVerify(documentCamera.id).then((result: ITruliooCaptureResponse) => {
    console.log(`Successfully captured a good image with imageId: ${result.imageId}`)
}).catch((error: unknown) => {
    if (error instanceof HandledError.FeedbackStopped) {
        console.log("startFeedbackWithVerify was stopped.")
    } else {
        // Other error handling
    }
})
```

Additionally, if we want to do a manual capture instead. We can call the `captureLatestFrame` function. This will return a `ITruliooManualCaptureResponse` that is similar to the `ITruliooCaptureResponse` excluding the auto capture specific fields.

Note that we would want to make sure the camera feed is currently running before triggering the manual capture, hence we can resume the camera again after a successful auto or manual capture using the `resumeCamera` function if we want to trigger another capture.

```typescript jsx showLineNumbers

truliooCapture.captureLatestFrame(documentCamera.id).then((result: ITruliooManualCaptureResponse) => {
    console.log(`Successfully captured an image manually with imageId: ${result.imageId}`)
})


```

The SDK also provides the `onFeedbackState` function that we can listen to for the ongoing capture state updates that is started by the `startFeedbackWithVerify` function.
This allows us to add any logic or render necessary custom UI based on the current capture state.
It is recommended to call the `onFeedbackState` function and start listening to the feedback state before calling the `startFeedbackWithVerify` function.


```typescript jsx showLineNumbers

truliooCapture.onFeedbackState((feedbackState: FeedbackState) => {
        switch (feedbackState) {
            case FeedbackState.NONE:
                // Nothing happened yet/no document detected at this point.
                break
            case FeedbackState.CAPTURING:
                // Currently in the middle of capturing a document.
                break
            case FeedbackState.BLUR:
                // The detected document is blurry. Show a blur UI feedback to user.
                break
            case FeedbackState.SUCCESS:
                // Managed to capture a document.
                break
            default:
                break
        }
    },
)

```

Note that the above flow is the same for the selfie capture type too.



### Analyzing the captured image result through post capture verify response

Once we have the resulting `ITruliooCaptureResponse` or `ITruliooManualCaptureResponse` image data, we are able to get a post capture feedback by simply calling the `verifyImage` function that is
part of the response data. This will give us more information regarding the captured image and let us decide whether we should submit the captured image for
verification by calling the `acceptImage` function.

Additionally, the post capture verify response also has a `requiresBackCapture` boolean field. This will give us information on whether the document requires a back capture or not.

```typescript jsx showLineNumbers

// As an example, we will submit the captured image for document verification if the post capture feedback VerificationStatus is CAN_BE_PROCESSED.
// Note that the documentVerifyResponse will have more than just documentTypeAccepted, the below code is just an example of just checking for documentTypeAccepted.

result.verifyImage().then((verifyFeedback: ITruliooVerifyResponse) => {
    if (verifyFeedback.verificationStatus == VerificationStatus.CAN_BE_PROCESSED) {

        // Note that the acceptImage can be called outside of the verifyImage function.
        result.acceptImage().then((status: boolean) => {
            console.log("Successfully submitted the image.")
            if (verifyFeedback.requiresBackCapture) {
                // Proceed to do a back capture flow.
            } else {
                // Proceed to the other flow, etc.
            }
        })
    } else {
        // Do something else, e.g., notify the user about the not accepted image and retake a new image.
    }
})

```



### Finalize the document verification transaction

Once we have submitted all the necessary images for the transaction, we can finalize the transaction by calling the `submitTransaction` function.

```javascript showLineNumbers

truliooCapture.submitTransaction().then((status: boolean) => {
    console.log("Transaction successfully submitted.")
})

```
