@paypercut/checkout-js 1.2.4 → 1.2.9

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
@@ -14,6 +14,10 @@ A lightweight, framework-agnostic JavaScript SDK for embedding Paypercut Checkou
14
14
  - [Installation](#installation)
15
15
  - [Quick Start — Embedded Checkout](#quick-start)
16
16
  - [API Reference — Embedded Checkout](#api-reference)
17
+ - [**Customisation**](#customisation)
18
+ - [Appearance at init time](#appearance-at-init-time)
19
+ - [Dynamic updates — updateAppearance()](#dynamic-updates--updateappearance)
20
+ - [AppearanceVariables reference](#appearancevariables-reference)
17
21
  - [Events — Embedded Checkout](#events)
18
22
  - [Form Validation for Wallet Payments](#form-validation-for-wallet-payments)
19
23
  - [**Express Checkout (Apple Pay / Google Pay)**](#express-checkout-apple-pay--google-pay)
@@ -63,12 +67,12 @@ pnpm add @paypercut/checkout-js
63
67
 
64
68
  ```html
65
69
  <!-- jsDelivr (recommended with SRI) -->
66
- <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js@1.2.4/dist/paypercut-checkout.iife.min.js"
70
+ <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js@1.2.5/dist/paypercut-checkout.iife.min.js"
67
71
  integrity="sha384-..."
68
72
  crossorigin="anonymous"></script>
69
73
 
70
74
  <!-- or UNPKG -->
71
- <script src="https://unpkg.com/@paypercut/checkout-js@1.2.4/dist/paypercut-checkout.iife.min.js"></script>
75
+ <script src="https://unpkg.com/@paypercut/checkout-js@1.2.5/dist/paypercut-checkout.iife.min.js"></script>
72
76
  ```
73
77
 
74
78
  ---
@@ -267,6 +271,113 @@ if (checkout.isMounted()) {
267
271
 
268
272
  ---
269
273
 
274
+ ## Customisation
275
+
276
+ > **Available since v1.2.5**
277
+
278
+ Paypercut Checkout supports full visual customisation — you can match your brand colors, typography, corner radius, and even inject your logo. Customisation works in two complementary ways:
279
+
280
+ | Approach | When it applies | How |
281
+ |---|---|---|
282
+ | `appearance` init option | At iframe creation (zero flash) | Pass in `PaypercutCheckout({ appearance: { … } })` |
283
+ | `checkout.updateAppearance()` | After mount (dynamic, e.g. dark-mode toggle) | Call at any time post-`render()` |
284
+
285
+ ---
286
+
287
+ ### Appearance at init time
288
+
289
+ Pass an `appearance` object when creating the checkout instance. These values are serialised into the iframe URL so the correct theme and CSS variables are applied before the first paint — no flash of unstyled content.
290
+
291
+ ```ts
292
+ const checkout = PaypercutCheckout({
293
+ id: 'CHK_xxx',
294
+ containerId: '#checkout',
295
+ appearance: {
296
+ theme: 'dark', // 'light' | 'dark'
297
+ preset: 'modal', // 'inline' | 'modal'
298
+ variables: {
299
+ brandColor: '#ff5500', // CTA button background
300
+ fontFamily: 'Inter, sans-serif',
301
+ borderRadius: '12px',
302
+ logoUrl: 'https://cdn.example.com/logo.png',
303
+ },
304
+ },
305
+ });
306
+
307
+ checkout.render();
308
+ ```
309
+
310
+ **`preset`**
311
+
312
+ | Value | Effect |
313
+ |---|---|
314
+ | `'inline'` | Compact form without the order summary card |
315
+ | `'modal'` | Full form with order summary card + logo rendered at the top |
316
+
317
+ ---
318
+
319
+ ### Dynamic updates — `updateAppearance()`
320
+
321
+ Call `checkout.updateAppearance(appearance)` at any point after `render()` to update the checkout's visual appearance without a full reload. The SDK sends an `UPDATE_APPEARANCE` postMessage to the iframe, which merges the incoming values on top of the current state.
322
+
323
+ ```ts
324
+ // Example: dark-mode toggle on merchant page
325
+ document.getElementById('dark-toggle').addEventListener('change', (e) => {
326
+ checkout.updateAppearance({ theme: e.target.checked ? 'dark' : 'light' });
327
+ });
328
+
329
+ // Example: update brand color after merchant customiser changes
330
+ checkout.updateAppearance({
331
+ variables: {
332
+ brandColor: '#e63946',
333
+ brandColorContrast: '#ffffff',
334
+ },
335
+ });
336
+
337
+ // Example: inject logo after it's fetched asynchronously
338
+ checkout.updateAppearance({
339
+ variables: { logoUrl: 'https://cdn.example.com/logo.png' },
340
+ });
341
+ ```
342
+
343
+ Updates are **merged** — you only need to pass the fields you want to change. Fields omitted from the update are left as-is.
344
+
345
+ > **Note:** `updateAppearance()` requires the checkout to be mounted (`render()` must have been called first). Calling it before `render()` logs a warning and is a no-op.
346
+
347
+ ---
348
+
349
+ ### `AppearanceVariables` reference
350
+
351
+ | Field | Type | Description |
352
+ |---|---|---|
353
+ | `brandColor` | `` `#${string}` `` | Background color of the primary CTA (Pay Now) button. Must be a hex value, e.g. `'#ff5500'`. |
354
+ | `fontFamily` | `string` | CSS font-family value. Applied globally inside the checkout. E.g. `'Inter, sans-serif'`. |
355
+ | `borderRadius` | `string` | CSS length value for element corner radii. Accepts `px`, `rem`, or `em`. E.g. `'8px'`. |
356
+ | `logoUrl` | `string` (https URL) | Your logo shown above the checkout header when `preset: 'modal'`. Must be `https://`. |
357
+
358
+ `brandColor` must be a 3- or 6-digit hex value (e.g. `'#fff'` or `'#ffffff'`). Invalid values log a warning and are silently dropped — the existing color is preserved.
359
+
360
+ ---
361
+
362
+ ### TypeScript types
363
+
364
+ ```ts
365
+ import type { Appearance, AppearanceVariables } from '@paypercut/checkout-js';
366
+
367
+ const appearance: Appearance = {
368
+ theme: 'dark',
369
+ variables: {
370
+ brandColor: '#6366f1',
371
+ fontFamily: 'Inter, sans-serif',
372
+ borderRadius: '10px',
373
+ },
374
+ };
375
+
376
+ checkout.updateAppearance(appearance);
377
+ ```
378
+
379
+ ---
380
+
270
381
  ## Events
271
382
 
272
383
  Subscribe to events using the `on()` method. You can use string event names or the `SdkEvent` enum.
@@ -760,7 +871,7 @@ Tip: Prefer subscribing with the SdkEvent enum for stronger typing.
760
871
  <body>
761
872
  <div id="checkout"></div>
762
873
 
763
- <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js@1.2.4/dist/paypercut-checkout.iife.min.js"></script>
874
+ <script src="https://cdn.jsdelivr.net/npm/@paypercut/checkout-js@1.2.5/dist/paypercut-checkout.iife.min.js"></script>
764
875
  <script>
765
876
  const checkout = PaypercutCheckout({
766
877
  id: '01KB23M9EC960C50G3AH14FTTT',
@@ -1388,7 +1499,7 @@ express.mount('#express-checkout');
1388
1499
  | `shippingOptions` | `ExpressCheckoutShippingOption[]` | Yes | Initial shipping options shown in the wallet sheet. Must include at least one. |
1389
1500
  | `lineItems` | `LineItem[]` | No | Line item breakdown shown in the **Apple Pay** sheet (subtotal, tax, etc.). Ignored by Google Pay. |
1390
1501
  | `walletOptions` | `('apple_pay' \| 'google_pay')[]` | No | Which wallets to show. Defaults to both. |
1391
- | `layout` | `'column' \| 'row'` | No | `'row'` (default) places buttons side by side. `'column'` stacks them vertically. |
1502
+ | `layout` | `'auto' \| 'row' \| 'column'` | No | Button layout. `'auto'` *(default)* uses a ResizeObserver to switch between row (>540 px) and column (≤540 px) automatically. `'row'` is always side by side. `'column'` always stacks vertically. |
1392
1503
  | `locale` | `string` | No | ISO 639-1 two-letter language code (e.g. `'en'`, `'bg'`, `'pl'`). Controls the language of the wallet button labels. Each wallet applies this independently — not all languages are supported by every wallet; unsupported values fall back to `'en'`. |
1393
1504
  | `buttonOptions` | `ExpressButtonOptions` | No | Customize the label type and color/style of the wallet buttons. See [Button Options](#button-options) below. |
1394
1505
 
package/dist/index.cjs CHANGED
@@ -91,7 +91,7 @@ class Emitter {
91
91
  * Production configuration (for merchants)
92
92
  */
93
93
  const productionConfig = {
94
- version: "1.2.4",
94
+ version: "1.2.9",
95
95
  defaultCheckoutOrigin: 'https://buy.paypercut.io',
96
96
  defaultApiOrigin: 'https://api.paypercut.io',
97
97
  defaultVaultApiUrl: 'https://api.basistheory.com',
@@ -532,6 +532,19 @@ exports.SdkEvent = void 0;
532
532
  SdkEvent["Cancel"] = "cancel";
533
533
  SdkEvent["FormValidation"] = "form_validation";
534
534
  })(exports.SdkEvent || (exports.SdkEvent = {}));
535
+ // Apple Pay bridge message names — wire format shared with hosted-checkout's CheckoutMessageType enum.
536
+ // Defined here as a const so the switch in index.ts is compile-checked within this repo.
537
+ // If a message name changes in hosted-checkout, update this map and the switch together.
538
+ const ApplePayBridgeMsg = {
539
+ START: 'APPLE_PAY_START',
540
+ VALIDATE_MERCHANT: 'APPLE_PAY_VALIDATE_MERCHANT',
541
+ MERCHANT_SESSION: 'APPLE_PAY_MERCHANT_SESSION',
542
+ MERCHANT_ERROR: 'APPLE_PAY_MERCHANT_ERROR',
543
+ PAYMENT_DATA: 'APPLE_PAY_PAYMENT_DATA',
544
+ PAYMENT_RESULT: 'APPLE_PAY_PAYMENT_RESULT',
545
+ CANCELLED: 'APPLE_PAY_CANCELLED',
546
+ SESSION_ERROR: 'APPLE_PAY_SESSION_ERROR',
547
+ };
535
548
 
536
549
  // ─── Locale ───────────────────────────────────────────────────────────────────
537
550
  /**
@@ -969,8 +982,8 @@ class ExpressCheckoutImpl {
969
982
  : [exports.WalletOption.APPLE_PAY, exports.WalletOption.GOOGLE_PAY];
970
983
  const showApplePay = requestedWallets.includes(exports.WalletOption.APPLE_PAY);
971
984
  const showGooglePay = requestedWallets.includes(exports.WalletOption.GOOGLE_PAY);
972
- // Wrapper — row (default) or column layout; 'auto' uses ResizeObserver
973
- const layoutOption = this.options.layout ?? 'row';
985
+ // Wrapper — auto (default), row, or column layout; 'auto' uses ResizeObserver
986
+ const layoutOption = this.options.layout ?? 'auto';
974
987
  this.preferredLayout = layoutOption === 'auto' ? 'row' : layoutOption;
975
988
  const wrapper = document.createElement('div');
976
989
  this.wrapper = wrapper;
@@ -2013,6 +2026,54 @@ const PaypercutExpressCheckout = function (options) {
2013
2026
  return new ExpressCheckoutImpl(options);
2014
2027
  };
2015
2028
 
2029
+ // ── Apple Pay SDK loader ──────────────────────────────────────────────────────
2030
+ // Tracks whether the Apple Pay CDN script has already been injected so multiple
2031
+ // CheckoutImpl instances don't race to add it more than once.
2032
+ let _applePaySdkInjected = false;
2033
+ /**
2034
+ * Injects Apple's cross-browser Apple Pay JS SDK into the parent page so that
2035
+ * window.ApplePaySession is available when the embedded bridge delegates session
2036
+ * creation here. On Safari, ApplePaySession is a browser built-in and the script
2037
+ * is a no-op; on Chrome it provides the iCloud Keychain integration.
2038
+ */
2039
+ function ensureApplePaySdk() {
2040
+ if (typeof window === 'undefined')
2041
+ return;
2042
+ if (window.ApplePaySession)
2043
+ return;
2044
+ if (_applePaySdkInjected)
2045
+ return;
2046
+ _applePaySdkInjected = true;
2047
+ const s = document.createElement('script');
2048
+ s.src = 'https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js';
2049
+ s.crossOrigin = 'anonymous';
2050
+ s.async = true;
2051
+ document.head.appendChild(s);
2052
+ }
2053
+ // ── Appearance validation ─────────────────────────────────────────────────────
2054
+ const _HEX_RE = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
2055
+ const _CSS_LEN_RE = /^(0|(\d+(\.\d+)?(px|rem|em)))$/;
2056
+ function warnInvalidAppearanceVariables(variables) {
2057
+ if (!variables)
2058
+ return;
2059
+ if (variables.brandColor !== undefined && !_HEX_RE.test(variables.brandColor)) {
2060
+ console.warn(`[PaypercutCheckout] Invalid appearance.variables.brandColor: "${variables.brandColor}". ` +
2061
+ `Expected a hex color (#RGB or #RRGGBB). Value ignored.`);
2062
+ }
2063
+ if (variables.fontFamily !== undefined && !variables.fontFamily.trim()) {
2064
+ console.warn(`[PaypercutCheckout] Invalid appearance.variables.fontFamily: value is empty. Value ignored.`);
2065
+ }
2066
+ if (variables.logoUrl !== undefined && !/^https:\/\//.test(variables.logoUrl)) {
2067
+ console.warn(`[PaypercutCheckout] Invalid appearance.variables.logoUrl: "${variables.logoUrl}". ` +
2068
+ `Must start with https://. Value ignored.`);
2069
+ }
2070
+ if (variables.borderRadius !== undefined &&
2071
+ !_CSS_LEN_RE.test(variables.borderRadius.trim())) {
2072
+ console.warn(`[PaypercutCheckout] Invalid appearance.variables.borderRadius: "${variables.borderRadius}". ` +
2073
+ `Expected a CSS length like "8px", "0.5rem", or "0". Value ignored.`);
2074
+ }
2075
+ }
2076
+ // ── Checkout implementation ───────────────────────────────────────────────────
2016
2077
  /**
2017
2078
  * Internal implementation of CheckoutInstance
2018
2079
  */
@@ -2023,6 +2084,9 @@ class CheckoutImpl {
2023
2084
  this.mounted = false;
2024
2085
  this.destroyed = false;
2025
2086
  this.iframe = null;
2087
+ // Apple Pay bridge state (embedded mode only)
2088
+ this.applePaySession = null;
2089
+ this.applePayBridgeTimeout = null;
2026
2090
  // Bind message handler
2027
2091
  this.messageHandler = this.onMessage.bind(this);
2028
2092
  this.threeDSModal = new ThreeDSModalController({
@@ -2032,6 +2096,10 @@ class CheckoutImpl {
2032
2096
  onReady: (iframe) => this.postThreeDSInit(iframe),
2033
2097
  });
2034
2098
  window.addEventListener('message', this.messageHandler);
2099
+ // In embedded mode the Apple Pay bridge delegates ApplePaySession creation to this parent window.
2100
+ if (validateUIMode(options.ui_mode ?? exports.UIMode.EMBEDDED) === exports.UIMode.EMBEDDED) {
2101
+ ensureApplePaySdk();
2102
+ }
2035
2103
  }
2036
2104
  /**
2037
2105
  * Build the iframe source URL with query parameters
@@ -2080,6 +2148,13 @@ class CheckoutImpl {
2080
2148
  if (this.options.appearance?.preset) {
2081
2149
  url.searchParams.set('preset', this.options.appearance.preset);
2082
2150
  }
2151
+ if (this.options.appearance?.theme) {
2152
+ url.searchParams.set('theme', this.options.appearance.theme);
2153
+ }
2154
+ if (this.options.appearance?.variables && Object.keys(this.options.appearance.variables).length > 0) {
2155
+ warnInvalidAppearanceVariables(this.options.appearance.variables);
2156
+ url.searchParams.set('appearance_vars', JSON.stringify(this.options.appearance.variables));
2157
+ }
2083
2158
  if (this.options.form_only !== undefined) {
2084
2159
  url.searchParams.set('form_only', String(this.options.form_only));
2085
2160
  }
@@ -2183,6 +2258,18 @@ class CheckoutImpl {
2183
2258
  wallet: data.wallet,
2184
2259
  });
2185
2260
  break;
2261
+ case ApplePayBridgeMsg.START:
2262
+ this.handleApplePayStart(data);
2263
+ break;
2264
+ case ApplePayBridgeMsg.MERCHANT_SESSION:
2265
+ this.handleApplePayMerchantSession(data.merchantSession);
2266
+ break;
2267
+ case ApplePayBridgeMsg.MERCHANT_ERROR:
2268
+ this.abortApplePaySession();
2269
+ break;
2270
+ case ApplePayBridgeMsg.PAYMENT_RESULT:
2271
+ this.handleApplePayPaymentResult(data.success === true);
2272
+ break;
2186
2273
  }
2187
2274
  }
2188
2275
  /**
@@ -2306,6 +2393,95 @@ class CheckoutImpl {
2306
2393
  checkoutId: this.options.id,
2307
2394
  }, checkoutOrigin);
2308
2395
  }
2396
+ // ---------------------------------------------------------------------------
2397
+ // Apple Pay bridge
2398
+ // ---------------------------------------------------------------------------
2399
+ /**
2400
+ * Called when the embedded iframe requests that we create an ApplePaySession at the
2401
+ * top-level window so the payment sheet / QR popup is not clipped by the container.
2402
+ */
2403
+ handleApplePayStart(data) {
2404
+ this.abortApplePaySession();
2405
+ const ApplePayAPI = window.ApplePaySession;
2406
+ if (!ApplePayAPI) {
2407
+ this.postToIframe({ type: ApplePayBridgeMsg.SESSION_ERROR, checkoutId: this.options.id });
2408
+ return;
2409
+ }
2410
+ const version = ApplePayAPI.supportsVersion?.(14) ? 14 : 3;
2411
+ let session;
2412
+ try {
2413
+ session = new ApplePayAPI(version, data.request);
2414
+ }
2415
+ catch (e) {
2416
+ console.error(e?.name === 'SecurityError'
2417
+ ? '[PaypercutCheckout] Apple Pay blocked — parent page missing allow="payment" on iframe'
2418
+ : '[PaypercutCheckout] Failed to create ApplePaySession', e);
2419
+ this.postToIframe({ type: ApplePayBridgeMsg.SESSION_ERROR, checkoutId: this.options.id });
2420
+ return;
2421
+ }
2422
+ this.applePaySession = session;
2423
+ session.onvalidatemerchant = (event) => {
2424
+ // If the iframe doesn't respond within 15 s, abort — Apple's own timeout is ~30 s
2425
+ // and we need to clean up the ref before that fires.
2426
+ this.applePayBridgeTimeout = setTimeout(() => this.abortApplePaySession(), 15000);
2427
+ this.postToIframe({
2428
+ type: ApplePayBridgeMsg.VALIDATE_MERCHANT,
2429
+ checkoutId: this.options.id,
2430
+ validationURL: event.validationURL,
2431
+ });
2432
+ };
2433
+ session.onpaymentauthorized = (event) => {
2434
+ this.postToIframe({
2435
+ type: ApplePayBridgeMsg.PAYMENT_DATA,
2436
+ checkoutId: this.options.id,
2437
+ payment: event.payment,
2438
+ });
2439
+ };
2440
+ session.oncancel = () => {
2441
+ this.applePaySession = null;
2442
+ this.postToIframe({ type: ApplePayBridgeMsg.CANCELLED, checkoutId: this.options.id });
2443
+ };
2444
+ session.begin();
2445
+ }
2446
+ handleApplePayMerchantSession(merchantSession) {
2447
+ if (this.applePayBridgeTimeout) {
2448
+ clearTimeout(this.applePayBridgeTimeout);
2449
+ this.applePayBridgeTimeout = null;
2450
+ }
2451
+ if (!this.applePaySession)
2452
+ return;
2453
+ try {
2454
+ this.applePaySession.completeMerchantValidation(merchantSession);
2455
+ }
2456
+ catch (e) {
2457
+ console.error('[PaypercutCheckout] completeMerchantValidation failed', e);
2458
+ this.abortApplePaySession();
2459
+ this.postToIframe({ type: ApplePayBridgeMsg.SESSION_ERROR, checkoutId: this.options.id });
2460
+ }
2461
+ }
2462
+ handleApplePayPaymentResult(success) {
2463
+ if (!this.applePaySession)
2464
+ return;
2465
+ const ApplePayAPI = window.ApplePaySession;
2466
+ try {
2467
+ this.applePaySession.completePayment(success ? ApplePayAPI.STATUS_SUCCESS : ApplePayAPI.STATUS_FAILURE);
2468
+ }
2469
+ catch (e) {
2470
+ console.error('[PaypercutCheckout] completePayment failed', e);
2471
+ }
2472
+ this.applePaySession = null;
2473
+ }
2474
+ abortApplePaySession() {
2475
+ if (this.applePayBridgeTimeout) {
2476
+ clearTimeout(this.applePayBridgeTimeout);
2477
+ this.applePayBridgeTimeout = null;
2478
+ }
2479
+ try {
2480
+ this.applePaySession?.abort();
2481
+ }
2482
+ catch { }
2483
+ this.applePaySession = null;
2484
+ }
2309
2485
  /**
2310
2486
  * Destroy the checkout instance and cleanup (idempotent)
2311
2487
  */
@@ -2326,6 +2502,8 @@ class CheckoutImpl {
2326
2502
  }
2327
2503
  // Cleanup 3DS modal if open
2328
2504
  this.threeDSModal.close();
2505
+ // Abort Apple Pay session if active
2506
+ this.abortApplePaySession();
2329
2507
  // Only set mounted = false after successful DOM removal
2330
2508
  this.mounted = false;
2331
2509
  this.destroyed = true;
@@ -2373,6 +2551,21 @@ class CheckoutImpl {
2373
2551
  status: 'success',
2374
2552
  });
2375
2553
  }
2554
+ /**
2555
+ * Dynamically update the checkout appearance after it has been rendered.
2556
+ */
2557
+ updateAppearance(appearance) {
2558
+ if (!this.mounted) {
2559
+ console.warn('[PaypercutCheckout] Cannot update appearance: not mounted');
2560
+ return;
2561
+ }
2562
+ warnInvalidAppearanceVariables(appearance.variables);
2563
+ this.postToIframe({
2564
+ type: 'UPDATE_APPEARANCE',
2565
+ checkoutId: this.options.id,
2566
+ appearance,
2567
+ });
2568
+ }
2376
2569
  /**
2377
2570
  * Fail form validation - prevents wallet payment from starting.
2378
2571
  * Call this in response to 'form_validation' event when merchant form has errors.