@paypercut/checkout-js 1.0.23 → 1.1.7

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.cjs CHANGED
@@ -65,6 +65,13 @@ class Emitter {
65
65
  }
66
66
  });
67
67
  }
68
+ /**
69
+ * Returns true if at least one handler is registered for the given event
70
+ */
71
+ hasListeners(event) {
72
+ const set = this.handlers.get(event);
73
+ return !!set && set.size > 0;
74
+ }
68
75
  /**
69
76
  * Clear all event handlers
70
77
  */
@@ -84,8 +91,10 @@ class Emitter {
84
91
  * Production configuration (for merchants)
85
92
  */
86
93
  const productionConfig = {
87
- version: "1.0.23",
94
+ version: "1.1.7",
88
95
  defaultCheckoutOrigin: 'https://buy.paypercut.io',
96
+ defaultApiOrigin: 'https://api.paypercut.io',
97
+ defaultVaultApiUrl: 'https://api.basistheory.com',
89
98
  allowedOrigins: [
90
99
  'https://buy.paypercut.io',
91
100
  ]};
@@ -105,6 +114,18 @@ function isOriginAllowed(origin) {
105
114
  function getCheckoutOrigin(override) {
106
115
  return config.defaultCheckoutOrigin;
107
116
  }
117
+ /**
118
+ * Get the Paypercut API origin (with optional override for internal builds)
119
+ */
120
+ function getApiOrigin(override) {
121
+ return config.defaultApiOrigin;
122
+ }
123
+ /**
124
+ * Get the vault provider API URL (not overridable — internal use only)
125
+ */
126
+ function getVaultApiUrl() {
127
+ return config.defaultVaultApiUrl;
128
+ }
108
129
 
109
130
  /**
110
131
  * Supported locales for Paypercut Checkout
@@ -140,6 +161,7 @@ const LOCALES = [
140
161
  'cs', 'cs-CZ',
141
162
  'sl', 'sl-SI',
142
163
  'sk', 'sk-SK',
164
+ 'hu', 'hu-HU',
143
165
  ];
144
166
  /**
145
167
  * Fast runtime check using Set for O(1) lookup
@@ -282,6 +304,1493 @@ exports.SdkEvent = void 0;
282
304
  SdkEvent["FormValidation"] = "form_validation";
283
305
  })(exports.SdkEvent || (exports.SdkEvent = {}));
284
306
 
307
+ // ─── Locale ───────────────────────────────────────────────────────────────────
308
+ /**
309
+ * ISO 639-1 two-letter language codes supported by the Express Checkout wallet buttons.
310
+ *
311
+ * Pass one of these to `locale` in the options or to `setLocale()` after mount.
312
+ * Each wallet applies the locale independently:
313
+ * - Apple Pay supports all values in this list.
314
+ * - Google Pay supports most; unsupported languages (e.g. 'ro', 'hu') fall back to 'en'.
315
+ */
316
+ /**
317
+ * ISO 639-1 language codes supported by Google Pay's buttonLocale parameter.
318
+ * Source: https://developers.google.com/pay/api/web/reference/request-objects#ButtonOptions
319
+ */
320
+ const GPAY_SUPPORTED_LOCALES = new Set([
321
+ 'ar', 'bg', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es', 'et',
322
+ 'fi', 'fr', 'hr', 'id', 'it', 'ja', 'ko', 'ms', 'nl', 'no',
323
+ 'pl', 'pt', 'ru', 'sk', 'sl', 'sr', 'sv', 'th', 'tr', 'uk', 'zh',
324
+ ]);
325
+ /** @internal */
326
+ function normalizeApplePayLocale(locale) {
327
+ return locale || 'en';
328
+ }
329
+ /** @internal */
330
+ function normalizeGPayLocale(locale) {
331
+ const lang = locale.split('-')[0].toLowerCase();
332
+ return GPAY_SUPPORTED_LOCALES.has(lang) ? lang : 'en';
333
+ }
334
+ exports.ExpressSdkEvent = void 0;
335
+ (function (ExpressSdkEvent) {
336
+ ExpressSdkEvent["Ready"] = "ready";
337
+ ExpressSdkEvent["Click"] = "click";
338
+ ExpressSdkEvent["SessionStart"] = "session_start";
339
+ ExpressSdkEvent["ShippingOptionsRequired"] = "shipping_options_required";
340
+ ExpressSdkEvent["ShippingAddressChange"] = "shipping_address_change";
341
+ ExpressSdkEvent["ShippingOptionChange"] = "shipping_option_change";
342
+ ExpressSdkEvent["PaymentMethodCreated"] = "payment_method_created";
343
+ ExpressSdkEvent["PaymentMethodFailed"] = "payment_method_failed";
344
+ ExpressSdkEvent["Cancel"] = "cancel";
345
+ ExpressSdkEvent["Error"] = "error";
346
+ })(exports.ExpressSdkEvent || (exports.ExpressSdkEvent = {}));
347
+
348
+ // ─── UUID helper ──────────────────────────────────────────────────────────────
349
+ function generateId() {
350
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
351
+ return crypto.randomUUID();
352
+ }
353
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
354
+ const r = (Math.random() * 16) | 0;
355
+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
356
+ });
357
+ }
358
+ // ─── Live key detection ───────────────────────────────────────────────────────
359
+ function isLiveKey(publishableKey) {
360
+ return publishableKey.startsWith('pk_live_');
361
+ }
362
+ // ─── Apple Pay JS SDK loader ──────────────────────────────────────────────────
363
+ let applePayScriptPromise = null;
364
+ function loadApplePayScript() {
365
+ if (applePayScriptPromise)
366
+ return applePayScriptPromise;
367
+ applePayScriptPromise = new Promise((resolve) => {
368
+ if (typeof window === 'undefined') {
369
+ resolve();
370
+ return;
371
+ }
372
+ // <apple-pay-button> custom element already registered — SDK already loaded
373
+ if (customElements?.get('apple-pay-button')) {
374
+ resolve();
375
+ return;
376
+ }
377
+ const script = document.createElement('script');
378
+ script.src = 'https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js';
379
+ script.async = true;
380
+ script.onload = () => resolve();
381
+ // Non-Apple browsers won't expose ApplePaySession — treat as unavailable, not an error
382
+ script.onerror = () => resolve();
383
+ document.head.appendChild(script);
384
+ });
385
+ return applePayScriptPromise;
386
+ }
387
+ // ─── Google Pay JS API loader ─────────────────────────────────────────────────
388
+ let gpayScriptPromise = null;
389
+ function loadGooglePayScript() {
390
+ if (gpayScriptPromise)
391
+ return gpayScriptPromise;
392
+ gpayScriptPromise = new Promise((resolve, reject) => {
393
+ if (typeof window === 'undefined') {
394
+ reject(new Error('No window'));
395
+ return;
396
+ }
397
+ if (globalThis.google?.payments?.api?.PaymentsClient) {
398
+ resolve();
399
+ return;
400
+ }
401
+ const script = document.createElement('script');
402
+ script.src = 'https://pay.google.com/gp/p/js/pay.js';
403
+ script.async = true;
404
+ script.onload = () => resolve();
405
+ script.onerror = () => reject(new Error('Failed to load Google Pay script'));
406
+ document.head.appendChild(script);
407
+ });
408
+ return gpayScriptPromise;
409
+ }
410
+ // ─── Google Pay PaymentDataRequestUpdate builder ──────────────────────────────
411
+ /**
412
+ * Converts SDK update options into the Google Pay `PaymentDataRequestUpdate` shape.
413
+ * Pure function — no class state needed beyond currency and countryCode.
414
+ */
415
+ function buildGpayPaymentDataUpdate(update, currency, countryCode = 'DE') {
416
+ const result = {};
417
+ if (update.amount !== undefined) {
418
+ result.newTransactionInfo = {
419
+ totalPriceStatus: 'FINAL',
420
+ totalPriceLabel: 'Total',
421
+ totalPrice: (update.amount / 100).toFixed(2),
422
+ currencyCode: currency,
423
+ countryCode,
424
+ };
425
+ }
426
+ if (update.shippingOptions?.length) {
427
+ result.newShippingOptionParameters = {
428
+ defaultSelectedOptionId: update.shippingOptions[0].id,
429
+ shippingOptions: update.shippingOptions.map((so) => ({
430
+ id: so.id,
431
+ label: so.label,
432
+ description: so.detail ?? `${(so.amount / 100).toFixed(2)} ${currency}`,
433
+ })),
434
+ };
435
+ }
436
+ if (update.status === 'invalid_shipping_address') {
437
+ result.error = {
438
+ reason: 'SHIPPING_ADDRESS_UNSERVICEABLE',
439
+ message: 'Cannot ship to this address.',
440
+ intent: 'SHIPPING_ADDRESS',
441
+ };
442
+ }
443
+ else if (update.status === 'invalid_shipping_option') {
444
+ result.error = {
445
+ reason: 'SHIPPING_OPTION_INVALID',
446
+ message: 'This shipping option is not available.',
447
+ intent: 'SHIPPING_OPTION',
448
+ };
449
+ }
450
+ return result;
451
+ }
452
+
453
+ // Apple Pay uses 'check-out' (hyphenated); our public API uses 'checkout' to match Google Pay
454
+ function toApplePayButtonType(type) {
455
+ return type === 'checkout' ? 'check-out' : type;
456
+ }
457
+ // Implementation
458
+ class ExpressCheckoutImpl {
459
+ constructor(options) {
460
+ this.options = options;
461
+ this.emitter = new Emitter();
462
+ this.mounted = false;
463
+ this.destroyed = false;
464
+ /** True while a wallet payment sheet is open — prevents concurrent sessions */
465
+ this.sessionActive = false;
466
+ // DOM elements created by mount()
467
+ this.tokenizeIframe = null;
468
+ this.wrapper = null;
469
+ this.applePayContainer = null;
470
+ this.applePayButtonEl = null;
471
+ this.gpayContainer = null;
472
+ this.gpayClient = null;
473
+ this.gpayPaymentRequest = null;
474
+ this.gpayCurrentAmount = 0;
475
+ // Layout state
476
+ this.preferredLayout = 'row';
477
+ this.layoutResizeObserver = null;
478
+ /**
479
+ * Client-generated ID used to route postMessages to the correct instance.
480
+ * Passed to each iframe as a query param; echoed back in every message.
481
+ */
482
+ this.instanceId = generateId();
483
+ /**
484
+ * Idempotency key for the current payment attempt.
485
+ * Regenerated on each wallet button click so retries get a fresh key.
486
+ */
487
+ this.idempotencyKey = generateId();
488
+ // 3DS modal — same pattern as CheckoutImpl
489
+ this.threeDSModal = null;
490
+ this.threeDSIframe = null;
491
+ // Pending 3DS data captured during THREEDS_START_FLOW while GPay sheet is still closing.
492
+ // Shown after loadPaymentData() resolves
493
+ this.pending3DSAfterGpay = null;
494
+ // Apple Pay native session state — session created directly in the SDK window
495
+ // on the merchant's registered domain.
496
+ this.applePaySession = null;
497
+ this.applePayCurrentAmount = 0;
498
+ this.currentLineItems = [];
499
+ this.applePayCurrentShippingOptions = [];
500
+ this.applePayPendingShippingOption = null;
501
+ this.applePayPendingCallback = null;
502
+ // Stored from onpaymentauthorized — used to populate PaymentMethodCreated after TOKENIZE_RESPONSE
503
+ this.applePayPendingBillingDetails = null;
504
+ this.applePayPendingShippingDetails = null;
505
+ /**
506
+ * Config fetched via HTTP from /api/express/config on mount().
507
+ * Populated before any wallet buttons are mounted.
508
+ */
509
+ this.expressConfig = null;
510
+ // Pending Google Pay payment data waiting for tokenization response
511
+ this.pendingGpayResolve = null;
512
+ this.pendingGpayReject = null;
513
+ // Stored GPay metadata for use when TOKENIZE_RESPONSE arrives after 3DS (sheet already closed)
514
+ this.pendingGpayBillingDetails = null;
515
+ this.pendingGpayShippingDetails = null;
516
+ this.pendingGpayShippingOption = undefined;
517
+ this.currentShippingOptions = options.shippingOptions ?? [];
518
+ this.messageHandler = this.onMessage.bind(this);
519
+ window.addEventListener('message', this.messageHandler);
520
+ }
521
+ // ─── URL builders
522
+ buildTokenizeSrc() {
523
+ const baseUrl = getCheckoutOrigin(this.options.hostedCheckoutUrl);
524
+ const url = new URL('/express/tokenize', baseUrl);
525
+ url.searchParams.set('instanceId', this.instanceId);
526
+ url.searchParams.set('liveMode', String(isLiveKey(this.options.publishableKey)));
527
+ return url.toString();
528
+ }
529
+ // ─── Config fetch
530
+ async fetchExpressConfig() {
531
+ const apiOrigin = getApiOrigin(this.options.apiUrl);
532
+ const url = new URL('/v1/elements/sessions', apiOrigin);
533
+ url.searchParams.set('type', 'deferred_intent');
534
+ url.searchParams.set('key', this.options.publishableKey);
535
+ url.searchParams.set('deferred_intent[mode]', 'payment');
536
+ url.searchParams.set('referrer_host', window.location.hostname);
537
+ try {
538
+ const res = await fetch(url.toString(), { cache: 'no-store' });
539
+ if (!res.ok)
540
+ throw new Error(`Config fetch failed: HTTP ${res.status}`);
541
+ const data = await res.json();
542
+ const liveMode = isLiveKey(this.options.publishableKey);
543
+ const googlePayTestMerchantId = 'BCR2DN5T735375Y7';
544
+ const googlePayMerchantRef = data.payment_domain?.wallets?.google_pay?.merchant_ref ?? '';
545
+ const googlePayStatus = data.payment_domain?.wallets?.google_pay?.status ?? 'inactive';
546
+ this.expressConfig = {
547
+ tenantId: data.payment_domain?.wallet_provider?.tenant_id ?? '',
548
+ publicKey: data.payment_domain?.wallet_provider?.public_key ?? '',
549
+ vaultApiUrl: getVaultApiUrl(),
550
+ googlePayMerchantId: liveMode
551
+ ? googlePayStatus === 'active'
552
+ ? googlePayMerchantRef
553
+ : googlePayTestMerchantId
554
+ : googlePayMerchantRef || googlePayTestMerchantId,
555
+ googlePayStatus,
556
+ applePayStatus: data.payment_domain?.wallets?.apple_pay?.status ?? 'inactive',
557
+ displayName: data.merchant?.name ?? '',
558
+ merchantMid: data.merchant?.mid ?? '',
559
+ merchantMcc: data.merchant?.mcc ?? '',
560
+ merchantCountry: data.merchant?.country ?? '',
561
+ merchantUrl: data.merchant?.business_url ?? '',
562
+ };
563
+ }
564
+ catch (err) {
565
+ console.error('[PaypercutExpressCheckout] Failed to fetch express config:', err);
566
+ // expressConfig stays null — wallet buttons will not mount
567
+ }
568
+ }
569
+ // postMessage handler
570
+ onMessage(evt) {
571
+ if (!isOriginAllowed(evt.origin)) {
572
+ if (evt.origin.includes('localhost')) {
573
+ console.warn('[PaypercutExpressCheckout] Message blocked — origin not allowed:', evt.origin);
574
+ }
575
+ return;
576
+ }
577
+ const data = evt.data;
578
+ if (!data || typeof data !== 'object' || !('type' in data))
579
+ return;
580
+ if (data.instanceId && data.instanceId !== this.instanceId) {
581
+ return;
582
+ }
583
+ switch (data.type) {
584
+ // Tokenization response from the hidden tokenize iframe — handles both wallets.
585
+ // For Apple Pay: calls createPaymentMethod, then completes/aborts the Apple Pay sheet.
586
+ // For Google Pay: resolves the pending promise inside handleGooglePayAuthorized.
587
+ case 'TOKENIZE_RESPONSE':
588
+ if (data.wallet === 'apple_pay') {
589
+ if (data.success) {
590
+ this.createPaymentMethod({
591
+ btTokenId: data.btTokenId,
592
+ cardPayload: data.cardPayload,
593
+ billingDetails: data.billingDetails,
594
+ csessId: data.csessId,
595
+ walletType: 'apple_pay',
596
+ }).then((paymentMethodId) => {
597
+ this.completeApplePaySession(true);
598
+ this.emitter.emit(exports.ExpressSdkEvent.PaymentMethodCreated, {
599
+ paymentMethodId,
600
+ wallet: 'apple_pay',
601
+ billingDetails: this.applePayPendingBillingDetails ?? undefined,
602
+ shippingDetails: this.applePayPendingShippingDetails ?? undefined,
603
+ selectedShippingOption: this.applePayPendingShippingOption ?? undefined,
604
+ });
605
+ this.applePayPendingBillingDetails = null;
606
+ this.applePayPendingShippingDetails = null;
607
+ this.applePayPendingShippingOption = null;
608
+ }).catch((err) => {
609
+ this.completeApplePaySession(false);
610
+ this.emitter.emit(exports.ExpressSdkEvent.Error, new Error(err?.message ?? 'Payment method creation failed'));
611
+ this.emitter.emit(exports.ExpressSdkEvent.PaymentMethodFailed, { error: err?.message ?? 'Payment method creation failed' });
612
+ this.applePayPendingBillingDetails = null;
613
+ this.applePayPendingShippingDetails = null;
614
+ this.applePayPendingShippingOption = null;
615
+ });
616
+ }
617
+ else {
618
+ this.completeApplePaySession(false);
619
+ this.emitter.emit(exports.ExpressSdkEvent.Error, new Error(data.error ?? 'Apple Pay payment failed'));
620
+ this.emitter.emit(exports.ExpressSdkEvent.PaymentMethodFailed, { error: data.error ?? 'Apple Pay payment failed' });
621
+ this.applePayPendingBillingDetails = null;
622
+ this.applePayPendingShippingDetails = null;
623
+ this.applePayPendingShippingOption = null;
624
+ }
625
+ }
626
+ else {
627
+ // Google Pay
628
+ if (data.success) {
629
+ if (this.pendingGpayResolve) {
630
+ // Normal path (no 3DS): resolve and let handleGooglePayAuthorized create PM
631
+ this.pendingGpayResolve(data);
632
+ this.pendingGpayResolve = null;
633
+ this.pendingGpayReject = null;
634
+ }
635
+ else {
636
+ // Post-3DS path: sheet was already closed — create PM directly, same as Apple Pay
637
+ this.createPaymentMethod({
638
+ btTokenId: data.btTokenId,
639
+ cardPayload: data.cardPayload,
640
+ billingDetails: data.billingDetails,
641
+ csessId: data.csessId,
642
+ walletType: 'google_pay',
643
+ }).then((paymentMethodId) => {
644
+ this.emitter.emit(exports.ExpressSdkEvent.PaymentMethodCreated, {
645
+ paymentMethodId,
646
+ wallet: 'google_pay',
647
+ billingDetails: this.pendingGpayBillingDetails ?? undefined,
648
+ shippingDetails: this.pendingGpayShippingDetails ?? undefined,
649
+ selectedShippingOption: this.pendingGpayShippingOption,
650
+ });
651
+ }).catch((err) => {
652
+ this.emitter.emit(exports.ExpressSdkEvent.Error, new Error(err?.message ?? 'Payment method creation failed'));
653
+ this.emitter.emit(exports.ExpressSdkEvent.PaymentMethodFailed, { error: err?.message ?? 'Payment method creation failed' });
654
+ }).finally(() => {
655
+ this.pendingGpayBillingDetails = null;
656
+ this.pendingGpayShippingDetails = null;
657
+ this.pendingGpayShippingOption = undefined;
658
+ });
659
+ }
660
+ }
661
+ else {
662
+ if (this.pendingGpayReject) {
663
+ // Normal path (no 3DS): reject the pending promise in handleGooglePayAuthorized
664
+ this.pendingGpayReject(new Error(data.error ?? 'Tokenization failed'));
665
+ this.pendingGpayResolve = null;
666
+ this.pendingGpayReject = null;
667
+ }
668
+ else {
669
+ // Post-3DS path: sheet already closed — emit events directly.
670
+ // Distinguish user cancellation from an actual error so integrators
671
+ // can handle them differently (e.g. "cancel" = re-show checkout,
672
+ // "error" = show an error message).
673
+ const errMsg = data.error ?? 'Google Pay payment failed';
674
+ const isCanceled = errMsg.toLowerCase().includes('cancel');
675
+ if (isCanceled) {
676
+ this.emitter.emit(exports.ExpressSdkEvent.Cancel);
677
+ }
678
+ else {
679
+ this.emitter.emit(exports.ExpressSdkEvent.Error, new Error(errMsg));
680
+ this.emitter.emit(exports.ExpressSdkEvent.PaymentMethodFailed, { error: errMsg });
681
+ }
682
+ this.pendingGpayBillingDetails = null;
683
+ this.pendingGpayShippingDetails = null;
684
+ this.pendingGpayShippingOption = undefined;
685
+ }
686
+ }
687
+ }
688
+ break;
689
+ // 3DS flow
690
+ case 'THREEDS_START_FLOW':
691
+ // Google Pay sheet is a native browser UI that cannot be overlaid by DOM elements.
692
+ // Resolve the pending GPay promise so GPay starts closing its sheet.
693
+ if (this.pendingGpayResolve) {
694
+ this.pending3DSAfterGpay = data;
695
+ this.pendingGpayResolve({ __closeSheet: true });
696
+ this.pendingGpayResolve = null;
697
+ this.pendingGpayReject = null;
698
+ }
699
+ else {
700
+ // Apple Pay or any path without a pending GPay sheet — show immediately
701
+ this.show3DSModal(data);
702
+ }
703
+ break;
704
+ case 'THREEDS_READY':
705
+ this.handle3DSReady();
706
+ break;
707
+ case 'THREEDS_COMPLETE':
708
+ case 'THREEDS_CANCELED':
709
+ case 'THREEDS_ERROR':
710
+ this.postToTokenizeIframe(data);
711
+ this.close3DSModal();
712
+ break;
713
+ }
714
+ }
715
+ // ─── Public API ──
716
+ mount(container) {
717
+ if (this.mounted) {
718
+ console.warn('[PaypercutExpressCheckout] mount() called but already mounted — ignoring');
719
+ return;
720
+ }
721
+ const el = typeof container === 'string'
722
+ ? document.querySelector(container)
723
+ : container;
724
+ if (!el) {
725
+ throw new Error(`[PaypercutExpressCheckout] Container not found: ${container}`);
726
+ }
727
+ const requestedWallets = this.options.walletOptions?.length
728
+ ? this.options.walletOptions
729
+ : [exports.WalletOption.APPLE_PAY, exports.WalletOption.GOOGLE_PAY];
730
+ const showApplePay = requestedWallets.includes(exports.WalletOption.APPLE_PAY);
731
+ const showGooglePay = requestedWallets.includes(exports.WalletOption.GOOGLE_PAY);
732
+ // Wrapper — row (default) or column layout; 'auto' uses ResizeObserver
733
+ const layoutOption = this.options.layout ?? 'row';
734
+ this.preferredLayout = layoutOption === 'auto' ? 'row' : layoutOption;
735
+ const wrapper = document.createElement('div');
736
+ this.wrapper = wrapper;
737
+ Object.assign(wrapper.style, {
738
+ display: 'flex',
739
+ flexDirection: this.preferredLayout === 'row' ? 'row' : 'column',
740
+ gap: '8px',
741
+ width: '100%',
742
+ });
743
+ // Placeholder containers — filled after config is fetched
744
+ // Google Pay is rendered first, Apple Pay second
745
+ if (showGooglePay) {
746
+ this.gpayContainer = document.createElement('div');
747
+ this.applyLayoutToContainers(this.preferredLayout, this.gpayContainer);
748
+ wrapper.appendChild(this.gpayContainer);
749
+ // Preload Google Pay script in parallel while config is being fetched
750
+ loadGooglePayScript().catch((err) => {
751
+ console.error('[PaypercutExpressCheckout] Failed to load Google Pay script:', err);
752
+ });
753
+ }
754
+ if (showApplePay) {
755
+ this.applePayContainer = document.createElement('div');
756
+ this.applyLayoutToContainers(this.preferredLayout, this.applePayContainer);
757
+ wrapper.appendChild(this.applePayContainer);
758
+ // Pre-load Apple Pay JS SDK in parallel while config is being fetched.
759
+ // Resolves even on non-Apple browsers — ApplePaySession check happens after.
760
+ loadApplePayScript();
761
+ }
762
+ el.appendChild(wrapper);
763
+ // Auto layout — observe container width and switch at 540px breakpoint
764
+ if (layoutOption === 'auto' && typeof ResizeObserver !== 'undefined') {
765
+ this.layoutResizeObserver = new ResizeObserver((entries) => {
766
+ const width = entries[0]?.contentRect.width ?? el.offsetWidth;
767
+ this.applyLayout(width <= 540 ? 'column' : 'row');
768
+ });
769
+ this.layoutResizeObserver.observe(el);
770
+ }
771
+ // Hidden tokenize iframe (appended to body, off-screen) — used by both wallets
772
+ const tokenizeSrc = this.buildTokenizeSrc();
773
+ this.tokenizeIframe = document.createElement('iframe');
774
+ this.tokenizeIframe.id = 'paypercut-express-tokenize-iframe';
775
+ this.tokenizeIframe.src = tokenizeSrc;
776
+ this.tokenizeIframe.setAttribute('frameborder', '0');
777
+ this.tokenizeIframe.setAttribute('sandbox', 'allow-scripts allow-forms allow-same-origin');
778
+ Object.assign(this.tokenizeIframe.style, {
779
+ position: 'absolute',
780
+ top: '-9999px',
781
+ left: '-9999px',
782
+ width: '1px',
783
+ height: '1px',
784
+ border: 'none',
785
+ visibility: 'hidden',
786
+ });
787
+ document.body.appendChild(this.tokenizeIframe);
788
+ this.mounted = true;
789
+ // Fetch config then mount wallet buttons
790
+ this.fetchExpressConfig().then(async () => {
791
+ if (this.destroyed)
792
+ return;
793
+ const config = this.expressConfig;
794
+ if (showApplePay && this.applePayContainer && config?.applePayStatus === 'active') {
795
+ await this.mountApplePayButton(this.applePayContainer);
796
+ }
797
+ else if (this.applePayContainer) {
798
+ // Apple Pay can't mount — remove its container so the remaining button fills full width
799
+ this.applePayContainer.remove();
800
+ this.applePayContainer = null;
801
+ }
802
+ if (showGooglePay && config) {
803
+ this.mountGooglePayFromConfig();
804
+ }
805
+ this.emitter.emit(exports.ExpressSdkEvent.Ready);
806
+ });
807
+ }
808
+ // ─── Layout ──────────────────────────────────────
809
+ applyLayoutToContainers(layout, ...containers) {
810
+ for (const container of containers) {
811
+ if (!container)
812
+ continue;
813
+ container.style.flex = layout === 'row' ? '1' : '';
814
+ container.style.minWidth = layout === 'row' ? '0' : '';
815
+ container.style.width = layout === 'row' ? '' : '100%';
816
+ }
817
+ }
818
+ applyLayout(layout) {
819
+ if (!this.wrapper)
820
+ return;
821
+ this.wrapper.style.flexDirection = layout === 'row' ? 'row' : 'column';
822
+ this.applyLayoutToContainers(layout, this.applePayContainer, this.gpayContainer);
823
+ }
824
+ /**
825
+ * Dynamically change the button layout after mount.
826
+ * 'row' places buttons side by side, 'column' stacks them vertically.
827
+ */
828
+ setLayout(layout) {
829
+ this.preferredLayout = layout;
830
+ this.applyLayout(layout);
831
+ }
832
+ /**
833
+ * Dynamically change the locale of the wallet buttons after mount.
834
+ *
835
+ * Pass an ISO 639-1 two-letter language code (e.g. `'en'`, `'bg'`, `'pl'`).
836
+ * Each wallet applies this independently:
837
+ * - Apple Pay updates its button label immediately.
838
+ * - Google Pay recreates its button with the new locale.
839
+ *
840
+ * Unsupported languages fall back to `'en'`. See `ExpressLocale` for the full list.
841
+ *
842
+ * @example
843
+ * express.setLocale('bg'); // switch both buttons to Bulgarian
844
+ */
845
+ setLocale(locale) {
846
+ this.options.locale = locale;
847
+ if (this.applePayButtonEl) {
848
+ this.applePayButtonEl.setAttribute('locale', normalizeApplePayLocale(locale));
849
+ }
850
+ if (this.gpayClient && this.gpayContainer && this.gpayPaymentRequest) {
851
+ this.setButtonOptions({});
852
+ }
853
+ }
854
+ setButtonOptions(opts) {
855
+ this.options.buttonOptions = { ...this.options.buttonOptions, ...opts };
856
+ const merged = this.options.buttonOptions;
857
+ // ── Apple Pay: update attributes on the live <apple-pay-button> element ──
858
+ if (this.applePayButtonEl) {
859
+ if (opts.applePayStyle !== undefined) {
860
+ this.applePayButtonEl.setAttribute('buttonstyle', opts.applePayStyle);
861
+ }
862
+ if (opts.type !== undefined) {
863
+ this.applePayButtonEl.setAttribute('type', toApplePayButtonType(opts.type));
864
+ }
865
+ if (opts.borderRadius !== undefined) {
866
+ this.applePayButtonEl.style.setProperty('--apple-pay-button-border-radius', opts.borderRadius);
867
+ }
868
+ }
869
+ // ── Google Pay: recreate the button (GPay SDK has no update API) ──
870
+ if (this.gpayClient && this.gpayContainer && this.gpayPaymentRequest) {
871
+ this.gpayContainer.innerHTML = '';
872
+ const button = this.gpayClient.createButton({
873
+ onClick: () => this.startGooglePay(this.gpayPaymentRequest),
874
+ buttonSizeMode: 'fill',
875
+ buttonType: merged?.type ?? 'plain',
876
+ buttonColor: merged?.googlePayColor ?? 'default',
877
+ ...(this.options.locale && { buttonLocale: normalizeGPayLocale(this.options.locale) }),
878
+ });
879
+ const borderRadius = merged?.borderRadius ?? '0.5rem';
880
+ button.style.width = '100%';
881
+ this.injectGpayInnerStyles(button, borderRadius);
882
+ this.gpayContainer.appendChild(button);
883
+ }
884
+ }
885
+ // ─── Apple Pay native button ────────────────────
886
+ async mountApplePayButton(container) {
887
+ await loadApplePayScript();
888
+ const ApplePayAPI = window.ApplePaySession;
889
+ if (!ApplePayAPI) {
890
+ console.log('[PaypercutExpressCheckout] ApplePaySession not available');
891
+ return;
892
+ }
893
+ if (!ApplePayAPI.canMakePayments?.()) {
894
+ console.log('[PaypercutExpressCheckout] ApplePaySession.canMakePayments() returned false — hiding Apple Pay button');
895
+ return;
896
+ }
897
+ const locale = this.options.locale ? normalizeApplePayLocale(this.options.locale) : 'en';
898
+ const buttonOpts = this.options.buttonOptions;
899
+ const button = document.createElement('apple-pay-button');
900
+ button.setAttribute('buttonstyle', buttonOpts?.applePayStyle ?? 'black');
901
+ button.setAttribute('type', toApplePayButtonType(buttonOpts?.type ?? 'plain'));
902
+ button.setAttribute('locale', locale);
903
+ button.style.setProperty('--apple-pay-button-width', '100%');
904
+ button.style.setProperty('--apple-pay-button-height', '48px');
905
+ button.style.setProperty('--apple-pay-button-border-radius', buttonOpts?.borderRadius ?? '0.5rem');
906
+ button.style.display = 'block';
907
+ button.style.cursor = 'pointer';
908
+ button.addEventListener('click', () => this.startApplePay());
909
+ // <apple-pay-button> is a custom element registered by the Apple Pay JS SDK.
910
+ // In Safari, ApplePaySession is native so it may already pass the check above
911
+ // before the SDK script has finished registering the custom element.
912
+ // Wait for it to be defined before appending so it renders correctly.
913
+ const appendButton = () => {
914
+ this.applePayButtonEl = button;
915
+ container.appendChild(button);
916
+ const shadow = button.shadowRoot;
917
+ if (shadow) {
918
+ const style = document.createElement('style');
919
+ style.textContent = 'span svg { height: 75% !important; width: auto !important; }';
920
+ shadow.appendChild(style);
921
+ }
922
+ };
923
+ if (customElements?.get('apple-pay-button')) {
924
+ appendButton();
925
+ }
926
+ else {
927
+ customElements?.whenDefined('apple-pay-button').then(appendButton).catch(() => appendButton());
928
+ }
929
+ }
930
+ /**
931
+ * Starts a native Apple Pay session in the SDK window (merchant's registered domain).
932
+ * Called synchronously from the Apple Pay button click handler.
933
+ * Uses async/await which Safari preserves as part of the user gesture.
934
+ */
935
+ async startApplePay() {
936
+ if (this.sessionActive)
937
+ return;
938
+ if (typeof window === 'undefined')
939
+ return;
940
+ const ApplePayAPI = window.ApplePaySession;
941
+ if (!ApplePayAPI) {
942
+ console.error('[PaypercutExpressCheckout] ApplePaySession not available');
943
+ return;
944
+ }
945
+ this.idempotencyKey = generateId();
946
+ this.setSessionActive(true);
947
+ this.emitter.emit(exports.ExpressSdkEvent.Click);
948
+ // Emit SessionStart — merchant must call updateWith() within 3s
949
+ const sessionInitResult = await new Promise((resolve) => {
950
+ if (!this.emitter.hasListeners(exports.ExpressSdkEvent.SessionStart)) {
951
+ resolve(null);
952
+ return;
953
+ }
954
+ const timer = setTimeout(() => resolve(null), 3000);
955
+ this.emitter.emit(exports.ExpressSdkEvent.SessionStart, {
956
+ wallet: 'apple_pay',
957
+ updateWith: (opts) => {
958
+ clearTimeout(timer);
959
+ resolve(opts);
960
+ },
961
+ });
962
+ });
963
+ if (!sessionInitResult) {
964
+ console.error('[PaypercutExpressCheckout] Apple Pay: no session_start response — aborting');
965
+ this.setSessionActive(false);
966
+ this.emitter.emit(exports.ExpressSdkEvent.ShippingOptionsRequired, { wallet: 'apple_pay' });
967
+ return;
968
+ }
969
+ // Apply merchant-provided initial state
970
+ if (typeof sessionInitResult.amount === 'number') {
971
+ this.applePayCurrentAmount = sessionInitResult.amount;
972
+ }
973
+ else {
974
+ this.applePayCurrentAmount = this.options.amount;
975
+ }
976
+ if (Array.isArray(sessionInitResult.lineItems)) {
977
+ this.currentLineItems = sessionInitResult.lineItems;
978
+ }
979
+ else {
980
+ this.currentLineItems = this.options.lineItems ?? [];
981
+ }
982
+ if (Array.isArray(sessionInitResult.shippingOptions)) {
983
+ this.applePayCurrentShippingOptions = sessionInitResult.shippingOptions;
984
+ }
985
+ else {
986
+ this.applePayCurrentShippingOptions = this.currentShippingOptions;
987
+ }
988
+ this.applePayPendingShippingOption = null;
989
+ const displayName = this.expressConfig?.displayName || 'Checkout';
990
+ const totalPrice = (this.applePayCurrentAmount / 100).toFixed(2);
991
+ const appleLineItems = this.currentLineItems.map((li) => ({
992
+ label: li.label,
993
+ amount: (li.amount / 100).toFixed(2),
994
+ type: li.type ?? 'final',
995
+ }));
996
+ const request = {
997
+ countryCode: this.options.countryCode ?? 'DE',
998
+ currencyCode: this.options.currency,
999
+ merchantCapabilities: ['supports3DS', 'supportsCredit', 'supportsDebit'],
1000
+ supportedNetworks: ['visa', 'masterCard'],
1001
+ lineItems: appleLineItems,
1002
+ total: {
1003
+ label: displayName,
1004
+ amount: totalPrice,
1005
+ type: 'final',
1006
+ },
1007
+ requiredBillingContactFields: ['postalAddress', 'name', 'email'],
1008
+ };
1009
+ // Shipping is always required for Express Checkout
1010
+ request.requiredShippingContactFields = ['postalAddress', 'name', 'email'];
1011
+ if (this.applePayCurrentShippingOptions.length) {
1012
+ request.shippingMethods = this.applePayCurrentShippingOptions.map((so) => ({
1013
+ label: so.label,
1014
+ detail: so.detail ?? '',
1015
+ amount: (so.amount / 100).toFixed(2),
1016
+ identifier: so.id,
1017
+ }));
1018
+ }
1019
+ request.shippingType = 'shipping';
1020
+ this.abortApplePaySession();
1021
+ const version = ApplePayAPI.supportsVersion?.(14) ? 14 : 3;
1022
+ try {
1023
+ const session = new ApplePayAPI(version, request);
1024
+ this.applePaySession = session;
1025
+ session.onvalidatemerchant = async (event) => {
1026
+ const vaultApiUrl = this.expressConfig?.vaultApiUrl ?? getVaultApiUrl();
1027
+ const publicKey = this.expressConfig?.publicKey ?? '';
1028
+ try {
1029
+ const headers = {
1030
+ 'Content-Type': 'application/json',
1031
+ 'BT-API-KEY': publicKey,
1032
+ };
1033
+ if (this.idempotencyKey)
1034
+ headers['Idempotency-Key'] = this.idempotencyKey;
1035
+ const res = await fetch(`${vaultApiUrl}/apple-pay/session`, {
1036
+ method: 'POST',
1037
+ headers,
1038
+ body: JSON.stringify({
1039
+ display_name: displayName,
1040
+ domain: window.location.host,
1041
+ validation_url: event.validationURL,
1042
+ }),
1043
+ });
1044
+ if (!res.ok) {
1045
+ const err = await res.json().catch(() => ({}));
1046
+ throw new Error(err?.message ?? `Merchant validation failed: HTTP ${res.status}`);
1047
+ }
1048
+ const merchantSession = await res.json();
1049
+ session.completeMerchantValidation(merchantSession);
1050
+ }
1051
+ catch (err) {
1052
+ console.error('[PaypercutExpressCheckout] Apple Pay merchant validation failed');
1053
+ this.abortApplePaySession();
1054
+ this.emitter.emit(exports.ExpressSdkEvent.Error, new Error(err?.message ?? 'Apple Pay merchant validation failed'));
1055
+ this.emitter.emit(exports.ExpressSdkEvent.Cancel);
1056
+ }
1057
+ };
1058
+ // Shipping address changed — emit to merchant, wait for updateWith(), complete session
1059
+ session.onshippingcontactselected = async (event) => {
1060
+ const contact = event.shippingContact;
1061
+ const update = await new Promise((resolve) => {
1062
+ this.applePayPendingCallback = { type: 'contact', resolve };
1063
+ this.emitter.emit(exports.ExpressSdkEvent.ShippingAddressChange, {
1064
+ address: {
1065
+ country: contact.countryCode ?? '',
1066
+ state: contact.administrativeArea,
1067
+ city: contact.locality,
1068
+ postalCode: contact.postalCode,
1069
+ },
1070
+ updateWith: (opts) => this.update(opts),
1071
+ });
1072
+ // 30s safety timeout — return unchanged data so the sheet doesn't freeze
1073
+ setTimeout(() => resolve({}), 30000);
1074
+ });
1075
+ this.applePayPendingCallback = null;
1076
+ if (typeof update.amount === 'number')
1077
+ this.applePayCurrentAmount = update.amount;
1078
+ if (Array.isArray(update.lineItems))
1079
+ this.currentLineItems = update.lineItems;
1080
+ if (Array.isArray(update.shippingOptions))
1081
+ this.applePayCurrentShippingOptions = update.shippingOptions;
1082
+ const status = update.status === 'invalid_shipping_address'
1083
+ ? ApplePayAPI.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS
1084
+ : ApplePayAPI.STATUS_SUCCESS;
1085
+ try {
1086
+ session.completeShippingContactSelection(status, this.applePayCurrentShippingOptions.map((so) => ({
1087
+ label: so.label,
1088
+ detail: so.detail ?? '',
1089
+ amount: (so.amount / 100).toFixed(2),
1090
+ identifier: so.id,
1091
+ })), {
1092
+ label: displayName,
1093
+ amount: (this.applePayCurrentAmount / 100).toFixed(2),
1094
+ type: 'final',
1095
+ }, this.currentLineItems.map((li) => ({
1096
+ label: li.label,
1097
+ amount: (li.amount / 100).toFixed(2),
1098
+ type: li.type ?? 'final',
1099
+ })));
1100
+ }
1101
+ catch (e) {
1102
+ console.error('[PaypercutExpressCheckout] completeShippingContactSelection failed', e);
1103
+ }
1104
+ };
1105
+ // Shipping method changed — emit to merchant, wait for updateWith(), complete session
1106
+ session.onshippingmethodselected = async (event) => {
1107
+ const method = event.shippingMethod;
1108
+ const selectedOption = {
1109
+ id: method.identifier,
1110
+ label: method.label,
1111
+ detail: method.detail,
1112
+ amount: Math.round(parseFloat(method.amount) * 100),
1113
+ };
1114
+ this.applePayPendingShippingOption = selectedOption;
1115
+ const update = await new Promise((resolve) => {
1116
+ this.applePayPendingCallback = { type: 'method', resolve };
1117
+ this.emitter.emit(exports.ExpressSdkEvent.ShippingOptionChange, {
1118
+ shippingOption: selectedOption,
1119
+ updateWith: (opts) => this.update(opts),
1120
+ });
1121
+ setTimeout(() => resolve({}), 30000);
1122
+ });
1123
+ this.applePayPendingCallback = null;
1124
+ if (typeof update.amount === 'number')
1125
+ this.applePayCurrentAmount = update.amount;
1126
+ if (Array.isArray(update.lineItems))
1127
+ this.currentLineItems = update.lineItems;
1128
+ try {
1129
+ session.completeShippingMethodSelection(ApplePayAPI.STATUS_SUCCESS, {
1130
+ label: displayName,
1131
+ amount: (this.applePayCurrentAmount / 100).toFixed(2),
1132
+ type: 'final',
1133
+ }, this.currentLineItems.map((li) => ({
1134
+ label: li.label,
1135
+ amount: (li.amount / 100).toFixed(2),
1136
+ type: li.type ?? 'final',
1137
+ })));
1138
+ }
1139
+ catch (e) {
1140
+ console.error('[PaypercutExpressCheckout] completeShippingMethodSelection failed', e);
1141
+ }
1142
+ };
1143
+ // Payment authorized — send raw token to tokenize iframe for BT tokenization
1144
+ // + createExpressPaymentMethod. completePayment is called from TOKENIZE_RESPONSE handler.
1145
+ session.onpaymentauthorized = (event) => {
1146
+ const billingContact = event.payment?.billingContact;
1147
+ const shippingContact = event.payment?.shippingContact;
1148
+ this.applePayPendingBillingDetails = billingContact
1149
+ ? {
1150
+ name: [billingContact.givenName, billingContact.familyName].filter(Boolean).join(' ') || undefined,
1151
+ email: billingContact.emailAddress,
1152
+ address: {
1153
+ line1: billingContact.addressLines?.[0],
1154
+ line2: billingContact.addressLines?.[1],
1155
+ city: billingContact.locality,
1156
+ state: billingContact.administrativeArea,
1157
+ postalCode: billingContact.postalCode,
1158
+ country: billingContact.countryCode,
1159
+ },
1160
+ }
1161
+ : null;
1162
+ this.applePayPendingShippingDetails = shippingContact
1163
+ ? {
1164
+ name: [shippingContact.givenName, shippingContact.familyName].filter(Boolean).join(' ') || undefined,
1165
+ address: {
1166
+ line1: shippingContact.addressLines?.[0],
1167
+ line2: shippingContact.addressLines?.[1],
1168
+ city: shippingContact.locality,
1169
+ state: shippingContact.administrativeArea,
1170
+ postalCode: shippingContact.postalCode,
1171
+ country: shippingContact.countryCode,
1172
+ },
1173
+ }
1174
+ : null;
1175
+ this.postToTokenizeIframe({
1176
+ type: 'TOKENIZE_REQUEST',
1177
+ instanceId: this.instanceId,
1178
+ wallet: 'apple_pay',
1179
+ applePaymentData: event.payment.token,
1180
+ idemKey: this.idempotencyKey,
1181
+ publishableKey: this.options.publishableKey,
1182
+ billingDetails: this.applePayPendingBillingDetails,
1183
+ amount: this.applePayCurrentAmount,
1184
+ currency: this.options.currency,
1185
+ merchantInfo: {
1186
+ name: this.expressConfig?.displayName ?? '',
1187
+ mid: this.expressConfig?.merchantMid ?? '',
1188
+ mcc: this.expressConfig?.merchantMcc ?? '',
1189
+ country: this.expressConfig?.merchantCountry ?? '',
1190
+ url: this.expressConfig?.merchantUrl ?? '',
1191
+ },
1192
+ });
1193
+ };
1194
+ session.oncancel = () => {
1195
+ this.applePaySession = null;
1196
+ this.applePayPendingCallback = null;
1197
+ this.applePayPendingShippingOption = null;
1198
+ this.emitter.emit(exports.ExpressSdkEvent.Cancel);
1199
+ };
1200
+ session.begin();
1201
+ }
1202
+ catch (e) {
1203
+ this.applePaySession = null;
1204
+ console.error('[PaypercutExpressCheckout] Failed to create ApplePaySession', {
1205
+ name: e?.name,
1206
+ message: e?.message,
1207
+ hint: e?.name === 'SecurityError'
1208
+ ? 'Page is not HTTPS or merchant domain is not registered for Apple Pay'
1209
+ : 'Check isSecureContext and that ApplePaySession.canMakePayments() returns true',
1210
+ });
1211
+ }
1212
+ }
1213
+ // ─── Google Pay native button ───────────────────
1214
+ /**
1215
+ * Called after config is fetched. Waits for the GPay script to finish loading,
1216
+ * then mounts the button.
1217
+ */
1218
+ removeGpayContainer() {
1219
+ this.gpayContainer?.remove();
1220
+ this.gpayContainer = null;
1221
+ }
1222
+ mountGooglePayFromConfig() {
1223
+ const config = this.expressConfig;
1224
+ if (!config)
1225
+ return;
1226
+ const liveMode = isLiveKey(this.options.publishableKey);
1227
+ const tenantId = config.tenantId;
1228
+ const googlePayMerchantId = config.googlePayMerchantId;
1229
+ const merchantName = config.displayName || 'Checkout';
1230
+ if (!tenantId) {
1231
+ console.error('[PaypercutExpressCheckout] tenantId is empty — Google Pay cannot be mounted without a valid gatewayMerchantId.');
1232
+ this.removeGpayContainer();
1233
+ return;
1234
+ }
1235
+ if (!googlePayMerchantId) {
1236
+ console.warn('[PaypercutExpressCheckout] googlePayMerchantId is empty — Google Pay will not be mounted (merchant may not have Google Pay active).');
1237
+ this.removeGpayContainer();
1238
+ return;
1239
+ }
1240
+ console.log({ liveMode });
1241
+ if (liveMode && (!config.merchantMcc || !config.merchantUrl)) {
1242
+ console.warn('[PaypercutExpressCheckout] Google Pay disabled!');
1243
+ this.removeGpayContainer();
1244
+ return;
1245
+ }
1246
+ loadGooglePayScript().then(() => {
1247
+ this.mountGooglePayButton(tenantId, googlePayMerchantId, merchantName, liveMode);
1248
+ }).catch((err) => {
1249
+ console.error('[PaypercutExpressCheckout] Failed to load Google Pay script:', err);
1250
+ });
1251
+ }
1252
+ mountGooglePayButton(tenantId, merchantId, merchantName, liveMode) {
1253
+ if (!this.gpayContainer) {
1254
+ console.error('[PaypercutExpressCheckout] gpayContainer is null');
1255
+ return;
1256
+ }
1257
+ const google = globalThis.google;
1258
+ if (!google?.payments?.api?.PaymentsClient) {
1259
+ console.error('[PaypercutExpressCheckout] google.payments.api.PaymentsClient not available');
1260
+ return;
1261
+ }
1262
+ const environment = liveMode ? 'PRODUCTION' : 'TEST';
1263
+ const countryCode = this.options.countryCode;
1264
+ if (!countryCode) {
1265
+ console.warn('[PaypercutExpressCheckout] countryCode is not set. This is required for Google Pay in production. Pass it via options.countryCode (e.g. "DE").');
1266
+ }
1267
+ const paymentRequest = {
1268
+ apiVersion: 2,
1269
+ apiVersionMinor: 0,
1270
+ allowedPaymentMethods: [
1271
+ {
1272
+ type: 'CARD',
1273
+ parameters: {
1274
+ allowedAuthMethods: ['CRYPTOGRAM_3DS', 'PAN_ONLY'],
1275
+ allowedCardNetworks: ['MASTERCARD', 'VISA'],
1276
+ billingAddressRequired: true,
1277
+ billingAddressParameters: {
1278
+ format: 'FULL',
1279
+ phoneNumberRequired: false,
1280
+ },
1281
+ },
1282
+ tokenizationSpecification: {
1283
+ type: 'PAYMENT_GATEWAY',
1284
+ parameters: {
1285
+ gateway: 'basistheory',
1286
+ gatewayMerchantId: tenantId,
1287
+ },
1288
+ },
1289
+ },
1290
+ ],
1291
+ merchantInfo: {
1292
+ merchantId,
1293
+ merchantName,
1294
+ },
1295
+ transactionInfo: {
1296
+ totalPriceStatus: 'FINAL',
1297
+ totalPriceLabel: 'Total',
1298
+ totalPrice: (this.options.amount / 100).toFixed(2),
1299
+ currencyCode: this.options.currency,
1300
+ countryCode,
1301
+ },
1302
+ callbackIntents: ['PAYMENT_AUTHORIZATION', 'SHIPPING_ADDRESS', 'SHIPPING_OPTION']
1303
+ ,
1304
+ };
1305
+ {
1306
+ paymentRequest.shippingAddressRequired = true;
1307
+ paymentRequest.shippingOptionRequired = true;
1308
+ if (this.options.allowedCountries?.length) {
1309
+ paymentRequest.shippingAddressParameters = {
1310
+ allowedCountryCodes: this.options.allowedCountries,
1311
+ phoneNumberRequired: false,
1312
+ };
1313
+ }
1314
+ if (this.options.shippingOptions?.length) {
1315
+ paymentRequest.shippingOptionParameters = {
1316
+ defaultSelectedOptionId: this.options.shippingOptions[0].id,
1317
+ shippingOptions: this.options.shippingOptions.map((so) => ({
1318
+ id: so.id,
1319
+ label: so.label,
1320
+ description: so.detail ?? `${(so.amount / 100).toFixed(2)} ${this.options.currency}`,
1321
+ })),
1322
+ };
1323
+ }
1324
+ }
1325
+ this.gpayPaymentRequest = paymentRequest;
1326
+ this.gpayClient = new google.payments.api.PaymentsClient({
1327
+ environment,
1328
+ paymentDataCallbacks: {
1329
+ onPaymentAuthorized: (paymentData) => this.handleGooglePayAuthorized(paymentData),
1330
+ ...({
1331
+ onPaymentDataChanged: (intermediatePaymentData) => this.handleGooglePayDataChanged(intermediatePaymentData),
1332
+ }),
1333
+ },
1334
+ });
1335
+ const buttonOpts = this.options.buttonOptions;
1336
+ const button = this.gpayClient.createButton({
1337
+ onClick: () => this.startGooglePay(paymentRequest),
1338
+ buttonSizeMode: 'fill',
1339
+ buttonType: buttonOpts?.type ?? 'plain',
1340
+ buttonColor: buttonOpts?.googlePayColor ?? 'default',
1341
+ ...(this.options.locale && { buttonLocale: normalizeGPayLocale(this.options.locale) }),
1342
+ });
1343
+ const borderRadius = buttonOpts?.borderRadius ?? '0.5rem';
1344
+ button.style.width = '100%';
1345
+ this.injectGpayInnerStyles(button, borderRadius);
1346
+ this.gpayContainer.appendChild(button);
1347
+ }
1348
+ injectGpayInnerStyles(buttonEl, borderRadius) {
1349
+ const style = document.createElement('style');
1350
+ style.textContent = `.gpay-button { height: 48px !important; border-radius: ${borderRadius} !important; background-size: auto 60% !important; } .gpay-card-info-container { border-radius: ${borderRadius} !important; } .gpay-card-info-container-fill, .gpay-card-info-container-fill > .gpay-card-info-container { height: 48px !important; }`;
1351
+ buttonEl.prepend(style);
1352
+ }
1353
+ async startGooglePay(paymentRequest) {
1354
+ if (!this.gpayClient)
1355
+ return;
1356
+ if (this.sessionActive)
1357
+ return;
1358
+ this.idempotencyKey = generateId();
1359
+ this.setSessionActive(true);
1360
+ this.emitter.emit(exports.ExpressSdkEvent.Click);
1361
+ // Ask merchant for initial shipping options before opening the sheet.
1362
+ // If no session_start handler is registered, skip straight through.
1363
+ if (this.emitter.hasListeners(exports.ExpressSdkEvent.SessionStart)) {
1364
+ const resolved = await new Promise((resolve) => {
1365
+ const timer = setTimeout(() => resolve(null), 3000);
1366
+ this.emitter.emit(exports.ExpressSdkEvent.SessionStart, {
1367
+ wallet: 'google_pay',
1368
+ updateWith: (opts) => {
1369
+ clearTimeout(timer);
1370
+ resolve(opts);
1371
+ },
1372
+ });
1373
+ });
1374
+ if (!resolved) {
1375
+ // Merchant didn't respond — do not open the sheet
1376
+ this.setSessionActive(false);
1377
+ this.emitter.emit(exports.ExpressSdkEvent.ShippingOptionsRequired, { wallet: 'google_pay' });
1378
+ return;
1379
+ }
1380
+ // Apply merchant's options before loadPaymentData
1381
+ if (resolved.shippingOptions) {
1382
+ this.currentShippingOptions = resolved.shippingOptions;
1383
+ paymentRequest.shippingOptionParameters = {
1384
+ defaultSelectedOptionId: resolved.shippingOptions[0]?.id,
1385
+ shippingOptions: resolved.shippingOptions.map((so) => ({
1386
+ id: so.id,
1387
+ label: so.label,
1388
+ description: so.detail ?? `${(so.amount / 100).toFixed(2)} ${this.options.currency}`,
1389
+ })),
1390
+ };
1391
+ }
1392
+ if (resolved.amount != null) {
1393
+ this.gpayCurrentAmount = resolved.amount;
1394
+ paymentRequest.transactionInfo = {
1395
+ ...paymentRequest.transactionInfo,
1396
+ totalPrice: (resolved.amount / 100).toFixed(2),
1397
+ };
1398
+ }
1399
+ }
1400
+ // Ensure gpayCurrentAmount is always set before the sheet opens
1401
+ if (!this.gpayCurrentAmount) {
1402
+ this.gpayCurrentAmount = this.options.amount;
1403
+ }
1404
+ try {
1405
+ await this.gpayClient.loadPaymentData(paymentRequest);
1406
+ // If 3DS was triggered, the GPay sheet is now fully dismissed — show the challenge modal.
1407
+ if (this.pending3DSAfterGpay) {
1408
+ const threeDSData = this.pending3DSAfterGpay;
1409
+ this.pending3DSAfterGpay = null;
1410
+ this.show3DSModal(threeDSData);
1411
+ }
1412
+ }
1413
+ catch (e) {
1414
+ if (e?.statusCode === 'CANCELED' || e?.message?.toLowerCase?.().includes('cancel')) {
1415
+ this.emitter.emit(exports.ExpressSdkEvent.Cancel);
1416
+ }
1417
+ else {
1418
+ this.emitter.emit(exports.ExpressSdkEvent.Error, new Error(e?.message ?? 'Google Pay failed'));
1419
+ }
1420
+ }
1421
+ finally {
1422
+ this.setSessionActive(false);
1423
+ }
1424
+ }
1425
+ async handleGooglePayAuthorized(paymentData) {
1426
+ try {
1427
+ const encryptedToken = paymentData.paymentMethodData.tokenizationData.token;
1428
+ const cardNetwork = paymentData.paymentMethodData?.info?.cardNetwork ?? '';
1429
+ const billingAddr = paymentData.paymentMethodData?.info?.billingAddress;
1430
+ const shippingAddr = paymentData.shippingAddress;
1431
+ const shippingOptionData = paymentData.shippingOptionData;
1432
+ const billingDetails = billingAddr ? {
1433
+ name: billingAddr.name,
1434
+ address: {
1435
+ line1: billingAddr.address1,
1436
+ city: billingAddr.locality,
1437
+ state: billingAddr.administrativeArea,
1438
+ postalCode: billingAddr.postalCode,
1439
+ country: billingAddr.countryCode,
1440
+ },
1441
+ } : null;
1442
+ const shippingDetails = shippingAddr ? {
1443
+ name: shippingAddr.name || undefined,
1444
+ address: {
1445
+ line1: shippingAddr.address1,
1446
+ city: shippingAddr.locality,
1447
+ state: shippingAddr.administrativeArea,
1448
+ postalCode: shippingAddr.postalCode,
1449
+ country: shippingAddr.countryCode,
1450
+ },
1451
+ } : undefined;
1452
+ const selectedShippingOption = shippingOptionData
1453
+ ? (this.currentShippingOptions.find((so) => so.id === shippingOptionData.id) ?? {
1454
+ id: shippingOptionData.id,
1455
+ label: shippingOptionData.label ?? shippingOptionData.id,
1456
+ amount: 0,
1457
+ })
1458
+ : undefined;
1459
+ // Store metadata upfront — needed if 3DS triggers and the sheet closes before TOKENIZE_RESPONSE
1460
+ this.pendingGpayBillingDetails = billingDetails;
1461
+ this.pendingGpayShippingDetails = shippingDetails;
1462
+ this.pendingGpayShippingOption = selectedShippingOption;
1463
+ // Send to hidden tokenize iframe — it will BT-tokenize + create the payment method
1464
+ const tokenResult = await new Promise((resolve, reject) => {
1465
+ const timeoutId = setTimeout(() => {
1466
+ this.pendingGpayResolve = null;
1467
+ this.pendingGpayReject = null;
1468
+ reject(new Error('Tokenization timed out'));
1469
+ }, 30000);
1470
+ this.pendingGpayResolve = (result) => { clearTimeout(timeoutId); resolve(result); };
1471
+ this.pendingGpayReject = (err) => { clearTimeout(timeoutId); reject(err); };
1472
+ this.postToTokenizeIframe({
1473
+ type: 'TOKENIZE_REQUEST',
1474
+ instanceId: this.instanceId,
1475
+ wallet: 'google_pay',
1476
+ encryptedToken,
1477
+ cardNetwork,
1478
+ idemKey: this.idempotencyKey,
1479
+ publishableKey: this.options.publishableKey,
1480
+ billingDetails,
1481
+ amount: this.options.amount,
1482
+ currency: this.options.currency,
1483
+ merchantInfo: {
1484
+ name: this.expressConfig?.displayName ?? '',
1485
+ mid: this.expressConfig?.merchantMid ?? '',
1486
+ mcc: this.expressConfig?.merchantMcc ?? '',
1487
+ country: this.expressConfig?.merchantCountry ?? '',
1488
+ url: this.expressConfig?.merchantUrl ?? '',
1489
+ },
1490
+ });
1491
+ });
1492
+ // 3DS was triggered — sheet already closed, payment method creation handled in message handler
1493
+ if (tokenResult.__closeSheet) {
1494
+ return { transactionState: 'SUCCESS' };
1495
+ }
1496
+ if (!tokenResult.success) {
1497
+ const errMsg = tokenResult.error ?? 'Tokenization failed';
1498
+ this.emitter.emit(exports.ExpressSdkEvent.Error, new Error(errMsg));
1499
+ this.emitter.emit(exports.ExpressSdkEvent.PaymentMethodFailed, { error: errMsg });
1500
+ return { transactionState: 'ERROR' };
1501
+ }
1502
+ const paymentMethodId = await this.createPaymentMethod({
1503
+ btTokenId: tokenResult.btTokenId,
1504
+ cardPayload: tokenResult.cardPayload,
1505
+ billingDetails: tokenResult.billingDetails,
1506
+ csessId: tokenResult.csessId,
1507
+ walletType: 'google_pay',
1508
+ });
1509
+ this.emitter.emit(exports.ExpressSdkEvent.PaymentMethodCreated, {
1510
+ paymentMethodId,
1511
+ wallet: 'google_pay',
1512
+ billingDetails: billingDetails ?? undefined,
1513
+ shippingDetails,
1514
+ selectedShippingOption,
1515
+ });
1516
+ this.pendingGpayBillingDetails = null;
1517
+ this.pendingGpayShippingDetails = null;
1518
+ this.pendingGpayShippingOption = undefined;
1519
+ return { transactionState: 'SUCCESS' };
1520
+ }
1521
+ catch (err) {
1522
+ console.error('[PaypercutExpressCheckout] handleGooglePayAuthorized error:', err?.message ?? err);
1523
+ this.emitter.emit(exports.ExpressSdkEvent.Error, new Error(err?.message ?? 'Google Pay authorization failed'));
1524
+ this.emitter.emit(exports.ExpressSdkEvent.PaymentMethodFailed, { error: err?.message ?? 'Google Pay authorization failed' });
1525
+ return { transactionState: 'ERROR' };
1526
+ }
1527
+ }
1528
+ /**
1529
+ * Google Pay `onPaymentDataChanged` callback.
1530
+ * Called when the user changes their shipping address or shipping option.
1531
+ */
1532
+ async handleGooglePayDataChanged(intermediatePaymentData) {
1533
+ const { callbackTrigger, shippingAddress, shippingOptionData } = intermediatePaymentData;
1534
+ if (callbackTrigger === 'INITIALIZE') {
1535
+ return buildGpayPaymentDataUpdate({
1536
+ amount: this.gpayCurrentAmount || this.options.amount,
1537
+ shippingOptions: this.currentShippingOptions,
1538
+ }, this.options.currency, this.options.countryCode);
1539
+ }
1540
+ if (callbackTrigger === 'SHIPPING_ADDRESS') {
1541
+ const update = await new Promise((resolve) => {
1542
+ this.emitter.emit(exports.ExpressSdkEvent.ShippingAddressChange, {
1543
+ address: {
1544
+ country: shippingAddress?.countryCode ?? '',
1545
+ state: shippingAddress?.administrativeArea,
1546
+ city: shippingAddress?.locality,
1547
+ postalCode: shippingAddress?.postalCode,
1548
+ },
1549
+ updateWith: (opts) => {
1550
+ if (opts.shippingOptions)
1551
+ this.currentShippingOptions = opts.shippingOptions;
1552
+ if (opts.amount != null)
1553
+ this.gpayCurrentAmount = opts.amount;
1554
+ resolve(opts);
1555
+ },
1556
+ });
1557
+ });
1558
+ return buildGpayPaymentDataUpdate(update, this.options.currency, this.options.countryCode);
1559
+ }
1560
+ if (callbackTrigger === 'SHIPPING_OPTION') {
1561
+ const selectedId = shippingOptionData?.id;
1562
+ const selected = this.currentShippingOptions.find((so) => so.id === selectedId);
1563
+ const update = await new Promise((resolve) => {
1564
+ this.emitter.emit(exports.ExpressSdkEvent.ShippingOptionChange, {
1565
+ shippingOption: {
1566
+ id: selectedId ?? '',
1567
+ label: selected?.label ?? selectedId ?? '',
1568
+ detail: selected?.detail,
1569
+ amount: selected?.amount ?? 0,
1570
+ },
1571
+ updateWith: (opts) => {
1572
+ if (opts.amount != null)
1573
+ this.gpayCurrentAmount = opts.amount;
1574
+ resolve(opts);
1575
+ },
1576
+ });
1577
+ });
1578
+ return buildGpayPaymentDataUpdate(update, this.options.currency, this.options.countryCode);
1579
+ }
1580
+ return {};
1581
+ }
1582
+ update(options) {
1583
+ if (!this.mounted) {
1584
+ console.warn('[PaypercutExpressCheckout] Cannot update: not mounted');
1585
+ return;
1586
+ }
1587
+ // If an Apple Pay shipping callback is waiting, resolve it directly
1588
+ if (this.applePayPendingCallback) {
1589
+ this.applePayPendingCallback.resolve(options);
1590
+ return;
1591
+ }
1592
+ }
1593
+ on(event, handler) {
1594
+ return this.emitter.on(event, handler);
1595
+ }
1596
+ destroy() {
1597
+ if (this.destroyed)
1598
+ return;
1599
+ if (this.tokenizeIframe) {
1600
+ try {
1601
+ this.tokenizeIframe.remove();
1602
+ }
1603
+ catch { }
1604
+ this.tokenizeIframe = null;
1605
+ }
1606
+ if (this.gpayContainer) {
1607
+ try {
1608
+ this.gpayContainer.remove();
1609
+ }
1610
+ catch { }
1611
+ this.gpayContainer = null;
1612
+ }
1613
+ this.applePayButtonEl = null;
1614
+ this.gpayPaymentRequest = null;
1615
+ if (this.layoutResizeObserver) {
1616
+ this.layoutResizeObserver.disconnect();
1617
+ this.layoutResizeObserver = null;
1618
+ }
1619
+ this.close3DSModal();
1620
+ this.abortApplePaySession();
1621
+ this.sessionActive = false;
1622
+ this.mounted = false;
1623
+ this.destroyed = true;
1624
+ window.removeEventListener('message', this.messageHandler);
1625
+ this.emitter.clear();
1626
+ }
1627
+ // Private helpers
1628
+ setSessionActive(active) {
1629
+ this.sessionActive = active;
1630
+ const opacity = active ? '0.5' : '';
1631
+ const pointerEvents = active ? 'none' : '';
1632
+ if (this.applePayContainer) {
1633
+ this.applePayContainer.style.opacity = opacity;
1634
+ this.applePayContainer.style.pointerEvents = pointerEvents;
1635
+ }
1636
+ if (this.gpayContainer) {
1637
+ this.gpayContainer.style.opacity = opacity;
1638
+ this.gpayContainer.style.pointerEvents = pointerEvents;
1639
+ }
1640
+ }
1641
+ completeApplePaySession(success) {
1642
+ try {
1643
+ if (this.applePaySession) {
1644
+ const ApplePayAPI = window.ApplePaySession;
1645
+ const status = success ? ApplePayAPI.STATUS_SUCCESS : ApplePayAPI.STATUS_FAILURE;
1646
+ this.applePaySession.completePayment(status);
1647
+ }
1648
+ }
1649
+ catch { }
1650
+ this.applePaySession = null;
1651
+ this.applePayPendingCallback = null;
1652
+ this.applePayPendingShippingOption = null;
1653
+ this.applePayPendingBillingDetails = null;
1654
+ this.applePayPendingShippingDetails = null;
1655
+ this.setSessionActive(false);
1656
+ }
1657
+ abortApplePaySession() {
1658
+ try {
1659
+ this.applePaySession?.abort();
1660
+ }
1661
+ catch { }
1662
+ this.applePaySession = null;
1663
+ this.applePayPendingCallback = null;
1664
+ this.applePayPendingShippingOption = null;
1665
+ this.applePayPendingBillingDetails = null;
1666
+ this.applePayPendingShippingDetails = null;
1667
+ this.setSessionActive(false);
1668
+ }
1669
+ async createPaymentMethod(params) {
1670
+ const { btTokenId, cardPayload, billingDetails, csessId, walletType } = params;
1671
+ if (!cardPayload || !btTokenId) {
1672
+ throw new Error(`[createPaymentMethod] Missing required tokenization data.`);
1673
+ }
1674
+ const url = new URL('/v1/payment_methods', getApiOrigin(this.options.apiUrl));
1675
+ const body = {
1676
+ type: 'card',
1677
+ key: this.options.publishableKey,
1678
+ card: {
1679
+ token: csessId ?? '',
1680
+ brand: cardPayload.brand ?? '',
1681
+ exp_month: cardPayload.exp_month ?? 1,
1682
+ exp_year: cardPayload.exp_year ?? 1,
1683
+ funding: cardPayload.funding ?? '',
1684
+ last4: cardPayload.last4 ?? '',
1685
+ iin: cardPayload.bin ?? '',
1686
+ issuer: cardPayload.issuer ?? null,
1687
+ fingerprint: cardPayload.fingerprint ?? null,
1688
+ segment: cardPayload.segment ?? '',
1689
+ wallet: { type: walletType, dynamic_last4: null },
1690
+ three_d_secure_usage: { supported: true },
1691
+ },
1692
+ billing_details: {
1693
+ name: billingDetails?.name ?? null,
1694
+ email: billingDetails?.email ?? null,
1695
+ phone: billingDetails?.phone ?? null,
1696
+ address: {
1697
+ city: billingDetails?.address?.city ?? null,
1698
+ country: billingDetails?.address?.country ?? null,
1699
+ line1: billingDetails?.address?.line1 ?? null,
1700
+ line2: billingDetails?.address?.line2 ?? null,
1701
+ postal_code: billingDetails?.address?.postalCode ?? null,
1702
+ state: billingDetails?.address?.state ?? null,
1703
+ },
1704
+ },
1705
+ confirmation_token: { token_id: btTokenId },
1706
+ };
1707
+ const res = await fetch(url.toString(), {
1708
+ method: 'POST',
1709
+ headers: { 'Content-Type': 'application/json' },
1710
+ body: JSON.stringify(body),
1711
+ cache: 'no-store',
1712
+ });
1713
+ if (!res.ok) {
1714
+ const msg = await res.text().catch(() => `HTTP ${res.status}`);
1715
+ throw new Error(`Payment method creation failed (${res.status}): ${msg}`);
1716
+ }
1717
+ const pm = await res.json();
1718
+ return pm.id;
1719
+ }
1720
+ postToTokenizeIframe(message) {
1721
+ if (!this.tokenizeIframe?.contentWindow) {
1722
+ return;
1723
+ }
1724
+ const origin = getCheckoutOrigin(this.options.hostedCheckoutUrl);
1725
+ this.tokenizeIframe.contentWindow.postMessage(message, origin);
1726
+ }
1727
+ // ─── 3DS modal (mirrors CheckoutImpl) ──────────
1728
+ show3DSModal(data) {
1729
+ this.threeDSModal = document.createElement('div');
1730
+ this.threeDSModal.id = 'paypercut-express-3ds-modal';
1731
+ Object.assign(this.threeDSModal.style, {
1732
+ position: 'fixed',
1733
+ top: '0',
1734
+ left: '0',
1735
+ width: '100%',
1736
+ height: '100%',
1737
+ display: 'flex',
1738
+ alignItems: 'center',
1739
+ justifyContent: 'center',
1740
+ zIndex: '999999',
1741
+ background: 'rgba(0, 0, 0, 0.4)',
1742
+ });
1743
+ this.threeDSIframe = document.createElement('iframe');
1744
+ const checkoutOrigin = getCheckoutOrigin(this.options.hostedCheckoutUrl);
1745
+ const threeDSUrl = new URL('/express/threeds', checkoutOrigin);
1746
+ threeDSUrl.searchParams.set('instanceId', this.instanceId);
1747
+ threeDSUrl.searchParams.set('sessionId', data.sessionId);
1748
+ threeDSUrl.searchParams.set('step', data.step);
1749
+ if (data.challengeUrl)
1750
+ threeDSUrl.searchParams.set('challengeUrl', data.challengeUrl);
1751
+ if (data.acsTransactionId)
1752
+ threeDSUrl.searchParams.set('acsTransactionId', data.acsTransactionId);
1753
+ if (data.threeDSVersion)
1754
+ threeDSUrl.searchParams.set('threeDSVersion', data.threeDSVersion);
1755
+ threeDSUrl.searchParams.set('liveMode', String(data.liveMode ?? false));
1756
+ this.threeDSIframe.src = threeDSUrl.toString();
1757
+ this.threeDSIframe.allow = 'payment *';
1758
+ this.threeDSIframe.setAttribute('frameborder', '0');
1759
+ Object.assign(this.threeDSIframe.style, {
1760
+ minWidth: '400px',
1761
+ minHeight: '400px',
1762
+ border: 'none',
1763
+ borderRadius: '8px',
1764
+ display: 'block',
1765
+ background: 'transparent',
1766
+ });
1767
+ this.threeDSModal.appendChild(this.threeDSIframe);
1768
+ document.body.appendChild(this.threeDSModal);
1769
+ this._pending3DSData = data;
1770
+ }
1771
+ handle3DSReady() {
1772
+ const data = this._pending3DSData;
1773
+ if (!data || !this.threeDSIframe?.contentWindow) {
1774
+ console.error('[PaypercutExpressCheckout] No pending 3DS data or iframe not ready');
1775
+ return;
1776
+ }
1777
+ const origin = getCheckoutOrigin(this.options.hostedCheckoutUrl);
1778
+ this.threeDSIframe.contentWindow.postMessage({ type: 'THREEDS_INIT', instanceId: this.instanceId }, origin);
1779
+ }
1780
+ close3DSModal() {
1781
+ if (this.threeDSModal) {
1782
+ this.threeDSModal.remove();
1783
+ this.threeDSModal = null;
1784
+ }
1785
+ this.threeDSIframe = null;
1786
+ delete this._pending3DSData;
1787
+ }
1788
+ }
1789
+ //Factory
1790
+ const PaypercutExpressCheckout = function (options) {
1791
+ return new ExpressCheckoutImpl(options);
1792
+ };
1793
+
285
1794
  /**
286
1795
  * Internal implementation of CheckoutInstance
287
1796
  */
@@ -694,5 +2203,6 @@ PaypercutCheckout.version = config.version;
694
2203
 
695
2204
  exports.LOCALES = LOCALES;
696
2205
  exports.PaypercutCheckout = PaypercutCheckout;
2206
+ exports.PaypercutExpressCheckout = PaypercutExpressCheckout;
697
2207
  exports.default = PaypercutCheckout;
698
2208
  //# sourceMappingURL=index.cjs.map