@funnelfox/billing 0.11.0 → 0.13.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.11.0';
562
+ const SDK_VERSION = '0.13.0';
563
563
  const DEFAULTS = {
564
564
  BASE_URL: 'https://billing.funnelfox.com',
565
565
  REGION: 'default',
@@ -613,6 +613,9 @@ const ERROR_CODES = {
613
613
  CONFIGURATION_ERROR: 'CONFIGURATION_ERROR',
614
614
  NETWORK_ERROR: 'NETWORK_ERROR',
615
615
  };
616
+ const PRIMER_DEFAULTS = {
617
+ PAYMENT_HANDLING: 'MANUAL',
618
+ API_VERSION: '2.4'};
616
619
  const ALLOWED_BUTTON_PAYMENT_METHODS = [
617
620
  PaymentMethod.GOOGLE_PAY,
618
621
  PaymentMethod.APPLE_PAY,
@@ -652,6 +655,7 @@ const DEFAULT_PAYMENT_METHOD_ORDER = [
652
655
  const DEFAULT_BUTTONS_OPTIONS = {
653
656
  [PaymentMethod.APPLE_PAY]: {
654
657
  buttonStyle: 'black',
658
+ buttonType: 'continue',
655
659
  },
656
660
  [PaymentMethod.PAYPAL]: {
657
661
  buttonColor: 'gold',
@@ -675,6 +679,13 @@ const APPLE_PAY_COLLECTING_EMAIL_OPTIONS = {
675
679
  requiredShippingContactFields: ['emailAddress'],
676
680
  },
677
681
  };
682
+ /**
683
+ * Backend decline codes that mean "the 3DS check failed" (as opposed to "3DS passed, then the
684
+ * issuer declined"). `null`: the codes cannot tell the two apart, so any decline after a
685
+ * challenge is `3ds_failed` (FFB-704 spike: in production both cases share REFER_TO_CARD_ISSUER,
686
+ * DO_NOT_HONOR and AUTHENTICATION_REQUIRED; human decision 10).
687
+ */
688
+ const THREE_DS_AUTH_DECLINE_CODES = null;
678
689
 
679
690
  /**
680
691
  * @fileoverview Input validation utilities for Funnefox SDK
@@ -1363,6 +1374,37 @@ class APIClient {
1363
1374
  throw new NetworkError('Network request failed', error);
1364
1375
  }
1365
1376
  }
1377
+ /**
1378
+ * Sends the request exactly once: no retry and no client timeout (FFB-704, decision 9).
1379
+ * Same URL, headers and error classes as `request()`. Used only by `silentPurchase`'s
1380
+ * `handle3DS` mode for `one_click` and `resume_payment`, which must not be POSTed twice.
1381
+ */
1382
+ async requestOnce(endpoint, options = {}) {
1383
+ const url = `${this.baseUrl}/${this.orgId}${endpoint}`;
1384
+ const requestOptions = {
1385
+ method: 'GET',
1386
+ headers: {
1387
+ 'Content-Type': 'application/json',
1388
+ 'X-SDK-Version': SDK_VERSION,
1389
+ ...(options.headers || {}),
1390
+ },
1391
+ ...options,
1392
+ };
1393
+ try {
1394
+ return await this._makeRequest(url, requestOptions);
1395
+ }
1396
+ catch (error) {
1397
+ if (error instanceof APIError) {
1398
+ // Same instance, enriched: _makeRequest leaves errorCode empty; fill it from the body.
1399
+ error.errorCode ?? (error.errorCode = getResponseErrorCodes(error.response)[0] ?? null);
1400
+ throw error;
1401
+ }
1402
+ if (error instanceof Error && error.name === 'NetworkError') {
1403
+ throw error;
1404
+ }
1405
+ throw new NetworkError('Network request failed', error);
1406
+ }
1407
+ }
1366
1408
  async _makeRequest(url, options) {
1367
1409
  let response;
1368
1410
  try {
@@ -1554,6 +1596,23 @@ class APIClient {
1554
1596
  body: JSON.stringify(payload),
1555
1597
  }));
1556
1598
  }
1599
+ /** `one_click`, POSTed exactly once (see `requestOnce`). */
1600
+ async oneClickOnce(payload) {
1601
+ return (await this.requestOnce(API_ENDPOINTS.ONE_CLICK, {
1602
+ method: 'POST',
1603
+ body: JSON.stringify(payload),
1604
+ }));
1605
+ }
1606
+ /** `resume_payment`, POSTed exactly once (see `requestOnce`). */
1607
+ async resumePaymentOnce(params) {
1608
+ return (await this.requestOnce(API_ENDPOINTS.RESUME_PAYMENT, {
1609
+ method: 'POST',
1610
+ body: JSON.stringify({
1611
+ order_id: params.orderId,
1612
+ resume_token: params.resumeToken,
1613
+ }),
1614
+ }));
1615
+ }
1557
1616
  async createSimpleClientSession(payload) {
1558
1617
  return (await this.request(API_ENDPOINTS.CREATE_SIMPLE_CLIENT_SESSION, {
1559
1618
  method: 'POST',
@@ -1565,6 +1624,19 @@ class APIClient {
1565
1624
  }));
1566
1625
  }
1567
1626
  }
1627
+ /**
1628
+ * Returns the `error[].code` values of a backend error envelope
1629
+ * (`{status: 'error', error: [{msg, code, type}]}`), e.g. from `APIError.response`.
1630
+ */
1631
+ function getResponseErrorCodes(response) {
1632
+ const errors = response?.error;
1633
+ if (!Array.isArray(errors)) {
1634
+ return [];
1635
+ }
1636
+ return errors
1637
+ .map(item => item?.code)
1638
+ .filter((code) => typeof code === 'string');
1639
+ }
1568
1640
 
1569
1641
  class SessionService {
1570
1642
  constructor() {
@@ -2597,7 +2669,7 @@ class CheckoutInstance extends EventEmitter {
2597
2669
  ...checkoutConfig,
2598
2670
  ...options,
2599
2671
  card: merge(this.getPrimerCardConfig() || {}, options.card || {}),
2600
- applePay: merge(this.checkoutConfig.applePay || {}, options.applePay || {}),
2672
+ applePay: merge(DEFAULT_BUTTONS_OPTIONS[PaymentMethod.APPLE_PAY], options.applePay || {}, this.checkoutConfig.applePay || {}),
2601
2673
  onTokenizeSuccess: this.handleTokenizeSuccess,
2602
2674
  onResumeSuccess: this.handleResumeSuccess,
2603
2675
  onResumeError: error => {
@@ -2899,6 +2971,278 @@ class CheckoutInstance extends EventEmitter {
2899
2971
  }
2900
2972
  }
2901
2973
 
2974
+ /**
2975
+ * @fileoverview 3DS challenge for one-click purchases (FFB-704). Internal module.
2976
+ *
2977
+ * Primer can run a 3DS challenge only from a tokenization handler
2978
+ * (`handler.continueWithNewClientToken`), and a one-click purchase has no tokenization in the
2979
+ * browser: the backend charges the vaulted instrument. Mechanism M1 (proven by the FFB-704 spike
2980
+ * on the Primer sandbox): open a customer-bound CHECKOUT client session, start a headless
2981
+ * checkout, tokenize a vaulted instrument through the vault manager as a stand-in, and in
2982
+ * `onTokenizeSuccess` continue with the one-click `action_required_token` instead. Primer then
2983
+ * shows its 3DS overlay; `onResumeSuccess` yields the resume token for `resume_payment`.
2984
+ */
2985
+ /** Primer client-token intents that carry a 3DS step. */
2986
+ const PRIMER_3DS_INTENTS = ['3DS_AUTHENTICATION', 'PROCESSOR_3DS'];
2987
+ /** Default `threeDSTimeoutMs`. */
2988
+ const DEFAULT_THREE_DS_TIMEOUT_MS = 600000;
2989
+ /** Close button of Primer's 3DS overlay (Primer Web SDK 2.57.3, verified in the spike). */
2990
+ const PRIMER_OVERLAY_CLOSE_SELECTOR = '[data-testid="OverlayContent.closeButton"]';
2991
+ /** Decodes the `intent` of a Primer client token (a JWT); `null` if it is not one. */
2992
+ function getPrimerTokenIntent(token) {
2993
+ try {
2994
+ const parts = token.split('.');
2995
+ if (parts.length !== 3) {
2996
+ return null;
2997
+ }
2998
+ const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
2999
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
3000
+ const payload = JSON.parse(atob(padded));
3001
+ return typeof payload?.intent === 'string' ? payload.intent : null;
3002
+ }
3003
+ catch {
3004
+ return null;
3005
+ }
3006
+ }
3007
+ /** The error Primer reports when the user closes the 3DS overlay (same check as checkout.ts). */
3008
+ function isThreeDSCloseError(error) {
3009
+ return Boolean(error?.stack?.includes('PROCESSOR_3DS') &&
3010
+ error.code === 'RESUME_ERROR' &&
3011
+ error.message?.includes('fetch resume key'));
3012
+ }
3013
+ /**
3014
+ * Picks the vaulted instrument used as the stand-in tokenization. Primer returns the vault
3015
+ * oldest-first and has no "default" flag; the 3DS check runs on the action token, not on this
3016
+ * instrument. Cards are preferred because their vault tokenization is silent (no CVV prompt).
3017
+ */
3018
+ function pickVaultedMethod(methods) {
3019
+ if (!methods || methods.length === 0) {
3020
+ return null;
3021
+ }
3022
+ return (methods.find(method => method.paymentInstrumentType === 'PAYMENT_CARD') ||
3023
+ methods[0]);
3024
+ }
3025
+ function dismissPrimerOverlay() {
3026
+ if (typeof document === 'undefined') {
3027
+ return;
3028
+ }
3029
+ const button = document.querySelector(PRIMER_OVERLAY_CLOSE_SELECTOR);
3030
+ button?.click();
3031
+ }
3032
+ function toPrimerError(message, error) {
3033
+ return error instanceof PrimerError ? error : new PrimerError(message, error);
3034
+ }
3035
+ function callSafely(fn) {
3036
+ try {
3037
+ fn();
3038
+ }
3039
+ catch {
3040
+ // Primer handler calls are best effort once the result is decided.
3041
+ }
3042
+ }
3043
+ /**
3044
+ * Runs the 3DS challenge for a one-click order and, when Primer hands back a resume token,
3045
+ * calls `resume_payment` once. Never rejects; the caller maps the result to an outcome.
3046
+ */
3047
+ async function runOneClickThreeDS(params) {
3048
+ const { apiClient, region, priceId, externalId, orderId, actionToken } = params;
3049
+ const intent = getPrimerTokenIntent(actionToken);
3050
+ if (!intent || !PRIMER_3DS_INTENTS.includes(intent)) {
3051
+ return {
3052
+ kind: 'error',
3053
+ error: new PrimerError('Unsupported one-click action: the action token is not a Primer 3DS client token', { intent }),
3054
+ };
3055
+ }
3056
+ const timeoutMs = Number.isFinite(params.timeoutMs) && params.timeoutMs > 0
3057
+ ? params.timeoutMs
3058
+ : DEFAULT_THREE_DS_TIMEOUT_MS;
3059
+ return new Promise(resolve => {
3060
+ let settled = false;
3061
+ let tokenized = false;
3062
+ // True only while create_client_session is in flight.
3063
+ let sessionInFlight = false;
3064
+ let timer = null;
3065
+ let headless = null;
3066
+ const settle = (result) => {
3067
+ if (settled) {
3068
+ return;
3069
+ }
3070
+ settled = true;
3071
+ if (timer) {
3072
+ clearTimeout(timer);
3073
+ timer = null;
3074
+ }
3075
+ headless = null;
3076
+ resolve(result);
3077
+ };
3078
+ timer = setTimeout(() => {
3079
+ timer = null;
3080
+ if (tokenized) {
3081
+ // The challenge was shown and the customer did not finish it.
3082
+ settle({ kind: 'abandoned' });
3083
+ // Close Primer's overlay; the close error it raises is ignored (already settled).
3084
+ dismissPrimerOverlay();
3085
+ return;
3086
+ }
3087
+ // No challenge was shown yet: this is a setup failure, not an abandoned challenge.
3088
+ if (sessionInFlight) {
3089
+ settle({
3090
+ kind: 'error',
3091
+ error: new NetworkError('create_client_session did not respond within threeDSTimeoutMs'),
3092
+ failedRequest: 'create_client_session',
3093
+ });
3094
+ return;
3095
+ }
3096
+ settle({
3097
+ kind: 'error',
3098
+ error: new PrimerError('Timed out before the 3DS challenge was shown (threeDSTimeoutMs)'),
3099
+ });
3100
+ }, timeoutMs);
3101
+ const onTokenizeSuccess = (_data, handler) => {
3102
+ if (settled) {
3103
+ callSafely(() => handler.handleFailure());
3104
+ return;
3105
+ }
3106
+ tokenized = true;
3107
+ // Ignore the stand-in vaulted token: run the one-click 3DS action instead.
3108
+ handler.continueWithNewClientToken(actionToken);
3109
+ };
3110
+ const onResumeSuccess = async (data, handler) => {
3111
+ if (settled) {
3112
+ callSafely(() => handler.handleFailure());
3113
+ return;
3114
+ }
3115
+ // The challenge is over: the timeout bounds only the challenge, never the POST.
3116
+ if (timer) {
3117
+ clearTimeout(timer);
3118
+ timer = null;
3119
+ }
3120
+ let response;
3121
+ try {
3122
+ response = await apiClient.resumePaymentOnce({
3123
+ orderId,
3124
+ resumeToken: data.resumeToken,
3125
+ });
3126
+ }
3127
+ catch (error) {
3128
+ callSafely(() => handler.handleFailure());
3129
+ settle({
3130
+ kind: 'error',
3131
+ error: error,
3132
+ failedRequest: 'resume_payment',
3133
+ });
3134
+ return;
3135
+ }
3136
+ const resumeData = response?.data;
3137
+ if (response?.status === 'success' &&
3138
+ resumeData?.checkout_status === 'succeeded' &&
3139
+ !resumeData.action_required_token) {
3140
+ callSafely(() => handler.handleSuccess());
3141
+ }
3142
+ else {
3143
+ // A chained action token is never continued (no second challenge).
3144
+ callSafely(() => handler.handleFailure(resumeData?.failed_message_for_user || undefined));
3145
+ }
3146
+ settle({ kind: 'resumed', response });
3147
+ };
3148
+ const onResumeError = (error) => {
3149
+ if (isThreeDSCloseError(error)) {
3150
+ settle({ kind: 'abandoned' });
3151
+ return;
3152
+ }
3153
+ settle({
3154
+ kind: 'failed',
3155
+ error: toPrimerError('3DS authentication failed', error),
3156
+ });
3157
+ };
3158
+ const onCheckoutFail = (error) => {
3159
+ if (tokenized) {
3160
+ settle({
3161
+ kind: 'failed',
3162
+ error: toPrimerError('3DS authentication failed', error),
3163
+ });
3164
+ }
3165
+ else {
3166
+ settle({
3167
+ kind: 'error',
3168
+ error: toPrimerError('Primer checkout failed before the 3DS challenge', error),
3169
+ });
3170
+ }
3171
+ };
3172
+ const onTokenizeError = (error) => {
3173
+ settle({
3174
+ kind: 'error',
3175
+ error: toPrimerError('Failed to tokenize the saved payment method', error),
3176
+ });
3177
+ };
3178
+ (async () => {
3179
+ await new PrimerWrapper().ensurePrimerLoaded();
3180
+ if (settled) {
3181
+ return;
3182
+ }
3183
+ let clientToken;
3184
+ sessionInFlight = true;
3185
+ try {
3186
+ const session = await apiClient.createClientSession({
3187
+ priceId,
3188
+ externalId,
3189
+ region,
3190
+ clientMetadata: {},
3191
+ });
3192
+ clientToken = apiClient.processSessionResponse(session).clientToken;
3193
+ sessionInFlight = false;
3194
+ }
3195
+ catch (error) {
3196
+ sessionInFlight = false;
3197
+ settle({
3198
+ kind: 'error',
3199
+ error: error,
3200
+ failedRequest: 'create_client_session',
3201
+ });
3202
+ return;
3203
+ }
3204
+ if (settled) {
3205
+ return;
3206
+ }
3207
+ // A dedicated instance, not the HeadlessManager cache used by checkouts.
3208
+ const instance = await window.Primer.createHeadless(clientToken, {
3209
+ paymentHandling: PRIMER_DEFAULTS.PAYMENT_HANDLING,
3210
+ apiVersion: PRIMER_DEFAULTS.API_VERSION,
3211
+ onAvailablePaymentMethodsLoad: () => { },
3212
+ onTokenizeSuccess,
3213
+ onTokenizeError,
3214
+ onResumeSuccess,
3215
+ onResumeError,
3216
+ onCheckoutFail,
3217
+ });
3218
+ headless = await instance;
3219
+ await headless.start();
3220
+ if (settled) {
3221
+ return;
3222
+ }
3223
+ const vaultManager = headless.createVaultManager();
3224
+ const methods = await vaultManager.fetchVaultedPaymentMethods();
3225
+ const method = pickVaultedMethod(methods);
3226
+ if (!method) {
3227
+ settle({
3228
+ kind: 'error',
3229
+ error: new PrimerError('No saved payment method found for the one-click 3DS challenge'),
3230
+ });
3231
+ return;
3232
+ }
3233
+ if (settled) {
3234
+ return;
3235
+ }
3236
+ await vaultManager.startPaymentFlow(method.id);
3237
+ })().catch(error => {
3238
+ settle({
3239
+ kind: 'error',
3240
+ error: toPrimerError('Failed to start the one-click 3DS challenge', error),
3241
+ });
3242
+ });
3243
+ });
3244
+ }
3245
+
2902
3246
  /**
2903
3247
  * @fileoverview Public API with configuration and orchestration logic
2904
3248
  */
@@ -2965,20 +3309,46 @@ async function createClientSession(params) {
2965
3309
  });
2966
3310
  return apiClient.processSessionResponse(sessionResponse);
2967
3311
  }
2968
- async function silentPurchase(options) {
2969
- const { priceId, externalId, clientMetadata, orgId, baseUrl } = options;
3312
+ /**
3313
+ * Builds the `one_click` body. The CIT fields are added only when the caller set them.
3314
+ */
3315
+ function buildOneClickRequest(options) {
3316
+ const payload = {
3317
+ pp_ident: options.priceId,
3318
+ external_id: options.externalId,
3319
+ client_metadata: options.clientMetadata,
3320
+ };
3321
+ if (options.initiationType !== undefined) {
3322
+ payload.initiation_type = options.initiationType;
3323
+ }
3324
+ if (options.citCardNetworks !== undefined) {
3325
+ payload.cit_card_networks = options.citCardNetworks;
3326
+ }
3327
+ if (options.citGooglePayPanOnly !== undefined) {
3328
+ payload.cit_google_pay_pan_only = options.citGooglePayPanOnly;
3329
+ }
3330
+ return payload;
3331
+ }
3332
+ function silentPurchase(options) {
3333
+ if (options?.handle3DS === true) {
3334
+ return silentPurchaseDetailed(options);
3335
+ }
3336
+ return silentPurchaseLegacy(options);
3337
+ }
3338
+ async function silentPurchaseLegacy(options) {
3339
+ const { orgId, baseUrl } = options;
2970
3340
  const apiClient = new APIClient({
2971
3341
  baseUrl: baseUrl,
2972
3342
  orgId: orgId,
2973
3343
  timeout: DEFAULTS.REQUEST_TIMEOUT,
2974
3344
  retryAttempts: DEFAULTS.RETRY_ATTEMPTS,
2975
3345
  });
3346
+ if (options.initiationType === 'cit') {
3347
+ // eslint-disable-next-line no-console
3348
+ console.warn('[FunnelfoxSDK] silentPurchase: initiationType "cit" can trigger a 3DS challenge, which only silentPurchase({ handle3DS: true }) handles.');
3349
+ }
2976
3350
  try {
2977
- const response = await apiClient.oneClick({
2978
- pp_ident: priceId,
2979
- external_id: externalId,
2980
- client_metadata: clientMetadata,
2981
- });
3351
+ const response = await apiClient.oneClick(buildOneClickRequest(options));
2982
3352
  if (response.status !== 'success' &&
2983
3353
  response.error.some(({ code }) => code === 'double_purchase')) {
2984
3354
  throw new APIError('This product was already purchased');
@@ -2998,6 +3368,308 @@ async function silentPurchase(options) {
2998
3368
  throw error;
2999
3369
  }
3000
3370
  }
3371
+ const ONE_CLICK_IN_PROGRESS = 'one_click_in_progress';
3372
+ const DOUBLE_PURCHASE = 'double_purchase';
3373
+ const oneClickInFlight = new Set();
3374
+ function declineFields(data) {
3375
+ return {
3376
+ failedMessageForUser: data.failed_message_for_user ?? null,
3377
+ declineCode: data.decline_code ?? null,
3378
+ declineCodeSource: data.decline_code_source ?? null,
3379
+ };
3380
+ }
3381
+ function envelopeError(response, fallbackMessage) {
3382
+ const firstError = response?.error?.[0];
3383
+ return new APIError(firstError?.msg || fallbackMessage, null, {
3384
+ errorCode: firstError?.code,
3385
+ errorType: firstError?.type,
3386
+ response,
3387
+ });
3388
+ }
3389
+ /** Maps a 2xx `one_click` response (rows 1-4, plus "needs action"). */
3390
+ function mapOneClickResponse(response) {
3391
+ const data = response?.data;
3392
+ if (response?.status !== 'success' || !data) {
3393
+ if (getResponseErrorCodes(response).includes(DOUBLE_PURCHASE)) {
3394
+ return {
3395
+ kind: 'result',
3396
+ result: {
3397
+ outcome: 'already_purchased',
3398
+ orderId: null,
3399
+ threeDSChallenged: false,
3400
+ },
3401
+ };
3402
+ }
3403
+ return {
3404
+ kind: 'result',
3405
+ result: {
3406
+ outcome: 'error',
3407
+ orderId: data?.order_id ?? null,
3408
+ threeDSChallenged: false,
3409
+ error: envelopeError(response, 'One-click purchase failed'),
3410
+ failedRequest: 'one_click',
3411
+ },
3412
+ };
3413
+ }
3414
+ const orderId = data.order_id ?? null;
3415
+ if (data.action_required_token) {
3416
+ return { kind: 'action', orderId, actionToken: data.action_required_token };
3417
+ }
3418
+ switch (data.checkout_status) {
3419
+ case 'succeeded':
3420
+ return {
3421
+ kind: 'result',
3422
+ result: { outcome: 'succeeded', orderId, threeDSChallenged: false },
3423
+ };
3424
+ case 'failed':
3425
+ return {
3426
+ kind: 'result',
3427
+ result: {
3428
+ outcome: 'declined',
3429
+ orderId,
3430
+ threeDSChallenged: false,
3431
+ ...declineFields(data),
3432
+ },
3433
+ };
3434
+ case 'processing':
3435
+ return {
3436
+ kind: 'result',
3437
+ result: { outcome: 'processing', orderId, threeDSChallenged: false },
3438
+ };
3439
+ case 'cancelled':
3440
+ return {
3441
+ kind: 'result',
3442
+ result: {
3443
+ outcome: 'error',
3444
+ orderId,
3445
+ threeDSChallenged: false,
3446
+ error: new APIError('Payment was cancelled', null, { response }),
3447
+ },
3448
+ };
3449
+ default:
3450
+ return {
3451
+ kind: 'result',
3452
+ result: {
3453
+ outcome: 'error',
3454
+ orderId,
3455
+ threeDSChallenged: false,
3456
+ error: new APIError(`Unhandled checkout status: ${data.checkout_status}`, null, { response }),
3457
+ },
3458
+ };
3459
+ }
3460
+ }
3461
+ /** Maps a `resume_payment` response after a challenge (rows 5, 6, 6b, 6c, 7, 8). */
3462
+ function mapResumeResponse(response, orderId, threeDSAuthDeclineCodes = THREE_DS_AUTH_DECLINE_CODES) {
3463
+ const data = response?.data;
3464
+ if (response?.status !== 'success' || !data) {
3465
+ return {
3466
+ threeDS: 'error',
3467
+ result: {
3468
+ outcome: 'error',
3469
+ orderId,
3470
+ threeDSChallenged: true,
3471
+ error: envelopeError(response, 'Resume payment failed'),
3472
+ failedRequest: 'resume_payment',
3473
+ },
3474
+ };
3475
+ }
3476
+ if (data.action_required_token) {
3477
+ // Chained action: not supported, no second challenge (human decision F3).
3478
+ return {
3479
+ threeDS: 'error',
3480
+ result: {
3481
+ outcome: 'error',
3482
+ orderId,
3483
+ threeDSChallenged: true,
3484
+ error: new FunnefoxSDKError('resume_payment returned another action token; chained 3DS is not supported', 'one_click_chained_action'),
3485
+ },
3486
+ };
3487
+ }
3488
+ switch (data.checkout_status) {
3489
+ case 'succeeded':
3490
+ return {
3491
+ threeDS: 'passed',
3492
+ result: { outcome: 'succeeded', orderId, threeDSChallenged: true },
3493
+ };
3494
+ case 'processing':
3495
+ return {
3496
+ threeDS: 'passed',
3497
+ result: { outcome: 'processing', orderId, threeDSChallenged: true },
3498
+ };
3499
+ case 'failed': {
3500
+ const authFailed = threeDSAuthDeclineCodes === null ||
3501
+ threeDSAuthDeclineCodes.includes(data.decline_code ?? '');
3502
+ return {
3503
+ threeDS: authFailed ? 'failed' : 'passed',
3504
+ result: {
3505
+ outcome: authFailed ? '3ds_failed' : 'declined',
3506
+ orderId,
3507
+ threeDSChallenged: true,
3508
+ ...declineFields(data),
3509
+ },
3510
+ };
3511
+ }
3512
+ default:
3513
+ return {
3514
+ threeDS: 'error',
3515
+ result: {
3516
+ outcome: 'error',
3517
+ orderId,
3518
+ threeDSChallenged: true,
3519
+ error: new APIError(data.checkout_status === 'cancelled'
3520
+ ? 'Payment was cancelled'
3521
+ : `Unhandled checkout status: ${data.checkout_status}`, null, { response }),
3522
+ },
3523
+ };
3524
+ }
3525
+ }
3526
+ function mapThreeDSRun(run, orderId) {
3527
+ switch (run.kind) {
3528
+ case 'resumed':
3529
+ return mapResumeResponse(run.response, orderId);
3530
+ case 'failed':
3531
+ return {
3532
+ threeDS: 'failed',
3533
+ result: {
3534
+ outcome: '3ds_failed',
3535
+ orderId,
3536
+ threeDSChallenged: true,
3537
+ error: run.error,
3538
+ },
3539
+ };
3540
+ case 'abandoned':
3541
+ return {
3542
+ threeDS: 'abandoned',
3543
+ result: { outcome: '3ds_abandoned', orderId, threeDSChallenged: true },
3544
+ };
3545
+ default: {
3546
+ const result = {
3547
+ outcome: 'error',
3548
+ orderId,
3549
+ threeDSChallenged: true,
3550
+ error: run.error,
3551
+ };
3552
+ if (run.failedRequest) {
3553
+ result.failedRequest = run.failedRequest;
3554
+ }
3555
+ return { threeDS: 'error', result };
3556
+ }
3557
+ }
3558
+ }
3559
+ function callHook(name, hook, info) {
3560
+ if (typeof hook !== 'function') {
3561
+ return;
3562
+ }
3563
+ try {
3564
+ hook(info);
3565
+ }
3566
+ catch (error) {
3567
+ // eslint-disable-next-line no-console
3568
+ console.error(`[FunnelfoxSDK] silentPurchase ${name} hook threw`, error);
3569
+ }
3570
+ }
3571
+ async function silentPurchaseDetailed(options) {
3572
+ for (const field of ['orgId', 'baseUrl', 'priceId', 'externalId']) {
3573
+ if (!options?.[field]) {
3574
+ throw new ValidationError(field, 'is required', options?.[field]);
3575
+ }
3576
+ }
3577
+ const { orgId, baseUrl, externalId } = options;
3578
+ const inFlightKey = `${orgId}\u0000${externalId}`;
3579
+ if (oneClickInFlight.has(inFlightKey)) {
3580
+ return {
3581
+ outcome: 'error',
3582
+ orderId: null,
3583
+ threeDSChallenged: false,
3584
+ error: new FunnefoxSDKError('A one-click purchase is already in progress for this customer', ONE_CLICK_IN_PROGRESS),
3585
+ };
3586
+ }
3587
+ oneClickInFlight.add(inFlightKey);
3588
+ try {
3589
+ const result = await runSilentPurchaseDetailed(options);
3590
+ if (result.outcome === 'error' && result.error) {
3591
+ const error = result.error;
3592
+ getErrorImage(orgId, {
3593
+ baseUrl,
3594
+ message: error.message,
3595
+ code: error.code,
3596
+ req_id: error.response?.req_id,
3597
+ });
3598
+ }
3599
+ return result;
3600
+ }
3601
+ finally {
3602
+ oneClickInFlight.delete(inFlightKey);
3603
+ }
3604
+ }
3605
+ async function runSilentPurchaseDetailed(options) {
3606
+ const apiClient = new APIClient({
3607
+ baseUrl: options.baseUrl,
3608
+ orgId: options.orgId,
3609
+ timeout: DEFAULTS.REQUEST_TIMEOUT,
3610
+ retryAttempts: DEFAULTS.RETRY_ATTEMPTS,
3611
+ });
3612
+ let response;
3613
+ try {
3614
+ response = await apiClient.oneClickOnce(buildOneClickRequest(options));
3615
+ }
3616
+ catch (error) {
3617
+ if (error instanceof APIError &&
3618
+ getResponseErrorCodes(error.response).includes(DOUBLE_PURCHASE)) {
3619
+ return {
3620
+ outcome: 'already_purchased',
3621
+ orderId: null,
3622
+ threeDSChallenged: false,
3623
+ };
3624
+ }
3625
+ return {
3626
+ outcome: 'error',
3627
+ orderId: null,
3628
+ threeDSChallenged: false,
3629
+ error: error,
3630
+ failedRequest: 'one_click',
3631
+ };
3632
+ }
3633
+ const step = mapOneClickResponse(response);
3634
+ if (step.kind === 'result') {
3635
+ return step.result;
3636
+ }
3637
+ const { orderId, actionToken } = step;
3638
+ let ended = false;
3639
+ const end = (result) => {
3640
+ if (ended) {
3641
+ return;
3642
+ }
3643
+ ended = true;
3644
+ callHook('onThreeDSEnd', options.onThreeDSEnd, { result });
3645
+ };
3646
+ callHook('onThreeDSStart', options.onThreeDSStart, { orderId });
3647
+ try {
3648
+ const run = await runOneClickThreeDS({
3649
+ apiClient,
3650
+ region: defaultConfig?.region || DEFAULTS.REGION,
3651
+ priceId: options.priceId,
3652
+ externalId: options.externalId,
3653
+ orderId,
3654
+ actionToken,
3655
+ timeoutMs: options.threeDSTimeoutMs ?? DEFAULT_THREE_DS_TIMEOUT_MS,
3656
+ });
3657
+ const mapped = mapThreeDSRun(run, orderId);
3658
+ end(mapped.threeDS);
3659
+ return mapped.result;
3660
+ }
3661
+ catch (error) {
3662
+ end('error');
3663
+ return {
3664
+ outcome: 'error',
3665
+ orderId,
3666
+ threeDSChallenged: true,
3667
+ error: error instanceof Error
3668
+ ? error
3669
+ : new FunnefoxSDKError('One-click 3DS step failed', undefined, error),
3670
+ };
3671
+ }
3672
+ }
3001
3673
  async function initMethod(method, element, options) {
3002
3674
  try {
3003
3675
  const checkoutInstance = new CheckoutInstance({