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

> 在 Web 上使用 Headless SDK 创建支付，生成一次性令牌并处理 3DS 操作

> [!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 SDK 可让您创建支付。使用 Headless SDK 时，请注意，您需要请求并通过 API 发送支付服务提供商要求的所有必填字段。在其 API 中生成支付需要这些字段。

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

* 使用信用卡信息创建[一次性使用令牌](https://docs.y.uno/zh-hans/docs/basic-concepts/tokens.md)，然后创建支付。
* 使用先前注册的信用卡的 `vaulted_token` 创建[一次性使用令牌](https://docs.y.uno/zh-hans/docs/basic-concepts/tokens.md)，然后创建支付。

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

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

在开始实现 Headless SDK 之前，请参阅 [SDK 集成概述](https://docs.y.uno/zh-hans/docs/sdks/overview/quickstart.md)，了解如何将 SDK 正确集成到您的项目中的详细说明。

集成指南提供了三种灵活的方法：

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

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

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

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

在您的 JavaScript 应用中，提供有效的 `PUBLIC_API_KEY`，创建 `Yuno` 类的实例。

```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 步：启动 checkout 流程

接下来，您将使用 `apiClientPayment` 函数并提供必要的配置参数来启动 checkout 流程。

### 参数

使用以下选项配置支付：

| 参数 | 说明 |
| - | - |
| `country_code` | 此参数指定为其设置支付流程的国家。使用表示所需国家代码的 `ENUM` 值。您可以在[国家覆盖范围](https://docs.y.uno/zh-hans/docs/sdks/resources/country-coverage.md)页面上找到支持的国家及其对应代码的完整列表。 |
| `checkout_session` | 指使用 [Create Checkout Session](https://docs.y.uno/zh-hans/reference/checkout-sessions/create-checkout-session.md) endpoint 为当前支付创建的结账会话。示例：`'438413b7-4921-41e4-b8f3-28a5a0141638'` |

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
const apiClientPayment = await yuno.apiClientPayment({
  country_code: "US",
  checkout_session: "eec6578e-ac2f-40a0-8065-25b5957f6dd3"
});
```

### 预加载欺诈指纹

如果您的账户使用[欺诈筛查](https://docs.y.uno/zh-hans/docs/basic-concepts/fraud)，且所用服务提供商的 fingerprint 脚本加载时间可能超过配置的欺诈超时时间，请在支付表单渲染时调用 `executeFraudCheck`，而不是在客户点击“Pay”时调用。在某些地区，部分服务提供商的 fingerprint 脚本加载时间会超过超时时间。在点击时连续调用 `apiClientPayment` 和 `generateToken`，可能会在 fingerprint 加载完成之前就生成一次性令牌。这意味着令牌将在没有设备指纹的情况下创建。

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
// Wrong: calling everything at "Pay" click time
payButton.onclick = async () => {
  const apiClientPayment = await yuno.apiClientPayment({ country_code, checkout_session });
  const oneTimeToken = await apiClientPayment.generateToken({ checkout_session, payment_method });
};
// The fraud provider's beacon may not have loaded in time, so the fingerprint can be missing from the token
```

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
// Correct: preload the fraud fingerprint when the form renders
await yuno.executeFraudCheck({ checkout_session, country_code });

// Later, when the customer clicks "Pay":
payButton.onclick = async () => {
  const apiClientPayment = await yuno.apiClientPayment({ country_code, checkout_session });
  const oneTimeToken = await apiClientPayment.generateToken({ checkout_session, payment_method });
  // The fingerprint is already cached, no race condition
};
```

## 第 4 步：生成令牌

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

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

要将一笔支付拆分到两张卡上，请在 `payment_method` 中传入一个数组。请参阅[将一笔支付拆分到两张卡上](#split-one-payment-across-two-cards)。

> [!NOTE]
>
> **使用 存储令牌的好处**
>
> 当您在 SDK 中使用 存储令牌时，系统会收集您在卡片路由中配置的服务提供商的所有欺诈信息。这些信息会附加到一次性令牌上。此外，如果服务提供商要求，您还可以添加分期信息和安全码。

```javascript Example 1 theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
const oneTimeToken = await apiClientPayment.generateToken({
  checkout_session: "eec6578e-ac2f-40a0-8065-25b5957f6dd3",
  payment_method: {
    type: "CARD",
    vaulted_token: null,
    card: {
      save: false,
      detail: {
        expiration_month: 11,
        expiration_year: 25,
        number: "4111111111111111",
        security_code: "123",
        holder_name: "ANDREA B",
        type: "CREDIT"
      },
      installment: {
        id: "64ceacef-0886-4c81-9779-b2b3029c4e8b",
        value: 1
      }
    },
    customer: {},
    device_fingerprint: "0753b47f-bb43-86ab-647b-d735b67baac6",
    third_party_session_id: "QbJU2KolVUm1fhQR0s9qgrS0ArEQmEfE"
  }
});
```

### 示例 1 的参数

| 参数 | 说明 |
| - | - |
| `checkout_session` | 使用 Create Checkout Session endpoint 创建的结账会话 |
| `payment_method.type` | 支付方式类型，设置为“CARD” |
| `payment_method.vaulted_token` | 可选：如果您有先前注册的支付方式，请使用此项 |
| `card.save` | 可选：设置为“true”可为该卡生成 存储令牌 |
| `card.detail` | 卡片信息，包括卡号、有效期、安全码和持卡人姓名 |
| `card.detail.type` | 可选：“CREDIT”或“DEBIT”。如果您省略此项，Yuno 会根据卡号检测类型。请仅在确定时发送，因为错误的类型可能导致拒绝 |
| `card.installment` | 可选：仅在配置了分期计划时必填 |
| `customer` | 可选：客户信息对象 |
| `device_fingerprint` | 可选：仅在配置了欺诈筛查时必填 |
| `third_party_session_id` | 可选：仅在存在第三方配置时必填 |

```javascript Example 2 theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
const oneTimeToken = await apiClientPayment.generateToken({
  checkout_session: "eec6578e-ac2f-40a0-8065-25b5957f6dd3",
  payment_method: {
    type: "CARD",
    vaulted_token: "aad8578e-ac2f-40a0-8065-25b5957f6555",
    card: {
      detail: {
        security_code: "123"
      },
      installment: {
        id: "64ceacef-0886-4c81-9779-b2b3029c4e8b",
        value: 1
      }
    }
  }
});
```

### 示例 2 的参数

| 参数 | 说明 |
| - | - |
| `checkout_session` | 使用 Create Checkout Session endpoint 创建的结账会话 |
| `payment_method.type` | 支付方式类型，设置为“CARD” |
| `payment_method.vaulted_token` | 使用先前注册的支付方式的 存储令牌 |
| `card.detail.security_code` | 已注册卡片的安全码 |
| `card.installment` | 可选：仅在配置了分期计划时必填 |

以下代码块展示了上述两个示例中 `apiClientPayment.generateToken` 函数的响应：

```json Example 1 theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
{
  "token": "ee78bc2a-63b4-45bb-bd28-3e6829ab1c3d",
  "vaulted_token": null,
  "vault_on_success": false,
  "type": "CARD",
  "card_data": {
    "holder_name": "ANDREA B",
    "iin": "41111111",
    "lfd": "1111",
    "number_length": 16,
    "security_code_length": 3,
    "brand": "VISA",
    "type": "CREDIT",
    "category": "CREDIT",
    "issuer_name": "JPMORGAN CHASE BANK N A",
    "issuer_code": null
  },
  "customer": {
    "first_name": "Cesar",
    "last_name": "Sanchez",
    "email": "cesar.sanchez@y.uno",
    "gender": "",
    "phone": null,
    "billing_address": null,
    "document": null,
    "browser_info": {
      "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
      "accept_header": "*/*",
      "accept_content": "*/*",
      "accept_browser": "*/*",
      "color_depth": "24",
      "screen_height": "1080",
      "screen_width": "2560",
      "javascript_enabled": true,
      "java_enabled": false,
      "browser_time_difference": "300",
      "language": "en-US"
    },
    "device_fingerprint": "19764508-c9df-a90b-a365-83b2d718c12e"
  },
  "installment": null,
  "country": "CO"
}
```

```json Example 2 theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
{
  token: 'ee78bc2a-63b4-45bb-bd28-3e6829ab1c3d',
  vaulted_token: aad8578e-ac2f-40a0-8065-25b5957f6555,
  vault_on_success: false,
  type: 'CARD',
  card_data: {
    holder_name: 'ANDREA B',
    iin: '41111111',
    lfd: '1111',
    number_length: 16,
    security_code_length: 3,
    brand: 'VISA',
    type: 'CREDIT',
    category: 'CREDIT',
    issuer_name: 'JPMORGAN CHASE BANK N A',
    issuer_code: null,
  },
  customer: {
    first_name: 'Cesar',
    last_name: 'Sanchez',
    email: 'cesar.sanchez@y.uno',
    gender: '',
    phone: null,
    billing_address: null,
    document: null,
    browser_info: {
      user_agent:
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
      accept_header: '*/*',
      accept_content: '*/*',
      accept_browser: '*/*',
      color_depth: '24',
      screen_height: '1080',
      screen_width: '2560',
      javascript_enabled: true,
      java_enabled: false,
      browser_time_difference: '300',
      language: 'en-US',
    },
    device_fingerprint: '19764508-c9df-a90b-a365-83b2d718c12e',
  },
  installment: null,
  country: 'CO',
}
```

## 第 5 步：创建支付

收到一次性令牌后，您可以使用 [Create Payment endpoint](https://docs.y.uno/zh-hans/reference/payments/create-payment.md) 创建支付，以获取最终的支付结果。您需要通过请求的 `payment_method.token` 参数传入在[第 4 步](#step-4-generate-token)中收到的一次性令牌。以下代码块展示了创建支付的请求示例：

```json theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
{
  "merchant_order_id": "0000022",
  "country": "US",
  "account_id": "<Your account_id>",
  "description": "Test",
  "amount": {
    "currency": "USD",
    "value": 500
  },
  "customer_payer": {
    "id": "cfae0941-7234-427a-a739-ef4fce966c79"
  },
  "checkout": {
    "session": "<checkout session>"
  },
  "workflow": "SDK_CHECKOUT",
  "payment_method": {
    "type": "CARD",
    "token": "2cd31999-e44e-4de3-bbe4-179981ff4295"
  }
}
```

endpoint 响应提供 `sdk_action_required` 参数，用于定义是否需要额外操作才能完成支付：

* 如果您的客户选择同步支付方式，支付会立即完成。在这种情况下，API 响应中的 `sdk_action_required` 字段将为 `false`，支付流程在此步骤结束。
* 当需要 SDK 进行额外交互才能完成支付流程时，`sdk_action_required` 将为 `true`。如果是这种情况，您需要按照[第 6 步](#step-6-get-the-3ds-challenge-url)中的说明操作。

## 第 6 步：获取 3DS 挑战 URL

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

* `THREE_D_SECURE `交易类型。
* 状态等于 `PENDING`，子状态等于 `WAITING_ADDITIONAL_STEP`。
* `sdk_action_required` 设置为 `true`。

要获取 3DS 挑战 URL，您应调用 `getThreeDSecureChallenge` 函数，并提供用于创建支付的 `checkoutSession`。

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
const data = await apiClientPayment.getThreeDSecureChallenge(checkoutSession?: string): Promise<{url: string}>
```

如果该卡不需要通过挑战来核实客户身份，`url` 将返回 `null`。

对于拆分到两张卡上的支付，请为每张卡各调用一次此函数。请参阅[运行每张卡的 3DS 挑战](#run-the-3ds-challenge-of-each-card)。

在 Web 浏览器中，您可以在新标签页或 IFrame 中打开该 URL。要在 iframe 中打开该 URL，您必须设置参数 `embedded = true`。否则，您可以省略此参数，其默认值为 `false`。以下代码块展示了在 IFrame 中显示 3DS 挑战内容的示例：

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
document.querySelector('#element').innerHTML = `
   <iframe
     src="${data.url}&embedded=true"
     height="700px"
     width="100%"
     border="0"
     frameBorder="0">
   </iframe>
 `;

window.addEventListener('message', (event) => {
   if (
        !event.origin.toLocaleLowerCase().includes('sdk-3ds') ||
        event?.data?.origin !== 'CHALLENGE'
   ) {
     return
   }
   document.querySelector('#element').innerHTML = '';
   if (event.data.status === 'ERROR') {
     document.querySelector('#element').innerHTML = 'There was an error';
   } else {
     document.querySelector('#element').innerHTML = 'Challenge was finished';
   }
});
```

您负责将客户重定向到 `redirect_url` 提供的 URL 以完成挑战。客户成功完成 3DS 挑战后，将被自动重定向到 `callback_url`。您在使用 [Create Checkout Session](https://docs.y.uno/zh-hans/reference/checkout-sessions/create-checkout-session.md) endpoint 创建 `checkout_session` 时提供了此 `callback_url`。

要完成 Headless SDK 支付流程，您需要使用 [Yuno Webhooks](https://docs.y.uno/zh-hans/docs/webhooks/configure-webhooks.md)。Webhooks 会及时通知您 3DS 挑战的结果和最终支付状态，确保您实时获取支付交易进展的更新。除 webhooks 外，您还可以使用 [Retrieve Payment by ID](https://docs.y.uno/reference/payments/retrieve-payment-by-id) endpoint 获取支付信息。

## 第 7 步：获取支付操作

有时，支付可能需要额外的操作才能继续支付流程。要确定需要什么操作，您应调用 `getContinuePaymentAction` 方法，并提供用于创建支付的 `checkoutSession`。

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
const data = await apiClientPayment.getContinuePaymentAction({ checkoutSession: string }): Promise<ContinuePaymentAction>
```

`getContinuePaymentAction` 方法返回一个 `ContinuePaymentAction` 对象。该对象描述继续支付流程所需的具体操作，具体取决于服务提供商和所需的具体步骤。

### `ContinuePaymentAction` 响应结构

响应包含所需操作的类型以及执行该操作所需的数据：

```typescript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
type ContinuePaymentAction = {
  type: Provider.Type;
  action: Provider.Action;
  payment_code?: {
    code: string;
    reference: string;
    expiration_time?: number;
  };
  image?: {
    type: string;
    value: string;
    reference: string;
    expiration_time?: number;
    additional_data?: Record<string, undefined>;
  };
  redirect?: {
    init_url: string;
    success_url: string;
    error_url: string;
  };
  otp?: {
    length: number;
    expiration_time: number;
    retries: {
      accepts: boolean;
      number: number;
    };
    resend: {
      timer: number;
      number: number;
    };
    payment_instructions: string;
  };
  three_d_secure_redirect?: {
    init_url: string;
    access_token: string;
    redirect_url?: string;
  };
  transaction_id?: string;
  request_html?: {
    body?: Record<string, string>;
    headers?: Record<string, string>;
    method?: "POST" | "GET" | "PUT" | "PATCH" | "DELETE";
    url: string;
  };
  sdk_provider?: {
    client_id?: string;
    intent?: string;
    components?: string;
    gateway: string;
    init_url?: string;
    merchant_id: string;
    amount: {
      currency: string;
      value: number;
    };
    protocol_version?: string;
    provider_id?: string;
    payment_methods?: string[];
    supported_networks?: string[];
    session?: {
      epoch_timestamp: number;
      expires_at: number;
      merchant_session_identifier: string;
      nonce: string;
      merchant_identifier: string;
      domain_name: string;
      display_name: string;
      signature: string;
      operational_analytics_identifier: string;
      retries: number;
      psp_id: string;
    };
    provider_token_id?: string;
  };
  render_html?: {
    content?: string;
    redirect_url?: string;
  };
  info?: {
    screen_info?: string;
  };
  render_iframe: {
    init_url: string;
    access_token: string;
    redirect_url?: string;
  };
};
```

### `ContinuePaymentAction` 字段

| 字段 | 说明 |
| - | - |
| `type` | 支付服务提供商的类型（例如 MERCADO\_PAGO、DLOCAL 等） |
| `action` | 继续支付所需的具体操作（例如 REDIRECT\_URL、OTP 等） |
| `payment_code` | 当支付服务提供商为现金支付签发支付码时使用 |
| `image` | 当必须向用户显示图片（例如二维码）时使用 |
| `redirect` | 当第三方支付流程需要重定向时使用 |
| `otp` | 当流程需要 OTP（一次性密码）验证时使用 |
| `three_d_secure_redirect` | 用于将用户重定向到安全验证步骤的 3DS 流程 |
| `transaction_id` | 唯一交易 ID（如有） |
| `request_html` | 用于渲染包含动态 HTML 和标头的支付表单 |
| `sdk_provider` | 用于基于 SDK 的服务提供商（例如 Apple Pay、Google Pay） |
| `render_html` | 用于直接在应用中显示 HTML 内容 |
| `info` | 一般信息或消息（例如显示确认消息） |
| `render_iframe` | 当服务提供商需要渲染 iframe 以进行用户交互时使用 |

### 服务提供商类型和操作

以下枚举定义了支持的支付服务提供商和可能的操作：

```typescript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
export declare namespace Provider {
  enum Type {
    MERCADO_PAGO = "MERCADO_PAGO",
    WOMPI = "WOMPI",
    PAYMENTEZ = "PAYMENTEZ",
    GETNET = "GETNET",
    TRANSFEERA = "TRANSFEERA",
    CYBERSOURCE_3DS = "CYBERSOURCE_3DS",
    NETCETERA_3DS = "NETCETERA_3DS",
    XENDIT_3DS = "XENDIT_3DS",
    DLOCAL = "DLOCAL",
    CIELO = "CIELO",
    INSWITCH = "INSWITCH",
    PAGALEVE = "PAGALEVE",
    UNLIMINT_3DS = "UNLIMINT_3DS"
  }

  enum Action {
    PAYMENT_CODE = "PAYMENT_CODE",
    IMAGE = "IMAGE",
    REDIRECT_URL = "REDIRECT_URL",
    FORM = "FORM",
    INFO = "INFO",
    OTP = "OTP",
    SDK_PROVIDER = "SDK_PROVIDER",
    THREE_D_SECURE_REDIRECT_URL = "THREE_D_SECURE_REDIRECT_URL",
    REQUEST_HTML = "REQUEST_HTML",
    RENDER_HTML = "RENDER_HTML",
    RENDER_IFRAME = "RENDER_IFRAME"
  }
}
```

### 服务提供商类型和操作参考

| 服务提供商类型 | 说明 |
| - | - |
| `MERCADO_PAGO` | Mercado Pago 支付服务提供商 |
| `WOMPI` | Wompi 支付服务提供商 |
| `PAYMENTEZ` | Paymentez 支付服务提供商 |
| `GETNET` | Getnet 支付服务提供商 |
| `TRANSFEERA` | Transfeera 支付服务提供商 |
| `CYBERSOURCE_3DS` | Cybersource 3DS 服务提供商 |
| `NETCETERA_3DS` | Netcetera 3DS 服务提供商 |
| `XENDIT_3DS` | Xendit 3DS 服务提供商 |
| `DLOCAL` | DLocal 支付服务提供商 |
| `CIELO` | Cielo 支付服务提供商 |
| `INSWITCH` | Inswitch 支付服务提供商 |
| `PAGALEVE` | Pagaleve 支付服务提供商 |
| `UNLIMINT_3DS` | Unlimint 3DS 服务提供商 |

| 操作类型 | 说明 |
| - | - |
| `PAYMENT_CODE` | 向用户显示支付码 |
| `IMAGE` | 显示图片（例如二维码） |
| `REDIRECT_URL` | 将用户重定向到外部页面 |
| `FORM` | 渲染表单以收集用户输入 |
| `INFO` | 显示信息页面 |
| `OTP` | 要求用户输入 OTP |
| `SDK_PROVIDER` | 使用 SDK 处理支付 |
| `THREE_D_SECURE_REDIRECT_URL` | 启动 3DS 认证 |
| `REQUEST_HTML` | 提交 HTML 表单请求 |
| `RENDER_HTML` | 在应用中渲染静态 HTML |
| `RENDER_IFRAME` | 为服务提供商 UI 渲染 iframe |

### 处理不同的操作类型

根据响应中的 `action` 字段，您应相应地处理每种类型的操作：

#### `REDIRECT_URL` 操作

当操作为 `REDIRECT_URL` 时，您应将用户重定向到 `data.redirect.init_url` 中提供的 URL：

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
if (data.action === "REDIRECT_URL") {
  window.location.href = data.redirect.init_url;
}
```

#### 其他操作类型

每种操作类型都需要根据所提供的数据进行特定处理：

* **PAYMENT\_CODE**：向用户显示支付码和参考号
* **IMAGE**：向用户显示二维码或其他图片
* **OTP**：向用户展示 OTP 输入表单
* **SDK\_PROVIDER**：初始化特定服务提供商的 SDK
* **RENDER\_IFRAME**：显示包含服务提供商界面的 iframe

> [!NOTE]
>
> **支付操作处理**
>
> 处理每种操作类型的具体实现取决于您应用的 UI framework 和需求。请确保处理您配置的支付服务提供商可能返回的所有操作类型。

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

## 将一笔支付拆分到两张卡上

从 Web SDK 1.11.43 开始，`generateToken` 可以为由两张卡共同出资的支付创建一个令牌。每张卡支付金额中属于自己的部分。该流程仅支持 headless：没有对应的 checkout UI。有关启用、状态、冲正、操作和错误，请参阅[使用两张卡支付](https://docs.y.uno/zh-hans/docs/payment-features/pay-with-two-cards.md)。

> [!NOTE]
>
> **版本**
>
> 您需要 Web SDK 1.11.43 或更高版本。如果您从 `https://sdk-web.y.uno/v1.11/main.js` 加载 SDK，则已经包含该版本。如果您从 npm 安装，请运行 `npm install @yuno-payments/sdk-web@^9`：9.x 包会从 CDN 加载 `v1.11` 版本线，该 CDN 提供 1.11.43 或更高版本。该包的 10.x 版本会加载 Web SDK v2。

### 为两张卡生成一个令牌

将 `payment_method` 作为一个恰好包含两个项目（每张卡一个）的数组传入，而不是单个对象。每个项目接受与单个支付方式相同的字段（`type`、`card` 或 `vaulted_token`、`customer`、`device_fingerprints`、`third_party_data`），外加该卡支付的 `amount`。请在 `payment_method` 旁边发送 `total`：否则支付稍后会被拒绝。

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
const compositeToken = await apiClientPayment.generateToken({
  checkout_session: "eec6578e-ac2f-40a0-8065-25b5957f6dd3",
  total: { currency: "USD", value: 100 },
  payment_method: [
    {
      type: "CARD",
      amount: { currency: "USD", value: 60 },
      card: {
        detail: {
          expiration_month: 11,
          expiration_year: 29,
          number: "4111111111111111",
          security_code: "123",
          holder_name: "ANDREA B",
          type: "CREDIT"
        }
      }
    },
    {
      type: "CARD",
      amount: { currency: "USD", value: 40 },
      vaulted_token: "aad8578e-ac2f-40a0-8065-25b5957f6555",
      card: {
        detail: {
          security_code: "123"
        }
      }
    }
  ]
});
```

| 参数 | 说明 |
| - | - |
| `payment_method` | 恰好包含两个项目的数组，每张卡一个。项目的顺序即各卡进行 3DS 的顺序。 |
| `payment_method[].type` | 支付方式类型，设置为“CARD”。 |
| `payment_method[].card` | 卡片信息，与示例 1 相同。每个项目都需要 `card` 或 `vaulted_token`。 |
| `payment_method[].vaulted_token` | 使用先前注册的卡片的 存储令牌，与示例 2 相同。 |
| `payment_method[].amount.currency` | 该卡所支付部分的币种。不能为空。 |
| `payment_method[].amount.value` | 该卡支付的金额，为大于零的数字。 |
| `total` | 创建支付时必填。每个项目都必须使用 `total.currency`，且各项目金额之和必须等于 `total.value`。Yuno 还会将其与结账会话金额进行核对。 |

SDK 会为每个项目收集欺诈数据和浏览器信息，与单张卡时相同。当您传入数组时，该函数会解析为单个复合令牌：

```json theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
{
  "token": "ee78bc2a-63b4-45bb-bd28-3e6829ab1c3d",
  "checkout_session": "eec6578e-ac2f-40a0-8065-25b5957f6dd3",
  "expires_at": "2026-10-22T15:30:00Z"
}
```

当您传入对象时，`generateToken` 的行为与之前相同，并返回[第 4 步](#step-4-generate-token)中所示的响应。现有集成不会发生变化。

SDK 会在发送任何请求之前检查数组，并抛出指明出错项目的错误。请将调用包裹在 `try/catch` 中。

| 输入 | 错误消息 |
| - | - |
| 少于两个项目 | `payment_method must have at least two items; use an object for one payment method` |
| 某个项目缺少 `card` 或 `vaulted_token` | `payment_method[1] needs card or vaulted_token` |
| `amount.value` 缺失、为零或为负数 | `payment_method[0].amount.value=0 is not valid` |
| `amount.currency` 为空 | `payment_method[0].amount.currency= is not valid` |
| 未知的 `type` | `payment_method[0].type=CARDS is not valid` |
| 项目币种与 `total.currency` 不同 | `payment_method[1].amount.currency=EUR does not match total.currency=USD` |
| 各项目金额之和不等于 `total.value` | `payment_method amounts add up to 60 + 30 but total.value=100` |

### 创建支付

从您的服务器使用 `POST /v2/payments` 创建支付（生产环境为 `https://api.y.uno/v2/payments`，sandbox 为 `https://api-sandbox.y.uno/v2/payments`）。使用与其他支付 endpoint 相同的身份验证标头。[第 5 步](#step-5-create-the-payment)中的 v1 [Create Payment endpoint](https://docs.y.uno/zh-hans/reference/payments/create-payment.md) 用于单一支付方式的令牌；复合令牌则发送到 `POST /v2/payments`。

```json theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
{
  "merchant_order_id": "0000023",
  "country": "US",
  "account_id": "<Your account_id>",
  "description": "Order paid with two cards",
  "amount": {
    "currency": "USD",
    "value": 100
  },
  "customer_payer": {
    "first_name": "Andrea",
    "last_name": "B",
    "email": "andrea.b@example.com"
  },
  "checkout": {
    "session": "eec6578e-ac2f-40a0-8065-25b5957f6dd3"
  },
  "workflow": "SDK_CHECKOUT",
  "payment_method": {
    "token": "ee78bc2a-63b4-45bb-bd28-3e6829ab1c3d",
    "capture": true
  },
  "callback_url": "https://merchant.example.com/checkout/return"
}
```

| 字段 | 说明 |
| - | - |
| `amount.value` | 支付总额：各卡金额之和。 |
| `amount.currency` | 与各卡金额相同的币种。 |
| `checkout.session` | 您为其创建复合令牌的结账会话。 |
| `workflow` | 设置为 `SDK_CHECKOUT`。 |
| `payment_method.token` | 复合令牌。无需 `payment_method.type`：令牌已标识了这些卡。 |
| `payment_method.capture` | 是否捕获该支付。 |
| `callback_url` | 可选。每张卡的 3DS 挑战完成后将客户返回到的地址。当某张卡可能需要 3DS 时发送。 |

要读取每张卡的结果，请从您的服务器使用相同的身份验证标头调用 `GET /v2/payments/{payment_id}`。其 `payment_method.payment_methods` 数组中每张卡对应一个条目，每个条目包含其 `sequence`（该卡在令牌中的位置）、`type`、`amount` 和 `transactions`。卡片没有自己的状态：请从每张卡的交易中读取其结果，其中该卡的 `THREE_D_SECURE` 交易携带其挑战的结果。支付级别的 `status` 和 `sub_status` 汇总了两张卡的情况。v1 Retrieve Payment endpoint 将支付作为一个整体显示，而不是按卡显示。有关完整响应、状态和操作，请参阅[使用两张卡支付](https://docs.y.uno/zh-hans/docs/payment-features/pay-with-two-cards.md)，以及 [Retrieve Payment (two cards)](https://docs.y.uno/reference/payments/retrieve-payment-two-cards.md) 参考。

### 运行每张卡的 3DS 挑战

当卡片需要 3DS 时，请按照 `payment_method` 数组的顺序，为每张卡各调用一次 `getThreeDSecureChallenge`。按照[第 6 步](#step-6-get-the-3ds-challenge-url)中的说明渲染它返回的每个 URL，并在该挑战完成后再进行下一次调用。每次调用都会按数组顺序返回第一张仍在等待 3DS 的卡的挑战。不需要挑战的卡会被跳过，因此下一次调用会直接返回下一张需要挑战的卡。当没有卡再等待 3DS 时，调用会以 `url: null` 解析：这是停止的信号，绝不表示某张卡获得了豁免。Yuno 会在客户完成挑战几秒钟后记录挑战结果，因此请等到该卡的 `THREE_D_SECURE` 交易离开 `PENDING`（通过您的 webhook 或 `GET /v2/payments/{payment_id}` 确认）后，再为下一张卡调用 `getThreeDSecureChallenge`；在此之前进行的调用可能会再次返回同一张卡的挑战。

```javascript theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
// showChallenge renders the URL in an iframe, as in Step 6,
// and resolves with event.data.status when the CHALLENGE message arrives.
// waitForCardResult asks your server to poll GET /v2/payments/{payment_id}
// until the THREE_D_SECURE transaction of that card is no longer PENDING.
async function runCardChallenges(checkoutSession, paymentId, cardCount) {
  for (let sequence = 1; sequence <= cardCount; sequence++) {
    const { url } = await apiClientPayment.getThreeDSecureChallenge(checkoutSession);

    if (!url) {
      return; // No card is waiting for 3DS
    }

    const status = await showChallenge(url);

    if (status === 'ERROR') {
      return; // The payment has ended: do not offer the other card
    }

    await waitForCardResult(paymentId, sequence);
  }
}
```

使用一张卡支付的支付行为与之前相同：一次调用，一次挑战。

### Yuno 如何处理两张卡

* 需要 3DS 的卡会在其自身的挑战完成后立即扣款。不需要 3DS 的卡会在创建支付时扣款。
* 如果某张卡的挑战失败或其发卡机构拒绝该卡，整个支付将终止。Yuno 会冲正已扣款的卡的款项，并取消另一张卡待处理的 3DS。不要要求您的客户使用剩余的卡继续：请改为发起新的支付。
* 最终支付在 `payment_method.payment_methods` 中每张卡对应一个条目，每个条目包含其 `sequence`、`type`、`amount` 和 `transactions`。没有按卡的状态：请从每张卡的交易中读取其结果。可通过您的 [webhooks](https://docs.y.uno/zh-hans/docs/webhooks/configure-webhooks.md) 或 `GET /v2/payments/{payment_id}` 读取。

## 错误处理

在您的应用中处理 SDK 返回的错误，例如支付失败或验证错误。有关 HTTP 状态码和响应代码，请参阅 API 参考中的[状态和响应代码](https://docs.y.uno/reference/getting-started/response-codes.md)。要对支付进行退款，请参阅[退款支付](https://docs.y.uno/zh-hans/docs/direct-integration-use-cases/refund-payments.md)和 [Refund payment](https://docs.y.uno/reference/payments/refund-payment.md) API。

## 保持更新

请访问[更新日志](https://docs.y.uno/changelog/web.md#v1-6-0)，了解最新的 SDK 更新和版本历史。


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