@paypercut/checkout-js 1.2.18 → 1.3.0

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
@@ -12,6 +12,18 @@ A lightweight, framework-agnostic JavaScript SDK for embedding Paypercut Checkou
12
12
  ## Table of Contents
13
13
 
14
14
  - [Installation](#installation)
15
+ - [Elements](#elements)
16
+ - [Complete TypeScript / ESM example](#complete-typescript--esm-example)
17
+ - [Complete vanilla JavaScript example](#complete-vanilla-javascript-example)
18
+ - [Card Element](#card-element)
19
+ - [Split card fields](#split-card-fields)
20
+ - [Payment Element availability](#payment-element-availability)
21
+ - [Express Checkout Element](#express-checkout-element)
22
+ - [Confirming payments and handling next actions](#confirming-payments-and-handling-next-actions)
23
+ - [Errors, retries, and application return](#errors-retries-and-application-return)
24
+ - [Events](#elements-events)
25
+ - [Localization, appearance, and layout](#localization-appearance-and-layout)
26
+ - [Lifecycle and safe teardown](#lifecycle-and-safe-teardown)
15
27
  - [Quick Start — Embedded Checkout](#quick-start)
16
28
  - [API Reference — Embedded Checkout](#api-reference)
17
29
  - [**Customisation**](#customisation)
@@ -20,16 +32,6 @@ A lightweight, framework-agnostic JavaScript SDK for embedding Paypercut Checkou
20
32
  - [AppearanceVariables reference](#appearancevariables-reference)
21
33
  - [Events — Embedded Checkout](#events)
22
34
  - [Form Validation for Wallet Payments](#form-validation-for-wallet-payments)
23
- - [**Express Checkout (Apple Pay / Google Pay)**](#express-checkout-apple-pay--google-pay)
24
- - [How It Works](#how-it-works)
25
- - [Initialization](#initialization)
26
- - [Button Options](#button-options)
27
- - [Options](#express-checkout-options)
28
- - [Methods](#express-checkout-methods)
29
- - [Events](#express-checkout-events)
30
- - [Shipping address & option changes](#shipping-address--option-changes)
31
- - [Full Example](#express-checkout-full-example)
32
- - [React Example](#express-checkout-react-example)
33
35
  - [Types](#types)
34
36
  - [Usage Examples](#usage-examples)
35
37
  - [Vanilla JavaScript](#vanilla-javascript-cdn)
@@ -66,17 +68,735 @@ pnpm add @paypercut/checkout-js
66
68
  ### Via CDN
67
69
 
68
70
  ```html
69
- <!-- jsDelivr (recommended with SRI) -->
70
- <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js@1.2.18/dist/paypercut-checkout.iife.min.js"
71
- integrity="sha384-..."
72
- crossorigin="anonymous"></script>
71
+ <!-- Pin an exact released version in production. -->
72
+ <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js@latest/dist/paypercut-checkout.iife.min.js"></script>
73
73
 
74
74
  <!-- or UNPKG -->
75
- <script src="https://unpkg.com/@paypercut/checkout-js@1.2.18/dist/paypercut-checkout.iife.min.js"></script>
75
+ <script src="https://unpkg.com/@paypercut/checkout-js@latest/dist/paypercut-checkout.iife.min.js"></script>
76
76
  ```
77
77
 
78
78
  ---
79
79
 
80
+ ## Elements
81
+
82
+ The Elements API is the composable integration surface for merchant-owned
83
+ payment pages. One `elements()` group owns the shared amount, currency, mode,
84
+ locale, appearance, secure components, validation state, and Payment Method
85
+ creation attempt.
86
+
87
+ The lifecycle is deliberately explicit:
88
+
89
+ 1. `paypercut.elements(options)` creates a group.
90
+ 2. `elements.create(type)` creates a visual Element; mounting it only renders
91
+ secure collection UI.
92
+ 3. `await elements.submit()` validates and prepares the current group. It does
93
+ not create a Payment Method or confirm a payment.
94
+ 4. `await paypercut.createPaymentMethod({ elements, params? })` creates an opaque
95
+ Payment Method.
96
+ 5. Send only the Payment Method ID and merchant-owned order data to your server.
97
+ 6. If the server returns an opaque client secret, call `confirmPayment()` (or its
98
+ advanced alias `handleNextAction()`) in the browser.
99
+
100
+ Mounting an Element never creates a Payment Method and never creates or confirms
101
+ a payment. The merchant server remains authoritative for the final amount,
102
+ currency, order state, authorization, capture, and fulfillment.
103
+
104
+ ### Complete TypeScript / ESM example
105
+
106
+ Use this merchant-owned markup:
107
+
108
+ ```html
109
+ <form id="payment-form">
110
+ <label>Billing name <input id="billing-name" autocomplete="cc-name" /></label>
111
+ <label>Billing email <input id="billing-email" type="email" autocomplete="email" /></label>
112
+ <div id="card-element"></div>
113
+ <button id="pay" type="submit" disabled>Pay</button>
114
+ </form>
115
+ ```
116
+
117
+ ```ts
118
+ import {
119
+ Paypercut,
120
+ type ElementsSubmitError,
121
+ type PaypercutConfirmPaymentResult,
122
+ } from '@paypercut/checkout-js';
123
+
124
+ type MerchantResponse = {
125
+ clientSecret?: string;
126
+ redirectUrl?: string;
127
+ };
128
+
129
+ const paypercut = Paypercut({ publishableKey: 'pk_test_replace_me' });
130
+ const elements = paypercut.elements({
131
+ mode: 'payment',
132
+ amount: 4999,
133
+ currency: 'EUR',
134
+ locale: 'auto',
135
+ appearance: {
136
+ theme: 'light',
137
+ inputs: 'condensed',
138
+ labels: 'auto',
139
+ },
140
+ });
141
+
142
+ const card = elements.create('card');
143
+ card.on('ready', () => {
144
+ document.querySelector<HTMLButtonElement>('#pay')!.disabled = false;
145
+ });
146
+ card.on('error', ({ code, recoverable }) => {
147
+ console.error('Secure payment UI error', { code, recoverable });
148
+ });
149
+ card.mount('#card-element');
150
+
151
+ const form = document.querySelector<HTMLFormElement>('#payment-form')!;
152
+ form.addEventListener('submit', async (event) => {
153
+ event.preventDefault();
154
+
155
+ try {
156
+ await elements.submit();
157
+ const paymentMethod = await paypercut.createPaymentMethod({
158
+ elements,
159
+ params: {
160
+ billing_details: {
161
+ name: document.querySelector<HTMLInputElement>('#billing-name')!.value,
162
+ email: document.querySelector<HTMLInputElement>('#billing-email')!.value,
163
+ },
164
+ },
165
+ });
166
+
167
+ const response = await fetch('/api/payments', {
168
+ method: 'POST',
169
+ headers: { 'Content-Type': 'application/json' },
170
+ body: JSON.stringify({ payment_method: paymentMethod.id }),
171
+ });
172
+ if (!response.ok) throw new Error('The server could not start the payment.');
173
+ const serverResult = (await response.json()) as MerchantResponse;
174
+
175
+ let result: PaypercutConfirmPaymentResult | undefined;
176
+ if (serverResult.clientSecret) {
177
+ result = await paypercut.confirmPayment({
178
+ clientSecret: serverResult.clientSecret,
179
+ });
180
+ }
181
+
182
+ if (
183
+ result &&
184
+ !['succeeded', 'processing', 'requires_capture'].includes(
185
+ result.checkoutSession.paymentObjectStatus ?? '',
186
+ )
187
+ ) {
188
+ throw new Error(`Payment status: ${result.checkoutSession.paymentObjectStatus}`);
189
+ }
190
+ if (serverResult.redirectUrl) window.location.assign(serverResult.redirectUrl);
191
+ } catch (error) {
192
+ const failure = error as Partial<ElementsSubmitError>;
193
+ console.error('Payment attempt failed', {
194
+ code: failure.code ?? 'merchant_payment_failed',
195
+ recoverable: failure.recoverable ?? false,
196
+ });
197
+ }
198
+ });
199
+
200
+ window.addEventListener('pagehide', () => elements.destroy(), { once: true });
201
+ ```
202
+
203
+ The same named client is available from CommonJS:
204
+
205
+ ```js
206
+ const { Paypercut } = require('@paypercut/checkout-js');
207
+ const paypercut = Paypercut({ publishableKey: 'pk_test_replace_me' });
208
+ ```
209
+
210
+ ### Complete vanilla JavaScript example
211
+
212
+ ```html
213
+ <!doctype html>
214
+ <html lang="en">
215
+ <head>
216
+ <meta charset="utf-8" />
217
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
218
+ <title>Paypercut card payment</title>
219
+ </head>
220
+ <body>
221
+ <form id="payment-form">
222
+ <label>Billing name <input id="billing-name" autocomplete="cc-name" /></label>
223
+ <div id="card-element"></div>
224
+ <button id="pay" type="submit" disabled>Pay</button>
225
+ <p id="payment-status" role="status"></p>
226
+ </form>
227
+
228
+ <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js@latest/dist/paypercut-checkout.iife.min.js"></script>
229
+ <script>
230
+ const status = document.querySelector('#payment-status');
231
+ const paypercut = window.Paypercut({ publishableKey: 'pk_test_replace_me' });
232
+ const elements = paypercut.elements({
233
+ mode: 'payment',
234
+ amount: 4999,
235
+ currency: 'EUR',
236
+ locale: 'auto',
237
+ });
238
+ const card = elements.create('card');
239
+
240
+ card.on('ready', () => {
241
+ document.querySelector('#pay').disabled = false;
242
+ });
243
+ card.on('error', ({ code }) => {
244
+ status.textContent = `Payment form error: ${code}`;
245
+ });
246
+ card.mount('#card-element');
247
+
248
+ document.querySelector('#payment-form').addEventListener('submit', async (event) => {
249
+ event.preventDefault();
250
+ status.textContent = 'Preparing payment…';
251
+ try {
252
+ await elements.submit();
253
+ const paymentMethod = await paypercut.createPaymentMethod({
254
+ elements,
255
+ params: {
256
+ billing_details: {
257
+ name: document.querySelector('#billing-name').value,
258
+ },
259
+ },
260
+ });
261
+
262
+ const response = await fetch('/api/payments', {
263
+ method: 'POST',
264
+ headers: { 'Content-Type': 'application/json' },
265
+ body: JSON.stringify({ payment_method: paymentMethod.id }),
266
+ });
267
+ const serverResult = await response.json();
268
+ if (!response.ok) throw new Error('The server rejected the payment.');
269
+
270
+ if (serverResult.clientSecret) {
271
+ const result = await paypercut.confirmPayment({
272
+ clientSecret: serverResult.clientSecret,
273
+ });
274
+ status.textContent = `Payment status: ${result.checkoutSession.paymentStatus}`;
275
+ } else {
276
+ status.textContent = 'Payment Method created.';
277
+ }
278
+ } catch (error) {
279
+ status.textContent = error && error.code
280
+ ? `Payment error: ${error.code}`
281
+ : 'Payment failed.';
282
+ }
283
+ });
284
+
285
+ window.addEventListener('pagehide', () => elements.destroy(), { once: true });
286
+ </script>
287
+ </body>
288
+ </html>
289
+ ```
290
+
291
+ Creating the group does not create a payment, setup, subscription, or Payment
292
+ Method. Amounts are non-negative integers in the currency's minor unit and the
293
+ currency is a three-letter ISO 4217 code.
294
+
295
+ ### Card Element
296
+
297
+ ```ts
298
+ const card = elements.create('card');
299
+ card.mount('#card-element');
300
+
301
+ await elements.submit();
302
+ const paymentMethod = await paypercut.createPaymentMethod({ elements });
303
+ // Send paymentMethod.id to your server. Do not confirm a payment from browser input.
304
+ ```
305
+
306
+ When the same card may be used again, declare that purpose once while creating
307
+ the Elements group:
308
+
309
+ ```ts
310
+ const elements = paypercut.elements({
311
+ mode: 'payment',
312
+ amount: 4999,
313
+ currency: 'USD',
314
+ setupFutureUsage: 'off_session', // or 'on_session'
315
+ });
316
+ const card = elements.create('card');
317
+ card.mount('#card-element');
318
+
319
+ await elements.submit();
320
+ const paymentMethod = await paypercut.createPaymentMethod({
321
+ elements,
322
+ params: {
323
+ billing_details: {
324
+ name: 'Ada Lovelace',
325
+ email: 'ada@example.com',
326
+ address: { country: 'GB', postal_code: 'SW1A 1AA' },
327
+ },
328
+ },
329
+ });
330
+ ```
331
+
332
+ Omitting `setupFutureUsage` in payment mode prepares the Payment Method for the
333
+ current payment only. Use `on_session` when the customer is expected to be
334
+ present for later use, or `off_session` when the server may use it without the
335
+ customer present. This is an immutable group-level option;
336
+ `createPaymentMethod()` cannot override it. It prepares the instrument and
337
+ authentication context but does not create a mandate, attach a customer, or
338
+ guarantee that a future authorization will succeed.
339
+
340
+ `params.billing_details` belongs to the Payment Method creation attempt, not to
341
+ the Elements group or a durable Customer. It accepts `name`, `email`, `phone`,
342
+ and `address` (`line1`, `line2`, `city`, `state`, `postal_code`, `country`).
343
+ Country accepts an ISO 3166-1 alpha-2 code and is normalized to uppercase. The
344
+ call does not create or attach a Customer. An identical retry on the same group
345
+ shares the existing attempt; changing billing details after creation requires a
346
+ fresh Elements group.
347
+
348
+ For flows that are already known to prepare a card for later use, initialize the
349
+ group with `setup` or `subscription` mode:
350
+
351
+ ```ts
352
+ const elements = paypercut.elements({
353
+ mode: 'subscription', // or 'setup'
354
+ amount: 4999,
355
+ currency: 'USD',
356
+ });
357
+
358
+ const card = elements.create('card');
359
+ card.mount('#card-element');
360
+ await elements.submit();
361
+ const paymentMethod = await paypercut.createPaymentMethod({ elements });
362
+ ```
363
+
364
+ Both modes derive `setupFutureUsage: 'off_session'` automatically and reject an
365
+ `on_session` override. They prepare an authenticated card Payment Method only:
366
+ they do not create a setup resource, subscription, mandate, customer attachment,
367
+ Checkout Session, or payment. `amount` and `currency` are still required by the
368
+ current public signature. Express Checkout is currently available only in
369
+ `payment` mode.
370
+
371
+ ### Split card fields
372
+
373
+ Use split fields when the merchant layout needs independent placement. All three
374
+ fields belong to the same Elements group. A field never exposes `submit()` and
375
+ its change event contains only PCI-safe state such as completeness and card
376
+ brand—never PAN, expiry, or CVC values.
377
+
378
+ ```ts
379
+ const cardNumber = elements.create('cardNumber', {
380
+ // Defaults to true. Set false to hide every card-number badge and reclaim
381
+ // its input space.
382
+ showIcon: true,
383
+ });
384
+ const cardExpiry = elements.create('cardExpiry');
385
+ const cardCvc = elements.create('cardCvc');
386
+
387
+ cardNumber.mount('#card-number');
388
+ cardExpiry.mount('#card-expiry');
389
+ cardCvc.mount('#card-cvc');
390
+
391
+ cardNumber.on('change', ({ complete, empty, brand }) => {
392
+ console.log({ complete, empty, brand });
393
+ });
394
+
395
+ // Validation is explicit and creates no server-side payment resources.
396
+ await elements.submit();
397
+
398
+ // Payment Method creation uses the same public lifecycle as Card Element.
399
+ const paymentMethod = await paypercut.createPaymentMethod({
400
+ elements,
401
+ params: {
402
+ billing_details: {
403
+ name: document.querySelector<HTMLInputElement>('[autocomplete="cc-name"]')?.value,
404
+ },
405
+ },
406
+ });
407
+ ```
408
+
409
+ For reusable cards, set `setupFutureUsage: 'on_session' | 'off_session'` in the
410
+ `paypercut.elements(...)` options before creating these fields.
411
+
412
+ Keep the three mount points and any merchant-owned cardholder-name input inside
413
+ one semantic form. Use the standard `cc-name` token for that merchant-owned
414
+ field; Paypercut supplies the corresponding `cc-number`, `cc-exp`, and `cc-csc`
415
+ metadata inside the three secure inputs.
416
+
417
+ ```html
418
+ <form id="payment-form" autocomplete="on">
419
+ <label>
420
+ Cardholder name
421
+ <input name="cardholderName" autocomplete="cc-name" />
422
+ </label>
423
+ <div id="card-number"></div>
424
+ <div id="card-expiry"></div>
425
+ <div id="card-cvc"></div>
426
+ <button type="submit">Continue</button>
427
+ </form>
428
+ ```
429
+
430
+ The secure fields expose the standard browser saved-card autocomplete metadata.
431
+ This is browser/password-manager integration, not Apple Pay or Google Pay.
432
+ Browsers may intentionally decline to store or refill CVC, so CVC autofill must
433
+ never be a checkout requirement.
434
+
435
+ One group accepts exactly one field of each split type. It rejects duplicate
436
+ fields and rejects mixing split fields with the high-level Card Element;
437
+ Express Checkout may coexist.
438
+
439
+ The SDK owns the non-sensitive visual shell around each secure input:
440
+ above or floating labels, focus and invalid borders, localized error messages,
441
+ and the card-number brand badges. `appearance.inputs` and `appearance.labels`
442
+ use the same `condensed | spaced` and `auto | above | floating` contract as the
443
+ Card Element. `.Input`, `.Input:focus`, `.Input--invalid`, `.Label`, and
444
+ `.Error` rules apply to split fields as well. Card-brand SVGs are embedded in
445
+ the SDK bundle, so showing them does not add an image-host CSP requirement.
446
+
447
+ Incomplete and invalid provider state is exposed through the PCI-safe `change`
448
+ event while the user edits. The visible error is delayed until blur and clears
449
+ on refocus or correction. This applies independently to card number, expiration
450
+ date, and security code.
451
+
452
+ `elements.submit()` validates the active payment-method source and displays its
453
+ field errors without tokenizing or creating server-side payment resources. A
454
+ successful validation is bound to the current source and input revision; card
455
+ edits, remounts, test presets, or group updates require another `submit()`.
456
+
457
+ `paypercut.createPaymentMethod({ elements, params? })` is the regular
458
+ Payment Method creation facade. `params.billing_details` is call-level Payment
459
+ Method data; it is not mutable group-level customer state. Calling creation
460
+ without a current successful validation rejects with
461
+ `elements_submit_required`.
462
+
463
+ Submission is single-flight and its terminal state belongs to the Elements
464
+ group, not to a particular iframe or field mount. Concurrent calls share one
465
+ attempt, and a successful result is returned again without creating another
466
+ Payment Method. If the SDK loses the authoritative result after submission has
467
+ started and still cannot verify it, the group rejects with
468
+ `elements_submit_indeterminate` and `recoverable: false`. Do not blindly create
469
+ a second Payment Method. Reconcile the order on your server; only then destroy
470
+ the old group and begin a deliberate new attempt.
471
+
472
+ ### Payment Element availability
473
+
474
+ This release does **not** export `elements.create('payment')`. The name is
475
+ reserved for a future multi-payment-method selector. Use Card Element for a
476
+ combined card form, split card fields for a custom card layout, and Express
477
+ Checkout Element for Apple Pay and Google Pay. A merchant asking for Card
478
+ Element will never receive additional payment methods because of server-side
479
+ configuration.
480
+
481
+ ### Confirming payments and handling next actions
482
+
483
+ Payment Method creation and payment confirmation are separate operations. Send
484
+ the opaque Payment Method ID to your authenticated server. The server creates or
485
+ confirms the order and may return an opaque Checkout Session client secret when
486
+ browser participation is required:
487
+
488
+ ```ts
489
+ const paymentMethod = await paypercut.createPaymentMethod({ elements });
490
+
491
+ const response = await fetch('/api/payments', {
492
+ method: 'POST',
493
+ headers: { 'Content-Type': 'application/json' },
494
+ body: JSON.stringify({ payment_method: paymentMethod.id }),
495
+ });
496
+ if (!response.ok) throw new Error('Unable to start payment.');
497
+
498
+ const { clientSecret } = (await response.json()) as { clientSecret?: string };
499
+ if (clientSecret) {
500
+ const result = await paypercut.confirmPayment({ clientSecret });
501
+ const payment = result.checkoutSession;
502
+
503
+ if (
504
+ payment.paymentObjectStatus === 'succeeded' ||
505
+ payment.paymentObjectStatus === 'requires_capture'
506
+ ) {
507
+ window.location.assign('/payment-complete');
508
+ } else if (payment.paymentObjectStatus === 'requires_payment_method') {
509
+ showMessage('Choose another payment method.');
510
+ } else if (payment.paymentObjectStatus === 'processing') {
511
+ showMessage('Your payment is processing.');
512
+ }
513
+ }
514
+ ```
515
+
516
+ The exact public signatures are:
517
+
518
+ ```text
519
+ paypercut.confirmPayment({ clientSecret: string }): Promise<PaypercutConfirmPaymentResult>;
520
+ paypercut.handleNextAction({ clientSecret: string }): Promise<PaypercutConfirmPaymentResult>;
521
+ ```
522
+
523
+ `confirmPayment()` is the primary facade: it retrieves authoritative state,
524
+ performs any supported browser action, confirms again when required, polls when
525
+ the server recommends polling, and returns the latest authoritative Checkout
526
+ Session state. `handleNextAction()` is an exact advanced alias backed by the
527
+ same coordinator. It is useful when integration code wants to name the
528
+ continuation step explicitly, but it does not accept a raw next-action payload.
529
+ Both methods currently accept exactly one input form: `{ clientSecret }`.
530
+
531
+ The client secret is an opaque browser capability. Do not parse it, put it in a
532
+ URL, or include it in logs or analytics. The current continuation supports
533
+ payment-mode Checkout Sessions. Setup and subscription groups create Payment
534
+ Methods, but server-side confirmation for those modes is not performed by this
535
+ browser method in this release.
536
+
537
+ A server may require another action after initial Payment Method creation or
538
+ after payment confirmation. Reuse the same Payment Method; do not collect and
539
+ create it again merely because a later authentication step is required.
540
+ Payment Method creation itself may also perform proactive card authentication.
541
+ In either phase, frictionless authentication presents no dialog. A genuine
542
+ challenge or out-of-band approval uses provider-owned UI; integrations must not
543
+ replace, cover, restyle, or attempt to read that UI.
544
+
545
+ ### Errors, retries, and application return
546
+
547
+ Validation, Payment Method creation, and confirmation reject with an `Error`
548
+ that includes `code` and `recoverable`. Use `code` for your localized customer
549
+ copy and keep a generic fallback for newer codes:
550
+
551
+ ```ts
552
+ type PublicElementsError = Error & { code?: string; recoverable?: boolean };
553
+
554
+ try {
555
+ await elements.submit();
556
+ const paymentMethod = await paypercut.createPaymentMethod({ elements });
557
+ await sendToMerchantServer(paymentMethod.id);
558
+ } catch (unknownError) {
559
+ const error = unknownError as PublicElementsError;
560
+
561
+ if (error.code === 'elements_payment_details_incomplete') {
562
+ showMessage('Complete your payment details.');
563
+ } else if (error.code === 'elements_action_canceled') {
564
+ showMessage('Authentication was canceled. You can try again.');
565
+ } else if (error.recoverable) {
566
+ showRetryButton();
567
+ } else {
568
+ showAnotherPaymentMethod();
569
+ }
570
+ }
571
+ ```
572
+
573
+ For validation errors, keep the current group mounted, let the customer correct
574
+ the fields, and call `submit()` again. For a recoverable confirmation
575
+ cancellation, timeout, or transient network failure, call `confirmPayment()`
576
+ again with the same client secret; it starts by reading authoritative state.
577
+ Never blindly recreate a Payment Method after
578
+ `elements_submit_indeterminate`.
579
+
580
+ During an out-of-band flow, the SDK listens for visibility, page-show, online,
581
+ and focus return and wakes its status check automatically. There is no public
582
+ manual-wake button or method. If a browser or WebView reloads the entire page,
583
+ obtain the same active client secret from your server and call
584
+ `confirmPayment()` again. A terminal `requires_payment_method` result means the
585
+ server requires a fresh payment-method attempt; `processing` means the server
586
+ still owns completion.
587
+
588
+ ### Elements events
589
+
590
+ Every `on()` call returns an unsubscribe function.
591
+
592
+ | Surface | Events | Public data |
593
+ | --- | --- | --- |
594
+ | Card Element | `ready`, `resize`, `error` | readiness, `{ height }`, or `{ code, message, recoverable }` |
595
+ | Split card field | `ready`, `change`, `focus`, `blur`, `error` | `change` exposes `complete`, `empty`, optional `brand`, and a safe validation error; never field values |
596
+ | Express Checkout | `ready`, `availablepaymentmethodschange`, `resize`, `click`, `shippingaddresschange`, `shippingratechange`, `confirm`, `cancel`, `error` | wallet availability, merchant-requested contact/shipping data, and an opaque Payment Method |
597
+
598
+ There are no group-level `validation` or `completion` events. Await
599
+ `elements.submit()` for validation, `createPaymentMethod()` for Payment Method
600
+ creation, and `confirmPayment()` for server-started payment continuation. The
601
+ Express Checkout `confirm` event is the wallet completion seam; call exactly one
602
+ of `event.complete()` or `event.paymentFailed()` after your server responds.
603
+
604
+ ### Localization, appearance, and layout
605
+
606
+ Pass `locale: 'auto'`, a language code such as `fr`, or a regional code such as
607
+ `fr-FR`. Language matching is case-insensitive and accepts compact regional
608
+ forms such as `BGBG`. Unsupported values behave like `auto`: browser languages
609
+ are tried first, followed by `en-GB`. Current translated languages are
610
+ Bulgarian, Czech, Danish, Dutch, English, Finnish, French, German, Greek,
611
+ Hungarian, Italian, Norwegian, Polish, Portuguese, Romanian, Slovak, Spanish,
612
+ and Swedish. The hosted runtime supplies the catalog used by every Element in
613
+ the group; translations are not hardcoded into the SDK bundle.
614
+
615
+ `locale`, `mode`, `currency`, and `setupFutureUsage` are immutable. Recreate the
616
+ group to change them. Configure Appearance before the first Element mounts;
617
+ after that mount, Appearance is locked for the lifetime of the group by default.
618
+ Amount remains independently mutable:
619
+
620
+ ```ts
621
+ const elements = paypercut.elements({
622
+ mode: 'payment',
623
+ amount: 4999,
624
+ currency: 'EUR',
625
+ locale: 'de-DE',
626
+ appearance: {
627
+ theme: 'dark',
628
+ inputs: 'spaced',
629
+ labels: 'above',
630
+ variables: {
631
+ colorPrimary: '#635bff',
632
+ borderRadius: '8px',
633
+ },
634
+ rules: {
635
+ '.Input:focus': { borderColor: '#635bff' },
636
+ '.Error': { color: '#b42318' },
637
+ },
638
+ },
639
+ });
640
+
641
+ elements.update({
642
+ amount: 5999,
643
+ });
644
+ ```
645
+
646
+ Appearance is locked after the first Element mounts by default. A later
647
+ `elements.update({ appearance })` call ignores only Appearance, logs one
648
+ `elements_appearance_locked` warning, and still applies other valid properties
649
+ in the same update, such as `amount`.
650
+
651
+ `appearanceUpdates: 'remount'` is an explicit integration-preview escape hatch
652
+ and should not be used for routine theme changes on a live payment page. An
653
+ Appearance update then remounts the affected payment fields while retaining
654
+ their public Element objects and listeners. During the remount, submission can
655
+ return a recoverable `elements_not_ready` error and entered secure-field data is
656
+ cleared. Wait for the Element's next `ready` event before resuming submission. If
657
+ the remount fails, the last successfully applied Appearance remains active.
658
+
659
+ `appearance.inputs` controls Card and split-field density (`condensed` or
660
+ `spaced`); `appearance.labels` accepts `auto`, `above`, or `floating`.
661
+ `theme`, allow-listed `variables`, semantic `rules`, and `disableAnimations`
662
+ apply across the group. Express Checkout has its own button grid under the
663
+ Element's `layout` option (`maxColumns`, `maxRows`, and `overflow`).
664
+
665
+ ### Lifecycle and safe teardown
666
+
667
+ Element handles and groups cannot be reused after `destroy()`:
668
+
669
+ ```ts
670
+ const card = elements.create('card');
671
+ card.mount('#card-element');
672
+
673
+ // Remove one mounted surface.
674
+ card.destroy();
675
+
676
+ // Create a fresh handle if the same group is still valid.
677
+ const replacementCard = elements.create('card');
678
+ replacementCard.mount('#card-element');
679
+
680
+ // Final page/component cleanup. This destroys every Element in the group.
681
+ elements.destroy();
682
+ ```
683
+
684
+ Call `elements.destroy()` when the owning page or framework component unmounts.
685
+ For a later checkout attempt, create a new Elements group and new Element
686
+ handles. Destroying UI does not cancel, reverse, or alter a server-side payment;
687
+ always reconcile the order with your server before starting another attempt.
688
+
689
+ If your page enforces Content Security Policy, allow the SDK distribution
690
+ origin and Paypercut-hosted frames and connections used by your integration.
691
+ Do not copy internal frame URLs or action parameters into application code;
692
+ contact Paypercut support for the current restrictive-CSP allowlist.
693
+
694
+ ### Express Checkout Element
695
+
696
+ The Express Checkout Element is one component. It checks wallet availability and
697
+ renders the available Apple Pay and Google Pay buttons inside its hosted frame.
698
+ It is not one Paypercut iframe per wallet and it is not a WooCommerce-specific
699
+ widget.
700
+
701
+ ```ts
702
+ import { Paypercut } from '@paypercut/checkout-js';
703
+
704
+ const paypercut = Paypercut({
705
+ publishableKey: 'pk_test_replace_me',
706
+ });
707
+ const elements = paypercut.elements({
708
+ mode: 'payment',
709
+ amount: 4999,
710
+ currency: 'EUR',
711
+ locale: 'en',
712
+ });
713
+
714
+ const expressCheckout = elements.create('expressCheckout', {
715
+ paymentMethods: {
716
+ applePay: 'auto',
717
+ googlePay: 'auto',
718
+ },
719
+ layout: {
720
+ maxColumns: 2,
721
+ maxRows: 1,
722
+ },
723
+ buttonHeight: 48,
724
+ emailRequired: true,
725
+ billingAddressRequired: true,
726
+ });
727
+
728
+ expressCheckout.on('ready', ({ availablePaymentMethods }) => {
729
+ const unavailable =
730
+ !availablePaymentMethods.applePay && !availablePaymentMethods.googlePay;
731
+ document.querySelector('#express-checkout')?.toggleAttribute('hidden', unavailable);
732
+ });
733
+
734
+ expressCheckout.on('click', (event) => {
735
+ // Resolve or reject promptly while the wallet's user gesture is active.
736
+ event.resolve({
737
+ lineItems: [{ name: 'Order total', amount: 4999 }],
738
+ });
739
+ });
740
+
741
+ expressCheckout.on('confirm', async (event) => {
742
+ try {
743
+ const response = await fetch('/api/payments', {
744
+ method: 'POST',
745
+ headers: { 'Content-Type': 'application/json' },
746
+ body: JSON.stringify({
747
+ payment_method: event.paymentMethod.id,
748
+ billing_details: event.billingDetails,
749
+ }),
750
+ });
751
+ if (!response.ok) throw new Error('The server rejected the wallet payment.');
752
+
753
+ const serverResult = (await response.json()) as { clientSecret?: string };
754
+ if (serverResult.clientSecret) {
755
+ const result = await paypercut.confirmPayment({
756
+ clientSecret: serverResult.clientSecret,
757
+ });
758
+ if (
759
+ !['succeeded', 'processing', 'requires_capture'].includes(
760
+ result.checkoutSession.paymentObjectStatus ?? '',
761
+ )
762
+ ) {
763
+ throw new Error(`Payment status: ${result.checkoutSession.paymentObjectStatus}`);
764
+ }
765
+ }
766
+ event.complete();
767
+ } catch (error) {
768
+ event.paymentFailed({
769
+ code: 'merchant_checkout_failed',
770
+ message: error instanceof Error ? error.message : 'Payment failed.',
771
+ });
772
+ }
773
+ });
774
+
775
+ expressCheckout.on('error', ({ code, message, recoverable }) => {
776
+ console.error('Express Checkout error', { code, message, recoverable });
777
+ });
778
+
779
+ expressCheckout.mount('#express-checkout');
780
+ ```
781
+
782
+ The component owns wallet capability detection, button rendering, loading
783
+ states, resizing, secure collection, Payment Method creation, and any required
784
+ customer authentication. Do not call `elements.submit()` or
785
+ `createPaymentMethod()` for the Payment Method already supplied by its `confirm`
786
+ event. The merchant integration owns product/cart placement, shipping quotes,
787
+ provider-neutral address conversion, and server-side order/payment confirmation.
788
+ The native wallet stays pending until the adapter calls `complete()` or
789
+ `paymentFailed()`.
790
+
791
+ Shipping is opt-in. Set `shippingAddressRequired` and provide `shippingRates` only
792
+ for physical fulfillment. When enabled, the Element emits address and rate change
793
+ events and requires each event to be resolved or rejected promptly. The final
794
+ `confirm` event returns the unredacted `shippingAddress` and selected
795
+ `shippingRate`. Integrations without shipping (for example, an EV charging
796
+ payment) should leave those options unset and receive no shipping callbacks.
797
+
798
+ ---
799
+
80
800
  ## Quick Start
81
801
 
82
802
  This returns a checkout session ID like `01KB23M9EC960C50G3AH14FTTT`.
@@ -90,8 +810,8 @@ import { PaypercutCheckout } from '@paypercut/checkout-js';
90
810
 
91
811
  // Initialize the checkout
92
812
  const checkout = PaypercutCheckout({
93
- id: '01KB23M9EC960C50G3AH14FTTT', // Your checkout session ID from step 1
94
- containerId: '#checkout' // CSS selector or HTMLElement
813
+ id: '01KB23M9EC960C50G3AH14FTTT', // Your checkout session ID from step 1
814
+ containerId: '#checkout', // CSS selector or HTMLElement
95
815
  });
96
816
 
97
817
  // Listen for payment events
@@ -118,9 +838,10 @@ That's it! The checkout is now embedded in your page.
118
838
 
119
839
  The SDK supports one display mode:
120
840
 
121
- | Mode | When to Use | Configuration |
122
- |------|-------------|---------------|
841
+ | Mode | When to Use | Configuration |
842
+ | ------------ | ------------------------------------ | --------------------- |
123
843
  | **Embedded** | Checkout is part of your page layout | Provide `containerId` |
844
+
124
845
  ---
125
846
 
126
847
  ## API Reference
@@ -131,18 +852,18 @@ Creates a new checkout instance.
131
852
 
132
853
  #### Options
133
854
 
134
- | Option | Type | Required | Default | Description |
135
- |------------------|------|----------|---------|----------------------------------------------------------------------------------------------------------------------------|
136
- | `id` | `string` | Yes | — | Checkout session identifier (e.g., `01KB23M9EC960C50G3AH14FTTT`) |
137
- | `containerId` | `string \| HTMLElement` | Yes | — | CSS selector or element where iframe mounts |
138
- | `locale` | `string` | No | `'auto'` | Locale for checkout UI. Options: `'auto'`, `'en'`, `'en-GB'`, `'bg'`, `'bg-BG'` |
139
- | `lang` | `string` | No | `'auto'` | Locale for checkout UI. Options: `'auto'`, `'en'`, `'en-GB'`, `'bg'`, `'bg-BG'` |
140
- | `ui_mode` | `'hosted' \| 'embedded'` | No | `'embedded'` | UI mode for checkout display |
141
- | `wallet_options` | `string[]` | No | `['apple_pay', 'google_pay']` | Digital wallet options. Pass `[]` to disable all wallets |
142
- | `form_only` | `boolean` | No | `false` | Show only payment form (no Pay Now button - use external button with `submit()`) |
143
- | `validate_form` | `boolean` | No | `false` | This indicates that Google Pay/Apple Pay flow to proceed you need to confirm form validation. For EMBEDDED checkouts only) |
144
- | `appearance` | `object` | No | `undefined` | Appearance configuration for the checkout UI |
145
- | `appearance.preset` | `'modal' \| 'inline'` | No | `undefined` | Controls checkout layout preset. `'modal'` shows the order summary (TotalCard) and header inside the iframe — use when rendering in a modal/dialog. `'inline'` hides the TotalCard — use when the merchant renders their own order summary outside the checkout. |
855
+ | Option | Type | Required | Default | Description |
856
+ | ------------------- | ------------------------ | -------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
857
+ | `id` | `string` | Yes | — | Checkout session identifier (e.g., `01KB23M9EC960C50G3AH14FTTT`) |
858
+ | `containerId` | `string \| HTMLElement` | Yes | — | CSS selector or element where iframe mounts |
859
+ | `locale` | `string` | No | `'auto'` | Locale for checkout UI. Options: `'auto'`, `'en'`, `'en-GB'`, `'bg'`, `'bg-BG'` |
860
+ | `lang` | `string` | No | `'auto'` | Locale for checkout UI. Options: `'auto'`, `'en'`, `'en-GB'`, `'bg'`, `'bg-BG'` |
861
+ | `ui_mode` | `'hosted' \| 'embedded'` | No | `'embedded'` | UI mode for checkout display |
862
+ | `wallet_options` | `string[]` | No | `['apple_pay', 'google_pay']` | Digital wallet options. Pass `[]` to disable all wallets |
863
+ | `form_only` | `boolean` | No | `false` | Show only payment form (no Pay Now button - use external button with `submit()`) |
864
+ | `validate_form` | `boolean` | No | `false` | This indicates that Google Pay/Apple Pay flow to proceed you need to confirm form validation. For EMBEDDED checkouts only) |
865
+ | `appearance` | `object` | No | `undefined` | Appearance configuration for the checkout UI |
866
+ | `appearance.preset` | `'modal' \| 'inline'` | No | `undefined` | Controls checkout layout preset. `'modal'` shows the order summary (TotalCard) and header inside the iframe — use when rendering in a modal/dialog. `'inline'` hides the TotalCard — use when the merchant renders their own order summary outside the checkout. |
146
867
 
147
868
  #### Examples
148
869
 
@@ -151,7 +872,7 @@ Creates a new checkout instance.
151
872
  ```typescript
152
873
  const checkout = PaypercutCheckout({
153
874
  id: '01KB23M9EC960C50G3AH14FTTT',
154
- containerId: '#checkout-container'
875
+ containerId: '#checkout-container',
155
876
  });
156
877
  ```
157
878
 
@@ -161,14 +882,14 @@ const checkout = PaypercutCheckout({
161
882
  const checkout = PaypercutCheckout({
162
883
  id: '01KB23M9EC960C50G3AH14FTTT',
163
884
  containerId: '#checkout-container',
164
- locale: 'en', // 'auto' | 'en' | 'en-GB' | 'bg' | 'bg-BG'
165
- lang: 'en', // 'auto' | 'en' | 'en-GB' | 'bg' | 'bg-BG'
166
- ui_mode: 'embedded', // 'hosted' | 'embedded'
885
+ locale: 'en', // 'auto' | 'en' | 'en-GB' | 'bg' | 'bg-BG'
886
+ lang: 'en', // 'auto' | 'en' | 'en-GB' | 'bg' | 'bg-BG'
887
+ ui_mode: 'embedded', // 'hosted' | 'embedded'
167
888
  wallet_options: ['apple_pay', 'google_pay'], // Can be empty array [] or contain one/both options
168
- form_only: false, // Set true to hide Pay Now button (use external button),
169
- validate_form: true, // Set true to require form validation before wallet payment
889
+ form_only: false, // Set true to hide Pay Now button (use external button),
890
+ validate_form: true, // Set true to require form validation before wallet payment
170
891
  appearance: {
171
- preset: 'modal', // 'modal' | 'inline' — 'modal' shows TotalCard + header, 'inline' hides them
892
+ preset: 'modal', // 'modal' | 'inline' — 'modal' shows TotalCard + header, 'inline' hides them
172
893
  },
173
894
  });
174
895
  ```
@@ -179,7 +900,7 @@ const checkout = PaypercutCheckout({
179
900
  const checkout = PaypercutCheckout({
180
901
  id: '01KB23M9EC960C50G3AH14FTTT',
181
902
  containerId: '#checkout-container',
182
- wallet_options: [] // No Apple Pay or Google Pay buttons
903
+ wallet_options: [], // No Apple Pay or Google Pay buttons
183
904
  });
184
905
  ```
185
906
 
@@ -189,7 +910,7 @@ const checkout = PaypercutCheckout({
189
910
  const checkout = PaypercutCheckout({
190
911
  id: '01KB23M9EC960C50G3AH14FTTT',
191
912
  containerId: '#checkout-container',
192
- wallet_options: ['apple_pay'] // Only Apple Pay, no Google Pay
913
+ wallet_options: ['apple_pay'], // Only Apple Pay, no Google Pay
193
914
  });
194
915
  ```
195
916
 
@@ -199,7 +920,7 @@ const checkout = PaypercutCheckout({
199
920
  const checkout = PaypercutCheckout({
200
921
  id: '01KB23M9EC960C50G3AH14FTTT',
201
922
  containerId: '#checkout-container',
202
- form_only: true // No Pay Now button inside checkout
923
+ form_only: true, // No Pay Now button inside checkout
203
924
  });
204
925
 
205
926
  // Use your own button to trigger payment
@@ -277,10 +998,10 @@ if (checkout.isMounted()) {
277
998
 
278
999
  Paypercut Checkout supports full visual customisation — you can match your brand colors, typography, corner radius, and even inject your logo. Customisation works in two complementary ways:
279
1000
 
280
- | Approach | When it applies | How |
281
- |---|---|---|
282
- | `appearance` init option | At iframe creation (zero flash) | Pass in `PaypercutCheckout({ appearance: { … } })` |
283
- | `checkout.updateAppearance()` | After mount (dynamic, e.g. dark-mode toggle) | Call at any time post-`render()` |
1001
+ | Approach | When it applies | How |
1002
+ | ----------------------------- | -------------------------------------------- | -------------------------------------------------- |
1003
+ | `appearance` init option | At iframe creation (zero flash) | Pass in `PaypercutCheckout({ appearance: { … } })` |
1004
+ | `checkout.updateAppearance()` | After mount (dynamic, e.g. dark-mode toggle) | Call at any time post-`render()` |
284
1005
 
285
1006
  ---
286
1007
 
@@ -293,13 +1014,13 @@ const checkout = PaypercutCheckout({
293
1014
  id: 'CHK_xxx',
294
1015
  containerId: '#checkout',
295
1016
  appearance: {
296
- theme: 'dark', // 'light' | 'dark'
297
- preset: 'modal', // 'inline' | 'modal'
1017
+ theme: 'dark', // 'light' | 'dark'
1018
+ preset: 'modal', // 'inline' | 'modal'
298
1019
  variables: {
299
- brandColor: '#ff5500', // CTA button background
300
- fontFamily: 'Inter, sans-serif',
1020
+ brandColor: '#ff5500', // CTA button background
1021
+ fontFamily: 'Inter, sans-serif',
301
1022
  borderRadius: '12px',
302
- logoUrl: 'https://cdn.example.com/logo.png',
1023
+ logoUrl: 'https://cdn.example.com/logo.png',
303
1024
  },
304
1025
  },
305
1026
  });
@@ -309,10 +1030,10 @@ checkout.render();
309
1030
 
310
1031
  **`preset`**
311
1032
 
312
- | Value | Effect |
313
- |---|---|
314
- | `'inline'` | Compact form without the order summary card |
315
- | `'modal'` | Full form with order summary card + logo rendered at the top |
1033
+ | Value | Effect |
1034
+ | ---------- | ------------------------------------------------------------ |
1035
+ | `'inline'` | Compact form without the order summary card |
1036
+ | `'modal'` | Full form with order summary card + logo rendered at the top |
316
1037
 
317
1038
  ---
318
1039
 
@@ -348,12 +1069,12 @@ Updates are **merged** — you only need to pass the fields you want to change.
348
1069
 
349
1070
  ### `AppearanceVariables` reference
350
1071
 
351
- | Field | Type | Description |
352
- |---|---|---|
353
- | `brandColor` | `` `#${string}` `` | Background color of the primary CTA (Pay Now) button. Must be a hex value, e.g. `'#ff5500'`. |
354
- | `fontFamily` | `string` | CSS font-family value. Applied globally inside the checkout. E.g. `'Inter, sans-serif'`. |
355
- | `borderRadius` | `string` | CSS length value for element corner radii. Accepts `px`, `rem`, or `em`. E.g. `'8px'`. |
356
- | `logoUrl` | `string` (https URL) | Your logo shown above the checkout header when `preset: 'modal'`. Must be `https://`. |
1072
+ | Field | Type | Description |
1073
+ | -------------- | -------------------- | -------------------------------------------------------------------------------------------- |
1074
+ | `brandColor` | `` `#${string}` `` | Background color of the primary CTA (Pay Now) button. Must be a hex value, e.g. `'#ff5500'`. |
1075
+ | `fontFamily` | `string` | CSS font-family value. Applied globally inside the checkout. E.g. `'Inter, sans-serif'`. |
1076
+ | `borderRadius` | `string` | CSS length value for element corner radii. Accepts `px`, `rem`, or `em`. E.g. `'8px'`. |
1077
+ | `logoUrl` | `string` (https URL) | Your logo shown above the checkout header when `preset: 'modal'`. Must be `https://`. |
357
1078
 
358
1079
  `brandColor` must be a 3- or 6-digit hex value (e.g. `'#fff'` or `'#ffffff'`). Invalid values log a warning and are silently dropped — the existing color is preserved.
359
1080
 
@@ -384,17 +1105,17 @@ Subscribe to events using the `on()` method. You can use string event names or t
384
1105
 
385
1106
  ### Event Reference
386
1107
 
387
- | Event | Enum | Description | Payload |
388
- |-------|------|-------------|---------|
389
- | `loaded` | `SdkEvent.Loaded` | Checkout iframe has finished loading | `void` |
390
- | `processing` | `SdkEvent.Processing` | Payment processing has started inside the hosted checkout | `{ checkoutId: string }` |
391
- | `success` | `SdkEvent.Success` | Payment completed successfully | `PaymentSuccessPayload` |
392
- | `error` | `SdkEvent.Error` | Terminal failure (tokenize, confirm, or 3DS) | `ApiErrorPayload` |
393
- | `expired` | `SdkEvent.Expired` | Checkout session expired | `void` |
394
- | `threeds_started` | `SdkEvent.ThreeDSStarted` | 3DS challenge flow started | `object` |
395
- | `threeds_complete` | `SdkEvent.ThreeDSComplete` | 3DS challenge completed | `object` |
396
- | `threeds_canceled` | `SdkEvent.ThreeDSCanceled` | 3DS challenge canceled by user | `object` |
397
- | `threeds_error` | `SdkEvent.ThreeDSError` | 3DS challenge error | `ApiErrorPayload` or `object` |
1108
+ | Event | Enum | Description | Payload |
1109
+ | ------------------ | -------------------------- | --------------------------------------------------------- | ----------------------------- |
1110
+ | `loaded` | `SdkEvent.Loaded` | Checkout iframe has finished loading | `void` |
1111
+ | `processing` | `SdkEvent.Processing` | Payment processing has started inside the hosted checkout | `{ checkoutId: string }` |
1112
+ | `success` | `SdkEvent.Success` | Payment completed successfully | `PaymentSuccessPayload` |
1113
+ | `error` | `SdkEvent.Error` | Terminal failure (tokenize, confirm, or 3DS) | `ApiErrorPayload` |
1114
+ | `expired` | `SdkEvent.Expired` | Checkout session expired | `void` |
1115
+ | `threeds_started` | `SdkEvent.ThreeDSStarted` | 3DS challenge flow started | `object` |
1116
+ | `threeds_complete` | `SdkEvent.ThreeDSComplete` | 3DS challenge completed | `object` |
1117
+ | `threeds_canceled` | `SdkEvent.ThreeDSCanceled` | 3DS challenge canceled by user | `object` |
1118
+ | `threeds_error` | `SdkEvent.ThreeDSError` | 3DS challenge error | `ApiErrorPayload` or `object` |
398
1119
 
399
1120
  ### Usage Examples
400
1121
 
@@ -480,10 +1201,10 @@ The `success` event returns a `PaymentSuccessPayload` with the payment method de
480
1201
  ```ts
481
1202
  type PaymentSuccessPayload = {
482
1203
  payment_method: {
483
- brand: string; // e.g., 'visa', 'mastercard', 'amex'
484
- last4: string; // Last 4 digits of card number
485
- exp_month: number; // Expiration month (1-12)
486
- exp_year: number; // Expiration year (e.g., 2030)
1204
+ brand: string; // e.g., 'visa', 'mastercard', 'amex'
1205
+ last4: string; // Last 4 digits of card number
1206
+ exp_month: number; // Expiration month (1-12)
1207
+ exp_year: number; // Expiration year (e.g., 2030)
487
1208
  };
488
1209
  };
489
1210
  ```
@@ -502,7 +1223,9 @@ checkout.on('success', (payload) => {
502
1223
  // }
503
1224
  // }
504
1225
 
505
- console.log(`Paid with ${payload.payment_method.brand} ending in ${payload.payment_method.last4}`);
1226
+ console.log(
1227
+ `Paid with ${payload.payment_method.brand} ending in ${payload.payment_method.last4}`,
1228
+ );
506
1229
  // Output: "Paid with visa ending in 4242"
507
1230
  });
508
1231
  ```
@@ -541,7 +1264,6 @@ checkout.on('error', (err) => {
541
1264
 
542
1265
  ## Form Validation for Wallet Payments
543
1266
 
544
-
545
1267
  ### How It Works
546
1268
 
547
1269
  1. User clicks Apple Pay or Google Pay button in the checkout
@@ -553,10 +1275,10 @@ checkout.on('error', (err) => {
553
1275
 
554
1276
  ### Event: `form_validation`
555
1277
 
556
- | Property | Type | Description |
557
- |----------|------|-------------|
558
- | `checkoutId` | `string` | The checkout session ID |
559
- | `wallet` | `'apple_pay' \| 'google_pay'` | Which wallet button was clicked |
1278
+ | Property | Type | Description |
1279
+ | ------------ | ----------------------------- | ------------------------------- |
1280
+ | `checkoutId` | `string` | The checkout session ID |
1281
+ | `wallet` | `'apple_pay' \| 'google_pay'` | Which wallet button was clicked |
560
1282
 
561
1283
  ### Methods
562
1284
 
@@ -575,7 +1297,7 @@ Call this when your form has errors. The wallet will not open, and you should di
575
1297
  ```typescript
576
1298
  checkout.failFormValidation('apple_pay', [
577
1299
  { code: 'invalid_email', message: 'Please enter a valid email address' },
578
- { code: 'missing_address', message: 'Shipping address is required' }
1300
+ { code: 'missing_address', message: 'Shipping address is required' },
579
1301
  ]);
580
1302
  ```
581
1303
 
@@ -587,7 +1309,7 @@ import { PaypercutCheckout, SdkEvent } from '@paypercut/checkout-js';
587
1309
  const checkout = PaypercutCheckout({
588
1310
  id: '01KB23M9EC960C50G3AH14FTTT',
589
1311
  containerId: '#checkout',
590
- wallet_options: ['apple_pay', 'google_pay']
1312
+ wallet_options: ['apple_pay', 'google_pay'],
591
1313
  });
592
1314
 
593
1315
  // Handle form validation for wallet payments
@@ -603,7 +1325,7 @@ checkout.on(SdkEvent.FormValidation, ({ wallet, checkoutId }) => {
603
1325
  // Form has errors - block wallet and show your errors
604
1326
  document.getElementById('email-error').textContent = 'Please enter a valid email';
605
1327
  checkout.failFormValidation(wallet, [
606
- { code: 'invalid_email', message: 'Please enter a valid email' }
1328
+ { code: 'invalid_email', message: 'Please enter a valid email' },
607
1329
  ]);
608
1330
  }
609
1331
  });
@@ -631,7 +1353,7 @@ export function CheckoutWithForm({ checkoutId }: { checkoutId: string }) {
631
1353
  containerId: containerRef.current,
632
1354
  ui_mode: 'embedded',
633
1355
  wallet_options: ['apple_pay', 'google_pay'],
634
- validate_form: true
1356
+ validate_form: true,
635
1357
  });
636
1358
 
637
1359
  // Handle wallet form validation
@@ -643,9 +1365,7 @@ export function CheckoutWithForm({ checkoutId }: { checkoutId: string }) {
643
1365
  checkout.completeFormValidation(wallet);
644
1366
  } else {
645
1367
  setEmailError('Please enter a valid email address');
646
- checkout.failFormValidation(wallet, [
647
- { code: 'invalid_email', message: 'Invalid email' }
648
- ]);
1368
+ checkout.failFormValidation(wallet, [{ code: 'invalid_email', message: 'Invalid email' }]);
649
1369
  }
650
1370
  });
651
1371
 
@@ -663,13 +1383,13 @@ export function CheckoutWithForm({ checkoutId }: { checkoutId: string }) {
663
1383
  <div>
664
1384
  {/* Your custom form fields */}
665
1385
  <div>
666
- <label htmlFor="email">Email</label>
1386
+ <label htmlFor='email'>Email</label>
667
1387
  <input
668
- id="email"
669
- type="email"
1388
+ id='email'
1389
+ type='email'
670
1390
  value={email}
671
1391
  onChange={(e) => setEmail(e.target.value)}
672
- placeholder="your@email.com"
1392
+ placeholder='your@email.com'
673
1393
  />
674
1394
  {emailError && <span style={{ color: 'red' }}>{emailError}</span>}
675
1395
  </div>
@@ -684,6 +1404,7 @@ export function CheckoutWithForm({ checkoutId }: { checkoutId: string }) {
684
1404
  ### Timeout Behavior
685
1405
 
686
1406
  If you don't respond to the `form_validation` event within 10 seconds, the SDK will:
1407
+
687
1408
  1. Emit an `error` event with code `form_validation_timeout`
688
1409
  2. Block the wallet payment from starting
689
1410
 
@@ -692,6 +1413,7 @@ This ensures the checkout doesn't hang indefinitely if the handler is not implem
692
1413
  ### When to Use
693
1414
 
694
1415
  Use form validation when you have:
1416
+
695
1417
  - Custom email/phone fields outside the checkout iframe
696
1418
  - Shipping address forms that must be filled before payment
697
1419
  - Terms & conditions checkboxes that must be accepted
@@ -708,6 +1430,55 @@ checkout.on('form_validation', ({ wallet }) => {
708
1430
 
709
1431
  ---
710
1432
 
1433
+ ## Paypercut Elements errors
1434
+
1435
+ `PaypercutElements.submit()`, `paypercut.createPaymentMethod()`, and each
1436
+ Element's `error` event expose a stable
1437
+ machine-readable `code` and a `recoverable` flag.
1438
+ The accompanying `message` is diagnostic English text. Customer-facing copy
1439
+ should be owned and localized by the merchant integration by mapping `code` to
1440
+ its own translated message.
1441
+
1442
+ ```ts
1443
+ try {
1444
+ await elements.submit();
1445
+ const paymentMethod = await paypercut.createPaymentMethod({ elements });
1446
+ await sendPaymentMethodToYourServer(paymentMethod);
1447
+ } catch (error) {
1448
+ const elementsError = error as ElementsSubmitError;
1449
+ showLocalizedPaymentError(elementsError.code);
1450
+
1451
+ if (!elementsError.recoverable) {
1452
+ disableThisPaymentMethod();
1453
+ }
1454
+ }
1455
+ ```
1456
+
1457
+ The public `ElementsErrorCode` type contains the known codes below and an
1458
+ open string member. This lets a newer hosted component introduce a safe code
1459
+ without forcing the merchant to upgrade Paypercut.js first. Integrations must
1460
+ always keep a generic translated fallback.
1461
+
1462
+ | Family | Codes | Meaning and integration response |
1463
+ | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1464
+ | Payment details | `elements_payment_details_incomplete`, `elements_card_fields_incomplete` | Required secure fields are empty or incomplete. Keep the form visible, focus or highlight its fields, and ask the customer to complete it. |
1465
+ | Payment details | `elements_payment_details_invalid` | One or more completed fields are invalid. Keep the form visible and ask the customer to correct the highlighted fields. |
1466
+ | Payment Method creation | `elements_payment_method_creation_failed` | The secure component could not create the server-consumable Payment Method. Keep the form mounted; offer a retry or another payment method according to `recoverable`. |
1467
+ | Provider tokenization | `elements_tokenization_duplicate`, `elements_tokenization_timeout` | The private provider tokenization exchange was duplicated or timed out. Do not retry blindly; follow `recoverable` and reconcile any active submission first. |
1468
+ | Element lifecycle | `elements_destroyed`, `elements_not_mounted`, `elements_not_ready`, `elements_reinitialized` | The caller submitted before work started against an unavailable Element. Wait for `ready` or mount the required source. `elements_reinitialized` remains in the public compatibility union but is not used to make an in-flight submission safely retryable. |
1469
+ | Controller/component initialization | `elements_initialization_invalid`, `elements_locale_invalid`, `elements_controller_failed`, `elements_component_configuration_invalid`, `elements_component_connect_failed`, `elements_component_attach_failed`, `elements_component_not_ready`, `elements_provider_initialization_failed` | The secure Elements surface could not initialize. Do not expose internal diagnostics; show a translated unavailable message and offer another payment method. |
1470
+ | Elements session | `elements_session_expired`, `elements_session_binding_mismatch`, `elements_session_verification_failed` | The form's authoritative configuration is expired or cannot be verified. Recreate or reload the Elements group instead of blindly resubmitting. |
1471
+ | Submission sequencing and concurrency | `elements_submit_required`, `elements_submission_in_progress`, `elements_submit_in_progress`, `elements_test_preset_in_progress` | Validate after the latest input change before creation, or wait for the operation that already owns the Element to settle. |
1472
+ | Submission result | `elements_submission_failed`, `elements_submit_failed` | Submission failed with no more specific safe classification. Use the generic translated fallback and `recoverable`. |
1473
+ | Ambiguous submission | `elements_submit_indeterminate`, `elements_submit_invalid_response`, `elements_submit_timeout` | The caller cannot safely infer whether the operation completed. Do not retry in the same Elements group. Reconcile server state, then create a new group only for a deliberate new attempt. |
1474
+ | Action shell | `elements_action_canceled`, `elements_action_channel_unavailable`, `elements_action_shell_timeout` | The detached action was canceled or its trusted channel could not be established. Keep the payment form available and give translated retry/alternative guidance. |
1475
+ | 3DS verification | `elements_action_challenge_failed`, `elements_three_ds_authentication_failed`, `elements_three_ds_challenge_failed`, `elements_three_ds_challenge_invalid`, `elements_three_ds_decoupled_not_supported`, `elements_three_ds_provider_session_failed`, `elements_three_ds_scope_mismatch` | Verification did not complete with trusted evidence. Never treat the payment as authenticated; allow a safe retry or another payment method according to server state. |
1476
+
1477
+ These codes describe browser collection and action handling. Once the merchant
1478
+ server starts payment confirmation, its response remains authoritative for
1479
+ payment-attempt failures. Map server error codes separately to localized
1480
+ integration copy.
1481
+
711
1482
  ## Types
712
1483
 
713
1484
  ### ApiErrorPayload
@@ -719,9 +1490,12 @@ The SDK forwards the error payload provided by Hosted Checkout. Common shapes in
719
1490
  type CardField = 'card_number' | 'expiration_date' | 'cvc' | 'cardholder_name';
720
1491
 
721
1492
  type CardValidationErrorCode =
722
- | 'invalid_number' | 'incomplete_number'
723
- | 'invalid_expiry' | 'incomplete_expiry'
724
- | 'invalid_cvc' | 'incomplete_cvc'
1493
+ | 'invalid_number'
1494
+ | 'incomplete_number'
1495
+ | 'invalid_expiry'
1496
+ | 'incomplete_expiry'
1497
+ | 'invalid_cvc'
1498
+ | 'incomplete_cvc'
725
1499
  | 'required';
726
1500
 
727
1501
  type VendorValidationType = 'invalid' | 'incomplete' | 'required';
@@ -754,7 +1528,7 @@ type ApiErrorPayload =
754
1528
  type?: 'card_error' | string;
755
1529
  message?: string;
756
1530
  status_code?: number; // some sources use `status`
757
- status?: number; // compatibility with some payloads
1531
+ status?: number; // compatibility with some payloads
758
1532
  decline_code?: string; // Optional decline reason
759
1533
  trace_id?: string;
760
1534
  timestamp?: string; // ISO8601
@@ -772,8 +1546,18 @@ type ApiErrorPayload =
772
1546
  "status_code": 400,
773
1547
  "timestamp": "2025-01-01T12:00:00.000Z",
774
1548
  "errors": [
775
- { "field": "card_number", "code": "invalid_number", "message": "Card number is invalid", "vendor_type": "invalid" },
776
- { "field": "expiration_date", "code": "incomplete_expiry", "message": "Incomplete date", "vendor_type": "incomplete" }
1549
+ {
1550
+ "field": "card_number",
1551
+ "code": "invalid_number",
1552
+ "message": "Card number is invalid",
1553
+ "vendor_type": "invalid"
1554
+ },
1555
+ {
1556
+ "field": "expiration_date",
1557
+ "code": "incomplete_expiry",
1558
+ "message": "Incomplete date",
1559
+ "vendor_type": "incomplete"
1560
+ }
777
1561
  ]
778
1562
  }
779
1563
  ```
@@ -815,8 +1599,8 @@ type ApiErrorPayload =
815
1599
  - session_expired — Checkout session is no longer valid; create a new session.
816
1600
  - permission_denied — Server responded with permission error (e.g., session not allowed). Not enumerated above; SDK forwards unknown codes unchanged.
817
1601
 
818
-
819
1602
  Notes:
1603
+
820
1604
  - For 3DS issues, you may receive `threeds_error` with `status_code` 424 and a server-provided message.
821
1605
  - For declines, expect `code: 'card_declined'`, optional `decline_code`, and a user-friendly `message`.
822
1606
  - The validation error `message` fields are already localized based on the checkout’s locale.
@@ -826,38 +1610,20 @@ Notes:
826
1610
  The SDK forwards whatever Hosted Checkout sends for 3DS events. Shapes may evolve.
827
1611
 
828
1612
  ```ts
829
- // threeds_started
830
- {
831
- type: 'THREEDS_START_FLOW',
832
- checkoutId: '01KB23M9EC960C50G3AH14FTTT',
833
- // additional context as provided by Hosted Checkout (e.g., method, acsUrl)
834
- }
835
-
836
- // threeds_complete
837
- {
838
- type: 'THREEDS_COMPLETE',
839
- checkoutId: '01KB23M9EC960C50G3AH14FTTT',
840
- // authentication result context (e.g., status: 'Y' | 'A' | 'C' | 'D')
841
- }
842
-
843
- // threeds_canceled
844
- {
845
- type: 'THREEDS_CANCELED',
846
- checkoutId: '01KB23M9EC960C50G3AH14FTTT',
847
- }
848
-
849
- // threeds_error (non-terminal)
850
- // Note: terminal failures will also be emitted on `error` with ApiErrorPayload
851
- {
852
- type: 'THREEDS_ERROR',
853
- checkoutId: '01KB23M9EC960C50G3AH14FTTT',
854
- error?: ApiErrorPayload,
855
- }
1613
+ const representativeThreeDSPayloads = [
1614
+ { type: 'THREEDS_START_FLOW', checkoutId: '01KB23M9EC960C50G3AH14FTTT' },
1615
+ { type: 'THREEDS_COMPLETE', checkoutId: '01KB23M9EC960C50G3AH14FTTT' },
1616
+ { type: 'THREEDS_CANCELED', checkoutId: '01KB23M9EC960C50G3AH14FTTT' },
1617
+ {
1618
+ type: 'THREEDS_ERROR',
1619
+ checkoutId: '01KB23M9EC960C50G3AH14FTTT',
1620
+ error: undefined,
1621
+ },
1622
+ ];
856
1623
  ```
857
1624
 
858
1625
  Tip: Prefer subscribing with the SdkEvent enum for stronger typing.
859
1626
 
860
-
861
1627
  ## Usage Examples
862
1628
 
863
1629
  ### Vanilla JavaScript (CDN)
@@ -865,34 +1631,39 @@ Tip: Prefer subscribing with the SdkEvent enum for stronger typing.
865
1631
  ```html
866
1632
  <!DOCTYPE html>
867
1633
  <html>
868
- <head>
869
- <title>Paypercut Checkout</title>
870
- </head>
871
- <body>
872
- <div id="checkout"></div>
873
-
874
- <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js@1.2.18/dist/paypercut-checkout.iife.min.js"></script>
875
- <script>
876
- const checkout = PaypercutCheckout({
877
- id: '01KB23M9EC960C50G3AH14FTTT',
878
- containerId: '#checkout',
879
- locale: 'en',
880
- ui_mode: 'embedded',
881
- wallet_options: ['apple_pay', 'google_pay']
882
- });
1634
+ <head>
1635
+ <title>Paypercut Checkout</title>
1636
+ </head>
1637
+ <body>
1638
+ <div id="checkout"></div>
1639
+
1640
+ <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js@1.3.0/dist/paypercut-checkout.iife.min.js"></script>
1641
+ <script>
1642
+ const checkout = PaypercutCheckout({
1643
+ id: '01KB23M9EC960C50G3AH14FTTT',
1644
+ containerId: '#checkout',
1645
+ locale: 'en',
1646
+ ui_mode: 'embedded',
1647
+ wallet_options: ['apple_pay', 'google_pay'],
1648
+ });
883
1649
 
884
- checkout.on('success', function(payload) {
885
- // payload.payment_method: { brand, last4, exp_month, exp_year }
886
- alert('Payment successful with ' + payload.payment_method.brand + ' ending in ' + payload.payment_method.last4);
887
- });
1650
+ checkout.on('success', function (payload) {
1651
+ // payload.payment_method: { brand, last4, exp_month, exp_year }
1652
+ alert(
1653
+ 'Payment successful with ' +
1654
+ payload.payment_method.brand +
1655
+ ' ending in ' +
1656
+ payload.payment_method.last4,
1657
+ );
1658
+ });
888
1659
 
889
- checkout.on('error', function(error) {
890
- alert('Payment failed: ' + error.message);
891
- });
1660
+ checkout.on('error', function (error) {
1661
+ alert('Payment failed: ' + error.message);
1662
+ });
892
1663
 
893
- checkout.render();
894
- </script>
895
- </body>
1664
+ checkout.render();
1665
+ </script>
1666
+ </body>
896
1667
  </html>
897
1668
  ```
898
1669
 
@@ -907,7 +1678,7 @@ const checkout = PaypercutCheckout({
907
1678
  locale: 'auto',
908
1679
  ui_mode: 'embedded',
909
1680
  wallet_options: ['apple_pay', 'google_pay'],
910
- form_only: false
1681
+ form_only: false,
911
1682
  });
912
1683
 
913
1684
  checkout.on('success', (payload) => {
@@ -955,7 +1726,7 @@ export function CheckoutComponent({ checkoutId }: { checkoutId: string }) {
955
1726
  locale: 'auto',
956
1727
  ui_mode: 'embedded',
957
1728
  wallet_options: ['apple_pay', 'google_pay'],
958
- form_only: false
1729
+ form_only: false,
959
1730
  });
960
1731
 
961
1732
  checkout.on('loaded', () => {
@@ -987,7 +1758,9 @@ export function CheckoutComponent({ checkoutId }: { checkoutId: string }) {
987
1758
  <div ref={containerRef} style={{ width: '100%', height: '600px' }} />
988
1759
  {status === 'loading' && <p>Processing payment...</p>}
989
1760
  {status === 'success' && paymentMethod && (
990
- <p>✅ Payment successful with {paymentMethod.brand} ending in {paymentMethod.last4}!</p>
1761
+ <p>
1762
+ ✅ Payment successful with {paymentMethod.brand} ending in {paymentMethod.last4}!
1763
+ </p>
991
1764
  )}
992
1765
  {status === 'error' && <p>❌ Payment failed. Please try again.</p>}
993
1766
  </div>
@@ -1003,7 +1776,13 @@ If you want to create a modal-like experience, you can use the `loaded` event to
1003
1776
  import { useEffect, useRef, useState } from 'react';
1004
1777
  import { PaypercutCheckout, CheckoutInstance } from '@paypercut/checkout-js';
1005
1778
 
1006
- export function ModalCheckout({ checkoutId, onClose }: { checkoutId: string; onClose: () => void }) {
1779
+ export function ModalCheckout({
1780
+ checkoutId,
1781
+ onClose,
1782
+ }: {
1783
+ checkoutId: string;
1784
+ onClose: () => void;
1785
+ }) {
1007
1786
  const containerRef = useRef<HTMLDivElement>(null);
1008
1787
  const [isLoading, setIsLoading] = useState(true);
1009
1788
 
@@ -1012,7 +1791,7 @@ export function ModalCheckout({ checkoutId, onClose }: { checkoutId: string; onC
1012
1791
 
1013
1792
  const checkout = PaypercutCheckout({
1014
1793
  id: checkoutId,
1015
- containerId: containerRef.current
1794
+ containerId: containerRef.current,
1016
1795
  });
1017
1796
 
1018
1797
  checkout.on('loaded', () => {
@@ -1036,41 +1815,47 @@ export function ModalCheckout({ checkoutId, onClose }: { checkoutId: string; onC
1036
1815
  }, [checkoutId, onClose]);
1037
1816
 
1038
1817
  return (
1039
- <div style={{
1040
- position: 'fixed',
1041
- top: 0,
1042
- left: 0,
1043
- right: 0,
1044
- bottom: 0,
1045
- backgroundColor: 'rgba(0, 0, 0, 0.5)',
1046
- display: 'flex',
1047
- alignItems: 'center',
1048
- justifyContent: 'center',
1049
- zIndex: 9999
1050
- }}>
1051
- <div style={{
1052
- position: 'relative',
1053
- width: '90%',
1054
- maxWidth: '500px',
1055
- height: '90%',
1056
- maxHeight: '700px',
1057
- backgroundColor: '#fff',
1058
- borderRadius: '12px',
1059
- overflow: 'hidden'
1060
- }}>
1818
+ <div
1819
+ style={{
1820
+ position: 'fixed',
1821
+ top: 0,
1822
+ left: 0,
1823
+ right: 0,
1824
+ bottom: 0,
1825
+ backgroundColor: 'rgba(0, 0, 0, 0.5)',
1826
+ display: 'flex',
1827
+ alignItems: 'center',
1828
+ justifyContent: 'center',
1829
+ zIndex: 9999,
1830
+ }}
1831
+ >
1832
+ <div
1833
+ style={{
1834
+ position: 'relative',
1835
+ width: '90%',
1836
+ maxWidth: '500px',
1837
+ height: '90%',
1838
+ maxHeight: '700px',
1839
+ backgroundColor: '#fff',
1840
+ borderRadius: '12px',
1841
+ overflow: 'hidden',
1842
+ }}
1843
+ >
1061
1844
  {isLoading && (
1062
- <div style={{
1063
- position: 'absolute',
1064
- top: 0,
1065
- left: 0,
1066
- right: 0,
1067
- bottom: 0,
1068
- display: 'flex',
1069
- alignItems: 'center',
1070
- justifyContent: 'center',
1071
- backgroundColor: '#fff',
1072
- zIndex: 1
1073
- }}>
1845
+ <div
1846
+ style={{
1847
+ position: 'absolute',
1848
+ top: 0,
1849
+ left: 0,
1850
+ right: 0,
1851
+ bottom: 0,
1852
+ display: 'flex',
1853
+ alignItems: 'center',
1854
+ justifyContent: 'center',
1855
+ backgroundColor: '#fff',
1856
+ zIndex: 1,
1857
+ }}
1858
+ >
1074
1859
  <p>Loading checkout...</p>
1075
1860
  </div>
1076
1861
  )}
@@ -1081,7 +1866,7 @@ export function ModalCheckout({ checkoutId, onClose }: { checkoutId: string; onC
1081
1866
  position: 'absolute',
1082
1867
  top: '10px',
1083
1868
  right: '10px',
1084
- zIndex: 2
1869
+ zIndex: 2,
1085
1870
  }}
1086
1871
  >
1087
1872
  ✕
@@ -1135,7 +1920,7 @@ The SDK automatically resizes the iframe to match the checkout content height. T
1135
1920
  ```javascript
1136
1921
  const checkout = PaypercutCheckout({
1137
1922
  id: '01KB23M9EC960C50G3AH14FTTT',
1138
- containerId: '#checkout-mount'
1923
+ containerId: '#checkout-mount',
1139
1924
  });
1140
1925
  checkout.render();
1141
1926
  ```
@@ -1150,15 +1935,28 @@ The SDK automatically validates all postMessage communications against the confi
1150
1935
 
1151
1936
  ### Content Security Policy
1152
1937
 
1153
- For enhanced security, configure your Content Security Policy headers:
1938
+ If your page uses a restrictive Content Security Policy, allow the SDK
1939
+ distribution origin plus the Paypercut checkout and API origins. For example,
1940
+ when loading from jsDelivr:
1154
1941
 
1155
1942
  ```
1156
1943
  Content-Security-Policy:
1157
- frame-src https://buy.paypercut.io OR something else;
1158
1944
  script-src 'self' https://cdn.jsdelivr.net https://unpkg.com;
1159
- connect-src https://buy.paypercut.io OR something else;
1945
+ frame-src https://buy.paypercut.io;
1946
+ connect-src 'self' https://api.paypercut.io https://buy.paypercut.io;
1160
1947
  ```
1161
1948
 
1949
+ Split secure card fields require additional third-party `script-src`,
1950
+ `frame-src`, and `connect-src` entries. Obtain the current production allowlist
1951
+ from Paypercut before deploying a restrictive policy rather than copying
1952
+ implementation-specific origins from browser developer tools.
1953
+
1954
+ Use only a publishable key in browser code. Secret or management credentials
1955
+ belong on your authenticated server and must never be bundled into JavaScript.
1956
+ Never inspect, log, store, or send raw card fields or wallet payment data; send
1957
+ only the opaque Payment Method returned by the SDK and merchant-owned checkout
1958
+ data.
1959
+
1162
1960
  ### HTTPS Only
1163
1961
 
1164
1962
  Always use HTTPS in production. The SDK is designed for secure communication over HTTPS.
@@ -1170,6 +1968,7 @@ Always use HTTPS in production. The SDK is designed for secure communication ove
1170
1968
  **Problem:** The iframe doesn't appear after calling `render()`.
1171
1969
 
1172
1970
  **Solutions:**
1971
+
1173
1972
  - Ensure the container element exists in the DOM before calling `render()`
1174
1973
  - Check that the `id` is a valid checkout session ID
1175
1974
  - Verify there are no CSP errors in the browser console
@@ -1180,6 +1979,7 @@ Always use HTTPS in production. The SDK is designed for secure communication ove
1180
1979
  **Problem:** Event handlers are not being called.
1181
1980
 
1182
1981
  **Solutions:**
1982
+
1183
1983
  - Ensure you subscribe to events before calling `render()`
1184
1984
  - Check that the checkout session is active and not expired
1185
1985
  - Enable debug mode to see message logs
@@ -1189,6 +1989,7 @@ Always use HTTPS in production. The SDK is designed for secure communication ove
1189
1989
  **Problem:** TypeScript shows type errors when using the SDK.
1190
1990
 
1191
1991
  **Solutions:**
1992
+
1192
1993
  - Ensure you're importing types: `import { PaypercutCheckout, CheckoutInstance } from '@paypercut/checkout-js'`
1193
1994
  - Update to the latest version of the SDK
1194
1995
  - Check that your `tsconfig.json` includes the SDK's type definitions
@@ -1200,8 +2001,8 @@ Always use HTTPS in production. The SDK is designed for secure communication ove
1200
2001
  Add DNS prefetch and preconnect hints to your HTML for faster loading:
1201
2002
 
1202
2003
  ```html
1203
- <link rel="preconnect" href="https://buy.paypercut.io ">
1204
- <link rel="dns-prefetch" href="https://buy.paypercut.io ">
2004
+ <link rel="preconnect" href="https://buy.paypercut.io " />
2005
+ <link rel="dns-prefetch" href="https://buy.paypercut.io " />
1205
2006
  ```
1206
2007
 
1207
2008
  ### Lazy Loading
@@ -1280,1035 +2081,7 @@ useEffect(() => {
1280
2081
 
1281
2082
  ---
1282
2083
 
1283
- ## Express Checkout (Apple Pay / Google Pay)
1284
-
1285
- Express Checkout lets you embed standalone Apple Pay and Google Pay buttons anywhere on your page — product pages, cart pages, or a dedicated checkout step — without a full checkout form. The SDK handles wallet sheet presentation, shipping address/option collection, tokenization, and payment method creation automatically.
1286
-
1287
- ### How It Works
1288
-
1289
- 1. Merchant calls `PaypercutExpressCheckout(options)` and mounts it into a container
1290
- 2. SDK renders Apple Pay and/or Google Pay buttons inside a secure hosted iframe
1291
- 3. User clicks a button → wallet payment sheet opens, collecting billing address, shipping address, and shipping option
1292
- 4. User changes shipping address or option → SDK fires `shipping_address_change` / `shipping_option_change` event → **merchant calls `updateWith()` with updated totals** → wallet sheet updates
1293
- 5. User confirms payment → SDK tokenizes the wallet token via Basis Theory, creates a Paypercut payment method, and auto-closes the wallet sheet
1294
- 6. SDK fires `payment_method_created` with `paymentMethodId` — use this server-side to create and confirm a payment intent
1295
-
1296
- > **Shipping is always required.** Express Checkout always collects both shipping address and shipping option. You must listen for `shipping_address_change` and `shipping_option_change` and call `updateWith()` to unblock the wallet sheet.
1297
-
1298
- ---
1299
-
1300
- ### Step-by-step flow (annotated example)
1301
-
1302
- The following shows the **exact call/receive sequence** for a complete Express Checkout payment, from initialization to payment confirmation.
1303
-
1304
- ```typescript
1305
- // ─── Step 1: Initialize ───────────────────────────────────────────────────────
1306
- // You call PaypercutExpressCheckout() with your config.
1307
- // Nothing is shown yet — buttons render after mount().
1308
-
1309
- const express = PaypercutExpressCheckout({
1310
- publishableKey: 'pk_test_...',
1311
- amount: 2500, // €25.00 — the initial total (before shipping is chosen)
1312
- currency: 'EUR',
1313
- countryCode: 'DE',
1314
- shippingOptions: [
1315
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 days', amount: 499 },
1316
- { id: 'express', label: 'Express Shipping', detail: '1–2 days', amount: 999 },
1317
- ],
1318
- });
1319
-
1320
-
1321
- // ─── Step 2: Subscribe to events (before mount) ───────────────────────────────
1322
- // Always subscribe before calling mount().
1323
-
1324
- // You RECEIVE: 'ready' — buttons are rendered and visible
1325
- express.on('ready', () => {
1326
- console.log('Wallet buttons ready');
1327
- });
1328
-
1329
- // You RECEIVE: 'click' — user tapped Apple Pay or Google Pay button
1330
- express.on('click', () => {
1331
- console.log('Wallet sheet opening...');
1332
- });
1333
-
1334
-
1335
- // ─── Step 3: Wallet sheet opens — provide initial shipping options ─────────────
1336
- // You RECEIVE: 'session_start' when the wallet sheet opens, BEFORE any address
1337
- // or option is shown. The wallet sheet is PAUSED — you must call updateWith()
1338
- // to provide the initial shipping options and unblock the sheet.
1339
- //
1340
- // This is your chance to dynamically load options from your backend.
1341
- // event.wallet tells you which wallet opened: 'apple_pay' | 'google_pay'
1342
-
1343
- express.on('session_start', async ({ wallet, updateWith }) => {
1344
- console.log('Wallet sheet opened:', wallet);
1345
-
1346
- // Optionally fetch shipping options from your backend
1347
- // const options = await fetch('/api/shipping-options').then(r => r.json());
1348
-
1349
- // You CALL: updateWith() — this unblocks the wallet sheet with initial options
1350
- updateWith({
1351
- amount: 2500 + 499, // subtotal + default shipping cost
1352
- shippingOptions: [
1353
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 days', amount: 499 },
1354
- { id: 'express', label: 'Express Shipping', detail: '1–2 days', amount: 999 },
1355
- ],
1356
- lineItems: [ // Apple Pay only — line item breakdown
1357
- { label: 'Subtotal', amount: 2500 },
1358
- { label: 'Standard Shipping', amount: 499 },
1359
- ],
1360
- });
1361
- // → Wallet sheet now renders with these options
1362
- });
1363
-
1364
-
1365
- // ─── Step 4: User changes shipping address ────────────────────────────────────
1366
- // You RECEIVE: 'shipping_address_change' with a partial address
1367
- // (country, state, city, postalCode — no street at this stage)
1368
- // The wallet sheet is PAUSED — you must call updateWith() to unblock it.
1369
-
1370
- express.on('shipping_address_change', ({ address, updateWith }) => {
1371
- console.log('User shipping to:', address.country, address.postalCode);
1372
- // address = { country: 'DE', state: 'BY', city: 'Munich', postalCode: '80331' }
1373
-
1374
- // Calculate shipping cost for this address on your end
1375
- const shippingCost = address.country === 'DE' ? 499 : 999;
1376
- const newTotal = 2500 + shippingCost;
1377
-
1378
- // You CALL: updateWith() — this unblocks the wallet sheet and updates the displayed total
1379
- updateWith({
1380
- amount: newTotal, // new total including shipping
1381
- shippingOptions: [ // updated options for this region
1382
- { id: 'standard', label: 'Standard Shipping', amount: shippingCost },
1383
- { id: 'express', label: 'Express Shipping', amount: shippingCost + 500 },
1384
- ],
1385
- lineItems: [ // Apple Pay only — line item breakdown
1386
- { label: 'Subtotal', amount: 2500 },
1387
- { label: 'Standard Shipping', amount: shippingCost },
1388
- ],
1389
- // To reject an unsupported address instead:
1390
- // status: 'invalid_shipping_address',
1391
- });
1392
- // → Wallet sheet now shows the updated total and shipping options
1393
- });
1394
-
1395
-
1396
- // ─── Step 5: User selects a shipping option ───────────────────────────────────
1397
- // You RECEIVE: 'shipping_option_change' when the user switches e.g. Standard → Express
1398
- // The wallet sheet is PAUSED again — you must call updateWith() again.
1399
-
1400
- express.on('shipping_option_change', ({ shippingOption, updateWith }) => {
1401
- console.log('User picked:', shippingOption.label, shippingOption.amount);
1402
- // shippingOption = { id: 'express', label: 'Express Shipping', amount: 999 }
1403
-
1404
- const newTotal = 2500 + shippingOption.amount;
1405
-
1406
- // You CALL: updateWith() — unblocks the sheet with the new total
1407
- updateWith({
1408
- amount: newTotal,
1409
- lineItems: [ // Apple Pay only
1410
- { label: 'Subtotal', amount: 2500 },
1411
- { label: shippingOption.label, amount: shippingOption.amount },
1412
- ],
1413
- });
1414
- // → Wallet sheet updates to show the new total
1415
- });
1416
-
1417
-
1418
- // ─── Step 6: User confirms payment ───────────────────────────────────────────
1419
- // User taps "Pay" in the wallet sheet.
1420
- // SDK tokenizes the card via Basis Theory, creates a Paypercut payment method,
1421
- // and auto-closes the wallet sheet. No action needed from you to close the sheet.
1422
-
1423
- // You RECEIVE: 'payment_method_created' with the payment method ID
1424
- express.on('payment_method_created', async ({ paymentMethodId, idempotencyKey, billingDetails, shippingDetails, selectedShippingOption }) => {
1425
- console.log('Payment method created:', paymentMethodId);
1426
- // paymentMethodId = 'pm_01J...'
1427
- // billingDetails = { name: 'John Doe', address: { line1: '...', country: 'DE', ... } }
1428
- // shippingDetails = { name: 'John Doe', address: { line1: '48 Example St', ... } }
1429
- // selectedShippingOption = { id: 'express', label: 'Express Shipping', amount: 999 }
1430
-
1431
- // You CALL: your backend to create and confirm the payment intent
1432
- const res = await fetch('/api/confirm-payment', {
1433
- method: 'POST',
1434
- headers: { 'Content-Type': 'application/json' },
1435
- body: JSON.stringify({ paymentMethodId, idempotencyKey }),
1436
- });
1437
-
1438
- if (res.ok) {
1439
- window.location.href = '/success';
1440
- }
1441
- });
1442
-
1443
-
1444
- // ─── Step 7: Handle failure or cancellation ───────────────────────────────────
1445
- // You RECEIVE: 'payment_method_failed' if tokenization or PM creation fails
1446
- express.on('payment_method_failed', ({ error }) => {
1447
- console.error('Payment failed:', error);
1448
- showErrorMessage('Payment could not be processed. Please try again.');
1449
- });
1450
-
1451
- // You RECEIVE: 'cancel' if the user dismisses the wallet sheet
1452
- express.on('cancel', () => {
1453
- console.log('User closed the wallet sheet');
1454
- });
1455
-
1456
-
1457
- // ─── Step 8: Mount ────────────────────────────────────────────────────────────
1458
- // You CALL: mount() — renders the wallet buttons into the container
1459
- express.mount('#express-checkout');
1460
- // → 'ready' fires once buttons are visible
1461
-
1462
-
1463
- // ─── Step 9: Cleanup ─────────────────────────────────────────────────────────
1464
- // You CALL: destroy() when the component unmounts to prevent memory leaks
1465
- // express.destroy();
1466
- ```
1467
-
1468
- ---
1469
-
1470
- ### Initialization
1471
-
1472
- ```typescript
1473
- import { PaypercutExpressCheckout, ExpressSdkEvent } from '@paypercut/checkout-js';
1474
-
1475
- const express = PaypercutExpressCheckout({
1476
- publishableKey: 'pk_test_...',
1477
- amount: 2999, // in minor units (€29.99)
1478
- currency: 'EUR',
1479
- countryCode: 'DE',
1480
- shippingOptions: [
1481
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 business days', amount: 499 },
1482
- { id: 'express', label: 'Express Shipping', detail: '1–2 business days', amount: 999 },
1483
- ],
1484
- });
1485
-
1486
- express.mount('#express-checkout');
1487
- ```
1488
-
1489
- ---
1490
-
1491
- ### Express Checkout Options
1492
-
1493
- | Option | Type | Required | Description |
1494
- |--------|------|----------|-------------|
1495
- | `publishableKey` | `string` | Yes | Your Paypercut publishable API key (`pk_test_…` or `pk_live_…`) |
1496
- | `amount` | `number` | Yes | Total amount in **minor units** (e.g. `1200` = €12.00) |
1497
- | `currency` | `string` | Yes | ISO 4217 currency code (e.g. `'EUR'`, `'USD'`) |
1498
- | `countryCode` | `string` | Yes | ISO 3166-1 alpha-2 merchant country code (e.g. `'DE'`). Required for Google Pay in production. |
1499
- | `shippingOptions` | `ExpressCheckoutShippingOption[]` | Yes | Initial shipping options shown in the wallet sheet. Must include at least one. |
1500
- | `lineItems` | `LineItem[]` | No | Line item breakdown shown in the **Apple Pay** sheet (subtotal, tax, etc.). Ignored by Google Pay. |
1501
- | `walletOptions` | `('apple_pay' \| 'google_pay')[]` | No | Which wallets to show. Defaults to both. |
1502
- | `layout` | `'auto' \| 'row' \| 'column'` | No | Button layout. `'auto'` *(default)* uses a ResizeObserver to switch between row (>540 px) and column (≤540 px) automatically. `'row'` is always side by side. `'column'` always stacks vertically. |
1503
- | `locale` | `string` | No | ISO 639-1 two-letter language code (e.g. `'en'`, `'bg'`, `'pl'`). Controls the language of the wallet button labels. Each wallet applies this independently — not all languages are supported by every wallet; unsupported values fall back to `'en'`. |
1504
- | `buttonOptions` | `ExpressButtonOptions` | No | Customize the label type and color/style of the wallet buttons. See [Button Options](#button-options) below. |
1505
-
1506
- ---
1507
-
1508
- ### Button Options
1509
-
1510
- Control the label and appearance of the Apple Pay and Google Pay buttons via the `buttonOptions` object.
1511
-
1512
- ```typescript
1513
- PaypercutExpressCheckout({
1514
- // ...
1515
- buttonOptions: {
1516
- type: 'pay', // label shown on both buttons — defaults to 'buy'
1517
- applePayStyle: 'black', // Apple Pay button color — defaults to 'black'
1518
- googlePayColor: 'default', // Google Pay button color — defaults to 'default'
1519
- borderRadius: '0.5rem', // border radius for both buttons — defaults to '0.5rem'
1520
- },
1521
- });
1522
- ```
1523
-
1524
- #### `type` — applies to both Apple Pay and Google Pay
1525
-
1526
- | Value | Button label |
1527
- |-------|-------------|
1528
- | `'plain'` *(default)* | Logo only (no text) |
1529
- | `'pay'` | Pay with Apple Pay / Pay with Google Pay |
1530
- | `'buy'` | Buy with Apple Pay / Buy with Google Pay |
1531
- | `'donate'` | Donate with … |
1532
- | `'checkout'` | Checkout with … |
1533
- | `'subscribe'` | Subscribe with … |
1534
- | `'book'` | Book with … |
1535
- | `'order'` | Order with … |
1536
- | `'tip'` | Tip with … |
1537
- | `'contribute'` | Contribute with … |
1538
-
1539
- #### `applePayStyle` — Apple Pay only
1540
-
1541
- | Value | Appearance |
1542
- |-------|-----------|
1543
- | `'black'` *(default)* | Black background, white logo |
1544
- | `'white'` | White background, black logo |
1545
- | `'white-outline'` | White background with a black border, black logo |
1546
-
1547
- #### `borderRadius` — applies to both
1548
-
1549
- Any valid CSS value (e.g. `'0.5rem'`, `'8px'`, `'50%'`). Defaults to `'0.5rem'`.
1550
-
1551
- #### `googlePayColor` — Google Pay only
1552
-
1553
- | Value | Appearance |
1554
- |-------|-----------|
1555
- | `'default'` *(default)* | White background on light themes, dark on dark themes |
1556
- | `'black'` | Black background |
1557
- | `'white'` | White background |
1558
-
1559
- ```typescript
1560
- interface ExpressCheckoutShippingOption {
1561
- id: string; // unique identifier, e.g. 'standard'
1562
- label: string; // display label, e.g. 'Standard Shipping'
1563
- detail?: string; // subtitle, e.g. '3–5 business days'
1564
- amount: number; // cost in minor units
1565
- }
1566
-
1567
- interface LineItem {
1568
- label: string;
1569
- amount: number; // minor units
1570
- type?: 'final' | 'pending';
1571
- }
1572
- ```
1573
-
1574
- ---
1575
-
1576
- ### Express Checkout Methods
1577
-
1578
- #### `mount(container)`
1579
-
1580
- Mounts the wallet buttons into the given container.
1581
-
1582
- ```typescript
1583
- express.mount('#express-checkout');
1584
- // or pass an HTMLElement
1585
- express.mount(document.getElementById('express-checkout')!);
1586
- ```
1587
-
1588
- #### `on(event, handler)`
1589
-
1590
- Subscribes to an event. Returns an unsubscribe function.
1591
-
1592
- ```typescript
1593
- const unsub = express.on('payment_method_created', (e) => { ... });
1594
- unsub(); // unsubscribe
1595
- ```
1596
-
1597
- #### `update(options)`
1598
-
1599
- Updates the wallet sheet with new totals or shipping options. Call this from `shipping_address_change` / `shipping_option_change` handlers via the provided `updateWith()` helper.
1600
-
1601
- ```typescript
1602
- express.update({
1603
- amount: 3998,
1604
- shippingOptions: [
1605
- { id: 'standard', label: 'Standard Shipping', amount: 499 },
1606
- { id: 'express', label: 'Express Shipping', amount: 999 },
1607
- ],
1608
- });
1609
- ```
1610
-
1611
- #### `destroy()`
1612
-
1613
- Removes iframes and all event listeners.
1614
-
1615
- ```typescript
1616
- express.destroy();
1617
- ```
1618
-
1619
- ---
1620
-
1621
- ### Express Checkout Events
1622
-
1623
- | Event | Enum | Payload | Description |
1624
- |-------|------|---------|-------------|
1625
- | `ready` | `ExpressSdkEvent.Ready` | — | Wallet buttons are rendered and ready |
1626
- | `click` | `ExpressSdkEvent.Click` | — | User tapped a wallet button |
1627
- | `session_start` | `ExpressSdkEvent.SessionStart` | `ExpressSessionStartEvent` | Wallet sheet opened — **must call `updateWith()`** with initial options to unblock |
1628
- | `shipping_address_change` | `ExpressSdkEvent.ShippingAddressChange` | `ShippingAddressChangeEvent` | User changed shipping address — must call `updateWith()` |
1629
- | `shipping_option_change` | `ExpressSdkEvent.ShippingOptionChange` | `ShippingOptionChangeEvent` | User selected a different shipping option — must call `updateWith()` |
1630
- | `payment_method_created` | `ExpressSdkEvent.PaymentMethodCreated` | `ExpressPaymentMethodCreatedEvent` | Payment method created — use `paymentMethodId` to confirm on backend |
1631
- | `payment_method_failed` | `ExpressSdkEvent.PaymentMethodFailed` | `ExpressPaymentMethodFailedEvent` | Tokenization or payment method creation failed |
1632
- | `cancel` | `ExpressSdkEvent.Cancel` | — | User dismissed the wallet sheet |
1633
- | `error` | `ExpressSdkEvent.Error` | `Error` | Unrecoverable SDK error |
1634
-
1635
- ---
1636
-
1637
- ### Shipping Address & Option Changes
1638
-
1639
- Shipping is **always collected** in Express Checkout. When the user selects or changes their address or shipping option inside the wallet sheet, the sheet is paused and waits for you to respond with updated totals. **You must call `updateWith()` within 30 seconds or the wallet sheet will show an error.**
1640
-
1641
- #### `shipping_address_change`
1642
-
1643
- Fires when the user picks or changes their shipping address. The address is partially anonymized at this stage (no street — only country, state, city, postal code).
1644
-
1645
- ```typescript
1646
- express.on('shipping_address_change', ({ address, updateWith }) => {
1647
- // address: { country, state?, city?, postalCode? }
1648
- console.log('Shipping to:', address.country, address.postalCode);
1649
-
1650
- // Calculate shipping cost for this address
1651
- const shippingCost = address.country === 'DE' ? 299 : 599;
1652
- const newTotal = 2500 + shippingCost;
1653
-
1654
- // REQUIRED: call updateWith() to unblock the wallet sheet
1655
- updateWith({
1656
- amount: newTotal,
1657
- shippingOptions: [
1658
- { id: 'standard', label: 'Standard Shipping', amount: shippingCost },
1659
- { id: 'express', label: 'Express Shipping', amount: shippingCost + 500 },
1660
- ],
1661
- // Use 'invalid_shipping_address' if you don't ship to this address:
1662
- // status: 'invalid_shipping_address',
1663
- });
1664
- });
1665
- ```
1666
-
1667
- #### `shipping_option_change`
1668
-
1669
- Fires when the user picks a different shipping option (e.g. switches from Standard to Express).
1670
-
1671
- ```typescript
1672
- express.on('shipping_option_change', ({ shippingOption, updateWith }) => {
1673
- // shippingOption: { id, label, detail?, amount }
1674
- console.log('Shipping option changed to:', shippingOption.label, shippingOption.amount);
1675
-
1676
- const newTotal = 2500 + shippingOption.amount;
1677
-
1678
- // REQUIRED: call updateWith() to unblock the wallet sheet
1679
- updateWith({
1680
- amount: newTotal,
1681
- // Optionally update Apple Pay line items to reflect the new shipping row:
1682
- lineItems: [
1683
- { label: 'Subtotal', amount: 2500 },
1684
- { label: shippingOption.label, amount: shippingOption.amount },
1685
- ],
1686
- });
1687
- });
1688
- ```
1689
-
1690
- #### `updateWith()` options
1691
-
1692
- | Field | Type | Description |
1693
- |-------|------|-------------|
1694
- | `amount` | `number` | New total in minor units |
1695
- | `shippingOptions` | `ExpressCheckoutShippingOption[]` | Updated shipping options list |
1696
- | `lineItems` | `LineItem[]` | Updated Apple Pay line items (ignored by Google Pay) |
1697
- | `status` | `'success' \| 'invalid_shipping_address' \| 'invalid_shipping_option'` | Use an invalid status to show an error inside the sheet without closing it |
1698
-
1699
- ---
1700
-
1701
- ### Restricting Shipping to Specific Countries / Addresses
1702
-
1703
- Wallets don't accept a pre-defined list of allowed addresses — but you have two tools to control where you ship.
1704
-
1705
- ---
1706
-
1707
- #### Option 1 — Country restriction (Google Pay only)
1708
-
1709
- Google Pay lets you restrict which countries are selectable in the address picker. Users from other countries simply cannot choose an address. This is the cleanest UX — the restriction is enforced before the user even types anything.
1710
-
1711
- This is controlled by passing `allowedCountries` in the SDK options:
1712
-
1713
- ```js
1714
- const express = PaypercutExpressCheckout({
1715
- publishableKey: 'pk_test_...',
1716
- amount: 2999,
1717
- currency: 'EUR',
1718
- countryCode: 'DE',
1719
- allowedCountries: ['DE', 'AT', 'CH'], // Google Pay only — user cannot select other countries
1720
- shippingOptions: [ ... ],
1721
- });
1722
- ```
1723
-
1724
- > Apple Pay does not support pre-filtering by country. Users always see their saved addresses regardless of origin country.
1725
-
1726
- ---
1727
-
1728
- #### Option 2 — Reject unsupported addresses at runtime (both wallets)
1729
-
1730
- This works for both Apple Pay and Google Pay. When `shipping_address_change` fires, check the address against your supported regions. If you don't ship there, call `updateWith()` with `status: 'invalid_shipping_address'` — the sheet stays open and shows an error to the user without closing.
1731
-
1732
- ```js
1733
- const SUPPORTED_COUNTRIES = ['DE', 'AT', 'CH', 'NL'];
1734
-
1735
- express.on('shipping_address_change', ({ address, updateWith }) => {
1736
- if (!SUPPORTED_COUNTRIES.includes(address.country)) {
1737
- // Reject — sheet shows an error, stays open
1738
- updateWith({ status: 'invalid_shipping_address' });
1739
- return;
1740
- }
1741
-
1742
- // Country is supported — calculate shipping and respond
1743
- const shippingCost = address.country === 'DE' ? 299 : 599;
1744
- updateWith({
1745
- amount: subtotal + shippingCost,
1746
- shippingOptions: [
1747
- { id: 'standard', label: 'Standard Shipping', amount: shippingCost },
1748
- { id: 'express', label: 'Express Shipping', amount: shippingCost + 500 },
1749
- ],
1750
- });
1751
- });
1752
- ```
1753
-
1754
- ---
1755
-
1756
- #### Option 3 — Combine both (recommended for Google Pay)
1757
-
1758
- Use `allowedCountries` to prevent unsupported countries from being selectable upfront, **and** validate in `shipping_address_change` as a safety net:
1759
-
1760
- ```js
1761
- const SUPPORTED_COUNTRIES = ['DE', 'AT', 'CH'];
1762
-
1763
- const express = PaypercutExpressCheckout({
1764
- publishableKey: 'pk_test_...',
1765
- amount: 2999,
1766
- currency: 'EUR',
1767
- countryCode: 'DE',
1768
- allowedCountries: SUPPORTED_COUNTRIES, // Google Pay: restricts picker
1769
- shippingOptions: [ ... ],
1770
- });
1771
-
1772
- express.on('shipping_address_change', ({ address, updateWith }) => {
1773
- // Apple Pay safety net — also catches any edge cases for Google Pay
1774
- if (!SUPPORTED_COUNTRIES.includes(address.country)) {
1775
- updateWith({ status: 'invalid_shipping_address' });
1776
- return;
1777
- }
1778
-
1779
- const shippingCost = address.country === 'DE' ? 299 : 599;
1780
- updateWith({
1781
- amount: 2999 + shippingCost,
1782
- shippingOptions: [
1783
- { id: 'standard', label: 'Standard Shipping', amount: shippingCost },
1784
- ],
1785
- });
1786
- });
1787
- ```
1788
-
1789
- ---
1790
-
1791
- #### Summary
1792
-
1793
- | Approach | Apple Pay | Google Pay | UX |
1794
- |----------|-----------|------------|-----|
1795
- | `allowedCountries` in options | ✗ not supported | ✅ restricts picker | Best — error before user interacts |
1796
- | `status: 'invalid_shipping_address'` in `shipping_address_change` | ✅ | ✅ | Sheet shows inline error, stays open |
1797
- | Both combined | ✅ (runtime only) | ✅ (picker + runtime) | Recommended |
1798
-
1799
- ---
1800
-
1801
- ## Express Checkout — Integration Examples
1802
-
1803
- Three real-world scenarios showing the complete integration from init to payment confirmation.
1804
-
1805
- ---
1806
-
1807
- ### Example 1 — Simple: static shipping options, EU-only (Google Pay + Apple Pay)
1808
-
1809
- Best for merchants with fixed shipping rates that don't change by address. Google Pay restricts the picker to EU countries. Apple Pay rejects other countries at runtime. Both wallets share the same event handlers.
1810
-
1811
- ```js
1812
- const SUPPORTED_COUNTRIES = ['DE', 'AT', 'CH', 'NL', 'FR'];
1813
- const SUBTOTAL = 4900; // €49.00
1814
-
1815
- const express = PaypercutExpressCheckout({
1816
- publishableKey: 'pk_live_...',
1817
- amount: SUBTOTAL + 499, // subtotal + default shipping
1818
- currency: 'EUR',
1819
- countryCode: 'DE',
1820
- allowedCountries: SUPPORTED_COUNTRIES, // Google Pay: restricts picker to these countries
1821
- });
1822
-
1823
- // Step 1 — Provide initial shipping options when wallet sheet opens
1824
- express.on('session_start', ({ wallet, updateWith }) => {
1825
- updateWith({
1826
- amount: SUBTOTAL + 499,
1827
- shippingOptions: [
1828
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 days', amount: 499 },
1829
- { id: 'express', label: 'Express Shipping', detail: '1–2 days', amount: 999 },
1830
- ],
1831
- lineItems: [
1832
- { label: 'Subtotal', amount: SUBTOTAL },
1833
- { label: 'Standard Shipping', amount: 499 },
1834
- ],
1835
- });
1836
- });
1837
-
1838
- // Step 2 — Validate address (Apple Pay: only way to restrict countries)
1839
- express.on('shipping_address_change', ({ address, updateWith }) => {
1840
- if (!SUPPORTED_COUNTRIES.includes(address.country)) {
1841
- updateWith({ status: 'invalid_shipping_address' });
1842
- return;
1843
- }
1844
-
1845
- updateWith({
1846
- amount: SUBTOTAL + 499,
1847
- shippingOptions: [
1848
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 days', amount: 499 },
1849
- { id: 'express', label: 'Express Shipping', detail: '1–2 days', amount: 999 },
1850
- ],
1851
- lineItems: [
1852
- { label: 'Subtotal', amount: SUBTOTAL },
1853
- { label: 'Standard Shipping', amount: 499 },
1854
- ],
1855
- });
1856
- });
1857
-
1858
- // Step 3 — Update total when user picks a different shipping option
1859
- express.on('shipping_option_change', ({ shippingOption, updateWith }) => {
1860
- updateWith({
1861
- amount: SUBTOTAL + shippingOption.amount,
1862
- lineItems: [
1863
- { label: 'Subtotal', amount: SUBTOTAL },
1864
- { label: shippingOption.label, amount: shippingOption.amount },
1865
- ],
1866
- });
1867
- });
1868
-
1869
- // Step 4 — Payment method created, confirm on your backend
1870
- express.on('payment_method_created', async ({ paymentMethodId, idempotencyKey, shippingDetails, selectedShippingOption }) => {
1871
- await fetch('/api/orders', {
1872
- method: 'POST',
1873
- headers: { 'Content-Type': 'application/json' },
1874
- body: JSON.stringify({
1875
- paymentMethodId,
1876
- idempotencyKey,
1877
- shippingAddress: shippingDetails?.address,
1878
- shippingOption: selectedShippingOption?.id,
1879
- }),
1880
- });
1881
- window.location.href = '/order/confirmation';
1882
- });
1883
-
1884
- express.on('shipping_options_required', ({ wallet }) => {
1885
- console.error(`${wallet}: session_start timed out — shipping options were not provided`);
1886
- });
1887
-
1888
- express.on('payment_method_failed', ({ error }) => console.error('Payment failed:', error));
1889
- express.on('cancel', () => console.log('User cancelled'));
1890
-
1891
- express.mount('#express-checkout');
1892
- ```
1893
-
1894
- ---
1895
-
1896
- ### Example 2 — Dynamic: shipping cost calculated from address via backend (Google Pay + Apple Pay)
1897
-
1898
- Best for merchants with zone-based pricing loaded from their own API. Shipping cost is unknown until the user's country/postal code is available.
1899
-
1900
- ```js
1901
- const SUBTOTAL = 7500; // €75.00
1902
-
1903
- const express = PaypercutExpressCheckout({
1904
- publishableKey: 'pk_live_...',
1905
- amount: SUBTOTAL, // no shipping added yet — will be set in session_start
1906
- currency: 'EUR',
1907
- countryCode: 'DE',
1908
- allowedCountries: ['DE', 'AT', 'CH', 'NL', 'BE', 'FR', 'IT', 'ES'],
1909
- });
1910
-
1911
- // Step 1 — Fetch initial options from your API before the sheet opens
1912
- express.on('session_start', async ({ wallet, updateWith }) => {
1913
- // Call your backend — you have 3 seconds
1914
- const { options, defaultAmount } = await fetch('/api/shipping/default').then(r => r.json());
1915
- // e.g. { options: [{ id: 'standard', label: 'Standard', amount: 599 }], defaultAmount: 8099 }
1916
-
1917
- updateWith({
1918
- amount: defaultAmount,
1919
- shippingOptions: options,
1920
- lineItems: [
1921
- { label: 'Subtotal', amount: SUBTOTAL },
1922
- { label: options[0].label, amount: options[0].amount },
1923
- ],
1924
- });
1925
- });
1926
-
1927
- // Step 2 — Recalculate when user changes address
1928
- express.on('shipping_address_change', async ({ address, updateWith }) => {
1929
- const res = await fetch('/api/shipping/calculate', {
1930
- method: 'POST',
1931
- headers: { 'Content-Type': 'application/json' },
1932
- body: JSON.stringify({ country: address.country, postalCode: address.postalCode }),
1933
- });
1934
-
1935
- if (!res.ok) {
1936
- // Country not supported or no shipping available
1937
- updateWith({ status: 'invalid_shipping_address' });
1938
- return;
1939
- }
1940
-
1941
- const { options, total } = await res.json();
1942
- // e.g. { options: [{ id: 'standard', amount: 699 }, { id: 'express', amount: 1199 }], total: 8199 }
1943
-
1944
- updateWith({
1945
- amount: total,
1946
- shippingOptions: options,
1947
- lineItems: [
1948
- { label: 'Subtotal', amount: SUBTOTAL },
1949
- { label: options[0].label, amount: options[0].amount },
1950
- ],
1951
- });
1952
- });
1953
-
1954
- // Step 3 — User switches shipping option
1955
- express.on('shipping_option_change', ({ shippingOption, updateWith }) => {
1956
- updateWith({
1957
- amount: SUBTOTAL + shippingOption.amount,
1958
- lineItems: [
1959
- { label: 'Subtotal', amount: SUBTOTAL },
1960
- { label: shippingOption.label, amount: shippingOption.amount },
1961
- ],
1962
- });
1963
- });
1964
-
1965
- // Step 4 — Create order on backend
1966
- express.on('payment_method_created', async ({ paymentMethodId, idempotencyKey, billingDetails, shippingDetails, selectedShippingOption }) => {
1967
- const res = await fetch('/api/orders', {
1968
- method: 'POST',
1969
- headers: { 'Content-Type': 'application/json' },
1970
- body: JSON.stringify({
1971
- paymentMethodId,
1972
- idempotencyKey,
1973
- billing: billingDetails,
1974
- shipping: shippingDetails,
1975
- shippingOptionId: selectedShippingOption?.id,
1976
- }),
1977
- });
1978
- const { orderId } = await res.json();
1979
- window.location.href = `/orders/${orderId}/confirmation`;
1980
- });
1981
-
1982
- express.on('shipping_options_required', ({ wallet }) => {
1983
- alert(`Could not load shipping options for ${wallet}. Please try again.`);
1984
- });
1985
-
1986
- express.on('payment_method_failed', ({ error }) => alert('Payment failed: ' + error));
1987
- express.on('cancel', () => console.log('User cancelled'));
1988
-
1989
- express.mount('#express-checkout');
1990
- ```
1991
-
1992
- ---
1993
-
1994
- ### Example 3 — React: Express Checkout as a component with dynamic options
1995
-
1996
- ```tsx
1997
- import { useEffect, useRef } from 'react';
1998
- import {
1999
- PaypercutExpressCheckout,
2000
- ExpressSdkEvent,
2001
- type ExpressCheckoutInstance,
2002
- } from '@paypercut/checkout-js';
2003
-
2004
- interface Props {
2005
- subtotal: number; // minor units
2006
- onSuccess: (orderId: string) => void;
2007
- onCancel: () => void;
2008
- }
2009
-
2010
- const SUPPORTED_COUNTRIES = ['DE', 'AT', 'CH', 'NL'];
2011
-
2012
- export function ExpressCheckout({ subtotal, onSuccess, onCancel }: Props) {
2013
- const containerRef = useRef<HTMLDivElement>(null);
2014
- const instanceRef = useRef<ExpressCheckoutInstance | null>(null);
2015
-
2016
- useEffect(() => {
2017
- if (!containerRef.current) return;
2018
-
2019
- const express = PaypercutExpressCheckout({
2020
- publishableKey: process.env.NEXT_PUBLIC_PAYPERCUT_KEY!,
2021
- amount: subtotal,
2022
- currency: 'EUR',
2023
- countryCode: 'DE',
2024
- allowedCountries: SUPPORTED_COUNTRIES,
2025
- });
2026
-
2027
- // Provide initial options before sheet opens
2028
- express.on(ExpressSdkEvent.SessionStart, async ({ wallet, updateWith }) => {
2029
- const { options } = await fetch('/api/shipping/default').then(r => r.json());
2030
- updateWith({
2031
- amount: subtotal + options[0].amount,
2032
- shippingOptions: options,
2033
- lineItems: [
2034
- { label: 'Subtotal', amount: subtotal },
2035
- { label: options[0].label, amount: options[0].amount },
2036
- ],
2037
- });
2038
- });
2039
-
2040
- // Recalculate when address changes
2041
- express.on(ExpressSdkEvent.ShippingAddressChange, async ({ address, updateWith }) => {
2042
- if (!SUPPORTED_COUNTRIES.includes(address.country)) {
2043
- updateWith({ status: 'invalid_shipping_address' });
2044
- return;
2045
- }
2046
- const { options, total } = await fetch('/api/shipping/calculate', {
2047
- method: 'POST',
2048
- headers: { 'Content-Type': 'application/json' },
2049
- body: JSON.stringify({ country: address.country, postalCode: address.postalCode }),
2050
- }).then(r => r.json());
2051
-
2052
- updateWith({
2053
- amount: total,
2054
- shippingOptions: options,
2055
- lineItems: [
2056
- { label: 'Subtotal', amount: subtotal },
2057
- { label: options[0].label, amount: options[0].amount },
2058
- ],
2059
- });
2060
- });
2061
-
2062
- // Update total when shipping option changes
2063
- express.on(ExpressSdkEvent.ShippingOptionChange, ({ shippingOption, updateWith }) => {
2064
- updateWith({
2065
- amount: subtotal + shippingOption.amount,
2066
- lineItems: [
2067
- { label: 'Subtotal', amount: subtotal },
2068
- { label: shippingOption.label, amount: shippingOption.amount },
2069
- ],
2070
- });
2071
- });
2072
-
2073
- // Payment method ready — confirm on backend
2074
- express.on(ExpressSdkEvent.PaymentMethodCreated, async ({ paymentMethodId, idempotencyKey, shippingDetails, selectedShippingOption }) => {
2075
- const { orderId } = await fetch('/api/orders', {
2076
- method: 'POST',
2077
- headers: { 'Content-Type': 'application/json' },
2078
- body: JSON.stringify({
2079
- paymentMethodId,
2080
- idempotencyKey,
2081
- shipping: shippingDetails,
2082
- shippingOptionId: selectedShippingOption?.id,
2083
- }),
2084
- }).then(r => r.json());
2085
-
2086
- onSuccess(orderId);
2087
- });
2088
-
2089
- express.on(ExpressSdkEvent.ShippingOptionsRequired, ({ wallet }) => {
2090
- console.error(`${wallet}: session_start timed out — implement the session_start handler`);
2091
- });
2092
-
2093
- express.on(ExpressSdkEvent.PaymentMethodFailed, ({ error }) => console.error('Payment failed:', error));
2094
- express.on(ExpressSdkEvent.Cancel, onCancel);
2095
-
2096
- express.mount(containerRef.current);
2097
- instanceRef.current = express;
2098
-
2099
- return () => {
2100
- instanceRef.current?.destroy();
2101
- instanceRef.current = null;
2102
- };
2103
- }, [subtotal, onSuccess, onCancel]);
2104
-
2105
- return <div ref={containerRef} style={{ width: '100%' }} />;
2106
- }
2107
- ```
2108
-
2109
- ---
2110
-
2111
- ### `payment_method_created` Event
2112
-
2113
- Fires after the user authorizes payment and the SDK has successfully created a Paypercut payment method. Use the `paymentMethodId` to create and confirm a payment intent on your backend.
2114
-
2115
- ```typescript
2116
- express.on('payment_method_created', (event) => {
2117
- // event.paymentMethodId — Paypercut PM ID (pm_xxx), use this to confirm payment on your backend
2118
- // event.token — { id: string, type: 'apple_pay' | 'google_pay' }
2119
- // event.idempotencyKey — unique key for this payment attempt (pass to your backend)
2120
- // event.billingDetails — { name?, email?, address? }
2121
- // event.shippingDetails — { name?, address? }
2122
- // event.selectedShippingOption — { id, label, amount }
2123
-
2124
- console.log('Payment method created:', event.paymentMethodId);
2125
- console.log('Shipping to:', event.shippingDetails?.address);
2126
- console.log('Selected option:', event.selectedShippingOption?.label);
2127
-
2128
- // Call your backend to create + confirm the payment intent
2129
- await fetch('/api/confirm-payment', {
2130
- method: 'POST',
2131
- body: JSON.stringify({
2132
- paymentMethodId: event.paymentMethodId,
2133
- idempotencyKey: event.idempotencyKey,
2134
- }),
2135
- });
2136
- });
2137
- ```
2138
-
2139
- ```typescript
2140
- interface ExpressPaymentMethodCreatedEvent {
2141
- paymentMethodId: string; // Paypercut PM ID (pm_xxx)
2142
- token: { id: string; type: 'apple_pay' | 'google_pay' };
2143
- idempotencyKey: string;
2144
- billingDetails?: {
2145
- name?: string;
2146
- email?: string;
2147
- phone?: string;
2148
- address?: { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string; country?: string };
2149
- };
2150
- shippingDetails?: {
2151
- name?: string;
2152
- address?: { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string; country?: string };
2153
- };
2154
- selectedShippingOption?: { id: string; label: string; detail?: string; amount: number };
2155
- }
2156
- ```
2157
-
2158
- ---
2159
-
2160
- ### Express Checkout Full Example
2161
-
2162
- ```html
2163
- <!DOCTYPE html>
2164
- <html>
2165
- <head><title>Express Checkout</title></head>
2166
- <body>
2167
- <div id="express-checkout" style="max-width: 400px;"></div>
2168
-
2169
- <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js/dist/paypercut-checkout.iife.min.js"></script>
2170
- <script>
2171
- const express = PaypercutExpressCheckout({
2172
- publishableKey: 'pk_test_...',
2173
- amount: 2500,
2174
- currency: 'EUR',
2175
- countryCode: 'DE',
2176
- shippingOptions: [
2177
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 days', amount: 499 },
2178
- { id: 'express', label: 'Express Shipping', detail: '1–2 days', amount: 999 },
2179
- ],
2180
- lineItems: [
2181
- { label: 'Subtotal', amount: 2500 },
2182
- { label: 'Standard Shipping', amount: 499 },
2183
- ],
2184
- });
2185
-
2186
- // Wallet buttons ready
2187
- express.on('ready', () => console.log('Express Checkout ready'));
2188
-
2189
- // Shipping address changed — recalculate and respond
2190
- express.on('shipping_address_change', ({ address, updateWith }) => {
2191
- const shippingCost = address.country === 'DE' ? 499 : 799;
2192
- updateWith({
2193
- amount: 2500 + shippingCost,
2194
- shippingOptions: [
2195
- { id: 'standard', label: 'Standard Shipping', amount: shippingCost },
2196
- { id: 'express', label: 'Express Shipping', amount: shippingCost + 500 },
2197
- ],
2198
- lineItems: [
2199
- { label: 'Subtotal', amount: 2500 },
2200
- { label: 'Standard Shipping', amount: shippingCost },
2201
- ],
2202
- });
2203
- });
2204
-
2205
- // Shipping option changed — update total
2206
- express.on('shipping_option_change', ({ shippingOption, updateWith }) => {
2207
- updateWith({
2208
- amount: 2500 + shippingOption.amount,
2209
- lineItems: [
2210
- { label: 'Subtotal', amount: 2500 },
2211
- { label: shippingOption.label, amount: shippingOption.amount },
2212
- ],
2213
- });
2214
- });
2215
-
2216
- // Payment method created — confirm on backend
2217
- express.on('payment_method_created', async (event) => {
2218
- console.log('Payment method:', event.paymentMethodId);
2219
- console.log('Shipping option:', event.selectedShippingOption?.label);
2220
- await fetch('/api/confirm-payment', {
2221
- method: 'POST',
2222
- headers: { 'Content-Type': 'application/json' },
2223
- body: JSON.stringify({ paymentMethodId: event.paymentMethodId }),
2224
- });
2225
- window.location.href = '/success';
2226
- });
2227
-
2228
- express.on('payment_method_failed', ({ error }) => {
2229
- console.error('Payment failed:', error);
2230
- });
2231
-
2232
- express.on('cancel', () => {
2233
- console.log('User dismissed the wallet sheet');
2234
- });
2235
-
2236
- express.mount('#express-checkout');
2237
- </script>
2238
- </body>
2239
- </html>
2240
- ```
2241
-
2242
- ---
2243
-
2244
- ### Express Checkout React Example
2245
-
2246
- ```tsx
2247
- import { useEffect, useRef } from 'react';
2248
- import { PaypercutExpressCheckout, ExpressSdkEvent, ExpressCheckoutInstance } from '@paypercut/checkout-js';
2249
-
2250
- interface Props {
2251
- subtotal: number; // minor units
2252
- onSuccess: (paymentMethodId: string) => void;
2253
- }
2254
-
2255
- export function ExpressCheckoutButton({ subtotal, onSuccess }: Props) {
2256
- const containerRef = useRef<HTMLDivElement>(null);
2257
- const instanceRef = useRef<ExpressCheckoutInstance | null>(null);
2258
-
2259
- useEffect(() => {
2260
- if (!containerRef.current) return;
2261
-
2262
- const express = PaypercutExpressCheckout({
2263
- publishableKey: process.env.NEXT_PUBLIC_PAYPERCUT_KEY!,
2264
- amount: subtotal + 499, // subtotal + default shipping
2265
- currency: 'EUR',
2266
- countryCode: 'DE',
2267
- shippingOptions: [
2268
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 days', amount: 499 },
2269
- { id: 'express', label: 'Express Shipping', detail: '1–2 days', amount: 999 },
2270
- ],
2271
- });
2272
-
2273
- express.on(ExpressSdkEvent.ShippingAddressChange, ({ address, updateWith }) => {
2274
- const shipping = address.country === 'DE' ? 499 : 799;
2275
- updateWith({
2276
- amount: subtotal + shipping,
2277
- shippingOptions: [
2278
- { id: 'standard', label: 'Standard Shipping', amount: shipping },
2279
- { id: 'express', label: 'Express Shipping', amount: shipping + 500 },
2280
- ],
2281
- });
2282
- });
2283
-
2284
- express.on(ExpressSdkEvent.ShippingOptionChange, ({ shippingOption, updateWith }) => {
2285
- updateWith({ amount: subtotal + shippingOption.amount });
2286
- });
2287
-
2288
- express.on(ExpressSdkEvent.PaymentMethodCreated, (event) => {
2289
- onSuccess(event.paymentMethodId);
2290
- });
2291
-
2292
- express.on(ExpressSdkEvent.PaymentMethodFailed, ({ error }) => {
2293
- console.error('Express payment failed:', error);
2294
- });
2295
-
2296
- express.mount(containerRef.current);
2297
- instanceRef.current = express;
2298
-
2299
- return () => {
2300
- instanceRef.current?.destroy();
2301
- instanceRef.current = null;
2302
- };
2303
- }, [subtotal, onSuccess]);
2304
-
2305
- return <div ref={containerRef} style={{ width: '100%' }} />;
2306
- }
2307
- ```
2308
-
2309
- ---
2310
-
2311
- ## FAQ For Internal Validation
2084
+ ## FAQ
2312
2085
 
2313
2086
  **Q: How do I handle successful payments?**
2314
2087
  Listen to the `success` event and redirect users or update your UI accordingly. Always verify the payment on your backend using webhooks.