> 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/5.-push-notifications/handle-push-notifications.md).

# Gestionar notificaciones push

NFC Wallet utiliza notificaciones push para notificar a su **aplicación de billetera digital**. Las notificaciones son enviadas por el backend de NFC Wallet.

{% hint style="info" %}
El manejo de las notificaciones push de NFC Wallet es necesario para soportar **LCM**, notificaciones de transacciones y flujos de inscripción de tarjetas donde la tarjeta digital es activada directamente por el emisor.
{% endhint %}

### Enruta las notificaciones usando `sender`

Leer  `sender` clave del payload del mensaje `data` y enruta la notificación al manejador correcto:

* `CPS`: operaciones de tarjeta digital (**LCM**)
* `TNS`: notificaciones de transacciones
* `MG`: reabastecimiento de claves de pago desencadenado por el **TSP**

<pre class="language-java" data-expandable="true"><code class="lang-java">private static final String KEY_SENDER = "sender";

public void processIncomingMessage(@NonNull final Context context,
                                   @NonNull final Map&#x3C;String, String> data) {
     
    String sender = "";
    if (!data.isEmpty()) {
        for (String key : data.keySet()) {
            if (KEY_SENDER.equalsIgnoreCase( key )) {
                sender = data.get(key);
            }
        }
    }
     
    switch (sender) {
    case "CPS":
        // Operaciones de tarjeta digital (LCM).
        // Ver `ProvisioningBusinessService.processIncomingMessage`
        break;
  
    case "TNS":
<strong>         // Notificaciones de transacciones.
</strong>         // Actualizar el historial de transacciones. Ver `MGTransactionHistoryService` en la referencia de API.
         break;
                  
    case "MG":
         // Reabastecimiento de claves desencadenado por el TSP.
         // Activar reabastecimiento. Ver `ReplenishmentService` en la referencia de API.
        break;

    default:
        // Notificaciones no relacionadas con el SDK
<strong>        break;
</strong>    }     
}
</code></pre>

### Procesar notificaciones CPS (operaciones de tarjeta digital) <a href="#process-cps-notifications-digital-card-operations" id="process-cps-notifications-digital-card-operations"></a>

Reenviar **CPS** notificaciones usando `ProvisioningBusinessService`.`processIncomingMessage()`.

<pre class="language-java" data-expandable="true"><code class="lang-java">public void processIncomingMessage(@NonNull final Context context,
                                   @NonNull final Map&#x3C;String, String> data) {
    // ...
    // Procesamiento del remitente CPS
<strong>    // 1 - Construir bundle desde los datos del payload push
</strong><strong>    final Bundle bundle = new Bundle();
</strong>    if (!data.isEmpty()) {
        for (String key : data.keySet()) {
            if (null != data.get(key)) {
                 bundle.putString(key, data.get(key));    
            }
        }
    }

<strong>    // 2 - Procesar push del remitente CPS
</strong><strong>    My_PushServiceListener pushListener = new My_PushServiceListener();
</strong>    final ProvisioningBusinessService provService 
                = ProvisioningServiceManager.getProvisioningBusinessService();                
    provService.processIncomingMessage( bundle, pushListener );
</code></pre>

El SDK de NFC Wallet procesa el push e interactúa con el backend de NFC Wallet.

#### Implemente `PushServiceListener`

Implemente `PushServiceListener`  para manejar el callback y rastrear la operación de la tarjeta digital.

Callbacks soportados:

* `onUnsupportedPushContent`: Se desencadena cuando el payload del push no es soportado por el SDK.
* `onComplete`: Se desencadena cuando el procesamiento se completa con éxito (por ejemplo, después de provisionar un perfil de tarjeta y las claves de pago).
* `serverMessage`: Se desencadena cuando el backend devuelve un mensaje del servidor. El SDK proporciona un `ProvisioningServiceMessage` objeto y un `tokenizedCardId`.

Cuando recibas `ProvisioningServiceMessage`, llame a `getMsgCode` para determinar qué operación está ejecutando el backend:

* `REQUEST_INSTALL_CARD`: el mensaje indica la solicitud para que la tarjeta sea instalada.
* `REQUEST_REPLENISH_KEYS`: el mensaje indica la solicitud de un reabastecimiento.
* `REQUEST_RESUME_CARD`: el mensaje indica la solicitud para mover una tarjeta de suspendida a activa.
* `REQUEST_SUSPEND_CARD`: el mensaje indica la solicitud para mover una tarjeta de activa a suspendida.
* `REQUEST_DELETE_CARD`: el mensaje indica la solicitud para eliminar una tarjeta.
* `REQUEST_RENEW_CARD`: el mensaje indica la solicitud para renovar una tarjeta

{% code expandable="true" %}

```java
public class My_PushServiceListener implements PushServiceListener {

  @Override
  public void onServerMessage(String tokenizedCardId, ProvisioningServiceMessage message) {
    /*
    Se desencadena durante los pasos del flujo de provisioning, durante una operación de gestión del ciclo de vida, durante el reabastecimiento de claves.

    Para entender qué acción se ha realizado, analice el objeto ProvisioningServiceMessage.
    **/

      //Ejemplo
    	String messageCode = provisioningServiceMessage.getMsgCode();

      switch (messageCode) {
          case KnownMessageCode.REQUEST_INSTALL_CARD:
              // 1a notificación push para instalar la tarjeta
          case KnownMessageCode.REQUEST_REPLENISH_KEYS:
              // 2a notificación push para instalar las claves de pago y reabastecimientos posteriores
          case KnownMessageCode.REQUEST_RESUME_CARD:
              // tarjeta a reanudar
          case KnownMessageCode.REQUEST_SUSPEND_CARD:
              // tarjeta a suspender
          case KnownMessageCode.REQUEST_RENEW_CARD:
              // token a renovar (actualización de perfil)
          case KnownMessageCode.REQUEST_DELETE_CARD:
              // tarjeta a eliminar.
              LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(ACTION_RELOAD_CARDS));
              break;
          default:
      }
  }

  @Override
  public void onUnsupportedPushContent(Bundle pushMessageBundle) {
    /*
    Se desencadena si el mensaje recibido no ha sido entendido o no es soportado
    **/
  }

  @Override
  public void onComplete() {
    /*
    Se desencadena una vez que la sesión de provisioning se ha completado con éxito. La tarjeta está lista para el pago.
    **/
  }

  @Override
  public void onError(ProvisioningServiceError error) {
    /*
    Se desencadena cuando ocurre un error. El desarrollador debe analizar el error y tomar las acciones apropiadas.
    **/
  }
}
```

{% endcode %}

### Procesar notificaciones TNS (transacciones)

Las notificaciones de transacciones proporcionan detalles sobre transacciones de pago completadas. Use `MGTransactionHistoryService` para recuperar registros de transacciones.

A través de la notificación push, el **aplicación de billetera digital** obtiene la siguiente información a través del payload del mensaje `data` :

* Clave `sender`: `TNS`.
* Clave `action`: `TNS:PaymentTransactionNotification`.
* Clave `digitalCardId`: Identificador de la tarjeta digital. Úselo con `MGTransactionHistoryService.refreshHistory()` para obtener la transacción
* Clave `transactionRecordType`: Presente solo para tarjetas co-badged. Páselo a `MGTransactionHistoryService.refreshHistory()` para obtener solo los registros relevantes (primario o auxiliar).

{% code expandable="true" %}

```java
private static final String KEY_SENDER = "sender";
private static final String KEY_ACTION = "action";
private static final String KEY_DIGITALIZED_CARD_ID = "digitalCardID";
private static final String KEY_TRANSACTION_RECORD_TYPE = "transactionRecordType";

public void processIncomingMessage(@NonNull final Context context,
                                   @NonNull final Map<String, String> data) {
    
    String action = "";
    String digitalCardID = "";
    String transactionRecordType = "";
    
    // ...
    // Procesamiento del remitente TNS
    // 1 - Extraer valores para la notificación del remitente TNS
    final Bundle bundle = new Bundle();
    if (!data.isEmpty()) {
        for (String key : data.keySet()) {
            if (KEY_DIGITALIZED_CARD_ID.equalsIgnoreCase( key )) {
                 digitalCardID = data.get(key);
            }
            else if (KEY_ACTION.equalsIgnoreCase( key )) {
                 action = data.get(key);
            }
            else if (KEY_TRANSACTION_RECORD_TYPE .equalsIgnoreCase( key )) {
                 transactionRecordType = data.get(key);
            }
        }
    }
    
    // 2 - comprobar parámetros
    if( ! "TNS:PaymentTransactionNotification".equals( action ) || digitalCardID == null ) {
         // registrar error
    }
    else {
         // 3 - Llamar al servicio de historial de transacciones MG         
         final MGTransactionHistoryService tnsService 
                = MobileGatewayManager.INSTANCE.getTransactionHistoryService();
                
         // 3a - primero debería obtener un token de acceso
         final ProvisioningBusinessService provService 
                = ProvisioningServiceManager.getProvisioningBusinessService();
         provService.getAccessToken(digitalCardID, 
              GetAccessTokenMode.REFRESH, new AccessTokenListener() {
                 @Override
                 public void onSuccess(String digitalCardId, String accessToken) {
                      // 3b - usando el token de acceso puede obtener la transacción
                      tnsService.refreshHistory(accessToken, 
                                               digitalCardID, null, transactionRecordType , new TransactionHistoryListener() {
                              
                              @Override
                              public void onSuccess(List<MGTransactionRecord> list, String digitalCardId, String timeStamp) {
                                  // Éxito
                                  // puede analizar la lista de registros de transacciones
                              }

                              @Override
                              public void onError(String s, MobileGatewayError mobileGatewayError) {
                                  // Registrar un error
                              }
                      });              
                 }
                 
                 @Override
                 public void onError(String digitalCardId, ProvisioningServiceError provisioningServiceError) {
                       // Error al obtener el token de acceso
                       // Registrar un error
                  }
             });
      } 
}


```

{% endcode %}

### Procesar notificaciones MG (reabastecimiento)

El **TSP** puede solicitar el reabastecimiento de claves de pago. Use `ProvisioningServiceManager.sendRequestForReplenishment` para reabastecer claves.

A través de la notificación push, el **aplicación de billetera digital** obtiene la siguiente información a través del payload del mensaje `data`&#x20;

* `sender`: `MG`.
* `action`: `MG:ReplenishmentNeededNotification`.
* `"digitalCardId`: Identificador de la tarjeta digital. Úselo con `ReplenishmentService.replenish(digitalCardID:isForced:)`.

<pre class="language-java" data-expandable="true"><code class="lang-java">private static final String KEY_SENDER = "sender";
private static final String KEY_ACTION = "action";
private static final String KEY_DIGITALIZED_CARD_ID = "digitalCardID";

public void processIncomingMessage(@NonNull final Context context,
                                   @NonNull final Map&#x3C;String, String> data) {
    
    String action = "";
    String digitalCardID = "";
    String transactionRecordType = "";
    
    // ...
    // Procesamiento del remitente MG
    // 1 - Extraer valores para la notificación del remitente TNS
    final Bundle bundle = new Bundle();
    if (!data.isEmpty()) {
        for (String key : data.keySet()) {
            if (KEY_DIGITALIZED_CARD_ID.equalsIgnoreCase( key )) {
                 digitalCardID = data.get(key);
            }
            else if (KEY_ACTION.equalsIgnoreCase( key )) {
                 action = data.get(key);
            }
        }
    }
    
    // 2 - comprobar parámetros
    if( ! "MG:ReplenishmentNeededNotification".equals( action ) || digitalCardID == null ) {
         // registrar error
    }
    else {
         // 3 - Llamar al servicio de negocio de Provisioning
         final ProvisioningBusinessService provService 
                = ProvisioningServiceManager.getProvisioningBusinessService();
         provService.sendRequestForReplenishment( digitalCardID, new ReplenishmentListener(), true);                             
    }
}

/**
 * Al usar este listener observaremos solo el resultado
 * de llamar a la API ProvisioningBusinessService#sendRequestForReplenishment() que usa
 * la misma API PushServiceListener, pero no hay procesamiento de mensajes push involucrado.
 */
private static class ReplenishmentListener implements PushServiceListener {

        public ReplenishmentListener(){
        }


        @Override
        public void onError(final ProvisioningServiceError provisioningServiceError) {
            // Registrar error
        }

        @Override
        public void onUnsupportedPushContent(final Bundle bundle) {
            // Esto nunca debería suceder en el caso de uso de reabastecimiento ya que no estamos pasando
            // Registrar error
        }

        @Override
        public void onServerMessage(final String tokenizedCardId,
                                    final ProvisioningServiceMessage provisioningServiceMessage) {
            //  Esto nunca debería suceder en el reabastecimiento
            // Registrar error
<strong>         }
</strong>
        @Override
        public void onComplete() {

            // Para tarjetas Mastercard y PURE (EMV de marca blanca) solo significa que enviamos la solicitud de reabastecimiento y debemos esperar
            // que llegue un mensaje push una vez que los SUK estén preparados para ser recuperados del backend.
 
            // Para tarjetas Visa esto significa que hemos terminado y la tarjeta está lista con la nueva LUK
            // Por lo tanto verificaremos si es una tarjeta Visa y, de ser así, reutilizaremos el código de manejo de mensajes push para notificar al usuario
        }
    }



</code></pre>


---

# 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/5.-push-notifications/handle-push-notifications.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.
