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

# Collect Card Details

> Securely collect and tokenize user payment cards

## Overview

The `collectPAN()` method securely collects credit card details from users through an isolated iframe. The card data is tokenized via Prava's PCI DSS vault and returns only safe metadata — your servers never see the raw PAN.

## Method Signature

```typescript theme={null}
prava.collectPAN(options: CollectPANOptions): Promise<CollectPANResult>
```

## Parameters

**options** `CollectPANOptions` *required*

Configuration options for card collection

**properties**

**sessionToken** `string` *required*

The `session_token` (JWT) from your backend session response — it authenticates in-session SDK
calls. Note: the session identifier the iframe loads is already embedded in `iframe_url`
(`?session=<session_id>`); you never build that URL yourself.

**iframeUrl** `string` *required*

The `iframe_url` from your backend session response — pass it **verbatim**. It already contains
the `?session=<session_id>` identifier; do not rebuild it or add your own query params.

**container** `string | HTMLElement` *required*

CSS selector or DOM element to mount the card form (e.g., `#card-form`)

**onReady** `() =\> void`

Called when the iframe is loaded and ready for input

**onChange** `(state: CardValidationState) =\> void`

Real-time validation state on every keystroke

**onSuccess** `(result: CollectPANResult) =\> void`

Called when card provisioning succeeds. In a `full_enrollment` session, passkey work may
still be in progress; use `onEnrollmentComplete` for the final enrollment result.

**onEnrollmentComplete** `(payload: CardEnrollmentCompletePayload) =\> void`

Called only for an enrollment-only session after the card and passkey are ready. The payload
contains `session_id`, `card_id`, `status: "completed"`,
`outcome: "fully_enrolled"`, `passkey: "registered" | "existing"`, and
`callback_url`.

**onEnrollmentCancelled** `(payload: \{ session_id: string; card_id: string | null \}) =\> void`

Called when the cardholder cancels an enrollment-only session. `card_id` can be non-null
when card provisioning completed before cancellation.

**onError** `(error: PravaError) =\> void`

Called on error

**onDismiss** `(payload: \{ reason: string \}) =\> void`

Called when the user dismisses the payment flow

**styles** `CardFormStyles`

Custom styles for the card form. Supports `base`, `invalid`, and `focus` states as CSS property maps.

## Return Value

**result** `CollectPANResult`

**properties**

**enrollmentId** `string`

Unique identifier for the collected card

**last4** `string`

Last 4 digits of the card number

**brand** `string`

Card brand (`visa`, etc.)

**expMonth** `number`

Card expiration month (1-12)

**expYear** `number`

Card expiration year (4 digits)

> [!NOTE]
>
> The `enrollmentId` identifies the collected card on the server side. Use your backend and the
> [API Reference](https://docs.prava.space/api-reference/overview.md) to read payment results and report status for that card.

## Full card-enrollment sessions

When `collectPAN()` receives a session created by
[Enroll Card](https://docs.prava.space/api-reference/enroll-card.md) with `enrollment_mode: "full_enrollment"`, its normal
`onSuccess` callback still reports the earlier card-provisioning milestone. Keep the SDK and iframe
mounted until `onEnrollmentComplete` or `onEnrollmentCancelled`.

```typescript theme={null}
void prava.collectPAN({
  sessionToken: session.session_token,
  iframeUrl: session.iframe_url,
  container: '#card-form',
  onSuccess: (card) => console.log('Card provisioned', card.enrollmentId),
  onEnrollmentComplete: (result) => {
    console.log('Full enrollment complete', result.card_id, result.passkey);
  },
  onEnrollmentCancelled: (result) => {
    console.log('Enrollment cancelled', result.card_id);
  },
  onError: (error) => console.error(error.code, error.message),
});
```

Use the callback for frontend coordination, but confirm the durable server-side result with
[Get Card Enrollment Status](https://docs.prava.space/api-reference/get-card-enrollment-status.md). A retryable iframe error
does not require a new SDK call: leave the iframe mounted while the cardholder selects **Try again**.

## Example

```typescript React theme={null}
import { useEffect, useRef, useState } from 'react';
import { PravaSDK } from '@prava-sdk/core';
import type { CollectPANResult } from '@prava-sdk/core';

function CardEnrollment({ session }: { session: { session_token: string; iframe_url: string } }) {
  const containerRef = useRef<HTMLDivElement>(null);
  const sdkRef = useRef<PravaSDK | null>(null);
  const [enrolled, setEnrolled] = useState<CollectPANResult | null>(null);

  useEffect(() => {
    const sdk = new PravaSDK({ publishableKey: 'pk_test_xxx' });
    sdkRef.current = sdk;
    return () => sdk.destroy();
  }, []);

  const handleEnroll = async () => {
    if (!sdkRef.current || !containerRef.current) return;

    const result = await sdkRef.current.collectPAN({
      sessionToken: session.session_token,
      iframeUrl: session.iframe_url,
      container: containerRef.current,
      onReady: () => console.log('Form loaded'),
      onChange: (state) => {
        console.log('Complete:', state.isComplete);
      },
      onSuccess: (data) => {
        console.log(`Enrolled: •••• ${data.last4}`);
        setEnrolled(data);
      },
      onError: (err) => console.error(err.code, err.message),
    });
  };

  return (
    <div>
      <div ref={containerRef} />
      <button onClick={handleEnroll}>Enroll Card</button>
      {enrolled && <p>Card enrolled: {enrolled.brand} •••• {enrolled.last4}</p>}
    </div>
  );
}
```

```typescript Vanilla JavaScript theme={null}
import { PravaSDK } from '@prava-sdk/core';

const prava = new PravaSDK({ publishableKey: 'pk_test_xxx' });

// Get session from your backend
const session = await fetch('/api/session').then(r => r.json());

// Collect card via secure iframe
const card = await prava.collectPAN({
  sessionToken: session.session_token,
  iframeUrl: session.iframe_url,
  container: '#card-form',
  onReady: () => console.log('Form loaded'),
  onChange: (state) => {
    document.getElementById('submit-btn').disabled = !state.isComplete;
  },
  onSuccess: (data) => {
    console.log(data.enrollmentId, data.last4, data.brand);
  },
  onError: (err) => console.error(err.code, err.message),
});
```

```html theme={null}
<div id="card-form"></div>
<button id="submit-btn" disabled>Enroll Card</button>
```

## Flow Diagram

```mermaid theme={null}
sequenceDiagram
    participant App as Your App
    participant SDK as Prava SDK
    participant Iframe as Secure Iframe
    participant Backend as Prava Backend
    participant Network as Card Network

    App->>SDK: collectPAN(sessionToken, iframeUrl)
    SDK->>Iframe: Mount iframe
    Iframe-->>SDK: onReady()
    SDK-->>App: Form ready

    Note over Iframe: User enters card details

    Iframe->>Backend: Tokenize via PCI DSS vault
    Backend->>Network: Provision token
    Network-->>Backend: Enrollment complete
    Backend-->>Iframe: Success
    Iframe-->>SDK: onSuccess(result)
    SDK-->>App: CollectPANResult
```

## Under the Hood

When you call `collectPAN()`, here's what happens:

**1. Iframe Injection**

The SDK injects a secure, sandboxed iframe into your specified container. The iframe is served from Prava's domain — card data never touches your DOM or servers.

**2. Session Validation**

The iframe validates the session token with Prava's backend to ensure the request is legitimate and not expired.

**3. User Input**

The user enters their card details (number, expiry, CVV) in the iframe form with real-time validation.

**4. PCI DSS Vaulting**

When the user submits, the iframe tokenizes the PAN via Prava's PCI DSS vault. Your servers never see the raw card number.

**5. Result**

The enrollment result (with `enrollmentId`, `last4`, `brand`, `expMonth`, `expYear`) is returned to your app.

## Validation States

The `onChange` callback receives a `CardValidationState` object on every keystroke:

```typescript theme={null}
interface CardValidationState {
  cardNumber: FieldState;
  expiry: FieldState;
  cvv: FieldState;
  isComplete: boolean; // true when all fields are valid
}

interface FieldState {
  isEmpty: boolean;
  isValid: boolean;
  isFocused: boolean;
  error?: string;
}
```

Use `isComplete` to enable/disable your submit button:

```typescript theme={null}
onChange: (state) => {
  submitButton.disabled = !state.isComplete;
}
```

## Error Handling

### Common Errors

| Code | Cause | Resolution |
| - | - | - |
| `SDK_ALREADY_ACTIVE` | `collectPAN` called while another collection is in progress | Call `destroy()` first |
| `INVALID_CONFIG` | Missing `iframeUrl` (or a bad `publishableKey`) | Pass the `iframe_url` from your backend session response |
| `IFRAME_LOAD_ERROR` | Iframe failed to load | Check network, verify `iframeUrl` |
| `Session preview failed: 404` | The `?session=` value isn't a valid `session_id` (e.g. the `session_token`/JWT was passed instead) | Pass `iframe_url` verbatim; don't set your own `session`/`session_token` param; verify sandbox vs prod host |
| `SDK_INIT_ERROR` | SDK initialization failed | Verify browser compatibility and config |

## Security Notes

> [!WARNING]
>
> **Never** attempt to bypass the iframe or collect card data directly. The iframe is sandboxed with `allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox` and a permissions policy of `payment; publickey-credentials-get; publickey-credentials-create`. Card data never touches your DOM, JS, or servers.

> [!NOTE]
>
> PostMessage communication is origin-locked. The iframe resolves its backend from its own hostname — merchants cannot inject a fake backend URL.

## Next Steps

> [card] [Enroll Card (API)](https://docs.prava.space/api-reference/enroll-card.md)
>
> Create a provision-only or full card-enrollment session

> [card] [List Cards (API)](https://docs.prava.space/api-reference/list-cards.md)
>
> Retrieve a customer's enrolled cards server-side

> [card] [Get Payment Result](https://docs.prava.space/api-reference/get-payment-result.md)
>
> Read the outcome after the card is collected


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