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

> ## Agent Instructions
> Test in the sandbox first: base URL https://api-sandbox.y.uno (Test Mode in the Dashboard). Production is https://api.y.uno (Live Mode).
> Every API request needs the public-api-key and private-secret-key headers. Get them in the Dashboard at https://dashboard.y.uno/developers (Developers > Credentials); sandbox and production keys are different.
> Send an X-Idempotency-Key (a UUID) when creating payments, refunds and cancels, so retries do not create duplicates.
> Start with the Quickstart (https://docs.y.uno/docs/quickstart.md) and the agent guide (https://docs.y.uno/agents.md). To search these docs from a coding agent, connect the docs MCP server at https://docs.y.uno/mcp.

# Headless 模式

> 将 Android Headless 集成（Yuno.apiClientPayment + generateToken）迁移到统一的 Transaction API。

Headless 过去是一个纯令牌化客户端：商户在自己的 UI 中收集卡片数据，调用 `apiClient.generateToken(collectedData, context)`，收到令牌，然后自行调用 backend 创建支付（当 backend 返回需要 3DS 的状态时，再通过 `apiClient.continueCardPayment(…)` 继续支付）。

在统一 API 中，同样的场景对应 **非 seamless headless** 模式：在 `PaymentMethodSelected` 的 `transactionData` 中传入预先收集的数据，覆盖 [`createPayment`](https://docs.y.uno/zh-hans/docs/yuno-sdk/controllers/create-payment) 以从您的 backend 创建支付，并让 SDK 自动编排令牌化、3DS 和状态轮询。商户不再需要调用单独的 3DS endpoint。

## 将支付方式列表与 Headless 结合使用

Headless 并不意味着您不能使用 SDK 组件。您可以将用于选择支付方式的 [`getPaymentMethodsViews`](https://docs.y.uno/zh-hans/docs/yuno-sdk/features/payment-methods-list) 与用于执行支付的 headless `start()` 结合使用。

* **职责划分**：
  * **Yuno 负责**：渲染支付方式列表、显示客户已保存的支付方式、快捷钱包按钮（Google Pay）、3DS 挑战、重定向和交接。
  * **商户负责**：渲染自定义的卡片收集输入框以及您自己的 Pay 按钮。

```kotlin theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
var selectedPayment: PaymentMethodSelected? = null

// Request the views. The list reports the shopper's choice to your PaymentListController
val views = transaction.getPaymentMethodsViews(
    host = this,
    types = listOf(PaymentMethodType.GooglePay(), PaymentMethodType.PaymentMethodList),
    controller = this
)

// In your PaymentListController:
override fun onPaymentSelected(paymentSelected: PaymentMethodSelected) {
    selectedPayment = paymentSelected
}

// When the customer taps your own Pay button:
selectedPayment?.let { selected ->
    val paymentSelected = when {
        selected.vaultedToken != null -> {
            // Saved card: keep the token from the list and add the CVV from your own input
            PaymentMethodSelected(
                type = selected.type,
                vaultedToken = selected.vaultedToken,
                transactionData = TransactionData(
                    card = CardData(securityCode = cvv),
                ),
            )
        }
        selected.type == "CARD" -> {
            // New card: send the data collected in your own inputs
            PaymentMethodSelected(
                type = "CARD",
                transactionData = TransactionData(
                    card = CardData(
                        number = cardNumber,
                        securityCode = cvv,
                        expirationMonth = expMonth,
                        expirationYear = expYear,
                        holderName = cardHolder,
                    ),
                ),
            )
        }
        // Non-card method (e.g. APM or redirect): pass the selection as it is
        else -> selected
    }
    transaction.start(activity = this, paymentSelected = paymentSelected)
}
```

> [!WARNING]
>
> **Unfolded display 不能与 headless 卡片收集一起使用**。在 **Checkout Builder → Styling** 中启用 **Unfolded display** 时，选择一种支付方式会直接在列表行内嵌入并提交 Yuno 的预构建表单。要在您自己的输入框中收集卡片详细信息，请确保 Unfolded display 已禁用，使列表仅作为选择器。

## 开始之前

* 将 `com.yuno.sdk.*` 导入替换为对应的 `com.yuno.payments.sdk.api.*`（对照代码中列出了它们）。您的公共 API 密钥以及您的 backend 创建的结账会话保持不变（[开始之前](https://docs.y.uno/zh-hans/docs/yuno-sdk/get-started.md#before-you-begin)）。
* 决定由谁创建支付。结账会话的 `workflow` 必须与该决定一致：

| 由谁创建支付 | 在 Headless 中您的做法 | 在统一 API 中 | 会话 `workflow` |
| - | - | - | - |
| 您的 backend | 始终如此：先调用 `generateToken`，再自行调用 backend | 覆盖 `createPayment` | 默认（`SDK_CHECKOUT`） |
| SDK | 无对应项：Headless 从不创建支付 | 不覆盖 | `SDK_SEAMLESS` |

> [!WARNING]
>
> 使用默认 workflow 且未覆盖 `createPayment` 的会话会以 `INTERNAL_ERROR` 结束：backend 会拒绝 SDK 创建支付。请参阅 [`createPayment`](https://docs.y.uno/zh-hans/docs/yuno-sdk/controllers/create-payment)。

## 对照

```kotlin Before. Headless mode theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
import com.yuno.sdk.Yuno
import com.yuno.sdk.ApiClientPayment
import com.yuno.sdk.ApiClientPayment.Companion.generateToken
import com.yuno.sdk.ApiClientPayment.Companion.continueCardPayment
import com.yuno.sdk.payments.TokenCollectedData
import com.yuno.sdk.payments.PaymentMethod
import com.yuno.sdk.payments.CardData
import com.yuno.sdk.payments.Detail

class CheckoutActivity : ComponentActivity() {

    private lateinit var apiClient: ApiClientPayment

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 1. Initialize once at app startup
        Yuno.initialize(applicationContext, apiKey = "your-public-api-key")

        // 2. Create the headless client
        apiClient = Yuno.apiClientPayment(
            checkoutSession = "session-from-backend",
            countryCode = "CO",
            context = this,
        )
    }

    // 3. Tokenize from your own form, then create the payment on your backend yourself
    suspend fun pay(number: String, cvv: String, expMonth: Int, expYear: Int, holder: String) {
        val data = TokenCollectedData(
            checkoutSession = "session-from-backend",
            paymentMethod = PaymentMethod(
                type = "CARD",
                vaultedToken = null,
                card = CardData(
                    save = false,
                    detail = Detail(
                        number = number,
                        securityCode = cvv,
                        expirationMonth = expMonth,
                        expirationYear = expYear,
                        holderName = holder,
                    ),
                ),
            ),
        )

        val result = apiClient.generateToken(data, context = this)
        val token = result["token"] as? String ?: return

        createPaymentOnBackend(token)   // your code
    }

    // 4. Optional: continue the payment if your backend returned a 3DS-required status
    fun continue3ds() {
        apiClient.continueCardPayment(
            activity = this,
            showPaymentStatus = false,
        ) { state, subState ->
            // handle the final state
        }
    }
}
```

```kotlin After. Non-seamless headless theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
import com.yuno.payments.sdk.api.SdkPayments
import com.yuno.payments.sdk.api.Transaction
import com.yuno.payments.sdk.api.TransactionConfig
import com.yuno.payments.sdk.api.TransactionController
import com.yuno.payments.sdk.api.models.PaymentMethodSelected
import com.yuno.payments.sdk.api.models.TransactionStatus
import com.yuno.payments.sdk.api.models.TransactionData
import com.yuno.payments.sdk.api.models.CardData

class CheckoutActivity : ComponentActivity(), TransactionController {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 1. Initialize once at app startup
        SdkPayments.initialize(applicationContext, apiKey = "your-public-api-key")
    }

    // 2. Override createPayment. The SDK will wait for this suspend fun to return before
    //    querying status. Returning normally signals "payment created, please continue."
    //    Throwing stops the flow (the SDK will not invoke onStatus).
    override suspend fun createPayment(token: Map<String, Any>) {
        createPaymentOnBackend(token["token"] as? String ?: "")
    }

    override fun onStatus(status: TransactionStatus) {
        // status.status: "SUCCEEDED" / "REJECTED" / ...
    }

    // 3. Build TransactionData from your own form, then start
    fun pay(number: String, cvv: String, expMonth: Int, expYear: Int, holder: String) {
        val paymentSelected = PaymentMethodSelected(
            type = "CARD",
            transactionData = TransactionData(
                card = CardData(
                    number = number,
                    securityCode = cvv,
                    expirationMonth = expMonth,
                    expirationYear = expYear,
                    holderName = holder,
                ),
            ),
        )

        val config = TransactionConfig(
            checkoutSession = "session-from-backend",
            countryCode = "CO",
            controller = this,
        )

        Transaction(config = config)
            .start(activity = this, paymentSelected = paymentSelected)
    }
}
```

## 变更内容

按您编辑代码的顺序分组。**重命名**：作用相同，名称变更。**移动**：值相同，归属对象变更。**移除**：无需调用任何内容。**新增**：没有旧版对应项。最后一列是除重命名之外您唯一需要做的事。

### 初始化和配置

| Headless | 统一 API | 变更 | 操作 |
| - | - | - | - |
| `import com.yuno.sdk.*` | `import com.yuno.payments.sdk.api.*` | 重命名 | |
| `Yuno.initialize(context, apiKey)` | `SdkPayments.initialize(context, apiKey)` | 重命名 | |
| `TokenCollectedData.checkoutSession` | `TransactionConfig.checkoutSession` | 移动 | 在配置中设置一次，同时设置您之前传给 `apiClientPayment` 的 `countryCode`。 |
| `PaymentMethod.type` | `PaymentMethodSelected.type` | 移动 | 移至父对象。请参阅 [`PaymentMethodSelected`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-pass#payment-method-selected)。 |
| `PaymentMethod.vaultedToken` | `PaymentMethodSelected.vaultedToken` | 移动 | 移至父对象。 |
| `PaymentMethod.card`（带有嵌套 `Detail` 的 `CardData`） | `TransactionData.card`（`CardData`） | 移动 | 字段相同，归入 `transactionData` 命名空间下并扁平化：没有 `detail` 封装层。请参阅 [`TransactionData`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-pass#transaction-data)。 |
| `PaymentMethod.customer` | `TransactionData.customer` | 移动 | 归入 `transactionData` 命名空间下。 |

### 控制器

| Headless | 统一 API | 变更 | 操作 |
| - | - | - | - |
| *（自由形式的 callback，没有控制器）* | `TransactionController` | 新增 | 在一个类上实现它，包含 `createPayment` 和 `onStatus`（无需其他内容），并将其作为 `TransactionConfig.controller` 传入。SDK 不会持有它：请在整个交易期间保持其存活。 |
| 在 `generateToken` 之后您自己的 backend 调用 | `createPayment(token: Map<String, Any>)` | 移动 | 覆盖它：SDK 会使用 `token`（以 map 形式表示的完整一次性令牌）调用您的处理程序。在您的 backend 上创建支付后返回。该处理程序是一个 `suspend fun`，返回即表示“支付已创建，请继续”：SDK 随后查询支付状态并完成流程。如果它抛出异常，流程将停止且不会调用 `onStatus`，因此请自行显示错误。请参阅 [`createPayment`](https://docs.y.uno/zh-hans/docs/yuno-sdk/controllers/create-payment)。 |
| *（没有结果控制器）* | `onStatus(status: TransactionStatus)` | 新增 | SDK 现在驱动完整的生命周期，并在此报告最终状态，每个交易一次。`status` 和 `substatus` 来自 backend；SDK 本身只会发出 `INTERNAL_ERROR` 和 `USER_CANCEL`。请参阅 [`Status`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-receive#status)。 |

### 入口点

| Headless | 统一 API | 变更 | 操作 |
| - | - | - | - |
| `Yuno.apiClientPayment(checkoutSession, countryCode, context)` | `Transaction(config)` | 重命名 | 交易对象替代 headless 客户端：不再有 `apiClient*` 对象，单个 `Transaction` 覆盖完整的生命周期。其 `checkoutSession` 和 `countryCode` 放入配置中。所有调用都不再需要 `Context` 参数：`SdkPayments.initialize` 会保留应用程序 context，`Transaction` / `TransactionConfig` 不需要它。 |
| `apiClient.generateToken(data, context)`（suspend，返回 `Map<String, Any?>`） | `Transaction(config).start(activity, paymentSelected)` | 重命名 | 您不再需要自行令牌化。在 Headless 显式执行的三件事（令牌化、在您的 backend 上创建支付、触发 3DS）中，只有创建支付仍由您负责，通过 `createPayment` 完成。使用您预先收集的 `transactionData` 构建 `PaymentMethodSelected`，然后调用 `start`：SDK 会进行令牌化，并使用该令牌调用 `createPayment`。 |
| `generateToken` 的结果（`Map<String, Any?>`） | `createPayment` 的 `token` 参数（`Map<String, Any>`） | 移动 | 概念上即 *OneTimeToken*，在所有平台上都是相同的 payload。请参阅 [`OneTimeToken`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-receive#one-time-token)。 |
| `apiClient.continueCardPayment(activity, showPaymentStatus, callbackPaymentState)` | *（已移除）* | 移除 | 删除该调用：SDK 会在交易过程中自动运行 3DS，并以全屏方式展示 WebView；您改为通过 `showLoading` / `onStatus` 观察进度。这一点是固定的：覆盖 [`showView`](https://docs.y.uno/zh-hans/docs/yuno-sdk/controllers/show-view) 不会改变它，因为 `showView` 仅针对非 WebView 的操作视图（例如二维码）触发，而不针对 3DS 挑战或重定向。 |

## 相关内容

* [`createPayment`](https://docs.y.uno/zh-hans/docs/yuno-sdk/controllers/create-payment)。接收令牌的控制器。
* [`TransactionData`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-pass#transaction-data)。预先收集数据的结构。
* [`PaymentMethodSelected`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-pass#payment-method-selected)。`transactionData` 所在的位置。
* [迁移 / Lite](https://docs.y.uno/zh-hans/docs/yuno-sdk/migration/android/payment/lite.md)。适用于更简单的“由 SDK 显示表单”的情况。


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