@funnelfox/billing 0.13.2 → 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.
@@ -559,7 +559,7 @@ var PaymentMethod;
559
559
  /**
560
560
  * @fileoverview Constants for Funnefox SDK
561
561
  */
562
- const SDK_VERSION = '0.13.2';
562
+ const SDK_VERSION = '0.14.0';
563
563
  const DEFAULTS = {
564
564
  BASE_URL: 'https://billing.funnelfox.com',
565
565
  REGION: 'default',
@@ -601,6 +601,7 @@ const API_ENDPOINTS = {
601
601
  CREATE_PAYMENT: '/v1/checkout/create_payment',
602
602
  RESUME_PAYMENT: '/v1/checkout/resume_payment',
603
603
  ONE_CLICK: '/v1/checkout/one_click',
604
+ ONE_CLICK_WALLET_SESSION: '/v1/checkout/one_click_wallet_session',
604
605
  CREATE_SIMPLE_CLIENT_SESSION: '/v1/checkout/create_simple_client_session',
605
606
  RECALCULATE_TAX: '/v1/checkout/recalculate_tax',
606
607
  };
@@ -804,7 +805,7 @@ async function overlayNativeApplePayButton(wrapper, options) {
804
805
  'height:100%',
805
806
  '--apple-pay-button-width:100%',
806
807
  '--apple-pay-button-height:100%',
807
- '--apple-pay-button-border-radius:28px',
808
+ `--apple-pay-button-border-radius:${options.borderRadius ?? 28}px`,
808
809
  'display:block',
809
810
  'cursor:pointer',
810
811
  'z-index:1',
@@ -1608,6 +1609,13 @@ class APIClient {
1608
1609
  body: JSON.stringify(payload),
1609
1610
  }, timeoutMs));
1610
1611
  }
1612
+ /** `one_click_wallet_session`: prepares the wallet re-auth button of a one-click upsell. */
1613
+ async oneClickWalletSession(payload, timeoutMs) {
1614
+ return (await this.requestOnce(API_ENDPOINTS.ONE_CLICK_WALLET_SESSION, {
1615
+ method: 'POST',
1616
+ body: JSON.stringify(payload),
1617
+ }, timeoutMs));
1618
+ }
1611
1619
  /** `resume_payment`, POSTed exactly once (see `requestOnce`). */
1612
1620
  async resumePaymentOnce(params) {
1613
1621
  return (await this.requestOnce(API_ENDPOINTS.RESUME_PAYMENT, {
@@ -3084,7 +3092,7 @@ function warnIfOverlayNotFound() {
3084
3092
  function toPrimerError(message, error) {
3085
3093
  return error instanceof PrimerError ? error : new PrimerError(message, error);
3086
3094
  }
3087
- function callSafely(fn) {
3095
+ function callSafely$1(fn) {
3088
3096
  try {
3089
3097
  fn();
3090
3098
  }
@@ -3167,7 +3175,7 @@ async function runOneClickThreeDS(params) {
3167
3175
  // A repeated tokenization would start a second reveal timer, so the challenge
3168
3176
  // (and the caller's onThreeDSStart) would be reported twice: refuse it.
3169
3177
  if (settled || tokenized) {
3170
- callSafely(() => handler.handleFailure());
3178
+ callSafely$1(() => handler.handleFailure());
3171
3179
  return;
3172
3180
  }
3173
3181
  tokenized = true;
@@ -3177,7 +3185,7 @@ async function runOneClickThreeDS(params) {
3177
3185
  revealed = true;
3178
3186
  showOverlay();
3179
3187
  warnIfOverlayNotFound();
3180
- callSafely(params.onChallengeShown);
3188
+ callSafely$1(params.onChallengeShown);
3181
3189
  // The whole timeout belongs to the challenge the customer can see.
3182
3190
  if (timer) {
3183
3191
  clearTimeout(timer);
@@ -3189,7 +3197,7 @@ async function runOneClickThreeDS(params) {
3189
3197
  };
3190
3198
  const onResumeSuccess = async (data, handler) => {
3191
3199
  if (settled) {
3192
- callSafely(() => handler.handleFailure());
3200
+ callSafely$1(() => handler.handleFailure());
3193
3201
  return;
3194
3202
  }
3195
3203
  // The challenge is over: the timeout bounds only the challenge, never the POST.
@@ -3209,7 +3217,7 @@ async function runOneClickThreeDS(params) {
3209
3217
  });
3210
3218
  }
3211
3219
  catch (error) {
3212
- callSafely(() => handler.handleFailure());
3220
+ callSafely$1(() => handler.handleFailure());
3213
3221
  settle({
3214
3222
  kind: 'error',
3215
3223
  error: error,
@@ -3221,11 +3229,11 @@ async function runOneClickThreeDS(params) {
3221
3229
  if (response?.status === 'success' &&
3222
3230
  resumeData?.checkout_status === 'succeeded' &&
3223
3231
  !resumeData.action_required_token) {
3224
- callSafely(() => handler.handleSuccess());
3232
+ callSafely$1(() => handler.handleSuccess());
3225
3233
  }
3226
3234
  else {
3227
3235
  // A chained action token is never continued (no second challenge).
3228
- callSafely(() => handler.handleFailure(resumeData?.failed_message_for_user || undefined));
3236
+ callSafely$1(() => handler.handleFailure(resumeData?.failed_message_for_user || undefined));
3229
3237
  }
3230
3238
  settle({ kind: 'resumed', response });
3231
3239
  };
@@ -3334,6 +3342,10 @@ let defaultConfig = null;
3334
3342
  function configure(config) {
3335
3343
  defaultConfig = config;
3336
3344
  }
3345
+ /** The base URL from `configure()`, else the production one. */
3346
+ function defaultBaseUrl() {
3347
+ return defaultConfig?.baseUrl || DEFAULTS.BASE_URL;
3348
+ }
3337
3349
  function resolveConfig(options, functionName) {
3338
3350
  const { orgId, apiConfig } = options || {};
3339
3351
  const finalOrgId = orgId || defaultConfig?.orgId;
@@ -3408,9 +3420,6 @@ function buildOneClickRequest(options) {
3408
3420
  if (options.citCardNetworks !== undefined) {
3409
3421
  payload.cit_card_networks = options.citCardNetworks;
3410
3422
  }
3411
- if (options.citGooglePayPanOnly !== undefined) {
3412
- payload.cit_google_pay_pan_only = options.citGooglePayPanOnly;
3413
- }
3414
3423
  return payload;
3415
3424
  }
3416
3425
  function silentPurchase(options) {
@@ -3458,7 +3467,11 @@ const IDEMPOTENCY_KEY_IN_PROGRESS = 'idempotency_key_in_progress';
3458
3467
  const ONE_CLICK_RETRY_DELAYS_MS = [1000, 2000, 4000];
3459
3468
  /** Longer than the backend's wait for the user's lock (~12.6 s). */
3460
3469
  const ONE_CLICK_TIMEOUT_MS = 25000;
3470
+ /** org + external id of the customers with a one-click purchase running (silent or wallet). */
3461
3471
  const oneClickInFlight = new Set();
3472
+ function oneClickInFlightKey(orgId, externalId) {
3473
+ return `${orgId}\u0000${externalId}`;
3474
+ }
3462
3475
  /** A random UUID v4, or `null` when the browser has no crypto (then one_click is not retried). */
3463
3476
  function createIdempotencyKey() {
3464
3477
  const cryptoApi = typeof crypto === 'undefined' ? undefined : crypto;
@@ -3724,7 +3737,7 @@ function callHook(name, hook, info) {
3724
3737
  }
3725
3738
  catch (error) {
3726
3739
  // eslint-disable-next-line no-console
3727
- console.error(`[FunnelfoxSDK] silentPurchase ${name} hook threw`, error);
3740
+ console.error(`[FunnelfoxSDK] ${name} hook threw`, error);
3728
3741
  }
3729
3742
  }
3730
3743
  async function silentPurchaseDetailed(options) {
@@ -3734,7 +3747,7 @@ async function silentPurchaseDetailed(options) {
3734
3747
  }
3735
3748
  }
3736
3749
  const { orgId, baseUrl, externalId } = options;
3737
- const inFlightKey = `${orgId}\u0000${externalId}`;
3750
+ const inFlightKey = oneClickInFlightKey(orgId, externalId);
3738
3751
  if (oneClickInFlight.has(inFlightKey)) {
3739
3752
  return {
3740
3753
  outcome: 'error',
@@ -4033,6 +4046,762 @@ async function getAvailableStripePaymentMethods(params) {
4033
4046
  : [PaymentMethod.PAYMENT_CARD];
4034
4047
  }
4035
4048
 
4049
+ /**
4050
+ * @fileoverview One-click upsell confirmed in the Apple Pay / Google Pay sheet (FFB-829).
4051
+ *
4052
+ * Primer (PRMSUP-10609): a saved wallet token must not be charged as a customer-initiated
4053
+ * payment, so the customer confirms the upsell in the wallet sheet again and the backend charges
4054
+ * that fresh, single-use token. The button is rendered from a client session the backend prepares
4055
+ * for the upsell (`one_click_wallet_session`). Apple Pay opens its sheet only from the tap itself,
4056
+ * with no request in between, so the session is prepared when the screen loads and kept alive
4057
+ * until the tap.
4058
+ */
4059
+ const WALLET_SESSION_INVALID = 'wallet_session_invalid';
4060
+ const WALLETS = ['APPLE_PAY', 'GOOGLE_PAY'];
4061
+ const SESSION_REQUEST_TIMEOUT_MS = 15000;
4062
+ /** How long Primer may take to report the payment methods the device can show. */
4063
+ const METHODS_TIMEOUT_MS = 10000;
4064
+ /**
4065
+ * The session is prepared again this long before it expires. The backend hands back an unused
4066
+ * session only while it has at least 10 minutes to live, so 15 always yields a fresh one.
4067
+ */
4068
+ const REFRESH_BEFORE_EXPIRY_MS = 15 * 60 * 1000;
4069
+ /** A tap on a session with less left than this is refused and the session is replaced. */
4070
+ const TAP_MIN_REMAINING_MS = 60 * 1000;
4071
+ /** Bounds the refresh timer for a session shorter than the refresh margin; a tap still checks it. */
4072
+ const MIN_REFRESH_DELAY_MS = 60 * 1000;
4073
+ const DEFAULT_BUTTON_HEIGHT = 54;
4074
+ const DEFAULT_BUTTON_RADIUS = 28;
4075
+ /** The backend sends naive UTC timestamps; without a zone `Date.parse` would read local time. */
4076
+ function parseUtc(value) {
4077
+ const hasZone = /([zZ]|[+-]\d{2}:?\d{2})$/.test(value);
4078
+ return Date.parse(hasZone ? value : `${value}Z`);
4079
+ }
4080
+ function parseWalletSession(data) {
4081
+ const expiresAt = data.expires_at ? parseUtc(data.expires_at) : NaN;
4082
+ if (!WALLETS.includes(data.wallet) ||
4083
+ !data.client_token ||
4084
+ !data.session_id ||
4085
+ !data.order_id ||
4086
+ !Number.isFinite(expiresAt)) {
4087
+ throw new APIError('Invalid one_click_wallet_session response', null, {
4088
+ response: data,
4089
+ });
4090
+ }
4091
+ return {
4092
+ wallet: data.wallet,
4093
+ clientToken: data.client_token,
4094
+ sessionId: data.session_id,
4095
+ orderId: data.order_id,
4096
+ amount: data.amount ?? null,
4097
+ currency: data.currency ?? null,
4098
+ expiresAt,
4099
+ };
4100
+ }
4101
+ /** `null` = the customer's saved method is not a Primer wallet. */
4102
+ async function prepareSession(apiClient, options) {
4103
+ const response = await apiClient.oneClickWalletSession({
4104
+ pp_ident: options.priceId,
4105
+ external_id: options.externalId,
4106
+ client_metadata: options.clientMetadata || {},
4107
+ }, SESSION_REQUEST_TIMEOUT_MS);
4108
+ if (response?.status !== 'success' || !response.data) {
4109
+ throw new APIError('one_click_wallet_session failed', null, { response });
4110
+ }
4111
+ if (response.data.wallet === null) {
4112
+ return null;
4113
+ }
4114
+ return parseWalletSession(response.data);
4115
+ }
4116
+ /** Primer's wallet options for the requested style; a type the wallet lacks becomes `plain`. */
4117
+ function primerWalletOptions(wallet, style) {
4118
+ const buttonType = style.buttonType || 'plain';
4119
+ const buttonColor = style.buttonColor || 'black';
4120
+ if (wallet === 'APPLE_PAY') {
4121
+ return {
4122
+ applePay: {
4123
+ buttonType: buttonType === 'buy' ? 'buy' : 'plain',
4124
+ buttonStyle: buttonColor,
4125
+ },
4126
+ };
4127
+ }
4128
+ return {
4129
+ googlePay: {
4130
+ buttonType: buttonType === 'continue' ? 'plain' : buttonType,
4131
+ buttonColor: buttonColor === 'black' ? 'black' : 'white',
4132
+ buttonSizeMode: 'fill',
4133
+ },
4134
+ };
4135
+ }
4136
+ function toError(message, error) {
4137
+ if (error instanceof FunnefoxSDKError) {
4138
+ return error;
4139
+ }
4140
+ return new PrimerError(message, error);
4141
+ }
4142
+ function callSafely(fn) {
4143
+ try {
4144
+ fn();
4145
+ }
4146
+ catch {
4147
+ // Primer handler calls are best effort once the outcome is decided.
4148
+ }
4149
+ }
4150
+ function isApiErrorWithCode(error, code) {
4151
+ return (error instanceof APIError &&
4152
+ (error.errorCode === code ||
4153
+ getResponseErrorCodes(error.response).includes(code)));
4154
+ }
4155
+ /** One mounted wallet button and the attempts made with it. */
4156
+ class WalletUpsell {
4157
+ constructor(container, options, session) {
4158
+ this.container = container;
4159
+ this.options = options;
4160
+ this.rendered = null;
4161
+ this.generation = 0;
4162
+ this.destroyed = false;
4163
+ /** An outcome other than `cancelled` was reported: the button stays disabled. */
4164
+ this.finished = false;
4165
+ this.disabledByCaller = false;
4166
+ this.refreshing = null;
4167
+ this.refreshTimer = null;
4168
+ this.attemptRunning = false;
4169
+ this.tokenizeStarted = false;
4170
+ /** The wallet token reached us: from here the attempt ends only with the charge's answer. */
4171
+ this.charging = false;
4172
+ this.threeDS = null;
4173
+ this.onVisibilityChange = () => {
4174
+ if (document.visibilityState === 'visible' && this.expiresSoon()) {
4175
+ this.refresh();
4176
+ }
4177
+ };
4178
+ this.session = session;
4179
+ this.apiClient = WalletUpsell.apiClientFor(options);
4180
+ this.inFlightKey = oneClickInFlightKey(options.orgId, options.externalId);
4181
+ }
4182
+ static apiClientFor(options) {
4183
+ return new APIClient({
4184
+ baseUrl: options.baseUrl || defaultBaseUrl(),
4185
+ orgId: options.orgId,
4186
+ timeout: DEFAULTS.REQUEST_TIMEOUT,
4187
+ retryAttempts: DEFAULTS.RETRY_ATTEMPTS,
4188
+ });
4189
+ }
4190
+ /** Renders the button for the current session: `false` when the device cannot show the wallet. */
4191
+ async render() {
4192
+ const generation = ++this.generation;
4193
+ const session = this.session;
4194
+ const style = this.options.style || {};
4195
+ await new PrimerWrapper().ensurePrimerLoaded();
4196
+ let reportMethods = () => { };
4197
+ let methodsTimer = null;
4198
+ const methods = new Promise((resolve, reject) => {
4199
+ reportMethods = resolve;
4200
+ methodsTimer = setTimeout(() => reject(new PrimerError('Primer did not report the available payment methods')), METHODS_TIMEOUT_MS);
4201
+ }).finally(() => clearTimeout(methodsTimer));
4202
+ // A dedicated instance: the checkouts' HeadlessManager caches by client token, and a
4203
+ // remounted upsell gets the same token back, so the cache would hand out a headless whose
4204
+ // callbacks belong to a destroyed mount.
4205
+ const headless = await window.Primer.createHeadless(session.clientToken, {
4206
+ paymentHandling: PRIMER_DEFAULTS.PAYMENT_HANDLING,
4207
+ apiVersion: PRIMER_DEFAULTS.API_VERSION,
4208
+ ...primerWalletOptions(session.wallet, style),
4209
+ onAvailablePaymentMethodsLoad: (items) => reportMethods(items.map(item => item.type)),
4210
+ onTokenizeShouldStart: () => this.onTap(generation),
4211
+ onTokenizeStart: () => {
4212
+ if (generation === this.generation) {
4213
+ this.tokenizeStarted = true;
4214
+ }
4215
+ },
4216
+ onPaymentMethodAction: action => {
4217
+ if (action === 'PAYMENT_METHOD_UNSELECTED') {
4218
+ this.onSheetClosed(generation);
4219
+ }
4220
+ },
4221
+ onTokenizeSuccess: (data, handler) => this.onTokenized(generation, data, handler),
4222
+ onTokenizeError: (error) => this.onPrimerFailure(generation, 'Wallet tokenization failed', error),
4223
+ onResumeSuccess: (data, handler) => this.onResumed(generation, data, handler),
4224
+ onResumeError: (error) => this.onResumeError(generation, error),
4225
+ onCheckoutFail: (error) => this.onPrimerFailure(generation, 'Primer checkout failed', error),
4226
+ });
4227
+ await headless.start();
4228
+ const available = await methods;
4229
+ if (!available.includes(session.wallet)) {
4230
+ return false;
4231
+ }
4232
+ const manager = await headless.createPaymentMethodManager(session.wallet);
4233
+ if (!manager || typeof manager.createButton !== 'function') {
4234
+ throw new PrimerError(`No ${session.wallet} button manager`);
4235
+ }
4236
+ const rendered = this.mountButton(generation, manager.createButton(), session.wallet, style);
4237
+ try {
4238
+ await rendered.button.render(rendered.wrapper, {});
4239
+ if (session.wallet === 'APPLE_PAY' && rendered.nativeOverlay === null) {
4240
+ rendered.nativeOverlay = await this.overlayAppleType(rendered, style);
4241
+ }
4242
+ }
4243
+ catch (error) {
4244
+ this.removeButton(rendered);
4245
+ throw error;
4246
+ }
4247
+ if (this.destroyed || generation !== this.generation) {
4248
+ this.removeButton(rendered);
4249
+ return true;
4250
+ }
4251
+ const previous = this.rendered;
4252
+ this.rendered = rendered;
4253
+ if (previous) {
4254
+ this.removeButton(previous);
4255
+ }
4256
+ this.applyDisabled();
4257
+ this.scheduleRefresh();
4258
+ return true;
4259
+ }
4260
+ mountButton(generation, button, wallet, style) {
4261
+ // Primer does not size its wallet buttons (FFB-169), so the wrapper's rules do.
4262
+ const wrapper = document.createElement('div');
4263
+ wrapper.className = generateId('funnelfox-wallet-upsell');
4264
+ const height = style.height ?? DEFAULT_BUTTON_HEIGHT;
4265
+ const radius = style.borderRadius ?? DEFAULT_BUTTON_RADIUS;
4266
+ const styleEl = document.createElement('style');
4267
+ styleEl.textContent = [
4268
+ `.${wrapper.className}{width:100%!important}`,
4269
+ `.${wrapper.className} button{height:${height}px!important;border-radius:${radius}px!important}`,
4270
+ wallet === 'APPLE_PAY' && style.buttonType === 'continue'
4271
+ ? `.${wrapper.className} > button{opacity:0!important}`
4272
+ : '',
4273
+ ].join('\n');
4274
+ document.head.appendChild(styleEl);
4275
+ this.container.appendChild(wrapper);
4276
+ return { generation, button, wrapper, styleEl, nativeOverlay: null };
4277
+ }
4278
+ /** PRD-1426: WebKit draws only the legacy Apple Pay types, so `continue` uses Apple's element. */
4279
+ async overlayAppleType(rendered, style) {
4280
+ if (style.buttonType !== 'continue') {
4281
+ return null;
4282
+ }
4283
+ const overlay = await overlayNativeApplePayButton(rendered.wrapper, {
4284
+ buttonType: style.buttonType,
4285
+ buttonStyle: style.buttonColor || 'black',
4286
+ borderRadius: style.borderRadius ?? DEFAULT_BUTTON_RADIUS,
4287
+ });
4288
+ if (!overlay) {
4289
+ // Apple's element could not load: show Primer's own (plain) button.
4290
+ rendered.styleEl.textContent = rendered.styleEl.textContent.replace(`.${rendered.wrapper.className} > button{opacity:0!important}`, '');
4291
+ }
4292
+ return overlay;
4293
+ }
4294
+ removeButton(rendered) {
4295
+ callSafely(() => rendered.button.clean());
4296
+ rendered.nativeOverlay?.remove();
4297
+ rendered.wrapper.remove();
4298
+ rendered.styleEl.remove();
4299
+ }
4300
+ applyDisabled() {
4301
+ const rendered = this.rendered;
4302
+ if (!rendered) {
4303
+ return;
4304
+ }
4305
+ const disabled = this.finished || this.disabledByCaller;
4306
+ void Promise.resolve(rendered.button.setDisabled(disabled)).catch(() => { });
4307
+ if (rendered.nativeOverlay) {
4308
+ rendered.nativeOverlay.style.pointerEvents = disabled ? 'none' : '';
4309
+ rendered.nativeOverlay.style.opacity = disabled ? '0.5' : '';
4310
+ }
4311
+ }
4312
+ setDisabled(disabled) {
4313
+ this.disabledByCaller = disabled;
4314
+ this.applyDisabled();
4315
+ }
4316
+ destroy() {
4317
+ if (this.destroyed) {
4318
+ return;
4319
+ }
4320
+ this.destroyed = true;
4321
+ this.generation += 1;
4322
+ if (this.attemptRunning && !this.charging) {
4323
+ // Primer's callbacks for this mount are ignored from now on, so nothing else ends it.
4324
+ this.attemptRunning = false;
4325
+ oneClickInFlight.delete(this.inFlightKey);
4326
+ }
4327
+ this.clearRefresh();
4328
+ if (typeof document !== 'undefined') {
4329
+ document.removeEventListener('visibilitychange', this.onVisibilityChange);
4330
+ }
4331
+ if (this.rendered) {
4332
+ this.removeButton(this.rendered);
4333
+ this.rendered = null;
4334
+ }
4335
+ }
4336
+ // ---------- session life ----------
4337
+ watchVisibility() {
4338
+ if (typeof document !== 'undefined') {
4339
+ document.addEventListener('visibilitychange', this.onVisibilityChange);
4340
+ }
4341
+ }
4342
+ expiresSoon(minRemainingMs = REFRESH_BEFORE_EXPIRY_MS) {
4343
+ return this.session.expiresAt - Date.now() < minRemainingMs;
4344
+ }
4345
+ clearRefresh() {
4346
+ if (this.refreshTimer) {
4347
+ clearTimeout(this.refreshTimer);
4348
+ this.refreshTimer = null;
4349
+ }
4350
+ }
4351
+ scheduleRefresh() {
4352
+ this.clearRefresh();
4353
+ if (this.destroyed || this.finished) {
4354
+ return;
4355
+ }
4356
+ const delay = Math.max(this.session.expiresAt - REFRESH_BEFORE_EXPIRY_MS - Date.now(), MIN_REFRESH_DELAY_MS);
4357
+ this.refreshTimer = setTimeout(() => {
4358
+ this.refreshTimer = null;
4359
+ this.refresh();
4360
+ }, delay);
4361
+ }
4362
+ /** Replaces the session and the button before the session expires; never during an attempt. */
4363
+ refresh() {
4364
+ // An attempt ends either for good or as `cancelled`, which checks the session again.
4365
+ if (this.refreshing ||
4366
+ this.destroyed ||
4367
+ this.finished ||
4368
+ this.attemptRunning) {
4369
+ return;
4370
+ }
4371
+ this.refreshing = this.replaceSession().finally(() => {
4372
+ this.refreshing = null;
4373
+ });
4374
+ }
4375
+ async replaceSession() {
4376
+ let failure = null;
4377
+ try {
4378
+ const next = await prepareSession(this.apiClient, this.options);
4379
+ if (this.destroyed || this.finished) {
4380
+ return;
4381
+ }
4382
+ if (!next || next.wallet !== this.session.wallet) {
4383
+ failure = new FunnefoxSDKError('The wallet upsell is no longer available for this customer', 'wallet_upsell_unavailable');
4384
+ }
4385
+ else {
4386
+ this.session = next;
4387
+ if (!(await this.render())) {
4388
+ failure = new FunnefoxSDKError('This device can no longer show the wallet', 'wallet_upsell_unavailable');
4389
+ }
4390
+ }
4391
+ }
4392
+ catch (error) {
4393
+ failure = toError('Failed to prepare the wallet upsell again', error);
4394
+ }
4395
+ if (failure && !this.destroyed && !this.finished && !this.attemptRunning) {
4396
+ // The button can no longer charge: the caller takes its own path.
4397
+ this.report({
4398
+ outcome: 'error',
4399
+ orderId: null,
4400
+ threeDSChallenged: false,
4401
+ error: failure,
4402
+ });
4403
+ }
4404
+ }
4405
+ // ---------- attempt ----------
4406
+ onTap(generation) {
4407
+ if (generation !== this.generation ||
4408
+ this.destroyed ||
4409
+ this.finished ||
4410
+ this.disabledByCaller ||
4411
+ this.refreshing ||
4412
+ // Double tap, either wallet.
4413
+ this.attemptRunning ||
4414
+ oneClickInFlight.has(this.inFlightKey)) {
4415
+ return false;
4416
+ }
4417
+ if (this.expiresSoon(TAP_MIN_REMAINING_MS)) {
4418
+ // Apple Pay needs the tap itself to open the sheet: the customer taps the new button.
4419
+ this.refresh();
4420
+ return false;
4421
+ }
4422
+ this.attemptRunning = true;
4423
+ this.tokenizeStarted = false;
4424
+ oneClickInFlight.add(this.inFlightKey);
4425
+ callHook('onStart', this.options.onStart, undefined);
4426
+ return true;
4427
+ }
4428
+ onSheetClosed(generation) {
4429
+ if (generation !== this.generation ||
4430
+ !this.attemptRunning ||
4431
+ this.tokenizeStarted) {
4432
+ return;
4433
+ }
4434
+ this.finish({
4435
+ outcome: 'cancelled',
4436
+ orderId: null,
4437
+ threeDSChallenged: false,
4438
+ });
4439
+ }
4440
+ onPrimerFailure(generation, message, error) {
4441
+ if (generation !== this.generation || !this.attemptRunning) {
4442
+ return;
4443
+ }
4444
+ if (this.threeDS) {
4445
+ this.endThreeDS('failed');
4446
+ this.finish({
4447
+ outcome: '3ds_failed',
4448
+ orderId: this.session.orderId,
4449
+ threeDSChallenged: this.threeDSChallenged(),
4450
+ error: toError('3DS authentication failed', error),
4451
+ });
4452
+ return;
4453
+ }
4454
+ this.finish({
4455
+ outcome: 'error',
4456
+ orderId: null,
4457
+ threeDSChallenged: false,
4458
+ error: toError(message, error),
4459
+ });
4460
+ }
4461
+ onTokenized(generation, data, handler) {
4462
+ if (generation !== this.generation ||
4463
+ !this.attemptRunning ||
4464
+ this.threeDS) {
4465
+ callSafely(() => handler.handleFailure());
4466
+ return;
4467
+ }
4468
+ this.tokenizeStarted = true;
4469
+ this.charging = true;
4470
+ void this.charge(data.token, handler, false).catch(error => {
4471
+ callSafely(() => handler.handleFailure());
4472
+ this.finish({
4473
+ outcome: 'error',
4474
+ orderId: this.session.orderId,
4475
+ threeDSChallenged: false,
4476
+ error: toError('Wallet upsell charge failed', error),
4477
+ });
4478
+ });
4479
+ }
4480
+ async charge(paymentMethodToken, handler, retried) {
4481
+ const session = this.session;
4482
+ const payload = {
4483
+ pp_ident: this.options.priceId,
4484
+ external_id: this.options.externalId,
4485
+ client_metadata: (this.options.clientMetadata ||
4486
+ {}),
4487
+ payment_method_token: paymentMethodToken,
4488
+ session_id: session.sessionId,
4489
+ };
4490
+ const idempotencyKey = createIdempotencyKey();
4491
+ if (idempotencyKey) {
4492
+ payload.idempotency_key = idempotencyKey;
4493
+ }
4494
+ let response;
4495
+ try {
4496
+ response = await postOneClick(this.apiClient, payload);
4497
+ }
4498
+ catch (error) {
4499
+ if (!retried &&
4500
+ isApiErrorWithCode(error, WALLET_SESSION_INVALID) &&
4501
+ (await this.sameAmountSession())) {
4502
+ // Nothing was charged and the customer approved this very amount: one more try.
4503
+ return this.charge(paymentMethodToken, handler, true);
4504
+ }
4505
+ callSafely(() => handler.handleFailure());
4506
+ this.finish(this.chargeFailure(error, Boolean(idempotencyKey)));
4507
+ return;
4508
+ }
4509
+ const step = mapOneClickResponse(response);
4510
+ if (step.kind === 'result') {
4511
+ const result = step.result;
4512
+ if (result.outcome === 'succeeded' || result.outcome === 'processing') {
4513
+ callSafely(() => handler.handleSuccess());
4514
+ }
4515
+ else {
4516
+ callSafely(() => handler.handleFailure(result.failedMessageForUser || undefined));
4517
+ }
4518
+ this.finish(result);
4519
+ return;
4520
+ }
4521
+ this.startThreeDS(step.orderId || session.orderId, step.actionToken, handler);
4522
+ }
4523
+ /** A new session for the same amount the customer approved in the sheet. */
4524
+ async sameAmountSession() {
4525
+ try {
4526
+ const next = await prepareSession(this.apiClient, this.options);
4527
+ if (!next ||
4528
+ next.wallet !== this.session.wallet ||
4529
+ next.amount !== this.session.amount ||
4530
+ next.currency !== this.session.currency) {
4531
+ return false;
4532
+ }
4533
+ this.session = next;
4534
+ return true;
4535
+ }
4536
+ catch {
4537
+ return false;
4538
+ }
4539
+ }
4540
+ chargeFailure(error, keyed) {
4541
+ if (isApiErrorWithCode(error, DOUBLE_PURCHASE)) {
4542
+ return {
4543
+ outcome: 'already_purchased',
4544
+ orderId: null,
4545
+ threeDSChallenged: false,
4546
+ };
4547
+ }
4548
+ if (keyed && isRetryableOneClickError(error)) {
4549
+ // The charge may have gone through: the caller must not start a new payment.
4550
+ return {
4551
+ outcome: 'processing',
4552
+ orderId: this.session.orderId,
4553
+ threeDSChallenged: false,
4554
+ error: error,
4555
+ failedRequest: 'one_click',
4556
+ };
4557
+ }
4558
+ return {
4559
+ outcome: 'error',
4560
+ orderId: null,
4561
+ threeDSChallenged: false,
4562
+ error: error instanceof Error ? error : toError('one_click failed', error),
4563
+ failedRequest: 'one_click',
4564
+ };
4565
+ }
4566
+ // ---------- 3DS ----------
4567
+ threeDSChallenged() {
4568
+ return Boolean(this.threeDS?.challenged);
4569
+ }
4570
+ startThreeDS(orderId, actionToken, handler) {
4571
+ const intent = getPrimerTokenIntent(actionToken);
4572
+ if (!intent || !PRIMER_3DS_INTENTS.includes(intent)) {
4573
+ callSafely(() => handler.handleFailure());
4574
+ this.finish({
4575
+ outcome: 'error',
4576
+ orderId,
4577
+ threeDSChallenged: false,
4578
+ error: new PrimerError('Unsupported one-click action: the action token is not a Primer 3DS client token', { intent }),
4579
+ });
4580
+ return;
4581
+ }
4582
+ const timeoutMs = DEFAULT_THREE_DS_TIMEOUT_MS;
4583
+ const threeDS = {
4584
+ orderId,
4585
+ challenged: false,
4586
+ revealTimer: null,
4587
+ timer: null,
4588
+ showOverlay: hidePrimerOverlay(),
4589
+ };
4590
+ this.threeDS = threeDS;
4591
+ const onTimeout = () => {
4592
+ threeDS.timer = null;
4593
+ if (!threeDS.challenged) {
4594
+ // The overlay is about to be shown: the reveal restarts the timer.
4595
+ return;
4596
+ }
4597
+ this.endThreeDS('abandoned');
4598
+ this.finish({
4599
+ outcome: '3ds_abandoned',
4600
+ orderId,
4601
+ threeDSChallenged: true,
4602
+ });
4603
+ dismissPrimerOverlay();
4604
+ };
4605
+ threeDS.timer = setTimeout(onTimeout, timeoutMs);
4606
+ threeDS.revealTimer = setTimeout(() => {
4607
+ threeDS.revealTimer = null;
4608
+ threeDS.challenged = true;
4609
+ threeDS.showOverlay();
4610
+ warnIfOverlayNotFound();
4611
+ callHook('onThreeDSStart', this.options.onThreeDSStart, { orderId });
4612
+ if (threeDS.timer) {
4613
+ clearTimeout(threeDS.timer);
4614
+ }
4615
+ threeDS.timer = setTimeout(onTimeout, timeoutMs);
4616
+ }, THREE_DS_OVERLAY_REVEAL_DELAY_MS);
4617
+ handler.continueWithNewClientToken(actionToken);
4618
+ }
4619
+ /** Stops the 3DS timers; reports `onThreeDSEnd` once, and only after `onThreeDSStart`. */
4620
+ endThreeDS(result) {
4621
+ const threeDS = this.threeDS;
4622
+ if (!threeDS) {
4623
+ return;
4624
+ }
4625
+ if (threeDS.timer) {
4626
+ clearTimeout(threeDS.timer);
4627
+ threeDS.timer = null;
4628
+ }
4629
+ if (threeDS.revealTimer) {
4630
+ clearTimeout(threeDS.revealTimer);
4631
+ threeDS.revealTimer = null;
4632
+ }
4633
+ threeDS.showOverlay();
4634
+ if (threeDS.challenged) {
4635
+ callHook('onThreeDSEnd', this.options.onThreeDSEnd, { result });
4636
+ }
4637
+ }
4638
+ async onResumed(generation, data, handler) {
4639
+ const threeDS = this.threeDS;
4640
+ if (generation !== this.generation || !this.attemptRunning || !threeDS) {
4641
+ callSafely(() => handler.handleFailure());
4642
+ return;
4643
+ }
4644
+ // The challenge is over: the timeout bounds only the challenge, never the POST.
4645
+ if (threeDS.timer) {
4646
+ clearTimeout(threeDS.timer);
4647
+ threeDS.timer = null;
4648
+ }
4649
+ if (threeDS.revealTimer) {
4650
+ clearTimeout(threeDS.revealTimer);
4651
+ threeDS.revealTimer = null;
4652
+ }
4653
+ let response;
4654
+ try {
4655
+ response = await this.apiClient.resumePaymentOnce({
4656
+ orderId: threeDS.orderId,
4657
+ resumeToken: data.resumeToken,
4658
+ });
4659
+ }
4660
+ catch (error) {
4661
+ callSafely(() => handler.handleFailure());
4662
+ this.endThreeDS('error');
4663
+ this.finish({
4664
+ outcome: 'error',
4665
+ orderId: threeDS.orderId,
4666
+ threeDSChallenged: threeDS.challenged,
4667
+ error: error,
4668
+ failedRequest: 'resume_payment',
4669
+ });
4670
+ return;
4671
+ }
4672
+ const mapped = mapResumeResponse(response, threeDS.orderId, threeDS.challenged);
4673
+ if (mapped.result.outcome === 'succeeded' ||
4674
+ mapped.result.outcome === 'processing') {
4675
+ callSafely(() => handler.handleSuccess());
4676
+ }
4677
+ else {
4678
+ callSafely(() => handler.handleFailure(mapped.result.failedMessageForUser || undefined));
4679
+ }
4680
+ this.endThreeDS(mapped.threeDS);
4681
+ this.finish(mapped.result);
4682
+ }
4683
+ onResumeError(generation, error) {
4684
+ const threeDS = this.threeDS;
4685
+ if (generation !== this.generation || !this.attemptRunning || !threeDS) {
4686
+ return;
4687
+ }
4688
+ if (isThreeDSCloseError(error)) {
4689
+ this.endThreeDS('abandoned');
4690
+ this.finish({
4691
+ outcome: '3ds_abandoned',
4692
+ orderId: threeDS.orderId,
4693
+ threeDSChallenged: threeDS.challenged,
4694
+ });
4695
+ return;
4696
+ }
4697
+ this.endThreeDS('failed');
4698
+ this.finish({
4699
+ outcome: '3ds_failed',
4700
+ orderId: threeDS.orderId,
4701
+ threeDSChallenged: threeDS.challenged,
4702
+ error: toError('3DS authentication failed', error),
4703
+ });
4704
+ }
4705
+ // ---------- result ----------
4706
+ /** Ends the running attempt with its one result; later calls for it are ignored. */
4707
+ finish(result) {
4708
+ if (!this.attemptRunning) {
4709
+ return;
4710
+ }
4711
+ this.attemptRunning = false;
4712
+ this.tokenizeStarted = false;
4713
+ this.charging = false;
4714
+ this.threeDS = null;
4715
+ oneClickInFlight.delete(this.inFlightKey);
4716
+ this.report(result);
4717
+ }
4718
+ report(result) {
4719
+ if (result.outcome !== 'cancelled') {
4720
+ this.finished = true;
4721
+ this.clearRefresh();
4722
+ this.applyDisabled();
4723
+ }
4724
+ else if (this.expiresSoon()) {
4725
+ this.refresh();
4726
+ }
4727
+ if (result.outcome === 'error' && result.error) {
4728
+ const error = result.error;
4729
+ getErrorImage(this.options.orgId, {
4730
+ baseUrl: this.options.baseUrl || defaultBaseUrl(),
4731
+ message: error.message,
4732
+ code: error.code,
4733
+ req_id: error.response?.req_id,
4734
+ });
4735
+ }
4736
+ if (!this.destroyed) {
4737
+ callHook('onResult', this.options.onResult, result);
4738
+ }
4739
+ }
4740
+ }
4741
+ function validate(container, options) {
4742
+ if (typeof HTMLElement === 'undefined' ||
4743
+ !(container instanceof HTMLElement)) {
4744
+ throw new ValidationError('container', 'must be an HTMLElement', container);
4745
+ }
4746
+ for (const field of ['orgId', 'priceId', 'externalId']) {
4747
+ if (!options?.[field]) {
4748
+ throw new ValidationError(field, 'is required', options?.[field]);
4749
+ }
4750
+ }
4751
+ if (typeof options.onResult !== 'function') {
4752
+ throw new ValidationError('onResult', 'must be a function', options.onResult);
4753
+ }
4754
+ }
4755
+ /**
4756
+ * Mounts Primer's native Apple Pay / Google Pay button for a one-click upsell. Rejects only with
4757
+ * `ValidationError`; any `mounted: false` leaves nothing in `container`.
4758
+ */
4759
+ async function mountWalletUpsell(container, options) {
4760
+ validate(container, options);
4761
+ let session;
4762
+ try {
4763
+ session = await prepareSession(WalletUpsell.apiClientFor(options), options);
4764
+ }
4765
+ catch (error) {
4766
+ return {
4767
+ mounted: false,
4768
+ reason: 'error',
4769
+ error: error instanceof Error
4770
+ ? error
4771
+ : toError('one_click_wallet_session failed', error),
4772
+ };
4773
+ }
4774
+ if (!session) {
4775
+ return { mounted: false, reason: 'not_wallet' };
4776
+ }
4777
+ const upsell = new WalletUpsell(container, options, session);
4778
+ try {
4779
+ if (!(await upsell.render())) {
4780
+ upsell.destroy();
4781
+ return {
4782
+ mounted: false,
4783
+ reason: 'wallet_unavailable',
4784
+ wallet: session.wallet,
4785
+ };
4786
+ }
4787
+ }
4788
+ catch (error) {
4789
+ upsell.destroy();
4790
+ return {
4791
+ mounted: false,
4792
+ reason: 'error',
4793
+ error: toError('Failed to mount the wallet button', error),
4794
+ };
4795
+ }
4796
+ upsell.watchVisibility();
4797
+ return {
4798
+ mounted: true,
4799
+ wallet: session.wallet,
4800
+ setDisabled: (disabled) => upsell.setDisabled(disabled),
4801
+ destroy: () => upsell.destroy(),
4802
+ };
4803
+ }
4804
+
4036
4805
  /**
4037
4806
  * @fileoverview Main entry point for @funnelfox/billing
4038
4807
  */
@@ -4042,6 +4811,7 @@ const Billing = {
4042
4811
  createClientSession: createClientSession,
4043
4812
  initMethod: initMethod,
4044
4813
  silentPurchase: silentPurchase,
4814
+ mountWalletUpsell,
4045
4815
  getAvailablePaymentMethods: getAvailablePaymentMethods,
4046
4816
  stripe: {
4047
4817
  createCardForm: createStripeCardForm,
@@ -4055,4 +4825,4 @@ if (typeof window !== 'undefined') {
4055
4825
  }
4056
4826
  console.debug('Billing SDK inited');
4057
4827
 
4058
- 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, resolveTaxDisplay as r, toPaymentFailure as t };
4828
+ 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, mountWalletUpsell as m, resolveTaxDisplay as r, toPaymentFailure as t };