> ## 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.

# Lite SDK（Web 支付）

> 在 Web 上集成 Lite SDK，用于展示支付方式并完全掌控 checkout

> [!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 Lite Web SDK 的支付功能。

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

第 1 步和第 2 步在新版 SDK 中的对应内容：[安装](https://docs.y.uno/zh-hans/docs/yuno-sdk/get-started.md#install)。

集成指南提供了[三种灵活的方式](https://docs.y.uno/zh-hans/docs/sdks/overview/quickstart.md)：

1. 直接通过 HTML script 引入
2. 通过 JavaScript 动态注入
3. 安装 NPM 模块

选择最适合您的开发工作流程和技术要求的集成方式。完成 SDK 集成后，您可以继续执行以下步骤来实现 Lite 功能。

> [!NOTE]
>
> **TypeScript 库**
>
> 如果您使用 TypeScript，Yuno 提供了一个[库](https://www.npmjs.com/package/@yuno-payments/sdk-web-types)，可用于访问 Yuno Web SDK 中的所有可用方法。

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

在您的 JavaScript 应用中提供有效的 `PUBLIC_API_KEY`，以初始化 Yuno SDK：

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
const yuno = await Yuno.initialize(PUBLIC_API_KEY);
```

> [!NOTE]
>
> **凭证**
>
> 如需了解更多信息，请参阅凭证页面：[/reference/getting-started/authentication](https://docs.y.uno/reference/getting-started/authentication.md)

## 第 3 步：创建结账会话

新版 SDK 中的对应内容：[创建结账会话](https://docs.y.uno/zh-hans/docs/yuno-sdk/get-started.md#create-the-checkout-session-backend)。

要初始化支付流程，请使用 [Create checkout session](https://docs.y.uno/zh-hans/reference/checkout-sessions/create-checkout-session.md) endpoint 创建新的 `checkout_session`。

* 首先，[创建客户](https://docs.y.uno/reference/customers/create-customer.md)或获取现有的客户 ID
* 在创建 `checkout_session` 时包含该 ID

> [!NOTE]
>
> **控制授权和捕获**
>
> 要控制卡支付的授权和捕获，请在您的 backend 从 `createPayment` 发送的 [Create Payment](https://docs.y.uno/zh-hans/reference/payments/create-payment.md) 请求中传入 `payment_method.detail.card.capture`：设置为 `false` 表示仅授权，设置为 `true` 表示立即捕获。Yuno 从支付请求中读取此字段。请参阅[取消和捕获流程](https://docs.y.uno/zh-hans/docs/payment-features/Cancel-and-capture-flow.md)。

### 关键参数

| 参数 | 必填 | 说明 |
| - | - | - |
| `amount` | 是 | 主要交易金额对象，包含 `currency`（ISO 4217 代码）和 `value`（以该币种表示的数值金额）。 |
| `alternative_amount` | 否 | 交易金额的另一种币种表示，结构与 `amount` 相同（`currency` 和 `value`）。适用于多币种场景。例如，您可以用客户偏好的币种（例如 USD）向其展示价格，同时以本地币种（例如 COP）处理支付。 |

> [!NOTE]
>
> **`onPaymentMethodSelect` 事件**
>
> 对于所有 APM（包括 Google Pay、Apple Pay 和 PayPal），只要客户选择了支付方式（在支付流程开始之前），就会触发 `onPaymentMethodSelected`。请在 `await yuno.mountCheckoutLite()` 之前，在 `await yuno.startCheckout()` 中定义 `onPaymentMethodSelected`。

## 第 4 步：启动 checkout 流程

第 4 步到第 6 步在新版 SDK 中的对应内容：[Lite 模式迁移](https://docs.y.uno/zh-hans/docs/yuno-sdk/migration/web/lite.md)。

使用以下配置，为您的客户提供轻量且易用的支付体验：

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
await yuno.startCheckout({
  checkoutSession: "438413b7-4921-41e4-b8f3-28a5a0141638",
  elementSelector: "#root",
  countryCode: "US",
  language: "en-US",
  showLoading: true,
  issuersFormEnable: true,
  showPaymentStatus: true,
  onLoading: (args) => console.log(args),
  renderMode: {
    type: "modal",
    elementSelector: {
      apmForm: "#form-element",
      actionForm: "#action-form-element",
    },
  },
  card: {
    type: "extends",
    styles: "",
    cardSaveEnable: false,
    texts: {},
  },
  texts: {},
  async createPayment(oneTimeToken, tokenWithInformation) {
    // Read ACH bank name if needed: const bankName = tokenWithInformation.bank_transfer?.bank_name;
    await createPayment({ 
      oneTimeToken, 
      checkoutSession,
      vault_on_success: true 
    });
    await yuno.continuePayment({ showPaymentStatus: true });
  },
  onPaymentMethodSelected(data) {
    console.log("Payment method selected:", data);
  },
  async paymentResult(data) {
    console.log("Payment result:", data);
    await yuno.hideLoader();
  },
  async error(error, data) {
    console.error("An error occurred:", error);
    await yuno.hideLoader();
  },
});
```

使用 `startCheckout` 时，请指定用于处理支付的 callback。您还可以使用 `texts` 对象自定义 checkout 界面。

### 参数

使用以下选项配置 Lite checkout：

| 参数 | 说明 |
| - | - |
| `checkoutSession` | 指当前支付的[结账会话](https://docs.y.uno/zh-hans/reference/checkout-sessions/create-checkout-session.md)。示例：`438413b7-4921-41e4-b8f3-28a5a0141638`。 |
| `elementSelector` | 用于渲染 checkout 的 HTML 元素。 |
| `countryCode` | 此参数指定要为其设置支付流程的国家/地区。请使用代表所需国家/地区代码的 `ENUM` 值。您可以在[国家/地区覆盖范围](https://docs.y.uno/zh-hans/docs/sdks/resources/country-coverage.md)页面上找到支持的国家/地区及其对应代码的完整列表。 |
| `language` | 支付表单的语言。可使用[支持的语言](https://docs.y.uno/zh-hans/docs/sdks/resources/languages-supported.md)中列出的任意代码。示例：`en-US`。如果可用，默认使用浏览器语言。 |
| `showLoading` | 控制支付过程中 Yuno 加载/加载动画页面的可见性。默认值：`true`。 |
| `onLoading` | 用于接收支付过程中服务器调用或加载事件的通知，必须提供。 |
| `issuersFormEnable` | 启用发卡机构表单（例如银行列表）。默认值：`true`。 |
| `showPaymentStatus` | 显示 Yuno 支付状态页面，在继续支付时非常有用。默认值：`true`。 |
| `showPayButton` | 控制客户表单或卡片表单中支付按钮的可见性。默认值：`true`。 |
| `renderMode` | 指定表单的渲染方式和位置。可用选项如下： |
| | ▪️ `type: modal`（默认） |
| | ▪️ `type: element`：如果您选择 `element`，则必须提供 `elementSelector` 以指定表单的渲染位置。 |
| `card` | 定义卡片表单的配置。包含自定义样式和保存卡片选项等设置。 |
| `texts` | 允许您为卡片和非卡片支付表单设置自定义按钮文本。 |
| `createPayment(oneTimeToken, tokenWithInformation)` | 用于创建支付的 callback 函数。接收 `oneTimeToken` 和 `tokenWithInformation`（与 [SDK checkout 令牌结构](https://docs.y.uno/reference/checkout-sessions/create-one-time-use-token-sdk-checkout)一致，例如 ACH 对应的 `tokenWithInformation.bank_transfer?.bank_name`）。将一次性令牌发送到您的 backend，通过 API 创建支付；然后调用 `await yuno.continuePayment()` 以恢复流程。对于返回 `DECLINED` 或 `ERROR` 的卡支付，也请调用 `continuePayment` 以执行支付重试；否则调用 `unmountSdk` 进行清理。请参阅[支付重试](https://docs.y.uno/zh-hans/docs/sdks/resources/references/web.md#payment-retry)。 |
| `onPaymentMethodSelected` | 选择支付方式时调用的 callback，同时提供该方式的类型和名称。 |
| `paymentResult` | 支付完成后调用的 callback。它会接收[支付状态](https://docs.y.uno/reference/payments/status-and-response-codes/payment.md)（例如 `SUCCEEDED`、`DECLINED`、`PENDING`、`ERROR`）以及一个可选的、用于限定该状态的 `subStatus`。请参阅[购物者取消的步骤](https://docs.y.uno/zh-hans/docs/sdks/resources/references/web.md#shopper-cancelled-steps)。 |
| `error` | 支付过程中出现错误时调用的 callback。接收错误类型和可选的附加数据。 |
| `onChange` | 报告支付表单的状态。接收 `{ form: { isValid, paymentMethodType, values, amount, taxQuoteStatus } }`。与 `showPayButton: false` 搭配使用，以控制您自己的支付按钮。`isValid` 自 v1.10.11 起可用。对于带有 `tax_collection` 的结账会话（v1.11.56 及更高版本）：`values.billingAddress` 包含账单字段，`values.taxInformation` 包含企业数据，`amount` 是上一次 `onBillingAddressChanged` 应答中的含税价格，`taxQuoteStatus` 为 `pending`、`ready` 或 `error`。除非其值为 `ready`，否则请保持您的支付按钮处于禁用状态。 |
| `onBillingAddressChanged` | 当结账会话带有 `tax_collection` 时必须提供（v1.11.56 及更高版本）。每当所选支付方式的账单国家/地区、邮政编码或企业数据发生变化时，SDK 都会调用它，并最多等待 10 秒以获取含税价格。请参阅[含税的 checkout](#checkouts-with-taxes)。 |

### 含税的 checkout

当结账会话带有 `tax_collection`（[本地价格和税费](https://docs.y.uno/zh-hans/docs/payment-features/subscriptions/local-price-and-taxes.md)）时，表单会要求填写账单国家/地区、美国和加拿大的邮政编码，以及一个可选的企业信息区块（企业名称、税号类型和税号）。每当其中一项发生变化时，SDK 都会调用 `onBillingAddressChanged`。请通过 [Create tax quote](https://docs.y.uno/reference/taxes/create-tax-quote.md) 从您的 backend 获取税费报价，并返回总额。如果没有 `onBillingAddressChanged`，SDK 不会挂载，并会以代码 `TAX_COLLECTION_CALLBACK_REQUIRED` 调用 `error`。

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
yuno.startCheckout({
  checkoutSession: '<checkout_session>',
  // ...
  onBillingAddressChanged: async ({ paymentMethodType, billingAddress, taxInformation }) => {
    // billingAddress: { country: 'US', zip_code: '10001' }
    // taxInformation: { business: true, name: 'ACME Inc', type: 'us_ein', id: '12-3456789' } or undefined
    const quote = await fetch('/my-backend/tax-quote', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ billingAddress, taxInformation }),
    }).then((response) => response.json())

    if (quote.code) {
      // Your backend maps the tax quote error to the field the buyer has to fix
      const fields = { TAX_LOCATION_INVALID: 'zip_code', TAX_ID_INVALID: 'tax_id' }
      const error = new Error(quote.messages?.[0] ?? 'Tax quote failed')
      error.code = quote.code
      error.field = fields[quote.code] // country, zip_code, business_name, tax_id_type or tax_id
      error.messageId = 'invalid' // invalid, unsupported or country_mismatch
      throw error
    }
    return { amount: { currency: quote.currency, value: quote.total } }
  },
})
```

* 返回一个 resolve 为 `{ amount: { currency, value } }` 的 promise，其值为零或更大。SDK 会将其显示为总额，并在收到之前保持支付按钮处于禁用状态：在此期间，按钮显示“Adding tax…”。
* 如果 promise 被 reject 或耗时超过 10 秒，按钮会显示“Try again to continue”并提供重试选项，同时以代码 `TAX_QUOTE_FAILED` 调用 `error`。带有 `field` 和 `messageId` 的 reject 会在该字段上标记对应的消息。
* 保留最后一次报价的 `tax_quote_id`：您在 `createPayment` 中创建的支付会在其税费行（`source: YUNO_TAX_QUOTE`）中携带它，并按报价总额扣款。
* 使用 `tax_collection` 时，Apple Pay 是唯一的快捷按钮。Google Pay、PayPal、Revolut Pay 和 Samsung Pay 会以列表行的形式显示，并带有各自的账单区块，在账单信息有效且价格已返回之前，它们的按钮保持禁用状态。

> [!NOTE]
>
> **促销**
>
> 当您的组织启用了[促销](https://docs.y.uno/zh-hans/docs/payment-features/promotions)时，Lite checkout 会在购物者输入卡片信息时请求促销报价，`createPayment` 会在 `tokenWithInformation.quote` 中收到该报价。此版本不支持钱包：`mountExternalButtons` 不会请求报价。请参阅[促销](https://docs.y.uno/zh-hans/docs/sdks/resources/references/web.md#promotions)。

> [!NOTE]
>
> **客户发起和商户发起的交易**
>
> 支付可以由客户发起（CIT），也可以由商户发起（MIT）。您可以在[存储凭证](https://docs.y.uno/zh-hans/docs/payment-features/stored-credentials.md)中找到有关其特点的更多信息。

## 第 5 步：挂载 SDK

要根据所选支付方式展示 checkout 流程，请使用 `await yuno.mountCheckoutLite()` 函数。此步骤可确保 SDK 正确挂载到您选择的 HTML 元素上。

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
await yuno.mountCheckoutLite({
  paymentMethodType: PAYMENT_METHOD_TYPE,
  vaultedToken: VAULTED_TOKEN,
});
```

请参阅[支付类型](https://docs.y.uno/reference/payment-type-list.md)页面，查看挂载 SDK 时可使用的支付方式类型的完整列表。

`vaultedToken` 是可选的。它表示之前已注册的支付方式。如果您提供 `vaultedToken`，用户将无需再次提供支付信息，因为这些信息已在之前的交易中提供过。

挂载后，您必须调用 `yuno.startPayment()` 来启动 checkout 流程。如果跳过此调用，支付表单将不会打开。请注意，`yuno.startPayment()` 也会返回一个 promise，应对其使用 await。

## 第 6 步：启动支付流程（必需）

在 `await yuno.mountCheckoutLite()` 之后立即调用 `await yuno.startPayment()`，以打开所选支付方式的界面：

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
await yuno.mountCheckoutLite({
  paymentMethodType: PAYMENT_METHOD_TYPE,
  vaultedToken: VAULTED_TOKEN,
});

await yuno.startPayment();
```

或者，您也可以通过用户操作（例如点击按钮）来触发启动：

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
const payButton = document.querySelector('#button-pay');
payButton.addEventListener('click', async () => {
  await yuno.startPayment();
});
```

> [!NOTE]
>
> **演示应用**
>
> 除了提供的代码示例外，您还可以访问[演示应用](https://github.com/yuno-payments/yuno-sdk-web)，查看 Yuno SDK 的完整实现（从代码仓库克隆）。

## 在列出支付方式之前检查其能否渲染

如果您自行绘制支付方式列表，请在展示之前询问 SDK 对于此购物者和结账会话，哪些方式实际能够渲染。在 `startCheckout` 之后调用 `isPaymentMethodAvailable`，并隐藏每个 resolve 为 `false` 的方式。否则，购物者可能会选择一个未在该会话中启用的方式，或设备无法使用的钱包，并在本应显示表单或按钮的位置看到一个空白框。

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
await yuno.startCheckout({ checkoutSession, elementSelector: '#root', countryCode: 'US' });

const methods = ['CARD', 'GOOGLE_PAY', 'APPLE_PAY', 'PAYPAL'];
const answers = await Promise.all(
  methods.map((paymentMethodType) => yuno.isPaymentMethodAvailable({ paymentMethodType }))
);
const availableMethods = methods.filter((_, index) => answers[index]);

renderMyPaymentList(availableMethods);
```

其结果与 SDK 渲染该方式时所做的判断相同，且该方法永远不会 reject。有关每种方式所检查的内容，请参阅 [`isPaymentMethodAvailable`](https://docs.y.uno/zh-hans/docs/sdks/resources/references/web#ispaymentmethodavailable)。

## 挂载外部按钮

您可以使用 `mountExternalButtons` 方法，在界面中的自定义位置渲染 Google Pay 和 Apple Pay 按钮。这让您可以控制这些按钮的显示位置。请在 `startCheckout` 之后调用它。

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
await yuno.startCheckout({ checkoutSession, elementSelector: '#root', countryCode: 'US' });

await yuno.mountExternalButtons([
  {
    paymentMethodType: 'APPLE_PAY',
    elementSelector: '#apple-pay',
  },
  {
    paymentMethodType: 'GOOGLE_PAY',
    elementSelector: '#google-pay',
  },
]);
```

> [!NOTE]
>
> 只有当支付方式已在结账会话中启用，并通过 SDK 的设备和浏览器检查（例如针对会话配置的 Google Pay `isReadyToPay()`）时，钱包按钮才会渲染。因此，同一段代码可能会在某个设备或浏览器上显示钱包按钮，而在另一个上不显示。在 Web SDK 1.11.43 及更高版本或 1.10.35 及更高版本中，请在挂载每个钱包之前为其调用 [`isPaymentMethodAvailable`](https://docs.y.uno/zh-hans/docs/sdks/resources/references/web#ispaymentmethodavailable)，并仅显示 resolve 为 `true` 的钱包的容器。

### 外部按钮参数

| 参数 | 说明 |
| :- | :- |
| `paymentMethodType` | 支付方式类型。必须为 `'APPLE_PAY'` 或 `'GOOGLE_PAY'`。 |
| `elementSelector` | 用于渲染按钮的 HTML 元素的 CSS 选择器（例如 `'#apple-pay'`、`'.button'`）。 |

### 卸载按钮

您可以按支付方式类型卸载单个外部按钮：

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
await yuno.unmountExternalButton('APPLE_PAY');
```

或者一次性卸载所有外部按钮：

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
await yuno.unmountAllExternalButtons();
```

### 卸载 SDK

如需显式清理 Yuno SDK（例如用户取消流程或您需要从 DOM 中移除 SDK 时），请使用 `unmountSdk()` 方法：

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
await yuno.unmountSdk();
```

## PayPal REDIRECT 工作流程

Yuno SDK 支持 PayPal 的 `REDIRECT` 工作流程。当 PayPal 未在 SDK 启动时初始化，或使用已有的 PayPal `orderId` 时，此工作流程非常有用。

* **PaypalButtonModal**：如果 PayPal 尚未初始化，SDK 可以在模态框中渲染 PayPal 按钮。
* **工作流程**：`REDIRECT` 工作流程会跳过欺诈检测和 OTT 创建，直接使用提供的 `orderId`。

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
// Example PayPal configuration
await yuno.startCheckout({
  // ... other config
  paypal: {
    workflow: 'REDIRECT',
    orderId: 'PAYPAL_ORDER_ID',
  }
});
```

## 在 Lite 流程中注册支付方式

新版 SDK 中的对应内容：[注册](https://docs.y.uno/zh-hans/docs/yuno-sdk/features/enrollment.md)。

您可以在 Lite 支付流程中直接注册支付方式（存储卡片以供将来使用），方法是在您的 backend 从 `createPayment` 发送的 [Create Payment](https://docs.y.uno/zh-hans/reference/payments/create-payment.md) 请求中设置 `payment_method.vault_on_success = true`，该字段嵌套在 `payment_method` 下，如下所示。在 Lite 流程中由您的服务器创建支付，因此该标志应放在这里；在结账会话上设置它属于 Seamless 模式的做法，在该模式中由 SDK 创建支付。

当 `vault_on_success` 设置为 `true` 时：

* 如果支付状态为 `SUCCEEDED`，支付方式将自动注册
* 如果支付未成功，则不会进行存储
* 支付响应将包含一个 `vaulted_token`，可用于将来的交易

**示例**（部分摘录，仅显示相关字段）：

```json theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
{
    "account_id": "...",
    ...
    "payment_method": {
        "vault_on_success": true
    }
}
```

> [!NOTE]
>
> **存储要求**
>
> 要在 `vault_on_success = true` 时生成并接收 `vaulted_token`，支付必须通过结账会话中的 `customer_payer.id` 引用一个已有的 Yuno 客户。在支付请求中内联创建或发送客户数据，并不会在 Yuno 系统中创建该客户，因此不会进行存储。

有关注册支付方式的更多信息，请参阅[注册支付方式](https://docs.y.uno/zh-hans/docs/payment-features/enrollment/enroll-payment-methods.md)。

## 错误处理

新版 SDK 中的对应内容：[onStatus](https://docs.y.uno/zh-hans/docs/yuno-sdk/controllers/on-status.md) 控制器。

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

## 保持更新

访问 [changelog](https://docs.y.uno/changelog/web.md)，了解最新的 SDK 更新和版本历史。


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