> ## 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（Android 注册）

> 在 Android 上使用 Headless SDK 注册支付方式，为卡片数据生成存储令牌

> [!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.

本页介绍用于 Android 注册的 Yuno Headless SDK。

Yuno Headless SDK for Android 提供灵活且无 UI 的解决方案，用于注册支付方式和对卡片进行令牌化。

此 SDK 让您完全控制支付方式注册流程，非常适合以下商户：

* 需要完全控制 UI 和用户体验
* 希望实现自定义注册流程
* 需要高级集成能力

Headless SDK 包含以下核心功能：

* 卡片令牌化
* 安全的支付方式注册
* 直接访问 API
* 自定义错误处理

如果商户需要预构建的 UI 解决方案或更简单的集成，可以考虑使用 Yuno 的其他 SDK 实现：

* [Full Checkout SDK](https://docs.y.uno/docs/sdks/full-checkout/android-payments)
* [Lite SDK](https://docs.y.uno/zh-hans/docs/sdks/lite-android/enrollment.md)

## 要求

开始集成 Yuno Android SDK 之前，请确保您的项目满足以下技术要求：

* **最低 SDK 版本**：`minSdkVersion` 23 或更高（Android 6.0）。自 Yuno Android SDK 2.24.0 起必需
* **Java**：已启用 Java 8
* **AndroidX**：使用 AndroidX 而非旧版支持库
* **Android Gradle Plugin**：4.0.0 或更高
* **ProGuard**：6.2.2 或更高
* **Kotlin Gradle Plugin**：1.4.0 或更高
* **ELF 页面大小支持**：符合 Google 的 16 KB ELF 页面对齐要求（适配 Android 15 / ARMv9）

### ProGuard / R8 配置

如果您的项目设置了 `minifyEnabled = true`，请将以下规则添加到您的 `proguard-rules.pro` 文件中，以确保 SDK 正常运行，尤其是在 **AGP 8.x+ R8 完整模式**下。

> [accordion] Yuno 官方 ProGuard / R8 规则
>
> ```proguard theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
> # Preserve generic type signatures and annotations
> -keepattributes Signature
> -keepattributes *Annotation*
>
> # Yuno SDK
> -keep class com.yuno.** { *; }
> -dontwarn com.yuno.**
>
> # Gson — R8 full mode compatibility
> -keep class com.google.gson.** { *; }
> -keep,allowobfuscation,allowshrinking,allowoptimization class * extends com.google.gson.reflect.TypeToken
> -dontwarn com.google.gson.**
>
> # Retrofit — R8 full mode compatibility
> -keep,allowobfuscation,allowshrinking interface retrofit2.Call
> -keep,allowobfuscation,allowshrinking class retrofit2.Response
> -keep,allowobfuscation,allowshrinking class kotlin.coroutines.Continuation
> -dontwarn retrofit2.**
>
> # OkHttp + Okio — Suppress warnings
> -dontwarn okhttp3.**
> -dontwarn okio.**
> ```
>
> ### 为什么需要这些规则？
>
> AGP 8.x+ 默认启用 **R8 完整模式**，该模式会大幅剥离泛型类型签名。如果没有 `-keepattributes Signature`，Gson 的 `TypeToken<T>` 可能会在运行时失败，并出现 `java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType`。

> [!NOTE]
>
> **SDK 版本信息**
>
> 查看发布说明或访问 [Yuno Android SDK 代码库](https://github.com/yuno-payments/yuno-sdk-android)，以确认当前的 SDK 版本。

## 步骤 1：创建客户

在注册支付方式之前，使用[创建客户](https://docs.y.uno/reference/customers/create-customer.md) endpoint 创建客户。

## 步骤 2：创建客户会话

使用[创建客户会话](https://docs.y.uno/reference/customer-sessions-enrollment/create-customer-session.md) endpoint 创建新的 `customer_session`：

* 在请求中包含客户 ID
* 保存返回的 `customer_session` ID
* 每次注册支付方式时生成新的 `customer_session`。

## 步骤 3：将 SDK 添加到项目

1. 添加代码库来源：

```kotlin theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
maven { url "https://yunopayments.jfrog.io/artifactory/snapshots-libs-release" }
```

2. 添加 SDK 依赖项：

```kotlin theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
dependencies {
    implementation 'com.yuno.payments:android-sdk:2.27.0'
}
```

> [!NOTE]
>
> **需要网络权限**
>
> Yuno SDK 会自动包含发出网络请求所需的 `INTERNET` 权限。请确保您的 AndroidManifest.xml 包含：
>
> `<uses-permission android:name="android.permission.INTERNET" />`

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

从 [Yuno Dashboard](https://dashboard.y.uno/) 获取您的公共 API 密钥。

如果您尚未实现自定义应用，请创建一个。在应用类的 `onCreate()` 方法中，调用初始化函数（`Yuno.initialize`）：

```kotlin theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
class CustomApplication : Application() {
  override fun onCreate() {
    super.onCreate()
    Yuno.initialize(
      this,
      PUBLIC_API_KEY,
      config = YunoConfig(),
    )
  }
}
```

## 步骤 5：创建注册支付方式对象

使用[注册支付方式](https://docs.y.uno/reference/payment-methods-checkout/enroll-payment-method-checkout.md) endpoint 创建注册支付方式对象，为注册设置 Headless SDK 集成。创建此对象时，请指定您的客户可以注册的支付方式类型。目前，Headless SDK 仅支持 CARD 支付方式类型。

> [!NOTE]
>
> **卡片验证**
>
> 如需在注册前验证卡片（零金额授权），请在为客户会话创建支付方式对象时包含 `verify` 对象。

## 步骤 6：启动注册流程

使用 `apiClientEnroll` 函数启动注册流程。此函数需要配置参数，用于定义如何处理注册。下表描述了必需的参数：

| 参数 | 说明 |
| - | - |
| `country_code` | 此参数确定正在为哪个国家配置支付流程。支持的国家及其 `country_code` 的完整列表请参阅[国家覆盖范围](https://docs.y.uno/zh-hans/docs/sdks/resources/country-coverage.md)页面。 |
| `customer_session` | 指当前注册的客户会话，作为[创建客户会话](https://docs.y.uno/reference/customer-sessions-enrollment/create-customer-session.md) endpoint 的响应接收。示例：`438413b7-4921-41e4-b8f3-28a5a0141638` |

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

```kotlin theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
override fun onCreate(savedInstanceState: Bundle?) {
	val apiClientEnroll = Yuno.apiClientEnroll(
    countryCode = "CO",
    customerSession = "eec6578e-ac2f-40a0-8065-25b5957f6dd3",
    context = this 
  )
 }
```

## 步骤 7：生成存储令牌

收集所有必需的客户信息后，使用 `apiClientEnroll.continueEnrollment` 函数创建 `vaulted_token`。由于这是一个异步函数，请使用 `try/catch` 块处理可能出现的任何错误。以下示例展示了如何创建 `vaulted_token`：

```kotlin theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
apiClientEnroll.continueEnrollment( 
 collectedData = EnrollmentCollectedData(
    customerSession = "customer_session",
    paymentMethod = EnrollmentMethod(
           type = "CARD",
           card = CardData(
               save = true,
               detail = Detail(
                   expirationMonth = 11,
                   expirationYear = 55,
                   number = "4111111111111111",
                   securityCode = "123",
                   holderName = "Firstname Lastname",
                   type = CardType.CREDIT
               ),
           ),
           customer = Customer(
               id = "id",
               merchantCustomerId = "merchant_customer_id",
               firstName = "firstName",
               email = "email@email.com",
               country = "CO",
               document = Document(
                   documentType = "PAS",
                   documentNumber = "PAS12312"
               ),
             phone = Phone(
                   number = "321123321123",
                   countryCode = "57"
               )
            )
      )
  ),
  context = this
 )

```

`Detail` 中的 `type` 是可选的。如果省略，Yuno 会根据卡号检测卡片类型。如果您发送它，它会与卡片一起保存并用于后续支付，因此错误的类型可能导致拒绝。

`apiClientEnroll.continueEnrollment` 函数是一个 `suspend` 函数。请在协程中调用它（例如 `lifecycleScope.launch`）。它返回包含完整响应的 `Map<String, Any?>`。以下是调用 `apiClientEnroll.continueEnrollment` 的响应示例：

```json theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
{
  "vaulted_token": "9104911d-5df9-429e-8488-ad41abea1a4b",
  "status": "SUCCEEDED",
  "customer": {
    "session": "eec6578e-ac2f-40a0-8065-25b5957f6dd3"
  }
}
```

以下代码块展示了读取响应的示例。`continueEnrollment` 声明在 `ApiClientEnroll` 伴生对象中，因此请显式导入它：

```kotlin theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
import com.yuno.sdk.ApiClientEnroll.Companion.continueEnrollment

lifecycleScope.launch {
   val response = apiClientEnroll.continueEnrollment(data, context)
   val status = response["status"] as String?
   val vaultedToken = response["vaulted_token"] as String?
}
```

### 注册流程状态

`apiClientEnroll.continueEnrollment` 函数返回的响应包含 `status` 字段，用于指示注册流程的当前状态。可能返回的状态如下：

```kotlin theme={"theme":{"light":"github-dark","dark":"github-dark-dimmed"}}
const val ENROLLMENT_STATE_SUCCEEDED = "SUCCEEDED"
const val ENROLLMENT_STATE_FAIL = "FAIL"
const val ENROLLMENT_STATE_PROCESSING = "PROCESSING"
const val ENROLLMENT_STATE_REJECT = "REJECT"
const val ENROLLMENT_STATE_INTERNAL_ERROR = "INTERNAL_ERROR"
const val ENROLLMENT_STATE_CANCELED_BY_USER = "CANCELED"
```

下表提供了有关可能状态的更多信息：

| 状态 | 说明 | 是否需要额外操作 |
| - | - | - |
| `SUCCEEDED` | 注册流程已成功完成，没有任何错误。 | 否。 |
| `FAIL` | 由于数据验证问题、服务器连接失败或技术问题等错误，注册尝试失败。 | 是。调查失败原因（验证、网络、服务器）并采取纠正措施。 |
| `PROCESSING` | 注册当前正在进行中，等待批准或验证。 | 否。 |
| `REJECT` | 由于缺少必要条件或检测到不一致等原因，注册被拒绝。 | 是。告知用户注册被拒绝，尽可能提供原因，并建议后续步骤。 |
| `INTERNAL_ERROR` | 处理注册流程的系统内部发生意外错误。 | 是。需要技术介入以检查系统、修复内部问题，然后重试或告知用户。 |
| `CANCELED` | 用户主动取消了注册流程或在完成前退出。 | 否。 |

> [!NOTE]
>
> **Webhook 状态跟踪**
>
> 建议使用通过 [Webhooks](https://docs.y.uno/zh-hans/docs/webhooks/index.md) 接收的注册状态。Yuno 建议您始终基于此状态在您的平台上做出业务决策。

## 错误处理

在您的应用中处理 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.