> For the complete documentation index, see [llms.txt](/llms.txt)

# Custom callbacks

## Start here

It is possible to integrate with the Entrust Identity Verification SDKs and use the data captured from the user, without the requirement of using this data only through the API. Custom callbacks enable you to control the end user data collected by the SDK after the end user has submitted their captured media. As a result, you can leverage Entrust's advanced on-device technology, including image quality validations, while still being able to handle end users’ data directly. This unlocks additional use cases, including compliance requirements and multi-vendor configurations, that require this additional flexibility.

Follow this guide to use custom callbacks with the Web, Android, iOS, React Native and Flutter Smart Capture SDKs.

**This feature must be enabled for your account.** Please contact your Entrust Solution Engineer or Customer Success Manager.

## Web

Custom callbacks that are invoked when the end user submits their captured media allow you to control the end user data collected by the SDK. The callbacks provide all of the information that would normally be sent directly to the API to you and expects a promise in response that controls what the SDK does next.

### Implementation

To use this feature, set `useCustomizedApiRequests` to `true` and provide the callbacks for `onSubmitDocument`, `onSubmitSelfie` and `onSubmitVideo` within the `enterpriseFeatures` block of the configuration options when initializing the SDK.

```javascript
Onfido.init({
  // Other options here
  enterpriseFeatures: {
    useCustomizedApiRequests: true,
    onSubmitDocument: (documentData) => {
      // Your callback code here
    },
    onSubmitSelfie: (selfieData) => {
      // Your callback code here
    },
    onSubmitVideo: (videoData) => {
      // Your callback code here
    },
  },
})
```

### Cross-device flow

In order to also use this feature on the Web SDK cross-device flow, you must host the cross-device experience of the SDK yourself. You can do this by specifying a custom or whitelabel cross-device URL that the cross-device flow will redirect to instead of the default `id.onfido.com`.

1. Generate an SDK token and use it to start the SDK.

```bash
$ curl https://api.onfido.com/v3.3/sdk_token \
 -H 'Authorization: Token token=YOUR_API_TOKEN' \
 -F 'applicant_id=YOUR_APPLICANT_ID' \
 -F 'referrer=REFERRER_PATTERN' \
 -F 'cross_device_url=YOUR_CUSTOM_URL'
```

**Note:** The custom URL can be a maximum of 24 characters long including the header (`https://`).

2. Set up a server to host the Web SDK at the provided URL

**Note:** The server must use the same version of the Web SDK.

3. Initialize the SDK with `Onfido.init({ mobileFlow: true })` as well as the callbacks and `useCustomizedApiRequests` options

For more information see [here](/sdk/web/#self-hosted-cross-device-url).

### User data

The callbacks return a FormData object, including the information that the SDK would send to Entrust. The callbacks are invoked when the end user confirms submission of their image through the SDK’s user interface.

**Note:** End user data will no longer be sent to the Entrust backend by default. If you want Entrust to process a check, you must upload the data to the API from your backend, or set `continueWithOnfidoSubmission: true`.

`onSubmitDocument` FormData Parameters:

```javascript
{
  file: blob,
  side: string,
  type: string,
  sdk_validations: object,
  sdk_source: string,
  sdk_version: string,
  sdk_metadata: object
}
```

`onSubmitSelfie` FormData Parameters:

```javascript
{
  file: blob,
  snapshot: blob,
  sdk_source: string,
  sdk_version: string,
  sdk_metadata: object
}
```

`onSubmtiVideo` FormData Parameters:

```javascript
{
  file: blob,
  challenge:  { type: 'recite' / 'movement', query: number[] / string }
  challenge_id: string,
  challenge_switch_at: number, // seconds
  languages: { source: 'sdk', language_code: string }
  sdk_source: string,
  sdk_version: string,
  sdk_metadata: object
}
```

### Create a check

After receiving the user data from the SDK, you can choose to create a check. In this case, you must either allow the SDK to upload the user data to the API or upload the user data yourself.

Please see our API documentation for more information on how to [create a check](/api/latest/#create-check).

#### Allow the SDK to upload data to Entrust

To allow the SDK to upload the user-submitted data directly to Entrust, you can resolve the promise with an object containing `continueWithOnfidoSubmission: true`.

```javascript
onSubmitDocument: (data) => {
  // Note: data is a FormData object, to view the contents you can use:
  for (const [key, value] of data.entries()) {
    console.log('data (key,value): ', key, value)
  }

  // Send data to your backend then resolve promise,
  return Promise.resolve({ continueWithOnfidoSubmission: true })
}
```

#### Upload user data to the API

You can upload the end user data to the API from your backend, after you have received it from the SDK callbacks. We strongly recommend that you include all of the data provided to you through the callbacks in your request to the appropriate endpoint.

[/documents](/api/latest/#upload-document)

[/live_photos](/api/latest/#upload-live-photo)

**Note:** The [/live_videos](/api/latest/#upload-live-video) endpoint is not currently available for direct upload to the API.

Additionally, you should use the SDK token created for each applicant in the Authorization header of the request.

`Authorization: Bearer `

**Note:** The SDK token is not included in the FormData provided by the callbacks. You may want to append this, or a different unique identifier that is mapped to the applicant's SDK token, on your backend before sending it off.

Once you have sent the request to Entrust from your backend, you can supply the SDK with the response so it can determine what the end user should be presented with. In the case where a success response is received, the promise should be resolved with `onfidoSuccessResponse: <onfidoResponse>`. Otherwise reject the promise with the error response.

**Note:** An error response could be returned due to image quality issues. In this case, the SDK will present the end user with the appropriate error message.

```javascript
onSubmitDocument: (data) => {
  // Send request to Onfido API /documents via your backend proxy
  .then(onfidoSuccessResponse =>
    Promise.resolve({ onfidoSuccessResponse: <onfidoResponse> }))
  .catch(onfidoError => Promise.reject(onfidoError))
}
```

We provide a [sample openAPI YAML file](/sdk/web/#managing-the-onfido-response) you could use as an example to start your own proxy.

## Android

### Implementation

To use this feature use `.withMediaCallback` and provide the callbacks for `DocumentResult`, `SelfieResult` and `LivenessResult`.

```java
onfidoConfigBuilder.withMediaCallback(new CustomMediaCallback());
private static class CustomMediaCallback implements MediaCallback {

    @Override
    public void onMediaCaptured(@NonNull MediaResult result) {
        if (result instanceof DocumentResult) {
            //TODO
        } else if (result instanceof LivenessResult) {
            //TODO
        } else if (result instanceof SelfieResult) {
            //TODO
        }
    }
}
```

```kotlin
onfidoConfigBuilder
  .withMediaCallback { mediaResult ->
      when(mediaResult){
          is DocumentResult -> // Your callback code here
          is SelfieResult -> // Your callback code here
          is LivenessResult -> // Your callback code here
      }
  }
```

**Note:** If you are using Java, don’t forget to set the inner class to static if outer class is not Serializable.
**Note:** If you are using Kotlin, don’t forget to use a nested class if the outer class is not Serializable.

### User data

The callbacks return an object including the information that the SDK normally sends directly to Entrust. The callbacks are invoked when the end user confirms submission of their image through the SDK’s user interface.

**Note:** Currently, end user data will still automatically be sent to the Entrust backend. You are **not** required to use Entrust to process this data.

#### Documents

For documents the callback returns a `DocumentResult` object:

```
    {
    fileData: MediaFile
    documentMetadata: DocumentMetadata
    }
```

**Note:** If a document was scanned using NFC, the callback will only return the `MediaFile`.

The `DocumentMetadata` object contains the metadata of the captured document.

```
    {
       side: String,
       type: String,
       issuingCountry: String
    }
```

**Note:** `issuingCountry` is optional based on end-user selection, and can be `null`.

#### Live photos and videos

For live photos the callback returns a `SelfieResult` object:

```
    {
      fileData: MediaFile
    }
```

For live videos the callback returns a `LivenessResult` object:

```
    {
      fileData: MediaFile
    }
```

The `MediaFile` object contains the raw data and MIME type of the captured photo or video.

```
    {
      fileData: ByteArray,
      fileType: String
    }
```

### Create a check

After receiving the user data from the SDK, you can choose to create a check. In this case, you don’t need to re-upload the end user data as it is sent automatically from the SDK to the Entrust backend.

Please see our API documentation for more information on how to [create a check](/api/latest/#create-check).

## iOS

### Implementation

To use this feature, use `.withMediaCallback` and provide the callbacks for `MediaDocumentResult` for documents and `MediaFile` for live photos and live videos.

```swift
final class SwiftDynamicFrameworkOnfidoRunner: OnfidoRunner, MediaCallback {
    func onMediaCaptured(result: MediaResult) {
           switch result {
               case let documentResult as MediaDocumentResult:
                   // Your callback code here
               case let selfieResult as SelfieResult:
                   // Your callback code here
               case let livenessResult as LivenessResult:
                   // Your callback code here
           default:
               Break
           }
    }
    configBuilder.withMediaCallback(mediaCallback: self)
}
```

### User data

The callbacks return an object including the information that the SDK normally sends directly to Entrust. The callbacks are invoked when the end user confirms submission of their image through the SDK’s user interface.

**Note:** Currently, end user data will still automatically be sent to the Entrust backend, but you are **not** required to use Entrust to process this data.

#### Documents

For documents, the callback returns a `MediaDocumentResult` object:

```json5
    {
        metadata: DocumentMetadata
        file: MediaFile
    }
```

**Note:** If a document was scanned using NFC, the callback will return the passport photo in `file` but no additional data.

The `DocumentMetadata` object contains the metadata of the captured document.

```json5
{
    side: String
    type: String
    issuingCountry: String?
}
```

**Note:** `issuingCountry` is optional based on end-user selection, and can be `null`

#### Live photos and videos

For live photos, the callback returns a `SelfieResult` object:

```json5
{
    fileData: MediaFile
}
```

For live videos, the callback returns a `LivenessResult` object:

```json5
{
    fileData: MediaFile
}
```

The `MediaFile` object contains:

```json5
{
    name: String
    data: Data
}
```

### Create a check

After receiving the user data from the SDK, you can choose to create a check. In this case, you don’t need to re-upload the end user data as it is sent automatically from the SDK to the Entrust backend.

Please see our API documentation for more information on how to [create a check](/api/latest/#create-check).

## React Native

### Implementation

To use this feature, use `Onfido.addCustomMediaCallback` and provide the callback.

```javascript
Onfido.addCustomMediaCallback((mediaResult) => {
  if (mediaResult.captureType === 'DOCUMENT') {
    // Callback code here
  } else if (mediaResult.captureType === 'FACE') {
    // Callback code here
  } else if (mediaResult.captureType === 'VIDEO') {
    // Callback code here
  }
})
```

### User data

The callbacks return an object including the information that the SDK normally sends directly to Entrust. The callbacks are invoked when the end user confirms submission of their image through the SDK’s user interface.

**Note:** Currently, end user data will still automatically be sent to the Entrust backend, but you are not required to use Entrust to process this data.

The callback returns 3 possible objects. Please note that `captureType` refers to the type of the media capture in each case.
These can be `DOCUMENT`, `FACE` or `VIDEO`.

For documents (`captureType` is `DOCUMENT`), the callback returns:

```json5
{
    captureType: String
    side: String
    type: String
    issuingCountry: String?
    fileData: String
    fileName: String
    fileType: String
}
```

**Notes:**

- `issuingCountry` is optional based on end-user selection, and can be `null`.
- `fileData` is a String representation of the byte array data corresponding to the captured photo of the document.
- If a document was scanned using NFC, the callback will return the passport photo in `fileData` but no additional data.

For live photos (`captureType` is `FACE`), the callback returns:

```json5
{
    captureType: String
    fileData: String
    fileName: String
    fileType: String
}
```

**Note:** `fileData` is a String representation of the byte array data corresponding to the captured live photo.

For videos (`captureType` is `VIDEO`), the callback returns:

```json5
{
    captureType: String
    fileData: String
    fileName: String
    fileType: String
}
```

**Note:** `fileData` is a String representation of the byte array data corresponding to the captured video.

Please note that, for your convenience, Entrust provides the `byteArrayStringToBase64` helper function to convert the `fileData` from String to a Base64 format. Here is an example of how to use it:

```javascript
let byteArrayString = mediaResult.fileData
let base64FileData = Onfido.byteArrayStringToBase64(byteArrayString)
```

## Flutter

### Implementation

To use this feature, implement the `OnfidoMediaCallback` interface and provide the callback for `OnfidoMediaResult` for documents, live photos and live videos.

```dart
class MediaCallback implements OnfidoMediaCallback {
  @override
  Future<void> onMediaCaptured({required OnfidoMediaResult result}) async {
    // Your callback code here
  }
}
```

Then you should pass this class to the SDK builder as a parameter:

```dart
MediaCallback callback = MediaCallback();

final Onfido onfido = Onfido(
    sdkToken: sdkToken,
    mediaCallback: callback,
    enterpriseFeatures: EnterpriseFeatures(
        hideOnfidoLogo: _hideOnfidoLogo,
    )
);
```