> ## 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 模式

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

Headless 是一个令牌化客户端：商户在自己的 UI 中收集卡片数据，调用 `generateToken(data:)`，收到一次性令牌，从自己的 backend 创建支付，然后调用 `continueCardPayment(onResult:)`，以便 SDK 运行任何剩余操作（例如 3DS）并交付结果。

在统一 API 中，同样的场景对应 **非 seamless 的 headless** 模式：在 `PaymentMethodSelected` 的 `transactionData` 中传入预先收集的数据，覆盖 [`createPayment`](https://docs.y.uno/zh-hans/docs/yuno-sdk/controllers/create-payment) 以从您的 backend 创建支付，并让 SDK 自动编排令牌化、3DS 和状态轮询。无需第二次调用来恢复支付：从 `createPayment` 返回即可完成这一步。

## 在 Headless 中使用支付方式列表

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

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

```swift theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
var selectedPayment: SdkPayments.PaymentMethodSelected?

// Request the views. The list reports the shopper's choice to your PaymentListController
let views = transaction.getPaymentMethodsViews(
    types: [.APPLE_PAY(), .PAYMENT_METHOD_LIST],
    controller: self
)

// In your SdkPayments.PaymentListController:
func onPaymentSelected(paymentSelected: SdkPayments.PaymentMethodSelected) {
    selectedPayment = paymentSelected
}

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

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

## 开始之前

* 将 `import YunoSDK` 替换为 `import SdkPayments`。您的公开 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)。

## 并排对照

```swift Before. Headless mode theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
import YunoSDK

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

// 2. Create the headless client
let paymentHeadless = try Yuno.apiClientPayment(
    countryCode: "CO",
    checkoutSession: "session-from-backend"
)

// 3. Build the data from your own form
let data = TokenCollectedData(
    checkoutSession: "session-from-backend",
    paymentMethod: CollectedData(
        type: "CARD",
        vaultedToken: nil,
        card: CardData(
            detail: CardData.Detail(
                number: cardNumber,
                expirationMonth: expMonth,
                expirationYear: expYear,
                securityCode: cvv,
                holderName: holder
            )
        ),
        customer: nil
    )
)

// 4. Tokenize, then create the payment on your backend yourself
let ott = try await paymentHeadless.generateToken(data: data)
let token = ott["token"] as? String ?? ""

await createPaymentOnBackend(token: token)   // your code

// 5. Hand the created payment back to the SDK: it runs any remaining action (3DS) and reports the result
paymentHeadless.continueCardPayment { result in
    switch result.status {
    case .succeeded:      print("Success")
    case .reject:         print("Rejected")
    case .fail:           print("Failed")
    case .processing:     print("Processing")
    case .internalError:  print("Internal error")
    case .userCancelled:  print("User cancelled")
    @unknown default:     break
    }
}
```

```swift After. Non-seamless headless theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
import SdkPayments

// 1. Initialize once at app startup
SdkPayments.initialize(apiKey: "your-public-api-key")

// 2. Implement the controller. Only createPayment + onStatus needed
final class Checkout: SdkPayments.TransactionController {

    func createPayment(token: SdkPayments.TransactionController.OneTimeToken) async throws {
        // Create the payment on your backend with the token.
        // Return when done; the SDK then polls status and runs 3DS if needed.
        try await createPaymentOnBackend(token: token["token"] as? String ?? "")
    }

    func onStatus(status: SdkPayments.TransactionStatus) {
        switch status.status {
        case "INTERNAL_ERROR":  print("Internal error")
        case "USER_CANCEL":     print("User cancelled")
        // Handle other backend statuses (e.g. SUCCEEDED, DECLINED, PENDING) as needed.
        default:                break
        }
    }

    // 3. Build TransactionData from your own form, then start
    func pay(cardNumber: String, cvv: String, expMonth: Int, expYear: Int, holder: String) {
        let paymentSelected = SdkPayments.PaymentMethodSelected(
            paymentMethodType: "CARD",
            transactionData: SdkPayments.TransactionData(
                card: SdkPayments.CardTransactionData(
                    number: cardNumber,
                    securityCode: cvv,
                    expirationMonth: expMonth,
                    expirationYear: expYear,
                    holderName: holder
                )
            )
        )

        let config = SdkPayments.TransactionConfig(
            checkoutSession: "session-from-backend",
            countryCode: "CO",
            controller: self
        )

        SdkPayments.Transaction(config: config)
            .start(paymentSelected: paymentSelected)
    }
}
```

## 变更内容

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

### 初始化与配置

| Headless | 统一 API | 变更 | 操作 |
| - | - | - | - |
| `import YunoSDK` | `import SdkPayments` | 重命名 | |
| `Yuno.initialize(apiKey:)` | `SdkPayments.initialize(apiKey:)` | 重命名 | `callback:` 参数已移除；如果您需要等待，请使用 `async` 重载。 |
| 在 `YunoConfig.appearance` 中传入的 `Yuno.Appearance` | `SdkPayments.TransactionConfig.appearance` 中的 `SdkPayments.Appearance` | 重命名 | 初始化方法相同；去掉 `Yuno.` 前缀，并在每笔交易中传入，而不是在启动时传入一次。 |
| `TokenCollectedData.checkoutSession` | `SdkPayments.TransactionConfig.checkoutSession` | 迁移 | 在配置中设置一次，同时设置您传给 `apiClientPayment` 的 `countryCode`。 |
| `CollectedData.type` | `SdkPayments.PaymentMethodSelected.paymentMethodType` | 迁移 | 移至父对象。请参阅 [`PaymentMethodSelected`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-pass#payment-method-selected)。 |
| `CollectedData.vaultedToken` | `SdkPayments.PaymentMethodSelected.vaultedToken` | 迁移 | 移至父对象。 |
| `CollectedData.card.detail`（`CardData.Detail`） | `SdkPayments.TransactionData.card`（`SdkPayments.CardTransactionData`） | 迁移 | 字段相同，归入 `transactionData` 命名空间下。请参阅 [`TransactionData`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-pass#transaction-data)。 |
| `CardData.save` | `SdkPayments.TransactionData.vaultOnSuccess` | 迁移 | 同样是 `Bool`，上移一级。 |
| `CardData.installment`（`CardData.Installment`） | `SdkPayments.TransactionData.installment`（`SdkPayments.InstallmentTransactionData`） | 迁移 | `id` 和 `value` 相同，上移一级。 |
| `CollectedData.customer` | `SdkPayments.TransactionData.customer` | 迁移 | 归入 `transactionData` 命名空间下。 |
| *（无）* | 其他 `SdkPayments.TransactionData` 字段 | 新增 | `issuerId`、`threeDSecure`、`bankTransfer`、`wallet` 和 `ticket` 携带 Headless 无法传递的预先收集的数据。 |

### 控制器

| Headless | 统一 API | 变更 | 操作 |
| - | - | - | - |
| *（无 delegate）* | `SdkPayments.TransactionController` | 新增 | 让一个类遵循该协议并实现 `createPayment` 和 `onStatus`（无需其他内容），然后将其作为 `TransactionConfig.controller` 传入。SDK 不会持有它：请在整个交易期间保持其存活。 |
| 在 `generateToken` 之后您自己的 backend 调用 | `createPayment(token:)` | 迁移 | 覆盖它：`token` 是以字典形式提供的完整一次性令牌。在处理程序中通过您的 backend 创建支付，该处理程序为 `async throws`。如果它抛出异常，流程会停止且不会调用 `onStatus`，因此请自行显示错误。请参阅 [`createPayment`](https://docs.y.uno/zh-hans/docs/yuno-sdk/controllers/create-payment)。 |
| `continueCardPayment` 的 `onResult` 闭包（`Yuno.Result`） | `onStatus(status:)`（`SdkPayments.TransactionStatus`） | 重命名 | 仍是结果 callback，现在每笔交易调用一次。`status` 和 `substatus` 来自 backend；SDK 本身只发出 `INTERNAL_ERROR` 和 `USER_CANCEL`。`message` 保持其作用：`source` 现在是一个枚举，`code` 不再是可选值。请参阅 [`Status`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-receive#status)。 |
| 由 `apiClientPayment` 和 `generateToken` 抛出的 `YunoPaymentHeadlessError` | `status == "INTERNAL_ERROR"` 且带有 `message` 的 `onStatus` | 迁移 | 不再抛出任何异常：请在 `onStatus` 中处理 `INTERNAL_ERROR`。 |

### 入口点

| Headless | 统一 API | 变更 | 操作 |
| - | - | - | - |
| `Yuno.apiClientPayment(countryCode:checkoutSession:)` | `SdkPayments.Transaction(config:)` | 重命名 | 交易对象取代了 headless 客户端：不再有 `apiClient*` 对象，单个 `Transaction` 涵盖完整的生命周期。其 `countryCode` 和 `checkoutSession` 放在配置中。 |
| `paymentHeadless.generateToken(data:)` | `SdkPayments.Transaction(config:).start(paymentSelected:)` | 重命名 | 您不再自行令牌化。在 Headless 显式执行的三件事（令牌化、在您的 backend 创建支付、通过 `continueCardPayment` 恢复）中，只有支付创建仍由您负责，通过 `createPayment` 完成。使用您预先收集的 `transactionData` 构建 `PaymentMethodSelected`，然后调用 `start`：SDK 会进行令牌化，并使用该令牌调用 `createPayment`。 |
| `generateToken` 的结果（`[String: Any]`） | `createPayment` 的 `token` 参数（`TransactionController.OneTimeToken`） | 迁移 | 仍是字典 `[String: Any]`（即该 typealias），以保持跨平台一致。请参阅 [`OneTimeToken`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-receive#one-time-token)。 |
| `paymentHeadless.continueCardPayment(onResult:)` | 从 `createPayment(token:)` 返回 | 迁移 | 删除该调用：从 `createPayment` 返回即可恢复流程。SDK 会检查支付状态，以全屏方式运行任何剩余操作（例如 3DS）（覆盖 [`showView`](https://docs.y.uno/zh-hans/docs/yuno-sdk/controllers/show-view) 不会改变这一点），并在 `onStatus` 中报告结果。 |

## 相关内容

* [`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/ios/payment/lite.md)。适用于更简单的“SDK 显示表单”场景。


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