@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/dist/index.d.ts CHANGED
@@ -57,6 +57,31 @@ declare enum WalletOption {
57
57
  /** Google Pay */
58
58
  GOOGLE_PAY = "google_pay"
59
59
  }
60
+ /**
61
+ * Appearance variables for customising the hosted checkout visual style.
62
+ * All fields are optional — only override what you need.
63
+ */
64
+ interface AppearanceVariables {
65
+ /** Primary button / CTA background colour (hex, e.g. '#0066ff') */
66
+ brandColor?: `#${string}`;
67
+ /** Font family for the checkout UI (must be available in the iframe context) */
68
+ fontFamily?: string;
69
+ /** Merchant logo URL shown in the checkout header (https only) */
70
+ logoUrl?: string;
71
+ /** Border radius for checkout panels and payment method selector (e.g. '8px', '0.5rem') */
72
+ borderRadius?: string;
73
+ }
74
+ /**
75
+ * Appearance options for the hosted checkout UI.
76
+ */
77
+ interface Appearance {
78
+ /** Layout preset */
79
+ preset?: 'inline' | 'modal';
80
+ /** Colour theme */
81
+ theme?: 'light' | 'dark';
82
+ /** Fine-grained visual variable overrides */
83
+ variables?: AppearanceVariables;
84
+ }
60
85
  /**
61
86
  * Configuration options for PaypercutCheckout
62
87
  */
@@ -101,15 +126,9 @@ interface PaypercutCheckoutOptions {
101
126
  */
102
127
  form_only?: boolean;
103
128
  /**
104
- * Optional: Appearance options
129
+ * Optional: Appearance options for theming the checkout UI
105
130
  */
106
- appearance?: {
107
- preset?: 'inline' | 'modal';
108
- theme?: 'light' | 'dark' | 'none' | 'flat';
109
- variables: {};
110
- rules: {};
111
- labels: 'floating' | 'above' | 'none';
112
- };
131
+ appearance?: Appearance;
113
132
  /**
114
133
  * Optional: Require form validation before wallet payment (Google Pay / Apple Pay)
115
134
  * @default false
@@ -186,6 +205,12 @@ interface CheckoutInstance {
186
205
  * @param errors - Optional array of validation errors to pass back
187
206
  */
188
207
  failFormValidation(wallet: WalletType, errors?: FormValidationError[]): void;
208
+ /**
209
+ * Dynamically update the checkout appearance after it has been rendered.
210
+ * Useful for syncing the checkout theme with the merchant page (e.g. dark mode toggle).
211
+ * @param appearance - Partial appearance options to merge into the current appearance
212
+ */
213
+ updateAppearance(appearance: Appearance): void;
189
214
  }
190
215
  /**
191
216
  * PaypercutCheckout static interface (callable and constructable)
@@ -464,4 +489,4 @@ declare const PaypercutExpressCheckout: ExpressCheckoutStatic;
464
489
  declare const PaypercutCheckout: PaypercutCheckoutStatic;
465
490
 
466
491
  export { ExpressSdkEvent, LOCALES, PaymentMethod, PaypercutCheckout, PaypercutExpressCheckout, SdkEvent, UIMode, WalletOption, PaypercutCheckout as default };
467
- export type { ApplePayButtonStyle, CancelPayload, CheckoutInstance, EventName, ExpressBillingDetails, ExpressButtonOptions, ExpressButtonType, ExpressCheckoutInstance, ExpressCheckoutOptions, ExpressCheckoutShippingOption, ExpressCheckoutUpdateOptions, ExpressEventName, ExpressPaymentMethodCreatedEvent, ExpressPaymentMethodFailedEvent, ExpressSessionStartEvent, ExpressShippingAddress, ExpressShippingDetails, ExpressTokenPayload, FormValidationError, GooglePayButtonColor, LineItem, Locale, PaypercutCheckoutOptions, PaypercutCheckoutStatic, ShippingAddressChangeEvent, ShippingOptionChangeEvent, WalletType };
492
+ export type { Appearance, AppearanceVariables, ApplePayButtonStyle, CancelPayload, CheckoutInstance, EventName, ExpressBillingDetails, ExpressButtonOptions, ExpressButtonType, ExpressCheckoutInstance, ExpressCheckoutOptions, ExpressCheckoutShippingOption, ExpressCheckoutUpdateOptions, ExpressEventName, ExpressPaymentMethodCreatedEvent, ExpressPaymentMethodFailedEvent, ExpressSessionStartEvent, ExpressShippingAddress, ExpressShippingDetails, ExpressTokenPayload, FormValidationError, GooglePayButtonColor, LineItem, Locale, PaypercutCheckoutOptions, PaypercutCheckoutStatic, ShippingAddressChangeEvent, ShippingOptionChangeEvent, WalletType };
package/dist/index.mjs CHANGED
@@ -87,7 +87,7 @@ class Emitter {
87
87
  * Production configuration (for merchants)
88
88
  */
89
89
  const productionConfig = {
90
- version: "1.2.4",
90
+ version: "1.2.9",
91
91
  defaultCheckoutOrigin: 'https://buy.paypercut.io',
92
92
  defaultApiOrigin: 'https://api.paypercut.io',
93
93
  defaultVaultApiUrl: 'https://api.basistheory.com',
@@ -528,6 +528,19 @@ var SdkEvent;
528
528
  SdkEvent["Cancel"] = "cancel";
529
529
  SdkEvent["FormValidation"] = "form_validation";
530
530
  })(SdkEvent || (SdkEvent = {}));
531
+ // Apple Pay bridge message names — wire format shared with hosted-checkout's CheckoutMessageType enum.
532
+ // Defined here as a const so the switch in index.ts is compile-checked within this repo.
533
+ // If a message name changes in hosted-checkout, update this map and the switch together.
534
+ const ApplePayBridgeMsg = {
535
+ START: 'APPLE_PAY_START',
536
+ VALIDATE_MERCHANT: 'APPLE_PAY_VALIDATE_MERCHANT',
537
+ MERCHANT_SESSION: 'APPLE_PAY_MERCHANT_SESSION',
538
+ MERCHANT_ERROR: 'APPLE_PAY_MERCHANT_ERROR',
539
+ PAYMENT_DATA: 'APPLE_PAY_PAYMENT_DATA',
540
+ PAYMENT_RESULT: 'APPLE_PAY_PAYMENT_RESULT',
541
+ CANCELLED: 'APPLE_PAY_CANCELLED',
542
+ SESSION_ERROR: 'APPLE_PAY_SESSION_ERROR',
543
+ };
531
544
 
532
545
  // ─── Locale ───────────────────────────────────────────────────────────────────
533
546
  /**
@@ -965,8 +978,8 @@ class ExpressCheckoutImpl {
965
978
  : [WalletOption.APPLE_PAY, WalletOption.GOOGLE_PAY];
966
979
  const showApplePay = requestedWallets.includes(WalletOption.APPLE_PAY);
967
980
  const showGooglePay = requestedWallets.includes(WalletOption.GOOGLE_PAY);
968
- // Wrapper — row (default) or column layout; 'auto' uses ResizeObserver
969
- const layoutOption = this.options.layout ?? 'row';
981
+ // Wrapper — auto (default), row, or column layout; 'auto' uses ResizeObserver
982
+ const layoutOption = this.options.layout ?? 'auto';
970
983
  this.preferredLayout = layoutOption === 'auto' ? 'row' : layoutOption;
971
984
  const wrapper = document.createElement('div');
972
985
  this.wrapper = wrapper;
@@ -2009,6 +2022,54 @@ const PaypercutExpressCheckout = function (options) {
2009
2022
  return new ExpressCheckoutImpl(options);
2010
2023
  };
2011
2024
 
2025
+ // ── Apple Pay SDK loader ──────────────────────────────────────────────────────
2026
+ // Tracks whether the Apple Pay CDN script has already been injected so multiple
2027
+ // CheckoutImpl instances don't race to add it more than once.
2028
+ let _applePaySdkInjected = false;
2029
+ /**
2030
+ * Injects Apple's cross-browser Apple Pay JS SDK into the parent page so that
2031
+ * window.ApplePaySession is available when the embedded bridge delegates session
2032
+ * creation here. On Safari, ApplePaySession is a browser built-in and the script
2033
+ * is a no-op; on Chrome it provides the iCloud Keychain integration.
2034
+ */
2035
+ function ensureApplePaySdk() {
2036
+ if (typeof window === 'undefined')
2037
+ return;
2038
+ if (window.ApplePaySession)
2039
+ return;
2040
+ if (_applePaySdkInjected)
2041
+ return;
2042
+ _applePaySdkInjected = true;
2043
+ const s = document.createElement('script');
2044
+ s.src = 'https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js';
2045
+ s.crossOrigin = 'anonymous';
2046
+ s.async = true;
2047
+ document.head.appendChild(s);
2048
+ }
2049
+ // ── Appearance validation ─────────────────────────────────────────────────────
2050
+ const _HEX_RE = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
2051
+ const _CSS_LEN_RE = /^(0|(\d+(\.\d+)?(px|rem|em)))$/;
2052
+ function warnInvalidAppearanceVariables(variables) {
2053
+ if (!variables)
2054
+ return;
2055
+ if (variables.brandColor !== undefined && !_HEX_RE.test(variables.brandColor)) {
2056
+ console.warn(`[PaypercutCheckout] Invalid appearance.variables.brandColor: "${variables.brandColor}". ` +
2057
+ `Expected a hex color (#RGB or #RRGGBB). Value ignored.`);
2058
+ }
2059
+ if (variables.fontFamily !== undefined && !variables.fontFamily.trim()) {
2060
+ console.warn(`[PaypercutCheckout] Invalid appearance.variables.fontFamily: value is empty. Value ignored.`);
2061
+ }
2062
+ if (variables.logoUrl !== undefined && !/^https:\/\//.test(variables.logoUrl)) {
2063
+ console.warn(`[PaypercutCheckout] Invalid appearance.variables.logoUrl: "${variables.logoUrl}". ` +
2064
+ `Must start with https://. Value ignored.`);
2065
+ }
2066
+ if (variables.borderRadius !== undefined &&
2067
+ !_CSS_LEN_RE.test(variables.borderRadius.trim())) {
2068
+ console.warn(`[PaypercutCheckout] Invalid appearance.variables.borderRadius: "${variables.borderRadius}". ` +
2069
+ `Expected a CSS length like "8px", "0.5rem", or "0". Value ignored.`);
2070
+ }
2071
+ }
2072
+ // ── Checkout implementation ───────────────────────────────────────────────────
2012
2073
  /**
2013
2074
  * Internal implementation of CheckoutInstance
2014
2075
  */
@@ -2019,6 +2080,9 @@ class CheckoutImpl {
2019
2080
  this.mounted = false;
2020
2081
  this.destroyed = false;
2021
2082
  this.iframe = null;
2083
+ // Apple Pay bridge state (embedded mode only)
2084
+ this.applePaySession = null;
2085
+ this.applePayBridgeTimeout = null;
2022
2086
  // Bind message handler
2023
2087
  this.messageHandler = this.onMessage.bind(this);
2024
2088
  this.threeDSModal = new ThreeDSModalController({
@@ -2028,6 +2092,10 @@ class CheckoutImpl {
2028
2092
  onReady: (iframe) => this.postThreeDSInit(iframe),
2029
2093
  });
2030
2094
  window.addEventListener('message', this.messageHandler);
2095
+ // In embedded mode the Apple Pay bridge delegates ApplePaySession creation to this parent window.
2096
+ if (validateUIMode(options.ui_mode ?? UIMode.EMBEDDED) === UIMode.EMBEDDED) {
2097
+ ensureApplePaySdk();
2098
+ }
2031
2099
  }
2032
2100
  /**
2033
2101
  * Build the iframe source URL with query parameters
@@ -2076,6 +2144,13 @@ class CheckoutImpl {
2076
2144
  if (this.options.appearance?.preset) {
2077
2145
  url.searchParams.set('preset', this.options.appearance.preset);
2078
2146
  }
2147
+ if (this.options.appearance?.theme) {
2148
+ url.searchParams.set('theme', this.options.appearance.theme);
2149
+ }
2150
+ if (this.options.appearance?.variables && Object.keys(this.options.appearance.variables).length > 0) {
2151
+ warnInvalidAppearanceVariables(this.options.appearance.variables);
2152
+ url.searchParams.set('appearance_vars', JSON.stringify(this.options.appearance.variables));
2153
+ }
2079
2154
  if (this.options.form_only !== undefined) {
2080
2155
  url.searchParams.set('form_only', String(this.options.form_only));
2081
2156
  }
@@ -2179,6 +2254,18 @@ class CheckoutImpl {
2179
2254
  wallet: data.wallet,
2180
2255
  });
2181
2256
  break;
2257
+ case ApplePayBridgeMsg.START:
2258
+ this.handleApplePayStart(data);
2259
+ break;
2260
+ case ApplePayBridgeMsg.MERCHANT_SESSION:
2261
+ this.handleApplePayMerchantSession(data.merchantSession);
2262
+ break;
2263
+ case ApplePayBridgeMsg.MERCHANT_ERROR:
2264
+ this.abortApplePaySession();
2265
+ break;
2266
+ case ApplePayBridgeMsg.PAYMENT_RESULT:
2267
+ this.handleApplePayPaymentResult(data.success === true);
2268
+ break;
2182
2269
  }
2183
2270
  }
2184
2271
  /**
@@ -2302,6 +2389,95 @@ class CheckoutImpl {
2302
2389
  checkoutId: this.options.id,
2303
2390
  }, checkoutOrigin);
2304
2391
  }
2392
+ // ---------------------------------------------------------------------------
2393
+ // Apple Pay bridge
2394
+ // ---------------------------------------------------------------------------
2395
+ /**
2396
+ * Called when the embedded iframe requests that we create an ApplePaySession at the
2397
+ * top-level window so the payment sheet / QR popup is not clipped by the container.
2398
+ */
2399
+ handleApplePayStart(data) {
2400
+ this.abortApplePaySession();
2401
+ const ApplePayAPI = window.ApplePaySession;
2402
+ if (!ApplePayAPI) {
2403
+ this.postToIframe({ type: ApplePayBridgeMsg.SESSION_ERROR, checkoutId: this.options.id });
2404
+ return;
2405
+ }
2406
+ const version = ApplePayAPI.supportsVersion?.(14) ? 14 : 3;
2407
+ let session;
2408
+ try {
2409
+ session = new ApplePayAPI(version, data.request);
2410
+ }
2411
+ catch (e) {
2412
+ console.error(e?.name === 'SecurityError'
2413
+ ? '[PaypercutCheckout] Apple Pay blocked — parent page missing allow="payment" on iframe'
2414
+ : '[PaypercutCheckout] Failed to create ApplePaySession', e);
2415
+ this.postToIframe({ type: ApplePayBridgeMsg.SESSION_ERROR, checkoutId: this.options.id });
2416
+ return;
2417
+ }
2418
+ this.applePaySession = session;
2419
+ session.onvalidatemerchant = (event) => {
2420
+ // If the iframe doesn't respond within 15 s, abort — Apple's own timeout is ~30 s
2421
+ // and we need to clean up the ref before that fires.
2422
+ this.applePayBridgeTimeout = setTimeout(() => this.abortApplePaySession(), 15000);
2423
+ this.postToIframe({
2424
+ type: ApplePayBridgeMsg.VALIDATE_MERCHANT,
2425
+ checkoutId: this.options.id,
2426
+ validationURL: event.validationURL,
2427
+ });
2428
+ };
2429
+ session.onpaymentauthorized = (event) => {
2430
+ this.postToIframe({
2431
+ type: ApplePayBridgeMsg.PAYMENT_DATA,
2432
+ checkoutId: this.options.id,
2433
+ payment: event.payment,
2434
+ });
2435
+ };
2436
+ session.oncancel = () => {
2437
+ this.applePaySession = null;
2438
+ this.postToIframe({ type: ApplePayBridgeMsg.CANCELLED, checkoutId: this.options.id });
2439
+ };
2440
+ session.begin();
2441
+ }
2442
+ handleApplePayMerchantSession(merchantSession) {
2443
+ if (this.applePayBridgeTimeout) {
2444
+ clearTimeout(this.applePayBridgeTimeout);
2445
+ this.applePayBridgeTimeout = null;
2446
+ }
2447
+ if (!this.applePaySession)
2448
+ return;
2449
+ try {
2450
+ this.applePaySession.completeMerchantValidation(merchantSession);
2451
+ }
2452
+ catch (e) {
2453
+ console.error('[PaypercutCheckout] completeMerchantValidation failed', e);
2454
+ this.abortApplePaySession();
2455
+ this.postToIframe({ type: ApplePayBridgeMsg.SESSION_ERROR, checkoutId: this.options.id });
2456
+ }
2457
+ }
2458
+ handleApplePayPaymentResult(success) {
2459
+ if (!this.applePaySession)
2460
+ return;
2461
+ const ApplePayAPI = window.ApplePaySession;
2462
+ try {
2463
+ this.applePaySession.completePayment(success ? ApplePayAPI.STATUS_SUCCESS : ApplePayAPI.STATUS_FAILURE);
2464
+ }
2465
+ catch (e) {
2466
+ console.error('[PaypercutCheckout] completePayment failed', e);
2467
+ }
2468
+ this.applePaySession = null;
2469
+ }
2470
+ abortApplePaySession() {
2471
+ if (this.applePayBridgeTimeout) {
2472
+ clearTimeout(this.applePayBridgeTimeout);
2473
+ this.applePayBridgeTimeout = null;
2474
+ }
2475
+ try {
2476
+ this.applePaySession?.abort();
2477
+ }
2478
+ catch { }
2479
+ this.applePaySession = null;
2480
+ }
2305
2481
  /**
2306
2482
  * Destroy the checkout instance and cleanup (idempotent)
2307
2483
  */
@@ -2322,6 +2498,8 @@ class CheckoutImpl {
2322
2498
  }
2323
2499
  // Cleanup 3DS modal if open
2324
2500
  this.threeDSModal.close();
2501
+ // Abort Apple Pay session if active
2502
+ this.abortApplePaySession();
2325
2503
  // Only set mounted = false after successful DOM removal
2326
2504
  this.mounted = false;
2327
2505
  this.destroyed = true;
@@ -2369,6 +2547,21 @@ class CheckoutImpl {
2369
2547
  status: 'success',
2370
2548
  });
2371
2549
  }
2550
+ /**
2551
+ * Dynamically update the checkout appearance after it has been rendered.
2552
+ */
2553
+ updateAppearance(appearance) {
2554
+ if (!this.mounted) {
2555
+ console.warn('[PaypercutCheckout] Cannot update appearance: not mounted');
2556
+ return;
2557
+ }
2558
+ warnInvalidAppearanceVariables(appearance.variables);
2559
+ this.postToIframe({
2560
+ type: 'UPDATE_APPEARANCE',
2561
+ checkoutId: this.options.id,
2562
+ appearance,
2563
+ });
2564
+ }
2372
2565
  /**
2373
2566
  * Fail form validation - prevents wallet payment from starting.
2374
2567
  * Call this in response to 'form_validation' event when merchant form has errors.