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

# Smart Fields 集成指南

本指南提供详细的分步说明，指导您如何将智能字段集成到支付流程中。完成本指南后，您将能够直接在网站上安全地收集支付信息，而敏感数据将由 Localpayment 处理。

## 先决条件

请确保您已准备好以下必需物品：

> [card] [API密钥](https://docs.localpayment.com/zh/docs/dashboard-smart-fields-api-keys.md)
>
> 您可以从 **测试** 环境或 **生产** 环境获取身份验证密钥。

> [card] [客户端代码](https://docs.localpayment.com/zh/docs/dashboard-clients-information)
>
> 您的唯一商户标识符，可在 Localpayment Business Portal 中找到。

> [card] [后端设置](https://docs.localpayment.com/zh/docs/payins-overview.md)
>
> 服务器 endpoint 已准备好接收支付令牌并处理交易。

***

## 集成步骤

### 包含 Smart Fields SDK

选择适合集成的环境：

> [tab] Stage（测试）
>
> 使用此功能可进行开发和测试，并模拟支付过程：
>
> ```html theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> <script src="https://sdk.stage.localpayment.com/localpayment-sdk.min.js"></script>
> ```
>
> > [!NOTE]
> >
> > **提示**\\
> >
> > 上线前，务必在测试环境中对集成进行彻底测试。

> [tab] Production（线上）
>
> 在您的网站上使用此功能来处理真实支付：
>
> ```html theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> <script src="https://sdk.localpayment.com/localpayment-sdk.min.js"></script>
> ```
>
> > [!WARNING]
> >
> > **重要提示**\\
> >
> > 只有在测试环境中完成所有测试后，才能切换到生产环境。

### 初始化 SDK

脚本加载完成后，使用您的凭据初始化 SDK：

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
const localpayment = LP({
    clientCode: 'your_client_code',  // Replace with your actual client code
    apiKey: 'your_api_key'           // Replace with your actual API key
});
```

**配置参数：**

| 参数 | 类型 | 必需的 | 描述 |
| - | - | - | - |
| `clientCode` | string | ✅ | 来自 Localpayment 的唯一商户标识符 |
| `apiKey` | string | ✅ | 您的身份验证 API 密钥 |

### 创建安全会话

与 Localpayment 服务器建立安全连接：

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
try {
    await localpayment.createSession();
    console.log('Session created successfully');
} catch (error) {
    console.error('Failed to create session:', error);
    // Handle session creation error
}
```

> [!NOTE]
>
> **安全须知**
>
> 该会话为所有支付数据建立加密通信通道。

### 设置付款表单

创建支付表单的 HTML 结构：

```html theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
<form id="payment-form" class="payment-form">
    <!-- Card Number Field -->
    <div class="form-group">
        <label for="pan-container">Card Number *</label>
        <div id="pan-container" class="field-container"></div>
        <div class="error-message" id="pan-error" role="alert"></div>
    </div>

    <!-- CVV Field -->
    <div class="form-group">
        <label for="cvv-container">Security Code *</label>
        <div id="cvv-container" class="field-container"></div>
        <div class="error-message" id="cvv-error" role="alert"></div>
    </div>

    <!-- Expiration Field -->
    <div class="form-group">
        <label for="expiration-container">Expiration Date *</label>
        <div id="expiration-container" class="field-container"></div>
        <div class="error-message" id="expiration-error" role="alert"></div>
    </div>

    <!-- Cardholder Name -->
    <div class="form-group">
        <label for="cardholder-name">Cardholder Name *</label>
        <input type="text" id="cardholder-name" name="cardholderName" 
               placeholder="John Doe" required>
    </div>

    <button type="submit" id="submit-payment" disabled>
        Process Payment
    </button>
</form>
```

### 创建并挂载支付字段

初始化安全支付字段并将其添加到表单中：

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Create individual payment fields
const panField = localpayment.create('pan');        // Card number
const cvvField = localpayment.create('cvv');        // Security code  
const expirationField = localpayment.create('expiration'); // Expiry date

// Mount fields to their respective containers
panField.mount('#pan-container');
cvvField.mount('#cvv-container');
expirationField.mount('#expiration-container');
```

使用 `mount()` 方法在您指定的容器内渲染安全的 iframe。传递一个 CSS 选择器字符串，用于标识您的目标 DOM 元素（例如 `#pan-container`）。

**字段类型和特征：**

| 字段类型 | 目的 | 验证功能 |
| - | - | - |
| `pan` | 卡号（PAN） | Luhn算法、品牌检测、格式化 |
| `cvv` | 安全码 | 长度验证（3-4 位数字），仅限数字 |
| `expiration` | 到期日 | MM/YY 格式，未来日期验证 |

### 处理字段事件和验证

监听每个字段的事件，以更新用户界面并跟踪其验证状态：

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Example: Listen for changes on the card number field
panField.on('change', (state) => {
    // state contains: isValid, isEmpty, isFocused, error
    if (state.isValid) {
        // Field is valid, update UI accordingly
    } else if (state.error) {
        // Show error message to user
        console.error(state.error);
    }
});
```

### 处理付款提交

获取会话数据和会话 ID：

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
const sessionData = localpayment.getSessionData(); // Contains sessionId, accessToken, clientCode.
console.log(sessionData.sessionId);
```

### 合并会话并获取令牌

向 Consolidate endpoint 发送 `POST` 请求，并附上 `sessionId` 和持卡人详细信息：

```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
const response = await fetch('https://tokenization.api.stage.localpayment.com/api/tokenization/consolidate', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    clientCode: 'your_client_code',
    sessionId: sessionData.sessionId,
    CardholderName: 'John Doe'
  })
});

const consolidationResult = await response.json();
console.log(consolidationResult);
```

> [!NOTE]
>
> **环境：**
>
> * **Stage**：[https://tokenization.api.stage.localpayment.com/api/tokenization/consolidate](https://tokenization.api.stage.localpayment.com/api/tokenization/consolidate)
> * **Production**：[https://tokenization.api.localpayment.com/api/tokenization/consolidate](https://tokenization.api.localpayment.com/api/tokenization/consolidate)

**预期的合并响应：**

```json theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
{
    "token": "lnZB3Rq1sbCB9sZnxgqtxbcPUR49G3I1tl%2BBsbt2vaM%3D",
    "bin": "424242",
    "brand": "VISA", 
    "country": "GB",
    "name": "John Doe",
    "last4": "4242",
    "expirationYear": 2029,
    "expirationMonth": 11
}
```

### 处理付款

创建一个 [新的 Payin](https://docs.localpayment.com/zh/docs/payins-overview.md)，并使用令牌参数代替持卡人信息。令牌可以安全地表示支付方式，而不会泄露敏感信息。

***

## 资源与后续步骤

利用这些关键资源，最大限度地提高您的集成成功率。

> [card] [Webhook 集成](https://docs.localpayment.com/zh/docs/webhooks.md)
>
> 设置交易状态更新的实时通知。

> [card] [报告 Business Portal](https://docs.localpayment.com/zh/docs/balance-report.md)
>
> 获取详细的分析、报告工具和对账功能。

> [card] [交易监控](https://docs.localpayment.com/zh/reference/transaction-status-error-codes)
>
> 学习查询交易状态并实现全面跟踪。

> [card] [API 参考](https://docs.localpayment.com/zh/reference/exchange-bulk.md)
>
> 提供包含交互式示例的完整 endpoint 文档。

> [!NOTE]
>
> **专业提示**
>
> 在部署到生产环境之前，务必先在我们的沙盒环境中测试您的工作流程。这可以确保您的错误处理、Webhook 处理和状态跟踪在所有场景下都能正常工作。

***

> [!NOTE]
>
> **需要帮助吗？**
>
> 如果您遇到任何问题或需要集成方面的帮助，请联系我们的[支持团队](mailto:support@localpayment.com)。


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