> 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/implement-nfc-wallet/tokenize-a-card/trigger-provisioning.md).

# Activar aprovisionamiento

## Descripción general

Después de digitalizar una tarjeta, inicie una sesión de aprovisionamiento para aprovisionar la tarjeta digital.

Durante la sesión de aprovisionamiento, el **Cartera NFC** aprovisiona de forma segura el perfil de la tarjeta digital y las claves de pago en su **aplicación de cartera digital**.

Inicie la sesión de aprovisionamiento justo después de recibir el `códigoDeActivación` de `MGDigitizationListener.onCPSActivationCodeAcquired`. Ver [Digitalizar una tarjeta](/nfc-wallet-sdk-android/es/implement-nfc-wallet/tokenize-a-card/digitize-a-card.md#sdk-integration).

Este callback también devuelve `idTarjetaDigital`. Guárdelo para operaciones posteriores (por ejemplo, tokens de acceso, historial de transacciones y LCM). No lo necesita para iniciar el aprovisionamiento seguro.

{% hint style="info" %}
Este paso también configura el canal seguro entre el **SDK de Cartera NFC** y el **backend de la Cartera NFC**.

Esta configuración se llama **registro del dispositivo** (también conocido como **registro CPS**).
{% endhint %}

## Diagrama de secuencia

<figure><img src="/files/833c5ecf8d166b4e7da038236ea3acc3946c2704" alt=""><figcaption><p>Flujo de aprovisionamiento seguro (registro del dispositivo y sesión de aprovisionamiento).</p></figcaption></figure>

## Integración del SDK

El aprovisionamiento seguro requiere **registro del dispositivo**.

El registro del dispositivo normalmente se requiere una vez por instancia de cartera en un dispositivo. Cuando se requiere el registro, el flujo de registro activa automáticamente la sesión de aprovisionamiento.

Si el registro del dispositivo ya está completo, inicie la sesión de aprovisionamiento llamando a `ProvisioningBusinessService.sendActivationCode(...)`.

El SDK solicita el `códigoDeActivación` a través de `EnrollingServiceListener.onCodeRequired(...)`. Proporcione el valor en ese momento.

### Prerrequisitos

Antes de comenzar, asegúrese de que tiene:

* Inicializado el **SDK de Cartera NFC**. Ver [Inicialice el SDK de Cartera NFC](/nfc-wallet-sdk-android/es/get-started/configuration/4.-initialize-the-nfc-wallet-sdk.md).
* Configuradas las notificaciones push y recuperado un token push. Ver [Notificaciones push](/nfc-wallet-sdk-android/es/get-started/configuration/5.-push-notifications.md).
* Recibido el `códigoDeActivación` de la digitalización. Ver [Digitalizar una tarjeta](/nfc-wallet-sdk-android/es/implement-nfc-wallet/tokenize-a-card/digitize-a-card.md#sdk-integration).

### Registro del dispositivo

El registro del dispositivo requiere estas entradas:

* `códigoDeActivación` (`byte[]`): Devuelto por la digitalización.
* `idCartera`: Recupérelo usando `MGCardEnrollmentService.getWalletId()`. Pase este valor como el `idUsuario` parámetro a `EnrollingBusinessService.enroll(...)`. Ver [Recuperar el ID de la cartera](/nfc-wallet-sdk-android/es/get-started/configuration/4.-initialize-the-nfc-wallet-sdk.md#retrieving-the-wallet-id).
* `tokenPush`: El token push para **FCM** o **HMS Push Kit**.

{% hint style="warning" %}
Prefijo **HMS Push Kit** tokens con `HMS:` (por ejemplo, `HMS:<token>`).
{% endhint %}

### Comprobar el estado de registro del dispositivo

Compruebe el estado de registro del dispositivo usando `EnrollingBusinessService.isEnrolled()`.

Este estado indica si el canal seguro ya está establecido para la instancia de cartera actual en este dispositivo.

Devuelve un `EstadoDeRegistro`:

* `REGISTRO_NECESARIO`: Llame a `EnrollingBusinessService.enroll(...)`.
* `REGISTRO_EN_PROGRESO`: Llame a `EnrollingBusinessService.continueEnrollment(...)`.
* `REGISTRO_COMPLETO`: Llame a `ProvisioningBusinessService.sendActivationCode(...)`.

### Implemente `EnrollingServiceListener`

Implemente `EnrollingServiceListener` para guiar el flujo de registro:

* `onCodeRequired`: Proporcione el `códigoDeActivación`.
* `onComplete`: El registro del dispositivo se completa con éxito.
* `onError`: Maneje errores usando `ProvisioningServiceError`.

<pre class="language-java" data-title="MyEnrollingServiceListener.java"><code class="lang-java"><strong>public class MyEnrollingServiceListener implements EnrollingServiceListener {
</strong>
    // Recibir de MGDigitizationListener.onCPSActivationCodeAcquired(...)
    private final byte[] activationCode;

    public MyEnrollingServiceListener(final byte[] activationCode) {
        this.activationCode = activationCode;
    }

    @Override
    public void onStarted() {
        // Llamado cuando comienza el flujo de registro.
    }

    @Override
    public void onCodeRequired(final CHCodeVerifier chCodeVerifier) {
        // Llamado cuando se requiere el código de activación para continuar el flujo.
        final SecureCodeInputer inputer = chCodeVerifier.getSecureCodeInputer();
        for (final byte b : activationCode) {
            inputer.input(b);
        }
        inputer.finish();
    }

    @Override
    public void onComplete() {
        // Llamado una vez que el registro del dispositivo se completa con éxito.
        // En un flujo Verde, esto usualmente significa que el aprovisionamiento está completo.
    }

    @Override
    public void onError(final ProvisioningServiceError error) {
        // Llamado cuando el registro del dispositivo falla.
        // Analice error.getCode() y aplique la lógica adecuada de reintento / recuperación.
    }
}
</code></pre>

### Implementación del código de registro del dispositivo

```java
byte[] activationCode = ...; // desde MGDigitizationListener.onCPSActivationCodeAcquired(...)
String pushToken = "..."; // desde FCM o HMS Push Kit
String language = "es"; // Use la configuración regional de su app cuando sea posible.

// El ID de la cartera es el identificador de usuario para el registro del dispositivo.
String walletId = MobileGatewayManager.INSTANCE.getCardEnrollmentService().getWalletId();

EnrollingServiceListener enrollingListener = new MyEnrollingServiceListener(activationCode);

final EnrollingBusinessService enrollingService = ProvisioningServiceManager.getEnrollingBusinessService();
final ProvisioningBusinessService provisioningBusinessService = ProvisioningServiceManager.getProvisioningBusinessService();

// Comprobar el estado de registro.
final EnrollmentStatus status = enrollingService.isEnrolled();
switch (status) {
    case REGISTRO_NECESARIO:
        // Primer intento de registro del dispositivo en esta instancia de cartera.
        enrollingService.enroll(walletId, pushToken, language, enrollingListener);
        break;
    
    case REGISTRO_EN_PROGRESO:
        // El registro se inició antes y debe reanudarse.
        enrollingService.continueEnrollment(language, enrollingListener);
        break;
    
    case REGISTRO_COMPLETO:
        // El registro del dispositivo ya se completó.
        // Iniciar el aprovisionamiento para esta tarjeta.
        // El SDK solicita el código de activación vía enrollingListener.onCodeRequired(...).
        provisioningBusinessService.sendActivationCode(enrollingListener);
        break;
    
    default:
        // Registrar error (estado desconocido).
 }

```


---

# 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/implement-nfc-wallet/tokenize-a-card/trigger-provisioning.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.
