> For the complete documentation index, see [llms.txt](https://docs.payments.thalescloud.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.payments.thalescloud.io/nfc-wallet-sdk-android/es/get-started/configuration/4.-initialize-the-nfc-wallet-sdk.md).

# 4. Inicializar el SDK NFC Wallet

## Inicializar el SDK de NFC Wallet

Inicialice el SDK de NFC Wallet antes de llamar a cualquier otra API del SDK.

Flujo recomendado:

1. Agregue los archivos de propiedades requeridos.
2. Compile un `CustomConfiguration`.
3. (Opcional) Llame a `SDKInitializer.INSTANCE.configure(...)` durante el inicio de la aplicación.
4. Llamar a `SDKInitializer.INSTANCE.initialize(...)` en un hilo en segundo plano.
5. Llamar a `MobileGatewayManager.INSTANCE.configure(...)` para configurar **Mobile Gateway (MG)**.

{% hint style="warning" %}

### Comprobar la versión de Android

Verifique que la versión de Android cumpla con los requisitos mínimos del SDK de Android de NFC Wallet antes de inicializar el SDK.

Ocultar las funciones de NFC Wallet para versiones de Android no compatibles.
{% endhint %}

### Agregar los archivos de propiedades requeridos

Cree los siguientes archivos en su Android **aplicación de cartera digital** `assets` carpeta:

* `mobilegateway.properties`
* `rages.properties`
* `gemcbp.properties`

Establezca los valores proporcionados por Thales (a menos que un valor esté explícitamente marcado como fijo a continuación).

#### mobilegateway.properties

<details>

<summary>Descripción de mobilegateway.properties</summary>

<table><thead><tr><th width="353">Clave</th><th>Descripción</th></tr></thead><tbody><tr><td>MG_CONNECTION_URL</td><td>[String] URL del servidor MG (proporcionada por Thales).</td></tr><tr><td>MG_TRANSACTION_HISTORY_CONNECTION_URL</td><td>[String] URL para recuperar el historial de transacciones (proporcionada por Thales).</td></tr><tr><td>WALLET_PROVIDER_ID</td><td>[String] ID del proveedor de billetera.</td></tr><tr><td>WALLET_APPLICATION_ID</td><td>[String] ID de la aplicación del proveedor de billetera (Opcional). Requerido cuando el proveedor de billetera admite varias aplicaciones de billetera.</td></tr><tr><td>MG_CONNECTION_TIMEOUT</td><td>[Integer] Tiempo de espera de conexión en milisegundos. Recomendado: 30000.</td></tr><tr><td>MG_CONNECTION_READ_TIMEOUT</td><td>[Integer] Tiempo de espera de lectura en milisegundos. Recomendado: 30000.</td></tr><tr><td>MG_RETRY_COUNTER</td><td>[Integer] Número de reintentos. Recomendado: 3.</td></tr><tr><td>MG_RETRY_INTERVAL</td><td>[Integer] Intervalo en milisegundos entre reintentos. Recomendado: 10000.</td></tr></tbody></table>

</details>

#### rages.properties

<details>

<summary>Descripción de rages.properties</summary>

<table><thead><tr><th width="353">Clave</th><th>Descripción</th></tr></thead><tbody><tr><td>REALM</td><td>[String] Valor fijo: <strong>CBP</strong>.</td></tr><tr><td>OAUTH_CONSUMER_KEY</td><td>[String] Clave de consumidor OAuth (proporcionada por Thales).</td></tr><tr><td>RAGES_GATEWAY_URL</td><td>[String] URL de la pasarela RAGES (proporcionada por Thales).</td></tr><tr><td>RAGES_CONNECTION_TIMEOUT</td><td>[Integer] Tiempo de espera de conexión en milisegundos. Recomendado: 30000.</td></tr><tr><td>CSR_DOMAIN</td><td>[String] Dominio usado en la solicitud de firma de certificado (CSR) para HTTPS. Solicite el valor al equipo de entrega de Thales.</td></tr><tr><td>CSR_EMAIL</td><td>[String] Dirección de correo electrónico de la empresa.</td></tr></tbody></table>

</details>

#### gemcbp.properties

<details>

<summary>Descripción de gemcbp.properties</summary>

<table><thead><tr><th width="353">Clave</th><th>Descripción</th></tr></thead><tbody><tr><td>CPS_URL</td><td>[String] URL de CPS (proporcionada por Thales).</td></tr><tr><td>CPS_CONNECTION_TIMEOUT</td><td>[Integer] Tiempo de espera de conexión en milisegundos. Recomendado: 30000.</td></tr><tr><td>CPS_READ_TIMEOUT</td><td>[Integer] Tiempo de espera de lectura en milisegundos. Recomendado: 30000.</td></tr></tbody></table>

</details>

### Configurar el comportamiento de pago

`CustomConfiguration` define el comportamiento de pago:

* `keyValidityPeriod`: Tiempo (en segundos) entre la autenticación del usuario final y el toque en el terminal POS. Rango: 0–300. Predeterminado: 45.
* `domesticCurrencyCode`: [código de moneda numérico ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) usado para CDCVM durante pagos LVT (Transacción de bajo valor). Predeterminado: 978 (EUR).

{% hint style="info" %}
`CustomConfiguration` admite parámetros adicionales de gestión de riesgos y CDCVM. Consulte [Definir la gestión de riesgos](/nfc-wallet-sdk-android/es/implement-nfc-wallet/make-payment/implement-contactless-payments/7.-configure-cdcvm-experiences/define-risk-management.md).

Recomendamos revisar estos parámetros al implementar el pago sin contacto.
{% endhint %}

El SDK usa `CustomConfiguration` durante la inicialización.

```java
/* Inicializar el SDK con valores distintos de los predeterminados */
CustomConfiguration customConfig = new CustomConfiguration.Builder()
                .domesticCurrencyCode(978)
                .keyValidityPeriod(60)
                .build();
```

{% hint style="warning" %}
No cambie `keyValidityPeriod` y `domesticCurrencyCode` después de la primera inicialización.

Los cambios pueden introducir retrasos y problemas intermitentes entre la autenticación y el toque final en el terminal POS.
{% endhint %}

### Ejecutar la configuración rápida del SDK (opcional)

Use `SDKInitializer.INSTANCE.configure(...)` para precargar el Android `Context`, `CustomConfiguration`, y las bibliotecas nativas.

Después de `configure(...),` puede llamar a las APIs que solo leen el almacenamiento local del SDK.

Consulte [Requisitos de la API del SDK](/nfc-wallet-sdk-android/es/help/sdk-api-requirements.md) para obtener más detalles.

{% hint style="info" %}
`configure()` no ejecuta la migración del SDK. Si se requiere migración, se ejecuta durante `initialize()`.
{% endhint %}

{% code title="MyApp.java" expandable="true" %}

```java
public class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        try {
            // 1. Compile su CustomConfiguration (ver arriba).
            ...

            // 2. Ejecute la configuración rápida para asegurarse de que el SDK tenga un Android Context.
            SDKInitializer.INSTANCE.configure(this, customConfig);
        } catch (InternalComponentException e) {
            // Puede registrar el error y continuar con initialize().
        } catch (Exception e) {
            // Medida de seguridad contra fallos durante el inicio de Application.
            // Puede registrar el error y continuar con initialize().
        } catch (Throwable e) {
            // Esto es poco probable.
            // Si ocurre, no llame a initialize().
            return;
        }

        // 3. Inicialice el SDK de forma asíncrona para que el inicio de Application no se bloquee.
        // Consulte "Inicializar el SDK (pago)" más abajo.
    }
}
```

{% endcode %}

### Inicializar el SDK (pago)

Compruebe el estado del SDK usando `SDKController.getInstance().getSDKServiceState()` e inicialice solo cuando sea necesario.

Use `SDKInitializer.INSTANCE.initialize(...)` para inicializar los componentes de pago:

* Proporcione `CustomConfiguration` como parámetro de entrada.
* Esta API es síncrona. Llámela desde un hilo en segundo plano.

{% code title="Inicializar el SDK de NFC Wallet (Java)" %}

```java
final Context appContext = getApplicationContext();

if (SDKController.getInstance().getSDKServiceState() != SDKServiceState.STATE_INITIALIZED) {
    Thread sdkInit = new Thread(new Runnable() {
        @Override
        public void run() {
            SDKInitializer.INSTANCE.initialize(appContext, customConfig);
        }
    });
    sdkInit.start();
}
```

{% endcode %}

{% hint style="info" %}
Las APIs de inicialización son idempotentes. Puede llamarlas varias veces de forma segura.
{% endhint %}

### Configurar Mobile Gateway (MG)

Después de que se complete la inicialización del SDK, llame a `MobileGatewayManager.INSTANCE.configure(...)` para habilitar la tokenización, la LCM de la tarjeta digital y el historial de transacciones.

Use `MobileGatewayManager.INSTANCE.getConfigurationState()` para comprobar el estado de la configuración.

{% code title="Configurar Mobile Gateway (Java)" %}

```java
protected void initMgSdk(@NonNull final Context context) {
    final MobileGatewayManager mgManager = MobileGatewayManager.INSTANCE;

    try {
        // Evite múltiples inicializaciones.
        if (mgManager.getConfigurationState() == MGSDKConfigurationState.NOT_CONFIGURED) {
            mgManager.configure(context);
        }
    } catch (final MGConfigurationException exception) {
        // Registrar error.
    }
}
```

{% endcode %}

### Obtener el ID de la billetera

Use `getWalletId()` de `MGCardEnrollmentService` para recuperar el identificador de la billetera.

{% code title="Obtener el ID de la billetera (Java)" lineNumbers="true" %}

```java
MGCardEnrollmentService enrollService = MobileGatewayManager.INSTANCE.getCardEnrollmentService();
String walletId = enrollService.getWalletId();
```

{% endcode %}

`MGSDKException` se lanza si ocurre un error al recuperar el ID de la billetera.

{% hint style="info" %}
Use el ID de la billetera para resolución de problemas y soporte.
{% endhint %}

El SDK genera el ID de la billetera la primera vez que inicializa el SDK:

* El ID de la billetera permanece estable entre reinicios de la aplicación.
* Si restablece el SDK, el ID de la billetera se vuelve a generar.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.payments.thalescloud.io/nfc-wallet-sdk-android/es/get-started/configuration/4.-initialize-the-nfc-wallet-sdk.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
