@paypercut/checkout-js 1.2.19 → 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
@@ -13,8 +13,17 @@ A lightweight, framework-agnostic JavaScript SDK for embedding Paypercut Checkou
13
13
 
14
14
  - [Installation](#installation)
15
15
  - [Elements](#elements)
16
- - [Payment Element](#payment-element)
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)
17
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)
18
27
  - [Quick Start — Embedded Checkout](#quick-start)
19
28
  - [API Reference — Embedded Checkout](#api-reference)
20
29
  - [**Customisation**](#customisation)
@@ -23,16 +32,6 @@ A lightweight, framework-agnostic JavaScript SDK for embedding Paypercut Checkou
23
32
  - [AppearanceVariables reference](#appearancevariables-reference)
24
33
  - [Events — Embedded Checkout](#events)
25
34
  - [Form Validation for Wallet Payments](#form-validation-for-wallet-payments)
26
- - [**Express Checkout (Apple Pay / Google Pay)**](#express-checkout-apple-pay--google-pay)
27
- - [How It Works](#how-it-works)
28
- - [Initialization](#initialization)
29
- - [Button Options](#button-options)
30
- - [Options](#express-checkout-options)
31
- - [Methods](#express-checkout-methods)
32
- - [Events](#express-checkout-events)
33
- - [Shipping address & option changes](#shipping-address--option-changes)
34
- - [Full Example](#express-checkout-full-example)
35
- - [React Example](#express-checkout-react-example)
36
35
  - [Types](#types)
37
36
  - [Usage Examples](#usage-examples)
38
37
  - [Vanilla JavaScript](#vanilla-javascript-cdn)
@@ -69,52 +68,629 @@ pnpm add @paypercut/checkout-js
69
68
  ### Via CDN
70
69
 
71
70
  ```html
72
- <!-- jsDelivr (recommended with SRI) -->
73
- <script
74
- src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js@1.2.19/dist/paypercut-checkout.iife.min.js"
75
- integrity="sha384-..."
76
- crossorigin="anonymous"
77
- ></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>
78
73
 
79
74
  <!-- or UNPKG -->
80
- <script src="https://unpkg.com/@paypercut/checkout-js@1.2.19/dist/paypercut-checkout.iife.min.js"></script>
75
+ <script src="https://unpkg.com/@paypercut/checkout-js@latest/dist/paypercut-checkout.iife.min.js"></script>
81
76
  ```
82
77
 
83
78
  ---
84
79
 
85
80
  ## Elements
86
81
 
87
- The Elements API is the composable integration surface for merchant-owned payment
88
- pages. One `elements()` object owns one shared controller and configuration
89
- session. Every Element created from it is an independently mounted, remotely
90
- hosted component; merchant and platform code decide where those components are
91
- placed.
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
+ ```
92
116
 
93
117
  ```ts
94
- import { Paypercut } from '@paypercut/checkout-js';
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
+ };
95
128
 
96
- const paypercut = Paypercut({ publishableKey: 'pk_...' });
129
+ const paypercut = Paypercut({ publishableKey: 'pk_test_replace_me' });
97
130
  const elements = paypercut.elements({
98
131
  mode: 'payment',
99
132
  amount: 4999,
100
- currency: 'USD',
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
+ }
101
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>
102
289
  ```
103
290
 
104
- Creating the group does not create a Checkout Session or Payment Intent. The
105
- merchant server remains authoritative for the final amount, currency, order, and
106
- payment confirmation.
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.
107
294
 
108
- ### Payment Element
295
+ ### Card Element
109
296
 
110
297
  ```ts
111
- const payment = elements.create('payment');
112
- payment.mount('#payment-element');
298
+ const card = elements.create('card');
299
+ card.mount('#card-element');
113
300
 
114
- const paymentMethod = await payment.submit();
301
+ await elements.submit();
302
+ const paymentMethod = await paypercut.createPaymentMethod({ elements });
115
303
  // Send paymentMethod.id to your server. Do not confirm a payment from browser input.
116
304
  ```
117
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
+
118
694
  ### Express Checkout Element
119
695
 
120
696
  The Express Checkout Element is one component. It checks wallet availability and
@@ -123,6 +699,18 @@ It is not one Paypercut iframe per wallet and it is not a WooCommerce-specific
123
699
  widget.
124
700
 
125
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
+
126
714
  const expressCheckout = elements.create('expressCheckout', {
127
715
  paymentMethods: {
128
716
  applePay: 'auto',
@@ -138,61 +726,43 @@ const expressCheckout = elements.create('expressCheckout', {
138
726
  });
139
727
 
140
728
  expressCheckout.on('ready', ({ availablePaymentMethods }) => {
141
- // Hide your placement if every value is false.
142
- document
143
- .querySelector('#express-checkout')
144
- ?.toggleAttribute(
145
- 'hidden',
146
- !availablePaymentMethods.applePay && !availablePaymentMethods.googlePay,
147
- );
148
- });
149
-
150
- expressCheckout.on('click', async (event) => {
151
- // Recalculate the cart presented by your UI before the Element accepts and
152
- // tokenizes the wallet result. Settle the event promptly (within one second).
153
- // A provider's native sheet may begin opening on the original user gesture.
154
- const cart = await readCurrentCart();
155
- if (!cart.isValid) {
156
- event.reject();
157
- return;
158
- }
159
- elements.update({ amount: cart.amount });
160
- event.resolve({
161
- lineItems: cart.lineItems,
162
- shippingAddressRequired: cart.needsShipping,
163
- shippingRates: cart.needsShipping ? cart.shippingRates : undefined,
164
- });
729
+ const unavailable =
730
+ !availablePaymentMethods.applePay && !availablePaymentMethods.googlePay;
731
+ document.querySelector('#express-checkout')?.toggleAttribute('hidden', unavailable);
165
732
  });
166
733
 
167
- expressCheckout.on('shippingaddresschange', async (event) => {
168
- try {
169
- const update = await quoteShipping(event.address);
170
- event.resolve(update); // { amount, lineItems, shippingRates }
171
- } catch {
172
- event.reject();
173
- }
174
- });
175
-
176
- expressCheckout.on('shippingratechange', async (event) => {
177
- try {
178
- const update = await selectShippingRate(event.shippingRate.id);
179
- event.resolve(update); // { amount, lineItems, shippingRates? }
180
- } catch {
181
- event.reject();
182
- }
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
+ });
183
739
  });
184
740
 
185
741
  expressCheckout.on('confirm', async (event) => {
186
742
  try {
187
- // Send the opaque Payment Method ID and final provider-neutral contact data
188
- // to your server. The server remains authoritative for the order and payment.
189
- await submitPaymentMethodToYourServer({
190
- wallet: event.wallet,
191
- payment_method: event.paymentMethod.id,
192
- billing_details: event.billingDetails,
193
- shipping_address: event.shippingAddress,
194
- shipping_rate: event.shippingRate,
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
+ }),
195
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
+ }
196
766
  event.complete();
197
767
  } catch (error) {
198
768
  event.paymentFailed({
@@ -203,15 +773,17 @@ expressCheckout.on('confirm', async (event) => {
203
773
  });
204
774
 
205
775
  expressCheckout.on('error', ({ code, message, recoverable }) => {
206
- reportPaymentError({ code, message, recoverable });
776
+ console.error('Express Checkout error', { code, message, recoverable });
207
777
  });
208
778
 
209
779
  expressCheckout.mount('#express-checkout');
210
780
  ```
211
781
 
212
- The component owns wallet SDK loading, capability detection, provider button
213
- rendering, loading states, resizing, tokenization, and the shared provider-verified
214
- 3DS lifecycle. The merchant adapter owns product/cart placement, shipping quotes,
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,
215
787
  provider-neutral address conversion, and server-side order/payment confirmation.
216
788
  The native wallet stays pending until the adapter calls `complete()` or
217
789
  `paymentFailed()`.
@@ -860,7 +1432,8 @@ checkout.on('form_validation', ({ wallet }) => {
860
1432
 
861
1433
  ## Paypercut Elements errors
862
1434
 
863
- `PaymentElement.submit()` and the Element's `error` event expose a stable
1435
+ `PaypercutElements.submit()`, `paypercut.createPaymentMethod()`, and each
1436
+ Element's `error` event expose a stable
864
1437
  machine-readable `code` and a `recoverable` flag.
865
1438
  The accompanying `message` is diagnostic English text. Customer-facing copy
866
1439
  should be owned and localized by the merchant integration by mapping `code` to
@@ -868,10 +1441,11 @@ its own translated message.
868
1441
 
869
1442
  ```ts
870
1443
  try {
871
- const paymentMethod = await paymentElement.submit();
1444
+ await elements.submit();
1445
+ const paymentMethod = await paypercut.createPaymentMethod({ elements });
872
1446
  await sendPaymentMethodToYourServer(paymentMethod);
873
1447
  } catch (error) {
874
- const elementsError = error as PaymentElementSubmitError;
1448
+ const elementsError = error as ElementsSubmitError;
875
1449
  showLocalizedPaymentError(elementsError.code);
876
1450
 
877
1451
  if (!elementsError.recoverable) {
@@ -880,30 +1454,30 @@ try {
880
1454
  }
881
1455
  ```
882
1456
 
883
- The public `PaymentElementErrorCode` type contains the known codes below and an
1457
+ The public `ElementsErrorCode` type contains the known codes below and an
884
1458
  open string member. This lets a newer hosted component introduce a safe code
885
1459
  without forcing the merchant to upgrade Paypercut.js first. Integrations must
886
1460
  always keep a generic translated fallback.
887
1461
 
888
- | Family | Codes | Meaning and integration response |
889
- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
890
- | Payment details | `elements_payment_details_incomplete` | Required secure fields are empty or incomplete. Keep the form visible, focus or highlight its fields, and ask the customer to complete it. |
891
- | 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. |
892
- | 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`. |
893
- | Element lifecycle | `elements_destroyed`, `elements_not_mounted`, `elements_not_ready`, `elements_reinitialized` | The caller submitted against an unavailable or replaced Element instance. Wait for `ready`, remount, or recreate the Element as appropriate. |
894
- | 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. |
895
- | 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. |
896
- | Submission concurrency | `elements_submission_in_progress`, `elements_submit_in_progress`, `elements_test_preset_in_progress` | Another operation already owns the Element. Keep the form visible and wait for that operation to settle. |
897
- | Submission result | `elements_submission_failed`, `elements_submit_failed` | Submission failed with no more specific safe classification. Use the generic translated fallback and `recoverable`. |
898
- | Ambiguous submission | `elements_submit_indeterminate`, `elements_submit_invalid_response`, `elements_submit_timeout` | The caller cannot safely infer whether the operation completed. Reconcile server state or refresh before another financial attempt. |
899
- | 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. |
900
- | 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. |
901
-
902
- These codes describe client collection and action handling. Once a concrete
903
- PaymentIntent or Checkout confirmation is attempted, server-owned Paycore
904
- fields such as `code`, `message_code`, `advice_code`, and `decline_code` remain
905
- the authority for payment-attempt failures. They are a separate taxonomy and
906
- should likewise be mapped to localized integration copy.
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.
907
1481
 
908
1482
  ## Types
909
1483
 
@@ -1036,33 +1610,16 @@ Notes:
1036
1610
  The SDK forwards whatever Hosted Checkout sends for 3DS events. Shapes may evolve.
1037
1611
 
1038
1612
  ```ts
1039
- // threeds_started
1040
- {
1041
- type: 'THREEDS_START_FLOW',
1042
- checkoutId: '01KB23M9EC960C50G3AH14FTTT',
1043
- // additional context as provided by Hosted Checkout (e.g., method, acsUrl)
1044
- }
1045
-
1046
- // threeds_complete
1047
- {
1048
- type: 'THREEDS_COMPLETE',
1049
- checkoutId: '01KB23M9EC960C50G3AH14FTTT',
1050
- // authentication result context (e.g., status: 'Y' | 'A' | 'C' | 'D')
1051
- }
1052
-
1053
- // threeds_canceled
1054
- {
1055
- type: 'THREEDS_CANCELED',
1056
- checkoutId: '01KB23M9EC960C50G3AH14FTTT',
1057
- }
1058
-
1059
- // threeds_error (non-terminal)
1060
- // Note: terminal failures will also be emitted on `error` with ApiErrorPayload
1061
- {
1062
- type: 'THREEDS_ERROR',
1063
- checkoutId: '01KB23M9EC960C50G3AH14FTTT',
1064
- error?: ApiErrorPayload,
1065
- }
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
+ ];
1066
1623
  ```
1067
1624
 
1068
1625
  Tip: Prefer subscribing with the SdkEvent enum for stronger typing.
@@ -1080,7 +1637,7 @@ Tip: Prefer subscribing with the SdkEvent enum for stronger typing.
1080
1637
  <body>
1081
1638
  <div id="checkout"></div>
1082
1639
 
1083
- <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js@1.2.19/dist/paypercut-checkout.iife.min.js"></script>
1640
+ <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js@1.3.0/dist/paypercut-checkout.iife.min.js"></script>
1084
1641
  <script>
1085
1642
  const checkout = PaypercutCheckout({
1086
1643
  id: '01KB23M9EC960C50G3AH14FTTT',
@@ -1378,15 +1935,28 @@ The SDK automatically validates all postMessage communications against the confi
1378
1935
 
1379
1936
  ### Content Security Policy
1380
1937
 
1381
- 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:
1382
1941
 
1383
1942
  ```
1384
1943
  Content-Security-Policy:
1385
- frame-src https://buy.paypercut.io OR something else;
1386
1944
  script-src 'self' https://cdn.jsdelivr.net https://unpkg.com;
1387
- 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;
1388
1947
  ```
1389
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
+
1390
1960
  ### HTTPS Only
1391
1961
 
1392
1962
  Always use HTTPS in production. The SDK is designed for secure communication over HTTPS.
@@ -1511,1077 +2081,7 @@ useEffect(() => {
1511
2081
 
1512
2082
  ---
1513
2083
 
1514
- ## Express Checkout (Apple Pay / Google Pay)
1515
-
1516
- 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.
1517
-
1518
- ### How It Works
1519
-
1520
- 1. Merchant calls `PaypercutExpressCheckout(options)` and mounts it into a container
1521
- 2. SDK renders Apple Pay and/or Google Pay buttons inside a secure hosted iframe
1522
- 3. User clicks a button → wallet payment sheet opens, collecting billing address, shipping address, and shipping option
1523
- 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
1524
- 5. User confirms payment → SDK tokenizes the wallet token via Basis Theory, creates a Paypercut payment method, and auto-closes the wallet sheet
1525
- 6. SDK fires `payment_method_created` with `paymentMethodId` — use this server-side to create and confirm a payment intent
1526
-
1527
- > **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.
1528
-
1529
- ---
1530
-
1531
- ### Step-by-step flow (annotated example)
1532
-
1533
- The following shows the **exact call/receive sequence** for a complete Express Checkout payment, from initialization to payment confirmation.
1534
-
1535
- ```typescript
1536
- // ─── Step 1: Initialize ───────────────────────────────────────────────────────
1537
- // You call PaypercutExpressCheckout() with your config.
1538
- // Nothing is shown yet — buttons render after mount().
1539
-
1540
- const express = PaypercutExpressCheckout({
1541
- publishableKey: 'pk_test_...',
1542
- amount: 2500, // €25.00 — the initial total (before shipping is chosen)
1543
- currency: 'EUR',
1544
- countryCode: 'DE',
1545
- shippingOptions: [
1546
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 days', amount: 499 },
1547
- { id: 'express', label: 'Express Shipping', detail: '1–2 days', amount: 999 },
1548
- ],
1549
- });
1550
-
1551
- // ─── Step 2: Subscribe to events (before mount) ───────────────────────────────
1552
- // Always subscribe before calling mount().
1553
-
1554
- // You RECEIVE: 'ready' — buttons are rendered and visible
1555
- express.on('ready', () => {
1556
- console.log('Wallet buttons ready');
1557
- });
1558
-
1559
- // You RECEIVE: 'click' — user tapped Apple Pay or Google Pay button
1560
- express.on('click', () => {
1561
- console.log('Wallet sheet opening...');
1562
- });
1563
-
1564
- // ─── Step 3: Wallet sheet opens — provide initial shipping options ─────────────
1565
- // You RECEIVE: 'session_start' when the wallet sheet opens, BEFORE any address
1566
- // or option is shown. The wallet sheet is PAUSED — you must call updateWith()
1567
- // to provide the initial shipping options and unblock the sheet.
1568
- //
1569
- // This is your chance to dynamically load options from your backend.
1570
- // event.wallet tells you which wallet opened: 'apple_pay' | 'google_pay'
1571
-
1572
- express.on('session_start', async ({ wallet, updateWith }) => {
1573
- console.log('Wallet sheet opened:', wallet);
1574
-
1575
- // Optionally fetch shipping options from your backend
1576
- // const options = await fetch('/api/shipping-options').then(r => r.json());
1577
-
1578
- // You CALL: updateWith() — this unblocks the wallet sheet with initial options
1579
- updateWith({
1580
- amount: 2500 + 499, // subtotal + default shipping cost
1581
- shippingOptions: [
1582
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 days', amount: 499 },
1583
- { id: 'express', label: 'Express Shipping', detail: '1–2 days', amount: 999 },
1584
- ],
1585
- lineItems: [
1586
- // Apple Pay only — line item breakdown
1587
- { label: 'Subtotal', amount: 2500 },
1588
- { label: 'Standard Shipping', amount: 499 },
1589
- ],
1590
- });
1591
- // → Wallet sheet now renders with these options
1592
- });
1593
-
1594
- // ─── Step 4: User changes shipping address ────────────────────────────────────
1595
- // You RECEIVE: 'shipping_address_change' with a partial address
1596
- // (country, state, city, postalCode — no street at this stage)
1597
- // The wallet sheet is PAUSED — you must call updateWith() to unblock it.
1598
-
1599
- express.on('shipping_address_change', ({ address, updateWith }) => {
1600
- console.log('User shipping to:', address.country, address.postalCode);
1601
- // address = { country: 'DE', state: 'BY', city: 'Munich', postalCode: '80331' }
1602
-
1603
- // Calculate shipping cost for this address on your end
1604
- const shippingCost = address.country === 'DE' ? 499 : 999;
1605
- const newTotal = 2500 + shippingCost;
1606
-
1607
- // You CALL: updateWith() — this unblocks the wallet sheet and updates the displayed total
1608
- updateWith({
1609
- amount: newTotal, // new total including shipping
1610
- shippingOptions: [
1611
- // updated options for this region
1612
- { id: 'standard', label: 'Standard Shipping', amount: shippingCost },
1613
- { id: 'express', label: 'Express Shipping', amount: shippingCost + 500 },
1614
- ],
1615
- lineItems: [
1616
- // Apple Pay only — line item breakdown
1617
- { label: 'Subtotal', amount: 2500 },
1618
- { label: 'Standard Shipping', amount: shippingCost },
1619
- ],
1620
- // To reject an unsupported address instead:
1621
- // status: 'invalid_shipping_address',
1622
- });
1623
- // → Wallet sheet now shows the updated total and shipping options
1624
- });
1625
-
1626
- // ─── Step 5: User selects a shipping option ───────────────────────────────────
1627
- // You RECEIVE: 'shipping_option_change' when the user switches e.g. Standard → Express
1628
- // The wallet sheet is PAUSED again — you must call updateWith() again.
1629
-
1630
- express.on('shipping_option_change', ({ shippingOption, updateWith }) => {
1631
- console.log('User picked:', shippingOption.label, shippingOption.amount);
1632
- // shippingOption = { id: 'express', label: 'Express Shipping', amount: 999 }
1633
-
1634
- const newTotal = 2500 + shippingOption.amount;
1635
-
1636
- // You CALL: updateWith() — unblocks the sheet with the new total
1637
- updateWith({
1638
- amount: newTotal,
1639
- lineItems: [
1640
- // Apple Pay only
1641
- { label: 'Subtotal', amount: 2500 },
1642
- { label: shippingOption.label, amount: shippingOption.amount },
1643
- ],
1644
- });
1645
- // → Wallet sheet updates to show the new total
1646
- });
1647
-
1648
- // ─── Step 6: User confirms payment ───────────────────────────────────────────
1649
- // User taps "Pay" in the wallet sheet.
1650
- // SDK tokenizes the card via Basis Theory, creates a Paypercut payment method,
1651
- // and auto-closes the wallet sheet. No action needed from you to close the sheet.
1652
-
1653
- // You RECEIVE: 'payment_method_created' with the payment method ID
1654
- express.on(
1655
- 'payment_method_created',
1656
- async ({
1657
- paymentMethodId,
1658
- idempotencyKey,
1659
- billingDetails,
1660
- shippingDetails,
1661
- selectedShippingOption,
1662
- }) => {
1663
- console.log('Payment method created:', paymentMethodId);
1664
- // paymentMethodId = 'pm_01J...'
1665
- // billingDetails = { name: 'John Doe', address: { line1: '...', country: 'DE', ... } }
1666
- // shippingDetails = { name: 'John Doe', address: { line1: '48 Example St', ... } }
1667
- // selectedShippingOption = { id: 'express', label: 'Express Shipping', amount: 999 }
1668
-
1669
- // You CALL: your backend to create and confirm the payment intent
1670
- const res = await fetch('/api/confirm-payment', {
1671
- method: 'POST',
1672
- headers: { 'Content-Type': 'application/json' },
1673
- body: JSON.stringify({ paymentMethodId, idempotencyKey }),
1674
- });
1675
-
1676
- if (res.ok) {
1677
- window.location.href = '/success';
1678
- }
1679
- },
1680
- );
1681
-
1682
- // ─── Step 7: Handle failure or cancellation ───────────────────────────────────
1683
- // You RECEIVE: 'payment_method_failed' if tokenization or PM creation fails
1684
- express.on('payment_method_failed', ({ error }) => {
1685
- console.error('Payment failed:', error);
1686
- showErrorMessage('Payment could not be processed. Please try again.');
1687
- });
1688
-
1689
- // You RECEIVE: 'cancel' if the user dismisses the wallet sheet
1690
- express.on('cancel', () => {
1691
- console.log('User closed the wallet sheet');
1692
- });
1693
-
1694
- // ─── Step 8: Mount ────────────────────────────────────────────────────────────
1695
- // You CALL: mount() — renders the wallet buttons into the container
1696
- express.mount('#express-checkout');
1697
- // → 'ready' fires once buttons are visible
1698
-
1699
- // ─── Step 9: Cleanup ─────────────────────────────────────────────────────────
1700
- // You CALL: destroy() when the component unmounts to prevent memory leaks
1701
- // express.destroy();
1702
- ```
1703
-
1704
- ---
1705
-
1706
- ### Initialization
1707
-
1708
- ```typescript
1709
- import { PaypercutExpressCheckout, ExpressSdkEvent } from '@paypercut/checkout-js';
1710
-
1711
- const express = PaypercutExpressCheckout({
1712
- publishableKey: 'pk_test_...',
1713
- amount: 2999, // in minor units (€29.99)
1714
- currency: 'EUR',
1715
- countryCode: 'DE',
1716
- shippingOptions: [
1717
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 business days', amount: 499 },
1718
- { id: 'express', label: 'Express Shipping', detail: '1–2 business days', amount: 999 },
1719
- ],
1720
- });
1721
-
1722
- express.mount('#express-checkout');
1723
- ```
1724
-
1725
- ---
1726
-
1727
- ### Express Checkout Options
1728
-
1729
- | Option | Type | Required | Description |
1730
- | ----------------- | --------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1731
- | `publishableKey` | `string` | Yes | Your Paypercut publishable API key (`pk_test_…` or `pk_live_…`) |
1732
- | `amount` | `number` | Yes | Total amount in **minor units** (e.g. `1200` = €12.00) |
1733
- | `currency` | `string` | Yes | ISO 4217 currency code (e.g. `'EUR'`, `'USD'`) |
1734
- | `countryCode` | `string` | Yes | ISO 3166-1 alpha-2 merchant country code (e.g. `'DE'`). Required for Google Pay in production. |
1735
- | `shippingOptions` | `ExpressCheckoutShippingOption[]` | Yes | Initial shipping options shown in the wallet sheet. Must include at least one. |
1736
- | `lineItems` | `LineItem[]` | No | Line item breakdown shown in the **Apple Pay** sheet (subtotal, tax, etc.). Ignored by Google Pay. |
1737
- | `walletOptions` | `('apple_pay' \| 'google_pay')[]` | No | Which wallets to show. Defaults to both. |
1738
- | `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. |
1739
- | `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'`. |
1740
- | `buttonOptions` | `ExpressButtonOptions` | No | Customize the label type and color/style of the wallet buttons. See [Button Options](#button-options) below. |
1741
-
1742
- ---
1743
-
1744
- ### Button Options
1745
-
1746
- Control the label and appearance of the Apple Pay and Google Pay buttons via the `buttonOptions` object.
1747
-
1748
- ```typescript
1749
- PaypercutExpressCheckout({
1750
- // ...
1751
- buttonOptions: {
1752
- type: 'pay', // label shown on both buttons — defaults to 'buy'
1753
- applePayStyle: 'black', // Apple Pay button color — defaults to 'black'
1754
- googlePayColor: 'default', // Google Pay button color — defaults to 'default'
1755
- borderRadius: '0.5rem', // border radius for both buttons — defaults to '0.5rem'
1756
- },
1757
- });
1758
- ```
1759
-
1760
- #### `type` — applies to both Apple Pay and Google Pay
1761
-
1762
- | Value | Button label |
1763
- | --------------------- | ---------------------------------------- |
1764
- | `'plain'` _(default)_ | Logo only (no text) |
1765
- | `'pay'` | Pay with Apple Pay / Pay with Google Pay |
1766
- | `'buy'` | Buy with Apple Pay / Buy with Google Pay |
1767
- | `'donate'` | Donate with … |
1768
- | `'checkout'` | Checkout with … |
1769
- | `'subscribe'` | Subscribe with … |
1770
- | `'book'` | Book with … |
1771
- | `'order'` | Order with … |
1772
- | `'tip'` | Tip with … |
1773
- | `'contribute'` | Contribute with … |
1774
-
1775
- #### `applePayStyle` — Apple Pay only
1776
-
1777
- | Value | Appearance |
1778
- | --------------------- | ------------------------------------------------ |
1779
- | `'black'` _(default)_ | Black background, white logo |
1780
- | `'white'` | White background, black logo |
1781
- | `'white-outline'` | White background with a black border, black logo |
1782
-
1783
- #### `borderRadius` — applies to both
1784
-
1785
- Any valid CSS value (e.g. `'0.5rem'`, `'8px'`, `'50%'`). Defaults to `'0.5rem'`.
1786
-
1787
- #### `googlePayColor` — Google Pay only
1788
-
1789
- | Value | Appearance |
1790
- | ----------------------- | ----------------------------------------------------- |
1791
- | `'default'` _(default)_ | White background on light themes, dark on dark themes |
1792
- | `'black'` | Black background |
1793
- | `'white'` | White background |
1794
-
1795
- ```typescript
1796
- interface ExpressCheckoutShippingOption {
1797
- id: string; // unique identifier, e.g. 'standard'
1798
- label: string; // display label, e.g. 'Standard Shipping'
1799
- detail?: string; // subtitle, e.g. '3–5 business days'
1800
- amount: number; // cost in minor units
1801
- }
1802
-
1803
- interface LineItem {
1804
- label: string;
1805
- amount: number; // minor units
1806
- type?: 'final' | 'pending';
1807
- }
1808
- ```
1809
-
1810
- ---
1811
-
1812
- ### Express Checkout Methods
1813
-
1814
- #### `mount(container)`
1815
-
1816
- Mounts the wallet buttons into the given container.
1817
-
1818
- ```typescript
1819
- express.mount('#express-checkout');
1820
- // or pass an HTMLElement
1821
- express.mount(document.getElementById('express-checkout')!);
1822
- ```
1823
-
1824
- #### `on(event, handler)`
1825
-
1826
- Subscribes to an event. Returns an unsubscribe function.
1827
-
1828
- ```typescript
1829
- const unsub = express.on('payment_method_created', (e) => { ... });
1830
- unsub(); // unsubscribe
1831
- ```
1832
-
1833
- #### `update(options)`
1834
-
1835
- 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.
1836
-
1837
- ```typescript
1838
- express.update({
1839
- amount: 3998,
1840
- shippingOptions: [
1841
- { id: 'standard', label: 'Standard Shipping', amount: 499 },
1842
- { id: 'express', label: 'Express Shipping', amount: 999 },
1843
- ],
1844
- });
1845
- ```
1846
-
1847
- #### `destroy()`
1848
-
1849
- Removes iframes and all event listeners.
1850
-
1851
- ```typescript
1852
- express.destroy();
1853
- ```
1854
-
1855
- ---
1856
-
1857
- ### Express Checkout Events
1858
-
1859
- | Event | Enum | Payload | Description |
1860
- | ------------------------- | --------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------- |
1861
- | `ready` | `ExpressSdkEvent.Ready` | — | Wallet buttons are rendered and ready |
1862
- | `click` | `ExpressSdkEvent.Click` | — | User tapped a wallet button |
1863
- | `session_start` | `ExpressSdkEvent.SessionStart` | `ExpressSessionStartEvent` | Wallet sheet opened — **must call `updateWith()`** with initial options to unblock |
1864
- | `shipping_address_change` | `ExpressSdkEvent.ShippingAddressChange` | `ShippingAddressChangeEvent` | User changed shipping address — must call `updateWith()` |
1865
- | `shipping_option_change` | `ExpressSdkEvent.ShippingOptionChange` | `ShippingOptionChangeEvent` | User selected a different shipping option — must call `updateWith()` |
1866
- | `payment_method_created` | `ExpressSdkEvent.PaymentMethodCreated` | `ExpressPaymentMethodCreatedEvent` | Payment method created — use `paymentMethodId` to confirm on backend |
1867
- | `payment_method_failed` | `ExpressSdkEvent.PaymentMethodFailed` | `ExpressPaymentMethodFailedEvent` | Tokenization or payment method creation failed |
1868
- | `cancel` | `ExpressSdkEvent.Cancel` | — | User dismissed the wallet sheet |
1869
- | `error` | `ExpressSdkEvent.Error` | `Error` | Unrecoverable SDK error |
1870
-
1871
- ---
1872
-
1873
- ### Shipping Address & Option Changes
1874
-
1875
- 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.**
1876
-
1877
- #### `shipping_address_change`
1878
-
1879
- 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).
1880
-
1881
- ```typescript
1882
- express.on('shipping_address_change', ({ address, updateWith }) => {
1883
- // address: { country, state?, city?, postalCode? }
1884
- console.log('Shipping to:', address.country, address.postalCode);
1885
-
1886
- // Calculate shipping cost for this address
1887
- const shippingCost = address.country === 'DE' ? 299 : 599;
1888
- const newTotal = 2500 + shippingCost;
1889
-
1890
- // REQUIRED: call updateWith() to unblock the wallet sheet
1891
- updateWith({
1892
- amount: newTotal,
1893
- shippingOptions: [
1894
- { id: 'standard', label: 'Standard Shipping', amount: shippingCost },
1895
- { id: 'express', label: 'Express Shipping', amount: shippingCost + 500 },
1896
- ],
1897
- // Use 'invalid_shipping_address' if you don't ship to this address:
1898
- // status: 'invalid_shipping_address',
1899
- });
1900
- });
1901
- ```
1902
-
1903
- #### `shipping_option_change`
1904
-
1905
- Fires when the user picks a different shipping option (e.g. switches from Standard to Express).
1906
-
1907
- ```typescript
1908
- express.on('shipping_option_change', ({ shippingOption, updateWith }) => {
1909
- // shippingOption: { id, label, detail?, amount }
1910
- console.log('Shipping option changed to:', shippingOption.label, shippingOption.amount);
1911
-
1912
- const newTotal = 2500 + shippingOption.amount;
1913
-
1914
- // REQUIRED: call updateWith() to unblock the wallet sheet
1915
- updateWith({
1916
- amount: newTotal,
1917
- // Optionally update Apple Pay line items to reflect the new shipping row:
1918
- lineItems: [
1919
- { label: 'Subtotal', amount: 2500 },
1920
- { label: shippingOption.label, amount: shippingOption.amount },
1921
- ],
1922
- });
1923
- });
1924
- ```
1925
-
1926
- #### `updateWith()` options
1927
-
1928
- | Field | Type | Description |
1929
- | ----------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------- |
1930
- | `amount` | `number` | New total in minor units |
1931
- | `shippingOptions` | `ExpressCheckoutShippingOption[]` | Updated shipping options list |
1932
- | `lineItems` | `LineItem[]` | Updated Apple Pay line items (ignored by Google Pay) |
1933
- | `status` | `'success' \| 'invalid_shipping_address' \| 'invalid_shipping_option'` | Use an invalid status to show an error inside the sheet without closing it |
1934
-
1935
- ---
1936
-
1937
- ### Restricting Shipping to Specific Countries / Addresses
1938
-
1939
- Wallets don't accept a pre-defined list of allowed addresses — but you have two tools to control where you ship.
1940
-
1941
- ---
1942
-
1943
- #### Option 1 — Country restriction (Google Pay only)
1944
-
1945
- 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.
1946
-
1947
- This is controlled by passing `allowedCountries` in the SDK options:
1948
-
1949
- ```js
1950
- const express = PaypercutExpressCheckout({
1951
- publishableKey: 'pk_test_...',
1952
- amount: 2999,
1953
- currency: 'EUR',
1954
- countryCode: 'DE',
1955
- allowedCountries: ['DE', 'AT', 'CH'], // Google Pay only — user cannot select other countries
1956
- shippingOptions: [ ... ],
1957
- });
1958
- ```
1959
-
1960
- > Apple Pay does not support pre-filtering by country. Users always see their saved addresses regardless of origin country.
1961
-
1962
- ---
1963
-
1964
- #### Option 2 — Reject unsupported addresses at runtime (both wallets)
1965
-
1966
- 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.
1967
-
1968
- ```js
1969
- const SUPPORTED_COUNTRIES = ['DE', 'AT', 'CH', 'NL'];
1970
-
1971
- express.on('shipping_address_change', ({ address, updateWith }) => {
1972
- if (!SUPPORTED_COUNTRIES.includes(address.country)) {
1973
- // Reject — sheet shows an error, stays open
1974
- updateWith({ status: 'invalid_shipping_address' });
1975
- return;
1976
- }
1977
-
1978
- // Country is supported — calculate shipping and respond
1979
- const shippingCost = address.country === 'DE' ? 299 : 599;
1980
- updateWith({
1981
- amount: subtotal + shippingCost,
1982
- shippingOptions: [
1983
- { id: 'standard', label: 'Standard Shipping', amount: shippingCost },
1984
- { id: 'express', label: 'Express Shipping', amount: shippingCost + 500 },
1985
- ],
1986
- });
1987
- });
1988
- ```
1989
-
1990
- ---
1991
-
1992
- #### Option 3 — Combine both (recommended for Google Pay)
1993
-
1994
- Use `allowedCountries` to prevent unsupported countries from being selectable upfront, **and** validate in `shipping_address_change` as a safety net:
1995
-
1996
- ```js
1997
- const SUPPORTED_COUNTRIES = ['DE', 'AT', 'CH'];
1998
-
1999
- const express = PaypercutExpressCheckout({
2000
- publishableKey: 'pk_test_...',
2001
- amount: 2999,
2002
- currency: 'EUR',
2003
- countryCode: 'DE',
2004
- allowedCountries: SUPPORTED_COUNTRIES, // Google Pay: restricts picker
2005
- shippingOptions: [ ... ],
2006
- });
2007
-
2008
- express.on('shipping_address_change', ({ address, updateWith }) => {
2009
- // Apple Pay safety net — also catches any edge cases for Google Pay
2010
- if (!SUPPORTED_COUNTRIES.includes(address.country)) {
2011
- updateWith({ status: 'invalid_shipping_address' });
2012
- return;
2013
- }
2014
-
2015
- const shippingCost = address.country === 'DE' ? 299 : 599;
2016
- updateWith({
2017
- amount: 2999 + shippingCost,
2018
- shippingOptions: [
2019
- { id: 'standard', label: 'Standard Shipping', amount: shippingCost },
2020
- ],
2021
- });
2022
- });
2023
- ```
2024
-
2025
- ---
2026
-
2027
- #### Summary
2028
-
2029
- | Approach | Apple Pay | Google Pay | UX |
2030
- | ----------------------------------------------------------------- | ----------------- | --------------------- | ------------------------------------ |
2031
- | `allowedCountries` in options | ✗ not supported | ✅ restricts picker | Best — error before user interacts |
2032
- | `status: 'invalid_shipping_address'` in `shipping_address_change` | ✅ | ✅ | Sheet shows inline error, stays open |
2033
- | Both combined | ✅ (runtime only) | ✅ (picker + runtime) | Recommended |
2034
-
2035
- ---
2036
-
2037
- ## Express Checkout — Integration Examples
2038
-
2039
- Three real-world scenarios showing the complete integration from init to payment confirmation.
2040
-
2041
- ---
2042
-
2043
- ### Example 1 — Simple: static shipping options, EU-only (Google Pay + Apple Pay)
2044
-
2045
- 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.
2046
-
2047
- ```js
2048
- const SUPPORTED_COUNTRIES = ['DE', 'AT', 'CH', 'NL', 'FR'];
2049
- const SUBTOTAL = 4900; // €49.00
2050
-
2051
- const express = PaypercutExpressCheckout({
2052
- publishableKey: 'pk_live_...',
2053
- amount: SUBTOTAL + 499, // subtotal + default shipping
2054
- currency: 'EUR',
2055
- countryCode: 'DE',
2056
- allowedCountries: SUPPORTED_COUNTRIES, // Google Pay: restricts picker to these countries
2057
- });
2058
-
2059
- // Step 1 — Provide initial shipping options when wallet sheet opens
2060
- express.on('session_start', ({ wallet, updateWith }) => {
2061
- updateWith({
2062
- amount: SUBTOTAL + 499,
2063
- shippingOptions: [
2064
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 days', amount: 499 },
2065
- { id: 'express', label: 'Express Shipping', detail: '1–2 days', amount: 999 },
2066
- ],
2067
- lineItems: [
2068
- { label: 'Subtotal', amount: SUBTOTAL },
2069
- { label: 'Standard Shipping', amount: 499 },
2070
- ],
2071
- });
2072
- });
2073
-
2074
- // Step 2 — Validate address (Apple Pay: only way to restrict countries)
2075
- express.on('shipping_address_change', ({ address, updateWith }) => {
2076
- if (!SUPPORTED_COUNTRIES.includes(address.country)) {
2077
- updateWith({ status: 'invalid_shipping_address' });
2078
- return;
2079
- }
2080
-
2081
- updateWith({
2082
- amount: SUBTOTAL + 499,
2083
- shippingOptions: [
2084
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 days', amount: 499 },
2085
- { id: 'express', label: 'Express Shipping', detail: '1–2 days', amount: 999 },
2086
- ],
2087
- lineItems: [
2088
- { label: 'Subtotal', amount: SUBTOTAL },
2089
- { label: 'Standard Shipping', amount: 499 },
2090
- ],
2091
- });
2092
- });
2093
-
2094
- // Step 3 — Update total when user picks a different shipping option
2095
- express.on('shipping_option_change', ({ shippingOption, updateWith }) => {
2096
- updateWith({
2097
- amount: SUBTOTAL + shippingOption.amount,
2098
- lineItems: [
2099
- { label: 'Subtotal', amount: SUBTOTAL },
2100
- { label: shippingOption.label, amount: shippingOption.amount },
2101
- ],
2102
- });
2103
- });
2104
-
2105
- // Step 4 — Payment method created, confirm on your backend
2106
- express.on(
2107
- 'payment_method_created',
2108
- async ({ paymentMethodId, idempotencyKey, shippingDetails, selectedShippingOption }) => {
2109
- await fetch('/api/orders', {
2110
- method: 'POST',
2111
- headers: { 'Content-Type': 'application/json' },
2112
- body: JSON.stringify({
2113
- paymentMethodId,
2114
- idempotencyKey,
2115
- shippingAddress: shippingDetails?.address,
2116
- shippingOption: selectedShippingOption?.id,
2117
- }),
2118
- });
2119
- window.location.href = '/order/confirmation';
2120
- },
2121
- );
2122
-
2123
- express.on('shipping_options_required', ({ wallet }) => {
2124
- console.error(`${wallet}: session_start timed out — shipping options were not provided`);
2125
- });
2126
-
2127
- express.on('payment_method_failed', ({ error }) => console.error('Payment failed:', error));
2128
- express.on('cancel', () => console.log('User cancelled'));
2129
-
2130
- express.mount('#express-checkout');
2131
- ```
2132
-
2133
- ---
2134
-
2135
- ### Example 2 — Dynamic: shipping cost calculated from address via backend (Google Pay + Apple Pay)
2136
-
2137
- 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.
2138
-
2139
- ```js
2140
- const SUBTOTAL = 7500; // €75.00
2141
-
2142
- const express = PaypercutExpressCheckout({
2143
- publishableKey: 'pk_live_...',
2144
- amount: SUBTOTAL, // no shipping added yet — will be set in session_start
2145
- currency: 'EUR',
2146
- countryCode: 'DE',
2147
- allowedCountries: ['DE', 'AT', 'CH', 'NL', 'BE', 'FR', 'IT', 'ES'],
2148
- });
2149
-
2150
- // Step 1 — Fetch initial options from your API before the sheet opens
2151
- express.on('session_start', async ({ wallet, updateWith }) => {
2152
- // Call your backend — you have 3 seconds
2153
- const { options, defaultAmount } = await fetch('/api/shipping/default').then((r) => r.json());
2154
- // e.g. { options: [{ id: 'standard', label: 'Standard', amount: 599 }], defaultAmount: 8099 }
2155
-
2156
- updateWith({
2157
- amount: defaultAmount,
2158
- shippingOptions: options,
2159
- lineItems: [
2160
- { label: 'Subtotal', amount: SUBTOTAL },
2161
- { label: options[0].label, amount: options[0].amount },
2162
- ],
2163
- });
2164
- });
2165
-
2166
- // Step 2 — Recalculate when user changes address
2167
- express.on('shipping_address_change', async ({ address, updateWith }) => {
2168
- const res = await fetch('/api/shipping/calculate', {
2169
- method: 'POST',
2170
- headers: { 'Content-Type': 'application/json' },
2171
- body: JSON.stringify({ country: address.country, postalCode: address.postalCode }),
2172
- });
2173
-
2174
- if (!res.ok) {
2175
- // Country not supported or no shipping available
2176
- updateWith({ status: 'invalid_shipping_address' });
2177
- return;
2178
- }
2179
-
2180
- const { options, total } = await res.json();
2181
- // e.g. { options: [{ id: 'standard', amount: 699 }, { id: 'express', amount: 1199 }], total: 8199 }
2182
-
2183
- updateWith({
2184
- amount: total,
2185
- shippingOptions: options,
2186
- lineItems: [
2187
- { label: 'Subtotal', amount: SUBTOTAL },
2188
- { label: options[0].label, amount: options[0].amount },
2189
- ],
2190
- });
2191
- });
2192
-
2193
- // Step 3 — User switches shipping option
2194
- express.on('shipping_option_change', ({ shippingOption, updateWith }) => {
2195
- updateWith({
2196
- amount: SUBTOTAL + shippingOption.amount,
2197
- lineItems: [
2198
- { label: 'Subtotal', amount: SUBTOTAL },
2199
- { label: shippingOption.label, amount: shippingOption.amount },
2200
- ],
2201
- });
2202
- });
2203
-
2204
- // Step 4 — Create order on backend
2205
- express.on(
2206
- 'payment_method_created',
2207
- async ({
2208
- paymentMethodId,
2209
- idempotencyKey,
2210
- billingDetails,
2211
- shippingDetails,
2212
- selectedShippingOption,
2213
- }) => {
2214
- const res = await fetch('/api/orders', {
2215
- method: 'POST',
2216
- headers: { 'Content-Type': 'application/json' },
2217
- body: JSON.stringify({
2218
- paymentMethodId,
2219
- idempotencyKey,
2220
- billing: billingDetails,
2221
- shipping: shippingDetails,
2222
- shippingOptionId: selectedShippingOption?.id,
2223
- }),
2224
- });
2225
- const { orderId } = await res.json();
2226
- window.location.href = `/orders/${orderId}/confirmation`;
2227
- },
2228
- );
2229
-
2230
- express.on('shipping_options_required', ({ wallet }) => {
2231
- alert(`Could not load shipping options for ${wallet}. Please try again.`);
2232
- });
2233
-
2234
- express.on('payment_method_failed', ({ error }) => alert('Payment failed: ' + error));
2235
- express.on('cancel', () => console.log('User cancelled'));
2236
-
2237
- express.mount('#express-checkout');
2238
- ```
2239
-
2240
- ---
2241
-
2242
- ### Example 3 — React: Express Checkout as a component with dynamic options
2243
-
2244
- ```tsx
2245
- import { useEffect, useRef } from 'react';
2246
- import {
2247
- PaypercutExpressCheckout,
2248
- ExpressSdkEvent,
2249
- type ExpressCheckoutInstance,
2250
- } from '@paypercut/checkout-js';
2251
-
2252
- interface Props {
2253
- subtotal: number; // minor units
2254
- onSuccess: (orderId: string) => void;
2255
- onCancel: () => void;
2256
- }
2257
-
2258
- const SUPPORTED_COUNTRIES = ['DE', 'AT', 'CH', 'NL'];
2259
-
2260
- export function ExpressCheckout({ subtotal, onSuccess, onCancel }: Props) {
2261
- const containerRef = useRef<HTMLDivElement>(null);
2262
- const instanceRef = useRef<ExpressCheckoutInstance | null>(null);
2263
-
2264
- useEffect(() => {
2265
- if (!containerRef.current) return;
2266
-
2267
- const express = PaypercutExpressCheckout({
2268
- publishableKey: process.env.NEXT_PUBLIC_PAYPERCUT_KEY!,
2269
- amount: subtotal,
2270
- currency: 'EUR',
2271
- countryCode: 'DE',
2272
- allowedCountries: SUPPORTED_COUNTRIES,
2273
- });
2274
-
2275
- // Provide initial options before sheet opens
2276
- express.on(ExpressSdkEvent.SessionStart, async ({ wallet, updateWith }) => {
2277
- const { options } = await fetch('/api/shipping/default').then((r) => r.json());
2278
- updateWith({
2279
- amount: subtotal + options[0].amount,
2280
- shippingOptions: options,
2281
- lineItems: [
2282
- { label: 'Subtotal', amount: subtotal },
2283
- { label: options[0].label, amount: options[0].amount },
2284
- ],
2285
- });
2286
- });
2287
-
2288
- // Recalculate when address changes
2289
- express.on(ExpressSdkEvent.ShippingAddressChange, async ({ address, updateWith }) => {
2290
- if (!SUPPORTED_COUNTRIES.includes(address.country)) {
2291
- updateWith({ status: 'invalid_shipping_address' });
2292
- return;
2293
- }
2294
- const { options, total } = await fetch('/api/shipping/calculate', {
2295
- method: 'POST',
2296
- headers: { 'Content-Type': 'application/json' },
2297
- body: JSON.stringify({ country: address.country, postalCode: address.postalCode }),
2298
- }).then((r) => r.json());
2299
-
2300
- updateWith({
2301
- amount: total,
2302
- shippingOptions: options,
2303
- lineItems: [
2304
- { label: 'Subtotal', amount: subtotal },
2305
- { label: options[0].label, amount: options[0].amount },
2306
- ],
2307
- });
2308
- });
2309
-
2310
- // Update total when shipping option changes
2311
- express.on(ExpressSdkEvent.ShippingOptionChange, ({ shippingOption, updateWith }) => {
2312
- updateWith({
2313
- amount: subtotal + shippingOption.amount,
2314
- lineItems: [
2315
- { label: 'Subtotal', amount: subtotal },
2316
- { label: shippingOption.label, amount: shippingOption.amount },
2317
- ],
2318
- });
2319
- });
2320
-
2321
- // Payment method ready — confirm on backend
2322
- express.on(
2323
- ExpressSdkEvent.PaymentMethodCreated,
2324
- async ({ paymentMethodId, idempotencyKey, shippingDetails, selectedShippingOption }) => {
2325
- const { orderId } = await fetch('/api/orders', {
2326
- method: 'POST',
2327
- headers: { 'Content-Type': 'application/json' },
2328
- body: JSON.stringify({
2329
- paymentMethodId,
2330
- idempotencyKey,
2331
- shipping: shippingDetails,
2332
- shippingOptionId: selectedShippingOption?.id,
2333
- }),
2334
- }).then((r) => r.json());
2335
-
2336
- onSuccess(orderId);
2337
- },
2338
- );
2339
-
2340
- express.on(ExpressSdkEvent.ShippingOptionsRequired, ({ wallet }) => {
2341
- console.error(`${wallet}: session_start timed out — implement the session_start handler`);
2342
- });
2343
-
2344
- express.on(ExpressSdkEvent.PaymentMethodFailed, ({ error }) =>
2345
- console.error('Payment failed:', error),
2346
- );
2347
- express.on(ExpressSdkEvent.Cancel, onCancel);
2348
-
2349
- express.mount(containerRef.current);
2350
- instanceRef.current = express;
2351
-
2352
- return () => {
2353
- instanceRef.current?.destroy();
2354
- instanceRef.current = null;
2355
- };
2356
- }, [subtotal, onSuccess, onCancel]);
2357
-
2358
- return <div ref={containerRef} style={{ width: '100%' }} />;
2359
- }
2360
- ```
2361
-
2362
- ---
2363
-
2364
- ### `payment_method_created` Event
2365
-
2366
- 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.
2367
-
2368
- ```typescript
2369
- express.on('payment_method_created', (event) => {
2370
- // event.paymentMethodId — Paypercut PM ID (pm_xxx), use this to confirm payment on your backend
2371
- // event.token — { id: string, type: 'apple_pay' | 'google_pay' }
2372
- // event.idempotencyKey — unique key for this payment attempt (pass to your backend)
2373
- // event.billingDetails — { name?, email?, address? }
2374
- // event.shippingDetails — { name?, address? }
2375
- // event.selectedShippingOption — { id, label, amount }
2376
-
2377
- console.log('Payment method created:', event.paymentMethodId);
2378
- console.log('Shipping to:', event.shippingDetails?.address);
2379
- console.log('Selected option:', event.selectedShippingOption?.label);
2380
-
2381
- // Call your backend to create + confirm the payment intent
2382
- await fetch('/api/confirm-payment', {
2383
- method: 'POST',
2384
- body: JSON.stringify({
2385
- paymentMethodId: event.paymentMethodId,
2386
- idempotencyKey: event.idempotencyKey,
2387
- }),
2388
- });
2389
- });
2390
- ```
2391
-
2392
- ```typescript
2393
- interface ExpressPaymentMethodCreatedEvent {
2394
- paymentMethodId: string; // Paypercut PM ID (pm_xxx)
2395
- token: { id: string; type: 'apple_pay' | 'google_pay' };
2396
- idempotencyKey: string;
2397
- billingDetails?: {
2398
- name?: string;
2399
- email?: string;
2400
- phone?: string;
2401
- address?: {
2402
- line1?: string;
2403
- line2?: string;
2404
- city?: string;
2405
- state?: string;
2406
- postalCode?: string;
2407
- country?: string;
2408
- };
2409
- };
2410
- shippingDetails?: {
2411
- name?: string;
2412
- address?: {
2413
- line1?: string;
2414
- line2?: string;
2415
- city?: string;
2416
- state?: string;
2417
- postalCode?: string;
2418
- country?: string;
2419
- };
2420
- };
2421
- selectedShippingOption?: { id: string; label: string; detail?: string; amount: number };
2422
- }
2423
- ```
2424
-
2425
- ---
2426
-
2427
- ### Express Checkout Full Example
2428
-
2429
- ```html
2430
- <!DOCTYPE html>
2431
- <html>
2432
- <head>
2433
- <title>Express Checkout</title>
2434
- </head>
2435
- <body>
2436
- <div id="express-checkout" style="max-width: 400px;"></div>
2437
-
2438
- <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js/dist/paypercut-checkout.iife.min.js"></script>
2439
- <script>
2440
- const express = PaypercutExpressCheckout({
2441
- publishableKey: 'pk_test_...',
2442
- amount: 2500,
2443
- currency: 'EUR',
2444
- countryCode: 'DE',
2445
- shippingOptions: [
2446
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 days', amount: 499 },
2447
- { id: 'express', label: 'Express Shipping', detail: '1–2 days', amount: 999 },
2448
- ],
2449
- lineItems: [
2450
- { label: 'Subtotal', amount: 2500 },
2451
- { label: 'Standard Shipping', amount: 499 },
2452
- ],
2453
- });
2454
-
2455
- // Wallet buttons ready
2456
- express.on('ready', () => console.log('Express Checkout ready'));
2457
-
2458
- // Shipping address changed — recalculate and respond
2459
- express.on('shipping_address_change', ({ address, updateWith }) => {
2460
- const shippingCost = address.country === 'DE' ? 499 : 799;
2461
- updateWith({
2462
- amount: 2500 + shippingCost,
2463
- shippingOptions: [
2464
- { id: 'standard', label: 'Standard Shipping', amount: shippingCost },
2465
- { id: 'express', label: 'Express Shipping', amount: shippingCost + 500 },
2466
- ],
2467
- lineItems: [
2468
- { label: 'Subtotal', amount: 2500 },
2469
- { label: 'Standard Shipping', amount: shippingCost },
2470
- ],
2471
- });
2472
- });
2473
-
2474
- // Shipping option changed — update total
2475
- express.on('shipping_option_change', ({ shippingOption, updateWith }) => {
2476
- updateWith({
2477
- amount: 2500 + shippingOption.amount,
2478
- lineItems: [
2479
- { label: 'Subtotal', amount: 2500 },
2480
- { label: shippingOption.label, amount: shippingOption.amount },
2481
- ],
2482
- });
2483
- });
2484
-
2485
- // Payment method created — confirm on backend
2486
- express.on('payment_method_created', async (event) => {
2487
- console.log('Payment method:', event.paymentMethodId);
2488
- console.log('Shipping option:', event.selectedShippingOption?.label);
2489
- await fetch('/api/confirm-payment', {
2490
- method: 'POST',
2491
- headers: { 'Content-Type': 'application/json' },
2492
- body: JSON.stringify({ paymentMethodId: event.paymentMethodId }),
2493
- });
2494
- window.location.href = '/success';
2495
- });
2496
-
2497
- express.on('payment_method_failed', ({ error }) => {
2498
- console.error('Payment failed:', error);
2499
- });
2500
-
2501
- express.on('cancel', () => {
2502
- console.log('User dismissed the wallet sheet');
2503
- });
2504
-
2505
- express.mount('#express-checkout');
2506
- </script>
2507
- </body>
2508
- </html>
2509
- ```
2510
-
2511
- ---
2512
-
2513
- ### Express Checkout React Example
2514
-
2515
- ```tsx
2516
- import { useEffect, useRef } from 'react';
2517
- import {
2518
- PaypercutExpressCheckout,
2519
- ExpressSdkEvent,
2520
- ExpressCheckoutInstance,
2521
- } from '@paypercut/checkout-js';
2522
-
2523
- interface Props {
2524
- subtotal: number; // minor units
2525
- onSuccess: (paymentMethodId: string) => void;
2526
- }
2527
-
2528
- export function ExpressCheckoutButton({ subtotal, onSuccess }: Props) {
2529
- const containerRef = useRef<HTMLDivElement>(null);
2530
- const instanceRef = useRef<ExpressCheckoutInstance | null>(null);
2531
-
2532
- useEffect(() => {
2533
- if (!containerRef.current) return;
2534
-
2535
- const express = PaypercutExpressCheckout({
2536
- publishableKey: process.env.NEXT_PUBLIC_PAYPERCUT_KEY!,
2537
- amount: subtotal + 499, // subtotal + default shipping
2538
- currency: 'EUR',
2539
- countryCode: 'DE',
2540
- shippingOptions: [
2541
- { id: 'standard', label: 'Standard Shipping', detail: '3–5 days', amount: 499 },
2542
- { id: 'express', label: 'Express Shipping', detail: '1–2 days', amount: 999 },
2543
- ],
2544
- });
2545
-
2546
- express.on(ExpressSdkEvent.ShippingAddressChange, ({ address, updateWith }) => {
2547
- const shipping = address.country === 'DE' ? 499 : 799;
2548
- updateWith({
2549
- amount: subtotal + shipping,
2550
- shippingOptions: [
2551
- { id: 'standard', label: 'Standard Shipping', amount: shipping },
2552
- { id: 'express', label: 'Express Shipping', amount: shipping + 500 },
2553
- ],
2554
- });
2555
- });
2556
-
2557
- express.on(ExpressSdkEvent.ShippingOptionChange, ({ shippingOption, updateWith }) => {
2558
- updateWith({ amount: subtotal + shippingOption.amount });
2559
- });
2560
-
2561
- express.on(ExpressSdkEvent.PaymentMethodCreated, (event) => {
2562
- onSuccess(event.paymentMethodId);
2563
- });
2564
-
2565
- express.on(ExpressSdkEvent.PaymentMethodFailed, ({ error }) => {
2566
- console.error('Express payment failed:', error);
2567
- });
2568
-
2569
- express.mount(containerRef.current);
2570
- instanceRef.current = express;
2571
-
2572
- return () => {
2573
- instanceRef.current?.destroy();
2574
- instanceRef.current = null;
2575
- };
2576
- }, [subtotal, onSuccess]);
2577
-
2578
- return <div ref={containerRef} style={{ width: '100%' }} />;
2579
- }
2580
- ```
2581
-
2582
- ---
2583
-
2584
- ## FAQ For Internal Validation
2084
+ ## FAQ
2585
2085
 
2586
2086
  **Q: How do I handle successful payments?**
2587
2087
  Listen to the `success` event and redirect users or update your UI accordingly. Always verify the payment on your backend using webhooks.