@paypercut/checkout-js 1.0.21 → 1.1.0

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