@funnelfox/billing 0.8.0-beta.4 → 0.8.0-ffb-395.5

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.
@@ -489,7 +489,7 @@ var PaymentMethod;
489
489
  /**
490
490
  * @fileoverview Constants for Funnefox SDK
491
491
  */
492
- const SDK_VERSION = '0.8.0-beta.4';
492
+ const SDK_VERSION = '0.9.0-beta.1';
493
493
  const DEFAULTS = {
494
494
  BASE_URL: 'https://billing.funnelfox.com',
495
495
  REGION: 'default',
@@ -1126,7 +1126,7 @@ class APIClient {
1126
1126
  async createClientSession(params) {
1127
1127
  const payload = {
1128
1128
  region: params.region || 'default',
1129
- integration_type: 'primer',
1129
+ integration_type: params.integration ?? 'primer',
1130
1130
  pp_ident: params.priceId,
1131
1131
  external_id: params.externalId,
1132
1132
  email_address: params.email,
@@ -1262,6 +1262,45 @@ class APIClient {
1262
1262
  }
1263
1263
  }
1264
1264
 
1265
+ class SessionService {
1266
+ constructor() {
1267
+ this.cache = new Map();
1268
+ }
1269
+ buildCacheKey(p) {
1270
+ return [p.orgId, p.priceId, p.externalId, p.email, p.integration].join('-');
1271
+ }
1272
+ makeClient(orgId, baseUrl) {
1273
+ return new APIClient({
1274
+ baseUrl: baseUrl || DEFAULTS.BASE_URL,
1275
+ orgId,
1276
+ timeout: DEFAULTS.REQUEST_TIMEOUT,
1277
+ retryAttempts: DEFAULTS.RETRY_ATTEMPTS,
1278
+ });
1279
+ }
1280
+ createSession(p) {
1281
+ const key = this.buildCacheKey(p);
1282
+ const cached = this.cache.get(key);
1283
+ if (cached)
1284
+ return cached;
1285
+ const client = this.makeClient(p.orgId, p.baseUrl);
1286
+ const req = client.createClientSession({
1287
+ priceId: p.priceId,
1288
+ externalId: p.externalId,
1289
+ email: p.email,
1290
+ region: p.region || DEFAULTS.REGION,
1291
+ clientMetadata: p.clientMetadata,
1292
+ countryCode: p.countryCode,
1293
+ integration: p.integration,
1294
+ });
1295
+ this.cache.set(key, req);
1296
+ return req;
1297
+ }
1298
+ clearCache() {
1299
+ this.cache.clear();
1300
+ }
1301
+ }
1302
+ var sessionService = new SessionService();
1303
+
1265
1304
  var loaderHtml = "<div class=\"ff-sdk-loader-container\">\n <div class=\"ff-sdk-loader\"></div>\n</div>\n";
1266
1305
 
1267
1306
  if(typeof document!=="undefined")document.head.appendChild(document.createElement("style")).textContent=".ff-sdk-loader-container {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: rgba(255, 255, 255);\n z-index: 2;\n}\n\n.ff-sdk-loader {\n width: 24px;\n height: 24px;\n border: 4px solid #e32f41;\n border-top: 4px solid transparent;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n}\n\n@keyframes spin {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n }";
@@ -1856,6 +1895,12 @@ class CheckoutInstance extends EventEmitter {
1856
1895
  this.cardEmailAddress = this.checkoutConfig.customer.email;
1857
1896
  this.shouldApplySessionCardholderNameConfig =
1858
1897
  this.checkoutConfig.card?.cardholderName?.required === undefined;
1898
+ this.apiClient = new APIClient({
1899
+ baseUrl: this.baseUrl || DEFAULTS.BASE_URL,
1900
+ orgId: this.orgId,
1901
+ timeout: DEFAULTS.REQUEST_TIMEOUT,
1902
+ retryAttempts: DEFAULTS.RETRY_ATTEMPTS,
1903
+ });
1859
1904
  this._setupCallbackBridges();
1860
1905
  }
1861
1906
  _setupCallbackBridges() {
@@ -1897,64 +1942,35 @@ class CheckoutInstance extends EventEmitter {
1897
1942
  }
1898
1943
  }
1899
1944
  async createSession() {
1900
- this.apiClient = new APIClient({
1901
- baseUrl: this.baseUrl || DEFAULTS.BASE_URL,
1945
+ const response = await sessionService.createSession({
1902
1946
  orgId: this.orgId,
1903
- timeout: DEFAULTS.REQUEST_TIMEOUT,
1904
- retryAttempts: DEFAULTS.RETRY_ATTEMPTS,
1905
- });
1906
- const sessionParams = {
1947
+ baseUrl: this.baseUrl,
1907
1948
  priceId: this.checkoutConfig.priceId,
1908
1949
  externalId: this.checkoutConfig.customer.externalId,
1909
1950
  email: this.checkoutConfig.customer.email,
1910
- region: this.region || DEFAULTS.REGION,
1951
+ region: this.region,
1911
1952
  clientMetadata: this.checkoutConfig.clientMetadata,
1912
1953
  countryCode: this.checkoutConfig.customer.countryCode,
1913
- };
1914
- const cacheKey = [
1915
- this.orgId,
1916
- this.checkoutConfig.priceId,
1917
- this.checkoutConfig.customer.externalId,
1918
- this.checkoutConfig.customer.email,
1919
- ].join('-');
1920
- let sessionResponse;
1921
- // Return cached response if payload hasn't changed
1922
- const cachedResponse = CheckoutInstance.sessionCache.get(cacheKey);
1923
- if (cachedResponse) {
1924
- sessionResponse = await cachedResponse;
1925
- }
1926
- else {
1927
- const sessionRequest = this.apiClient
1928
- .createClientSession(sessionParams)
1929
- .then((response) => {
1930
- const cachedResponse = response;
1931
- if (response.data?.stripe_public_key) {
1932
- const stripePublicKey = response.data.stripe_public_key;
1933
- cachedResponse.radarSessionId = loadStripe(stripePublicKey)
1934
- .then(stripe => stripe
1935
- ? stripe
1936
- .createRadarSession()
1937
- .then(session => session?.radarSession?.id || '')
1938
- .catch(() => '')
1939
- : '')
1940
- .catch(() => '');
1941
- }
1942
- // Initialize Airwallex device fingerprinting if enabled by backend
1943
- if (response.data?.airwallex_risk_enabled) {
1944
- const isLivemode = response.data?.is_livemode;
1945
- const deviceId = generateUUID();
1946
- cachedResponse.airwallexDeviceId = loadAirwallexDeviceFingerprint(deviceId, isLivemode)
1947
- .then(() => deviceId)
1948
- .catch(() => {
1949
- // Silently fail - return deviceId anyway
1950
- return deviceId;
1951
- });
1952
- }
1953
- return cachedResponse;
1954
- });
1955
- // Cache the successful response
1956
- CheckoutInstance.sessionCache.set(cacheKey, sessionRequest);
1957
- sessionResponse = await sessionRequest;
1954
+ integration: 'primer',
1955
+ });
1956
+ const sessionResponse = response;
1957
+ if (response.data?.stripe_public_key) {
1958
+ const stripePublicKey = response.data.stripe_public_key;
1959
+ sessionResponse.radarSessionId = loadStripe(stripePublicKey)
1960
+ .then(stripe => stripe
1961
+ ? stripe
1962
+ .createRadarSession()
1963
+ .then(session => session?.radarSession?.id || '')
1964
+ .catch(() => '')
1965
+ : '')
1966
+ .catch(() => '');
1967
+ }
1968
+ if (response.data?.airwallex_risk_enabled) {
1969
+ const isLivemode = response.data?.is_livemode;
1970
+ const deviceId = generateUUID();
1971
+ sessionResponse.airwallexDeviceId = loadAirwallexDeviceFingerprint(deviceId, isLivemode)
1972
+ .then(() => deviceId)
1973
+ .catch(() => deviceId);
1958
1974
  }
1959
1975
  this.cachedSessionResponse = sessionResponse;
1960
1976
  this.isTelemetryEnabled = !!sessionResponse.data?.sdk_telemetry_enabled;
@@ -2213,8 +2229,7 @@ class CheckoutInstance extends EventEmitter {
2213
2229
  try {
2214
2230
  this.onLoaderChangeWithRace(true);
2215
2231
  this._setState('updating');
2216
- // Invalidate session cache
2217
- CheckoutInstance.sessionCache.clear();
2232
+ sessionService.clearCache();
2218
2233
  await this.apiClient.updateClientSession({
2219
2234
  orderId: this.orderId,
2220
2235
  clientToken: this.clientToken,
@@ -2247,7 +2262,7 @@ class CheckoutInstance extends EventEmitter {
2247
2262
  return;
2248
2263
  try {
2249
2264
  this.stopUnhandledTelemetry();
2250
- CheckoutInstance.sessionCache.clear();
2265
+ sessionService.clearCache();
2251
2266
  await this.primerWrapper.destroy();
2252
2267
  this._setState('destroyed');
2253
2268
  this.orderId = null;
@@ -2458,7 +2473,6 @@ class CheckoutInstance extends EventEmitter {
2458
2473
  this.telemetryPaymentMethod = undefined;
2459
2474
  }
2460
2475
  }
2461
- CheckoutInstance.sessionCache = new Map();
2462
2476
 
2463
2477
  /**
2464
2478
  * @fileoverview Public API with configuration and orchestration logic
@@ -2649,6 +2663,79 @@ async function getAvailablePaymentMethods(params) {
2649
2663
  throw error;
2650
2664
  }
2651
2665
  }
2666
+ async function createStripeCardForm(element, params) {
2667
+ const config = resolveConfig(params, 'createStripeCardForm');
2668
+ const [session, { mountStripeCardForm }] = await Promise.all([
2669
+ sessionService.createSession({
2670
+ orgId: config.orgId,
2671
+ baseUrl: config.baseUrl,
2672
+ region: config.region,
2673
+ priceId: params.priceId,
2674
+ externalId: params.externalId,
2675
+ email: params.email,
2676
+ clientMetadata: params.clientMetadata,
2677
+ countryCode: params.countryCode,
2678
+ integration: 'stripe',
2679
+ }),
2680
+ import('./chunk-stripe-card-form.es.js'),
2681
+ ]);
2682
+ const apiClient = new APIClient({
2683
+ orgId: config.orgId,
2684
+ baseUrl: config.baseUrl || DEFAULTS.BASE_URL,
2685
+ });
2686
+ return mountStripeCardForm(element, session, { ...params, apiClient });
2687
+ }
2688
+ async function purchaseStripeWallet(params) {
2689
+ const config = resolveConfig(params, 'purchaseStripeWallet');
2690
+ const [session, { purchaseWallet }] = await Promise.all([
2691
+ sessionService.createSession({
2692
+ orgId: config.orgId,
2693
+ baseUrl: config.baseUrl,
2694
+ region: config.region,
2695
+ priceId: params.priceId,
2696
+ externalId: params.externalId,
2697
+ email: params.email,
2698
+ clientMetadata: params.clientMetadata,
2699
+ countryCode: params.countryCode,
2700
+ integration: 'stripe',
2701
+ }),
2702
+ import('./chunk-stripe-wallet.es.js'),
2703
+ ]);
2704
+ const apiClient = new APIClient({
2705
+ orgId: config.orgId,
2706
+ baseUrl: config.baseUrl || DEFAULTS.BASE_URL,
2707
+ });
2708
+ return purchaseWallet(session, { ...params, apiClient });
2709
+ }
2710
+ async function getAvailableStripeWallet(params) {
2711
+ const config = resolveConfig(params, 'getAvailableStripeWallet');
2712
+ const [session, { getAvailableWallet }] = await Promise.all([
2713
+ sessionService.createSession({
2714
+ orgId: config.orgId,
2715
+ baseUrl: config.baseUrl,
2716
+ region: config.region,
2717
+ priceId: params.priceId,
2718
+ externalId: params.externalId,
2719
+ email: params.email,
2720
+ clientMetadata: params.clientMetadata,
2721
+ countryCode: params.countryCode,
2722
+ integration: 'stripe',
2723
+ }),
2724
+ import('./chunk-stripe-wallet.es.js'),
2725
+ ]);
2726
+ const result = await getAvailableWallet(session);
2727
+ if (result === 'APPLE_PAY')
2728
+ return PaymentMethod.APPLE_PAY;
2729
+ if (result === 'GOOGLE_PAY')
2730
+ return PaymentMethod.GOOGLE_PAY;
2731
+ return null;
2732
+ }
2733
+ async function getAvailableStripePaymentMethods(params) {
2734
+ const wallet = await getAvailableStripeWallet(params);
2735
+ return wallet
2736
+ ? [PaymentMethod.PAYMENT_CARD, wallet]
2737
+ : [PaymentMethod.PAYMENT_CARD];
2738
+ }
2652
2739
 
2653
2740
  /**
2654
2741
  * @fileoverview Main entry point for @funnelfox/billing
@@ -2660,9 +2747,15 @@ const Billing = {
2660
2747
  initMethod: initMethod,
2661
2748
  silentPurchase: silentPurchase,
2662
2749
  getAvailablePaymentMethods: getAvailablePaymentMethods,
2750
+ stripe: {
2751
+ createCardForm: createStripeCardForm,
2752
+ purchaseWallet: purchaseStripeWallet,
2753
+ getAvailableWallet: getAvailableStripeWallet,
2754
+ getAvailablePaymentMethods: getAvailableStripePaymentMethods,
2755
+ },
2663
2756
  };
2664
2757
  if (typeof window !== 'undefined') {
2665
2758
  window.Billing = Billing;
2666
2759
  }
2667
2760
 
2668
- export { APIError as A, Billing as B, CheckoutError as C, DEFAULT_BUTTONS_OPTIONS as D, EVENTS as E, FunnefoxSDKError as F, NetworkError as N, PaymentMethod as P, SDK_VERSION as S, ValidationError as V, PrimerError as a, ConfigurationError as b, DEFAULTS as c, CHECKOUT_STATES as d, ERROR_CODES as e, configure as f, createCheckout as g, createClientSession as h, getAvailablePaymentMethods as i };
2761
+ export { APIError as A, Billing as B, CheckoutError as C, DEFAULT_BUTTONS_OPTIONS as D, EVENTS as E, FunnefoxSDKError as F, NetworkError as N, PaymentMethod as P, SDK_VERSION as S, ValidationError as V, PrimerError as a, ConfigurationError as b, DEFAULTS as c, CHECKOUT_STATES as d, ERROR_CODES as e, configure as f, createCheckout as g, createClientSession as h, getAvailablePaymentMethods as i, loadStripe as l };
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @funnelfox/billing v0.1.0
3
+ * JavaScript SDK for Funnelfox billing with Primer integration
4
+ *
5
+ * @author Funnelfox
6
+ * @license MIT
7
+ */
8
+ 'use strict';
9
+
10
+ var stripeLoader = require('./chunk-stripe-loader.cjs.js');
11
+ require('./chunk-index.cjs.js');
12
+
13
+ async function mountStripeCardForm(element, session, params) {
14
+ const { stripe_public_key, amount, currency, order_id, is_link_enabled } = session.data;
15
+ const stripe = await stripeLoader.getStripe(stripe_public_key);
16
+ if (!stripe)
17
+ throw new Error('Failed to load Stripe');
18
+ const stripeElements = stripe.elements({
19
+ mode: 'subscription',
20
+ amount,
21
+ currency,
22
+ paymentMethodCreation: 'manual',
23
+ paymentMethodTypes: is_link_enabled ? ['card', 'link'] : ['card'],
24
+ appearance: params.appearance,
25
+ });
26
+ const paymentElement = stripeElements.create('payment', {
27
+ layout: 'tabs',
28
+ wallets: {
29
+ applePay: params.showWallets ? 'auto' : 'never',
30
+ googlePay: params.showWallets ? 'auto' : 'never',
31
+ },
32
+ terms: { card: 'never' },
33
+ });
34
+ paymentElement.mount(element);
35
+ await new Promise((resolve, reject) => {
36
+ paymentElement.once('ready', () => resolve());
37
+ // 'loaderror' is a valid Stripe event but not yet in the @stripe/stripe-js types
38
+ paymentElement.once('loaderror', e => reject(e.error));
39
+ });
40
+ params.onRenderSuccess?.();
41
+ return {
42
+ submit: async () => {
43
+ params.onLoaderChange?.(true);
44
+ try {
45
+ const { error: submitError } = await stripeElements.submit();
46
+ if (submitError)
47
+ throw submitError;
48
+ const { error, paymentMethod } = await stripe.createPaymentMethod({
49
+ elements: stripeElements,
50
+ });
51
+ if (error)
52
+ throw error;
53
+ const raw = await params.apiClient.createPayment({
54
+ orderId: order_id,
55
+ paymentMethodToken: paymentMethod.id,
56
+ email: params.email,
57
+ countryCode: params.countryCode,
58
+ clientMetadata: params.clientMetadata,
59
+ });
60
+ const result = params.apiClient.processPaymentResponse(raw);
61
+ if (result.type === 'action_required') {
62
+ const { error: confirmError } = await stripe.confirmPayment({
63
+ clientSecret: result.clientToken,
64
+ redirect: 'if_required',
65
+ confirmParams: { return_url: window.location.href },
66
+ });
67
+ if (confirmError)
68
+ throw confirmError;
69
+ }
70
+ params.onPaymentSuccess?.(paymentMethod, order_id);
71
+ }
72
+ catch (err) {
73
+ params.onPaymentFail?.(err);
74
+ throw err;
75
+ }
76
+ finally {
77
+ params.onLoaderChange?.(false);
78
+ }
79
+ },
80
+ };
81
+ }
82
+
83
+ exports.mountStripeCardForm = mountStripeCardForm;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @funnelfox/billing v0.1.0
3
+ * JavaScript SDK for Funnelfox billing with Primer integration
4
+ *
5
+ * @author Funnelfox
6
+ * @license MIT
7
+ */
8
+ import { g as getStripe } from './chunk-stripe-loader.es.js';
9
+ import './chunk-index.es.js';
10
+
11
+ async function mountStripeCardForm(element, session, params) {
12
+ const { stripe_public_key, amount, currency, order_id, is_link_enabled } = session.data;
13
+ const stripe = await getStripe(stripe_public_key);
14
+ if (!stripe)
15
+ throw new Error('Failed to load Stripe');
16
+ const stripeElements = stripe.elements({
17
+ mode: 'subscription',
18
+ amount,
19
+ currency,
20
+ paymentMethodCreation: 'manual',
21
+ paymentMethodTypes: is_link_enabled ? ['card', 'link'] : ['card'],
22
+ appearance: params.appearance,
23
+ });
24
+ const paymentElement = stripeElements.create('payment', {
25
+ layout: 'tabs',
26
+ wallets: {
27
+ applePay: params.showWallets ? 'auto' : 'never',
28
+ googlePay: params.showWallets ? 'auto' : 'never',
29
+ },
30
+ terms: { card: 'never' },
31
+ });
32
+ paymentElement.mount(element);
33
+ await new Promise((resolve, reject) => {
34
+ paymentElement.once('ready', () => resolve());
35
+ // 'loaderror' is a valid Stripe event but not yet in the @stripe/stripe-js types
36
+ paymentElement.once('loaderror', e => reject(e.error));
37
+ });
38
+ params.onRenderSuccess?.();
39
+ return {
40
+ submit: async () => {
41
+ params.onLoaderChange?.(true);
42
+ try {
43
+ const { error: submitError } = await stripeElements.submit();
44
+ if (submitError)
45
+ throw submitError;
46
+ const { error, paymentMethod } = await stripe.createPaymentMethod({
47
+ elements: stripeElements,
48
+ });
49
+ if (error)
50
+ throw error;
51
+ const raw = await params.apiClient.createPayment({
52
+ orderId: order_id,
53
+ paymentMethodToken: paymentMethod.id,
54
+ email: params.email,
55
+ countryCode: params.countryCode,
56
+ clientMetadata: params.clientMetadata,
57
+ });
58
+ const result = params.apiClient.processPaymentResponse(raw);
59
+ if (result.type === 'action_required') {
60
+ const { error: confirmError } = await stripe.confirmPayment({
61
+ clientSecret: result.clientToken,
62
+ redirect: 'if_required',
63
+ confirmParams: { return_url: window.location.href },
64
+ });
65
+ if (confirmError)
66
+ throw confirmError;
67
+ }
68
+ params.onPaymentSuccess?.(paymentMethod, order_id);
69
+ }
70
+ catch (err) {
71
+ params.onPaymentFail?.(err);
72
+ throw err;
73
+ }
74
+ finally {
75
+ params.onLoaderChange?.(false);
76
+ }
77
+ },
78
+ };
79
+ }
80
+
81
+ export { mountStripeCardForm };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @funnelfox/billing v0.1.0
3
+ * JavaScript SDK for Funnelfox billing with Primer integration
4
+ *
5
+ * @author Funnelfox
6
+ * @license MIT
7
+ */
8
+ 'use strict';
9
+
10
+ var index = require('./chunk-index.cjs.js');
11
+
12
+ const cache = new Map();
13
+ function getStripe(publicKey) {
14
+ if (!cache.has(publicKey)) {
15
+ cache.set(publicKey, index.loadStripe(publicKey));
16
+ }
17
+ return cache.get(publicKey);
18
+ }
19
+
20
+ exports.getStripe = getStripe;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @funnelfox/billing v0.1.0
3
+ * JavaScript SDK for Funnelfox billing with Primer integration
4
+ *
5
+ * @author Funnelfox
6
+ * @license MIT
7
+ */
8
+ import { l as loadStripe } from './chunk-index.es.js';
9
+
10
+ const cache = new Map();
11
+ function getStripe(publicKey) {
12
+ if (!cache.has(publicKey)) {
13
+ cache.set(publicKey, loadStripe(publicKey));
14
+ }
15
+ return cache.get(publicKey);
16
+ }
17
+
18
+ export { getStripe as g };
@@ -0,0 +1,114 @@
1
+ /**
2
+ * @funnelfox/billing v0.1.0
3
+ * JavaScript SDK for Funnelfox billing with Primer integration
4
+ *
5
+ * @author Funnelfox
6
+ * @license MIT
7
+ */
8
+ 'use strict';
9
+
10
+ var stripeLoader = require('./chunk-stripe-loader.cjs.js');
11
+ require('./chunk-index.cjs.js');
12
+
13
+ function buildPaymentRequest(stripe, data, totalLabel) {
14
+ const raw = data.apple_pay_recurring_payment_request;
15
+ if (raw) {
16
+ const parseDates = (b) => {
17
+ if (b.recurringPaymentStartDate)
18
+ Object.assign(b, {
19
+ recurringPaymentStartDate: new Date(b.recurringPaymentStartDate),
20
+ });
21
+ if (b.recurringPaymentEndDate)
22
+ Object.assign(b, {
23
+ recurringPaymentEndDate: new Date(b.recurringPaymentEndDate),
24
+ });
25
+ };
26
+ parseDates(raw.regularBilling);
27
+ if (raw.trialBilling)
28
+ parseDates(raw.trialBilling);
29
+ }
30
+ const applePay = raw
31
+ ? { recurringPaymentRequest: raw }
32
+ : undefined;
33
+ return stripe.paymentRequest({
34
+ country: data.country,
35
+ currency: data.currency,
36
+ total: {
37
+ label: totalLabel?.trim() || 'Total',
38
+ amount: data.amount,
39
+ },
40
+ requestPayerName: false,
41
+ requestPayerEmail: false,
42
+ applePay,
43
+ });
44
+ }
45
+ async function getAvailableWallet(session) {
46
+ const { stripe_public_key } = session.data;
47
+ const stripe = await stripeLoader.getStripe(stripe_public_key);
48
+ if (!stripe)
49
+ throw new Error('Failed to load Stripe');
50
+ const paymentRequest = buildPaymentRequest(stripe, session.data);
51
+ const result = await paymentRequest.canMakePayment();
52
+ if (!result)
53
+ return null;
54
+ if (result.applePay)
55
+ return 'APPLE_PAY';
56
+ if (result.googlePay)
57
+ return 'GOOGLE_PAY';
58
+ return null;
59
+ }
60
+ async function purchaseWallet(session, params) {
61
+ const { stripe_public_key, order_id } = session.data;
62
+ const stripe = await stripeLoader.getStripe(stripe_public_key);
63
+ if (!stripe)
64
+ throw new Error('Failed to load Stripe');
65
+ const paymentRequest = buildPaymentRequest(stripe, session.data, params.totalLabel);
66
+ const canPay = await paymentRequest.canMakePayment();
67
+ if (!canPay)
68
+ throw new Error('No wallet payment method available');
69
+ return new Promise((resolve, reject) => {
70
+ paymentRequest.on('paymentmethod', async (event) => {
71
+ params.onLoaderChange?.(true);
72
+ try {
73
+ const raw = await params.apiClient.createPayment({
74
+ orderId: order_id,
75
+ paymentMethodToken: event.paymentMethod.id,
76
+ email: params.email,
77
+ countryCode: params.countryCode,
78
+ clientMetadata: params.clientMetadata,
79
+ });
80
+ const result = params.apiClient.processPaymentResponse(raw);
81
+ if (result.type === 'action_required') {
82
+ const { error } = await stripe.confirmPayment({
83
+ clientSecret: result.clientToken,
84
+ redirect: 'if_required',
85
+ confirmParams: { return_url: window.location.href },
86
+ });
87
+ if (error) {
88
+ event.complete('fail');
89
+ throw error;
90
+ }
91
+ }
92
+ event.complete('success');
93
+ params.onPaymentSuccess?.(event.paymentMethod, order_id);
94
+ resolve();
95
+ }
96
+ catch (err) {
97
+ event.complete('fail');
98
+ params.onPaymentFail?.(err);
99
+ reject(err);
100
+ }
101
+ finally {
102
+ params.onLoaderChange?.(false);
103
+ }
104
+ });
105
+ paymentRequest.on('cancel', () => {
106
+ params.onPaymentCancel?.();
107
+ resolve();
108
+ });
109
+ paymentRequest.show();
110
+ });
111
+ }
112
+
113
+ exports.getAvailableWallet = getAvailableWallet;
114
+ exports.purchaseWallet = purchaseWallet;