> For the complete documentation index, see [llms.txt](https://docs.facephi.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.facephi.com/docs.facephi-en/sdks/sdk-mobile/android-sdk/ajustes-avanzados.md).

# Advanced settings

## Introduction <a href="#id-1-introduccion" id="id-1-introduccion"></a>

This section provides additional general information about the SDK launch.

***

## Advanced SDK Launch Information <a href="#id-2-informacion-avanzada-del-lanzamiento-del-sdk" id="id-2-informacion-avanzada-del-lanzamiento-del-sdk"></a>

This section provides additional information about the “Simplified Launch of the SDK” section.

### Add a private repository <a href="#id-21-anadir-repositorio-privado" id="id-21-anadir-repositorio-privado"></a>

For security and maintenance reasons, the new components of ***SDKMobile*** are stored in private repositories that require specific credentials to access. You can obtain these credentials from the *support team* at **Facephi**.

Once you have obtained the credentials, include the following code snippet to configure the Maven repository in your project's **Gradle** or in its **settings.gradle** file. We recommend adding it after *mavenCentral()*

```kotlin
maven {
    Properties props = new Properties()
    def propsFile = new File('local.properties')
    if(propsFile.exists()){
        props.load(new FileInputStream(propsFile))
    }
    name="external"
    url = uri("https://facephicorp.jfrog.io/artifactory/maven-pro-fphi")
    credentials {
        username = props["artifactory.user"] ?: System.getenv("USERNAME_ARTIFACTORY")
        password = props["artifactory.token"] ?: System.getenv("TOKEN_ARTIFACTORY")
    }
}
```

For the project to retrieve dependencies correctly, the credentials (username and Token) must be configured correctly.

There are several ways to configure repository access credentials:

* As environment variables with the following names. For example:

  ```
  export USERNAME_ARTIFACTORY=YOUR_CREDENTIALS_USERNAME
  export TOKEN_ARTIFACTORY=YOUR_CREDENTIALS_TOKEN
  ```

  **If the dependencies are not recognized during synchronization**, add them as environment variables in the file:

`~/.zshrc`

* Add them to the *local.properties* file using the following structure:

  ```
  artifactory.user=YOUR_CREDENTIALS_USERNAME
  artifactory.token=YOUR_CREDENTIALS_TOKEN
  ```

### SDK Initialization <a href="#id-22-inicializacion-del-sdk" id="id-22-inicializacion-del-sdk"></a>

**Avoid initializing a controller that will not be used.**.

The SDK works through a main controller (SDKController), which must be initialized correctly to use the rest of its functionality. Follow these steps to initialize it:

1. Include the Application object using the SdkApplication class.
2. Decide whether to provide the license as a *String* or through a *remote licensing service* (see the section **License Injection**).
3. The controller *TrackingController* if you want to connect to the platform.

The **step 3** is optional and requires using the Tracking component (see its own documentation for more information about this module).

`SdkConfigurationData` has the following fields:

| Field                | Type                   | Required                         | Description                                                                                                    |
| -------------------- | ---------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `sdkApplication`     | `SdkApplication`       | Yes                              | Object `Application` of the application, wrapped in `SdkApplication`.                                          |
| `licensing`          | `Licensing`            | Yes                              | How to inject the license: `LicensingOnline` or `LicensingOffline` (see **License injection**).                |
| `trackingController` | `ITrackingController?` | No (defaults to `null`)          | Tracking controller (`TrackingController`) to connect to the platform.                                         |
| `locale`             | `String?`              | No (defaults to `null`)          | SDK language (for example, `"es"` or `"en"`). If it is `null`, empty, or invalid, the system language is used. |
| `integrationId`      | `String?`              | No (defaults to `null`)          | Integration identifier. Only applies to licenses that allow it (demo environments).                            |
| `orientation`        | `SdkViewOrientation`   | No (defaults to `FOLLOW_SYSTEM`) | Orientation of the SDK views. Values: `PORTRAIT`, `PORTRAIT_PHONES`, `LANDSCAPE` and `FOLLOW_SYSTEM`.          |
| `internalOptions`    | `SdkInternalOptions?`  | No (defaults to `null`)          | Internal options, for development or demo only (see the **Security**).                                         |

An example of initialization without *TrackingController* would be as follows:

```kotlin
val sdkConfig = SdkConfigurationData(
    sdkApplication = SdkApplication(application),
    licensing = LicensingOffline("LICENSE")
)

val result = SDKController.initSdk(sdkConfig)

when (result) {
  is SdkResult.Success -> Napier.d("APP: INIT SDK: OK")
  is SdkResult.Error -> Napier.d(
          "APP: INIT SDK: KO - ${result.error.name}"
        )
}
```

An example of initialization with *TrackingController* would be as follows:

```kotlin
val sdkConfig = SdkConfigurationData(
    sdkApplication = SdkApplication(application),
    licensing = LicensingOffline("LICENSE"),
    trackingController = TrackingController(),
)

val result = SDKController.initSdk(sdkConfig)

when (result) {
  is SdkResult.Success -> Napier.d("APP: INIT SDK: OK")
  is SdkResult.Error -> Napier.d(
          "APP: INIT SDK: KO - ${result.error.name}"
        )
}
```

#### **License injection**

As mentioned previously, there are currently two ways to inject the license:

**a. Obtaining the license through a service**

Through a service that requires only an API key as an identifier and, optionally, a URL (`url`, whose default value is `https://licensing.facephi.pro`). This would avoid problems when handling the license, as well as the need to constantly replace licenses if an issue arises (malformation or unauthorized modification, expiration of the license...)

Kotlin implementation example:

```kotlin
val sdkConfig = SdkConfigurationData(
    sdkApplication = SdkApplication(application),
    licensing = LicensingOnline(EnvironmentLicensingData(
            apiKey = "...")
      ),
)

val result = SDKController.initSdk(sdkConfig)

when (result) {
  is SdkResult.Success -> Napier.d("APP: INIT SDK: OK")
  is SdkResult.Error -> Napier.d(
          "APP: INIT SDK: KO - ${result.error.name}"
        )
}
```

**b. Injecting the license as a String**

The license can be assigned directly as a String, as follows:

Kotlin implementation example:

```kotlin
val sdkConfig = SdkConfigurationData(
    sdkApplication = SdkApplication(application),
    licensing = LicensingOffline("LICENSE"),
)

val result = SDKController.initSdk(sdkConfig)

when (result) {
  is SdkResult.Success -> Napier.d("APP: INIT SDK: OK")
  is SdkResult.Error -> Napier.d(
          "APP: INIT SDK: KO - ${result.error.name}"
        )
}
```

#### **Receiving errors**

For errors, we have the SdkError class.

List of errors:

All errors have the fields `name`, `reason` and `code`. Those that receive a parameter `error: String` expose it as the `error`.

* EMPTY\_LICENSE: Empty license (reason: `SDK_EMPTY_LICENSE`, code: `SDK_003`)
* INIT\_AI\_MODELS(error: String): Error returned by the model download service (reason: `SDK_INIT_AI_MODELS`, code: `SDK_100`)
* INIT\_FLOW (error: String): Error returned by the flow download service (reason: `SDK_INIT_FLOW`, code: `SDK_101`)
* LICENSE\_CHECKER\_ERROR (error: String): Error returned while checking whether the license is valid (reason: `SDK_LICENSE_CHECKER_ERROR`, code: `SDK_102`)
* LICENSING\_ERROR (error: String): Error returned by the license download service (reason: `SDK_LICENSING_ERROR`, code: `SDK_103`)
* NETWORK\_CONNECTION\_ERROR: Internet connection error (reason: `SDK_NETWORK_CONNECTION_ERROR`, code: `SDK_104`)
* OPERATION\_ALREADY\_LAUNCHED: An operation is already being created (reason: `SDK_OPERATION_ALREADY_LAUNCHED`, code: `SDK_105`)
* TRACKING\_ERROR (error: String): Error returned while starting the tracking controller (reason: `SDK_TRACKING_ERROR`, code: `SDK_106`)
* INTERNAL\_ERROR (error: String): Internal error, mainly security-related; `error` contains a token for analysis (reason: `SDK_INTERNAL_ERROR`, code: `SDK_135`)
* SDK\_NOT\_INITIALIZED\_ERROR: The SDK has not been initialized correctly (reason: `SDK_NOT_INITIALIZED_ERROR`, code: `SDK_136`)

***

## Start a new operation <a href="#id-3-iniciar-nueva-operacion" id="id-3-iniciar-nueva-operacion"></a>

Whenever you want to start the flow for a new operation (examples of operations include: *onboarding, authentication, videoCall*,...) it is essential to tell the **SDKController** that it is about to begin, so the SDK knows that subsequent calls to **Components** (also called **Steps**) will be part of that operation.

When starting a process or flow, **always** call the **newOperation**

method. This method has the following input parameters:

1. **operationType**: Indicates whether an ONBOARDING or AUTHENTICATION process will be performed.
2. **customerId**: (Optional) Unique user ID, if available (managed at the application level)
   1. This parameter will be reflected for each operation on the platform.
3. **steps**: (Optional) List of operation steps (`Step`) if they have been defined in advance. Available values: `SELPHI_COMPONENT`, `SELPHID_COMPONENT`, `NFC_COMPONENT`, `PHINGERS_COMPONENT`, `VIDEO_CALL_COMPONENT`, `VIDEO_ID_COMPONENT`, `VIDEO_RECORDING_COMPONENT`, `VOICE_COMPONENT`, `QR_CAPTURE_COMPONENT` and `PHACTURA_CAPTURE_COMPONENT`.
4. **enableTracking**: Enables or disables the sending of tracking events for this operation. If not specified, it is considered `true`.

There are two ways to start an operation, depending on whether **the steps are known** that will make up the registration or authentication process flow (if the components are executed sequentially and always in the same way) or, otherwise, whether the flow **is undefined** and unknown (for example, if the end customer decides the order in which the components are executed).

* Flow **known** (the operation will appear *tracked* on the platform with all the steps in the list).

  Kotlin implementation example:

```kotlin
val result = SDKController.newOperation(
        operationType = OperationType.ONBOARDING,
        customerId = "customer_id",
        steps = listOf(Step.SELPHI_COMPONENT, Step.SELPHID_COMPONENT),
        enableTracking = true)
when (result) {
    is SdkResult.Success -> {
        Timber.d("APP: NEW OPERATION OK")
        Timber.d("Session ID: ${result.data.sessionId}")
        Timber.d("Operation ID: ${result.data.operationId}")
    }
    is SdkResult.Error -> {
        Timber.d("APP: NEW OPERATION ERROR: ${result.error.name}")
    }
}
```

* Flow **unknown** (the operation will appear *tracked* on the platform with ellipses). Kotlin implementation example:

```kotlin
val result = SDKController.newOperation(
        operationType = OperationType.ONBOARDING,
        customerId = "customer_id",
        enableTracking = true)
when (result) {
    is SdkResult.Success -> {
        Timber.d("APP: NEW OPERATION OK")
    }
    is SdkResult.Error -> {
        Timber.d("APP: NEW OPERATION ERROR: ${result.error.name}")
    }
}
```

`result` → Contains in `data` the information about the operation that was created.

When the result is successful, `data` is an `OperationResult` with:

| Field         | Description                                                   |
| ------------- | ------------------------------------------------------------- |
| `sessionId`   | Identifier of the session created or retrieved by the SDK.    |
| `operationId` | Identifier of the active operation.                           |
| `type`        | Type of operation started (`ONBOARDING` or `AUTHENTICATION`). |
| `customerId`  | Identifier of the user associated with the operation.         |

**Once the operation has been created,** the SDK components associated with this operation can be executed. See the documentation for each component to learn how.

### **Existing operation types** <a href="#id-31-tipos-de-operacion-existentes" id="id-31-tipos-de-operacion-existentes"></a>

Currently, the following operations are available, each using specific **components (STEPS).**

The following table shows the relationship between *operations* and *steps*:

| **Operation (OperationType)** | **Component (Step)**                           | Description                                                                                                                |
| ----------------------------- | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| ONBOARDING                    | <p>SELPHI\_COMPONENT<br>SELPHID\_COMPONENT</p> | <p>- Facial validation of a selfie against the face in a document<br>- Document OCR extraction<br>- Liveness detection</p> |
| AUTHENTICATION                | SELPHI\_COMPONENT                              | <p>- Facial validation using templates<br>- Liveness detection</p>                                                         |

This list will be expanded in future SDK updates as new components and use cases become available.

{% hint style="info" %}
If creating a new operation returns an error of type **INTERNAL\_ERROR** this is mainly due to a **security**. To investigate the cause, you can retrieve the token associated with the error, which provides additional information for analysis.

```
if (result.error is SdkError.INTERNAL_ERROR){
    val token = (result.error as SdkError.INTERNAL_ERROR).error
}
```

{% endhint %}

***

## Security <a href="#id-24-lanzamiento-de-los-componentes" id="id-24-lanzamiento-de-los-componentes"></a>

The Android SDK includes a security system designed to detect and block potentially untrusted environments or those that may indicate attack attempts.<br>

This mechanism is enabled by default, helps identify situations that could compromise security, and prevents the SDK from running in contexts that are not considered safe. When an unsafe environment is detected, creating the operation (`newOperation`) returns an `SdkError.INTERNAL_ERROR` with a token for its analysis (see the section *Start a new operation*).

The method `SDKController.securityMode(...)` is no longer available. The check is controlled using the parameter `internalOptions` of `SdkConfigurationData` (or using `SDKController.setInternalParams`), and is reserved **for development or demo environments only, not production**:

```kotlin
val sdkConfig = SdkConfigurationData(
    sdkApplication = SdkApplication(application),
    licensing = LicensingOffline("LICENSE"),
    internalOptions = if (BuildConfig.DEBUG) {
        SdkInternalOptions(params = mapOf("SKIP_ENV_CHECK" to "true"))
    } else {
        null
    }
)
```

Available keys in `SdkInternalOptions.params`:

| Key                | Value                                      | Effect                                                                                                                            |
| ------------------ | ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| `SKIP_ENV_CHECK`   | `"true"`                                   | Disables secure environment evaluation (for example, to allow testing in emulators). Any other value keeps the evaluation active. |
| `SECURITY_PROFILE` | `"STRICT"`, `"BALANCED"` or `"PERMISSIVE"` | Environment evaluation blocking profile. By default, `PERMISSIVE`; an invalid value keeps `PERMISSIVE`.                           |

***

## Launching components <a href="#id-4-lanzamiento-de-componentes" id="id-4-lanzamiento-de-componentes"></a>

The SDK's functionality is divided into different components with their own controllers. These controllers are launched from the main controller.

Once the **new operation** (**section 3**) has been created, you can launch the different SDK controllers. For more information, refer to the **documentation for each specific component**.

Kotlin launch example:

```kotlin
val result = SDKController.launch(ExampleController(ConfigurationData()))
when (result) {
    is SdkResult.Success -> {
        //Result OK
        result.data
    }
    is SdkResult.Error -> {
        //Result KO
        result.error.name
    }
}
```

### Options for launching the component <a href="#id-41-opciones-para-el-lanzamiento-del-componente" id="id-41-opciones-para-el-lanzamiento-del-componente"></a>

Once the SDK has been initialized and a new operation has been created, you can launch the component. There are two ways to launch it:

* **\[WITH TRACKING]** This call launches the component's functionality as usual, but internal events are tracked on the *Tracking*:

```
val response = SDKController.launch(
    ExampleController(ConfigurationData(...))
)
when (response) {
    is SdkResult.Error -> Napier.d("ERROR - ${response.error.name}")
    is SdkResult.Success -> response.data
}
```

* **\[NO TRACKING]** This call allows the component functionality to be launched normally, but  **no events will be tracked** to the tracking *server*:

```
val response = SDKController.launchMethod(
    ExampleController(ConfigurationData(...))
)
when (response) {
    is SdkResult.Error -> Napier.d("ERROR - ${response.error.name}")
    is SdkResult.Success -> response.data
}
```

The **launch** method should be used **by default**. This method allows you to use  ***Tracking*** if your component is enabled, and will not use it when it is disabled (or the component is not installed).

In contrast, the **launchMethod** method covers a special case in which the integrator has Tracking installed and enabled, but does not want to track information in a particular Flow within the application. In that case, this method is used to prevent that information from being sent to the platform.

***

## Returning a result <a href="#id-5-retorno-de-resultado" id="id-5-retorno-de-resultado"></a>

The result of each component is returned through the SDK, always maintaining the same structure through the class  ***SdkResult*** , which is a sealed class that can have two possible states:

* SdkResult.Success: Indicates that the operation has completed successfully and contains:
  * ***data:*** Contains the data type required for the launched process/component.
* SdkResult.Error
  * ***error:*** Contains the error type required for the launched process/component.

The documentation for each specific component details the different fields this object can return.

Usage example:

```kotlin
when (result) {
    is SdkResult.Success -> {
        Napier.d("Selphi: OK")
        // SelphiResult:
        // result.data.bestImage
    }

    is SdkResult.Error -> Napier.d("Selphi: KO - ${result.error.name}")
}
```

***

## Auxiliary controllers <a href="#id-6-controladores-auxiliares" id="id-6-controladores-auxiliares"></a>

This section includes other controllers and auxiliary operations, some of which are optional and may be needed to complete the Flow correctly.

These fields are required to communicate with the **Facephi**, if you want to perform any **verification** and want to perform *Tracking* for a given operation.

### Getting the OperationId <a href="#id-61-obtencion-del-operationid" id="id-61-obtencion-del-operationid"></a>

```
val result = SDKController.launch(GetOperationIdController())
Napier.d("Operation ID ${result}")
```

### Getting the OperationType <a href="#id-62-obtencion-del-operationtype" id="id-62-obtencion-del-operationtype"></a>

```
val result = SDKController.launch(GetOperationTypeController())
Napier.d("Operation type ${result}")
```

### Getting the SessionId <a href="#id-63-obtencion-del-sessionid" id="id-63-obtencion-del-sessionid"></a>

```
val result = SDKController.launch(GetSessionIdController())
Napier.d("Session ID ${result}")
```

### Retrieving the Customer ID <a href="#id-64-obtencion-del-customerid" id="id-64-obtencion-del-customerid"></a>

```
val result = SDKController.launch(GetCustomerIdController())
Napier.d("Customer ID ${result}")
```

### Setting the Customer ID <a href="#id-65-asignacion-del-customerid" id="id-65-asignacion-del-customerid"></a>

```
SDKController.launch(CustomerIdController("CustomerId"))
```

### Canceling the running component <a href="#id-66-cancelacion-del-componente-en-ejecucion" id="id-66-cancelacion-del-componente-en-ejecucion"></a>

```
SDKController.cancelLaunch()
```

Sends a cancellation notification to the SDK to stop the component that is currently running.

### Closing the session <a href="#id-67-cierre-de-sesion" id="id-67-cierre-de-sesion"></a>

```
SDKController.closeSession()
```

Closes the current SDK session: closes the Tracking session (if active), removes session and operation data, clears saved customization, and releases internal services. After calling it, the SDK will need to be initialized again (`initSdk`) and a new operation created to launch components.

### Restoring an existing session <a href="#id-68-restauracion-de-una-sesion-existente" id="id-68-restauracion-de-una-sesion-existente"></a>

Retrieves the identifiers of a previously created session and operation (all parameters are required):

```kotlin
val result = SDKController.launch(
    ResumeSdkDataController(
        sessionId = "sessionId",
        operationId = "operationId",
        operationType = OperationType.ONBOARDING,
        customerId = "customer_id"
    )
)
when (result) {
    is SdkResult.Success -> Napier.d("APP: RESUME SDK DATA: OK")
    is SdkResult.Error -> Napier.d("APP: RESUME SDK DATA: KO - ${result.error.name}")
}
```

If the secure environment control blocks the restoration, an `SdkError.INTERNAL_ERROR`.

***

## Debugging and error handling options <a href="#id-7-opciones-de-depuracion-y-control-de-errores" id="id-7-opciones-de-depuracion-y-control-de-errores"></a>

The SDK provides certain options that enable more detailed debug logs so you can verify that everything is working correctly.

### Handling errors in Tracking connections to the platform <a href="#id-71-control-de-errores-en-las-conexiones-de-tracking-con-la-plataforma" id="id-71-control-de-errores-en-las-conexiones-de-tracking-con-la-plataforma"></a>

Once the SDK has started successfully, you can apply certain settings to get more information about possible Tracking errors. You can monitor them using this controller launch:

```kotlin
SDKController.launch(TrackingErrorController {
    Napier.d("Tracking Error: ${it.name}")
})
```

### Enabling general Debug logs <a href="#id-72-activacion-de-logs-de-depuracion-general" id="id-72-activacion-de-logs-de-depuracion-general"></a>

```kotlin
 if (BuildConfig.DEBUG) {
  SDKController.enableDebugMode()
 }
```

### Receiving SDK logs in the application <a href="#id-73-recepcion-de-los-logs-del-sdk" id="id-73-recepcion-de-los-logs-del-sdk"></a>

You can receive all log messages emitted by the SDK in the application using `SDKController.setLoggerBackend`, specifying a `CallbackLoggerBackend`. The callback receives the level (`CallbackLoggerLevel`: `VERBOSE`, `DEBUG`, `INFO`, `WARN` or `ERROR`), the tag, the message and, optionally, the associated exception:

```kotlin
SDKController.setLoggerBackend(
    CallbackLoggerBackend { level, tag, message, throwable ->
        Log.d("SDK_LOG", "[${level.name}] $tag: $message")
    }
)
```

To stop receiving logs, you can call the method with `null`:

```kotlin
SDKController.setLoggerBackend(null)
```

***

## Tracking and Analyzing Events in the Application <a href="#id-8-seguimiento-y-analisis-de-eventos-en-la-aplicacion" id="id-8-seguimiento-y-analisis-de-eventos-en-la-aplicacion"></a>

The event functionality lets you record and interpret key interactions within the application, such as screen changes and user actions, making it easier to analyze behavior in real time.

Each event is sent with a timestamp, type, and specific details, providing structured tracking and optimizing the user experience with precise, actionable data.

```kotlin
 SDKController.getAnalyticsEvents { time, componentName, eventType, info ->
            Log.i("EVENTS", "*** $time - ${componentName.name} -" +
                " ${eventType.name} -  ${info ?: ""} ")
        }
```

The callback receives the following parameters:

* `time` (`Long`): event timestamp.
* `componentName` (`ComponentName`): component that generates the event. Values: `NFC_COMPONENT`, `VOICE_COMPONENT`, `DISCLAIMER_COMPONENT`, `DOCUMENT_CAPTURE_COMPONENT`, `QR_CAPTURE_COMPONENT`, `SELPHID_COMPONENT`, `SELPHI_COMPONENT`, `SELPHI_SIGNATURE_COMPONENT`, `VIDEO_ID_SIGNATURE_COMPONENT`, `PHINGERS_COMPONENT`, `PHINGERS_TF_COMPONENT`, `VIDEO_ID_COMPONENT`, `VIDEO_CALL_COMPONENT` and `VIDEO_RECORDING_COMPONENT`.
* `eventType` (`EventType`): event type. Values: `SCREEN_VIEW`, `BUTTON_CLICK`, `COMPONENT_STARTED` and `COMPONENT_STOPPED`.
* `info` (`String?`): specific event details, if any.
