> ## 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 SDK（iOS 支付）

> 将 Yuno 的 Headless SDK（iOS 支付）集成到您的移动应用中的 分步指南。

> [!NOTE]
>
> **This page documents a legacy SDK.** Starting a new integration? Use the [Yuno SDK](https://docs.y.uno/docs/yuno-sdk/get-started.md). Already on a legacy SDK? Follow the [migration guide](https://docs.y.uno/docs/yuno-sdk/migration/overview.md).
>
> The new **Yuno SDK** (Web v2.x, iOS v3.x, Android v3.x, React Native v2.x) replaces the Full, Lite, Seamless, Render, Headless, and Secure Fields SDKs with one API across every platform. Legacy SDKs remain supported side by side during the transition and are scheduled for deprecation in **2027**. Contact your Account Manager for migration planning.

> [!WARNING]
>
> **Orientation: Choosing Your Integration Flow**, before you begin, please review the [Official Integration Flow](https://docs.y.uno/docs/sdks/overview/understanding-flows.md).
>
> * **Standard Flow ([Full Checkout](https://docs.y.uno/docs/sdks/full-checkout/web-payments))**: Recommended for most merchants. Yuno handles the UI, security, and automatic updates for payment methods.
> * **Custom Flow (This SDK)**: Use this only if you require full control over the UX. **Note**: You will be responsible for manually handling payment statuses, 3DS transitions, and fraud routing data collection.

Yuno 的 Headless iOS SDK 让您可以同时创建支付和注册支付方式。使用 Headless SDK 时，请注意您需要通过 API 请求并发送支付服务提供商要求的所有必填字段。在其 API 中生成支付需要这些字段。

Yuno 的 Headless SDK 让您可以在两种不同场景下创建支付：

* 使用信用卡信息或替代支付方式创建一次性令牌，然后创建支付。
* 使用先前注册的支付方式的 `vaulted_token` 创建一次性令牌。这会在您创建支付之前为欺诈服务提供商收集相关信息。

以下步骤介绍如何使用 Yuno 的 Headless SDK 创建支付。

## 步骤 1：在项目中引入库

第一步是将 Yuno SDK 安装到您的 iOS 项目中。

> [!NOTE]
>
> **查看 iOS SDK 版本**
>
> 如需查看所有可用版本，请访问 Yuno iOS SDK 代码库的[发布页面](https://github.com/yuno-payments/yuno-sdk-ios/releases)。

您可以使用 [Swift Package Manager](https://www.swift.org/package-manager/) 安装 Yuno SDK。YunoSDK 已不再发布到 CocoaPods，最后一个 CocoaPods 版本是 2.30.0。设置 Swift 包，然后将 Yuno SDK 添加为依赖项，如以下代码块所示：

```swift theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
dependencies: [
    .package(url: "https://github.com/yuno-payments/yuno-sdk-ios.git", .upToNextMajor(from: "2.31.0"))
]
```

将 `YunoSDK`（动态）或 `YunoSDK-Static`（静态，即 CocoaPods 提供的版本）添加到您的应用 target，切勿同时添加两者。

## 步骤 2：使用公钥初始化 Headless SDK

要初始化 Headless SDK，您需要导入 Yuno 并提供有效的 **PUBLIC\_API\_KEY**。如果您还没有 API 凭证，请访问[开发者（凭证）](https://docs.y.uno/zh-hans/docs/using-yuno/settings/developers-credentials.md)页面，了解如何从 Dashboard 获取凭证。

> [!WARNING]
>
> **UISceneDelegate 初始化**
>
> 如果您的应用使用 `UISceneDelegate`，请确保将 Yuno 初始化代码放在您的 `SceneDelegate` 中。

以下代码块展示了导入和初始化 `Yuno` 的示例。

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

Yuno.initialize(
    apiKey: "PUBLIC_API_KEY"
)
```

> [!NOTE]
>
> **Swift 6 并发要求**
>
> 如果您使用 Swift 6，在使用 SDK 的异步方法时需要正确处理并发。有关详细的实现选项和最佳实践，请参阅 [Swift 6 并发](https://docs.y.uno/zh-hans/docs/sdks/resources/swift-6-concurrency.md)指南。

## 步骤 3：启动 checkout 流程

接下来，您将使用 `apiClientPayment` 函数并提供必要的配置参数来启动 checkout 流程。您需要在客户选择支付方式后调用此函数。之后，SDK 将开始收集您在路由中配置的 3DS 和欺诈预防工具所需的相关信息。

### 参数

下表列出了所有必需的参数及其说明。

| 参数 | 说明 |
| - | - |
| `countryCode` | 此参数确定正在为哪个国家配置支付流程。支持的国家及其 `countryCode` 的完整列表请参阅[国家覆盖范围](https://docs.y.uno/zh-hans/docs/sdks/resources/country-coverage.md)页面。 |
| `checkout_session` | 指当前支付的结账会话，通过[创建结账会话](https://docs.y.uno/zh-hans/reference/checkout-sessions/create-checkout-session.md) endpoint 创建。示例：'438413b7-4921-41e4-b8f3-28a5a0141638' |

以下代码块展示了参数配置示例。

```swift theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
var apiClientPayment: YunoPaymentHeadless?

apiClientPayment = try Yuno.apiClientPayment(
    countryCode: "CO",
    checkoutSession: "438413b7-4921-41e4-b8f3-28a5a0141638"
)
```

## 步骤 4：生成令牌

收集所有用户信息后，您就可以开始支付。首先，您需要使用 `apiClientPayment.generateToken` 函数创建一次性令牌（OTT）。由于这是一个异步函数，您可以使用 `do/catch` 来确保正确处理触发的错误。以下是创建一次性令牌的两种不同场景示例：

1. **示例 1**：使用卡片作为支付方式并包含所有必需的卡片信息，创建一次性令牌。
2. **示例 2**：使用 `vaulted_token` 信息创建一次性令牌。

> [!TIP]
>
> **使用存储令牌的优势**
>
> 在 SDK 中使用存储令牌，可确保收集您所配置的服务提供商的所有欺诈信息，并将其附加到一次性令牌上。此外，如果服务提供商要求，您还可以包含分期付款详情和安全码。

```swift Example 1 theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
let tokenCollectedData: TokenCollectedData = TokenCollectedData(
    checkoutSession: "438413b7-4921-41e4-b8f3-28a5a0141638",
    paymentMethod: CollectedData(
        type: "CARD",
        vaultedToken: nil,
        card: CardData(
            save: true,
            detail: CardData.Detail(
                number: "4111111111111111",
                expirationMonth: 12,
                expirationYear: 25,
                securityCode: "123",
                holderName: "Andrea",
                type: .credit
            ),
            installment: CardData.Installment(
                id: "64ceacef-0886-4c81-9779-b2b3029c4e8b",
                value: 1
            )
        ),
        customer: Customer()
    )
)

let result = try await apiClientPayment?.generateToken(
    data: tokenCollectedData
)
```

```swift Example 2 theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
let tokenCollectedData: TokenCollectedData = TokenCollectedData(
    checkoutSession: "438413b7-4921-41e4-b8f3-28a5a0141638",
    paymentMethod: CollectedData(
        type: "CARD",
        vaultedToken: "c8bb2bd8-8abf-4265-b478-0ec4e3c10cd5",
        card: CardData(
            installment: CardData.Installment(
                id: "64ceacef-0886-4c81-9779-b2b3029c4e8b",
                value: 1
            )
        ),
        customer: Customer()
    )
)

let result = try await apiClientPayment?.generateToken(
    data: tokenCollectedData
)
```

以下代码块展示了上述两个示例中 `apiClientPayment.generateToken` 函数的响应。响应是 `[String: Any]` 类型的字典。

```swift Example 1 theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
 ["token": "9ee44ac7-9134-4598-ae28-a26fec03099d",
     "type": "CARD",
     "customer": ["billing_address": nil,
                  "first_name": nil,
                  "gender": "",
                  "phone": nil,
                  "browser_info": ["color_depth": nil,
                                   "language": "en",
                                   "accept_header": "*/*",
                                   "browser_time_difference": null,
                                   "accept_content": null,
                                   "accept_browser": null,
                                   "java_enabled": null,
                                   "user_agent": "YunoSDK_Example/1 CFNetwork/1406.0.4 Darwin/22.6.0",
                                   "screen_height": "844.0",
                                   "screen_width": "390.0",
                                   "javascript_enabled": null],
                  "document": null,
                  "last_name": null,
                  "device_fingerprint": nil,
                  "email": nil],
     "country": "BR",
     "vaulted_token": nil,
     "installment": ["rate": "",
                     "id": "cca80084-961b-4212-9c34-54f03f4f10ae",
                     "value": 24,
                     "amount": null],
     "card_data": null]

```

```swift Example 2 theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
["token": "9ee44ac7-9134-4598-ae28-a26fec03099d",
     "type": "CARD",
     "customer": ["billing_address": nil,
                  "first_name": nil,
                  "gender": "",
                  "phone": nil,
                  "browser_info": ["color_depth": nil,
                                   "language": "en",
                                   "accept_header": "*/*",
                                   "browser_time_difference": null,
                                   "accept_content": null,
                                   "accept_browser": null,
                                   "java_enabled": null,
                                   "user_agent": "YunoSDK_Example/1 CFNetwork/1406.0.4 Darwin/22.6.0",
                                   "screen_height": "844.0",
                                   "screen_width": "390.0",
                                   "javascript_enabled": null],
                  "document": null,
                  "last_name": null,
                  "device_fingerprint": nil,
                  "email": nil],
     "country": "BR",
     "vaulted_token": "a1c7c5d1-b260-4dc6-909a-8368704233cf",
     "installment": ["rate": "",
                     "id": "cca80084-961b-4212-9c34-54f03f4f10ae",
                     "value": 24,
                     "amount": null],
     "card_data": null]

```

## 步骤 5：创建支付

完成前面所述的步骤后，您就可以创建支付。生成令牌后，立即从您的 backend 调用[创建支付 endpoint](https://docs.y.uno/zh-hans/reference/payments/create-payment.md)，并使用一次性令牌和结账会话。

endpoint 响应包含 `sdk_action_required` 参数，用于指示完成支付是否需要额外操作：

对于同步支付方式，支付会立即完成。在这种情况下，API 响应中的 `sdk_action_required` 将为 false，支付流程结束。如果支付需要 SDK 进一步交互才能完成流程，`sdk_action_required` 将为 true。在这种情况下，请按照步骤 6 中的说明继续操作。

## 步骤 6：处理异步支付（可选）

使用 3DS 的支付可能需要额外的挑战来验证客户身份，如 [3DS 卡片验证](https://docs.y.uno/zh-hans/docs/security-and-compliance/3d-secure.md)页面所述。如果需要 3DS 验证挑战，[创建支付](https://docs.y.uno/zh-hans/reference/payments/create-payment.md) endpoint 的响应将包含：

* 状态等于 `PENDING`，子状态等于 `WAITING_ADDITIONAL_STEP`
* `sdk_action_required = true`

要执行挑战并完成支付，请使用以下集成选项：

### 完成 3DS 挑战

要完成您从服务器创建的卡支付的 3DS 挑战，请在您的 Headless 客户端上调用 `continueCardPayment` 函数。SDK 将获取支付状态，向您的客户呈现 3DS 挑战，并将每次支付状态更新回报给您。

> [!NOTE]
>
> `continueCardPayment` 仅支持 `CARD` 支付。

```swift theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
func continueCardPayment(onResult: @escaping (Yuno.Result) -> Void)
```

该函数可在您用于生成一次性令牌的同一个 `YunoPaymentHeadless` 实例上使用。以下是一个完整示例：

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

apiClientPayment?.continueCardPayment { result in
    switch result.status {
    case .processing:
        // The challenge was presented; the payment is being processed.
        break
    case .succeeded:
        // The customer completed the challenge and the payment was approved.
        break
    case .reject, .fail:
        // The payment was rejected or failed.
        break
    case .userCancelled:
        // The customer closed the challenge without completing it.
        break
    case .internalError:
        // Something went wrong while continuing the payment.
        break
    @unknown default:
        break
    }
}
```

当您调用 `continueCardPayment` 时，SDK 将：

1. 获取与 `checkoutSession` 关联的支付的当前状态。
2. 在安全的 Web 视图中，于您应用的当前页面之上呈现 3DS 挑战。
3. 客户完成挑战后自动关闭挑战页面。
4. 实时监听交易结果，并通过在主线程上调用的 `onResult` 闭包传递每次状态更新。

`onResult` 闭包可能会被调用多次。在交易确认期间，您会收到中间状态 `processing`，随后是终态（`succeeded`、`reject`、`fail`、`userCancelled` 或 `internalError`）。

> [!WARNING]
>
> **已弃用：`getThreeDSecureChallenge`**
>
> `getThreeDSecureChallenge` 方法已在 2.18.0 版本中弃用。请改用 `continueCardPayment`。

## 错误处理

在您的应用中处理 SDK 返回的错误，例如支付失败或验证错误。有关 HTTP 状态码和响应代码，请参阅 API 参考中的[状态和响应代码](https://docs.y.uno/reference/payments/status-and-response-codes/payment.md)。


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