> ## Documentation Index
> Fetch the complete documentation index at: https://devs.tapipay.la/llms.txt
> Use this file to discover all available pages before exploring further.

# App ↔ SDK channel

> Talk to the open checkout in both directions: prefill data, limit payment methods and receive events with an explicit response.

The **app ↔ SDK channel** is two-way communication between your app (or your page) and the Tapipay checkout that the SDKs mount:

* **From your app to the checkout:** you pass it data, for example the CLABE to prefill direct debit or the payment methods to show, and the checkout answers whether it accepted it.
* **From the checkout to your app:** it tells you what happened, for example that the user submitted the payment or closed the checkout without paying.

It works the same in the [web SDK](https://devs.tapipay.la/en/payment-portal/payment-methods-sdk.md) and in the [Android and iOS SDKs](https://devs.tapipay.la/en/payment-portal/mobile-sdk.md): the same keys, the same responses and the same error codes. Only each platform's syntax changes.

> [card] [Web](#web)
>
> `tapipay.channel` in `@npmtapi/embed`.

> [card] [Android](#android)
>
> `Tapipay.presentWithChannel()` in Kotlin.

> [card] [iOS](#ios)
>
> `Tapipay.channel` in Swift.

## How it works

1. You open the checkout as usual: `initialize()` on web or `present()` in the native SDKs.
2. When the checkout loads, it greets the SDK with a `hello` message that carries the **capabilities** enabled for your organization. The SDK answers with its own `hello` and the channel is open.
3. Your app writes input keys with `set`. The checkout validates each one and answers **`ack`** if it applied it, or **`error`** with a code if it did not.
4. The checkout emits output keys (for example, `payment.submitted`) and the SDK delivers them to the handlers you registered with `on`.

You do not need to wait for the checkout to finish loading: whatever you send before the `hello` is queued and goes out in order as soon as the channel opens.

> [!NOTE]
>
> Data sent through the channel stays on the user's device: it goes from your app to the checkout without passing through the URL or your server. On web, the SDK uses a private channel with the iframe that no other script on your page can read.

## Capabilities

Each key has a version (`@1`). Your organization can only use the capabilities it has enabled, and the checkout only announces those in the `hello`.

| Capability | Direction | What it does | Enabled by default |
| - | - | - | - |
| `domiciliation.prefill@1` | App → checkout | Prefills the CLABE and the account holder in the direct debit form, even with the checkout already open. | No, enabled on request |
| `payment.methods@1` | App → checkout | Limits the payment methods your user sees. | No, enabled on request |
| `payment.submitted@1` | Checkout → app | The user submitted the payment. | Yes |
| `payment.cancelled@1` | Checkout → app | The user closed the checkout without paying. Native SDKs only. | Yes |

To find out whether a key is available, call `supports("payment.methods")` (the key without its version) **after** the handshake. Before the `hello`, or if the channel did not open, it always returns `false`.

### `domiciliation.prefill`

Prefills the CLABE and the account holder's name in the direct debit form. It applies to both screens where that form appears: the "direct debit" payment method in the payments view and the direct debit enrollment in [autopay management](https://devs.tapipay.la/en/payment-portal/autopay-sdk.md).

| Field | Type | Rule |
| - | - | - |
| `clabe` | `string` | Optional. 18 digits, no spaces, with a valid check digit. |
| `accountHolderName` | `string` | Optional. 3 to 100 characters: letters only (accented letters included) and spaces. |

* **It is a prefill:** the user sees the data and can edit it before confirming.
* If a value fails validation, the checkout answers `invalid_value` and shows the form empty.
* **With the checkout open**, the prefill only applies to the fields the user has not changed yet. If the user already submitted their account details, the checkout answers `ack` but the prefill **has no effect**: the CLABE the user submitted is the one that counts.
* It is a **sensitive** key: the SDKs never write it to logs. Do not log it on your side either.

### `payment.methods`

Limits the payment methods your user sees in the payments view. The value is `{ allowed: [...] }`, with at least one method and no duplicates.

| Channel value | Payment method |
| - | - |
| `card` | Credit or debit card |
| `spei` | SPEI bank transfer |
| `wallet` | Digital payment (wallets and digital banks) |
| `direct_debit` | Direct debit |
| `cash` | Cash at convenience stores |
| `bbva_pay_by_bank` | BBVA Pay by Bank |
| `codi` | CoDi (a payment request your user accepts from their bank app) |

* **It only restricts.** The checkout shows the methods you asked for **and** that your organization has enabled. If none is left, it answers `invalid_value` and does not change what it shows.
* **Tapipay defines the order**, not the order of your list.
* **With the checkout open**, the change applies right away, but it does not take your user out of the method they are using: if they already picked it or started entering data, that method stays available until they pick another one.

> [!NOTE]
>
> The channel values are not the same as the ones of the `paymentMethods` opening option (`CARD`, `BANK_TRANSFER`, etc.). Each SDK gives you a type with the right values for each path.

### `payment.submitted`

Arrives when the user submits the payment. The value is `{ status: "pending", data }`: `status` is always `"pending"` and `data` carries the parameters returned by the payment provider, which may be empty.

> [!WARNING]
>
> `payment.submitted` means **submitted, not settled**. Never mark a debt as paid with this event: the real status reaches your backend through the [payment notification](https://devs.tapipay.la/en/webhooks/payment-notification.md).

### `payment.cancelled`

Arrives when the user **closes the whole checkout** without having submitted a payment. The value is an empty object.

* **Native SDKs only.** The SDK generates it when the user closes the checkout from the app: the **Close** button, the back gesture on Android or swiping the sheet down on iOS, also in the middle of 3DS authentication or a redirect.
* It arrives **at most once** per opening, and **never after** a `payment.submitted`.
* It does **not** arrive when your app closes the checkout with `Tapipay.dismiss()`: that is not a user cancellation.
* It does **not** arrive when the user closes the card payment window: they can still pay with another method. For that case, the usual `PaymentCancelled` / `.paymentCancelled` event keeps arriving.
* **It never arrives on web.** The checkout lives inside your page and has no close of its own, and `tapipay.destroy()` is not a cancellation. That is why, on web, `supports("payment.cancelled")` returns `false` even if your organization has it.

`payment.submitted@1` and `payment.cancelled@1` are on by default and **coupled**: if your organization turns one off, the checkout announces neither. That way you never receive a "cancelled" without being able to receive the "submitted".

## How to enable it

**1. Request the input capabilities**

`domiciliation.prefill@1` and `payment.methods@1` are enabled per organization, on request. Ask your Tapipay contact for them. The output ones are already on.

**2. Web only: declare your origins**

Send Tapipay the list of **exact origins** of the pages that embed the widget (scheme, domain and port, for example `https://app.acme.com`). `https:` is accepted and, for development, `http://localhost`. **Without that list, the web channel does not open**: the widget still works, but without a channel.

**3. Update the SDK**

Use `@npmtapi/embed` `1.10.0` or later on web, and version `0.2.0` or later of the Android and iOS SDKs.

The native SDKs do not need to declare origins: the channel is bound to the checkout the SDK itself opens.

## Responses and errors

Every `set` ends in one of two ways: the checkout answers `ack` (on web the promise resolves; on Android and iOS the function returns without error) or the SDK hands you an error with its code.

| Code | When it arrives |
| - | - |
| `unsupported_key` | The key does not exist **or** is not enabled for your organization. It is the same code in both cases. |
| `invalid_value` | The value does not match the key's format or fails a validation (for example, the CLABE check digit, or a list of methods that leaves none available). |
| `read_only` | You called `set` on an output key, such as `payment.submitted`. |
| `payload_too_large` | The message exceeds 64 KB. |
| `invalid_envelope` | The message does not have the channel format. It should not happen if you use the SDK methods. |
| `timeout` | The checkout did not answer in time. Generated by the SDK. |
| `channel_unavailable` | The channel did not open (checkout without a channel, origin not declared on web, WebView without support on Android) or is already closed. Also when queued `set` calls wait more than 15 seconds without the channel opening. Generated by the SDK. |

> [!TIP]
>
> Treat any code not in this table as a generic error: new versions may add codes. A channel error **never interrupts the checkout flow**: the user can still pay or type their CLABE by hand.

### Lifecycle

* **One channel per opening.** Queued `set` calls and `on` handlers belong to the checkout being opened. If that checkout closes or never opens, whatever was queued fails with `channel_unavailable`: it never moves to another checkout.
* **Register your handlers again on every opening.** When the checkout closes (or, on web, when the last widget is destroyed with `tapipay.destroy()`), the SDK removes the handlers. On the next opening, register them again.
* **If the checkout reloads** (for example, because the system recreated the screen), the checkout greets again and the channel reopens with the new capabilities. A `set` that was waiting for an answer may end in `timeout`: send it again if you need to.
* **The usual events keep arriving.** The channel does not replace the `paymentSubmitted`, `PaymentSubmitted` or `.paymentSubmitted` events: they arrive as before, with or without a channel.

## Web

Available from `@npmtapi/embed` `1.10.0`, with the `embed.js` script served by Tapipay.

```bash theme={null}
npm install @npmtapi/embed@^1.10.0
```

The channel is `tapipay.channel`. You can use it before or after `initialize()`: whatever you send before the checkout opens the channel is queued.

```javascript theme={null}
tapipay.initialize({
  container: "#widget",
  organization: "acme-corp",
  identifier: "CLI-00042"
});

// App → checkout: each set resolves with the ack or rejects with an error that has a code
tapipay.channel
  .setDomiciliationPrefill({ clabe: "012180655094520118", accountHolderName: "Maria Perez" })
  .catch((error) => console.warn(error.code)); // e.g. "invalid_value", "unsupported_key"

tapipay.channel
  .setPaymentMethods({ allowed: ["card", "spei"] })
  .catch((error) => console.warn(error.code));

// Checkout → app: on() returns a function to unsubscribe
const unsubscribe = tapipay.channel.on("payment.submitted", (value) => {
  console.log(value.status); // "pending": submitted, not settled
});

// After the handshake: true only for the keys enabled for your organization
tapipay.channel.supports("payment.methods");
```

| Method | What it does |
| - | - |
| `set(key, value)` | Writes an input key. Returns a `Promise` that resolves with the `ack` or rejects with a `TapipayChannelError` (with `code`). |
| `setDomiciliationPrefill(value)` | Typed shortcut for `set("domiciliation.prefill", value)`. |
| `setPaymentMethods(value)` | Typed shortcut for `set("payment.methods", value)`. |
| `on(key, handler)` | Listens to an output key. Returns the function to unsubscribe. |
| `off(key, handler)` | Removes a handler. |
| `supports(key)` | `true` only for the keys the checkout announced for your organization. |

The types (`TapipayChannel`, `TapipayChannelError`, `TapipayChannelPaymentMethod`, etc.) are exported from `@npmtapi/embed`. In React, get the instance with `useTapipay()` and use `tapipay.channel` the same way.

> [!NOTE]
>
> `tapipay.channel` is exposed by the `embed.js` served by Tapipay. If you load an older version of the script, `tapipay.channel` is `undefined`: use `tapipay.channel?.` if your code can run against a cached script.

* **Several widgets on the same page:** the channel belongs to the last widget mounted. `set` calls go to that checkout and only that one delivers events. To initialize again, call `tapipay.destroy(container)` first.
* **The value travels as a JSON copy.** You can pass Vue or MobX reactive objects. If the value cannot be serialized, the `set` fails with `invalid_value`.
* **The channel is not available in a hand-built iframe:** it needs the SDK. The [`postMessage` messages](https://devs.tapipay.la/en/payment-portal/postmessage-events) are still emitted as before.

## Android

Available from `la.tapipay.ui:button:0.2.0`.

```kotlin build.gradle.kts theme={null}
dependencies {
    implementation("la.tapipay.ui:button:0.2.0")
}
```

Open the checkout with `Tapipay.presentWithChannel()`: it does the same as `present()` and also returns the channel of **that** opening. It returns `null` if the call was ignored because a checkout was already open.

```kotlin theme={null}
import la.tapipay.ui.button.Tapipay
import la.tapipay.ui.button.TapipayChannelException
import la.tapipay.ui.button.TapipayChannelPaymentMethod
import la.tapipay.ui.button.TapipayConfig
import la.tapipay.ui.button.TapipayDomiciliationPrefill

val channel = Tapipay.presentWithChannel(
    context = this,
    config = TapipayConfig(identifier = "CLI-00042", organization = "acme-corp"),
) { event -> handle(event) } // the usual events keep arriving here
    ?: return // ignored: a checkout was already open

// Checkout → app
val submitted = channel.onPaymentSubmitted { value ->
    showProcessing() // value.status is always "pending"; value.data may be empty
}
channel.onPaymentCancelled {
    // the user closed the whole checkout without paying
}

// App → checkout: set is a suspend function
lifecycleScope.launch {
    try {
        channel.setPaymentMethods(setOf(TapipayChannelPaymentMethod.CARD, TapipayChannelPaymentMethod.SPEI))
        channel.setDomiciliationPrefill(
            TapipayDomiciliationPrefill(clabe = "012180655094520118", accountHolderName = "Maria Perez"),
        )
    } catch (e: TapipayChannelException) {
        // e.code: UNSUPPORTED_KEY, INVALID_VALUE, TIMEOUT, CHANNEL_UNAVAILABLE...
    }
}

channel.supports("payment.methods") // after the handshake
submitted.cancel()                  // unsubscribe
```

| API | What it does |
| - | - |
| `set(key, value)` | `suspend`. Returns with the `ack` or throws `TapipayChannelException` with its `code` (`TapipayChannelErrorCode`). |
| `setDomiciliationPrefill(TapipayDomiciliationPrefill)` | Typed shortcut for `domiciliation.prefill`. |
| `setPaymentMethods(Set<TapipayChannelPaymentMethod>)` | Typed shortcut for `payment.methods`: `CARD`, `SPEI`, `WALLET`, `DIRECT_DEBIT`, `CASH`, `BBVA_PAY_BY_BANK`, `CODI`. |
| `on(key, handler)` | Listens to an output key. Returns a `TapipayChannelSubscription` with `cancel()`. |
| `onPaymentSubmitted { }` / `onPaymentCancelled { }` | Typed shortcuts for the output keys. |
| `supports(key)` | `true` only for the keys the checkout announced. |
| `state` | `WAITING`, `OPEN`, `UNAVAILABLE` or `CLOSED`. |

* `Tapipay.channel` returns the channel of the checkout open right now, or `null` if there is none. Prefer the one `presentWithChannel()` returns: it belongs to your opening even if another checkout opens later.
* Handlers are called on the main thread. A handler that throws does not break the channel.
* Cancelling the coroutine of a `set` only stops waiting for the answer.
* The channel API is for Kotlin: from Java you can only use `on`, `supports` and `state`.

> [!WARNING]
>
> On devices whose WebView does not support `WEB_MESSAGE_LISTENER` (very outdated versions of Android System WebView), **the channel does not open**: `set` calls fail with `CHANNEL_UNAVAILABLE` and only the usual events arrive. The checkout keeps working.

## iOS

Available from version `0.2.0` of the `Tapipay` package, installed with Swift Package Manager as in the [mobile apps SDK](https://devs.tapipay.la/en/payment-portal/mobile-sdk.md#ios).

```swift Package.swift theme={null}
.package(
    url: "https://bitbucket.org/tapila/tapi-tapipay-ios-sdk.git",
    .upToNextMinor(from: "0.2.0")
)
```

The channel is `Tapipay.channel`: it belongs to the open checkout or, if there is none, to the next one you open. That is why you can register handlers **before** calling `present()`.

```swift theme={null}
import Tapipay

let channel = Tapipay.channel

// Checkout → app
let submitted = channel.onPaymentSubmitted { value in
    showProcessing() // value.status is always .pending; value.data may be nil
}
channel.onPaymentCancelled { _ in
    // the user closed the whole checkout without paying
}

try Tapipay.present(
    config: TapipayConfig(identifier: "CLI-00042", organization: "acme-corp")
) { event in
    handle(event) // the usual events keep arriving here
}

// App → checkout: set is async throws
Task {
    do {
        try await channel.setPaymentMethods(TapipayChannelPaymentMethods(allowed: [.card, .spei]))
        try await channel.setDomiciliationPrefill(
            TapipayDomiciliationPrefill(clabe: "012180655094520118", accountHolderName: "Maria Perez")
        )
    } catch let error as TapipayChannelError {
        switch error.code {
        case .unsupportedKey, .channelUnavailable:
            break // the organization does not have the key, or there is no channel
        case .invalidValue:
            break // the checkout rejected the value
        default:
            break
        }
    }
}

if channel.supports(TapipayChannelKey.paymentMethods) { /* announced by the checkout */ }
submitted.cancel() // unsubscribe
```

| API | What it does |
| - | - |
| `set(_ key:, _ value:)` | `async throws`. Returns with the `ack` or throws `TapipayChannelError` with its `code`. `value` is any `Encodable`. |
| `setDomiciliationPrefill(_:)` | Typed shortcut for `domiciliation.prefill`. |
| `setPaymentMethods(_:)` | Typed shortcut for `payment.methods`: `.card`, `.spei`, `.wallet`, `.directDebit`, `.cash`, `.bbvaPayByBank`, `.codi`. |
| `on(_ key:, _ handler:)` | Listens to an output key with the raw value (`TapipayJSONValue`). There is also `on(_:as:_:)` to decode it into your own type. Returns a `TapipayChannelSubscription` with `cancel()`. |
| `onPaymentSubmitted(_:)` / `onPaymentCancelled(_:)` | Typed shortcuts for the output keys. |
| `supports(_:)` | `true` only for the keys the checkout announced. The constants are in `TapipayChannelKey`. |
| `state` | `.waiting`, `.open`, `.unavailable` or `.closed`. |

* `TapipayChannel` is `@MainActor`: handlers are called on the main thread.
* When the checkout starts closing (**Close** button, swiping the sheet or `Tapipay.dismiss()`), `Tapipay.channel` becomes a new channel for the next checkout. Whatever you do from then on does not reach the one that is closing.
* If you cancel the `Task` of a `set`, the `set` leaves the queue or stops waiting for the answer and throws `CancellationError`.
* Include `default` in your `switch` statements over `TapipayChannelError.Code` and `TapipayChannelPaymentMethods.Method`: new versions may add cases.

## Compatibility

The channel is optional and does not change anything you already have integrated.

* **Without a channel, everything works as before.** If you use an older SDK, if your organization does not have a capability or if the channel does not open, the checkout works the same and the usual events keep arriving. Only the channel `set` calls fail, with `channel_unavailable` or `unsupported_key`.
* **The opening prefill and filter keep working.** The `domiciliationPrefill` option (in `initialize()` on web and in `TapipayConfig` on Android and iOS) prefills the CLABE and the account holder when the checkout opens, without depending on the channel. The same goes for the [`paymentMethods`](https://devs.tapipay.la/en/payment-portal/payment-methods-sdk#filter-payment-methods-beta) option.
* **The SDK never reloads the checkout** to switch from one path to the other: if `setDomiciliationPrefill` fails, there is no automatic retry through the opening option.

| | `domiciliationPrefill` opening option | Channel `setDomiciliationPrefill` |
| - | - | - |
| When it is sent | Only when the checkout opens | Before opening or with the checkout open |
| Response | None: if the checkout discards it, you do not find out | `ack` or an error with a code |
| Requires | Nothing else | An open channel and `domiciliation.prefill@1` enabled |
| When to use it | While your organization does not have the capability | When your organization has the capability |

> [!WARNING]
>
> Do not send the same prefill through both paths: the checkout could apply both. Pick one per organization, or check `supports("domiciliation.prefill")` after the handshake to decide.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.