# Hosted Payment Fields - Integration Guide

## Welcome to Secure Payment Processing

Hosted Payment Fields (HPF) makes it easy to accept payments securely on your website. By using our iframe-based payment fields, you can collect sensitive card information without it ever touching your servers – keeping you and your customers safe while maintaining a smooth checkout experience.

## Getting Started: Your Integration Journey

### Step 1: Get Your API Access Ready

Before we begin, you'll need to obtain your API token. This gives you access to our payment systems.

**What you need to do:**

-   Follow our Authentication guide to request your API token. [POST Generate an authentication token for Direct and Order API](https://novatti.portal.swaggerhub.com/proxy/docs/novatti-unify-authentication-api-v-1-0-0#/Authentication/generateToken)
-   Keep this token secure – you'll use it for all API calls

### Step 2: Request Your Session Credentials

Think of this step as getting your "permission slip" for each transaction. You'll make a request to our Capture Context API [POST Create Capture Context](https://novatti.portal.swaggerhub.com/proxy/docs/capture-context-api-v-1-0-0#/Capture%20Context/createCaptureContext) endpoint to receive a special JWT token that contains all the configuration details for your payment form.

**Why this matters:** Each transaction gets its own unique security credentials. This ensures maximum security for every payment.

**Important:** The security values in your JWT response are unique for each transaction. Never hard-code these values – always use them dynamically to avoid security issues.

#### Here's what a typical session response looks like:

```text
{
    "Result": {
        "ResponseCode": "1000",
        "ResponseMessage": "Request successful",
        "ResponseTimestamp": "08072025140101",
        "MerchantID": "BWAQOK8PLRDMCJW"
    },
    "ContextDetails": {
        "Token": "eyJraWQiOiJ6dSIsImFsZyI6IlJTMjU2In0..."
    }
}
```

### Step 3: Understanding Your JWT Token

The JWT token contains important configuration data. When you decode it, you'll find a section that looks like this:

```text
"ctx": [
    {
      "data": {
        "clientLibraryIntegrity": "sha256-0aJp5jhj/kMM+adaZFuEGqWa/xsM1MYp3c1IbHn6vK0=",
        "clientLibrary": "https://testflex.cybersource.com/microform/bundle/v2.7.0/flex-microform.min.js",
        "allowedCardNetworks": ["VISA", "AMEX"],
        "targetOrigins": ["https://www.yourwebsite.com"],
        "mfOrigin": "https://testflex.cybersource.com",
        "allowedPaymentTypes": ["CARD"]
      },
      "type": "mf-2.1.0"
    }
]
```

**What these values mean:**

-   `clientLibrary`: The secure JavaScript library URL
-   `clientLibraryIntegrity`: Security hash to verify the library
-   `allowedCardNetworks`: Which card types you can accept
-   `targetOrigins`: Your website domains that can use this session

### Step 4: Loading the Payment Library

Now let's load the secure payment library on your page. We recommend the dynamic approach for better security and flexibility.

#### Dynamic Loading (Recommended Approach)

```javascript
// Extract the values from your session response
const clientLibrary = "[YOUR_CLIENT_LIBRARY_URL]";
const clientLibraryIntegrity = "[YOUR_INTEGRITY_HASH]";

// Create and configure the script element
const script = document.createElement("script");
script.src = clientLibrary;
script.type = "text/javascript";
script.async = true;
script.integrity = clientLibraryIntegrity;
script.crossOrigin = "anonymous";

// Initialize HPF when the script loads
script.onload = function() {
    initializeMicroform();
};

// Add the script to your page
document.head.appendChild(script);
```

### Step 5: Creating Your Payment Form

Set up your HTML form with placeholder containers where our secure payment fields will appear. Don't worry – we'll replace these with secure iframes automatically.

```html
<h1>Secure Checkout</h1>

<!-- Error messages will appear here -->
<div id="errors-output" role="alert" aria-live="polite"></div>

<form action="/process-payment" id="checkout-form" method="post">
  <!-- Customer name (handled by you) -->
  <div class="form-group">
    <label for="cardholderName">Cardholder Name</label>
    <input 
      id="cardholderName" 
      class="form-control" 
      name="cardholderName" 
      placeholder="Name as it appears on card"
      required>
  </div>

  <!-- Secure card number (handled by us) -->
  <div class="form-group">
    <label for="number-container">Card Number</label>
    <div id="number-container" class="form-control microform-field"></div>
  </div>

  <!-- Secure CVV (handled by us) -->
  <div class="form-group">
    <label for="securityCode-container">Security Code</label>
    <div id="securityCode-container" class="form-control microform-field"></div>
  </div>

  <!-- Expiration date (handled by you) -->
  <div class="form-row">
    <div class="form-group col-md-6">
      <label for="expMonth">Expiration Month</label>
      <select id="expMonth" class="form-control" required>
        <option value="">Month</option>
        <option value="01">01 - January</option>
        <option value="02">02 - February</option>
        <!-- ... add all months ... -->
        <option value="12">12 - December</option>
      </select>
    </div>
    
    <div class="form-group col-md-6">
      <label for="expYear">Expiration Year</label>
      <select id="expYear" class="form-control" required>
        <option value="">Year</option>
        <option value="2024">2024</option>
        <option value="2025">2025</option>
        <!-- ... add future years ... -->
      </select>
    </div>
  </div>

  <button type="button" id="pay-button" class="btn btn-primary">
    Complete Payment
  </button>
  
  <!-- This will hold your secure payment token -->
  <input type="hidden" id="payment-token" name="paymentToken">
</form>
```

### Step 6: Initialise the Flex SDK

Create your Flex instance using the session credentials you received:

```javascript
function initializeMicroform() {
    // Use the capture context from your session response
    const flex = new Flex(captureContext);
    
    // Continue with setting up your payment form
    setupMicroform(flex);
}
```

### Step 7: Customise Your Payment Fields

Make your payment fields look great and match your website's design. Refer to the 'Hosted Payment Fields - Styling Guide' page.

```javascript
function setupMicroform(flex) {
    // Define how you want your payment fields to look
    const fieldStyles = {
        'input': {
            'font-size': '16px',
            'font-family': 'Arial, sans-serif',
            'color': '#333333',
            'padding': '10px'
        },
        ':focus': {
            'border-color': '#0066cc',
            'outline': 'none'
        },
        '.valid': {
            'border-color': '#28a745'
        },
        '.invalid': {
            'border-color': '#dc3545'
        }
    };

    // Create your payment form with custom styling
    const microform = flex.microform("card", { styles: fieldStyles });
    
    // Set up the payment fields
    createPaymentFields(microform);
}
```

### Step 8: Set Up Your Secure Payment Fields

Create the secure input fields and connect them to your form:

```javascript
function createPaymentFields(microform) {
    // Create secure card number field
    const cardNumber = microform.createField('number', {
        placeholder: 'Enter your card number'
    });

    // Create secure CVV field
    const securityCode = microform.createField('securityCode', {
        placeholder: 'CVV'
    });

    // Connect the fields to your HTML containers
    cardNumber.load('#number-container');
    securityCode.load('#securityCode-container');

    // Set up payment processing
    setupPaymentHandler(microform);
}
```

### Step 9: Handle Payment Submission

Create the logic to process payments when customers click your payment button:

```javascript
function setupPaymentHandler(microform) {
    const payButton = document.getElementById('pay-button');
    const errorContainer = document.getElementById('errors-output');

    payButton.addEventListener('click', function(event) {
        event.preventDefault();
        
        // Clear any previous error messages
        errorContainer.innerHTML = '';
        
        // Compiling MM & YY into optional parameters     
        const options = {
            expirationMonth: document.querySelector('#expMonth').value,
            expirationYear: document.querySelector('#expYear').value
        };
        //  
        
        // Generate the secure payment token
        microform.createToken(options, function(error, token) {
            if (error) {
                // Something went wrong - show the error to your customer
                displayError(error.message);
            } else {
                // Success! Process the payment
                processPayment(token);
            }
        });
    });
}

function displayError(message) {
    const errorContainer = document.getElementById('errors-output');
    errorContainer.innerHTML = `<div class="alert alert-danger">${message}</div>`;
}

function processPayment(token) {
    // Add the secure token to your form and submit it
    document.getElementById('payment-token').value = token;
    document.getElementById('checkout-form').submit();
}
```

This will return a transient token that can be used to submit your payment in the next step

### Step 10: Submit the transient token to the OneStep API 

Use the transient token obtained in the previous step and submit it to the Direct API > OneStep Payment with token.

[POST Create a One Step Payment using a Secure Token](https://novatti.portal.swaggerhub.com/proxy/docs/novatti-proxy-api-v-2-1-2#/Payments/createTokenPayment)

## Mobile App Integration

Planning to integrate with a mobile app? Here's what you need to know:

### Requirements for Mobile Apps

**Web View Integration:** You'll need to host your payment form on a web page within your mobile app's web view.

**Secure Fields:** All sensitive payment information must be collected through our web-based HPF fields – this ensures maximum security.

**Communication Bridge:** Set up communication between your native app and the web view for a seamless user experience.

### Implementation Steps

1.  **Create a dedicated web page** following all the steps above
2.  **Load this page** within a web view in your mobile application
3.  **Implement JavaScript bridges** for communication between native and web components
4.  **Handle the payment token** response in your native application code

## Security Best Practices

Following these practices will keep your integration secure and compliant:

### Essential Security Rules

-   **Never store sensitive payment data** on your servers – let us handle it
-   **Always use HTTPS** for all payment-related pages
-   **Validate all form inputs** on both client and server sides
-   **Keep your integration updated** with the latest security patches
-   **Test thoroughly** in a sandbox environment before going live

### Why This Approach is Secure

Our HPF solution ensures that sensitive card data never touches your servers, reducing your PCI compliance scope while maintaining a great user experience for your customers.

## Troubleshooting Common Issues

Don't worry if you run into issues – here are solutions to the most common problems:

### Library Loading Problems

**Issue:** The payment library won't load **Solutions:**

-   Make sure you're using the dynamic `clientLibrary` and `clientLibraryIntegrity` values from your session response
-   Check that your Content Security Policy allows our library domain
-   Look at your browser console for specific error messages

### Payment Fields Not Appearing

**Issue:** The secure payment fields don't show up **Solutions:**

-   Confirm your container elements have unique IDs that match your JavaScript
-   Make sure containers are visible and properly sized on your page
-   Check that your CSS isn't interfering with our iframe styling

### Token Generation Failures

**Issue:** Payment tokens aren't being created **Solutions:**

-   Verify all required fields are completed by the customer
-   Check for JavaScript errors in your browser console
-   Ensure your capture context is valid and hasn't expired

## Getting Help

If you need assistance with your integration, our support team is here to help. Check your developer documentation or contact support with specific error messages and code examples.

Remember: Every merchant's integration is unique, so don't hesitate to reach out if you need guidance tailored to your specific setup.
