> 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-ios/es/get-started/configuration/4.-push-notifications/handle-push-notifications.md).

# Gestionar notificaciones push

NFC Wallet usa notificaciones push para notificarte de tu **aplicación de billetera digital**. Las notificaciones son enviadas por el backend de NFC Wallet.

{% hint style="info" %}
Es necesario gestionar las notificaciones push de NFC Wallet para admitir **LCM**, notificaciones de transacciones y flujos de inscripción de tarjetas en los que la tarjeta digital se activa directamente por el emisor.
{% endhint %}

### Enruta las notificaciones usando `emisor`

Leer `userInfo["sender"]` y enruta la notificación al manejador correcto:

* `CPS`: operaciones de tarjeta digital (**LCM**)
* `TNS`: notificaciones de transacciones
* `MG`: reposición de claves de pago activada por el **TSP**

```swift
func application(
    _ application: UIApplication,
    didReceiveRemoteNotification userInfo: [AnyHashable : Any],
    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
    let sender = userInfo["sender"] as? String

    Task {
        do {
            switch sender {
            case "CPS":
                // Operaciones de tarjeta digital (LCM).
                // Llama al controlador de notificaciones del SDK. Consulta `NotificationService` en la referencia de la API.
                break

            case "TNS":
                // Notificaciones de transacciones.
                // Actualiza el historial de transacciones. Consulta `TransactionHistoryService` en la referencia de la API.
                break

            case "MG":
                // Reposición de claves activada por el TSP.
                // Inicia la reposición. Consulta `ReplenishmentService` en la referencia de la API.
                break

            default:
                // Notificaciones que no son del SDK.
                break
            }

            completionHandler(.newData)
        } catch {
            completionHandler(.failed)
        }
    }
}
```

### Procesa notificaciones CPS (operaciones de tarjeta digital)

Reenvía **CPS** las notificaciones push al SDK usando `NotificationService.processNotification()`.

<pre class="language-swift"><code class="lang-swift">let notification = NotificationService()
<strong>do {
</strong>    try await notification.processNotification(forUserInfo: userInfo)
} catch {
    // muestra el error
}
</code></pre>

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

Luego, el SDK puede emitir eventos de notificación a través de `NotificationService.notificationEventStream`. Usa estos eventos para rastrear la operación de la tarjeta digital.

Eventos admitidos:

* `unsupportedPushContent`: Se activa cuando la carga útil del push no es compatible con el SDK.
* `completed`: Se activa cuando el procesamiento se completa correctamente (por ejemplo, después de aprovisionar un perfil de tarjeta y claves de pago).
* `serverMessage`: Se activa cuando el backend devuelve una instrucción. El SDK proporciona un `serverMessage` objeto y un `tokenizedId`.

#### Mensaje del servidor

Cuando recibas `serverMessage`, analiza el `serverMessage` objeto para determinar qué operación solicitó el backend.

En particular:

* `requestInstallCard`: Solicitud para instalar una tarjeta.
* `requestResumeCard`: Solicitud para mover una tarjeta de suspendida a activa.
* `requestSuspendCard`: Solicitud para mover una tarjeta de activa a suspendida.
* `requestDeleteCard`: Solicitud para eliminar una tarjeta.

### Procesa notificaciones TNS (transacciones)

Las notificaciones de transacciones proporcionan detalles sobre las transacciones de pago completadas. Usa `TransactionHistoryService` para recuperar los 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 `userInfo` parámetro:

* `userInfo["sender"]`: `TNS`.
* `userInfo["action"]`: `TNS:PaymentTransactionNotification`.
* `userInfo["digitalCardId"]`: Identificador de la tarjeta digital. Úsalo con `TransactionHistoryService.records(forDigitalCardID:)`.
* `userInfo["transactionRecordType"]`: Solo presente para tarjetas de doble marca. Pásalo a `TransactionHistoryService.records(forDigitalCardID:transactionRecordType:)` para obtener solo los registros relevantes (principal o auxiliar).

<pre class="language-swift"><code class="lang-swift">let action = userInfo["action"] as? String
let cardId = userInfo["digitalCardId"] as? String
let recordType = userInfo["transactionRecordType"] as? String

// Comprueba la acción esperada y la presencia del id de la tarjeta.
guard "TNS:PaymentTransactionNotification" == action, let cardId = cardId else {
    // muestra el error
}

let historyService = TransactionHistoryService()
do {       
<strong>    let records = try await historyService.records(forDigitalCardID: cardId, transactionRecordType: recodType)
</strong>} catch {
    // muestra el error
}
</code></pre>

### Procesar notificaciones de MG (renovación)

El **TSP** puede solicitar la reposición de claves de pago. Usa `ReplenishmentService` para reponer las claves.

A través de la notificación push, el **aplicación de billetera digital** obtiene la siguiente información a través del `userInfo` parámetro:

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

<pre class="language-swift"><code class="lang-swift">let action = userInfo["action"] as? String
let cardId = userInfo["digitalCardId"] as? String

// Comprueba la acción esperada y la presencia del id de la tarjeta.
guard "MG:ReplenishmentNeededNotification" == action, let cardId = cardId else {
    // muestra el error
}

let replenishmentService = ReplenishmentService()
do {       
<strong>    try await replenishmentService.replenish(digitalCardID: cardId, isForced: true)
</strong>} catch {
    // muestra el error
}
</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-ios/es/get-started/configuration/4.-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.
