> ## Documentation Index
> Fetch the complete documentation index at: https://docs.localpayment.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 字段对象

探索字段对象，了解如何创建支付表单。本文档详细介绍了 fields.create()、field.mount() 和事件处理。

使用 `localpayment.create()` 创建字段后，您可以对返回的对象使用以下方法。

| 方法 | 描述 | 例子 |
| - | - | - |
| `mount(selector)` | 将字段的 iframe 挂载到指定的 DOM 容器中。 | `panField.mount('#card-number-container');` |
| `unmount()` | 从 DOM 中移除字段的 iframe。 | `panField.unmount();` |
| `clear()` | 清除字段中的当前值。 | `panField.clear();` |
| `focus()` | 使字段获得焦点。 | `panField.focus();` |
| `blur()` | 使字段失去焦点。 | `panField.blur();` |
| `on(event, callback)` | 为该字段上的特定事件注册回调函数。 | `panField.on('change', (state) => { … });` |

### 字段类型

以下字段类型可通过 `create()` 方法创建。

| 字段类型 | `create()` 参数 | 描述 | 示例输出 |
| - | - | - | - |
| 卡号 | `'pan'` | 输入主账号（PAN）。自动格式化并添加空格。 | `4111 1111 1111 1111` |
| 安全码 | `'cvv'` | 输入卡片验证值（CVV/CVC）。 | `123` |
| 截止日期 | `'expiration'` | 输入卡片的有效期。格式为MM-YYYY。 | `12-2028` |

***

## 事件

使用 `.on()` 方法监听字段实例上的事件，以便对状态变化作出响应。

### `'change'` 事件

当字段值或验证状态发生变化时触发。

回调接收：`state`（Object）

* `state.isEmpty`（`Boolean`）：如果字段没有值，则为 `true`。
* `state.isValid`（`Boolean`）：如果当前值有效，则为 `true`。
* `state.isFocused`（`Boolean`）：如果字段当前具有焦点，则为 `true`。
* `state.error`（`String` | `undefined`）：描述验证错误的字符串（如果有）。

**例子：**

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
panField.on('change', (state) => {
  if (state.isValid) {
    // Update UI to show valid state
    console.log('Card number is valid');
  } else if (state.error) {
    // Update UI to show error message
    console.error('Validation error:', state.error);
  }
});
```

### `'tokenized'` 事件

当字段值被 Localpayment 后端成功令牌化后触发。这通常发生在输入有效值且字段失去焦点之后。

**例子：**

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
panField.on('tokenized', (token) => {
  console.log('PAN tokenized with token:', token);
  // You can track that this field is ready for consolidation
});
```

### `'error'` 事件

当发生不可恢复的错误时触发，例如令牌化失败。

回调接收：`error`（Object）

* `error.error`（`String`）：一条通用错误消息。
* `error.metadata`（`Object` | `undefined`）：有关该错误的其他元数据。

**例子：**

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
panField.on('error', (error) => {
  console.error('An error occurred:', error.error);
  if (error.metadata) {
    console.error('Error details:', error.metadata);
  }
});

```

***

## 错误处理

SDK 通过 `error` 事件和被拒绝的 promise 提供错误。常见的错误场景包括：

* **网络错误**：如果无法发出网络请求，`createSession()` 将失败。
* **无效凭据**：如果 `clientCode` 或 `apiKey` 不正确，`createSession()` 将失败。
* **令牌化错误**：如果字段值无法令牌化（例如，无效的卡号通过了基本验证，但被处理器拒绝），则会触发 \`error 事件。
* **会话过期**：如果会话已过期，操作将失败。您必须捕获此错误并通常需要重新创建会话。

**全面错误处理示例：**

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Handle field errors
panField.on('error', (error) => {
  showUserError(`Card number error: ${error.error}`);
});
// Handle session creation errors
try {
  await localpayment.createSession();
} catch (error) {
  console.error('Session creation failed. Please check your credentials.', error);
}
```


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