@funnelfox/billing 0.13.1 → 0.14.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.
@@ -561,7 +561,7 @@ exports.PaymentMethod = void 0;
561
561
  /**
562
562
  * @fileoverview Constants for Funnefox SDK
563
563
  */
564
- const SDK_VERSION = '0.13.1';
564
+ const SDK_VERSION = '0.14.0';
565
565
  const DEFAULTS = {
566
566
  BASE_URL: 'https://billing.funnelfox.com',
567
567
  REGION: 'default',
@@ -603,6 +603,7 @@ const API_ENDPOINTS = {
603
603
  CREATE_PAYMENT: '/v1/checkout/create_payment',
604
604
  RESUME_PAYMENT: '/v1/checkout/resume_payment',
605
605
  ONE_CLICK: '/v1/checkout/one_click',
606
+ ONE_CLICK_WALLET_SESSION: '/v1/checkout/one_click_wallet_session',
606
607
  CREATE_SIMPLE_CLIENT_SESSION: '/v1/checkout/create_simple_client_session',
607
608
  RECALCULATE_TAX: '/v1/checkout/recalculate_tax',
608
609
  };
@@ -806,7 +807,7 @@ async function overlayNativeApplePayButton(wrapper, options) {
806
807
  'height:100%',
807
808
  '--apple-pay-button-width:100%',
808
809
  '--apple-pay-button-height:100%',
809
- '--apple-pay-button-border-radius:28px',
810
+ `--apple-pay-button-border-radius:${options.borderRadius ?? 28}px`,
810
811
  'display:block',
811
812
  'cursor:pointer',
812
813
  'z-index:1',
@@ -1377,11 +1378,13 @@ class APIClient {
1377
1378
  }
1378
1379
  }
1379
1380
  /**
1380
- * Sends the request exactly once: no retry and no client timeout (FFB-704, decision 9).
1381
+ * Sends the request exactly once: no retry and, without `timeoutMs`, no client timeout
1382
+ * (FFB-704, decision 9).
1381
1383
  * Same URL, headers and error classes as `request()`. Used only by `silentPurchase`'s
1382
- * `handle3DS` mode for `one_click` and `resume_payment`, which must not be POSTed twice.
1384
+ * `handle3DS` mode for `one_click` and `resume_payment`, which must not be POSTed twice;
1385
+ * `one_click` is re-sent by the caller only with the same idempotency key.
1383
1386
  */
1384
- async requestOnce(endpoint, options = {}) {
1387
+ async requestOnce(endpoint, options = {}, timeoutMs) {
1385
1388
  const url = `${this.baseUrl}/${this.orgId}${endpoint}`;
1386
1389
  const requestOptions = {
1387
1390
  method: 'GET',
@@ -1393,7 +1396,10 @@ class APIClient {
1393
1396
  ...options,
1394
1397
  };
1395
1398
  try {
1396
- return await this._makeRequest(url, requestOptions);
1399
+ const request = this._makeRequest(url, requestOptions);
1400
+ return await (timeoutMs
1401
+ ? withTimeout(request, timeoutMs, 'Request timed out')
1402
+ : request);
1397
1403
  }
1398
1404
  catch (error) {
1399
1405
  if (error instanceof APIError) {
@@ -1599,11 +1605,18 @@ class APIClient {
1599
1605
  }));
1600
1606
  }
1601
1607
  /** `one_click`, POSTed exactly once (see `requestOnce`). */
1602
- async oneClickOnce(payload) {
1608
+ async oneClickOnce(payload, timeoutMs) {
1603
1609
  return (await this.requestOnce(API_ENDPOINTS.ONE_CLICK, {
1604
1610
  method: 'POST',
1605
1611
  body: JSON.stringify(payload),
1606
- }));
1612
+ }, timeoutMs));
1613
+ }
1614
+ /** `one_click_wallet_session`: prepares the wallet re-auth button of a one-click upsell. */
1615
+ async oneClickWalletSession(payload, timeoutMs) {
1616
+ return (await this.requestOnce(API_ENDPOINTS.ONE_CLICK_WALLET_SESSION, {
1617
+ method: 'POST',
1618
+ body: JSON.stringify(payload),
1619
+ }, timeoutMs));
1607
1620
  }
1608
1621
  /** `resume_payment`, POSTed exactly once (see `requestOnce`). */
1609
1622
  async resumePaymentOnce(params) {
@@ -2156,6 +2169,9 @@ class CheckoutInstance extends EventEmitter {
2156
2169
  this.counter = 0;
2157
2170
  this.cachedSessionResponse = null;
2158
2171
  this.taxRecalcSeq = 0;
2172
+ // WebKit allows one ApplePaySession per page: a second tap while the sheet is
2173
+ // still opening throws InvalidAccessError, but Primer asks to start first.
2174
+ this.isApplePaySheetOpen = false;
2159
2175
  this.cardSessionFieldConfig = {};
2160
2176
  this.isTelemetryEnabled = false;
2161
2177
  this.telemetryCleanup = null;
@@ -2322,6 +2338,7 @@ class CheckoutInstance extends EventEmitter {
2322
2338
  primerHandler.handleFailure(error?.message || 'Payment processing failed');
2323
2339
  }
2324
2340
  finally {
2341
+ this.isApplePaySheetOpen = false;
2325
2342
  this.onLoaderChangeWithRace(false);
2326
2343
  this._setState('ready');
2327
2344
  }
@@ -2347,6 +2364,7 @@ class CheckoutInstance extends EventEmitter {
2347
2364
  primerHandler.handleFailure(error?.message || 'Payment processing failed');
2348
2365
  }
2349
2366
  finally {
2367
+ this.isApplePaySheetOpen = false;
2350
2368
  this.emit(EVENTS.PURCHASE_COMPLETED);
2351
2369
  this.onLoaderChangeWithRace(false);
2352
2370
  this._setState('ready');
@@ -2675,6 +2693,7 @@ class CheckoutInstance extends EventEmitter {
2675
2693
  onTokenizeSuccess: this.handleTokenizeSuccess,
2676
2694
  onResumeSuccess: this.handleResumeSuccess,
2677
2695
  onResumeError: error => {
2696
+ this.isApplePaySheetOpen = false;
2678
2697
  if (error.stack?.includes('PROCESSOR_3DS') &&
2679
2698
  error.code === 'RESUME_ERROR' &&
2680
2699
  error.message?.includes('fetch resume key')) {
@@ -2684,15 +2703,23 @@ class CheckoutInstance extends EventEmitter {
2684
2703
  this.emit(EVENTS.PURCHASE_FAILURE, error);
2685
2704
  },
2686
2705
  onCheckoutFail: error => {
2706
+ this.isApplePaySheetOpen = false;
2687
2707
  this.emit(EVENTS.PURCHASE_FAILURE, error);
2688
2708
  },
2689
2709
  onTokenizeError: error => {
2710
+ this.isApplePaySheetOpen = false;
2690
2711
  this.emit(EVENTS.PURCHASE_FAILURE, error);
2691
2712
  },
2692
2713
  onTokenizeStart: () => {
2693
2714
  wasPaymentProcessedStarted = true;
2694
2715
  },
2695
2716
  onTokenizeShouldStart: data => {
2717
+ if (data.paymentMethodType === exports.PaymentMethod.APPLE_PAY) {
2718
+ if (this.isApplePaySheetOpen) {
2719
+ return false;
2720
+ }
2721
+ this.isApplePaySheetOpen = true;
2722
+ }
2696
2723
  this.activePaymentMethodType = data.paymentMethodType;
2697
2724
  this.emit(EVENTS.ERROR, undefined);
2698
2725
  this.emit(EVENTS.START_PURCHASE, data.paymentMethodType);
@@ -2704,6 +2731,7 @@ class CheckoutInstance extends EventEmitter {
2704
2731
  this.emit(EVENTS.ERROR, undefined);
2705
2732
  break;
2706
2733
  case 'PAYMENT_METHOD_UNSELECTED':
2734
+ this.isApplePaySheetOpen = false;
2707
2735
  if (!wasPaymentProcessedStarted) {
2708
2736
  this.emit(EVENTS.PURCHASE_CANCELLED);
2709
2737
  }
@@ -2983,11 +3011,23 @@ class CheckoutInstance extends EventEmitter {
2983
3011
  * checkout, tokenize a vaulted instrument through the vault manager as a stand-in, and in
2984
3012
  * `onTokenizeSuccess` continue with the one-click `action_required_token` instead. Primer then
2985
3013
  * shows its 3DS overlay; `onResumeSuccess` yields the resume token for `resume_payment`.
3014
+ *
3015
+ * With processor 3DS (`PROCESSOR_3DS`) Primer frames the processor's hosted 3DS page and cannot
3016
+ * tell a frictionless check from a challenge, and nothing reaches the page from the cross-origin
3017
+ * frame (FFB-758 spike). A frictionless check finishes within ~5 s, so the overlay stays
3018
+ * invisible for `THREE_DS_OVERLAY_REVEAL_DELAY_MS` and only then counts as a shown challenge.
2986
3019
  */
2987
3020
  /** Primer client-token intents that carry a 3DS step. */
2988
3021
  const PRIMER_3DS_INTENTS = ['3DS_AUTHENTICATION', 'PROCESSOR_3DS'];
2989
3022
  /** Default `threeDSTimeoutMs`. */
2990
3023
  const DEFAULT_THREE_DS_TIMEOUT_MS = 600000;
3024
+ /**
3025
+ * How long Primer's 3DS overlay stays invisible. Frictionless checks on billing-dev took
3026
+ * 4.2-5.0 s from overlay to resume; a real challenge is shown this much later.
3027
+ */
3028
+ const THREE_DS_OVERLAY_REVEAL_DELAY_MS = 6000;
3029
+ /** Primer's 3DS overlay (Primer Web SDK 2.57.3, verified in the FFB-758 spike). */
3030
+ const PRIMER_OVERLAY_SELECTOR = '#primer-overlay';
2991
3031
  /** Close button of Primer's 3DS overlay (Primer Web SDK 2.57.3, verified in the spike). */
2992
3032
  const PRIMER_OVERLAY_CLOSE_SELECTOR = '[data-testid="OverlayContent.closeButton"]';
2993
3033
  /** Decodes the `intent` of a Primer client token (a JWT); `null` if it is not one. */
@@ -3031,10 +3071,30 @@ function dismissPrimerOverlay() {
3031
3071
  const button = document.querySelector(PRIMER_OVERLAY_CLOSE_SELECTOR);
3032
3072
  button?.click();
3033
3073
  }
3074
+ /** Hides Primer's overlay until the returned function is called. */
3075
+ function hidePrimerOverlay() {
3076
+ if (typeof document === 'undefined') {
3077
+ return () => { };
3078
+ }
3079
+ const style = document.createElement('style');
3080
+ style.textContent = `${PRIMER_OVERLAY_SELECTOR}{opacity:0!important;pointer-events:none!important}`;
3081
+ document.head.appendChild(style);
3082
+ return () => style.remove();
3083
+ }
3084
+ /**
3085
+ * A Primer update that renames the overlay would leave it visible during the hidden phase, while
3086
+ * `threeDSChallenged` stays false for a check that finishes in that time.
3087
+ */
3088
+ function warnIfOverlayNotFound() {
3089
+ if (typeof document !== 'undefined' &&
3090
+ !document.querySelector(PRIMER_OVERLAY_SELECTOR)) {
3091
+ console.warn(`[FunnelfoxSDK] Primer 3DS overlay ${PRIMER_OVERLAY_SELECTOR} not found`);
3092
+ }
3093
+ }
3034
3094
  function toPrimerError(message, error) {
3035
3095
  return error instanceof PrimerError ? error : new PrimerError(message, error);
3036
3096
  }
3037
- function callSafely(fn) {
3097
+ function callSafely$1(fn) {
3038
3098
  try {
3039
3099
  fn();
3040
3100
  }
@@ -3061,6 +3121,9 @@ async function runOneClickThreeDS(params) {
3061
3121
  return new Promise(resolve => {
3062
3122
  let settled = false;
3063
3123
  let tokenized = false;
3124
+ let revealed = false;
3125
+ let revealTimer = null;
3126
+ let showOverlay = () => { };
3064
3127
  // True only while create_client_session is in flight.
3065
3128
  let sessionInFlight = false;
3066
3129
  let timer = null;
@@ -3074,12 +3137,17 @@ async function runOneClickThreeDS(params) {
3074
3137
  clearTimeout(timer);
3075
3138
  timer = null;
3076
3139
  }
3140
+ if (revealTimer) {
3141
+ clearTimeout(revealTimer);
3142
+ revealTimer = null;
3143
+ }
3144
+ showOverlay();
3077
3145
  headless = null;
3078
3146
  resolve(result);
3079
3147
  };
3080
- timer = setTimeout(() => {
3148
+ const onTimeout = () => {
3081
3149
  timer = null;
3082
- if (tokenized) {
3150
+ if (revealed) {
3083
3151
  // The challenge was shown and the customer did not finish it.
3084
3152
  settle({ kind: 'abandoned' });
3085
3153
  // Close Primer's overlay; the close error it raises is ignored (already settled).
@@ -3095,23 +3163,43 @@ async function runOneClickThreeDS(params) {
3095
3163
  });
3096
3164
  return;
3097
3165
  }
3166
+ if (tokenized) {
3167
+ // The overlay is about to be shown: the reveal restarts the timer.
3168
+ return;
3169
+ }
3098
3170
  settle({
3099
3171
  kind: 'error',
3100
3172
  error: new PrimerError('Timed out before the 3DS challenge was shown (threeDSTimeoutMs)'),
3101
3173
  });
3102
- }, timeoutMs);
3174
+ };
3175
+ timer = setTimeout(onTimeout, timeoutMs);
3103
3176
  const onTokenizeSuccess = (_data, handler) => {
3104
- if (settled) {
3105
- callSafely(() => handler.handleFailure());
3177
+ // A repeated tokenization would start a second reveal timer, so the challenge
3178
+ // (and the caller's onThreeDSStart) would be reported twice: refuse it.
3179
+ if (settled || tokenized) {
3180
+ callSafely$1(() => handler.handleFailure());
3106
3181
  return;
3107
3182
  }
3108
3183
  tokenized = true;
3184
+ showOverlay = hidePrimerOverlay();
3185
+ revealTimer = setTimeout(() => {
3186
+ revealTimer = null;
3187
+ revealed = true;
3188
+ showOverlay();
3189
+ warnIfOverlayNotFound();
3190
+ callSafely$1(params.onChallengeShown);
3191
+ // The whole timeout belongs to the challenge the customer can see.
3192
+ if (timer) {
3193
+ clearTimeout(timer);
3194
+ }
3195
+ timer = setTimeout(onTimeout, timeoutMs);
3196
+ }, params.revealDelayMs);
3109
3197
  // Ignore the stand-in vaulted token: run the one-click 3DS action instead.
3110
3198
  handler.continueWithNewClientToken(actionToken);
3111
3199
  };
3112
3200
  const onResumeSuccess = async (data, handler) => {
3113
3201
  if (settled) {
3114
- callSafely(() => handler.handleFailure());
3202
+ callSafely$1(() => handler.handleFailure());
3115
3203
  return;
3116
3204
  }
3117
3205
  // The challenge is over: the timeout bounds only the challenge, never the POST.
@@ -3119,6 +3207,10 @@ async function runOneClickThreeDS(params) {
3119
3207
  clearTimeout(timer);
3120
3208
  timer = null;
3121
3209
  }
3210
+ if (revealTimer) {
3211
+ clearTimeout(revealTimer);
3212
+ revealTimer = null;
3213
+ }
3122
3214
  let response;
3123
3215
  try {
3124
3216
  response = await apiClient.resumePaymentOnce({
@@ -3127,7 +3219,7 @@ async function runOneClickThreeDS(params) {
3127
3219
  });
3128
3220
  }
3129
3221
  catch (error) {
3130
- callSafely(() => handler.handleFailure());
3222
+ callSafely$1(() => handler.handleFailure());
3131
3223
  settle({
3132
3224
  kind: 'error',
3133
3225
  error: error,
@@ -3139,11 +3231,11 @@ async function runOneClickThreeDS(params) {
3139
3231
  if (response?.status === 'success' &&
3140
3232
  resumeData?.checkout_status === 'succeeded' &&
3141
3233
  !resumeData.action_required_token) {
3142
- callSafely(() => handler.handleSuccess());
3234
+ callSafely$1(() => handler.handleSuccess());
3143
3235
  }
3144
3236
  else {
3145
3237
  // A chained action token is never continued (no second challenge).
3146
- callSafely(() => handler.handleFailure(resumeData?.failed_message_for_user || undefined));
3238
+ callSafely$1(() => handler.handleFailure(resumeData?.failed_message_for_user || undefined));
3147
3239
  }
3148
3240
  settle({ kind: 'resumed', response });
3149
3241
  };
@@ -3252,6 +3344,10 @@ let defaultConfig = null;
3252
3344
  function configure(config) {
3253
3345
  defaultConfig = config;
3254
3346
  }
3347
+ /** The base URL from `configure()`, else the production one. */
3348
+ function defaultBaseUrl() {
3349
+ return defaultConfig?.baseUrl || DEFAULTS.BASE_URL;
3350
+ }
3255
3351
  function resolveConfig(options, functionName) {
3256
3352
  const { orgId, apiConfig } = options || {};
3257
3353
  const finalOrgId = orgId || defaultConfig?.orgId;
@@ -3326,9 +3422,6 @@ function buildOneClickRequest(options) {
3326
3422
  if (options.citCardNetworks !== undefined) {
3327
3423
  payload.cit_card_networks = options.citCardNetworks;
3328
3424
  }
3329
- if (options.citGooglePayPanOnly !== undefined) {
3330
- payload.cit_google_pay_pan_only = options.citGooglePayPanOnly;
3331
- }
3332
3425
  return payload;
3333
3426
  }
3334
3427
  function silentPurchase(options) {
@@ -3372,7 +3465,84 @@ async function silentPurchaseLegacy(options) {
3372
3465
  }
3373
3466
  const ONE_CLICK_IN_PROGRESS = 'one_click_in_progress';
3374
3467
  const DOUBLE_PURCHASE = 'double_purchase';
3468
+ const IDEMPOTENCY_KEY_IN_PROGRESS = 'idempotency_key_in_progress';
3469
+ const ONE_CLICK_RETRY_DELAYS_MS = [1000, 2000, 4000];
3470
+ /** Longer than the backend's wait for the user's lock (~12.6 s). */
3471
+ const ONE_CLICK_TIMEOUT_MS = 25000;
3472
+ /** org + external id of the customers with a one-click purchase running (silent or wallet). */
3375
3473
  const oneClickInFlight = new Set();
3474
+ function oneClickInFlightKey(orgId, externalId) {
3475
+ return `${orgId}\u0000${externalId}`;
3476
+ }
3477
+ /** A random UUID v4, or `null` when the browser has no crypto (then one_click is not retried). */
3478
+ function createIdempotencyKey() {
3479
+ const cryptoApi = typeof crypto === 'undefined' ? undefined : crypto;
3480
+ if (typeof cryptoApi?.randomUUID === 'function') {
3481
+ return cryptoApi.randomUUID();
3482
+ }
3483
+ if (typeof cryptoApi?.getRandomValues !== 'function') {
3484
+ return null;
3485
+ }
3486
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
3487
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
3488
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
3489
+ const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));
3490
+ return [
3491
+ hex.slice(0, 4).join(''),
3492
+ hex.slice(4, 6).join(''),
3493
+ hex.slice(6, 8).join(''),
3494
+ hex.slice(8, 10).join(''),
3495
+ hex.slice(10, 16).join(''),
3496
+ ].join('-');
3497
+ }
3498
+ /**
3499
+ * Failures after which the backend may or may not have processed the request. Retrying them
3500
+ * with the same idempotency key is safe: the backend never charges a key twice (FFB-757).
3501
+ * A 2xx APIError means the body could not be parsed.
3502
+ */
3503
+ function isRetryableOneClickError(error) {
3504
+ if (error instanceof NetworkError) {
3505
+ return true;
3506
+ }
3507
+ if (!(error instanceof APIError) || error.statusCode === null) {
3508
+ return false;
3509
+ }
3510
+ if (error.statusCode >= 500) {
3511
+ return true;
3512
+ }
3513
+ if (error.statusCode >= 200 && error.statusCode < 300) {
3514
+ return true;
3515
+ }
3516
+ return (error.statusCode === 400 && error.errorCode === IDEMPOTENCY_KEY_IN_PROGRESS);
3517
+ }
3518
+ function isEmptyResponse(response) {
3519
+ return !response || typeof response !== 'object' || !('status' in response);
3520
+ }
3521
+ /** `one_click`, retried with the same idempotency key; sent once when there is no key. */
3522
+ async function postOneClick(apiClient, payload) {
3523
+ if (!payload.idempotency_key) {
3524
+ return apiClient.oneClickOnce(payload);
3525
+ }
3526
+ for (const delay of ONE_CLICK_RETRY_DELAYS_MS) {
3527
+ try {
3528
+ const response = await apiClient.oneClickOnce(payload, ONE_CLICK_TIMEOUT_MS);
3529
+ if (!isEmptyResponse(response)) {
3530
+ return response;
3531
+ }
3532
+ }
3533
+ catch (error) {
3534
+ if (!isRetryableOneClickError(error)) {
3535
+ throw error;
3536
+ }
3537
+ }
3538
+ await sleep(delay);
3539
+ }
3540
+ const response = await apiClient.oneClickOnce(payload, ONE_CLICK_TIMEOUT_MS);
3541
+ if (isEmptyResponse(response)) {
3542
+ throw new NetworkError('one_click returned an empty response');
3543
+ }
3544
+ return response;
3545
+ }
3376
3546
  function declineFields(data) {
3377
3547
  return {
3378
3548
  failedMessageForUser: data.failed_message_for_user ?? null,
@@ -3461,7 +3631,7 @@ function mapOneClickResponse(response) {
3461
3631
  }
3462
3632
  }
3463
3633
  /** Maps a `resume_payment` response after a challenge (rows 5, 6, 6b, 6c, 7, 8). */
3464
- function mapResumeResponse(response, orderId, threeDSAuthDeclineCodes = THREE_DS_AUTH_DECLINE_CODES) {
3634
+ function mapResumeResponse(response, orderId, threeDSChallenged, threeDSAuthDeclineCodes = THREE_DS_AUTH_DECLINE_CODES) {
3465
3635
  const data = response?.data;
3466
3636
  if (response?.status !== 'success' || !data) {
3467
3637
  return {
@@ -3469,7 +3639,7 @@ function mapResumeResponse(response, orderId, threeDSAuthDeclineCodes = THREE_DS
3469
3639
  result: {
3470
3640
  outcome: 'error',
3471
3641
  orderId,
3472
- threeDSChallenged: true,
3642
+ threeDSChallenged,
3473
3643
  error: envelopeError(response, 'Resume payment failed'),
3474
3644
  failedRequest: 'resume_payment',
3475
3645
  },
@@ -3482,7 +3652,7 @@ function mapResumeResponse(response, orderId, threeDSAuthDeclineCodes = THREE_DS
3482
3652
  result: {
3483
3653
  outcome: 'error',
3484
3654
  orderId,
3485
- threeDSChallenged: true,
3655
+ threeDSChallenged,
3486
3656
  error: new FunnefoxSDKError('resume_payment returned another action token; chained 3DS is not supported', 'one_click_chained_action'),
3487
3657
  },
3488
3658
  };
@@ -3491,22 +3661,24 @@ function mapResumeResponse(response, orderId, threeDSAuthDeclineCodes = THREE_DS
3491
3661
  case 'succeeded':
3492
3662
  return {
3493
3663
  threeDS: 'passed',
3494
- result: { outcome: 'succeeded', orderId, threeDSChallenged: true },
3664
+ result: { outcome: 'succeeded', orderId, threeDSChallenged },
3495
3665
  };
3496
3666
  case 'processing':
3497
3667
  return {
3498
3668
  threeDS: 'passed',
3499
- result: { outcome: 'processing', orderId, threeDSChallenged: true },
3669
+ result: { outcome: 'processing', orderId, threeDSChallenged },
3500
3670
  };
3501
3671
  case 'failed': {
3502
- const authFailed = threeDSAuthDeclineCodes === null ||
3503
- threeDSAuthDeclineCodes.includes(data.decline_code ?? '');
3672
+ // Without a shown challenge the customer saw no 3DS step: a decline is a plain decline.
3673
+ const authFailed = threeDSChallenged &&
3674
+ (threeDSAuthDeclineCodes === null ||
3675
+ threeDSAuthDeclineCodes.includes(data.decline_code ?? ''));
3504
3676
  return {
3505
3677
  threeDS: authFailed ? 'failed' : 'passed',
3506
3678
  result: {
3507
3679
  outcome: authFailed ? '3ds_failed' : 'declined',
3508
3680
  orderId,
3509
- threeDSChallenged: true,
3681
+ threeDSChallenged,
3510
3682
  ...declineFields(data),
3511
3683
  },
3512
3684
  };
@@ -3517,7 +3689,7 @@ function mapResumeResponse(response, orderId, threeDSAuthDeclineCodes = THREE_DS
3517
3689
  result: {
3518
3690
  outcome: 'error',
3519
3691
  orderId,
3520
- threeDSChallenged: true,
3692
+ threeDSChallenged,
3521
3693
  error: new APIError(data.checkout_status === 'cancelled'
3522
3694
  ? 'Payment was cancelled'
3523
3695
  : `Unhandled checkout status: ${data.checkout_status}`, null, { response }),
@@ -3525,30 +3697,30 @@ function mapResumeResponse(response, orderId, threeDSAuthDeclineCodes = THREE_DS
3525
3697
  };
3526
3698
  }
3527
3699
  }
3528
- function mapThreeDSRun(run, orderId) {
3700
+ function mapThreeDSRun(run, orderId, threeDSChallenged) {
3529
3701
  switch (run.kind) {
3530
3702
  case 'resumed':
3531
- return mapResumeResponse(run.response, orderId);
3703
+ return mapResumeResponse(run.response, orderId, threeDSChallenged);
3532
3704
  case 'failed':
3533
3705
  return {
3534
3706
  threeDS: 'failed',
3535
3707
  result: {
3536
3708
  outcome: '3ds_failed',
3537
3709
  orderId,
3538
- threeDSChallenged: true,
3710
+ threeDSChallenged,
3539
3711
  error: run.error,
3540
3712
  },
3541
3713
  };
3542
3714
  case 'abandoned':
3543
3715
  return {
3544
3716
  threeDS: 'abandoned',
3545
- result: { outcome: '3ds_abandoned', orderId, threeDSChallenged: true },
3717
+ result: { outcome: '3ds_abandoned', orderId, threeDSChallenged },
3546
3718
  };
3547
3719
  default: {
3548
3720
  const result = {
3549
3721
  outcome: 'error',
3550
3722
  orderId,
3551
- threeDSChallenged: true,
3723
+ threeDSChallenged,
3552
3724
  error: run.error,
3553
3725
  };
3554
3726
  if (run.failedRequest) {
@@ -3567,7 +3739,7 @@ function callHook(name, hook, info) {
3567
3739
  }
3568
3740
  catch (error) {
3569
3741
  // eslint-disable-next-line no-console
3570
- console.error(`[FunnelfoxSDK] silentPurchase ${name} hook threw`, error);
3742
+ console.error(`[FunnelfoxSDK] ${name} hook threw`, error);
3571
3743
  }
3572
3744
  }
3573
3745
  async function silentPurchaseDetailed(options) {
@@ -3577,7 +3749,7 @@ async function silentPurchaseDetailed(options) {
3577
3749
  }
3578
3750
  }
3579
3751
  const { orgId, baseUrl, externalId } = options;
3580
- const inFlightKey = `${orgId}\u0000${externalId}`;
3752
+ const inFlightKey = oneClickInFlightKey(orgId, externalId);
3581
3753
  if (oneClickInFlight.has(inFlightKey)) {
3582
3754
  return {
3583
3755
  outcome: 'error',
@@ -3611,9 +3783,14 @@ async function runSilentPurchaseDetailed(options) {
3611
3783
  timeout: DEFAULTS.REQUEST_TIMEOUT,
3612
3784
  retryAttempts: DEFAULTS.RETRY_ATTEMPTS,
3613
3785
  });
3786
+ const payload = buildOneClickRequest(options);
3787
+ const idempotencyKey = createIdempotencyKey();
3788
+ if (idempotencyKey) {
3789
+ payload.idempotency_key = idempotencyKey;
3790
+ }
3614
3791
  let response;
3615
3792
  try {
3616
- response = await apiClient.oneClickOnce(buildOneClickRequest(options));
3793
+ response = await postOneClick(apiClient, payload);
3617
3794
  }
3618
3795
  catch (error) {
3619
3796
  if (error instanceof APIError &&
@@ -3624,6 +3801,16 @@ async function runSilentPurchaseDetailed(options) {
3624
3801
  threeDSChallenged: false,
3625
3802
  };
3626
3803
  }
3804
+ if (idempotencyKey && isRetryableOneClickError(error)) {
3805
+ // The charge may have gone through: the caller must not start a new payment.
3806
+ return {
3807
+ outcome: 'processing',
3808
+ orderId: null,
3809
+ threeDSChallenged: false,
3810
+ error: error,
3811
+ failedRequest: 'one_click',
3812
+ };
3813
+ }
3627
3814
  return {
3628
3815
  outcome: 'error',
3629
3816
  orderId: null,
@@ -3637,15 +3824,15 @@ async function runSilentPurchaseDetailed(options) {
3637
3824
  return step.result;
3638
3825
  }
3639
3826
  const { orderId, actionToken } = step;
3827
+ let challenged = false;
3640
3828
  let ended = false;
3641
3829
  const end = (result) => {
3642
- if (ended) {
3830
+ if (!challenged || ended) {
3643
3831
  return;
3644
3832
  }
3645
3833
  ended = true;
3646
3834
  callHook('onThreeDSEnd', options.onThreeDSEnd, { result });
3647
3835
  };
3648
- callHook('onThreeDSStart', options.onThreeDSStart, { orderId });
3649
3836
  try {
3650
3837
  const run = await runOneClickThreeDS({
3651
3838
  apiClient,
@@ -3655,8 +3842,13 @@ async function runSilentPurchaseDetailed(options) {
3655
3842
  orderId,
3656
3843
  actionToken,
3657
3844
  timeoutMs: options.threeDSTimeoutMs ?? DEFAULT_THREE_DS_TIMEOUT_MS,
3845
+ revealDelayMs: THREE_DS_OVERLAY_REVEAL_DELAY_MS,
3846
+ onChallengeShown: () => {
3847
+ challenged = true;
3848
+ callHook('onThreeDSStart', options.onThreeDSStart, { orderId });
3849
+ },
3658
3850
  });
3659
- const mapped = mapThreeDSRun(run, orderId);
3851
+ const mapped = mapThreeDSRun(run, orderId, challenged);
3660
3852
  end(mapped.threeDS);
3661
3853
  return mapped.result;
3662
3854
  }
@@ -3665,7 +3857,7 @@ async function runSilentPurchaseDetailed(options) {
3665
3857
  return {
3666
3858
  outcome: 'error',
3667
3859
  orderId,
3668
- threeDSChallenged: true,
3860
+ threeDSChallenged: challenged,
3669
3861
  error: error instanceof Error
3670
3862
  ? error
3671
3863
  : new FunnefoxSDKError('One-click 3DS step failed', undefined, error),
@@ -3856,6 +4048,762 @@ async function getAvailableStripePaymentMethods(params) {
3856
4048
  : [exports.PaymentMethod.PAYMENT_CARD];
3857
4049
  }
3858
4050
 
4051
+ /**
4052
+ * @fileoverview One-click upsell confirmed in the Apple Pay / Google Pay sheet (FFB-829).
4053
+ *
4054
+ * Primer (PRMSUP-10609): a saved wallet token must not be charged as a customer-initiated
4055
+ * payment, so the customer confirms the upsell in the wallet sheet again and the backend charges
4056
+ * that fresh, single-use token. The button is rendered from a client session the backend prepares
4057
+ * for the upsell (`one_click_wallet_session`). Apple Pay opens its sheet only from the tap itself,
4058
+ * with no request in between, so the session is prepared when the screen loads and kept alive
4059
+ * until the tap.
4060
+ */
4061
+ const WALLET_SESSION_INVALID = 'wallet_session_invalid';
4062
+ const WALLETS = ['APPLE_PAY', 'GOOGLE_PAY'];
4063
+ const SESSION_REQUEST_TIMEOUT_MS = 15000;
4064
+ /** How long Primer may take to report the payment methods the device can show. */
4065
+ const METHODS_TIMEOUT_MS = 10000;
4066
+ /**
4067
+ * The session is prepared again this long before it expires. The backend hands back an unused
4068
+ * session only while it has at least 10 minutes to live, so 15 always yields a fresh one.
4069
+ */
4070
+ const REFRESH_BEFORE_EXPIRY_MS = 15 * 60 * 1000;
4071
+ /** A tap on a session with less left than this is refused and the session is replaced. */
4072
+ const TAP_MIN_REMAINING_MS = 60 * 1000;
4073
+ /** Bounds the refresh timer for a session shorter than the refresh margin; a tap still checks it. */
4074
+ const MIN_REFRESH_DELAY_MS = 60 * 1000;
4075
+ const DEFAULT_BUTTON_HEIGHT = 54;
4076
+ const DEFAULT_BUTTON_RADIUS = 28;
4077
+ /** The backend sends naive UTC timestamps; without a zone `Date.parse` would read local time. */
4078
+ function parseUtc(value) {
4079
+ const hasZone = /([zZ]|[+-]\d{2}:?\d{2})$/.test(value);
4080
+ return Date.parse(hasZone ? value : `${value}Z`);
4081
+ }
4082
+ function parseWalletSession(data) {
4083
+ const expiresAt = data.expires_at ? parseUtc(data.expires_at) : NaN;
4084
+ if (!WALLETS.includes(data.wallet) ||
4085
+ !data.client_token ||
4086
+ !data.session_id ||
4087
+ !data.order_id ||
4088
+ !Number.isFinite(expiresAt)) {
4089
+ throw new APIError('Invalid one_click_wallet_session response', null, {
4090
+ response: data,
4091
+ });
4092
+ }
4093
+ return {
4094
+ wallet: data.wallet,
4095
+ clientToken: data.client_token,
4096
+ sessionId: data.session_id,
4097
+ orderId: data.order_id,
4098
+ amount: data.amount ?? null,
4099
+ currency: data.currency ?? null,
4100
+ expiresAt,
4101
+ };
4102
+ }
4103
+ /** `null` = the customer's saved method is not a Primer wallet. */
4104
+ async function prepareSession(apiClient, options) {
4105
+ const response = await apiClient.oneClickWalletSession({
4106
+ pp_ident: options.priceId,
4107
+ external_id: options.externalId,
4108
+ client_metadata: options.clientMetadata || {},
4109
+ }, SESSION_REQUEST_TIMEOUT_MS);
4110
+ if (response?.status !== 'success' || !response.data) {
4111
+ throw new APIError('one_click_wallet_session failed', null, { response });
4112
+ }
4113
+ if (response.data.wallet === null) {
4114
+ return null;
4115
+ }
4116
+ return parseWalletSession(response.data);
4117
+ }
4118
+ /** Primer's wallet options for the requested style; a type the wallet lacks becomes `plain`. */
4119
+ function primerWalletOptions(wallet, style) {
4120
+ const buttonType = style.buttonType || 'plain';
4121
+ const buttonColor = style.buttonColor || 'black';
4122
+ if (wallet === 'APPLE_PAY') {
4123
+ return {
4124
+ applePay: {
4125
+ buttonType: buttonType === 'buy' ? 'buy' : 'plain',
4126
+ buttonStyle: buttonColor,
4127
+ },
4128
+ };
4129
+ }
4130
+ return {
4131
+ googlePay: {
4132
+ buttonType: buttonType === 'continue' ? 'plain' : buttonType,
4133
+ buttonColor: buttonColor === 'black' ? 'black' : 'white',
4134
+ buttonSizeMode: 'fill',
4135
+ },
4136
+ };
4137
+ }
4138
+ function toError(message, error) {
4139
+ if (error instanceof FunnefoxSDKError) {
4140
+ return error;
4141
+ }
4142
+ return new PrimerError(message, error);
4143
+ }
4144
+ function callSafely(fn) {
4145
+ try {
4146
+ fn();
4147
+ }
4148
+ catch {
4149
+ // Primer handler calls are best effort once the outcome is decided.
4150
+ }
4151
+ }
4152
+ function isApiErrorWithCode(error, code) {
4153
+ return (error instanceof APIError &&
4154
+ (error.errorCode === code ||
4155
+ getResponseErrorCodes(error.response).includes(code)));
4156
+ }
4157
+ /** One mounted wallet button and the attempts made with it. */
4158
+ class WalletUpsell {
4159
+ constructor(container, options, session) {
4160
+ this.container = container;
4161
+ this.options = options;
4162
+ this.rendered = null;
4163
+ this.generation = 0;
4164
+ this.destroyed = false;
4165
+ /** An outcome other than `cancelled` was reported: the button stays disabled. */
4166
+ this.finished = false;
4167
+ this.disabledByCaller = false;
4168
+ this.refreshing = null;
4169
+ this.refreshTimer = null;
4170
+ this.attemptRunning = false;
4171
+ this.tokenizeStarted = false;
4172
+ /** The wallet token reached us: from here the attempt ends only with the charge's answer. */
4173
+ this.charging = false;
4174
+ this.threeDS = null;
4175
+ this.onVisibilityChange = () => {
4176
+ if (document.visibilityState === 'visible' && this.expiresSoon()) {
4177
+ this.refresh();
4178
+ }
4179
+ };
4180
+ this.session = session;
4181
+ this.apiClient = WalletUpsell.apiClientFor(options);
4182
+ this.inFlightKey = oneClickInFlightKey(options.orgId, options.externalId);
4183
+ }
4184
+ static apiClientFor(options) {
4185
+ return new APIClient({
4186
+ baseUrl: options.baseUrl || defaultBaseUrl(),
4187
+ orgId: options.orgId,
4188
+ timeout: DEFAULTS.REQUEST_TIMEOUT,
4189
+ retryAttempts: DEFAULTS.RETRY_ATTEMPTS,
4190
+ });
4191
+ }
4192
+ /** Renders the button for the current session: `false` when the device cannot show the wallet. */
4193
+ async render() {
4194
+ const generation = ++this.generation;
4195
+ const session = this.session;
4196
+ const style = this.options.style || {};
4197
+ await new PrimerWrapper().ensurePrimerLoaded();
4198
+ let reportMethods = () => { };
4199
+ let methodsTimer = null;
4200
+ const methods = new Promise((resolve, reject) => {
4201
+ reportMethods = resolve;
4202
+ methodsTimer = setTimeout(() => reject(new PrimerError('Primer did not report the available payment methods')), METHODS_TIMEOUT_MS);
4203
+ }).finally(() => clearTimeout(methodsTimer));
4204
+ // A dedicated instance: the checkouts' HeadlessManager caches by client token, and a
4205
+ // remounted upsell gets the same token back, so the cache would hand out a headless whose
4206
+ // callbacks belong to a destroyed mount.
4207
+ const headless = await window.Primer.createHeadless(session.clientToken, {
4208
+ paymentHandling: PRIMER_DEFAULTS.PAYMENT_HANDLING,
4209
+ apiVersion: PRIMER_DEFAULTS.API_VERSION,
4210
+ ...primerWalletOptions(session.wallet, style),
4211
+ onAvailablePaymentMethodsLoad: (items) => reportMethods(items.map(item => item.type)),
4212
+ onTokenizeShouldStart: () => this.onTap(generation),
4213
+ onTokenizeStart: () => {
4214
+ if (generation === this.generation) {
4215
+ this.tokenizeStarted = true;
4216
+ }
4217
+ },
4218
+ onPaymentMethodAction: action => {
4219
+ if (action === 'PAYMENT_METHOD_UNSELECTED') {
4220
+ this.onSheetClosed(generation);
4221
+ }
4222
+ },
4223
+ onTokenizeSuccess: (data, handler) => this.onTokenized(generation, data, handler),
4224
+ onTokenizeError: (error) => this.onPrimerFailure(generation, 'Wallet tokenization failed', error),
4225
+ onResumeSuccess: (data, handler) => this.onResumed(generation, data, handler),
4226
+ onResumeError: (error) => this.onResumeError(generation, error),
4227
+ onCheckoutFail: (error) => this.onPrimerFailure(generation, 'Primer checkout failed', error),
4228
+ });
4229
+ await headless.start();
4230
+ const available = await methods;
4231
+ if (!available.includes(session.wallet)) {
4232
+ return false;
4233
+ }
4234
+ const manager = await headless.createPaymentMethodManager(session.wallet);
4235
+ if (!manager || typeof manager.createButton !== 'function') {
4236
+ throw new PrimerError(`No ${session.wallet} button manager`);
4237
+ }
4238
+ const rendered = this.mountButton(generation, manager.createButton(), session.wallet, style);
4239
+ try {
4240
+ await rendered.button.render(rendered.wrapper, {});
4241
+ if (session.wallet === 'APPLE_PAY' && rendered.nativeOverlay === null) {
4242
+ rendered.nativeOverlay = await this.overlayAppleType(rendered, style);
4243
+ }
4244
+ }
4245
+ catch (error) {
4246
+ this.removeButton(rendered);
4247
+ throw error;
4248
+ }
4249
+ if (this.destroyed || generation !== this.generation) {
4250
+ this.removeButton(rendered);
4251
+ return true;
4252
+ }
4253
+ const previous = this.rendered;
4254
+ this.rendered = rendered;
4255
+ if (previous) {
4256
+ this.removeButton(previous);
4257
+ }
4258
+ this.applyDisabled();
4259
+ this.scheduleRefresh();
4260
+ return true;
4261
+ }
4262
+ mountButton(generation, button, wallet, style) {
4263
+ // Primer does not size its wallet buttons (FFB-169), so the wrapper's rules do.
4264
+ const wrapper = document.createElement('div');
4265
+ wrapper.className = generateId('funnelfox-wallet-upsell');
4266
+ const height = style.height ?? DEFAULT_BUTTON_HEIGHT;
4267
+ const radius = style.borderRadius ?? DEFAULT_BUTTON_RADIUS;
4268
+ const styleEl = document.createElement('style');
4269
+ styleEl.textContent = [
4270
+ `.${wrapper.className}{width:100%!important}`,
4271
+ `.${wrapper.className} button{height:${height}px!important;border-radius:${radius}px!important}`,
4272
+ wallet === 'APPLE_PAY' && style.buttonType === 'continue'
4273
+ ? `.${wrapper.className} > button{opacity:0!important}`
4274
+ : '',
4275
+ ].join('\n');
4276
+ document.head.appendChild(styleEl);
4277
+ this.container.appendChild(wrapper);
4278
+ return { generation, button, wrapper, styleEl, nativeOverlay: null };
4279
+ }
4280
+ /** PRD-1426: WebKit draws only the legacy Apple Pay types, so `continue` uses Apple's element. */
4281
+ async overlayAppleType(rendered, style) {
4282
+ if (style.buttonType !== 'continue') {
4283
+ return null;
4284
+ }
4285
+ const overlay = await overlayNativeApplePayButton(rendered.wrapper, {
4286
+ buttonType: style.buttonType,
4287
+ buttonStyle: style.buttonColor || 'black',
4288
+ borderRadius: style.borderRadius ?? DEFAULT_BUTTON_RADIUS,
4289
+ });
4290
+ if (!overlay) {
4291
+ // Apple's element could not load: show Primer's own (plain) button.
4292
+ rendered.styleEl.textContent = rendered.styleEl.textContent.replace(`.${rendered.wrapper.className} > button{opacity:0!important}`, '');
4293
+ }
4294
+ return overlay;
4295
+ }
4296
+ removeButton(rendered) {
4297
+ callSafely(() => rendered.button.clean());
4298
+ rendered.nativeOverlay?.remove();
4299
+ rendered.wrapper.remove();
4300
+ rendered.styleEl.remove();
4301
+ }
4302
+ applyDisabled() {
4303
+ const rendered = this.rendered;
4304
+ if (!rendered) {
4305
+ return;
4306
+ }
4307
+ const disabled = this.finished || this.disabledByCaller;
4308
+ void Promise.resolve(rendered.button.setDisabled(disabled)).catch(() => { });
4309
+ if (rendered.nativeOverlay) {
4310
+ rendered.nativeOverlay.style.pointerEvents = disabled ? 'none' : '';
4311
+ rendered.nativeOverlay.style.opacity = disabled ? '0.5' : '';
4312
+ }
4313
+ }
4314
+ setDisabled(disabled) {
4315
+ this.disabledByCaller = disabled;
4316
+ this.applyDisabled();
4317
+ }
4318
+ destroy() {
4319
+ if (this.destroyed) {
4320
+ return;
4321
+ }
4322
+ this.destroyed = true;
4323
+ this.generation += 1;
4324
+ if (this.attemptRunning && !this.charging) {
4325
+ // Primer's callbacks for this mount are ignored from now on, so nothing else ends it.
4326
+ this.attemptRunning = false;
4327
+ oneClickInFlight.delete(this.inFlightKey);
4328
+ }
4329
+ this.clearRefresh();
4330
+ if (typeof document !== 'undefined') {
4331
+ document.removeEventListener('visibilitychange', this.onVisibilityChange);
4332
+ }
4333
+ if (this.rendered) {
4334
+ this.removeButton(this.rendered);
4335
+ this.rendered = null;
4336
+ }
4337
+ }
4338
+ // ---------- session life ----------
4339
+ watchVisibility() {
4340
+ if (typeof document !== 'undefined') {
4341
+ document.addEventListener('visibilitychange', this.onVisibilityChange);
4342
+ }
4343
+ }
4344
+ expiresSoon(minRemainingMs = REFRESH_BEFORE_EXPIRY_MS) {
4345
+ return this.session.expiresAt - Date.now() < minRemainingMs;
4346
+ }
4347
+ clearRefresh() {
4348
+ if (this.refreshTimer) {
4349
+ clearTimeout(this.refreshTimer);
4350
+ this.refreshTimer = null;
4351
+ }
4352
+ }
4353
+ scheduleRefresh() {
4354
+ this.clearRefresh();
4355
+ if (this.destroyed || this.finished) {
4356
+ return;
4357
+ }
4358
+ const delay = Math.max(this.session.expiresAt - REFRESH_BEFORE_EXPIRY_MS - Date.now(), MIN_REFRESH_DELAY_MS);
4359
+ this.refreshTimer = setTimeout(() => {
4360
+ this.refreshTimer = null;
4361
+ this.refresh();
4362
+ }, delay);
4363
+ }
4364
+ /** Replaces the session and the button before the session expires; never during an attempt. */
4365
+ refresh() {
4366
+ // An attempt ends either for good or as `cancelled`, which checks the session again.
4367
+ if (this.refreshing ||
4368
+ this.destroyed ||
4369
+ this.finished ||
4370
+ this.attemptRunning) {
4371
+ return;
4372
+ }
4373
+ this.refreshing = this.replaceSession().finally(() => {
4374
+ this.refreshing = null;
4375
+ });
4376
+ }
4377
+ async replaceSession() {
4378
+ let failure = null;
4379
+ try {
4380
+ const next = await prepareSession(this.apiClient, this.options);
4381
+ if (this.destroyed || this.finished) {
4382
+ return;
4383
+ }
4384
+ if (!next || next.wallet !== this.session.wallet) {
4385
+ failure = new FunnefoxSDKError('The wallet upsell is no longer available for this customer', 'wallet_upsell_unavailable');
4386
+ }
4387
+ else {
4388
+ this.session = next;
4389
+ if (!(await this.render())) {
4390
+ failure = new FunnefoxSDKError('This device can no longer show the wallet', 'wallet_upsell_unavailable');
4391
+ }
4392
+ }
4393
+ }
4394
+ catch (error) {
4395
+ failure = toError('Failed to prepare the wallet upsell again', error);
4396
+ }
4397
+ if (failure && !this.destroyed && !this.finished && !this.attemptRunning) {
4398
+ // The button can no longer charge: the caller takes its own path.
4399
+ this.report({
4400
+ outcome: 'error',
4401
+ orderId: null,
4402
+ threeDSChallenged: false,
4403
+ error: failure,
4404
+ });
4405
+ }
4406
+ }
4407
+ // ---------- attempt ----------
4408
+ onTap(generation) {
4409
+ if (generation !== this.generation ||
4410
+ this.destroyed ||
4411
+ this.finished ||
4412
+ this.disabledByCaller ||
4413
+ this.refreshing ||
4414
+ // Double tap, either wallet.
4415
+ this.attemptRunning ||
4416
+ oneClickInFlight.has(this.inFlightKey)) {
4417
+ return false;
4418
+ }
4419
+ if (this.expiresSoon(TAP_MIN_REMAINING_MS)) {
4420
+ // Apple Pay needs the tap itself to open the sheet: the customer taps the new button.
4421
+ this.refresh();
4422
+ return false;
4423
+ }
4424
+ this.attemptRunning = true;
4425
+ this.tokenizeStarted = false;
4426
+ oneClickInFlight.add(this.inFlightKey);
4427
+ callHook('onStart', this.options.onStart, undefined);
4428
+ return true;
4429
+ }
4430
+ onSheetClosed(generation) {
4431
+ if (generation !== this.generation ||
4432
+ !this.attemptRunning ||
4433
+ this.tokenizeStarted) {
4434
+ return;
4435
+ }
4436
+ this.finish({
4437
+ outcome: 'cancelled',
4438
+ orderId: null,
4439
+ threeDSChallenged: false,
4440
+ });
4441
+ }
4442
+ onPrimerFailure(generation, message, error) {
4443
+ if (generation !== this.generation || !this.attemptRunning) {
4444
+ return;
4445
+ }
4446
+ if (this.threeDS) {
4447
+ this.endThreeDS('failed');
4448
+ this.finish({
4449
+ outcome: '3ds_failed',
4450
+ orderId: this.session.orderId,
4451
+ threeDSChallenged: this.threeDSChallenged(),
4452
+ error: toError('3DS authentication failed', error),
4453
+ });
4454
+ return;
4455
+ }
4456
+ this.finish({
4457
+ outcome: 'error',
4458
+ orderId: null,
4459
+ threeDSChallenged: false,
4460
+ error: toError(message, error),
4461
+ });
4462
+ }
4463
+ onTokenized(generation, data, handler) {
4464
+ if (generation !== this.generation ||
4465
+ !this.attemptRunning ||
4466
+ this.threeDS) {
4467
+ callSafely(() => handler.handleFailure());
4468
+ return;
4469
+ }
4470
+ this.tokenizeStarted = true;
4471
+ this.charging = true;
4472
+ void this.charge(data.token, handler, false).catch(error => {
4473
+ callSafely(() => handler.handleFailure());
4474
+ this.finish({
4475
+ outcome: 'error',
4476
+ orderId: this.session.orderId,
4477
+ threeDSChallenged: false,
4478
+ error: toError('Wallet upsell charge failed', error),
4479
+ });
4480
+ });
4481
+ }
4482
+ async charge(paymentMethodToken, handler, retried) {
4483
+ const session = this.session;
4484
+ const payload = {
4485
+ pp_ident: this.options.priceId,
4486
+ external_id: this.options.externalId,
4487
+ client_metadata: (this.options.clientMetadata ||
4488
+ {}),
4489
+ payment_method_token: paymentMethodToken,
4490
+ session_id: session.sessionId,
4491
+ };
4492
+ const idempotencyKey = createIdempotencyKey();
4493
+ if (idempotencyKey) {
4494
+ payload.idempotency_key = idempotencyKey;
4495
+ }
4496
+ let response;
4497
+ try {
4498
+ response = await postOneClick(this.apiClient, payload);
4499
+ }
4500
+ catch (error) {
4501
+ if (!retried &&
4502
+ isApiErrorWithCode(error, WALLET_SESSION_INVALID) &&
4503
+ (await this.sameAmountSession())) {
4504
+ // Nothing was charged and the customer approved this very amount: one more try.
4505
+ return this.charge(paymentMethodToken, handler, true);
4506
+ }
4507
+ callSafely(() => handler.handleFailure());
4508
+ this.finish(this.chargeFailure(error, Boolean(idempotencyKey)));
4509
+ return;
4510
+ }
4511
+ const step = mapOneClickResponse(response);
4512
+ if (step.kind === 'result') {
4513
+ const result = step.result;
4514
+ if (result.outcome === 'succeeded' || result.outcome === 'processing') {
4515
+ callSafely(() => handler.handleSuccess());
4516
+ }
4517
+ else {
4518
+ callSafely(() => handler.handleFailure(result.failedMessageForUser || undefined));
4519
+ }
4520
+ this.finish(result);
4521
+ return;
4522
+ }
4523
+ this.startThreeDS(step.orderId || session.orderId, step.actionToken, handler);
4524
+ }
4525
+ /** A new session for the same amount the customer approved in the sheet. */
4526
+ async sameAmountSession() {
4527
+ try {
4528
+ const next = await prepareSession(this.apiClient, this.options);
4529
+ if (!next ||
4530
+ next.wallet !== this.session.wallet ||
4531
+ next.amount !== this.session.amount ||
4532
+ next.currency !== this.session.currency) {
4533
+ return false;
4534
+ }
4535
+ this.session = next;
4536
+ return true;
4537
+ }
4538
+ catch {
4539
+ return false;
4540
+ }
4541
+ }
4542
+ chargeFailure(error, keyed) {
4543
+ if (isApiErrorWithCode(error, DOUBLE_PURCHASE)) {
4544
+ return {
4545
+ outcome: 'already_purchased',
4546
+ orderId: null,
4547
+ threeDSChallenged: false,
4548
+ };
4549
+ }
4550
+ if (keyed && isRetryableOneClickError(error)) {
4551
+ // The charge may have gone through: the caller must not start a new payment.
4552
+ return {
4553
+ outcome: 'processing',
4554
+ orderId: this.session.orderId,
4555
+ threeDSChallenged: false,
4556
+ error: error,
4557
+ failedRequest: 'one_click',
4558
+ };
4559
+ }
4560
+ return {
4561
+ outcome: 'error',
4562
+ orderId: null,
4563
+ threeDSChallenged: false,
4564
+ error: error instanceof Error ? error : toError('one_click failed', error),
4565
+ failedRequest: 'one_click',
4566
+ };
4567
+ }
4568
+ // ---------- 3DS ----------
4569
+ threeDSChallenged() {
4570
+ return Boolean(this.threeDS?.challenged);
4571
+ }
4572
+ startThreeDS(orderId, actionToken, handler) {
4573
+ const intent = getPrimerTokenIntent(actionToken);
4574
+ if (!intent || !PRIMER_3DS_INTENTS.includes(intent)) {
4575
+ callSafely(() => handler.handleFailure());
4576
+ this.finish({
4577
+ outcome: 'error',
4578
+ orderId,
4579
+ threeDSChallenged: false,
4580
+ error: new PrimerError('Unsupported one-click action: the action token is not a Primer 3DS client token', { intent }),
4581
+ });
4582
+ return;
4583
+ }
4584
+ const timeoutMs = DEFAULT_THREE_DS_TIMEOUT_MS;
4585
+ const threeDS = {
4586
+ orderId,
4587
+ challenged: false,
4588
+ revealTimer: null,
4589
+ timer: null,
4590
+ showOverlay: hidePrimerOverlay(),
4591
+ };
4592
+ this.threeDS = threeDS;
4593
+ const onTimeout = () => {
4594
+ threeDS.timer = null;
4595
+ if (!threeDS.challenged) {
4596
+ // The overlay is about to be shown: the reveal restarts the timer.
4597
+ return;
4598
+ }
4599
+ this.endThreeDS('abandoned');
4600
+ this.finish({
4601
+ outcome: '3ds_abandoned',
4602
+ orderId,
4603
+ threeDSChallenged: true,
4604
+ });
4605
+ dismissPrimerOverlay();
4606
+ };
4607
+ threeDS.timer = setTimeout(onTimeout, timeoutMs);
4608
+ threeDS.revealTimer = setTimeout(() => {
4609
+ threeDS.revealTimer = null;
4610
+ threeDS.challenged = true;
4611
+ threeDS.showOverlay();
4612
+ warnIfOverlayNotFound();
4613
+ callHook('onThreeDSStart', this.options.onThreeDSStart, { orderId });
4614
+ if (threeDS.timer) {
4615
+ clearTimeout(threeDS.timer);
4616
+ }
4617
+ threeDS.timer = setTimeout(onTimeout, timeoutMs);
4618
+ }, THREE_DS_OVERLAY_REVEAL_DELAY_MS);
4619
+ handler.continueWithNewClientToken(actionToken);
4620
+ }
4621
+ /** Stops the 3DS timers; reports `onThreeDSEnd` once, and only after `onThreeDSStart`. */
4622
+ endThreeDS(result) {
4623
+ const threeDS = this.threeDS;
4624
+ if (!threeDS) {
4625
+ return;
4626
+ }
4627
+ if (threeDS.timer) {
4628
+ clearTimeout(threeDS.timer);
4629
+ threeDS.timer = null;
4630
+ }
4631
+ if (threeDS.revealTimer) {
4632
+ clearTimeout(threeDS.revealTimer);
4633
+ threeDS.revealTimer = null;
4634
+ }
4635
+ threeDS.showOverlay();
4636
+ if (threeDS.challenged) {
4637
+ callHook('onThreeDSEnd', this.options.onThreeDSEnd, { result });
4638
+ }
4639
+ }
4640
+ async onResumed(generation, data, handler) {
4641
+ const threeDS = this.threeDS;
4642
+ if (generation !== this.generation || !this.attemptRunning || !threeDS) {
4643
+ callSafely(() => handler.handleFailure());
4644
+ return;
4645
+ }
4646
+ // The challenge is over: the timeout bounds only the challenge, never the POST.
4647
+ if (threeDS.timer) {
4648
+ clearTimeout(threeDS.timer);
4649
+ threeDS.timer = null;
4650
+ }
4651
+ if (threeDS.revealTimer) {
4652
+ clearTimeout(threeDS.revealTimer);
4653
+ threeDS.revealTimer = null;
4654
+ }
4655
+ let response;
4656
+ try {
4657
+ response = await this.apiClient.resumePaymentOnce({
4658
+ orderId: threeDS.orderId,
4659
+ resumeToken: data.resumeToken,
4660
+ });
4661
+ }
4662
+ catch (error) {
4663
+ callSafely(() => handler.handleFailure());
4664
+ this.endThreeDS('error');
4665
+ this.finish({
4666
+ outcome: 'error',
4667
+ orderId: threeDS.orderId,
4668
+ threeDSChallenged: threeDS.challenged,
4669
+ error: error,
4670
+ failedRequest: 'resume_payment',
4671
+ });
4672
+ return;
4673
+ }
4674
+ const mapped = mapResumeResponse(response, threeDS.orderId, threeDS.challenged);
4675
+ if (mapped.result.outcome === 'succeeded' ||
4676
+ mapped.result.outcome === 'processing') {
4677
+ callSafely(() => handler.handleSuccess());
4678
+ }
4679
+ else {
4680
+ callSafely(() => handler.handleFailure(mapped.result.failedMessageForUser || undefined));
4681
+ }
4682
+ this.endThreeDS(mapped.threeDS);
4683
+ this.finish(mapped.result);
4684
+ }
4685
+ onResumeError(generation, error) {
4686
+ const threeDS = this.threeDS;
4687
+ if (generation !== this.generation || !this.attemptRunning || !threeDS) {
4688
+ return;
4689
+ }
4690
+ if (isThreeDSCloseError(error)) {
4691
+ this.endThreeDS('abandoned');
4692
+ this.finish({
4693
+ outcome: '3ds_abandoned',
4694
+ orderId: threeDS.orderId,
4695
+ threeDSChallenged: threeDS.challenged,
4696
+ });
4697
+ return;
4698
+ }
4699
+ this.endThreeDS('failed');
4700
+ this.finish({
4701
+ outcome: '3ds_failed',
4702
+ orderId: threeDS.orderId,
4703
+ threeDSChallenged: threeDS.challenged,
4704
+ error: toError('3DS authentication failed', error),
4705
+ });
4706
+ }
4707
+ // ---------- result ----------
4708
+ /** Ends the running attempt with its one result; later calls for it are ignored. */
4709
+ finish(result) {
4710
+ if (!this.attemptRunning) {
4711
+ return;
4712
+ }
4713
+ this.attemptRunning = false;
4714
+ this.tokenizeStarted = false;
4715
+ this.charging = false;
4716
+ this.threeDS = null;
4717
+ oneClickInFlight.delete(this.inFlightKey);
4718
+ this.report(result);
4719
+ }
4720
+ report(result) {
4721
+ if (result.outcome !== 'cancelled') {
4722
+ this.finished = true;
4723
+ this.clearRefresh();
4724
+ this.applyDisabled();
4725
+ }
4726
+ else if (this.expiresSoon()) {
4727
+ this.refresh();
4728
+ }
4729
+ if (result.outcome === 'error' && result.error) {
4730
+ const error = result.error;
4731
+ getErrorImage(this.options.orgId, {
4732
+ baseUrl: this.options.baseUrl || defaultBaseUrl(),
4733
+ message: error.message,
4734
+ code: error.code,
4735
+ req_id: error.response?.req_id,
4736
+ });
4737
+ }
4738
+ if (!this.destroyed) {
4739
+ callHook('onResult', this.options.onResult, result);
4740
+ }
4741
+ }
4742
+ }
4743
+ function validate(container, options) {
4744
+ if (typeof HTMLElement === 'undefined' ||
4745
+ !(container instanceof HTMLElement)) {
4746
+ throw new ValidationError('container', 'must be an HTMLElement', container);
4747
+ }
4748
+ for (const field of ['orgId', 'priceId', 'externalId']) {
4749
+ if (!options?.[field]) {
4750
+ throw new ValidationError(field, 'is required', options?.[field]);
4751
+ }
4752
+ }
4753
+ if (typeof options.onResult !== 'function') {
4754
+ throw new ValidationError('onResult', 'must be a function', options.onResult);
4755
+ }
4756
+ }
4757
+ /**
4758
+ * Mounts Primer's native Apple Pay / Google Pay button for a one-click upsell. Rejects only with
4759
+ * `ValidationError`; any `mounted: false` leaves nothing in `container`.
4760
+ */
4761
+ async function mountWalletUpsell(container, options) {
4762
+ validate(container, options);
4763
+ let session;
4764
+ try {
4765
+ session = await prepareSession(WalletUpsell.apiClientFor(options), options);
4766
+ }
4767
+ catch (error) {
4768
+ return {
4769
+ mounted: false,
4770
+ reason: 'error',
4771
+ error: error instanceof Error
4772
+ ? error
4773
+ : toError('one_click_wallet_session failed', error),
4774
+ };
4775
+ }
4776
+ if (!session) {
4777
+ return { mounted: false, reason: 'not_wallet' };
4778
+ }
4779
+ const upsell = new WalletUpsell(container, options, session);
4780
+ try {
4781
+ if (!(await upsell.render())) {
4782
+ upsell.destroy();
4783
+ return {
4784
+ mounted: false,
4785
+ reason: 'wallet_unavailable',
4786
+ wallet: session.wallet,
4787
+ };
4788
+ }
4789
+ }
4790
+ catch (error) {
4791
+ upsell.destroy();
4792
+ return {
4793
+ mounted: false,
4794
+ reason: 'error',
4795
+ error: toError('Failed to mount the wallet button', error),
4796
+ };
4797
+ }
4798
+ upsell.watchVisibility();
4799
+ return {
4800
+ mounted: true,
4801
+ wallet: session.wallet,
4802
+ setDisabled: (disabled) => upsell.setDisabled(disabled),
4803
+ destroy: () => upsell.destroy(),
4804
+ };
4805
+ }
4806
+
3859
4807
  /**
3860
4808
  * @fileoverview Main entry point for @funnelfox/billing
3861
4809
  */
@@ -3865,6 +4813,7 @@ const Billing = {
3865
4813
  createClientSession: createClientSession,
3866
4814
  initMethod: initMethod,
3867
4815
  silentPurchase: silentPurchase,
4816
+ mountWalletUpsell,
3868
4817
  getAvailablePaymentMethods: getAvailablePaymentMethods,
3869
4818
  stripe: {
3870
4819
  createCardForm: createStripeCardForm,
@@ -3897,5 +4846,6 @@ exports.createCheckout = createCheckout;
3897
4846
  exports.createClientSession = createClientSession;
3898
4847
  exports.getAvailablePaymentMethods = getAvailablePaymentMethods;
3899
4848
  exports.loadStripe = loadStripe;
4849
+ exports.mountWalletUpsell = mountWalletUpsell;
3900
4850
  exports.resolveTaxDisplay = resolveTaxDisplay;
3901
4851
  exports.toPaymentFailure = toPaymentFailure;