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

> 将 Web Headless 集成（yuno.apiClientPayment）迁移到统一的 Transaction API。

Headless 过去是一个纯令牌化客户端：商户在自己的 UI 中收集卡片数据，生成令牌，然后自行调用 backend 创建支付。

在统一 API 中，同样的场景对应 headless `start()`。在您传给 `start()` 的 `paymentMethod` 中，通过 `data` 传入预先收集的数据，覆盖 [`createPayment`](https://docs.y.uno/zh-hans/docs/yuno-sdk/controllers/create-payment) 以向您的 backend 发送 POST 请求（手动模式），并让 SDK 自动编排令牌化、3DS 和状态轮询。如果您不希望 SDK 在创建支付后继续流程，请在 [`TransactionConfig`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-pass#transaction-config) 对象上将 `autoContinuePayment` 设置为 `false`。

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

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

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

```typescript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
let selectedMethod: PaymentMethodSelected | null = null

const views = transaction.getPaymentMethodsViews({
    types: ['applePay', 'googlePay', 'paymentMethodList'],
    onPaymentSelected: (selection) => {
        // selection contains { type, name, vaultedToken, selectionSource }
        selectedMethod = selection
    },
})

views.paymentMethodList?.mount({ elementSelector: '#payment-list' })

// When the customer submits with your own Pay button:
if (selectedMethod) {
    if (selectedMethod.vaultedToken) {
        // Customer selected a saved (vaulted) method
        await transaction.start({
            paymentMethod: {
                type: selectedMethod.type,
                vaultedToken: selectedMethod.vaultedToken,
                data: {
                    card: {
                        securityCode: cvv,
                    },
                },
            },
        })
    } else if (selectedMethod.type === 'CARD') {
        // Customer selected new card: submit your custom card form data
        await transaction.start({
            paymentMethod: {
                type: 'CARD',
                data: {
                    card: {
                        holderName: cardHolder,
                        number: cardNumber,
                        securityCode: cvv,
                        expirationMonth: expMonth,
                        expirationYear: expYear,
                    },
                },
            },
        })
    } else {
        // Non-card method (e.g. APM or direct redirect)
        await transaction.start({
            paymentMethod: {
                type: selectedMethod.type,
            },
        })
    }
}
```

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

## 开始之前

* 加载统一 SDK 包而不是旧版包，并按照对照代码所示进行初始化：`window.Yuno.initialize(...)` 变为 `SdkPayments.initialize(...)`。您的公共 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)。

## 对照

```typescript Before. Headless (apiClientPayment) theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
const yuno = await window.Yuno.initialize('your-public-api-key')

const apiClientPayment = await yuno.apiClientPayment({
    checkout_session: 'session-from-backend',
    country_code: 'CO',
})

// Merchant collects card data in their own UI, then:
const oneTimeToken = await apiClientPayment.generateToken({
    payment_method: {
        type: 'CARD',
        card: {
            detail: {
                holder_name: 'John Doe',
                number: '4111111111111111',
                security_code: '123',
                expiration_month: 12,
                expiration_year: 28,
            },
        },
        third_party_data: null,
    },
})

// Merchant POSTs to their backend
const paymentId = await myBackend.pay({ oneTimeToken, checkoutSession })

// If 3DS needed, merchant calls SDK again to challenge (bespoke per integration)
```

```typescript After. Unified Transaction (headless) theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
const sdkPayments = await SdkPayments.initialize('your-public-api-key')

const transaction = sdkPayments.transaction({
    checkoutSession: 'session-from-backend',
    countryCode: 'CO',
    createPayment: async (token) => {
        await myBackend.pay({ token: token.token })
    },
    onStatus: (result) => console.log('done:', result.status),
})

await transaction.start({
    paymentMethod: {
        type: 'CARD',
        data: {
            card: {
                holderName: 'John Doe',
                number: '4111111111111111',
                securityCode: '123',
                expirationMonth: 12,
                expirationYear: 28,
            },
        },
    },
})
```

## 变更内容

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

### 初始化和配置

| Headless | 统一 API | 变更 | 操作 |
| - | - | - | - |
| `window.Yuno.initialize(publicApiKey)` | `SdkPayments.initialize(publicApiKey)` | 重命名 | 全局对象是 `window.SdkPayments`。与之前一样，对其使用 `await`：它会解析为您用来创建交易的 `SdkPayments` 实例。 |
| `apiClientPayment` 的 `checkout_session`、`country_code` 参数 | 交易配置中的 `checkoutSession`、`countryCode` | 移动 | 在配置中设置一次。 |
| `payment_method.card.detail` 下的 `holder_name`、`number`、`security_code`、`expiration_month`、`expiration_year`（`generateToken` 的参数） | `paymentMethod.data.card` 下的 `holderName`、`number`、`securityCode`、`expirationMonth`、`expirationYear` | 移动 | 卡片数据以内联方式传给 `start()`，嵌套在 `data.card` 下，采用统一的 `TransactionData` 结构。该结构支持更多字段，不仅涵盖卡片，还涵盖替代支付方式（APM），例如银行转账、票据、钱包等。完整结构请参阅 [`TransactionData`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-pass#transaction-data)。 |
| *（无）* | `paymentMethod.vaultedToken` | 新增 | 对于已保存的卡片，在 `paymentMethod` 上传入 `vaultedToken`，并在 `data.card` 下只传入 `securityCode`：`transaction.start({ paymentMethod: { type: 'CARD', vaultedToken: 'tok_saved_abc', data: { card: { securityCode: '123' } } } })`。 |

### Callback

| Headless | 统一 API | 变更 | 操作 |
| - | - | - | - |
| 在 `generateToken` 之后您自己的 backend 调用 | `createPayment(token)` | 移动 | 在交易配置中连接它：`token` 与过去 `generateToken` 直接返回给您代码的令牌相同，现在作为您覆盖方法的参数传递；无需单独调用来获取它。将其 POST 到您的 backend 并 resolve 该 Promise：SDK 会从那里继续。请参阅 [`createPayment`](https://docs.y.uno/zh-hans/docs/yuno-sdk/controllers/create-payment) 和 [`OneTimeToken`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-receive#one-time-token)。 |
| *（没有结果 callback）* | `onStatus(result)` | 新增 | SDK 现在驱动完整的生命周期（令牌化、3DS、状态轮询），并在此报告最终状态。请参阅 [`Status`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-receive#status)。 |

### 入口点

| Headless | 统一 API | 变更 | 操作 |
| - | - | - | - |
| `yuno.apiClientPayment({ checkout_session, country_code })` | `sdkPayments.transaction({ checkoutSession, countryCode, createPayment })` | 重命名 | 该工厂方法整合了 API 客户端和 Transaction 两套接口：不再有单独的 `apiClientPayment` 接口，只有一个 `sdkPayments.transaction(config)`。 |
| `apiClientPayment.generateToken(cardData)` | `transaction.start({ paymentMethod: { type: 'CARD', data: { card } } })` | 重命名 | 您不再需要自行令牌化：使用您预先收集的卡片数据构建 `paymentMethod`（请参阅“初始化和配置”），然后调用 `start`。SDK 会进行令牌化，并使用该令牌调用 `createPayment`。 |
| `apiClientPayment.getThreeDSecureChallenge(...)`（少见） | *（已移除）* | 移除 | 删除该调用。Headless 过去要求每个集成自行处理 3DS；一旦 `createPayment` resolve，SDK 会在内部编排 3DS。 |
| backend POST 之后的 `yuno.continuePayment()` | *（已移除）* | 移除 | 删除该调用：由 Promise 约定驱动流程推进。resolve `createPayment`，SDK 就会继续。 |

## 相关内容

* [`createPayment`](https://docs.y.uno/zh-hans/docs/yuno-sdk/controllers/create-payment)。切换模式的 callback。
* [`TransactionData`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-pass#transaction-data)。各支付方式的 headless 数据结构。
* [`OneTimeToken`](https://docs.y.uno/zh-hans/docs/yuno-sdk/reference/objects-you-receive#one-time-token)。发送到您 backend 的令牌 payload。


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