@ozura/elements 1.2.3 β†’ 1.2.4-next.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,1445 +1,1445 @@
1
- # @ozura/elements
2
-
3
- PCI-isolated card and bank account tokenization SDK for the Ozura Vault.
4
-
5
- Card data is collected inside Ozura-hosted iframes so raw numbers never touch your JavaScript bundle, your server logs, or your network traffic. The tokenizer communicates directly with the vault using `MessageChannel` port transfers β€” the merchant page acts as a layout host only.
6
-
7
- > **πŸ“– Full documentation:** [docs.ozura.com/sdks/elements/overview](https://docs.ozura.com/sdks/elements/overview)
8
- >
9
- > The docs include step-by-step guides, interactive examples, a complete API reference, and styling walkthroughs. If you are starting a new integration, the docs are the best place to begin.
10
-
11
- ---
12
-
13
- ## Table of contents
14
-
15
- - [Full documentation](#full-documentation)
16
- - [How it works](#how-it-works)
17
- - [Installation](#installation)
18
- - [Quick start β€” React](#quick-start--react)
19
- - [Quick start β€” Vanilla JS](#quick-start--vanilla-js)
20
- - [Server setup](#server-setup)
21
- - [Session endpoint](#session-endpoint)
22
- - [Card sale endpoint](#card-sale-endpoint)
23
- - [Vanilla JS API](#vanilla-js-api)
24
- - [OzVault.create()](#ozvaultcreate)
25
- - [vault.createElement()](#vaultcreateelementtypeoptions)
26
- - [vault.createToken()](#vaultcreatetokenoptions)
27
- - [vault.createBankElement()](#vaultcreatebankelement)
28
- - [vault.createBankToken()](#vaultcreatebanktokenoptions)
29
- - [vault.reset()](#vaultreset)
30
- - [vault.destroy()](#vaultdestroy)
31
- - [vault.debugState()](#vaultdebugstate)
32
- - [OzElement events](#ozelement-events)
33
- - [React API](#react-api)
34
- - [OzElements provider](#ozelements-provider)
35
- - [OzCard](#ozcard)
36
- - [Individual field components](#individual-field-components)
37
- - [OzBankCard](#ozbankcard)
38
- - [useOzElements()](#useozelements)
39
- - [Styling](#styling)
40
- - [Per-element styles](#per-element-styles)
41
- - [Global appearance](#global-appearance)
42
- - [Custom fonts](#custom-fonts)
43
- - [Billing details](#billing-details)
44
- - [Error handling](#error-handling)
45
- - [Debug mode](#debug-mode)
46
- - [Server utilities](#server-utilities)
47
- - [Ozura class](#ozura-class)
48
- - [Route handler factories](#route-handler-factories)
49
- - [Local development](#local-development)
50
- - [Content Security Policy](#content-security-policy)
51
- - [TypeScript reference](#typescript-reference)
52
-
53
- ---
54
-
55
- ## Full documentation
56
-
57
- The README covers the most common integration patterns. The hosted docs at **[docs.ozura.com/sdks/elements](https://docs.ozura.com/sdks/elements/overview)** go deeper on every topic:
58
-
59
- | Page | URL |
60
- |---|---|
61
- | Overview | [docs.ozura.com/sdks/elements/overview](https://docs.ozura.com/sdks/elements/overview) |
62
- | Installation & setup | [docs.ozura.com/sdks/elements/installation](https://docs.ozura.com/sdks/elements/installation) |
63
- | Card elements | [docs.ozura.com/sdks/elements/card-elements](https://docs.ozura.com/sdks/elements/card-elements) |
64
- | Bank elements | [docs.ozura.com/sdks/elements/bank-elements](https://docs.ozura.com/sdks/elements/bank-elements) |
65
- | React integration | [docs.ozura.com/sdks/elements/react](https://docs.ozura.com/sdks/elements/react) |
66
- | Styling | [docs.ozura.com/sdks/elements/styling](https://docs.ozura.com/sdks/elements/styling) |
67
- | Error handling | [docs.ozura.com/sdks/elements/error-handling](https://docs.ozura.com/sdks/elements/error-handling) |
68
- | Server SDK | [docs.ozura.com/sdks/elements/server](https://docs.ozura.com/sdks/elements/server) |
69
- | API reference | [docs.ozura.com/sdks/elements/api-reference](https://docs.ozura.com/sdks/elements/api-reference) |
70
-
71
- ---
72
-
73
- ## How it works
74
-
75
- ```
76
- Merchant page
77
- β”œβ”€β”€ OzVault (manages tokenizer iframe + element iframes)
78
- β”œβ”€β”€ [hidden] tokenizer-frame.html ← Ozura origin
79
- β”œβ”€β”€ [visible] element-frame.html ← card number ─┐ MessageChannel
80
- β”œβ”€β”€ [visible] element-frame.html ← expiry β”œβ”€ port transfer
81
- └── [visible] element-frame.html ← CVV β”€β”˜
82
- ```
83
-
84
- 1. `OzVault.create()` mounts a hidden tokenizer iframe and fetches a short-lived **session key** from your server.
85
- 2. Calling `vault.createElement()` mounts a visible input iframe for each field.
86
- 3. `vault.createToken()` opens a direct `MessageChannel` between each element iframe and the tokenizer iframe. Raw values travel over those ports β€” they never pass through your JavaScript.
87
- 4. The tokenizer POSTs directly to the vault API over HTTPS and returns a token to your page.
88
-
89
- Your server only ever sees a token, never card data.
90
-
91
- ---
92
-
93
- ## Credentials
94
-
95
- | Credential | Format | Where it lives | Required for |
96
- |---|---|---|---|
97
- | **Vault pub key** | `pk_live_…` or `pk_prod_…` | Frontend env var (safe to expose) | All integrations |
98
- | **Vault API key** | `key_…` | Server env var β€” **never in the browser** | Creating sessions (all integrations) |
99
- | **Pay API key** | `ak_…` | Server env var only | OzuraPay merchants (card charging) |
100
- | **Merchant ID** | `ozu_…` | Server env var only | OzuraPay merchants (card charging) |
101
-
102
- If you are not routing payments through OzuraPay you only need the vault pub key (frontend) and vault API key (backend).
103
-
104
- ---
105
-
106
- ## Installation
107
-
108
- > πŸ“– [Installation guide](https://docs.ozura.com/sdks/elements/installation) β€” npm, yarn, CDN setup, and TypeScript configuration.
109
-
110
- ```bash
111
- npm install @ozura/elements
112
- ```
113
-
114
- React and React DOM are peer dependencies (optional β€” only needed for `@ozura/elements/react`):
115
-
116
- ```bash
117
- npm install react react-dom # if not already installed
118
- ```
119
-
120
- **Requirements:** Node β‰₯ 18, React β‰₯ 17 (React peer).
121
-
122
- ---
123
-
124
- ## Quick start β€” React
125
-
126
- > πŸ“– [React integration guide](https://docs.ozura.com/sdks/elements/react) β€” provider setup, pre-built components, hook reference, and full examples.
127
-
128
- ```tsx
129
- // 1. Wrap your checkout in <OzElements>
130
- import { OzElements, OzCard, useOzElements } from '@ozura/elements/react';
131
-
132
- function CheckoutPage() {
133
- return (
134
- <OzElements
135
- pubKey="pk_live_..."
136
- sessionUrl="/api/oz-session"
137
- >
138
- <CheckoutForm />
139
- </OzElements>
140
- );
141
- }
142
-
143
- // 2. Collect card data and tokenize
144
- function CheckoutForm() {
145
- const { createToken, reset, ready } = useOzElements();
146
-
147
- const handleSubmit = async (e: React.FormEvent) => {
148
- e.preventDefault();
149
- try {
150
- const { token, cvcSession, billing } = await createToken({
151
- billing: {
152
- firstName: 'Jane',
153
- lastName: 'Smith',
154
- email: 'jane@example.com',
155
- address: { line1: '123 Main St', city: 'Austin', state: 'TX', zip: '78701', country: 'US' },
156
- },
157
- });
158
-
159
- // Send token to your server
160
- await fetch('/api/charge', {
161
- method: 'POST',
162
- headers: { 'Content-Type': 'application/json' },
163
- body: JSON.stringify({ token, cvcSession, billing }),
164
- });
165
- } catch (err) {
166
- reset(); // clear fields so the customer can re-enter
167
- console.error(err);
168
- }
169
- };
170
-
171
- return (
172
- <form onSubmit={handleSubmit}>
173
- <OzCard onChange={(state) => console.log(state.cardBrand)} />
174
- <button type="submit" disabled={!ready}>Pay</button>
175
- </form>
176
- );
177
- }
178
- ```
179
-
180
- ---
181
-
182
- ## Quick start β€” Vanilla JS
183
-
184
- > πŸ“– [Card elements guide](https://docs.ozura.com/sdks/elements/card-elements) β€” full end-to-end example, field events, submit-button gating, and auto-advance behaviour.
185
-
186
- ```ts
187
- import { OzVault } from '@ozura/elements';
188
-
189
- // Declare state BEFORE OzVault.create(). The onReady callback fires when the
190
- // tokenizer iframe loads β€” this can happen before create() resolves because the
191
- // iframe loads concurrently with fetchWaxKey. At that moment, `vault` is still
192
- // undefined. Do not reference `vault` inside onReady.
193
- let readyCount = 0;
194
- let tokenizerIsReady = false;
195
-
196
- function checkReady() {
197
- if (readyCount === 3 && tokenizerIsReady) enablePayButton();
198
- }
199
-
200
- const vault = await OzVault.create({
201
- pubKey: 'pk_live_...',
202
- sessionUrl: '/api/oz-session',
203
- onReady: () => { tokenizerIsReady = true; checkReady(); }, // tokenizer iframe loaded
204
- });
205
-
206
- const cardNumberEl = vault.createElement('cardNumber');
207
- const expiryEl = vault.createElement('expirationDate');
208
- const cvvEl = vault.createElement('cvv');
209
-
210
- cardNumberEl.mount('#card-number');
211
- expiryEl.mount('#expiry');
212
- cvvEl.mount('#cvv');
213
-
214
- [cardNumberEl, expiryEl, cvvEl].forEach(el => {
215
- el.on('ready', () => { readyCount++; checkReady(); });
216
- });
217
-
218
- async function pay() {
219
- try {
220
- const { token, cvcSession, card } = await vault.createToken({
221
- billing: { firstName: 'Jane', lastName: 'Smith' },
222
- });
223
- // POST { token, cvcSession } to your server
224
- } catch (err) {
225
- vault.reset(); // clear fields; let customer re-enter
226
- console.error(err);
227
- }
228
- }
229
-
230
- // Clean up when done
231
- vault.destroy();
232
- ```
233
-
234
- > **Gating the submit button in vanilla JS** requires checking both `vault.isReady` (tokenizer iframe loaded) **and** every element's `ready` event (input iframes loaded). In React, `useOzElements().ready` combines both automatically.
235
-
236
- ---
237
-
238
- ## Server setup
239
-
240
- > πŸ“– [Server SDK guide](https://docs.ozura.com/sdks/elements/server) β€” session creation, card sale handler factories, IP extraction, and manual implementation patterns.
241
-
242
- ### Session endpoint
243
-
244
- The SDK calls your session endpoint whenever it needs to start or refresh a payment session. Your backend creates a short-lived session key from the vault using your vault API key β€” the key never touches the browser.
245
-
246
- **Next.js App Router (recommended)**
247
-
248
- ```ts
249
- // app/api/oz-session/route.ts
250
- import { Ozura, createSessionHandler } from '@ozura/elements/server';
251
-
252
- const ozura = new Ozura({ vaultKey: process.env.VAULT_API_KEY! });
253
-
254
- export const POST = createSessionHandler(ozura);
255
- ```
256
-
257
- **Express**
258
-
259
- ```ts
260
- import express from 'express';
261
- import { Ozura, createSessionMiddleware } from '@ozura/elements/server';
262
-
263
- const ozura = new Ozura({ vaultKey: process.env.VAULT_API_KEY! });
264
- const app = express();
265
-
266
- app.use(express.json());
267
- app.post('/api/oz-session', createSessionMiddleware(ozura));
268
- ```
269
-
270
- **Manual implementation** (for custom logic or auth checks)
271
-
272
- ```ts
273
- // POST /api/oz-session
274
- const { sessionId } = await req.json();
275
- const { sessionKey } = await ozura.createSession({ sessionId });
276
- return Response.json({ sessionKey });
277
- ```
278
-
279
- ### Card sale endpoint
280
-
281
- After `createToken()` resolves on the frontend, POST `{ token, cvcSession, billing }` to your server to charge the card.
282
-
283
- **Next.js App Router**
284
-
285
- ```ts
286
- // app/api/charge/route.ts
287
- import { Ozura, createCardSaleHandler } from '@ozura/elements/server';
288
-
289
- const ozura = new Ozura({ merchantId: '...', apiKey: '...', vaultKey: '...' });
290
-
291
- export const POST = createCardSaleHandler(ozura, {
292
- getAmount: async (body) => {
293
- const order = await db.orders.findById(body.orderId as string);
294
- return order.total; // decimal string, e.g. "49.00"
295
- },
296
- // getCurrency: async (body) => 'USD', // optional, defaults to "USD"
297
- });
298
- ```
299
-
300
- **Express**
301
-
302
- ```ts
303
- app.post('/api/charge', createCardSaleMiddleware(ozura, {
304
- getAmount: async (body) => {
305
- const order = await db.orders.findById(body.orderId as string);
306
- return order.total; // decimal string, e.g. "49.00"
307
- },
308
- // getCurrency: async (body) => 'USD', // optional, defaults to "USD"
309
- }));
310
- ```
311
-
312
- > `createCardSaleMiddleware` always terminates the request β€” it does not call `next()` and cannot be composed in a middleware chain.
313
-
314
- **Manual implementation**
315
-
316
- ```ts
317
- const { token, cvcSession, billing } = await req.json();
318
- const result = await ozura.cardSale({
319
- token,
320
- cvcSession,
321
- amount: '49.00',
322
- currency: 'USD',
323
- billing,
324
- // Take the first IP from the forwarded-for chain; fall back to socket address.
325
- // req is a Fetch API Request (Next.js App Router / Vercel Edge).
326
- clientIpAddress: req.headers.get('x-forwarded-for')?.split(',')[0].trim()
327
- ?? req.headers.get('x-real-ip')
328
- ?? '',
329
- });
330
- // result.transactionId, result.amount, result.cardLastFour, result.cardBrand
331
- ```
332
-
333
- ---
334
-
335
- ## Vanilla JS API
336
-
337
- > πŸ“– [API reference](https://docs.ozura.com/sdks/elements/api-reference) β€” complete type definitions and method signatures for every class.
338
-
339
- ### OzVault.create(options)
340
-
341
- ```ts
342
- const vault = await OzVault.create(options: VaultOptions): Promise<OzVault>
343
- ```
344
-
345
- Mounts the hidden tokenizer iframe and fetches a session key concurrently. Both happen in parallel β€” by the time `create()` resolves, the iframe may already be ready.
346
-
347
- | Option | Type | Required | Description |
348
- |---|---|---|---|
349
- | `pubKey` | `string` | βœ“ | Your public key from the Ozura admin. |
350
- | `sessionUrl` | `string` | βœ“ ΒΉ | URL of your session endpoint. The simplest option β€” pass the path and the SDK handles everything. |
351
- | `getSessionKey` | `(sessionId: string) => Promise<string>` | βœ“ ΒΉ | Custom async callback for obtaining the session key. Use when you need custom headers or auth logic. |
352
- | `fetchWaxKey` | `(sessionId: string) => Promise<string>` | βœ“ ΒΉ | **Deprecated.** Use `sessionUrl` or `getSessionKey` instead. |
353
- | `frameBaseUrl` | `string` | β€” | Base URL for iframe assets. Defaults to production CDN. Override for local dev (see [Local development](#local-development)). |
354
- | `fonts` | `FontSource[]` | β€” | Custom fonts to inject into all element iframes. |
355
- | `appearance` | `Appearance` | β€” | Global theme and variable overrides. |
356
- | `loadTimeoutMs` | `number` | β€” | Tokenizer iframe load timeout in ms. Default: `10000`. Only takes effect when `onLoadError` is also provided. |
357
- | `onLoadError` | `() => void` | β€” | Called if the tokenizer iframe fails to load within `loadTimeoutMs`. |
358
- | `onSessionRefresh` | `() => void` | β€” | Called when the SDK silently refreshes the session mid-tokenization (key expired or consumed). |
359
- | `onReady` | `() => void` | β€” | Called once when the tokenizer iframe has loaded and is ready. Use in vanilla JS to re-check submit-button readiness. In React, `useOzElements().ready` handles this automatically. |
360
- | `sessionLimit` | `number` | β€” | Card submissions allowed per session before the SDK refreshes automatically. Default: `3`. Must match `sessionLimit` in your server-side `createSession` call. |
361
- | `debug` | `boolean` | β€” | Enables structured `[OzVault]`-prefixed `console.log` output at every lifecycle event. Safe to use in production β€” no sensitive data is ever logged. Default: `false`. See [Debug mode](#debug-mode) for details. |
362
-
363
- ΒΉ Exactly one of `sessionUrl`, `getSessionKey`, or `fetchWaxKey` is required.
364
-
365
- Throws `OzError` if the session fetch rejects, returns an empty string, or returns a non-string value.
366
-
367
- > **`sessionUrl` retry behavior:** The SDK enforces a **10-second per-attempt timeout** and retries **once after 750 ms on pure network failures** (connection refused, DNS failure, offline). HTTP 4xx/5xx errors are never retried β€” they signal endpoint misconfiguration or invalid credentials and require developer action. Errors are thrown as `OzError` instances so you can inspect `err.errorCode`.
368
-
369
- ---
370
-
371
- ### vault.createElement(type, options?)
372
-
373
- ```ts
374
- vault.createElement(type: ElementType, options?: ElementOptions): OzElement
375
- ```
376
-
377
- Creates and returns an element iframe. Call `.mount(target)` to attach it to the DOM.
378
-
379
- `ElementType`: `'cardNumber'` | `'cvv'` | `'expirationDate'`
380
-
381
- ```ts
382
- const cardEl = vault.createElement('cardNumber', {
383
- placeholder: '1234 5678 9012 3456',
384
- style: {
385
- base: { color: '#1a1a1a', fontSize: '16px' },
386
- focus: { borderColor: '#6366f1' },
387
- invalid: { color: '#dc2626' },
388
- complete: { color: '#16a34a' },
389
- },
390
- });
391
-
392
- cardEl.mount('#card-number-container');
393
- ```
394
-
395
- `ElementOptions`:
396
-
397
- | Option | Type | Description |
398
- |---|---|---|
399
- | `style` | `ElementStyleConfig` | Per-state style overrides. See [Styling](#styling). |
400
- | `placeholder` | `string` | Placeholder text (max 100 characters). |
401
- | `disabled` | `boolean` | Disables the input. |
402
- | `loadTimeoutMs` | `number` | Iframe load timeout in ms. Default: `10000`. |
403
-
404
- **OzElement methods:**
405
-
406
- | Method | Description |
407
- |---|---|
408
- | `.mount(target)` | Mount the iframe. Accepts a CSS selector string or `HTMLElement`. |
409
- | `.unmount()` | Remove the iframe from the DOM. The element can be re-mounted. |
410
- | `.destroy()` | Permanently destroy the element. Cannot be re-mounted. |
411
- | `.update(options)` | Update placeholder, style, or disabled state without re-mounting. **Merge semantics** β€” only provided keys are applied; omitted keys retain their values. To reset a property, pass it with an empty string (e.g. `{ style: { base: { color: '' } } }`). To fully reset all styles, destroy and recreate the element. |
412
- | `.clear()` | Clear the field value. |
413
- | `.focus()` | Programmatically focus the input. |
414
- | `.blur()` | Programmatically blur the input. |
415
- | `.on(event, fn)` | Subscribe to an event. Returns `this` for chaining. |
416
- | `.off(event, fn)` | Remove an event handler. |
417
- | `.once(event, fn)` | Subscribe for a single invocation. |
418
- | `.isReady` | `true` once the iframe has loaded and signalled ready. |
419
-
420
- ---
421
-
422
- ### vault.createToken(options?)
423
-
424
- ```ts
425
- vault.createToken(options?: TokenizeOptions): Promise<TokenResponse>
426
- ```
427
-
428
- Tokenizes all mounted and ready card elements. Raw values travel directly from element iframes to the tokenizer iframe via `MessageChannel` β€” they never pass through your page's JavaScript.
429
-
430
- Returns a `TokenResponse`:
431
-
432
- ```ts
433
- interface TokenResponse {
434
- token: string; // Vault token β€” pass to cardSale
435
- cvcSession: string; // CVC session β€” always present; pass to cardSale
436
- card?: { // Card metadata β€” present when vault returns all four fields
437
- last4: string; // e.g. "4242"
438
- brand: string; // e.g. "visa"
439
- expMonth: string; // e.g. "09"
440
- expYear: string; // e.g. "2027"
441
- };
442
- billing?: BillingDetails; // Normalized billing β€” only present if billing was passed in
443
- }
444
- ```
445
-
446
- `TokenizeOptions`:
447
-
448
- | Option | Type | Description |
449
- |---|---|---|
450
- | `billing` | `BillingDetails` | Validated and normalized billing details. Returned in `TokenResponse.billing`. |
451
- | `firstName` | `string` | **Deprecated.** Pass inside `billing` instead. |
452
- | `lastName` | `string` | **Deprecated.** Pass inside `billing` instead. |
453
-
454
- Throws `OzError` if:
455
- - The vault is not ready (`errorCode: 'unknown'`)
456
- - A tokenization is already in progress
457
- - Billing validation fails (`errorCode: 'validation'`)
458
- - No elements are mounted
459
- - The vault returns an error (`errorCode` reflects the HTTP status)
460
- - The request times out after 30 seconds (`errorCode: 'timeout'`) β€” this timeout is separate from `loadTimeoutMs` and is not configurable
461
-
462
- **`vault.tokenizeCount`**
463
-
464
- ```ts
465
- vault.tokenizeCount: number // read-only getter
466
- ```
467
-
468
- Returns the number of successful `createToken()` / `createBankToken()` calls made in the current session. Resets to `0` each time the session is refreshed (proactively or reactively). Use this in vanilla JS to display "attempts remaining" feedback or gate the submit button:
469
-
470
- ```ts
471
- const MAX = 3; // matches maxTokenizeCalls
472
- const remaining = MAX - vault.tokenizeCount;
473
- payButton.textContent = `Pay (${remaining} attempt${remaining === 1 ? '' : 's'} remaining)`;
474
- ```
475
-
476
- In React, use `tokenizeCount` from `useOzElements()` instead β€” it is a reactive state value and will trigger re-renders automatically.
477
-
478
- ---
479
-
480
- ### vault.createBankElement()
481
-
482
- ```ts
483
- vault.createBankElement(type: BankElementType, options?: ElementOptions): OzElement
484
- ```
485
-
486
- Creates a bank account element. `BankElementType`: `'accountNumber'` | `'routingNumber'`.
487
-
488
- ```ts
489
- const accountEl = vault.createBankElement('accountNumber');
490
- const routingEl = vault.createBankElement('routingNumber');
491
- accountEl.mount('#account-number');
492
- routingEl.mount('#routing-number');
493
- ```
494
-
495
- ---
496
-
497
- ### vault.createBankToken(options)
498
-
499
- ```ts
500
- vault.createBankToken(options: BankTokenizeOptions): Promise<BankTokenResponse>
501
- ```
502
-
503
- Tokenizes the mounted `accountNumber` and `routingNumber` elements. Both must be mounted and ready.
504
-
505
- ```ts
506
- interface BankTokenizeOptions {
507
- firstName: string; // Account holder first name (required, max 50 chars)
508
- lastName: string; // Account holder last name (required, max 50 chars)
509
- }
510
-
511
- interface BankTokenResponse {
512
- token: string;
513
- bank?: {
514
- last4: string; // Last 4 digits of account number
515
- routingNumberLast4: string;
516
- };
517
- }
518
- ```
519
-
520
- > **Note:** OzuraPay does not currently support bank account payments. Use the bank token with your own ACH processor. Bank tokens can be passed to any ACH-capable processor directly.
521
-
522
- > **Card tokens and processors:** Card tokenization returns a `cvcSession` alongside the `token`. OzuraPay's charge API requires `cvcSession`. If you are routing to a non-Ozura processor, pass the `token` directly β€” your processor's documentation will tell you whether a CVC session token is required.
523
-
524
- ---
525
-
526
- ### vault.destroy()
527
-
528
- ```ts
529
- vault.destroy(): void
530
- ```
531
-
532
- Tears down the vault: removes all element and tokenizer iframes, clears the `message` event listener, rejects any pending `createToken()` / `createBankToken()` promises, and cancels active timeout handles. Call this when the checkout component unmounts.
533
-
534
- ```ts
535
- // React useEffect cleanup β€” the cancel flag prevents a vault from leaking
536
- // if the component unmounts before OzVault.create() resolves.
537
- useEffect(() => {
538
- let cancelled = false;
539
- let vault: OzVault | null = null;
540
- OzVault.create(options).then(v => {
541
- if (cancelled) { v.destroy(); return; }
542
- vault = v;
543
- });
544
- return () => {
545
- cancelled = true;
546
- vault?.destroy();
547
- };
548
- }, []);
549
- ```
550
-
551
- ---
552
-
553
- ### vault.reset()
554
-
555
- ```ts
556
- vault.reset(): void
557
- ```
558
-
559
- Clears all mounted card and bank element fields without destroying the vault, refreshing the session, or resetting the tokenization budget. Call this after a declined payment to let the customer re-enter their card details on the same checkout screen.
560
-
561
- The session key, its remaining budget, and all iframes are fully preserved β€” no network calls are made.
562
-
563
- **Session model:** One session covers the full checkout. The default `sessionLimit: 3` is enough for two declines and a final attempt. Use `vault.reset()` between declines β€” not `vault.destroy()` + recreate, which would waste the remaining budget and cause iframe flicker.
564
-
565
- ```ts
566
- try {
567
- const { token, cvcSession } = await vault.createToken({ billing });
568
- await fetch('/api/charge', {
569
- method: 'POST',
570
- headers: { 'Content-Type': 'application/json' },
571
- body: JSON.stringify({ token, cvcSession }),
572
- });
573
- } catch (err) {
574
- vault.reset(); // clear fields; let customer re-enter
575
- showError(err instanceof OzError ? err.message : 'Payment failed.');
576
- }
577
- ```
578
-
579
- ---
580
-
581
- ### vault.debugState()
582
-
583
- ```ts
584
- vault.debugState(): Record<string, unknown>
585
- ```
586
-
587
- Returns a structured snapshot of the vault's internal state. Always available regardless of whether `debug: true` is set. Useful for attaching to support tickets or dumping on error.
588
-
589
- ```ts
590
- console.log(vault.debugState());
591
- // {
592
- // vaultId: 'vault_abc12...',
593
- // isReady: true,
594
- // tokenizing: null,
595
- // destroyed: false,
596
- // waxKeyPresent: true,
597
- // tokenizeSuccessCount: 1,
598
- // maxTokenizeCalls: 3,
599
- // resetCount: 0,
600
- // elements: ['cardNumber', 'expirationDate', 'cvv'],
601
- // bankElements: [],
602
- // completionState: { 'a1b2c3d4': true, 'e5f6a7b8': true, '...' : false },
603
- // pendingTokenizations: 0,
604
- // pendingBankTokenizations: 0,
605
- // }
606
- ```
607
-
608
- No sensitive data is returned: wax keys, tokens, CVC sessions, and billing fields are never included.
609
-
610
- ---
611
-
612
- ### OzElement events
613
-
614
- ```ts
615
- element.on('change', (event: ElementChangeEvent) => { ... });
616
- element.on('focus', () => { ... });
617
- element.on('blur', () => { ... });
618
- element.on('ready', () => { ... });
619
- element.on('loaderror', (payload: { elementType: string; error: string }) => { ... });
620
- ```
621
-
622
- `ElementChangeEvent`:
623
-
624
- | Field | Type | Description |
625
- |---|---|---|
626
- | `empty` | `boolean` | `true` when the field is empty. |
627
- | `complete` | `boolean` | `true` when the field has enough digits to be complete. |
628
- | `valid` | `boolean` | `true` when the value passes all validation (Luhn, expiry date, etc.). |
629
- | `error` | `string \| undefined` | User-facing error message when `valid` is `false` and the field has been touched. |
630
- | `cardBrand` | `string \| undefined` | Detected brand β€” only on `cardNumber` fields (e.g. `"visa"`, `"amex"`). |
631
- | `month` | `string \| undefined` | Parsed 2-digit month β€” only on `expirationDate` fields. |
632
- | `year` | `string \| undefined` | Parsed 2-digit year β€” only on `expirationDate` fields. |
633
-
634
- > **Expiry data and PCI scope:** The expiry `onChange` event delivers parsed `month` and `year` to your handler for display purposes (e.g. "Card expires MM/YY"). These are not PANs or CVVs, but they are cardholder data. If your PCI scope requires zero cardholder data on the merchant page, do not read, log, or store these fields.
635
-
636
- Auto-advance is built in: the vault automatically moves focus from card number β†’ expiry β†’ CVV when each field completes. No additional code required.
637
-
638
- ---
639
-
640
- ## React API
641
-
642
- > πŸ“– [React guide](https://docs.ozura.com/sdks/elements/react) β€” `OzElements` provider, `useOzElements` hook, pre-built `OzCard` and `OzBankCard` components, and StrictMode behaviour.
643
-
644
- ### OzElements provider
645
-
646
- ```tsx
647
- import { OzElements } from '@ozura/elements/react';
648
-
649
- <OzElements
650
- pubKey="pk_live_..."
651
- sessionUrl="/api/oz-session"
652
- appearance={{ theme: 'flat', variables: { colorPrimary: '#6366f1' } }}
653
- onLoadError={() => setPaymentUnavailable(true)}
654
- >
655
- {children}
656
- </OzElements>
657
- ```
658
-
659
- All `VaultOptions` are accepted as props. The provider creates a single `OzVault` instance and destroys it on unmount.
660
-
661
- > **Prop changes and vault lifecycle:** Changing `pubKey`, `sessionUrl`, `frameBaseUrl`, `loadTimeoutMs`, `appearance`, `fonts`, or `sessionLimit` destroys the current vault and creates a new one β€” all field iframes will remount. Changing `getSessionKey`, `fetchWaxKey`, `onLoadError`, `onSessionRefresh`, or `onReady` updates the callback in place via refs without recreating the vault.
662
-
663
- > **One card form per provider:** A vault holds one element per field type (`cardNumber`, `expiry`, `cvv`, etc.). Rendering two `<OzCard>` components under the same `<OzElements>` provider will cause the second to silently replace the first's iframes, breaking the first form. If you genuinely need two independent card forms on the same page, wrap each in its own `<OzElements>` provider with separate `pubKey` / `sessionUrl` configurations.
664
-
665
- ---
666
-
667
- ### OzCard
668
-
669
- Drop-in combined card component. Renders card number, expiry, and CVV with a configurable layout.
670
-
671
- ```tsx
672
- import { OzCard } from '@ozura/elements/react';
673
-
674
- <OzCard
675
- layout="default" // "default" (number on top, expiry+CVV below) | "rows" (stacked)
676
- onChange={(state) => {
677
- // state.complete β€” all three fields complete + valid
678
- // state.cardBrand β€” detected brand
679
- // state.error β€” first error across all fields
680
- // state.fields β€” per-field ElementChangeEvent objects
681
- }}
682
- onReady={() => console.log('all card fields loaded')}
683
- disabled={isSubmitting}
684
- labels={{ cardNumber: 'Card Number', expiry: 'Expiry', cvv: 'CVV' }}
685
- placeholders={{ cardNumber: '1234 5678 9012 3456', expiry: 'MM/YY', cvv: 'Β·Β·Β·' }}
686
- />
687
- ```
688
-
689
- `OzCardProps` (full):
690
-
691
- | Prop | Type | Description |
692
- |---|---|---|
693
- | `layout` | `'default' \| 'rows'` | `'default'`: number full-width, expiry+CVV side by side. `'rows'`: all stacked. |
694
- | `gap` | `number \| string` | Gap between fields. Default: `8` (px). |
695
- | `style` | `ElementStyleConfig` | Shared style applied to all three inputs. |
696
- | `styles` | `{ cardNumber?, expiry?, cvv? }` | Per-field overrides merged on top of `style`. |
697
- | `classNames` | `{ cardNumber?, expiry?, cvv?, row? }` | CSS class names for field wrappers and the expiry+CVV row. |
698
- | `labels` | `{ cardNumber?, expiry?, cvv? }` | Optional label text above each field. |
699
- | `labelStyle` | `React.CSSProperties` | Style applied to all `<label>` elements. |
700
- | `labelClassName` | `string` | Class applied to all `<label>` elements. |
701
- | `placeholders` | `{ cardNumber?, expiry?, cvv? }` | Custom placeholder text per field. |
702
- | `hideErrors` | `boolean` | Suppress the built-in error display. Handle via `onChange`. |
703
- | `errorStyle` | `React.CSSProperties` | Style for the built-in error container. |
704
- | `errorClassName` | `string` | Class for the built-in error container. |
705
- | `renderError` | `(error: string) => ReactNode` | Custom error renderer. |
706
- | `onChange` | `(state: OzCardState) => void` | Fires on any field change. |
707
- | `onReady` | `() => void` | Fires once all three iframes have loaded. |
708
- | `onFocus` | `(field: 'cardNumber' \| 'expiry' \| 'cvv') => void` | |
709
- | `onBlur` | `(field: 'cardNumber' \| 'expiry' \| 'cvv') => void` | |
710
- | `disabled` | `boolean` | Disable all inputs. |
711
- | `className` | `string` | Class for the outer wrapper. |
712
-
713
- ---
714
-
715
- ### Individual field components
716
-
717
- For custom layouts where `OzCard` is too opinionated:
718
-
719
- ```tsx
720
- import { OzCardNumber, OzExpiry, OzCvv } from '@ozura/elements/react';
721
-
722
- <OzCardNumber onChange={handleChange} placeholder="Card number" />
723
- <OzExpiry onChange={handleChange} />
724
- <OzCvv onChange={handleChange} />
725
- ```
726
-
727
- All accept `OzFieldProps`:
728
-
729
- | Prop | Type | Description |
730
- |---|---|---|
731
- | `style` | `ElementStyleConfig` | Input styles. |
732
- | `placeholder` | `string` | Placeholder text. |
733
- | `disabled` | `boolean` | Disables the input. |
734
- | `loadTimeoutMs` | `number` | Iframe load timeout in ms. |
735
- | `onChange` | `(event: ElementChangeEvent) => void` | |
736
- | `onFocus` | `() => void` | |
737
- | `onBlur` | `() => void` | |
738
- | `onReady` | `() => void` | |
739
- | `onLoadError` | `(error: string) => void` | |
740
- | `className` | `string` | Class for the outer wrapper div. |
741
-
742
- ---
743
-
744
- ### OzBankCard
745
-
746
- ```tsx
747
- import { OzBankCard } from '@ozura/elements/react';
748
-
749
- <OzBankCard
750
- onChange={(state) => {
751
- // state.complete, state.error, state.fields.accountNumber, state.fields.routingNumber
752
- }}
753
- labels={{ accountNumber: 'Account Number', routingNumber: 'Routing Number' }}
754
- />
755
- ```
756
-
757
- Or use individual bank components:
758
-
759
- ```tsx
760
- import { OzBankAccountNumber, OzBankRoutingNumber } from '@ozura/elements/react';
761
-
762
- <OzBankAccountNumber onChange={handleChange} />
763
- <OzBankRoutingNumber onChange={handleChange} />
764
- ```
765
-
766
- ---
767
-
768
- ### useOzElements()
769
-
770
- ```ts
771
- const { createToken, createBankToken, reset, ready, initError, tokenizeCount } = useOzElements();
772
- ```
773
-
774
- Must be called from inside an `<OzElements>` provider tree.
775
-
776
- | Return | Type | Description |
777
- |---|---|---|
778
- | `createToken` | `(options?: TokenizeOptions) => Promise<TokenResponse>` | Tokenize mounted card elements. |
779
- | `createBankToken` | `(options: BankTokenizeOptions) => Promise<BankTokenResponse>` | Tokenize mounted bank elements. |
780
- | `reset` | `() => void` | Clear all mounted element fields without destroying the vault or refreshing the session. Call after a declined payment so the customer can re-enter their details. |
781
- | `ready` | `boolean` | `true` when the tokenizer **and** all mounted element iframes are ready. Gate your submit button on this. See note below. |
782
- | `initError` | `Error \| null` | Non-null if `OzVault.create()` failed (e.g. session endpoint unreachable). Render a fallback UI. |
783
- | `tokenizeCount` | `number` | Number of successful tokenizations in the current session. Resets on session refresh or provider re-init. Useful for tracking calls against `sessionLimit`. |
784
-
785
- > **`ready` vs `vault.isReady`:** `ready` from `useOzElements()` is a composite β€” it combines `vault.isReady` (tokenizer loaded) with element readiness (all mounted input iframes loaded). `vault.isReady` alone is insufficient for gating a submit button. Always use `ready` from `useOzElements()` in React.
786
-
787
- ---
788
-
789
- ## Vue API
790
-
791
- > πŸ“– Vue 3 integration using the Composition API. Requires `vue >= 3.3`. No `.vue` SFC files needed in your setup β€” components work with `<script setup>` or the Options API.
792
-
793
- ### Installation
794
-
795
- npm install @ozura/elements vue
796
-
797
- ### Quick start
798
-
799
- `useOzElements()` calls Vue's `inject()` under the hood, so it must be called from a **child** of `<OzElements>`, not from the same component that renders it. Use two components β€” an outer wrapper that provides `<OzElements>`, and an inner form component that calls the composable:
800
-
801
- **CheckoutPage.vue** β€” renders the provider
802
-
803
- <script setup lang="ts">
804
- import { OzElements } from '@ozura/elements/vue';
805
- import CheckoutForm from './CheckoutForm.vue';
806
- </script>
807
-
808
- <template>
809
- <OzElements pub-key="pk_live_..." session-url="/api/oz-session">
810
- <CheckoutForm />
811
- </OzElements>
812
- </template>
813
-
814
- **CheckoutForm.vue** β€” child component, calls the composable
815
-
816
- <script setup lang="ts">
817
- import { OzCardNumber, OzExpiry, OzCvv, useOzElements } from '@ozura/elements/vue';
818
-
819
- const { createToken, ready } = useOzElements();
820
-
821
- async function handlePay() {
822
- const { token, cvcSession } = await createToken({
823
- billing: { firstName: 'Jane', lastName: 'Doe' },
824
- });
825
- // send token to your backend
826
- }
827
- </script>
828
-
829
- <template>
830
- <OzCardNumber @change="(e) => console.log(e.cardBrand)" />
831
- <OzExpiry />
832
- <OzCvv />
833
- <button :disabled="!ready" @click="handlePay">Pay</button>
834
- </template>
835
-
836
- ### Individual fields
837
-
838
- | Component | Element type |
839
- |---|---|
840
- | `<OzCardNumber>` | Card number |
841
- | `<OzExpiry>` | Expiry date |
842
- | `<OzCvv>` | CVV / CVC |
843
- | `<OzBankAccountNumber>` | Bank account number |
844
- | `<OzBankRoutingNumber>` | Bank routing number |
845
-
846
- ### `<OzElements>` props
847
-
848
- | Prop | Type | Description |
849
- |---|---|---|
850
- | `pubKey` | `string` | **Required.** System public key from Ozura admin. |
851
- | `sessionUrl` | `string` | URL of your backend session endpoint (simplest path). |
852
- | `getSessionKey` | `(sessionId: string) => Promise<string>` | Custom async function for session key. Use instead of `sessionUrl` when you need custom headers or auth. |
853
- | `frameBaseUrl` | `string` | Override the default frame host (`elements.ozura.com`). |
854
- | `fonts` | `FontSource[]` | Custom fonts injected into element iframes. |
855
- | `appearance` | `Appearance` | Global theme and variable overrides applied to all elements. |
856
- | `loadTimeoutMs` | `number` | Iframe load timeout in ms. Default: 10 000. |
857
- | `debug` | `boolean` | Enable structured `[OzVault]` debug logging. Default: `false`. |
858
-
859
- **Event:** `@ready` β€” emitted once when the vault and all mounted field iframes are ready.
860
-
861
- ### `useOzElements()` return values
862
-
863
- | Value | Type | Description |
864
- |---|---|---|
865
- | `createToken` | `(options?: TokenizeOptions) => Promise<TokenResponse>` | Tokenize mounted card fields. |
866
- | `createBankToken` | `(options?: BankTokenizeOptions) => Promise<BankTokenResponse>` | Tokenize mounted bank fields. |
867
- | `ready` | `ComputedRef<boolean>` | `true` when vault and all field iframes are ready. Gate your submit button on this. |
868
- | `initError` | `Ref<Error \| null>` | Non-null if `OzVault.create()` failed. Render a fallback UI. |
869
- | `tokenizeCount` | `Ref<number>` | Successful tokenizations in the current session. Resets on session refresh. |
870
- | `reset` | `() => void` | Clear all fields without destroying the vault. Call after a declined payment. |
871
-
872
- ### Field props and events
873
-
874
- All five field components share the same props and emits:
875
-
876
- **Props:**
877
-
878
- | Prop | Type | Description |
879
- |---|---|---|
880
- | `placeholder` | `string` | Override the default placeholder text. |
881
- | `disabled` | `boolean` | Disable the input. |
882
- | `style` | `ElementStyleConfig` | CSS-in-JS style object applied to the inner input. See [Styling](#styling). |
883
-
884
- **Emits:**
885
-
886
- | Event | Payload | Description |
887
- |---|---|---|
888
- | `@change` | `ElementChangeEvent` | Fires on every keystroke with validation state and metadata. |
889
- | `@focus` | `void` | Fires when the field gains focus. |
890
- | `@blur` | `void` | Fires when the field loses focus. |
891
-
892
- ---
893
-
894
- ## Styling
895
-
896
- > πŸ“– [Styling guide](https://docs.ozura.com/sdks/elements/styling) β€” full property allowlist, theme variables, `appearance` options, custom fonts, and `var()` limitations.
897
-
898
- ### Per-element styles
899
-
900
- Styles apply inside each iframe's `<input>` element. Only an explicit allowlist of CSS properties is accepted (typography, spacing, borders, box-shadow, cursor, transitions). Values containing `url()`, `var()`, `expression()`, `javascript:`, or CSS breakout characters are blocked on both the SDK and iframe sides. Use literal values instead of CSS custom properties (`var(--token)` is rejected). When a value is stripped, the browser falls back to the element's default (unstyled) appearance for that property β€” the failure is silent with no error or console warning. Resolve design tokens to literal values before passing them in.
901
-
902
- ```ts
903
- const style: ElementStyleConfig = {
904
- base: {
905
- color: '#1a1a1a',
906
- fontSize: '16px',
907
- fontFamily: '"Inter", sans-serif',
908
- padding: '10px 12px',
909
- backgroundColor: '#ffffff',
910
- borderRadius: '6px',
911
- border: '1px solid #d1d5db',
912
- },
913
- focus: {
914
- borderColor: '#6366f1',
915
- boxShadow: '0 0 0 3px rgba(99,102,241,0.15)',
916
- outline: 'none',
917
- },
918
- invalid: {
919
- borderColor: '#ef4444',
920
- color: '#dc2626',
921
- },
922
- complete: {
923
- borderColor: '#22c55e',
924
- },
925
- placeholder: {
926
- color: '#9ca3af',
927
- },
928
- };
929
- ```
930
-
931
- State precedence: `placeholder` applies to the `::placeholder` pseudo-element. `focus`, `invalid`, and `complete` merge on top of `base`.
932
-
933
- ### Global appearance
934
-
935
- Apply a preset theme and/or variable overrides to all elements at once:
936
-
937
- ```ts
938
- // OzVault.create
939
- const vault = await OzVault.create({
940
- pubKey: '...',
941
- sessionUrl: '/api/oz-session',
942
- appearance: {
943
- theme: 'flat', // 'default' | 'night' | 'flat'
944
- variables: {
945
- colorText: '#1a1a1a',
946
- colorBackground: '#ffffff',
947
- colorPrimary: '#6366f1', // focus caret + color
948
- colorDanger: '#dc2626', // invalid state
949
- colorSuccess: '#16a34a', // complete state
950
- colorPlaceholder: '#9ca3af',
951
- fontFamily: '"Inter", sans-serif',
952
- fontSize: '15px',
953
- fontWeight: '400',
954
- padding: '10px 14px',
955
- letterSpacing: '0.01em',
956
- },
957
- },
958
- });
959
-
960
- // React provider
961
- <OzElements pubKey="..." sessionUrl="..." appearance={{ theme: 'night' }}>
962
- ```
963
-
964
- Per-element `style` takes precedence over `appearance` variables.
965
-
966
- > **`appearance: {}` is not "no theme":** Passing `appearance: {}` or `appearance: { variables: { ... } }` without a `theme` key applies the `'default'` preset as a base. To render elements with no preset styling, omit `appearance` entirely and use per-element `style` overrides.
967
- >
968
- > | `appearance` value | Result |
969
- > |---|---|
970
- > | *(omitted entirely)* | No preset β€” element uses minimal built-in defaults |
971
- > | `{}` | Equivalent to `{ theme: 'default' }` β€” full default theme applied |
972
- > | `{ theme: 'night' }` | Night theme |
973
- > | `{ variables: { colorText: '#333' } }` | Default theme + variable overrides |
974
-
975
- ### Custom fonts
976
-
977
- Fonts are injected into each iframe so they render inside the input fields:
978
-
979
- ```ts
980
- fonts: [
981
- // Google Fonts or any HTTPS CSS URL
982
- { cssSrc: 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500&display=swap' },
983
-
984
- // Custom @font-face
985
- {
986
- family: 'BrandFont',
987
- src: 'url(https://cdn.example.com/brand-font.woff2)',
988
- weight: '400',
989
- style: 'normal',
990
- display: 'swap',
991
- },
992
- ]
993
- ```
994
-
995
- Font `src` values must start with `url(https://...)`. HTTP and data URIs are rejected.
996
-
997
- ---
998
-
999
- ## Billing details
1000
-
1001
- ```ts
1002
- interface BillingDetails {
1003
- firstName: string; // 1–50 characters
1004
- lastName: string; // 1–50 characters
1005
- email?: string; // Valid email, max 50 characters
1006
- phone?: string; // E.164 format, e.g. "+15551234567", max 50 characters
1007
- address?: {
1008
- line1: string; // 1–50 characters
1009
- line2?: string; // Optional, omitted from cardSale if blank
1010
- city: string; // 1–50 characters
1011
- state: string; // For US/CA: normalized to 2-letter abbreviation
1012
- zip: string; // 1–50 characters
1013
- country: string; // ISO 3166-1 alpha-2, e.g. "US"
1014
- };
1015
- }
1016
- ```
1017
-
1018
- Billing is validated and normalized by both `vault.createToken()` and the server-side handler factories. `TokenResponse.billing` contains the normalized result ready to spread into a `cardSale` call.
1019
-
1020
- ---
1021
-
1022
- ## Error handling
1023
-
1024
- > πŸ“– [Error handling guide](https://docs.ozura.com/sdks/elements/error-handling) β€” `OzError` fields, every `errorCode` value, retry guidance, and session expiry behaviour.
1025
-
1026
- All SDK errors are instances of `OzError`:
1027
-
1028
- ```ts
1029
- import { OzError } from '@ozura/elements';
1030
-
1031
- try {
1032
- const { token } = await vault.createToken({ billing });
1033
- } catch (err) {
1034
- if (err instanceof OzError) {
1035
- switch (err.errorCode) {
1036
- case 'network': // Connection failure β€” show retry UI
1037
- case 'timeout': // 30s deadline exceeded β€” safe to retry
1038
- case 'server': // 5xx from vault β€” transient, safe to retry
1039
- if (err.retryable) showRetryPrompt();
1040
- break;
1041
-
1042
- case 'auth': // Bad pub key / API key β€” configuration issue
1043
- case 'validation': // Bad card data β€” show field-level error
1044
- case 'config': // frameBaseUrl not in permitted allowlist
1045
- case 'unknown':
1046
- showError(err.message);
1047
- break;
1048
- }
1049
- }
1050
- }
1051
- ```
1052
-
1053
- `OzError` fields:
1054
-
1055
- | Field | Type | Description |
1056
- |---|---|---|
1057
- | `message` | `string` | Human-readable, consumer-facing error message. |
1058
- | `errorCode` | `OzErrorCode` | `'network' \| 'timeout' \| 'auth' \| 'validation' \| 'server' \| 'config' \| 'unknown'` |
1059
- | `raw` | `string` | Raw error string from the vault API, if available. |
1060
- | `retryable` | `boolean` | `true` for `network`, `timeout`, `server`. `false` for `auth`, `validation`, `config`, `unknown`. |
1061
-
1062
- > **Session expiry is handled automatically.** When a session expires or is consumed between initialization and the user clicking Pay, the SDK silently fetches a fresh session and retries the tokenization once. You will only receive an `auth` error if the session refresh itself fails β€” for example, if your `/api/oz-session` backend endpoint is unreachable. A healthy `auth` error in production means your session endpoint needs attention, not that the user's card is bad.
1063
-
1064
- **Error normalisation helpers** (for displaying errors from `cardSale` to users):
1065
-
1066
- ```ts
1067
- import { normalizeVaultError, normalizeBankVaultError, normalizeCardSaleError } from '@ozura/elements';
1068
-
1069
- // Maps vault tokenize error strings to user-facing copy
1070
- const display = normalizeVaultError(err.raw); // card flows
1071
- const display = normalizeBankVaultError(err.raw); // bank/ACH flows
1072
- const display = normalizeCardSaleError(err.message); // cardSale API errors
1073
- ```
1074
-
1075
- ---
1076
-
1077
- ## Debug mode
1078
-
1079
- Pass `debug: true` in `VaultOptions` (or as a prop on `<OzElements>`) to activate structured console logging at every SDK lifecycle event.
1080
-
1081
- ```ts
1082
- const vault = await OzVault.create({
1083
- pubKey: 'pk_live_...',
1084
- sessionUrl: '/api/oz-session',
1085
- debug: true, // enables [OzVault] console.log output
1086
- });
1087
- ```
1088
-
1089
- ```tsx
1090
- // React
1091
- <OzElements pubKey="pk_live_..." sessionUrl="/api/oz-session" debug>
1092
- ...
1093
- </OzElements>
1094
- ```
1095
-
1096
- Each log entry is a `[OzVault] <message>` prefixed `console.log` call. Events logged include:
1097
-
1098
- | Event | When it fires |
1099
- |---|---|
1100
- | `vault created` | Constructor completes |
1101
- | `wax key received` | `fetchWaxKey` resolves |
1102
- | `mounting tokenizer iframe` | Tokenizer iframe creation begins |
1103
- | `tokenizer iframe ready` | Tokenizer iframe handshake complete |
1104
- | `element iframe ready` | Each card/bank input iframe loads |
1105
- | `field changed` | Per-field `change` event (empty/complete/valid/auto-advance state) |
1106
- | `auto-advance` | Focus moves automatically between card fields |
1107
- | `createToken() called` | Entry to `createToken()` |
1108
- | `OZ_TOKENIZE sent` | Tokenize request dispatched to iframe |
1109
- | `token received` | Token result returned (with elapsed ms) |
1110
- | `token error` | Vault or network error during tokenize |
1111
- | `proactive wax key refresh triggered` | Budget exhausted; refresh starting |
1112
- | `wax key refresh started/succeeded/failed` | Refresh lifecycle |
1113
- | `tab hidden` / `tab visible` | `visibilitychange` events |
1114
- | `reset() called` | `vault.reset()` entry |
1115
- | `destroy() called` | `vault.destroy()` entry |
1116
-
1117
- **Security:** No sensitive data is ever logged. Wax keys, tokens, CVC sessions, and billing fields appear only as boolean presence flags (`waxKeyPresent: true`). Frame IDs and request IDs are truncated.
1118
-
1119
- ### vault.debugState()
1120
-
1121
- `vault.debugState()` is always available β€” regardless of whether `debug: true` was set β€” and returns a one-time snapshot for attaching to bug reports:
1122
-
1123
- ```ts
1124
- console.log(vault.debugState());
1125
- ```
1126
-
1127
- Sample output:
1128
-
1129
- ```json
1130
- {
1131
- "vaultId": "vault_abc12...",
1132
- "isReady": true,
1133
- "tokenizing": null,
1134
- "destroyed": false,
1135
- "waxKeyPresent": true,
1136
- "tokenizeSuccessCount": 1,
1137
- "maxTokenizeCalls": 3,
1138
- "resetCount": 0,
1139
- "elements": ["cardNumber", "expirationDate", "cvv"],
1140
- "bankElements": [],
1141
- "completionState": { "a1b2c3d4": true, "e5f6a7b8": true, "c9d0e1f2": false },
1142
- "pendingTokenizations": 0,
1143
- "pendingBankTokenizations": 0
1144
- }
1145
- ```
1146
-
1147
- ---
1148
-
1149
- ## Server utilities
1150
-
1151
- > πŸ“– [Server SDK guide](https://docs.ozura.com/sdks/elements/server) β€” `Ozura` class methods, route handler factories, `getClientIp`, error types, and rate limits.
1152
-
1153
- ### Ozura class
1154
-
1155
- ```ts
1156
- import { Ozura, OzuraError } from '@ozura/elements/server';
1157
-
1158
- const ozura = new Ozura({
1159
- merchantId: process.env.MERCHANT_ID!,
1160
- apiKey: process.env.MERCHANT_API_KEY!,
1161
- vaultKey: process.env.VAULT_API_KEY!,
1162
- // apiUrl: 'https://api.ozura.com', // override Pay API URL
1163
- // vaultUrl: 'https://vault.ozura.com', // override vault URL
1164
- timeoutMs: 30000, // default
1165
- retries: 2, // max retry attempts for 5xx/network errors (3 total attempts)
1166
- });
1167
- ```
1168
-
1169
- > **Tokenize-only integrations** (session creation + tokenize cards, no charging) only need `vaultKey`. The `merchantId` and `apiKey` fields are optional β€” they are validated lazily and only required when `cardSale()` is called.
1170
- >
1171
- > ```ts
1172
- > const ozura = new Ozura({ vaultKey: process.env.VAULT_API_KEY! });
1173
- > ```
1174
-
1175
- **Methods:**
1176
-
1177
- ```ts
1178
- // Charge a tokenized card
1179
- const result = await ozura.cardSale({
1180
- token: tokenResponse.token,
1181
- cvcSession: tokenResponse.cvcSession,
1182
- amount: '49.00',
1183
- currency: 'USD', // default: 'USD'
1184
- billing: tokenResponse.billing,
1185
- clientIpAddress: '1.2.3.4', // fetch server-side, never from the browser
1186
- // surchargePercent, tipAmount, salesTaxExempt, processor
1187
- });
1188
- // result.transactionId, result.amount, result.cardLastFour, result.cardBrand
1189
- // result.surchargeAmount and result.tipAmount are optional β€” only present when non-zero
1190
- const surcharge = result.surchargeAmount ?? '0.00';
1191
- const tip = result.tipAmount ?? '0.00';
1192
-
1193
- // Create a session key (for custom session endpoint implementations)
1194
- const { sessionKey, expiresInSeconds } = await ozura.createSession({
1195
- sessionId,
1196
- sessionLimit: 3, // must match VaultOptions.sessionLimit on the client (default: 3)
1197
- // pass null to remove the cap (vault default = unlimited)
1198
- // Optional β€” stored in vault audit log for correlation with your own records:
1199
- // orderId: order.id,
1200
- // customerId: user.id,
1201
- // cartId: cart.id,
1202
- // metadata: { source: 'web' },
1203
- // ttlSeconds: 600, // shorter TTL for quicker checkouts (default: 1800)
1204
- });
1205
-
1206
- // Revoke a session β€” call on all three session-end paths
1207
- // Best-effort β€” never throws. Shortens the exposure window before the vault's ~30 min TTL.
1208
- await ozura.revokeSession(sessionKey);
1209
-
1210
- // Suggested pattern β€” wire all three exit paths:
1211
- // 1. Payment success
1212
- const result = await ozura.cardSale({ ... });
1213
- await ozura.revokeSession(sessionKey); // session is spent; close the window immediately
1214
-
1215
- // 2. User cancels checkout
1216
- router.post('/api/cancel', async (req) => {
1217
- const { sessionKey } = await db.session.get(req.sessionId);
1218
- await ozura.revokeSession(sessionKey);
1219
- return Response.json({ ok: true });
1220
- });
1221
-
1222
- // 3. Page/tab close (best-effort β€” browser may not deliver this)
1223
- // Use sendBeacon so the request survives navigation / tab close.
1224
- window.addEventListener('visibilitychange', () => {
1225
- if (document.visibilityState === 'hidden') {
1226
- navigator.sendBeacon('/api/cancel', JSON.stringify({ sessionId }));
1227
- }
1228
- });
1229
-
1230
- // List transactions
1231
- const { transactions, pagination } = await ozura.listTransactions({
1232
- dateFrom: '2025-01-01',
1233
- dateTo: '2025-12-31',
1234
- transactionType: 'CreditCardSale',
1235
- page: 1,
1236
- limit: 50,
1237
- });
1238
- ```
1239
-
1240
- **`OzuraError`** (thrown by all `Ozura` methods):
1241
-
1242
- ```ts
1243
- try {
1244
- await ozura.cardSale(input);
1245
- } catch (err) {
1246
- if (err instanceof OzuraError) {
1247
- err.statusCode; // HTTP status code
1248
- err.message; // Normalized message
1249
- err.raw; // Raw API response string
1250
- err.retryAfter; // Seconds (only present on 429)
1251
- }
1252
- }
1253
- ```
1254
-
1255
- Rate limits: `cardSale` β€” 100 req/min per merchant. `listTransactions` β€” 200 req/min per merchant.
1256
-
1257
- > **Retry behavior:** `createSession` and `listTransactions` retry on 5xx and network errors using exponential backoff (1 s / 2 s / 4 s…) up to `retries + 1` total attempts. **`cardSale` is never retried** β€” it is a non-idempotent financial operation and the result of a duplicate charge cannot be predicted.
1258
-
1259
- ---
1260
-
1261
- ### Route handler factories
1262
-
1263
- The server package exports factory functions covering two runtimes Γ— two endpoints:
1264
-
1265
- | Function | Runtime | Endpoint |
1266
- |---|---|---|
1267
- | `createSessionHandler` | Fetch API (Next.js App Router, Cloudflare, Vercel Edge) | `POST /api/oz-session` |
1268
- | `createSessionMiddleware` | Express / Connect | `POST /api/oz-session` |
1269
- | `createCardSaleHandler` | Fetch API | `POST /api/charge` |
1270
- | `createCardSaleMiddleware` | Express / Connect | `POST /api/charge` |
1271
-
1272
- `createCardSaleHandler` / `createCardSaleMiddleware` accept a `CardSaleHandlerOptions` object:
1273
-
1274
- ```ts
1275
- interface CardSaleHandlerOptions {
1276
- /**
1277
- * Required. Return the charge amount as a decimal string.
1278
- * Never trust the amount from the request body β€” resolve it from your database.
1279
- */
1280
- getAmount: (body: Record<string, unknown>) => Promise<string>;
1281
-
1282
- /**
1283
- * Optional. Return the ISO 4217 currency code. Default: "USD".
1284
- */
1285
- getCurrency?: (body: Record<string, unknown>) => Promise<string>;
1286
- }
1287
- ```
1288
-
1289
- Both handler factories validate `Content-Type: application/json`, run `validateBilling()`, extract the client IP from standard proxy headers, and return normalized `{ transactionId, amount, cardLastFour, cardBrand }` on success.
1290
-
1291
- ---
1292
-
1293
- ## Local development
1294
-
1295
- The repository includes a development server at `dev-server.mjs` that serves the built frame assets and proxies vault API requests:
1296
-
1297
- ```bash
1298
- npm run dev # build + start dev server on http://localhost:4242
1299
- ```
1300
-
1301
- Set `frameBaseUrl` to point your vault at the local server:
1302
-
1303
- ```ts
1304
- const vault = await OzVault.create({
1305
- pubKey: 'pk_test_...',
1306
- sessionUrl: '/api/oz-session',
1307
- frameBaseUrl: 'http://localhost:4242', // local dev only
1308
- });
1309
- ```
1310
-
1311
- Or in React:
1312
-
1313
- ```tsx
1314
- <OzElements
1315
- pubKey="pk_test_..."
1316
- sessionUrl="/api/oz-session"
1317
- frameBaseUrl="http://localhost:4242"
1318
- >
1319
- ```
1320
-
1321
- Configure environment variables for the dev server:
1322
-
1323
- ```bash
1324
- VAULT_URL=https://vault-staging.example.com
1325
- VAULT_API_KEY=vk_test_...
1326
- ```
1327
-
1328
- ---
1329
-
1330
- ## Content Security Policy
1331
-
1332
- The SDK loads iframes from the Ozura frame origin. Add the following directives to your CSP:
1333
-
1334
- ```
1335
- frame-src https://elements.ozura.com;
1336
- ```
1337
-
1338
- If loading custom fonts via `fonts[].cssSrc`, also allow the font stylesheet origin:
1339
-
1340
- ```
1341
- style-src https://fonts.googleapis.com;
1342
- font-src https://fonts.gstatic.com;
1343
- ```
1344
-
1345
- To verify your CSP after a build:
1346
-
1347
- ```bash
1348
- npm run check:csp
1349
- ```
1350
-
1351
- ---
1352
-
1353
- ## TypeScript reference
1354
-
1355
- > πŸ“– [API reference](https://docs.ozura.com/sdks/elements/api-reference) β€” every interface, union, and enum fully annotated with JSDoc.
1356
-
1357
- All public types are exported from `@ozura/elements`:
1358
-
1359
- ```ts
1360
- import type {
1361
- // Element types
1362
- ElementType, // 'cardNumber' | 'cvv' | 'expirationDate'
1363
- BankElementType, // 'accountNumber' | 'routingNumber'
1364
- ElementOptions,
1365
- ElementStyleConfig,
1366
- ElementStyle,
1367
- ElementChangeEvent,
1368
-
1369
- // Vault config
1370
- VaultOptions,
1371
- FontSource,
1372
- CssFontSource,
1373
- CustomFontSource,
1374
- Appearance,
1375
- AppearanceVariables,
1376
- OzTheme, // 'default' | 'night' | 'flat'
1377
-
1378
- // Tokenization
1379
- TokenizeOptions,
1380
- BankTokenizeOptions,
1381
- TokenResponse,
1382
- BankTokenResponse,
1383
- CardMetadata,
1384
- BankAccountMetadata,
1385
-
1386
- // Billing
1387
- BillingDetails,
1388
- BillingAddress,
1389
-
1390
- // Card sale
1391
- CardSaleRequest,
1392
- CardSaleResponseData,
1393
- CardSaleApiResponse,
1394
-
1395
- // Transactions
1396
- TransactionQueryParams,
1397
- TransactionQueryPagination,
1398
- TransactionQueryResponse,
1399
- TransactionType,
1400
- TransactionData,
1401
- CardTransactionData,
1402
- AchTransactionData,
1403
- CryptoTransactionData,
1404
-
1405
- // Errors
1406
- OzErrorCode,
1407
- } from '@ozura/elements';
1408
- ```
1409
-
1410
- Server-specific types are exported from `@ozura/elements/server`:
1411
-
1412
- ```ts
1413
- import type {
1414
- OzuraConfig,
1415
- CardSaleInput,
1416
- CreateSessionOptions,
1417
- CreateSessionResult,
1418
- ListTransactionsInput,
1419
- } from '@ozura/elements/server';
1420
- ```
1421
-
1422
- React-specific types are exported from `@ozura/elements/react`:
1423
-
1424
- ```ts
1425
- import type { OzFieldProps, OzCardProps, OzCardState, OzBankCardProps, OzBankCardState } from '@ozura/elements/react';
1426
- ```
1427
-
1428
- ---
1429
-
1430
- ## Need help?
1431
-
1432
- The full documentation β€” including interactive examples, a complete API reference, and integration walkthroughs β€” lives at:
1433
-
1434
- **[docs.ozura.com/sdks/elements/overview](https://docs.ozura.com/sdks/elements/overview)**
1435
-
1436
- | I want to… | Go to |
1437
- |---|---|
1438
- | Get started from scratch | [Installation](https://docs.ozura.com/sdks/elements/installation) |
1439
- | Build a card payment form | [Card elements](https://docs.ozura.com/sdks/elements/card-elements) |
1440
- | Build an ACH / bank form | [Bank elements](https://docs.ozura.com/sdks/elements/bank-elements) |
1441
- | Use the React components | [React guide](https://docs.ozura.com/sdks/elements/react) |
1442
- | Style the input fields | [Styling](https://docs.ozura.com/sdks/elements/styling) |
1443
- | Handle errors correctly | [Error handling](https://docs.ozura.com/sdks/elements/error-handling) |
1444
- | Set up the server side | [Server SDK](https://docs.ozura.com/sdks/elements/server) |
1445
- | Look up a type or method | [API reference](https://docs.ozura.com/sdks/elements/api-reference) |
1
+ # @ozura/elements
2
+
3
+ PCI-isolated card and bank account tokenization SDK for the Ozura Vault.
4
+
5
+ Card data is collected inside Ozura-hosted iframes so raw numbers never touch your JavaScript bundle, your server logs, or your network traffic. The tokenizer communicates directly with the vault using `MessageChannel` port transfers β€” the merchant page acts as a layout host only.
6
+
7
+ > **πŸ“– Full documentation:** [docs.ozura.com/sdks/elements/overview](https://docs.ozura.com/sdks/elements/overview)
8
+ >
9
+ > The docs include step-by-step guides, interactive examples, a complete API reference, and styling walkthroughs. If you are starting a new integration, the docs are the best place to begin.
10
+
11
+ ---
12
+
13
+ ## Table of contents
14
+
15
+ - [Full documentation](#full-documentation)
16
+ - [How it works](#how-it-works)
17
+ - [Installation](#installation)
18
+ - [Quick start β€” React](#quick-start--react)
19
+ - [Quick start β€” Vanilla JS](#quick-start--vanilla-js)
20
+ - [Server setup](#server-setup)
21
+ - [Session endpoint](#session-endpoint)
22
+ - [Card sale endpoint](#card-sale-endpoint)
23
+ - [Vanilla JS API](#vanilla-js-api)
24
+ - [OzVault.create()](#ozvaultcreate)
25
+ - [vault.createElement()](#vaultcreateelementtypeoptions)
26
+ - [vault.createToken()](#vaultcreatetokenoptions)
27
+ - [vault.createBankElement()](#vaultcreatebankelement)
28
+ - [vault.createBankToken()](#vaultcreatebanktokenoptions)
29
+ - [vault.reset()](#vaultreset)
30
+ - [vault.destroy()](#vaultdestroy)
31
+ - [vault.debugState()](#vaultdebugstate)
32
+ - [OzElement events](#ozelement-events)
33
+ - [React API](#react-api)
34
+ - [OzElements provider](#ozelements-provider)
35
+ - [OzCard](#ozcard)
36
+ - [Individual field components](#individual-field-components)
37
+ - [OzBankCard](#ozbankcard)
38
+ - [useOzElements()](#useozelements)
39
+ - [Styling](#styling)
40
+ - [Per-element styles](#per-element-styles)
41
+ - [Global appearance](#global-appearance)
42
+ - [Custom fonts](#custom-fonts)
43
+ - [Billing details](#billing-details)
44
+ - [Error handling](#error-handling)
45
+ - [Debug mode](#debug-mode)
46
+ - [Server utilities](#server-utilities)
47
+ - [Ozura class](#ozura-class)
48
+ - [Route handler factories](#route-handler-factories)
49
+ - [Local development](#local-development)
50
+ - [Content Security Policy](#content-security-policy)
51
+ - [TypeScript reference](#typescript-reference)
52
+
53
+ ---
54
+
55
+ ## Full documentation
56
+
57
+ The README covers the most common integration patterns. The hosted docs at **[docs.ozura.com/sdks/elements](https://docs.ozura.com/sdks/elements/overview)** go deeper on every topic:
58
+
59
+ | Page | URL |
60
+ |---|---|
61
+ | Overview | [docs.ozura.com/sdks/elements/overview](https://docs.ozura.com/sdks/elements/overview) |
62
+ | Installation & setup | [docs.ozura.com/sdks/elements/installation](https://docs.ozura.com/sdks/elements/installation) |
63
+ | Card elements | [docs.ozura.com/sdks/elements/card-elements](https://docs.ozura.com/sdks/elements/card-elements) |
64
+ | Bank elements | [docs.ozura.com/sdks/elements/bank-elements](https://docs.ozura.com/sdks/elements/bank-elements) |
65
+ | React integration | [docs.ozura.com/sdks/elements/react](https://docs.ozura.com/sdks/elements/react) |
66
+ | Styling | [docs.ozura.com/sdks/elements/styling](https://docs.ozura.com/sdks/elements/styling) |
67
+ | Error handling | [docs.ozura.com/sdks/elements/error-handling](https://docs.ozura.com/sdks/elements/error-handling) |
68
+ | Server SDK | [docs.ozura.com/sdks/elements/server](https://docs.ozura.com/sdks/elements/server) |
69
+ | API reference | [docs.ozura.com/sdks/elements/api-reference](https://docs.ozura.com/sdks/elements/api-reference) |
70
+
71
+ ---
72
+
73
+ ## How it works
74
+
75
+ ```
76
+ Merchant page
77
+ β”œβ”€β”€ OzVault (manages tokenizer iframe + element iframes)
78
+ β”œβ”€β”€ [hidden] tokenizer-frame.html ← Ozura origin
79
+ β”œβ”€β”€ [visible] element-frame.html ← card number ─┐ MessageChannel
80
+ β”œβ”€β”€ [visible] element-frame.html ← expiry β”œβ”€ port transfer
81
+ └── [visible] element-frame.html ← CVV β”€β”˜
82
+ ```
83
+
84
+ 1. `OzVault.create()` mounts a hidden tokenizer iframe and fetches a short-lived **session key** from your server.
85
+ 2. Calling `vault.createElement()` mounts a visible input iframe for each field.
86
+ 3. `vault.createToken()` opens a direct `MessageChannel` between each element iframe and the tokenizer iframe. Raw values travel over those ports β€” they never pass through your JavaScript.
87
+ 4. The tokenizer POSTs directly to the vault API over HTTPS and returns a token to your page.
88
+
89
+ Your server only ever sees a token, never card data.
90
+
91
+ ---
92
+
93
+ ## Credentials
94
+
95
+ | Credential | Format | Where it lives | Required for |
96
+ |---|---|---|---|
97
+ | **Vault pub key** | `pk_live_…` or `pk_prod_…` | Frontend env var (safe to expose) | All integrations |
98
+ | **Vault API key** | `key_…` | Server env var β€” **never in the browser** | Creating sessions (all integrations) |
99
+ | **Pay API key** | `ak_…` | Server env var only | OzuraPay merchants (card charging) |
100
+ | **Merchant ID** | `ozu_…` | Server env var only | OzuraPay merchants (card charging) |
101
+
102
+ If you are not routing payments through OzuraPay you only need the vault pub key (frontend) and vault API key (backend).
103
+
104
+ ---
105
+
106
+ ## Installation
107
+
108
+ > πŸ“– [Installation guide](https://docs.ozura.com/sdks/elements/installation) β€” npm, yarn, CDN setup, and TypeScript configuration.
109
+
110
+ ```bash
111
+ npm install @ozura/elements
112
+ ```
113
+
114
+ React and React DOM are peer dependencies (optional β€” only needed for `@ozura/elements/react`):
115
+
116
+ ```bash
117
+ npm install react react-dom # if not already installed
118
+ ```
119
+
120
+ **Requirements:** Node β‰₯ 18, React β‰₯ 17 (React peer).
121
+
122
+ ---
123
+
124
+ ## Quick start β€” React
125
+
126
+ > πŸ“– [React integration guide](https://docs.ozura.com/sdks/elements/react) β€” provider setup, pre-built components, hook reference, and full examples.
127
+
128
+ ```tsx
129
+ // 1. Wrap your checkout in <OzElements>
130
+ import { OzElements, OzCard, useOzElements } from '@ozura/elements/react';
131
+
132
+ function CheckoutPage() {
133
+ return (
134
+ <OzElements
135
+ pubKey="pk_live_..."
136
+ sessionUrl="/api/oz-session"
137
+ >
138
+ <CheckoutForm />
139
+ </OzElements>
140
+ );
141
+ }
142
+
143
+ // 2. Collect card data and tokenize
144
+ function CheckoutForm() {
145
+ const { createToken, reset, ready } = useOzElements();
146
+
147
+ const handleSubmit = async (e: React.FormEvent) => {
148
+ e.preventDefault();
149
+ try {
150
+ const { token, cvcSession, billing } = await createToken({
151
+ billing: {
152
+ firstName: 'Jane',
153
+ lastName: 'Smith',
154
+ email: 'jane@example.com',
155
+ address: { line1: '123 Main St', city: 'Austin', state: 'TX', zip: '78701', country: 'US' },
156
+ },
157
+ });
158
+
159
+ // Send token to your server
160
+ await fetch('/api/charge', {
161
+ method: 'POST',
162
+ headers: { 'Content-Type': 'application/json' },
163
+ body: JSON.stringify({ token, cvcSession, billing }),
164
+ });
165
+ } catch (err) {
166
+ reset(); // clear fields so the customer can re-enter
167
+ console.error(err);
168
+ }
169
+ };
170
+
171
+ return (
172
+ <form onSubmit={handleSubmit}>
173
+ <OzCard onChange={(state) => console.log(state.cardBrand)} />
174
+ <button type="submit" disabled={!ready}>Pay</button>
175
+ </form>
176
+ );
177
+ }
178
+ ```
179
+
180
+ ---
181
+
182
+ ## Quick start β€” Vanilla JS
183
+
184
+ > πŸ“– [Card elements guide](https://docs.ozura.com/sdks/elements/card-elements) β€” full end-to-end example, field events, submit-button gating, and auto-advance behaviour.
185
+
186
+ ```ts
187
+ import { OzVault } from '@ozura/elements';
188
+
189
+ // Declare state BEFORE OzVault.create(). The onReady callback fires when the
190
+ // tokenizer iframe loads β€” this can happen before create() resolves because the
191
+ // iframe loads concurrently with fetchWaxKey. At that moment, `vault` is still
192
+ // undefined. Do not reference `vault` inside onReady.
193
+ let readyCount = 0;
194
+ let tokenizerIsReady = false;
195
+
196
+ function checkReady() {
197
+ if (readyCount === 3 && tokenizerIsReady) enablePayButton();
198
+ }
199
+
200
+ const vault = await OzVault.create({
201
+ pubKey: 'pk_live_...',
202
+ sessionUrl: '/api/oz-session',
203
+ onReady: () => { tokenizerIsReady = true; checkReady(); }, // tokenizer iframe loaded
204
+ });
205
+
206
+ const cardNumberEl = vault.createElement('cardNumber');
207
+ const expiryEl = vault.createElement('expirationDate');
208
+ const cvvEl = vault.createElement('cvv');
209
+
210
+ cardNumberEl.mount('#card-number');
211
+ expiryEl.mount('#expiry');
212
+ cvvEl.mount('#cvv');
213
+
214
+ [cardNumberEl, expiryEl, cvvEl].forEach(el => {
215
+ el.on('ready', () => { readyCount++; checkReady(); });
216
+ });
217
+
218
+ async function pay() {
219
+ try {
220
+ const { token, cvcSession, card } = await vault.createToken({
221
+ billing: { firstName: 'Jane', lastName: 'Smith' },
222
+ });
223
+ // POST { token, cvcSession } to your server
224
+ } catch (err) {
225
+ vault.reset(); // clear fields; let customer re-enter
226
+ console.error(err);
227
+ }
228
+ }
229
+
230
+ // Clean up when done
231
+ vault.destroy();
232
+ ```
233
+
234
+ > **Gating the submit button in vanilla JS** requires checking both `vault.isReady` (tokenizer iframe loaded) **and** every element's `ready` event (input iframes loaded). In React, `useOzElements().ready` combines both automatically.
235
+
236
+ ---
237
+
238
+ ## Server setup
239
+
240
+ > πŸ“– [Server SDK guide](https://docs.ozura.com/sdks/elements/server) β€” session creation, card sale handler factories, IP extraction, and manual implementation patterns.
241
+
242
+ ### Session endpoint
243
+
244
+ The SDK calls your session endpoint whenever it needs to start or refresh a payment session. Your backend creates a short-lived session key from the vault using your vault API key β€” the key never touches the browser.
245
+
246
+ **Next.js App Router (recommended)**
247
+
248
+ ```ts
249
+ // app/api/oz-session/route.ts
250
+ import { Ozura, createSessionHandler } from '@ozura/elements/server';
251
+
252
+ const ozura = new Ozura({ vaultKey: process.env.VAULT_API_KEY! });
253
+
254
+ export const POST = createSessionHandler(ozura);
255
+ ```
256
+
257
+ **Express**
258
+
259
+ ```ts
260
+ import express from 'express';
261
+ import { Ozura, createSessionMiddleware } from '@ozura/elements/server';
262
+
263
+ const ozura = new Ozura({ vaultKey: process.env.VAULT_API_KEY! });
264
+ const app = express();
265
+
266
+ app.use(express.json());
267
+ app.post('/api/oz-session', createSessionMiddleware(ozura));
268
+ ```
269
+
270
+ **Manual implementation** (for custom logic or auth checks)
271
+
272
+ ```ts
273
+ // POST /api/oz-session
274
+ const { sessionId } = await req.json();
275
+ const { sessionKey } = await ozura.createSession({ sessionId });
276
+ return Response.json({ sessionKey });
277
+ ```
278
+
279
+ ### Card sale endpoint
280
+
281
+ After `createToken()` resolves on the frontend, POST `{ token, cvcSession, billing }` to your server to charge the card.
282
+
283
+ **Next.js App Router**
284
+
285
+ ```ts
286
+ // app/api/charge/route.ts
287
+ import { Ozura, createCardSaleHandler } from '@ozura/elements/server';
288
+
289
+ const ozura = new Ozura({ merchantId: '...', apiKey: '...', vaultKey: '...' });
290
+
291
+ export const POST = createCardSaleHandler(ozura, {
292
+ getAmount: async (body) => {
293
+ const order = await db.orders.findById(body.orderId as string);
294
+ return order.total; // decimal string, e.g. "49.00"
295
+ },
296
+ // getCurrency: async (body) => 'USD', // optional, defaults to "USD"
297
+ });
298
+ ```
299
+
300
+ **Express**
301
+
302
+ ```ts
303
+ app.post('/api/charge', createCardSaleMiddleware(ozura, {
304
+ getAmount: async (body) => {
305
+ const order = await db.orders.findById(body.orderId as string);
306
+ return order.total; // decimal string, e.g. "49.00"
307
+ },
308
+ // getCurrency: async (body) => 'USD', // optional, defaults to "USD"
309
+ }));
310
+ ```
311
+
312
+ > `createCardSaleMiddleware` always terminates the request β€” it does not call `next()` and cannot be composed in a middleware chain.
313
+
314
+ **Manual implementation**
315
+
316
+ ```ts
317
+ const { token, cvcSession, billing } = await req.json();
318
+ const result = await ozura.cardSale({
319
+ token,
320
+ cvcSession,
321
+ amount: '49.00',
322
+ currency: 'USD',
323
+ billing,
324
+ // Take the first IP from the forwarded-for chain; fall back to socket address.
325
+ // req is a Fetch API Request (Next.js App Router / Vercel Edge).
326
+ clientIpAddress: req.headers.get('x-forwarded-for')?.split(',')[0].trim()
327
+ ?? req.headers.get('x-real-ip')
328
+ ?? '',
329
+ });
330
+ // result.transactionId, result.amount, result.cardLastFour, result.cardBrand
331
+ ```
332
+
333
+ ---
334
+
335
+ ## Vanilla JS API
336
+
337
+ > πŸ“– [API reference](https://docs.ozura.com/sdks/elements/api-reference) β€” complete type definitions and method signatures for every class.
338
+
339
+ ### OzVault.create(options)
340
+
341
+ ```ts
342
+ const vault = await OzVault.create(options: VaultOptions): Promise<OzVault>
343
+ ```
344
+
345
+ Mounts the hidden tokenizer iframe and fetches a session key concurrently. Both happen in parallel β€” by the time `create()` resolves, the iframe may already be ready.
346
+
347
+ | Option | Type | Required | Description |
348
+ |---|---|---|---|
349
+ | `pubKey` | `string` | βœ“ | Your public key from the Ozura admin. |
350
+ | `sessionUrl` | `string` | βœ“ ΒΉ | URL of your session endpoint. The simplest option β€” pass the path and the SDK handles everything. |
351
+ | `getSessionKey` | `(sessionId: string) => Promise<string>` | βœ“ ΒΉ | Custom async callback for obtaining the session key. Use when you need custom headers or auth logic. |
352
+ | `fetchWaxKey` | `(sessionId: string) => Promise<string>` | βœ“ ΒΉ | **Deprecated.** Use `sessionUrl` or `getSessionKey` instead. |
353
+ | `frameBaseUrl` | `string` | β€” | Base URL for iframe assets. Defaults to production CDN. Override for local dev (see [Local development](#local-development)). |
354
+ | `fonts` | `FontSource[]` | β€” | Custom fonts to inject into all element iframes. |
355
+ | `appearance` | `Appearance` | β€” | Global theme and variable overrides. |
356
+ | `loadTimeoutMs` | `number` | β€” | Tokenizer iframe load timeout in ms. Default: `10000`. Only takes effect when `onLoadError` is also provided. |
357
+ | `onLoadError` | `() => void` | β€” | Called if the tokenizer iframe fails to load within `loadTimeoutMs`. |
358
+ | `onSessionRefresh` | `() => void` | β€” | Called when the SDK silently refreshes the session mid-tokenization (key expired or consumed). |
359
+ | `onReady` | `() => void` | β€” | Called once when the tokenizer iframe has loaded and is ready. Use in vanilla JS to re-check submit-button readiness. In React, `useOzElements().ready` handles this automatically. |
360
+ | `sessionLimit` | `number` | β€” | Card submissions allowed per session before the SDK refreshes automatically. Default: `3`. Must match `sessionLimit` in your server-side `createSession` call. |
361
+ | `debug` | `boolean` | β€” | Enables structured `[OzVault]`-prefixed `console.log` output at every lifecycle event. Safe to use in production β€” no sensitive data is ever logged. Default: `false`. See [Debug mode](#debug-mode) for details. |
362
+
363
+ ΒΉ Exactly one of `sessionUrl`, `getSessionKey`, or `fetchWaxKey` is required.
364
+
365
+ Throws `OzError` if the session fetch rejects, returns an empty string, or returns a non-string value.
366
+
367
+ > **`sessionUrl` retry behavior:** The SDK enforces a **10-second per-attempt timeout** and retries **once after 750 ms on pure network failures** (connection refused, DNS failure, offline). HTTP 4xx/5xx errors are never retried β€” they signal endpoint misconfiguration or invalid credentials and require developer action. Errors are thrown as `OzError` instances so you can inspect `err.errorCode`.
368
+
369
+ ---
370
+
371
+ ### vault.createElement(type, options?)
372
+
373
+ ```ts
374
+ vault.createElement(type: ElementType, options?: ElementOptions): OzElement
375
+ ```
376
+
377
+ Creates and returns an element iframe. Call `.mount(target)` to attach it to the DOM.
378
+
379
+ `ElementType`: `'cardNumber'` | `'cvv'` | `'expirationDate'`
380
+
381
+ ```ts
382
+ const cardEl = vault.createElement('cardNumber', {
383
+ placeholder: '1234 5678 9012 3456',
384
+ style: {
385
+ base: { color: '#1a1a1a', fontSize: '16px' },
386
+ focus: { borderColor: '#6366f1' },
387
+ invalid: { color: '#dc2626' },
388
+ complete: { color: '#16a34a' },
389
+ },
390
+ });
391
+
392
+ cardEl.mount('#card-number-container');
393
+ ```
394
+
395
+ `ElementOptions`:
396
+
397
+ | Option | Type | Description |
398
+ |---|---|---|
399
+ | `style` | `ElementStyleConfig` | Per-state style overrides. See [Styling](#styling). |
400
+ | `placeholder` | `string` | Placeholder text (max 100 characters). |
401
+ | `disabled` | `boolean` | Disables the input. |
402
+ | `loadTimeoutMs` | `number` | Iframe load timeout in ms. Default: `10000`. |
403
+
404
+ **OzElement methods:**
405
+
406
+ | Method | Description |
407
+ |---|---|
408
+ | `.mount(target)` | Mount the iframe. Accepts a CSS selector string or `HTMLElement`. |
409
+ | `.unmount()` | Remove the iframe from the DOM. The element can be re-mounted. |
410
+ | `.destroy()` | Permanently destroy the element. Cannot be re-mounted. |
411
+ | `.update(options)` | Update placeholder, style, or disabled state without re-mounting. **Merge semantics** β€” only provided keys are applied; omitted keys retain their values. To reset a property, pass it with an empty string (e.g. `{ style: { base: { color: '' } } }`). To fully reset all styles, destroy and recreate the element. |
412
+ | `.clear()` | Clear the field value. |
413
+ | `.focus()` | Programmatically focus the input. |
414
+ | `.blur()` | Programmatically blur the input. |
415
+ | `.on(event, fn)` | Subscribe to an event. Returns `this` for chaining. |
416
+ | `.off(event, fn)` | Remove an event handler. |
417
+ | `.once(event, fn)` | Subscribe for a single invocation. |
418
+ | `.isReady` | `true` once the iframe has loaded and signalled ready. |
419
+
420
+ ---
421
+
422
+ ### vault.createToken(options?)
423
+
424
+ ```ts
425
+ vault.createToken(options?: TokenizeOptions): Promise<TokenResponse>
426
+ ```
427
+
428
+ Tokenizes all mounted and ready card elements. Raw values travel directly from element iframes to the tokenizer iframe via `MessageChannel` β€” they never pass through your page's JavaScript.
429
+
430
+ Returns a `TokenResponse`:
431
+
432
+ ```ts
433
+ interface TokenResponse {
434
+ token: string; // Vault token β€” pass to cardSale
435
+ cvcSession: string; // CVC session β€” always present; pass to cardSale
436
+ card?: { // Card metadata β€” present when vault returns all four fields
437
+ last4: string; // e.g. "4242"
438
+ brand: string; // e.g. "visa"
439
+ expMonth: string; // e.g. "09"
440
+ expYear: string; // e.g. "2027"
441
+ };
442
+ billing?: BillingDetails; // Normalized billing β€” only present if billing was passed in
443
+ }
444
+ ```
445
+
446
+ `TokenizeOptions`:
447
+
448
+ | Option | Type | Description |
449
+ |---|---|---|
450
+ | `billing` | `BillingDetails` | Validated and normalized billing details. Returned in `TokenResponse.billing`. |
451
+ | `firstName` | `string` | **Deprecated.** Pass inside `billing` instead. |
452
+ | `lastName` | `string` | **Deprecated.** Pass inside `billing` instead. |
453
+
454
+ Throws `OzError` if:
455
+ - The vault is not ready (`errorCode: 'unknown'`)
456
+ - A tokenization is already in progress
457
+ - Billing validation fails (`errorCode: 'validation'`)
458
+ - No elements are mounted
459
+ - The vault returns an error (`errorCode` reflects the HTTP status)
460
+ - The request times out after 30 seconds (`errorCode: 'timeout'`) β€” this timeout is separate from `loadTimeoutMs` and is not configurable
461
+
462
+ **`vault.tokenizeCount`**
463
+
464
+ ```ts
465
+ vault.tokenizeCount: number // read-only getter
466
+ ```
467
+
468
+ Returns the number of successful `createToken()` / `createBankToken()` calls made in the current session. Resets to `0` each time the session is refreshed (proactively or reactively). Use this in vanilla JS to display "attempts remaining" feedback or gate the submit button:
469
+
470
+ ```ts
471
+ const MAX = 3; // matches maxTokenizeCalls
472
+ const remaining = MAX - vault.tokenizeCount;
473
+ payButton.textContent = `Pay (${remaining} attempt${remaining === 1 ? '' : 's'} remaining)`;
474
+ ```
475
+
476
+ In React, use `tokenizeCount` from `useOzElements()` instead β€” it is a reactive state value and will trigger re-renders automatically.
477
+
478
+ ---
479
+
480
+ ### vault.createBankElement()
481
+
482
+ ```ts
483
+ vault.createBankElement(type: BankElementType, options?: ElementOptions): OzElement
484
+ ```
485
+
486
+ Creates a bank account element. `BankElementType`: `'accountNumber'` | `'routingNumber'`.
487
+
488
+ ```ts
489
+ const accountEl = vault.createBankElement('accountNumber');
490
+ const routingEl = vault.createBankElement('routingNumber');
491
+ accountEl.mount('#account-number');
492
+ routingEl.mount('#routing-number');
493
+ ```
494
+
495
+ ---
496
+
497
+ ### vault.createBankToken(options)
498
+
499
+ ```ts
500
+ vault.createBankToken(options: BankTokenizeOptions): Promise<BankTokenResponse>
501
+ ```
502
+
503
+ Tokenizes the mounted `accountNumber` and `routingNumber` elements. Both must be mounted and ready.
504
+
505
+ ```ts
506
+ interface BankTokenizeOptions {
507
+ firstName: string; // Account holder first name (required, max 50 chars)
508
+ lastName: string; // Account holder last name (required, max 50 chars)
509
+ }
510
+
511
+ interface BankTokenResponse {
512
+ token: string;
513
+ bank?: {
514
+ last4: string; // Last 4 digits of account number
515
+ routingNumberLast4: string;
516
+ };
517
+ }
518
+ ```
519
+
520
+ > **Note:** OzuraPay does not currently support bank account payments. Use the bank token with your own ACH processor. Bank tokens can be passed to any ACH-capable processor directly.
521
+
522
+ > **Card tokens and processors:** Card tokenization returns a `cvcSession` alongside the `token`. OzuraPay's charge API requires `cvcSession`. If you are routing to a non-Ozura processor, pass the `token` directly β€” your processor's documentation will tell you whether a CVC session token is required.
523
+
524
+ ---
525
+
526
+ ### vault.destroy()
527
+
528
+ ```ts
529
+ vault.destroy(): void
530
+ ```
531
+
532
+ Tears down the vault: removes all element and tokenizer iframes, clears the `message` event listener, rejects any pending `createToken()` / `createBankToken()` promises, and cancels active timeout handles. Call this when the checkout component unmounts.
533
+
534
+ ```ts
535
+ // React useEffect cleanup β€” the cancel flag prevents a vault from leaking
536
+ // if the component unmounts before OzVault.create() resolves.
537
+ useEffect(() => {
538
+ let cancelled = false;
539
+ let vault: OzVault | null = null;
540
+ OzVault.create(options).then(v => {
541
+ if (cancelled) { v.destroy(); return; }
542
+ vault = v;
543
+ });
544
+ return () => {
545
+ cancelled = true;
546
+ vault?.destroy();
547
+ };
548
+ }, []);
549
+ ```
550
+
551
+ ---
552
+
553
+ ### vault.reset()
554
+
555
+ ```ts
556
+ vault.reset(): void
557
+ ```
558
+
559
+ Clears all mounted card and bank element fields without destroying the vault, refreshing the session, or resetting the tokenization budget. Call this after a declined payment to let the customer re-enter their card details on the same checkout screen.
560
+
561
+ The session key, its remaining budget, and all iframes are fully preserved β€” no network calls are made.
562
+
563
+ **Session model:** One session covers the full checkout. The default `sessionLimit: 3` is enough for two declines and a final attempt. Use `vault.reset()` between declines β€” not `vault.destroy()` + recreate, which would waste the remaining budget and cause iframe flicker.
564
+
565
+ ```ts
566
+ try {
567
+ const { token, cvcSession } = await vault.createToken({ billing });
568
+ await fetch('/api/charge', {
569
+ method: 'POST',
570
+ headers: { 'Content-Type': 'application/json' },
571
+ body: JSON.stringify({ token, cvcSession }),
572
+ });
573
+ } catch (err) {
574
+ vault.reset(); // clear fields; let customer re-enter
575
+ showError(err instanceof OzError ? err.message : 'Payment failed.');
576
+ }
577
+ ```
578
+
579
+ ---
580
+
581
+ ### vault.debugState()
582
+
583
+ ```ts
584
+ vault.debugState(): Record<string, unknown>
585
+ ```
586
+
587
+ Returns a structured snapshot of the vault's internal state. Always available regardless of whether `debug: true` is set. Useful for attaching to support tickets or dumping on error.
588
+
589
+ ```ts
590
+ console.log(vault.debugState());
591
+ // {
592
+ // vaultId: 'vault_abc12...',
593
+ // isReady: true,
594
+ // tokenizing: null,
595
+ // destroyed: false,
596
+ // waxKeyPresent: true,
597
+ // tokenizeSuccessCount: 1,
598
+ // maxTokenizeCalls: 3,
599
+ // resetCount: 0,
600
+ // elements: ['cardNumber', 'expirationDate', 'cvv'],
601
+ // bankElements: [],
602
+ // completionState: { 'a1b2c3d4': true, 'e5f6a7b8': true, '...' : false },
603
+ // pendingTokenizations: 0,
604
+ // pendingBankTokenizations: 0,
605
+ // }
606
+ ```
607
+
608
+ No sensitive data is returned: wax keys, tokens, CVC sessions, and billing fields are never included.
609
+
610
+ ---
611
+
612
+ ### OzElement events
613
+
614
+ ```ts
615
+ element.on('change', (event: ElementChangeEvent) => { ... });
616
+ element.on('focus', () => { ... });
617
+ element.on('blur', () => { ... });
618
+ element.on('ready', () => { ... });
619
+ element.on('loaderror', (payload: { elementType: string; error: string }) => { ... });
620
+ ```
621
+
622
+ `ElementChangeEvent`:
623
+
624
+ | Field | Type | Description |
625
+ |---|---|---|
626
+ | `empty` | `boolean` | `true` when the field is empty. |
627
+ | `complete` | `boolean` | `true` when the field has enough digits to be complete. |
628
+ | `valid` | `boolean` | `true` when the value passes all validation (Luhn, expiry date, etc.). |
629
+ | `error` | `string \| undefined` | User-facing error message when `valid` is `false` and the field has been touched. |
630
+ | `cardBrand` | `string \| undefined` | Detected brand β€” only on `cardNumber` fields (e.g. `"visa"`, `"amex"`). |
631
+ | `month` | `string \| undefined` | Parsed 2-digit month β€” only on `expirationDate` fields. |
632
+ | `year` | `string \| undefined` | Parsed 2-digit year β€” only on `expirationDate` fields. |
633
+
634
+ > **Expiry data and PCI scope:** The expiry `onChange` event delivers parsed `month` and `year` to your handler for display purposes (e.g. "Card expires MM/YY"). These are not PANs or CVVs, but they are cardholder data. If your PCI scope requires zero cardholder data on the merchant page, do not read, log, or store these fields.
635
+
636
+ Auto-advance is built in: the vault automatically moves focus from card number β†’ expiry β†’ CVV when each field completes. No additional code required.
637
+
638
+ ---
639
+
640
+ ## React API
641
+
642
+ > πŸ“– [React guide](https://docs.ozura.com/sdks/elements/react) β€” `OzElements` provider, `useOzElements` hook, pre-built `OzCard` and `OzBankCard` components, and StrictMode behaviour.
643
+
644
+ ### OzElements provider
645
+
646
+ ```tsx
647
+ import { OzElements } from '@ozura/elements/react';
648
+
649
+ <OzElements
650
+ pubKey="pk_live_..."
651
+ sessionUrl="/api/oz-session"
652
+ appearance={{ theme: 'flat', variables: { colorPrimary: '#6366f1' } }}
653
+ onLoadError={() => setPaymentUnavailable(true)}
654
+ >
655
+ {children}
656
+ </OzElements>
657
+ ```
658
+
659
+ All `VaultOptions` are accepted as props. The provider creates a single `OzVault` instance and destroys it on unmount.
660
+
661
+ > **Prop changes and vault lifecycle:** Changing `pubKey`, `sessionUrl`, `frameBaseUrl`, `loadTimeoutMs`, `appearance`, `fonts`, or `sessionLimit` destroys the current vault and creates a new one β€” all field iframes will remount. Changing `getSessionKey`, `fetchWaxKey`, `onLoadError`, `onSessionRefresh`, or `onReady` updates the callback in place via refs without recreating the vault.
662
+
663
+ > **One card form per provider:** A vault holds one element per field type (`cardNumber`, `expiry`, `cvv`, etc.). Rendering two `<OzCard>` components under the same `<OzElements>` provider will cause the second to silently replace the first's iframes, breaking the first form. If you genuinely need two independent card forms on the same page, wrap each in its own `<OzElements>` provider with separate `pubKey` / `sessionUrl` configurations.
664
+
665
+ ---
666
+
667
+ ### OzCard
668
+
669
+ Drop-in combined card component. Renders card number, expiry, and CVV with a configurable layout.
670
+
671
+ ```tsx
672
+ import { OzCard } from '@ozura/elements/react';
673
+
674
+ <OzCard
675
+ layout="default" // "default" (number on top, expiry+CVV below) | "rows" (stacked)
676
+ onChange={(state) => {
677
+ // state.complete β€” all three fields complete + valid
678
+ // state.cardBrand β€” detected brand
679
+ // state.error β€” first error across all fields
680
+ // state.fields β€” per-field ElementChangeEvent objects
681
+ }}
682
+ onReady={() => console.log('all card fields loaded')}
683
+ disabled={isSubmitting}
684
+ labels={{ cardNumber: 'Card Number', expiry: 'Expiry', cvv: 'CVV' }}
685
+ placeholders={{ cardNumber: '1234 5678 9012 3456', expiry: 'MM/YY', cvv: 'Β·Β·Β·' }}
686
+ />
687
+ ```
688
+
689
+ `OzCardProps` (full):
690
+
691
+ | Prop | Type | Description |
692
+ |---|---|---|
693
+ | `layout` | `'default' \| 'rows'` | `'default'`: number full-width, expiry+CVV side by side. `'rows'`: all stacked. |
694
+ | `gap` | `number \| string` | Gap between fields. Default: `8` (px). |
695
+ | `style` | `ElementStyleConfig` | Shared style applied to all three inputs. |
696
+ | `styles` | `{ cardNumber?, expiry?, cvv? }` | Per-field overrides merged on top of `style`. |
697
+ | `classNames` | `{ cardNumber?, expiry?, cvv?, row? }` | CSS class names for field wrappers and the expiry+CVV row. |
698
+ | `labels` | `{ cardNumber?, expiry?, cvv? }` | Optional label text above each field. |
699
+ | `labelStyle` | `React.CSSProperties` | Style applied to all `<label>` elements. |
700
+ | `labelClassName` | `string` | Class applied to all `<label>` elements. |
701
+ | `placeholders` | `{ cardNumber?, expiry?, cvv? }` | Custom placeholder text per field. |
702
+ | `hideErrors` | `boolean` | Suppress the built-in error display. Handle via `onChange`. |
703
+ | `errorStyle` | `React.CSSProperties` | Style for the built-in error container. |
704
+ | `errorClassName` | `string` | Class for the built-in error container. |
705
+ | `renderError` | `(error: string) => ReactNode` | Custom error renderer. |
706
+ | `onChange` | `(state: OzCardState) => void` | Fires on any field change. |
707
+ | `onReady` | `() => void` | Fires once all three iframes have loaded. |
708
+ | `onFocus` | `(field: 'cardNumber' \| 'expiry' \| 'cvv') => void` | |
709
+ | `onBlur` | `(field: 'cardNumber' \| 'expiry' \| 'cvv') => void` | |
710
+ | `disabled` | `boolean` | Disable all inputs. |
711
+ | `className` | `string` | Class for the outer wrapper. |
712
+
713
+ ---
714
+
715
+ ### Individual field components
716
+
717
+ For custom layouts where `OzCard` is too opinionated:
718
+
719
+ ```tsx
720
+ import { OzCardNumber, OzExpiry, OzCvv } from '@ozura/elements/react';
721
+
722
+ <OzCardNumber onChange={handleChange} placeholder="Card number" />
723
+ <OzExpiry onChange={handleChange} />
724
+ <OzCvv onChange={handleChange} />
725
+ ```
726
+
727
+ All accept `OzFieldProps`:
728
+
729
+ | Prop | Type | Description |
730
+ |---|---|---|
731
+ | `style` | `ElementStyleConfig` | Input styles. |
732
+ | `placeholder` | `string` | Placeholder text. |
733
+ | `disabled` | `boolean` | Disables the input. |
734
+ | `loadTimeoutMs` | `number` | Iframe load timeout in ms. |
735
+ | `onChange` | `(event: ElementChangeEvent) => void` | |
736
+ | `onFocus` | `() => void` | |
737
+ | `onBlur` | `() => void` | |
738
+ | `onReady` | `() => void` | |
739
+ | `onLoadError` | `(error: string) => void` | |
740
+ | `className` | `string` | Class for the outer wrapper div. |
741
+
742
+ ---
743
+
744
+ ### OzBankCard
745
+
746
+ ```tsx
747
+ import { OzBankCard } from '@ozura/elements/react';
748
+
749
+ <OzBankCard
750
+ onChange={(state) => {
751
+ // state.complete, state.error, state.fields.accountNumber, state.fields.routingNumber
752
+ }}
753
+ labels={{ accountNumber: 'Account Number', routingNumber: 'Routing Number' }}
754
+ />
755
+ ```
756
+
757
+ Or use individual bank components:
758
+
759
+ ```tsx
760
+ import { OzBankAccountNumber, OzBankRoutingNumber } from '@ozura/elements/react';
761
+
762
+ <OzBankAccountNumber onChange={handleChange} />
763
+ <OzBankRoutingNumber onChange={handleChange} />
764
+ ```
765
+
766
+ ---
767
+
768
+ ### useOzElements()
769
+
770
+ ```ts
771
+ const { createToken, createBankToken, reset, ready, initError, tokenizeCount } = useOzElements();
772
+ ```
773
+
774
+ Must be called from inside an `<OzElements>` provider tree.
775
+
776
+ | Return | Type | Description |
777
+ |---|---|---|
778
+ | `createToken` | `(options?: TokenizeOptions) => Promise<TokenResponse>` | Tokenize mounted card elements. |
779
+ | `createBankToken` | `(options: BankTokenizeOptions) => Promise<BankTokenResponse>` | Tokenize mounted bank elements. |
780
+ | `reset` | `() => void` | Clear all mounted element fields without destroying the vault or refreshing the session. Call after a declined payment so the customer can re-enter their details. |
781
+ | `ready` | `boolean` | `true` when the tokenizer **and** all mounted element iframes are ready. Gate your submit button on this. See note below. |
782
+ | `initError` | `Error \| null` | Non-null if `OzVault.create()` failed (e.g. session endpoint unreachable). Render a fallback UI. |
783
+ | `tokenizeCount` | `number` | Number of successful tokenizations in the current session. Resets on session refresh or provider re-init. Useful for tracking calls against `sessionLimit`. |
784
+
785
+ > **`ready` vs `vault.isReady`:** `ready` from `useOzElements()` is a composite β€” it combines `vault.isReady` (tokenizer loaded) with element readiness (all mounted input iframes loaded). `vault.isReady` alone is insufficient for gating a submit button. Always use `ready` from `useOzElements()` in React.
786
+
787
+ ---
788
+
789
+ ## Vue API
790
+
791
+ > πŸ“– Vue 3 integration using the Composition API. Requires `vue >= 3.3`. No `.vue` SFC files needed in your setup β€” components work with `<script setup>` or the Options API.
792
+
793
+ ### Installation
794
+
795
+ npm install @ozura/elements vue
796
+
797
+ ### Quick start
798
+
799
+ `useOzElements()` calls Vue's `inject()` under the hood, so it must be called from a **child** of `<OzElements>`, not from the same component that renders it. Use two components β€” an outer wrapper that provides `<OzElements>`, and an inner form component that calls the composable:
800
+
801
+ **CheckoutPage.vue** β€” renders the provider
802
+
803
+ <script setup lang="ts">
804
+ import { OzElements } from '@ozura/elements/vue';
805
+ import CheckoutForm from './CheckoutForm.vue';
806
+ </script>
807
+
808
+ <template>
809
+ <OzElements pub-key="pk_live_..." session-url="/api/oz-session">
810
+ <CheckoutForm />
811
+ </OzElements>
812
+ </template>
813
+
814
+ **CheckoutForm.vue** β€” child component, calls the composable
815
+
816
+ <script setup lang="ts">
817
+ import { OzCardNumber, OzExpiry, OzCvv, useOzElements } from '@ozura/elements/vue';
818
+
819
+ const { createToken, ready } = useOzElements();
820
+
821
+ async function handlePay() {
822
+ const { token, cvcSession } = await createToken({
823
+ billing: { firstName: 'Jane', lastName: 'Doe' },
824
+ });
825
+ // send token to your backend
826
+ }
827
+ </script>
828
+
829
+ <template>
830
+ <OzCardNumber @change="(e) => console.log(e.cardBrand)" />
831
+ <OzExpiry />
832
+ <OzCvv />
833
+ <button :disabled="!ready" @click="handlePay">Pay</button>
834
+ </template>
835
+
836
+ ### Individual fields
837
+
838
+ | Component | Element type |
839
+ |---|---|
840
+ | `<OzCardNumber>` | Card number |
841
+ | `<OzExpiry>` | Expiry date |
842
+ | `<OzCvv>` | CVV / CVC |
843
+ | `<OzBankAccountNumber>` | Bank account number |
844
+ | `<OzBankRoutingNumber>` | Bank routing number |
845
+
846
+ ### `<OzElements>` props
847
+
848
+ | Prop | Type | Description |
849
+ |---|---|---|
850
+ | `pubKey` | `string` | **Required.** System public key from Ozura admin. |
851
+ | `sessionUrl` | `string` | URL of your backend session endpoint (simplest path). |
852
+ | `getSessionKey` | `(sessionId: string) => Promise<string>` | Custom async function for session key. Use instead of `sessionUrl` when you need custom headers or auth. |
853
+ | `frameBaseUrl` | `string` | Override the default frame host (`elements.ozura.com`). |
854
+ | `fonts` | `FontSource[]` | Custom fonts injected into element iframes. |
855
+ | `appearance` | `Appearance` | Global theme and variable overrides applied to all elements. |
856
+ | `loadTimeoutMs` | `number` | Iframe load timeout in ms. Default: 10 000. |
857
+ | `debug` | `boolean` | Enable structured `[OzVault]` debug logging. Default: `false`. |
858
+
859
+ **Event:** `@ready` β€” emitted once when the vault and all mounted field iframes are ready.
860
+
861
+ ### `useOzElements()` return values
862
+
863
+ | Value | Type | Description |
864
+ |---|---|---|
865
+ | `createToken` | `(options?: TokenizeOptions) => Promise<TokenResponse>` | Tokenize mounted card fields. |
866
+ | `createBankToken` | `(options?: BankTokenizeOptions) => Promise<BankTokenResponse>` | Tokenize mounted bank fields. |
867
+ | `ready` | `ComputedRef<boolean>` | `true` when vault and all field iframes are ready. Gate your submit button on this. |
868
+ | `initError` | `Ref<Error \| null>` | Non-null if `OzVault.create()` failed. Render a fallback UI. |
869
+ | `tokenizeCount` | `Ref<number>` | Successful tokenizations in the current session. Resets on session refresh. |
870
+ | `reset` | `() => void` | Clear all fields without destroying the vault. Call after a declined payment. |
871
+
872
+ ### Field props and events
873
+
874
+ All five field components share the same props and emits:
875
+
876
+ **Props:**
877
+
878
+ | Prop | Type | Description |
879
+ |---|---|---|
880
+ | `placeholder` | `string` | Override the default placeholder text. |
881
+ | `disabled` | `boolean` | Disable the input. |
882
+ | `style` | `ElementStyleConfig` | CSS-in-JS style object applied to the inner input. See [Styling](#styling). |
883
+
884
+ **Emits:**
885
+
886
+ | Event | Payload | Description |
887
+ |---|---|---|
888
+ | `@change` | `ElementChangeEvent` | Fires on every keystroke with validation state and metadata. |
889
+ | `@focus` | `void` | Fires when the field gains focus. |
890
+ | `@blur` | `void` | Fires when the field loses focus. |
891
+
892
+ ---
893
+
894
+ ## Styling
895
+
896
+ > πŸ“– [Styling guide](https://docs.ozura.com/sdks/elements/styling) β€” full property allowlist, theme variables, `appearance` options, custom fonts, and `var()` limitations.
897
+
898
+ ### Per-element styles
899
+
900
+ Styles apply inside each iframe's `<input>` element. Only an explicit allowlist of CSS properties is accepted (typography, spacing, borders, box-shadow, cursor, transitions). Values containing `url()`, `var()`, `expression()`, `javascript:`, or CSS breakout characters are blocked on both the SDK and iframe sides. Use literal values instead of CSS custom properties (`var(--token)` is rejected). When a value is stripped, the browser falls back to the element's default (unstyled) appearance for that property β€” the failure is silent with no error or console warning. Resolve design tokens to literal values before passing them in.
901
+
902
+ ```ts
903
+ const style: ElementStyleConfig = {
904
+ base: {
905
+ color: '#1a1a1a',
906
+ fontSize: '16px',
907
+ fontFamily: '"Inter", sans-serif',
908
+ padding: '10px 12px',
909
+ backgroundColor: '#ffffff',
910
+ borderRadius: '6px',
911
+ border: '1px solid #d1d5db',
912
+ },
913
+ focus: {
914
+ borderColor: '#6366f1',
915
+ boxShadow: '0 0 0 3px rgba(99,102,241,0.15)',
916
+ outline: 'none',
917
+ },
918
+ invalid: {
919
+ borderColor: '#ef4444',
920
+ color: '#dc2626',
921
+ },
922
+ complete: {
923
+ borderColor: '#22c55e',
924
+ },
925
+ placeholder: {
926
+ color: '#9ca3af',
927
+ },
928
+ };
929
+ ```
930
+
931
+ State precedence: `placeholder` applies to the `::placeholder` pseudo-element. `focus`, `invalid`, and `complete` merge on top of `base`.
932
+
933
+ ### Global appearance
934
+
935
+ Apply a preset theme and/or variable overrides to all elements at once:
936
+
937
+ ```ts
938
+ // OzVault.create
939
+ const vault = await OzVault.create({
940
+ pubKey: '...',
941
+ sessionUrl: '/api/oz-session',
942
+ appearance: {
943
+ theme: 'flat', // 'default' | 'night' | 'flat'
944
+ variables: {
945
+ colorText: '#1a1a1a',
946
+ colorBackground: '#ffffff',
947
+ colorPrimary: '#6366f1', // focus caret + color
948
+ colorDanger: '#dc2626', // invalid state
949
+ colorSuccess: '#16a34a', // complete state
950
+ colorPlaceholder: '#9ca3af',
951
+ fontFamily: '"Inter", sans-serif',
952
+ fontSize: '15px',
953
+ fontWeight: '400',
954
+ padding: '10px 14px',
955
+ letterSpacing: '0.01em',
956
+ },
957
+ },
958
+ });
959
+
960
+ // React provider
961
+ <OzElements pubKey="..." sessionUrl="..." appearance={{ theme: 'night' }}>
962
+ ```
963
+
964
+ Per-element `style` takes precedence over `appearance` variables.
965
+
966
+ > **`appearance: {}` is not "no theme":** Passing `appearance: {}` or `appearance: { variables: { ... } }` without a `theme` key applies the `'default'` preset as a base. To render elements with no preset styling, omit `appearance` entirely and use per-element `style` overrides.
967
+ >
968
+ > | `appearance` value | Result |
969
+ > |---|---|
970
+ > | *(omitted entirely)* | No preset β€” element uses minimal built-in defaults |
971
+ > | `{}` | Equivalent to `{ theme: 'default' }` β€” full default theme applied |
972
+ > | `{ theme: 'night' }` | Night theme |
973
+ > | `{ variables: { colorText: '#333' } }` | Default theme + variable overrides |
974
+
975
+ ### Custom fonts
976
+
977
+ Fonts are injected into each iframe so they render inside the input fields:
978
+
979
+ ```ts
980
+ fonts: [
981
+ // Google Fonts or any HTTPS CSS URL
982
+ { cssSrc: 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500&display=swap' },
983
+
984
+ // Custom @font-face
985
+ {
986
+ family: 'BrandFont',
987
+ src: 'url(https://cdn.example.com/brand-font.woff2)',
988
+ weight: '400',
989
+ style: 'normal',
990
+ display: 'swap',
991
+ },
992
+ ]
993
+ ```
994
+
995
+ Font `src` values must start with `url(https://...)`. HTTP and data URIs are rejected.
996
+
997
+ ---
998
+
999
+ ## Billing details
1000
+
1001
+ ```ts
1002
+ interface BillingDetails {
1003
+ firstName: string; // 1–50 characters
1004
+ lastName: string; // 1–50 characters
1005
+ email?: string; // Valid email, max 50 characters
1006
+ phone?: string; // E.164 format, e.g. "+15551234567", max 50 characters
1007
+ address?: {
1008
+ line1: string; // 1–50 characters
1009
+ line2?: string; // Optional, omitted from cardSale if blank
1010
+ city: string; // 1–50 characters
1011
+ state: string; // For US/CA: normalized to 2-letter abbreviation
1012
+ zip: string; // 1–50 characters
1013
+ country: string; // ISO 3166-1 alpha-2, e.g. "US"
1014
+ };
1015
+ }
1016
+ ```
1017
+
1018
+ Billing is validated and normalized by both `vault.createToken()` and the server-side handler factories. `TokenResponse.billing` contains the normalized result ready to spread into a `cardSale` call.
1019
+
1020
+ ---
1021
+
1022
+ ## Error handling
1023
+
1024
+ > πŸ“– [Error handling guide](https://docs.ozura.com/sdks/elements/error-handling) β€” `OzError` fields, every `errorCode` value, retry guidance, and session expiry behaviour.
1025
+
1026
+ All SDK errors are instances of `OzError`:
1027
+
1028
+ ```ts
1029
+ import { OzError } from '@ozura/elements';
1030
+
1031
+ try {
1032
+ const { token } = await vault.createToken({ billing });
1033
+ } catch (err) {
1034
+ if (err instanceof OzError) {
1035
+ switch (err.errorCode) {
1036
+ case 'network': // Connection failure β€” show retry UI
1037
+ case 'timeout': // 30s deadline exceeded β€” safe to retry
1038
+ case 'server': // 5xx from vault β€” transient, safe to retry
1039
+ if (err.retryable) showRetryPrompt();
1040
+ break;
1041
+
1042
+ case 'auth': // Bad pub key / API key β€” configuration issue
1043
+ case 'validation': // Bad card data β€” show field-level error
1044
+ case 'config': // frameBaseUrl not in permitted allowlist
1045
+ case 'unknown':
1046
+ showError(err.message);
1047
+ break;
1048
+ }
1049
+ }
1050
+ }
1051
+ ```
1052
+
1053
+ `OzError` fields:
1054
+
1055
+ | Field | Type | Description |
1056
+ |---|---|---|
1057
+ | `message` | `string` | Human-readable, consumer-facing error message. |
1058
+ | `errorCode` | `OzErrorCode` | `'network' \| 'timeout' \| 'auth' \| 'validation' \| 'server' \| 'config' \| 'unknown'` |
1059
+ | `raw` | `string` | Raw error string from the vault API, if available. |
1060
+ | `retryable` | `boolean` | `true` for `network`, `timeout`, `server`. `false` for `auth`, `validation`, `config`, `unknown`. |
1061
+
1062
+ > **Session expiry is handled automatically.** When a session expires or is consumed between initialization and the user clicking Pay, the SDK silently fetches a fresh session and retries the tokenization once. You will only receive an `auth` error if the session refresh itself fails β€” for example, if your `/api/oz-session` backend endpoint is unreachable. A healthy `auth` error in production means your session endpoint needs attention, not that the user's card is bad.
1063
+
1064
+ **Error normalisation helpers** (for displaying errors from `cardSale` to users):
1065
+
1066
+ ```ts
1067
+ import { normalizeVaultError, normalizeBankVaultError, normalizeCardSaleError } from '@ozura/elements';
1068
+
1069
+ // Maps vault tokenize error strings to user-facing copy
1070
+ const display = normalizeVaultError(err.raw); // card flows
1071
+ const display = normalizeBankVaultError(err.raw); // bank/ACH flows
1072
+ const display = normalizeCardSaleError(err.message); // cardSale API errors
1073
+ ```
1074
+
1075
+ ---
1076
+
1077
+ ## Debug mode
1078
+
1079
+ Pass `debug: true` in `VaultOptions` (or as a prop on `<OzElements>`) to activate structured console logging at every SDK lifecycle event.
1080
+
1081
+ ```ts
1082
+ const vault = await OzVault.create({
1083
+ pubKey: 'pk_live_...',
1084
+ sessionUrl: '/api/oz-session',
1085
+ debug: true, // enables [OzVault] console.log output
1086
+ });
1087
+ ```
1088
+
1089
+ ```tsx
1090
+ // React
1091
+ <OzElements pubKey="pk_live_..." sessionUrl="/api/oz-session" debug>
1092
+ ...
1093
+ </OzElements>
1094
+ ```
1095
+
1096
+ Each log entry is a `[OzVault] <message>` prefixed `console.log` call. Events logged include:
1097
+
1098
+ | Event | When it fires |
1099
+ |---|---|
1100
+ | `vault created` | Constructor completes |
1101
+ | `wax key received` | `fetchWaxKey` resolves |
1102
+ | `mounting tokenizer iframe` | Tokenizer iframe creation begins |
1103
+ | `tokenizer iframe ready` | Tokenizer iframe handshake complete |
1104
+ | `element iframe ready` | Each card/bank input iframe loads |
1105
+ | `field changed` | Per-field `change` event (empty/complete/valid/auto-advance state) |
1106
+ | `auto-advance` | Focus moves automatically between card fields |
1107
+ | `createToken() called` | Entry to `createToken()` |
1108
+ | `OZ_TOKENIZE sent` | Tokenize request dispatched to iframe |
1109
+ | `token received` | Token result returned (with elapsed ms) |
1110
+ | `token error` | Vault or network error during tokenize |
1111
+ | `proactive wax key refresh triggered` | Budget exhausted; refresh starting |
1112
+ | `wax key refresh started/succeeded/failed` | Refresh lifecycle |
1113
+ | `tab hidden` / `tab visible` | `visibilitychange` events |
1114
+ | `reset() called` | `vault.reset()` entry |
1115
+ | `destroy() called` | `vault.destroy()` entry |
1116
+
1117
+ **Security:** No sensitive data is ever logged. Wax keys, tokens, CVC sessions, and billing fields appear only as boolean presence flags (`waxKeyPresent: true`). Frame IDs and request IDs are truncated.
1118
+
1119
+ ### vault.debugState()
1120
+
1121
+ `vault.debugState()` is always available β€” regardless of whether `debug: true` was set β€” and returns a one-time snapshot for attaching to bug reports:
1122
+
1123
+ ```ts
1124
+ console.log(vault.debugState());
1125
+ ```
1126
+
1127
+ Sample output:
1128
+
1129
+ ```json
1130
+ {
1131
+ "vaultId": "vault_abc12...",
1132
+ "isReady": true,
1133
+ "tokenizing": null,
1134
+ "destroyed": false,
1135
+ "waxKeyPresent": true,
1136
+ "tokenizeSuccessCount": 1,
1137
+ "maxTokenizeCalls": 3,
1138
+ "resetCount": 0,
1139
+ "elements": ["cardNumber", "expirationDate", "cvv"],
1140
+ "bankElements": [],
1141
+ "completionState": { "a1b2c3d4": true, "e5f6a7b8": true, "c9d0e1f2": false },
1142
+ "pendingTokenizations": 0,
1143
+ "pendingBankTokenizations": 0
1144
+ }
1145
+ ```
1146
+
1147
+ ---
1148
+
1149
+ ## Server utilities
1150
+
1151
+ > πŸ“– [Server SDK guide](https://docs.ozura.com/sdks/elements/server) β€” `Ozura` class methods, route handler factories, `getClientIp`, error types, and rate limits.
1152
+
1153
+ ### Ozura class
1154
+
1155
+ ```ts
1156
+ import { Ozura, OzuraError } from '@ozura/elements/server';
1157
+
1158
+ const ozura = new Ozura({
1159
+ merchantId: process.env.MERCHANT_ID!,
1160
+ apiKey: process.env.MERCHANT_API_KEY!,
1161
+ vaultKey: process.env.VAULT_API_KEY!,
1162
+ // apiUrl: 'https://api.ozura.com', // override Pay API URL
1163
+ // vaultUrl: 'https://vault.ozura.com', // override vault URL
1164
+ timeoutMs: 30000, // default
1165
+ retries: 2, // max retry attempts for 5xx/network errors (3 total attempts)
1166
+ });
1167
+ ```
1168
+
1169
+ > **Tokenize-only integrations** (session creation + tokenize cards, no charging) only need `vaultKey`. The `merchantId` and `apiKey` fields are optional β€” they are validated lazily and only required when `cardSale()` is called.
1170
+ >
1171
+ > ```ts
1172
+ > const ozura = new Ozura({ vaultKey: process.env.VAULT_API_KEY! });
1173
+ > ```
1174
+
1175
+ **Methods:**
1176
+
1177
+ ```ts
1178
+ // Charge a tokenized card
1179
+ const result = await ozura.cardSale({
1180
+ token: tokenResponse.token,
1181
+ cvcSession: tokenResponse.cvcSession,
1182
+ amount: '49.00',
1183
+ currency: 'USD', // default: 'USD'
1184
+ billing: tokenResponse.billing,
1185
+ clientIpAddress: '1.2.3.4', // fetch server-side, never from the browser
1186
+ // surchargePercent, tipAmount, salesTaxExempt, processor
1187
+ });
1188
+ // result.transactionId, result.amount, result.cardLastFour, result.cardBrand
1189
+ // result.surchargeAmount and result.tipAmount are optional β€” only present when non-zero
1190
+ const surcharge = result.surchargeAmount ?? '0.00';
1191
+ const tip = result.tipAmount ?? '0.00';
1192
+
1193
+ // Create a session key (for custom session endpoint implementations)
1194
+ const { sessionKey, expiresInSeconds } = await ozura.createSession({
1195
+ sessionId,
1196
+ sessionLimit: 3, // must match VaultOptions.sessionLimit on the client (default: 3)
1197
+ // pass null to remove the cap (vault default = unlimited)
1198
+ // Optional β€” stored in vault audit log for correlation with your own records:
1199
+ // orderId: order.id,
1200
+ // customerId: user.id,
1201
+ // cartId: cart.id,
1202
+ // metadata: { source: 'web' },
1203
+ // ttlSeconds: 600, // shorter TTL for quicker checkouts (default: 1800)
1204
+ });
1205
+
1206
+ // Revoke a session β€” call on all three session-end paths
1207
+ // Best-effort β€” never throws. Shortens the exposure window before the vault's ~30 min TTL.
1208
+ await ozura.revokeSession(sessionKey);
1209
+
1210
+ // Suggested pattern β€” wire all three exit paths:
1211
+ // 1. Payment success
1212
+ const result = await ozura.cardSale({ ... });
1213
+ await ozura.revokeSession(sessionKey); // session is spent; close the window immediately
1214
+
1215
+ // 2. User cancels checkout
1216
+ router.post('/api/cancel', async (req) => {
1217
+ const { sessionKey } = await db.session.get(req.sessionId);
1218
+ await ozura.revokeSession(sessionKey);
1219
+ return Response.json({ ok: true });
1220
+ });
1221
+
1222
+ // 3. Page/tab close (best-effort β€” browser may not deliver this)
1223
+ // Use sendBeacon so the request survives navigation / tab close.
1224
+ window.addEventListener('visibilitychange', () => {
1225
+ if (document.visibilityState === 'hidden') {
1226
+ navigator.sendBeacon('/api/cancel', JSON.stringify({ sessionId }));
1227
+ }
1228
+ });
1229
+
1230
+ // List transactions
1231
+ const { transactions, pagination } = await ozura.listTransactions({
1232
+ dateFrom: '2025-01-01',
1233
+ dateTo: '2025-12-31',
1234
+ transactionType: 'CreditCardSale',
1235
+ page: 1,
1236
+ limit: 50,
1237
+ });
1238
+ ```
1239
+
1240
+ **`OzuraError`** (thrown by all `Ozura` methods):
1241
+
1242
+ ```ts
1243
+ try {
1244
+ await ozura.cardSale(input);
1245
+ } catch (err) {
1246
+ if (err instanceof OzuraError) {
1247
+ err.statusCode; // HTTP status code
1248
+ err.message; // Normalized message
1249
+ err.raw; // Raw API response string
1250
+ err.retryAfter; // Seconds (only present on 429)
1251
+ }
1252
+ }
1253
+ ```
1254
+
1255
+ Rate limits: `cardSale` β€” 100 req/min per merchant. `listTransactions` β€” 200 req/min per merchant.
1256
+
1257
+ > **Retry behavior:** `createSession` and `listTransactions` retry on 5xx and network errors using exponential backoff (1 s / 2 s / 4 s…) up to `retries + 1` total attempts. **`cardSale` is never retried** β€” it is a non-idempotent financial operation and the result of a duplicate charge cannot be predicted.
1258
+
1259
+ ---
1260
+
1261
+ ### Route handler factories
1262
+
1263
+ The server package exports factory functions covering two runtimes Γ— two endpoints:
1264
+
1265
+ | Function | Runtime | Endpoint |
1266
+ |---|---|---|
1267
+ | `createSessionHandler` | Fetch API (Next.js App Router, Cloudflare, Vercel Edge) | `POST /api/oz-session` |
1268
+ | `createSessionMiddleware` | Express / Connect | `POST /api/oz-session` |
1269
+ | `createCardSaleHandler` | Fetch API | `POST /api/charge` |
1270
+ | `createCardSaleMiddleware` | Express / Connect | `POST /api/charge` |
1271
+
1272
+ `createCardSaleHandler` / `createCardSaleMiddleware` accept a `CardSaleHandlerOptions` object:
1273
+
1274
+ ```ts
1275
+ interface CardSaleHandlerOptions {
1276
+ /**
1277
+ * Required. Return the charge amount as a decimal string.
1278
+ * Never trust the amount from the request body β€” resolve it from your database.
1279
+ */
1280
+ getAmount: (body: Record<string, unknown>) => Promise<string>;
1281
+
1282
+ /**
1283
+ * Optional. Return the ISO 4217 currency code. Default: "USD".
1284
+ */
1285
+ getCurrency?: (body: Record<string, unknown>) => Promise<string>;
1286
+ }
1287
+ ```
1288
+
1289
+ Both handler factories validate `Content-Type: application/json`, run `validateBilling()`, extract the client IP from standard proxy headers, and return normalized `{ transactionId, amount, cardLastFour, cardBrand }` on success.
1290
+
1291
+ ---
1292
+
1293
+ ## Local development
1294
+
1295
+ The repository includes a development server at `dev-server.mjs` that serves the built frame assets and proxies vault API requests:
1296
+
1297
+ ```bash
1298
+ npm run dev # build + start dev server on http://localhost:4242
1299
+ ```
1300
+
1301
+ Set `frameBaseUrl` to point your vault at the local server:
1302
+
1303
+ ```ts
1304
+ const vault = await OzVault.create({
1305
+ pubKey: 'pk_test_...',
1306
+ sessionUrl: '/api/oz-session',
1307
+ frameBaseUrl: 'http://localhost:4242', // local dev only
1308
+ });
1309
+ ```
1310
+
1311
+ Or in React:
1312
+
1313
+ ```tsx
1314
+ <OzElements
1315
+ pubKey="pk_test_..."
1316
+ sessionUrl="/api/oz-session"
1317
+ frameBaseUrl="http://localhost:4242"
1318
+ >
1319
+ ```
1320
+
1321
+ Configure environment variables for the dev server:
1322
+
1323
+ ```bash
1324
+ VAULT_URL=https://vault-staging.example.com
1325
+ VAULT_API_KEY=vk_test_...
1326
+ ```
1327
+
1328
+ ---
1329
+
1330
+ ## Content Security Policy
1331
+
1332
+ The SDK loads iframes from the Ozura frame origin. Add the following directives to your CSP:
1333
+
1334
+ ```
1335
+ frame-src https://elements.ozura.com;
1336
+ ```
1337
+
1338
+ If loading custom fonts via `fonts[].cssSrc`, also allow the font stylesheet origin:
1339
+
1340
+ ```
1341
+ style-src https://fonts.googleapis.com;
1342
+ font-src https://fonts.gstatic.com;
1343
+ ```
1344
+
1345
+ To verify your CSP after a build:
1346
+
1347
+ ```bash
1348
+ npm run check:csp
1349
+ ```
1350
+
1351
+ ---
1352
+
1353
+ ## TypeScript reference
1354
+
1355
+ > πŸ“– [API reference](https://docs.ozura.com/sdks/elements/api-reference) β€” every interface, union, and enum fully annotated with JSDoc.
1356
+
1357
+ All public types are exported from `@ozura/elements`:
1358
+
1359
+ ```ts
1360
+ import type {
1361
+ // Element types
1362
+ ElementType, // 'cardNumber' | 'cvv' | 'expirationDate'
1363
+ BankElementType, // 'accountNumber' | 'routingNumber'
1364
+ ElementOptions,
1365
+ ElementStyleConfig,
1366
+ ElementStyle,
1367
+ ElementChangeEvent,
1368
+
1369
+ // Vault config
1370
+ VaultOptions,
1371
+ FontSource,
1372
+ CssFontSource,
1373
+ CustomFontSource,
1374
+ Appearance,
1375
+ AppearanceVariables,
1376
+ OzTheme, // 'default' | 'night' | 'flat'
1377
+
1378
+ // Tokenization
1379
+ TokenizeOptions,
1380
+ BankTokenizeOptions,
1381
+ TokenResponse,
1382
+ BankTokenResponse,
1383
+ CardMetadata,
1384
+ BankAccountMetadata,
1385
+
1386
+ // Billing
1387
+ BillingDetails,
1388
+ BillingAddress,
1389
+
1390
+ // Card sale
1391
+ CardSaleRequest,
1392
+ CardSaleResponseData,
1393
+ CardSaleApiResponse,
1394
+
1395
+ // Transactions
1396
+ TransactionQueryParams,
1397
+ TransactionQueryPagination,
1398
+ TransactionQueryResponse,
1399
+ TransactionType,
1400
+ TransactionData,
1401
+ CardTransactionData,
1402
+ AchTransactionData,
1403
+ CryptoTransactionData,
1404
+
1405
+ // Errors
1406
+ OzErrorCode,
1407
+ } from '@ozura/elements';
1408
+ ```
1409
+
1410
+ Server-specific types are exported from `@ozura/elements/server`:
1411
+
1412
+ ```ts
1413
+ import type {
1414
+ OzuraConfig,
1415
+ CardSaleInput,
1416
+ CreateSessionOptions,
1417
+ CreateSessionResult,
1418
+ ListTransactionsInput,
1419
+ } from '@ozura/elements/server';
1420
+ ```
1421
+
1422
+ React-specific types are exported from `@ozura/elements/react`:
1423
+
1424
+ ```ts
1425
+ import type { OzFieldProps, OzCardProps, OzCardState, OzBankCardProps, OzBankCardState } from '@ozura/elements/react';
1426
+ ```
1427
+
1428
+ ---
1429
+
1430
+ ## Need help?
1431
+
1432
+ The full documentation β€” including interactive examples, a complete API reference, and integration walkthroughs β€” lives at:
1433
+
1434
+ **[docs.ozura.com/sdks/elements/overview](https://docs.ozura.com/sdks/elements/overview)**
1435
+
1436
+ | I want to… | Go to |
1437
+ |---|---|
1438
+ | Get started from scratch | [Installation](https://docs.ozura.com/sdks/elements/installation) |
1439
+ | Build a card payment form | [Card elements](https://docs.ozura.com/sdks/elements/card-elements) |
1440
+ | Build an ACH / bank form | [Bank elements](https://docs.ozura.com/sdks/elements/bank-elements) |
1441
+ | Use the React components | [React guide](https://docs.ozura.com/sdks/elements/react) |
1442
+ | Style the input fields | [Styling](https://docs.ozura.com/sdks/elements/styling) |
1443
+ | Handle errors correctly | [Error handling](https://docs.ozura.com/sdks/elements/error-handling) |
1444
+ | Set up the server side | [Server SDK](https://docs.ozura.com/sdks/elements/server) |
1445
+ | Look up a type or method | [API reference](https://docs.ozura.com/sdks/elements/api-reference) |