> ## 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 Integration Guide

This guide provides a detailed, step-by-step process for integrating Smart Fields into your payment checkout. By the end, you will be able to securely collect payment details directly within your website while Localpayment handles the sensitive data.

## Prerequisites

Ensure you have these essential components ready:

> [card] [API Keys](https://docs.localpayment.com/docs/dashboard-smart-fields-api-keys.md)
>
> Get your authentication keys from either **Stage** (testing) or **Production** environment.

> [card] [Client Code](https://docs.localpayment.com/docs/dashboard-clients-information)
>
> Your unique merchant identifier found the Localpayment business portal.

> [card] [Backend Setup](https://docs.localpayment.com/docs/payins-overview.md)
>
> A server endpoint ready to receive payment tokens and process transactions.

***

## Integration Steps

### 1. Include the Smart Fields SDK

Choose the appropriate environment for your integration:

> [tab] Stage (Testing)
>
> Use this for development and testing with simulated payments:
>
> ```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]
> >
> > **Tip**\\
> >
> > Always test your integration thoroughly in the stage environment before going live.

> [tab] Production (Live)
>
> Use this for your live website to process real payments:
>
> ```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]
> >
> > **Important**\\
> >
> > Only switch to production after complete testing in the stage environment.

### 2. Initialize the SDK

Initialize the SDK with your credentials once the script loads:

```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
});
```

**Configuration Parameters:**

| Parameter | Type | Required | Description |
| - | - | - | - |
| `clientCode` | string | ✅ | Your unique merchant identifier from Localpayment |
| `apiKey` | string | ✅ | Your secret API key for authentication |

### 3. Create a Secure Session

Establish a secure connection with Localpayment's servers:

```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]
>
> **Security Note**
>
> The session establishes encrypted communication channels for all payment data.

### 4. Set Up Payment Form

Create the HTML structure for your payment form:

```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>
```

### 5. Create and Mount Payment Fields

Initialize the secure payment fields and mount them to your 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');
```

Use the `mount()` method to render the secure iframe within your specified container. Pass a CSS selector string that identifies your target DOM element (e.g., `#pan-container`).

**Field Types and Features:**

| Field Type | Purpose | Validation Features |
| - | - | - |
| `pan` | Card number (PAN) | Luhn algorithm, brand detection, formatting |
| `cvv` | Security code | Length validation (3-4 digits), numeric only |
| `expiration` | Expiry date | MM/YY format, future date validation |

### 6. Handle Field Events and Validation

Listen to events from each field to update your UI and track their validation status:

```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);
    }
});
```

### 7. Process Payment Submission

Retrieve the session data and sessionId:

```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);
```

### 8. Consolidate Session and Get Token

Create a `POST` request to the Consolidate endpoint, sending the `sessionId` and cardholder details:

```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]
>
> **Environments:**
>
> * **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)

**Expected Consolidation Response:**

```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
}
```

### 9. Process Payment

Create a [new Payin](https://docs.localpayment.com/docs/payins-overview.md) and use the token parameter instead of cardholder information. The token securely represents the payment method without exposing sensitive details.

***

## Resources & Next Steps

Maximize your integration success with these essential resources

> [card] [Webhook Integration](https://docs.localpayment.com/docs/webhooks.md)
>
> Set up real-time notifications for transaction status updates.

> [card] [Reporting Business Portal](https://docs.localpayment.com/docs/balance-report.md)
>
> Access detailed analytics, reporting tools, and reconciliation features.

> [card] [Transaction Monitoring](https://docs.localpayment.com/reference/transaction-status-error-codes)
>
> Learn to query transaction status and implement comprehensive tracking.

> [card] [API Reference](https://docs.localpayment.com/reference/exchange-bulk.md)
>
> Complete endpoint documentation with interactive examples.

> [!NOTE]
>
> **Pro Tip**
>
> Always test your workflow in our sandbox environment before deploying to production. This ensures your error handling, webhook processing, and status tracking work correctly across all scenarios.

***

> [!NOTE]
>
> **Need Help?**
>
> Contact our [support team](mailto:support@localpayment.com) if you experience any issues or need assistance for integration.


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