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

# Web Instruments SDK

> Save a customer's card on your website without charging it, then pay with it later.

**Version:** `1.1.0` (`@litesa/js-sdk`)

The Instruments SDK saves a customer's card without taking a payment. You get back an **instrument**: an id you can pay with later, plus the card's scheme, issuing bank, issuing country and funding source. Use it when your price or eligibility depends on the card, for example a discount for one scheme or different terms for domestic cards, or when you want to keep a card on file before the first payment.

It is part of the same `@litesa/js-sdk` package as the Checkout SDK. Card details are entered in lite's secure fields and encrypted inside lite-hosted iframes: your page's code and your server never see them.

## Secure fields, elements and the hosted page

lite offers three ways to collect a payment method on the web. A tokenization session supports two of them:

| Option | What it is | On a tokenization session |
| - | - | - |
| **Secure fields** | Card number, expiry, CVV and cardholder name inputs that you place in your own page. You draw the button. | Supported. This is how you save a card. |
| **Elements** | Ready-made payment-method components, such as the Apple Pay button. | Apple Pay is supported. |
| **Hosted checkout page** | lite's complete checkout on lite's domain. | Not supported. The page tells the customer the link can't be used to pay. |

## How it works

1. Your server creates a **tokenization session** with the lite API and gets back its `client_secret`.
2. Your page starts the SDK with that `client_secret`.
3. The customer enters a card in the secure fields, or authorizes Apple Pay.
4. The SDK encrypts the card and saves it with lite. Nothing is charged.
5. Your page receives the instrument and sends its `id` to your server.
6. Your server fetches the instrument from lite, decides what to do, and optionally charges it.

## Before you begin

You need:

* A lite account with a **terminal** that has **cards** enabled. To save cards with Apple Pay, enable **Apple Pay** on the same terminal. A tokenization session offers only the payment methods enabled there.
* lite API keys, kept on your server.
* A backend endpoint that creates tokenization sessions.
* A page served over HTTPS, and a bundler that installs from npm.

> [!WARNING]
>
> Never put your lite API keys in your page or your JavaScript bundle. Your server creates the session and sends only its `client_secret` to the browser.

## 1. Install the SDK

```bash theme={null}
npm install @litesa/js-sdk
```

Import the SDK where you save cards, and its stylesheet once, in your app's entry point:

```ts theme={null}
import { Lite, PaymentOperationStatus, isTokenizationSession } from '@litesa/js-sdk';
import '@litesa/js-sdk/styles.css';
```

## 2. Create a tokenization session

A **tokenization session** is a checkout session that saves one card instead of taking a payment. Your server creates it with your API key, the same way as a payment session, with `type: "tokenization"` and the customer's id. It has no amount, currency or order.

```bash theme={null}
curl https://api.lite.sa/checkout-sessions \
  -H "x-api-key: $LITE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "tokenization",
    "customer": { "id": "cust_8f3a91" },
    "expiry": 600
  }'
```

```json theme={null}
{
  "id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
  "client_secret": "eyJhbGciOiJIUzI1NiIs...",
  "status": "Pending",
  "expires_on": "2026-06-01T12:10:00.000Z"
}
```

`terminal_id` is optional and sets the card networks and wallets the session offers. Without it, the session uses your default online terminal. To use another, send its ID: open the terminal under **Acceptance → Online** in the dashboard, and the ID is the last part of the page address. See [Create a checkout session](https://docs.lite.sa/api-reference/hosted-checkout/create-a-checkout-session.md) for every field.

Create the session when the customer reaches the card step, not when the page loads. It expires after `expiry` seconds.

## 3. Pass the client secret to the SDK

The **`client_secret`** is a short-lived credential for this one session: a signed token that expires with the session. It lets the SDK read the session and save one card on it. It cannot read other sessions, and it cannot pay. Return it from your server to the page. Keep the session `id` on your server.

Do not log the `client_secret`.

Start the SDK with it:

```ts theme={null}
let lite: Lite;

try {
  lite = await Lite.init({ secret: clientSecret });
} catch (error) {
  // The secret is expired or rejected, or lite could not be reached.
  showError('Saving a card is unavailable. Try again.');
}
```

`isTokenizationSession(lite.session)` is `true` for a tokenization session.

## 4. Collect the card

### Secure fields (cards)

Mount the secure fields in your page and add your own **Save card** button. Enable it once every field is valid.

```html theme={null}
<div id="cardholder-name"></div>
<div id="card-number"></div>
<div id="expiry"></div>
<div id="cvv"></div>
<button id="save" disabled>Save card</button>
```

```ts theme={null}
const elements = lite.elements();

const fields = {
  cardholderName: elements.create('cardholderName'),
  cardNumber: elements.create('cardNumber'),
  expiry: elements.create('expiry'),
  cvv: elements.create('cvv'),
};

const valid: Record<string, boolean> = {};
for (const [name, field] of Object.entries(fields)) {
  field.on('change', (state) => {
    valid[name] = state.valid;
    saveButton.disabled = !Object.keys(fields).every((key) => valid[key]);
  });
}

await fields.cardholderName.mount('#cardholder-name');
await fields.cardNumber.mount('#card-number');
await fields.expiry.mount('#expiry');
await fields.cvv.mount('#cvv');

saveButton.addEventListener('click', async () => {
  handle(await lite.tokenize({ store_for_future: true }));
});
```

* `tokenize` saves the card and never charges it. Pass `store_for_future: true` only with the customer's consent to keep the card for later payments. Without it, the instrument is for a single payment.
* Mount at most one field of each type. Each field's `change` reports `valid` only, and never the card data. Style the fields as in the [Checkout SDK guide](https://docs.lite.sa/guides/web-sdk.md#style-the-fields).
* Calling `tokenize` again while a save is running returns the same promise, so a double click saves once.
* A tokenization session has nothing to pay: `lite.pay()` resolves with a failure whose `errorCode` is `session_type_unsupported`, and it lists no saved cards.

### Elements: Apple Pay

On a tokenization session, the Apple Pay button saves the card the customer authorizes instead of paying. The sheet reads **Save card**, with the amount shown as pending, and nothing is charged. Listen for `tokenize`. It carries the same result as `lite.tokenize()`, once the sheet closes:

```ts theme={null}
let applePayButton;

try {
  applePayButton = lite.elements().create('apple_pay');
} catch {
  // Apple Pay isn't active on this session's terminal. Offer the card fields only.
}

if (applePayButton) {
  applePayButton.on('tokenize', (result) => handle(result));
  await applePayButton.mount('#apple-pay');
}
```

* `create('apple_pay')` throws when Apple Pay isn't configured or active on the session's terminal. Catch it, so that the card fields still mount.
* Once created, the button shows only when the browser can pay with Apple Pay. Saving a card also needs Apple Pay version 4, which iOS 12.1 and macOS 10.14.1 and later have; on older devices the button doesn't show. It never emits `result` on a tokenization session.
* If the customer tries again in the same sheet after a failure, `tokenize` fires once per attempt: the failure first, then the retry's result. Treat the last one as final.
* `cancel` fires if the customer closes the sheet without saving.
* The button saves the card for one payment, without `future_usage`, so charge it within about 20 minutes.

Apple Pay on your own page needs your domain registered with Apple through lite. Follow [Apple Pay](https://docs.lite.sa/guides/web-sdk.md#apple-pay) in the Checkout SDK guide. Test it in Safari on a device with a card in Wallet.

## 5. Handle the tokenization result

Both `tokenize()` and the Apple Pay button's `tokenize` event give you a `TokenizeResult`:

```ts theme={null}
import type { TokenizeResult } from '@litesa/js-sdk';

function handle(result: TokenizeResult) {
  if (result.status === PaymentOperationStatus.SUCCESS) {
    // Send the id to your server; fetch the instrument there before you rely on it.
    sendToServer(result.instrument.id);
  } else {
    showError(result.errorCode);
  }
}
```

On success, `result.instrument` is a `LiteInstrument`. Its fields carry the API's names:

| Field | Description |
| - | - |
| `id` | The instrument's id. Pay with this. |
| `type` | `card` for the secure fields, `apple_pay` for Apple Pay. |
| `holder_id` | The session's customer. |
| `future_usage` | Set when the card is kept for later payments. `null` for a single-use instrument. |
| `agreement_id` | The agreement the card is kept under. Set whenever `future_usage` is. See [Payment instruments](https://docs.lite.sa/guides/payment-instruments.md). |
| `card.scheme` | `mada`, `visa`, `mastercard`, and others. |
| `card.last4` | The last four digits. |
| `card.expiry_month`, `card.expiry_year` | Strings: `'03'`, `'2028'`. |
| `card.issuer_bin` | The issuer's BIN. |
| `card.funding_source` | `credit`, `debit`, `prepaid` or `charge`. |
| `card.issuer_name` | The issuing bank's name. |
| `card.issuer_country` | ISO 3166-1 alpha-2, such as `SA`. |

Any card detail lite doesn't know is `null`. If you pass `store_for_future: true` and the customer already has this card stored, lite returns the instrument they already have, with its `id`.

On failure, `result.errorCode` says why, `result.error` describes it, and `result.apiErrorCode` carries lite's own code when there is one:

| `errorCode` | What happened | What to do |
| - | - | - |
| `tokenize_failed` | The card was incomplete, the fields weren't mounted, lite refused the card, or lite could not be reached. | Let the customer correct the card and try again on the same session. |
| `session_expired` | The session expired before the card was saved. | Create a new session. |
| `session_consumed` | This session already saved a card. | Create a new session for another card. |
| `session_type_unsupported` | The `client_secret` belongs to a payment session. | Create the session with `type: "tokenization"`. |
| `card_not_configured` | Cards are not enabled on the session. | Enable cards on the terminal. |

`tokenize()` doesn't throw for these: it resolves with the failure.

A session saves **one** card, whether from the secure fields or Apple Pay. A refused attempt doesn't use the session up, so the customer can retry until it expires. After a success, disable your Save button.

> [!WARNING]
>
> **Make decisions on your server.** The instrument reached your page through the customer's browser. Send only its `id` to your server, fetch the instrument from lite there, and check that its `holder_id` is the customer you're serving before you rely on its card details.

## 6. Charge the instrument (optional)

Saving a card authorizes nothing, so the card can still be declined when you charge it. A card saved without `store_for_future: true` is for one payment: charge it within about 20 minutes. There are two ways to charge an instrument.

### With the Checkout SDK

Use this when the customer confirms the final price on your page. Your server creates a normal **payment session** for the same customer with the final amount. Start the SDK with that session's `client_secret` and pay with the instrument id. The customer doesn't enter the card again, so this step needs no card fields.

```ts theme={null}
const payment = await Lite.init({ secret: paymentClientSecret });

try {
  const result = await payment.pay({ instrument_id: instrumentId });
  handlePayment(result);
} catch (error) {
  // lite refused the request or couldn't be reached. A declined card resolves instead, as a failure.
  showError('The payment could not be completed. Try again.');
}
```

`result` is the Checkout SDK's payment result, with 3D Secure handled as for a new card: see [Handle the result](https://docs.lite.sa/guides/web-sdk.md#7-handle-the-result).

### With the Payments API

A card saved with this SDK is stored as `unscheduled`, with no consent record, so charge it with `POST /payments` only while the customer is on your page, passing its id as `payment_instrument.id` with the `amount`, `currency` and the customer's `device` details. To charge a customer who isn't there, store the card with an agreement through the [instruments API](https://docs.lite.sa/guides/payment-instruments.md#store-a-card-with-an-agreement). See the [Payments API](https://docs.lite.sa/guides/payments-api.md) guide.

## 7. Clean up

When the customer leaves the page without saving, for example on a route change in a single-page app, remove the fields and the SDK:

```ts theme={null}
Object.values(fields).forEach((field) => field.destroy());
applePayButton?.destroy();
lite.destroy();
```

Destroy every field and the Apple Pay button first. `lite.destroy()` removes only lite's hidden card iframe and clears the session: fields you didn't destroy stay on the page. To save another card, create a new tokenization session and call `Lite.init` again.

## What's new in 1.1.0

* **Tokenization sessions.** `lite.tokenize()` saves the card in the secure fields without paying.
* **Save cards with Apple Pay.** On a tokenization session, the Apple Pay button saves the card and reports it on its `tokenize` event.
* **Pay with an instrument.** `lite.pay({ instrument_id })` on a payment session takes the instrument `tokenize()` returned.


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