@flopay/vue 1.20.14 → 2.0.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.
Files changed (39) hide show
  1. package/README.md +56 -57
  2. package/dist/card-setup-entry.cjs +184 -569
  3. package/dist/card-setup-entry.d.ts +2 -2
  4. package/dist/card-setup-entry.mjs +3 -7
  5. package/dist/chunk-2VPPDVV7.mjs +218 -0
  6. package/dist/chunk-OCVTEXQA.mjs +20 -0
  7. package/dist/flopay-runtime-checkout.d.ts +11 -0
  8. package/dist/hosted-runtime-components.d.ts +587 -0
  9. package/dist/index.cjs +279 -5402
  10. package/dist/index.d.ts +3 -21
  11. package/dist/index.mjs +231 -3728
  12. package/dist/payment-method-setup-entry.cjs +194 -1852
  13. package/dist/payment-method-setup-entry.d.ts +2 -2
  14. package/dist/payment-method-setup-entry.mjs +4 -4
  15. package/dist/runtime-context.d.ts +11 -0
  16. package/package.json +3 -5
  17. package/dist/automatic-payment-button.d.ts +0 -296
  18. package/dist/buyer-identity-fallback.d.ts +0 -82
  19. package/dist/chunk-2USKULEH.mjs +0 -530
  20. package/dist/chunk-HH25IC76.mjs +0 -98
  21. package/dist/chunk-IJKGJSHH.mjs +0 -333
  22. package/dist/chunk-RAGPQWRA.mjs +0 -923
  23. package/dist/context.d.ts +0 -56
  24. package/dist/direct-paypal-button.d.ts +0 -325
  25. package/dist/flopay-card-setup.d.ts +0 -158
  26. package/dist/flopay-checkout.d.ts +0 -517
  27. package/dist/flopay-payment-method-setup-main.d.ts +0 -152
  28. package/dist/hooks.d.ts +0 -22
  29. package/dist/hosted-setup.d.ts +0 -116
  30. package/dist/payment-method-setup-paypal-D6FEQQJY.mjs +0 -151
  31. package/dist/payment-method-setup-paypal.d.ts +0 -108
  32. package/dist/processing-overlay.d.ts +0 -82
  33. package/dist/provider.d.ts +0 -76
  34. package/dist/saved-payment.d.ts +0 -44
  35. package/dist/split-card-form.d.ts +0 -777
  36. package/dist/stripe-elements-SI2PI6EO.mjs +0 -6
  37. package/dist/stripe-elements.d.ts +0 -280
  38. package/dist/stripe-paypal-continuation.d.ts +0 -28
  39. package/dist/vault-card-fields.d.ts +0 -129
package/dist/index.mjs CHANGED
@@ -1,3707 +1,36 @@
1
1
  import {
2
- FloPayCardSetup
3
- } from "./chunk-HH25IC76.mjs";
2
+ FloPayRuntimePaymentMethodSetup
3
+ } from "./chunk-OCVTEXQA.mjs";
4
4
  import {
5
- FloPayPaymentMethodSetup
6
- } from "./chunk-IJKGJSHH.mjs";
7
- import {
8
- FloPayCardSetupError,
9
- VaultCardFields
10
- } from "./chunk-2USKULEH.mjs";
11
- import {
12
- CHECKOUT_FORM_DEFAULTS,
13
- CHECKOUT_STATE,
14
- FLOPAY_CONTEXT,
15
- FloPayProvider,
16
- StripePaymentMethods,
17
- hasStripePayPalReturn
18
- } from "./chunk-RAGPQWRA.mjs";
19
-
20
- // src/index.ts
21
- import { dropThirdPartyOnlyError } from "@flopay/shared";
22
-
23
- // src/automatic-payment-button.ts
24
- import { PaymentAPI as PaymentAPI4 } from "@flopay/js";
25
- import {
26
- darkenHex,
27
- derivePrimaryTileStyle as derivePrimaryTileStyle2,
28
- FloPayError as FloPayError5,
29
- invokeMerchantCallback as invokeMerchantCallback4,
30
- resolveBillingApiUrl as resolveBillingApiUrl4,
31
- resolveButtonsLayoutTheme as resolveButtonsLayoutTheme2,
32
- resolveTheme as resolveTheme3
33
- } from "@flopay/shared";
34
- import { computed as computed3, defineComponent as defineComponent5, h as h5, onBeforeUnmount as onBeforeUnmount5, ref as ref5 } from "vue";
35
-
36
- // src/flopay-checkout.ts
37
- import { loadFloPay, PaymentAPI as PaymentAPI3 } from "@flopay/js";
38
- import {
39
- applyClaimAdvertisement,
40
- buildCheckoutDisplayData,
41
- clearCachedInlineCheckout,
42
- clearCachedInlineSession,
43
- FloPayError as FloPayError4,
44
- hashCreateParams,
45
- invokeMerchantCallback as invokeMerchantCallback3,
46
- isDeclineCallbackFailure,
47
- isDetachedSessionEligible,
48
- legacyCachedSessionMatchesDraft,
49
- markSessionRecentlyCompleted as markSessionRecentlyCompleted2,
50
- persistCachedInlineIdempotencyKey,
51
- persistCachedInlineSession,
52
- readCachedInlineIdempotencyKey,
53
- readCachedInlineSession,
54
- resolveBillingApiUrl as resolveBillingApiUrl3,
55
- resolveCheckoutLogLayout,
56
- resolveDirectPaypalConfig,
57
- resolveIdempotencyKey,
58
- resolveTheme as resolveTheme2,
59
- serializeCreateParams,
60
- toPublicCheckoutInitError,
61
- wasSessionRecentlyCompleted
62
- } from "@flopay/shared";
63
- import {
64
- defineComponent as defineComponent4,
65
- h as h4,
66
- onBeforeUnmount as onBeforeUnmount4,
67
- onMounted as onMounted3,
68
- provide,
69
- reactive,
70
- ref as ref4,
71
- shallowRef as shallowRef3,
72
- watch as watch3
73
- } from "vue";
74
-
75
- // src/saved-payment.ts
76
- import {
77
- beginSavedCardChallengeTelemetry,
78
- completeSavedCardNextAction
79
- } from "@flopay/js";
80
- import { FloPayError, normalizeCheckoutFailureOutcome } from "@flopay/shared";
81
- var SAVED_PAYMENT_SUCCESS_DELAY_MS = 600;
82
- function isTerminalSuccess(session) {
83
- return session?.status === "authorized" || session?.status === "complete";
84
- }
85
- function terminalResult(session, sessionId) {
86
- if (session.status !== "authorized") return { status: "succeeded" };
87
- return {
88
- status: "authorized",
89
- paymentId: session.paymentId,
90
- sessionId: session.id || sessionId || void 0,
91
- authorizationExpiresAt: session.authorizationExpiresAt
92
- };
93
- }
94
- function completionSession(completion, prior) {
95
- if (completion.data.session) return completion.data.session;
96
- const raw = completion.raw;
97
- const attempt = raw?.latestTransactionAttempt?.result;
98
- if (raw?.status === "authorized" || attempt === "AUTHORIZED") {
99
- return { ...prior, status: "authorized" };
100
- }
101
- if (raw?.status === "completed" || attempt === "SUCCESS") {
102
- return { ...prior, status: "complete" };
103
- }
104
- return null;
105
- }
106
- function processErrorToFloPayError(error, fallback) {
107
- return new FloPayError(error.message ?? fallback, "api_error", {
108
- code: error.code ?? normalizeCheckoutFailureOutcome(error.outcome) ?? normalizeCheckoutFailureOutcome(error.type) ?? error.gatewayErrorCode
109
- });
110
- }
111
- function readErrorCode(error) {
112
- const code = error?.code;
113
- return typeof code === "string" ? code : void 0;
114
- }
115
- function coerceError(error, fallback) {
116
- if (error instanceof FloPayError) return error;
117
- return new FloPayError(error instanceof Error ? error.message : fallback, "api_error", {
118
- ...readErrorCode(error) ? { code: readErrorCode(error) } : {}
119
- });
120
- }
121
- async function chargeSavedPayment(options) {
122
- const { api, session, unified, signal } = options;
123
- const nonce = options.nonce || session.clientSecret || void 0;
124
- const completeAction = async (nextActionRedirectUrl, actionNonce) => {
125
- const challengeTelemetry = beginSavedCardChallengeTelemetry(api, session.id, session);
126
- const completed = await completeSavedCardNextAction(
127
- {
128
- billingApiUrl: options.billingApiUrl,
129
- sessionId: session.id,
130
- nonce: actionNonce,
131
- nextActionRedirectUrl,
132
- ...signal ? { signal } : {},
133
- ...challengeTelemetry ? { telemetry: challengeTelemetry } : {}
134
- },
135
- api
136
- );
137
- if (completed.autoProcessingError) {
138
- throw processErrorToFloPayError(
139
- completed.autoProcessingError,
140
- "Card authentication was not completed."
141
- );
142
- }
143
- const settled = completionSession(completed, session);
144
- if (!isTerminalSuccess(settled)) {
145
- throw new FloPayError("Card authentication was not completed.", "api_error");
146
- }
147
- return { ...terminalResult(settled, session.id), checkoutMethod: "card" };
148
- };
149
- const settleCompletion = async (completed) => {
150
- const failure = completed.autoProcessingError;
151
- if (failure?.type === "3ds_required" && failure.nextActionRedirectUrl && nonce) {
152
- return completeAction(failure.nextActionRedirectUrl, nonce);
153
- }
154
- if (failure) {
155
- throw processErrorToFloPayError(failure, "Automatic payment failed. Please try again.");
156
- }
157
- const settled = completionSession(completed, session);
158
- if (!isTerminalSuccess(settled)) {
159
- throw new FloPayError("Automatic payment failed. Please try again.", "api_error", {
160
- ...settled?.status === "expired" ? { code: "session_expired" } : {}
161
- });
162
- }
163
- return terminalResult(settled, session.id);
164
- };
165
- if (unified?.autoProcessingPending || unified?.autoProcessingError) {
166
- const pending = unified.autoProcessingPending;
167
- const completed = pending ? await api.waitForCheckoutSessionCompletion(pending.sessionId || session.id, {
168
- initialDelayMs: pending.retryAfterMs,
169
- nonce,
170
- statusUrl: pending.statusUrl,
171
- ...signal ? { signal } : {}
172
- }) : unified;
173
- return settleCompletion(completed);
174
- }
175
- const customer = session.customer;
176
- const response = await api.processPayment(customer?.id ?? "", {
177
- sessionId: session.id,
178
- nonce,
179
- paymentMethodCategory: "saved",
180
- accountData: {
181
- userId: customer?.id ?? "",
182
- email: customer?.email ?? "",
183
- firstName: customer?.firstName ?? "",
184
- lastName: customer?.lastName ?? "",
185
- country: customer?.country ?? void 0,
186
- zip: customer?.zip ?? void 0
187
- },
188
- returnUrl: typeof window === "undefined" ? void 0 : window.location.href
189
- });
190
- const body = await response.json().catch(() => null);
191
- if (response.status === 202) {
192
- const completed = await api.waitForCheckoutSessionCompletion(session.id, {
193
- ...typeof body?.retryAfterMs === "number" ? { initialDelayMs: body.retryAfterMs } : {},
194
- ...typeof body?.statusUrl === "string" ? { statusUrl: body.statusUrl } : {},
195
- nonce,
196
- ...signal ? { signal } : {}
197
- });
198
- return settleCompletion(completed);
199
- }
200
- if (response.ok) {
201
- const authorized = body?.status === "authorized" || session.captureMethod === "manual";
202
- return authorized ? { status: "authorized", paymentId: body?.paymentId ?? session.paymentId } : { status: "succeeded" };
203
- }
204
- if (body?.type === "3ds_required" && typeof body.nextActionRedirectUrl === "string" && nonce) {
205
- return completeAction(body.nextActionRedirectUrl, nonce);
206
- }
207
- throw new FloPayError(
208
- body?.message ?? "Payment failed. Please try again.",
209
- "api_error",
210
- {
211
- code: body?.code ?? body?.gatewayErrorCode,
212
- declineCode: body?.declineCode ?? body?.gatewayDeclineReason,
213
- statusCode: response.status
214
- }
215
- );
216
- }
217
-
218
- // src/split-card-form.ts
219
- import { PaymentAPI as PaymentAPI2, PciVaultCardCapture } from "@flopay/js/card-setup";
220
- import {
221
- buildCardFieldLabelsPayload,
222
- buildCheckoutProcessMetadata,
223
- buildProcessPaymentAvsAccount,
224
- buyerEmailRequiredPrompt,
225
- CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED,
226
- COUNTRY_OPTIONS,
227
- canRecoverHostedCardForm,
228
- cardFieldsInstrumentSource,
229
- computeVaultCardThemeColors,
230
- derivePrimaryTileStyle,
231
- detectPayPalEnvironment as detectPayPalEnvironment2,
232
- FloPayError as FloPayError3,
233
- filterStripeMethodsByCountryGate,
234
- getStateFromPostalCode,
235
- invokeMerchantCallback as invokeMerchantCallback2,
236
- isAVSFieldVisible,
237
- isMountableVaultBlock,
238
- isValidEmail as isValidEmail3,
239
- isValidPostalCode,
240
- markSessionRecentlyCompleted,
241
- normalizeBeforeButtonClickError,
242
- resolveAVSConfig,
243
- resolveBillingApiUrl as resolveBillingApiUrl2,
244
- resolveButtonsLayoutTheme,
245
- resolveStripePayPalPresentation,
246
- resolveTheme,
247
- resolveVaultMountOptions,
248
- STRIPE_EXPRESS_METHODS,
249
- WALLET_SHEET_WINDOW_TOO_SMALL_CODE
250
- } from "@flopay/shared";
251
- import {
252
- Comment,
253
- computed as computed2,
254
- defineComponent as defineComponent3,
255
- Fragment,
256
- h as h3,
257
- inject as inject2,
258
- onBeforeUnmount as onBeforeUnmount3,
259
- onMounted as onMounted2,
260
- ref as ref3,
261
- shallowRef as shallowRef2,
262
- Text,
263
- watch as watch2
264
- } from "vue";
265
-
266
- // src/direct-paypal-button.ts
267
- import { PaymentAPI } from "@flopay/js/card-setup";
268
- import {
269
- applyFriendlyMessageOverride,
270
- buildExternalMethodRecoveryMessage,
271
- buildPayPalCancelEvent,
272
- buildPayPalProcessPaymentRequest,
273
- buildPayPalSessionIntentRequest,
274
- buildPayPalTokenizedBody,
275
- classifyExternalMethodFailure,
276
- compactBuyerIdentity as compactBuyerIdentity2,
277
- describePayPalProcessFailure,
278
- detectPayPalEnvironment,
279
- FloPayError as FloPayError2,
280
- friendlyPayPalFailureMessage,
281
- generateIdempotencyKey,
282
- invokeMerchantCallback,
283
- isPayPalAcknowledgementDeadWindow,
284
- isPayPalTeardownMessage,
285
- isSettledSessionIntent,
286
- isValidEmail as isValidEmail2,
287
- mergePayPalPayerIdentity,
288
- needsPayPalPayerDetails,
289
- normalizeGatewayEnvironment,
290
- paypalProviderIdentityRequired,
291
- resolveBillingApiUrl,
292
- resolvePayPalApprovalIdentity,
293
- resolvePayPalDeclineReason,
294
- resolvePayPalPresentationMode
295
- } from "@flopay/shared";
296
- import { loadScript } from "@paypal/paypal-js";
297
- import {
298
- computed,
299
- defineComponent as defineComponent2,
300
- h as h2,
301
- inject,
302
- onBeforeUnmount as onBeforeUnmount2,
303
- onMounted,
304
- ref as ref2,
305
- watch
306
- } from "vue";
307
-
308
- // src/buyer-identity-fallback.ts
309
- import { compactBuyerIdentity, isValidEmail } from "@flopay/shared";
310
- import { defineComponent, h, onBeforeUnmount, ref, shallowRef } from "vue";
311
- function createBuyerIdentityFallback() {
312
- const request = shallowRef(null);
313
- let resolver = null;
314
- let requestId = 0;
315
- const collect = (methodLabel, identity) => {
316
- resolver?.(null);
317
- requestId += 1;
318
- request.value = { id: requestId, methodLabel, identity };
319
- return new Promise((resolve) => {
320
- resolver = resolve;
321
- });
322
- };
323
- const finish = (identity) => {
324
- const resolve = resolver;
325
- resolver = null;
326
- request.value = null;
327
- resolve?.(identity);
328
- };
329
- onBeforeUnmount(() => {
330
- resolver?.(null);
331
- resolver = null;
332
- });
333
- return { request, collect, finish };
334
- }
335
- var inputStyle = {
336
- minHeight: "42px",
337
- padding: "0 0.75rem",
338
- border: "1px solid #d1d5db",
339
- borderRadius: "6px"
340
- };
341
- var BuyerIdentityFallbackPanel = defineComponent({
342
- name: "BuyerIdentityFallbackPanel",
343
- props: {
344
- identity: { type: Object, required: true },
345
- methodLabel: { type: String, required: true },
346
- /** Renders a Cancel button (React renders it when `onCancel` is passed). */
347
- cancellable: { type: Boolean, default: false },
348
- submitting: { type: Boolean, default: false },
349
- testId: { type: String, default: "flopay-buyer-identity-pane" }
350
- },
351
- emits: {
352
- complete: (_identity) => true,
353
- cancel: () => true
354
- },
355
- setup(props, { emit }) {
356
- const email = ref(props.identity.email?.trim() ?? "");
357
- return () => {
358
- const valid = isValidEmail(email.value.trim());
359
- return h(
360
- "div",
361
- {
362
- "data-testid": props.testId,
363
- style: {
364
- display: "flex",
365
- flexDirection: "column",
366
- gap: "0.75rem",
367
- padding: "0.875rem",
368
- border: "1px solid #d1d5db",
369
- borderRadius: "8px",
370
- background: "#fff",
371
- color: "#262833"
372
- }
373
- },
374
- [
375
- h("div", { style: { fontWeight: 700 } }, `Continue with ${props.methodLabel}`),
376
- h("label", { style: { display: "flex", flexDirection: "column", gap: "0.375rem" } }, [
377
- "Email address",
378
- h("input", {
379
- type: "email",
380
- autocomplete: "email",
381
- "data-testid": "flopay-email",
382
- required: true,
383
- value: email.value,
384
- onInput: (event) => {
385
- email.value = event.target.value;
386
- },
387
- style: inputStyle
388
- })
389
- ]),
390
- h("div", { style: { display: "flex", gap: "0.5rem" } }, [
391
- props.cancellable ? h(
392
- "button",
393
- {
394
- type: "button",
395
- onClick: () => emit("cancel"),
396
- style: { flex: 1, minHeight: "42px" }
397
- },
398
- "Cancel"
399
- ) : null,
400
- h(
401
- "button",
402
- {
403
- type: "button",
404
- disabled: !valid || props.submitting,
405
- onClick: () => emit(
406
- "complete",
407
- compactBuyerIdentity({ ...props.identity, email: email.value.trim() })
408
- ),
409
- style: { flex: 2, minHeight: "42px" }
410
- },
411
- `Continue with ${props.methodLabel}`
412
- )
413
- ])
414
- ]
415
- );
416
- };
417
- }
418
- });
419
-
420
- // src/direct-paypal-button.ts
421
- var PAYPAL_INTENT_SETTLED_CODE = "paypal_intent_settled";
422
- var PAYPAL_INIT_RETRY_DELAY_MS = 1e3;
423
- var PayPalStartupFailure = class extends Error {
424
- constructor(message, options = {}) {
425
- super(message);
426
- this.ineligible = options.ineligible ?? false;
427
- if (options.cause !== void 0) this.cause = options.cause;
428
- }
429
- };
430
- var errorMessage = (error, fallback) => error instanceof Error ? error.message : fallback;
431
- var debugPanelStyle = (failed) => ({
432
- margin: "0 0 8px 0",
433
- padding: "6px 8px",
434
- background: failed ? "#fef2f2" : "#f3f4f6",
435
- border: `1px solid ${failed ? "#fca5a5" : "#d1d5db"}`,
436
- borderRadius: "6px",
437
- color: "#111827",
438
- font: "11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",
439
- whiteSpace: "pre-wrap",
440
- wordBreak: "break-word",
441
- maxHeight: "220px",
442
- overflowY: "auto"
443
- });
444
- var DirectPayPalButton = defineComponent2({
445
- name: "DirectPayPalButton",
446
- props: {
447
- sessionId: { type: String, default: void 0 },
448
- nonce: { type: String, default: void 0 },
449
- billingApiUrl: { type: String, default: void 0 },
450
- email: { type: String, default: void 0 },
451
- billingName: { type: String, default: void 0 },
452
- onBuyerIdentityReady: {
453
- type: Function,
454
- default: void 0
455
- },
456
- clientId: { type: String, default: void 0 },
457
- environment: {
458
- type: String,
459
- default: void 0
460
- },
461
- currency: { type: String, default: void 0 },
462
- isSubscription: { type: Boolean, default: void 0 },
463
- providerObjectType: {
464
- type: String,
465
- default: void 0
466
- },
467
- approvalPresentation: {
468
- type: String,
469
- default: void 0
470
- },
471
- session: { type: Object, default: null },
472
- existingOrderId: { type: String, default: void 0 },
473
- isProcessing: { type: Boolean, default: false },
474
- allowAutomaticRetry: { type: Boolean, default: true },
475
- runBeforeButtonClick: {
476
- type: Function,
477
- default: void 0
478
- },
479
- onTokenizedBody: {
480
- type: Function,
481
- default: void 0
482
- },
483
- onTechnicalFailure: {
484
- type: Function,
485
- default: void 0
486
- },
487
- telemetry: { type: Boolean, default: void 0 },
488
- debug: { type: Boolean, default: false }
489
- },
490
- emits: {
491
- complete: (_result) => true,
492
- decline: (_decline) => true,
493
- /** The buyer closed or left PayPal without approving (once per click attempt). */
494
- cancel: (_event) => true,
495
- error: (_error) => true,
496
- errorChange: (_message) => true,
497
- buttonClick: (_method) => true,
498
- loadStateChange: (_ready) => true,
499
- initializationStateChange: (_state) => true
500
- },
501
- setup(props, { emit }) {
502
- const provider = inject(FLOPAY_CONTEXT, null);
503
- const container = ref2(null);
504
- const state = ref2("loading");
505
- const submitting = ref2(false);
506
- const debugLines = ref2([]);
507
- let buttons = null;
508
- let mounted = false;
509
- let unmounted = false;
510
- let generation = 0;
511
- let retryTimer = null;
512
- let prepared = null;
513
- let attemptLive = false;
514
- let intentIdempotencyKey;
515
- let intentAttemptActive = false;
516
- let attemptSettled = false;
517
- const beginIntentAttempt = () => {
518
- intentIdempotencyKey = generateIdempotencyKey();
519
- if (!intentIdempotencyKey) {
520
- console.warn(
521
- "[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."
522
- );
523
- }
524
- intentAttemptActive = true;
525
- };
526
- const {
527
- request: identityRequest,
528
- collect: collectBuyerIdentity,
529
- finish: finishBuyerIdentity
530
- } = createBuyerIdentityFallback();
531
- let identityRequirement = {
532
- sessionId: props.sessionId,
533
- required: paypalProviderIdentityRequired(props.email, props.session)
534
- };
535
- const providerIdentityRequired = () => {
536
- if (identityRequirement.sessionId !== props.sessionId) {
537
- identityRequirement = {
538
- sessionId: props.sessionId,
539
- required: paypalProviderIdentityRequired(props.email, props.session)
540
- };
541
- }
542
- return identityRequirement.required;
543
- };
544
- watch(
545
- () => props.sessionId,
546
- () => {
547
- providerIdentityRequired();
548
- }
549
- );
550
- const isCurrent = (gen) => !unmounted && gen === generation;
551
- const trace = (line) => {
552
- if (!props.debug) return;
553
- debugLines.value = [...debugLines.value, `${(/* @__PURE__ */ new Date()).toISOString().slice(11, 23)} ${line}`];
554
- };
555
- watch(
556
- () => props.debug,
557
- (on) => {
558
- if (on) trace("debug:enabled");
559
- },
560
- { immediate: true }
561
- );
562
- const setState = (next) => {
563
- state.value = next;
564
- invokeMerchantCallback(() => emit("initializationStateChange", next));
565
- };
566
- const ready = computed(() => state.value === "ready");
567
- const failed = computed(() => state.value === "exhausted");
568
- watch(
569
- [ready, failed],
570
- ([isReady, isFailed]) => {
571
- if (!mounted) return;
572
- invokeMerchantCallback(() => emit("loadStateChange", isReady && !isFailed));
573
- },
574
- { flush: "sync" }
575
- );
576
- const baseUrl = () => resolveBillingApiUrl(props.billingApiUrl ?? provider?.billingApiUrl() ?? void 0);
577
- const configuredObjectType = () => props.session?.gateways?.paypal?.providerObjectType ?? props.providerObjectType;
578
- const objectType = () => configuredObjectType() ?? (props.isSubscription ? "subscription" : "order");
579
- const advertisedPresentation = () => props.session?.gateways?.paypal?.approvalPresentation ?? props.approvalPresentation;
580
- const api = () => new PaymentAPI(baseUrl(), { telemetry: false });
581
- const inAppBrowser = () => detectPayPalEnvironment().inAppBrowser;
582
- const effectiveSessionId = () => prepared?.sessionId ?? props.sessionId ?? "";
583
- const effectiveNonce = () => prepared?.nonce ?? props.nonce;
584
- const reportSettledIntentVerdict = async (response, sessionId) => {
585
- if (response.ok) {
586
- const result = { status: "succeeded", checkoutMethod: "paypal" };
587
- invokeMerchantCallback(() => emit("complete", result));
588
- return;
589
- }
590
- const json = await response.json().catch(() => null);
591
- const failure = describePayPalProcessFailure(json);
592
- emitDecline(failure.message, sessionId, {
593
- code: failure.code,
594
- declineCode: failure.declineCode
595
- });
596
- };
597
- const createIntent = async () => {
598
- if (!intentAttemptActive) beginIntentAttempt();
599
- const intent = await api().createSessionIntent(
600
- effectiveSessionId(),
601
- effectiveNonce() ?? "",
602
- buildPayPalSessionIntentRequest(configuredObjectType()),
603
- { idempotencyKey: intentIdempotencyKey }
604
- );
605
- if (isSettledSessionIntent(intent)) {
606
- await reportSettledIntentVerdict(intent.response, effectiveSessionId());
607
- attemptSettled = true;
608
- attemptLive = false;
609
- prepared = null;
610
- throw new FloPayError2("PayPal checkout already settled.", "api_error", {
611
- code: PAYPAL_INTENT_SETTLED_CODE
612
- });
613
- }
614
- if (intent.provider !== "paypal" || intent.providerObjectType !== objectType()) {
615
- throw new FloPayError2("PayPal could not start this payment.", "api_error", {
616
- code: "paypal_intent_mismatch"
617
- });
618
- }
619
- return intent.providerObjectId;
620
- };
621
- const emitDecline = (message, sessionId, codes = {}) => {
622
- const event = {
623
- method: "paypal",
624
- message,
625
- ...codes.code ? { code: codes.code } : {},
626
- ...codes.declineCode ? { declineCode: codes.declineCode } : {},
627
- ...sessionId ? { sessionId } : {}
628
- };
629
- invokeMerchantCallback(() => emit("decline", event));
630
- };
631
- const decline = (error) => {
632
- const message = errorMessage(error, "PayPal payment failed.");
633
- const nonce = effectiveNonce();
634
- const sessionId = effectiveSessionId();
635
- if (nonce) {
636
- void api().reportSessionIntentDecline(sessionId, nonce, {
637
- provider: "paypal",
638
- paymentMethodCategory: "wallet",
639
- paymentMethodType: "paypal",
640
- providerDeclineReason: resolvePayPalDeclineReason(error)
641
- }).catch(() => {
642
- });
643
- }
644
- emitDecline(message, sessionId);
645
- };
646
- const forwardError = (message) => {
647
- if (isPayPalTeardownMessage(message)) return;
648
- const friendly = applyFriendlyMessageOverride(message) ?? message;
649
- invokeMerchantCallback(() => emit("errorChange", friendly));
650
- };
651
- const notifyTechnicalFailure = (error, recoveryMessage, options) => {
652
- const handler = props.onTechnicalFailure;
653
- if (handler) {
654
- const callbackError = options.popupBlocked && inAppBrowser() ? new FloPayError2(recoveryMessage, "api_error", {
655
- code: options.code ?? "paypal_popup_blocked"
656
- }) : error;
657
- invokeMerchantCallback(() => handler("paypal", callbackError, options));
658
- return;
659
- }
660
- invokeMerchantCallback(() => emit("errorChange", recoveryMessage));
661
- };
662
- const runtimeFailure = (error) => {
663
- attemptLive = false;
664
- const message = errorMessage(error, "PayPal failed to render.");
665
- if (isPayPalTeardownMessage(message)) {
666
- prepared = null;
667
- return;
668
- }
669
- const classification = classifyExternalMethodFailure(error, {
670
- inAppBrowser: inAppBrowser(),
671
- handoffObserved: false
672
- });
673
- if (classification.providerDeclined) {
674
- decline(error);
675
- prepared = null;
676
- return;
677
- }
678
- prepared = null;
679
- if (error instanceof FloPayError2 && error.code === "checkout_processing_timeout") {
680
- invokeMerchantCallback(() => emit("error", error));
681
- notifyTechnicalFailure(error, error.message, {
682
- code: "checkout_processing_timeout",
683
- popupBlocked: false,
684
- provider: "paypal",
685
- paymentMethodCategory: "paypal",
686
- terminalReason: classification.terminalReason
687
- });
688
- return;
689
- }
690
- const recoveryMessage = buildExternalMethodRecoveryMessage(
691
- "PayPal",
692
- classification.popupBlocked,
693
- inAppBrowser()
694
- );
695
- const failure = new FloPayError2(recoveryMessage, "api_error", {
696
- code: classification.popupBlocked ? "paypal_popup_blocked" : "paypal_runtime_failed"
697
- });
698
- invokeMerchantCallback(() => emit("error", failure));
699
- notifyTechnicalFailure(error, recoveryMessage, {
700
- code: "paypal_runtime_failed",
701
- popupBlocked: classification.popupBlocked,
702
- provider: "paypal",
703
- paymentMethodCategory: "paypal",
704
- terminalReason: classification.terminalReason
705
- });
706
- };
707
- const tokenizedBody = (token) => buildPayPalTokenizedBody(token, configuredObjectType());
708
- const processApproval = async (gen, body, attempt) => {
709
- const sessionId = attempt?.sessionId ?? props.sessionId ?? "";
710
- const request = buildPayPalProcessPaymentRequest({
711
- body,
712
- sessionId,
713
- nonce: attempt?.nonce ?? props.nonce,
714
- accountPatch: attempt?.accountPatch,
715
- session: props.session,
716
- email: props.email
717
- });
718
- let response;
719
- try {
720
- response = await api().processPayment(request.userId, request.params);
721
- } catch (error) {
722
- if (!isCurrent(gen)) return;
723
- const message = friendlyPayPalFailureMessage(
724
- error instanceof Error ? error.message : void 0
725
- );
726
- forwardError(message);
727
- emitDecline(message, sessionId);
728
- return;
729
- }
730
- if (response.ok) {
731
- if (gen !== generation) return;
732
- trace("process:ok");
733
- const result = { status: "succeeded", checkoutMethod: "paypal" };
734
- invokeMerchantCallback(() => emit("complete", result));
735
- return;
736
- }
737
- if (!isCurrent(gen)) return;
738
- const json = await response.json().catch(() => null);
739
- const failure = describePayPalProcessFailure(json);
740
- trace(`process:rejected status=${response.status}`);
741
- forwardError(failure.message);
742
- emitDecline(failure.message, sessionId, {
743
- code: failure.code,
744
- declineCode: failure.declineCode
745
- });
746
- };
747
- const resolveApprovalIdentity = async (attempt, actions) => {
748
- let identity = resolvePayPalApprovalIdentity({
749
- accountPatch: attempt?.accountPatch,
750
- email: props.email,
751
- billingName: props.billingName,
752
- session: props.session
753
- });
754
- if (needsPayPalPayerDetails(identity)) {
755
- try {
756
- identity = mergePayPalPayerIdentity(identity, await actions?.order?.get?.());
757
- } catch {
758
- }
759
- }
760
- if ((props.onBuyerIdentityReady || providerIdentityRequired()) && !isValidEmail2(identity.email)) {
761
- trace("identity:collect");
762
- const collected = await collectBuyerIdentity("PayPal", identity);
763
- if (!collected) return null;
764
- identity = collected;
765
- }
766
- return identity;
767
- };
768
- const approve = async (gen, data, actions) => {
769
- if (!isCurrent(gen)) return;
770
- attemptLive = false;
771
- const attempt = { ...prepared ?? {} };
772
- submitting.value = true;
773
- trace("onApprove");
774
- invokeMerchantCallback(() => emit("errorChange", null));
775
- try {
776
- const token = data.vaultSetupToken ?? data.subscriptionID ?? data.orderID ?? "";
777
- if (!token) {
778
- throw new FloPayError2("PayPal did not return an approval token.", "api_error", {
779
- code: "paypal_missing_token"
780
- });
781
- }
782
- const identity = await resolveApprovalIdentity(attempt, actions);
783
- if (!identity) {
784
- trace("identity:cancelled");
785
- return;
786
- }
787
- if (isValidEmail2(identity.email)) {
788
- attempt.accountPatch = compactBuyerIdentity2({ ...attempt.accountPatch, ...identity });
789
- await props.onBuyerIdentityReady?.(identity);
790
- }
791
- if (!isCurrent(gen)) return;
792
- const body = tokenizedBody(token);
793
- const handler = props.onTokenizedBody;
794
- if (handler) {
795
- await handler(body, {
796
- sessionId: attempt.sessionId ?? props.sessionId,
797
- accountPatch: attempt.accountPatch,
798
- nonce: attempt.nonce
799
- });
800
- return;
801
- }
802
- await processApproval(gen, body, attempt);
803
- } catch (error) {
804
- if (!isCurrent(gen)) return;
805
- forwardError(errorMessage(error, "PayPal capture failed."));
806
- } finally {
807
- if (!unmounted) submitting.value = false;
808
- }
809
- };
810
- const click = async (gen, actions) => {
811
- if (!isCurrent(gen)) {
812
- await actions.reject();
813
- return;
814
- }
815
- beginIntentAttempt();
816
- prepared = null;
817
- attemptLive = false;
818
- attemptSettled = false;
819
- let next = {};
820
- const runner = props.runBeforeButtonClick;
821
- if (runner) {
822
- try {
823
- const beforeClick = await runner("paypal");
824
- if (!isCurrent(gen)) {
825
- await actions.reject();
826
- return;
827
- }
828
- if (!beforeClick.proceed) {
829
- trace("onClick:runBeforeButtonClick proceed=false");
830
- await actions.reject();
831
- return;
832
- }
833
- next = {
834
- sessionId: beforeClick.sessionId,
835
- accountPatch: beforeClick.accountPatch,
836
- nonce: beforeClick.nonce
837
- };
838
- } catch (error) {
839
- trace(
840
- `onClick:runBeforeButtonClick rejected msg=${errorMessage(error, String(error)).slice(0, 120)}`
841
- );
842
- await actions.reject();
843
- return;
844
- }
845
- }
846
- invokeMerchantCallback(() => emit("buttonClick", "paypal"));
847
- prepared = next;
848
- attemptLive = true;
849
- trace("onClick:resolve");
850
- await actions.resolve();
851
- };
852
- const cancel = (gen) => {
853
- if (!isCurrent(gen) || !attemptLive) return;
854
- attemptLive = false;
855
- const event = buildPayPalCancelEvent(effectiveSessionId(), configuredObjectType());
856
- prepared = null;
857
- trace("onCancel");
858
- invokeMerchantCallback(() => emit("cancel", event));
859
- };
860
- const renderButtons = async (gen) => {
861
- const normalized = normalizeGatewayEnvironment(props.environment);
862
- const environment = normalized === "live" ? "production" : normalized;
863
- const type = objectType();
864
- const existingOrderId = props.existingOrderId;
865
- trace(`loadScript:start env=${environment ?? "default"} type=${type}`);
866
- let paypal;
867
- try {
868
- paypal = await loadScript({
869
- clientId: props.clientId ?? "",
870
- ...props.currency ? { currency: props.currency } : {},
871
- ...type === "subscription" ? { intent: "subscription", vault: true } : {},
872
- ...type === "order" ? { intent: "capture" } : {},
873
- ...environment ? { environment } : {},
874
- ...environment === "sandbox" ? { dataNamespace: "paypal_sandbox" } : {}
875
- });
876
- } catch (error) {
877
- trace(`loadScript:fail msg=${errorMessage(error, String(error)).slice(0, 120)}`);
878
- throw new PayPalStartupFailure(errorMessage(error, "PayPal failed to load."), {
879
- cause: error
880
- });
881
- }
882
- if (!isCurrent(gen)) return;
883
- trace("loadScript:ok");
884
- if (!paypal?.Buttons) throw new PayPalStartupFailure("PayPal did not initialize.");
885
- const start2 = () => {
886
- if (!existingOrderId) return createIntent();
887
- if (isCurrent(gen)) return Promise.resolve(existingOrderId);
888
- return Promise.reject(
889
- new FloPayError2("PayPal render was superseded.", "api_error", {
890
- code: "paypal_render_superseded"
891
- })
892
- );
893
- };
894
- let handlers;
895
- if (type === "subscription") handlers = { createSubscription: start2 };
896
- else if (type === "setup_token") handlers = { createVaultSetupToken: () => createIntent() };
897
- else handlers = { createOrder: start2 };
898
- const presentation = resolvePayPalPresentationMode(
899
- detectPayPalEnvironment(),
900
- advertisedPresentation() === "app_switch" ? "app_switch" : void 0,
901
- type
902
- );
903
- trace(`presentation=${presentation}`);
904
- let rendered = false;
905
- const instance = paypal.Buttons({
906
- style: { layout: "horizontal", tagline: false, height: 44 },
907
- ...presentation === "app_switch" ? { appSwitchWhenAvailable: true } : {},
908
- ...handlers,
909
- onClick: (_data, actions) => click(gen, actions),
910
- onApprove: (data, actions) => approve(gen, data, actions),
911
- onCancel: () => cancel(gen),
912
- onError: (error) => {
913
- if (!isCurrent(gen)) return;
914
- if (attemptSettled || error instanceof FloPayError2 && error.code === PAYPAL_INTENT_SETTLED_CODE) {
915
- trace("onError:settled");
916
- return;
917
- }
918
- trace(
919
- `onError rendered=${rendered} msg=${errorMessage(error, "PayPal failed to render.").slice(0, 120)}`
920
- );
921
- if (rendered) runtimeFailure(error);
922
- }
923
- });
924
- buttons = instance;
925
- const eligible = instance.isEligible();
926
- trace(`isEligible=${eligible}`);
927
- if (!eligible) {
928
- throw new PayPalStartupFailure("PayPal is not available for this buyer.", {
929
- ineligible: true
930
- });
931
- }
932
- try {
933
- if (container.value) await instance.render(container.value);
934
- } catch (error) {
935
- trace(`render:fail msg=${errorMessage(error, String(error)).slice(0, 120)}`);
936
- throw new PayPalStartupFailure(errorMessage(error, "PayPal failed to render."), {
937
- cause: error
938
- });
939
- }
940
- if (!isCurrent(gen)) return;
941
- rendered = true;
942
- trace("render:ok");
943
- };
944
- const exhaust = (failure) => {
945
- setState("exhausted");
946
- trace(`exhausted msg=${failure.message.slice(0, 120)}`);
947
- if (failure.ineligible) {
948
- console.error("[FloPay] DirectPayPal load/render failure:", failure.message);
949
- return;
950
- }
951
- const classification = classifyExternalMethodFailure(
952
- {
953
- code: isPayPalAcknowledgementDeadWindow(failure.message) ? "paypal_init_timeout" : "paypal_init_failure",
954
- message: failure.message
955
- },
956
- { inAppBrowser: inAppBrowser(), handoffObserved: false }
957
- );
958
- provider?.emitInstrument({
959
- class: "technical_error",
960
- errorCode: "PROVIDER_LOAD_FAILED",
961
- provider: "paypal"
962
- });
963
- const error = classification.popupBlocked ? new FloPayError2(
964
- buildExternalMethodRecoveryMessage("PayPal", true, inAppBrowser()),
965
- "api_error",
966
- { code: "paypal_popup_blocked" }
967
- ) : new FloPayError2(failure.message, "api_error", { code: "PROVIDER_LOAD_FAILED" });
968
- invokeMerchantCallback(() => emit("error", error));
969
- };
970
- const closeButtons = () => {
971
- void buttons?.close().catch(() => {
972
- });
973
- buttons = null;
974
- };
975
- const start = async (gen, retryUsed) => {
976
- try {
977
- await renderButtons(gen);
978
- if (isCurrent(gen)) setState("ready");
979
- } catch (error) {
980
- if (!isCurrent(gen)) return;
981
- const failure = error instanceof PayPalStartupFailure ? error : new PayPalStartupFailure(errorMessage(error, String(error)), { cause: error });
982
- closeButtons();
983
- if (!failure.ineligible && !retryUsed && props.allowAutomaticRetry) {
984
- setState("retrying");
985
- trace("retry:scheduled");
986
- retryTimer = setTimeout(() => {
987
- retryTimer = null;
988
- if (isCurrent(gen)) void start(gen, true);
989
- }, PAYPAL_INIT_RETRY_DELAY_MS);
990
- return;
991
- }
992
- exhaust(failure);
993
- }
994
- };
995
- const restart = () => {
996
- generation += 1;
997
- if (retryTimer) clearTimeout(retryTimer);
998
- retryTimer = null;
999
- prepared = null;
1000
- attemptLive = false;
1001
- intentIdempotencyKey = void 0;
1002
- intentAttemptActive = false;
1003
- attemptSettled = false;
1004
- closeButtons();
1005
- if (!props.clientId) {
1006
- setState("exhausted");
1007
- return;
1008
- }
1009
- setState("loading");
1010
- trace("mount");
1011
- void start(generation, false);
1012
- };
1013
- const configKey = computed(
1014
- () => JSON.stringify([
1015
- baseUrl(),
1016
- props.clientId ?? "",
1017
- props.currency ?? "",
1018
- props.environment ?? "",
1019
- objectType(),
1020
- props.sessionId ?? "",
1021
- props.existingOrderId ?? "",
1022
- advertisedPresentation() === "app_switch" ? "app_switch" : ""
1023
- ])
1024
- );
1025
- watch(configKey, () => {
1026
- if (mounted && !unmounted) restart();
1027
- });
1028
- onMounted(() => {
1029
- mounted = true;
1030
- invokeMerchantCallback(() => emit("loadStateChange", false));
1031
- restart();
1032
- });
1033
- onBeforeUnmount2(() => {
1034
- unmounted = true;
1035
- if (retryTimer) clearTimeout(retryTimer);
1036
- retryTimer = null;
1037
- prepared = null;
1038
- closeButtons();
1039
- });
1040
- return () => {
1041
- const debugPanel = props.debug ? h2(
1042
- "pre",
1043
- {
1044
- "data-testid": "flopay-direct-paypal-debug",
1045
- style: debugPanelStyle(failed.value)
1046
- },
1047
- `FloPay/DirectPayPal-debug (ready=${ready.value} failed=${failed.value})${debugLines.value.length === 0 ? "\n(waiting for first lifecycle event\u2026)" : `
1048
- ${debugLines.value.join("\n")}`}`
1049
- ) : null;
1050
- if (failed.value) return debugPanel ? h2("div", [debugPanel]) : null;
1051
- const request = identityRequest.value;
1052
- return h2("div", [
1053
- debugPanel,
1054
- request ? h2(BuyerIdentityFallbackPanel, {
1055
- key: request.id,
1056
- identity: request.identity,
1057
- methodLabel: request.methodLabel,
1058
- cancellable: true,
1059
- testId: "flopay-direct-paypal-identity-pane",
1060
- onComplete: (identity) => finishBuyerIdentity(identity),
1061
- onCancel: () => finishBuyerIdentity(null)
1062
- }) : null,
1063
- // While the panel is open React keeps PayPal mounted but out of the
1064
- // way (zoid needs a measurable container, so no `display: none`).
1065
- h2("div", {
1066
- ref: container,
1067
- "data-testid": "flopay-direct-paypal",
1068
- "data-state": state.value,
1069
- "aria-busy": submitting.value || props.isProcessing,
1070
- ...request ? {
1071
- "aria-hidden": "true",
1072
- style: { position: "relative", height: "0", opacity: "0", pointerEvents: "none" }
1073
- } : {}
1074
- })
1075
- ]);
1076
- };
1077
- }
1078
- });
1079
-
1080
- // src/split-card-form.ts
1081
- var SUCCESS_DELAY_MS = 600;
1082
- var isStripeExpressMethod = (method) => STRIPE_EXPRESS_METHODS.includes(method);
1083
- var GATE_DEBUG_STYLE = {
1084
- margin: 0,
1085
- padding: "6px 8px",
1086
- background: "#eef2ff",
1087
- border: "1px solid #c7d2fe",
1088
- borderRadius: "6px",
1089
- color: "#111827",
1090
- font: "11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",
1091
- whiteSpace: "pre-wrap",
1092
- wordBreak: "break-word"
1093
- };
1094
- var PAYPAL_DIRECT_RETRY_LIMIT = 2;
1095
- function isEmptySlotOutput(nodes) {
1096
- return nodes.every((node) => {
1097
- if (node.type === Comment) return true;
1098
- if (node.type === Text) return !String(node.children ?? "").trim();
1099
- if (node.type === Fragment) {
1100
- return Array.isArray(node.children) && isEmptySlotOutput(node.children);
1101
- }
1102
- return false;
1103
- });
1104
- }
1105
- function defaultCardButtonContent() {
1106
- const svg = { fill: "none", "stroke-linecap": "round", "stroke-linejoin": "round" };
1107
- return [
1108
- h3(
1109
- "svg",
1110
- {
1111
- ...svg,
1112
- width: "20",
1113
- height: "20",
1114
- viewBox: "0 0 24 24",
1115
- stroke: "currentColor",
1116
- "stroke-width": "1.5",
1117
- "aria-hidden": "true"
1118
- },
1119
- [
1120
- h3("rect", { width: "20", height: "14", x: "2", y: "5", rx: "2" }),
1121
- h3("line", { x1: "2", x2: "22", y1: "10", y2: "10" })
1122
- ]
1123
- ),
1124
- "Credit / Debit Card",
1125
- h3(
1126
- "svg",
1127
- {
1128
- ...svg,
1129
- width: "16",
1130
- height: "16",
1131
- viewBox: "0 0 24 24",
1132
- stroke: "#9ca3af",
1133
- "stroke-width": "2",
1134
- style: { position: "absolute", right: "1rem" },
1135
- "aria-hidden": "true"
1136
- },
1137
- [h3("path", { d: "M9 18l6-6-6-6" })]
1138
- )
1139
- ];
1140
- }
1141
- var DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT = 44;
1142
- function resolveFormButtonsStyles(bundleStyles, buttonsTheme, override) {
1143
- const base = bundleStyles ?? resolveButtonsLayoutTheme(buttonsTheme);
1144
- if (!override) return base;
1145
- return {
1146
- ...base,
1147
- ...override,
1148
- cardButton: { ...base.cardButton, ...override.cardButton },
1149
- cardFormContainer: { ...base.cardFormContainer, ...override.cardFormContainer },
1150
- backButton: { ...base.backButton, ...override.backButton },
1151
- backButtonIcon: { ...base.backButtonIcon, ...override.backButtonIcon },
1152
- submitButton: { ...base.submitButton, ...override.submitButton },
1153
- title: { ...base.title, ...override.title }
1154
- };
1155
- }
1156
- var ERROR_DELAY_MS = 1200;
1157
- function isAccountValidationError(error) {
1158
- return error instanceof FloPayError3 && typeof error.statusCode === "number" && error.statusCode >= 400 && error.statusCode < 500;
1159
- }
1160
- function noVaultCapabilityError() {
1161
- return new FloPayError3(
1162
- "FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.",
1163
- "api_error",
1164
- { code: "UnsupportedBackendVaultCapability" }
1165
- );
1166
- }
1167
- var CARD_FIELD_PLACEHOLDER_KEYS = ["number", "expiry", "cvv", "name"];
1168
- function cardFieldPlaceholdersContentKey(value) {
1169
- if (value === null || typeof value !== "object") return null;
1170
- const fields = {};
1171
- for (const key of CARD_FIELD_PLACEHOLDER_KEYS) {
1172
- const text = value[key];
1173
- if (typeof text === "string") fields[key] = text;
1174
- }
1175
- return JSON.stringify(fields);
1176
- }
1177
- var SplitCardForm = defineComponent3({
1178
- name: "SplitCardForm",
1179
- props: {
1180
- session: { type: Object, default: void 0 },
1181
- sessionId: { type: String, default: void 0 },
1182
- nonce: { type: String, default: void 0 },
1183
- billingApiUrl: { type: String, default: void 0 },
1184
- telemetry: { type: Boolean, default: void 0 },
1185
- email: { type: String, default: void 0 },
1186
- firstName: { type: String, default: void 0 },
1187
- lastName: { type: String, default: void 0 },
1188
- layout: { type: String, default: "default" },
1189
- initialCardOpen: { type: Boolean, default: false },
1190
- showPayPal: { type: Boolean, default: true },
1191
- // No default here: an unset prop takes the checkout's value, then `'auto'`.
1192
- walletPresentation: { type: String, default: void 0 },
1193
- showStripe: { type: Boolean, default: true },
1194
- showApplePay: { type: Boolean, default: true },
1195
- showGooglePay: { type: Boolean, default: true },
1196
- enabledPaymentMethods: { type: Array, default: void 0 },
1197
- dataAttachmentPending: { type: Boolean, default: void 0 },
1198
- dataAttachmentRequiresIdentity: { type: Boolean, default: void 0 },
1199
- submitLabel: { type: String, default: void 0 },
1200
- enableAVS: {
1201
- type: [Boolean, Object],
1202
- default: void 0
1203
- },
1204
- avsLayout: { type: String, default: "row" },
1205
- country: { type: String, default: void 0 },
1206
- zip: { type: String, default: void 0 },
1207
- addressLine1: { type: String, default: void 0 },
1208
- addressLine2: { type: String, default: void 0 },
1209
- city: { type: String, default: void 0 },
1210
- state: { type: String, default: void 0 },
1211
- isProcessing: { type: Boolean, default: void 0 },
1212
- error: { type: String, default: void 0 },
1213
- theme: { type: String, default: void 0 },
1214
- buttonsTheme: { type: String, default: void 0 },
1215
- buttonsStyles: { type: Object, default: void 0 },
1216
- appearance: { type: Object, default: void 0 },
1217
- className: { type: String, default: void 0 },
1218
- cardFieldOrder: { type: Array, default: void 0 },
1219
- showCardBrandIcons: { type: Boolean, default: false },
1220
- // `default: undefined` keeps an omitted prop `undefined` (Vue would cast an
1221
- // absent Boolean to `false`), so a form without it sends nothing.
1222
- showCardFieldLabels: { type: Boolean, default: void 0 },
1223
- cardFieldLabels: { type: Object, default: void 0 },
1224
- cardFieldPlaceholders: {
1225
- type: Object,
1226
- default: void 0
1227
- },
1228
- cardAutoFocus: { type: Boolean, default: true },
1229
- /** Milliseconds the card fields may take to become ready before `timeout` (default 15 000). */
1230
- cardFieldsTimeoutMs: { type: Number, default: void 0 },
1231
- onBeforeButtonClick: {
1232
- type: Function,
1233
- default: void 0
1234
- },
1235
- onBuyerIdentityReady: {
1236
- type: Function,
1237
- default: void 0
1238
- },
1239
- userId: { type: String, default: void 0 },
1240
- avsCheck: { type: Boolean, default: void 0 },
1241
- /** @deprecated Not rendered (React's deprecated `showSecurityFooter`). */
1242
- showSecurityFooter: { type: Boolean, default: void 0 },
1243
- directPaypal: { type: Object, default: void 0 },
1244
- currency: { type: String, default: void 0 },
1245
- isSubscription: { type: Boolean, default: void 0 },
1246
- /**
1247
- * React's `totalAmount`: the cart total due today, in minor units
1248
- * (`FloPayCheckout` passes it). Payment-mode Stripe Elements use
1249
- * `totalAmount || 100` (React's `amountInCents` placeholder for a $0 cart),
1250
- * and the wallet row runs in setup mode for $0. Default `0`, as React's.
1251
- */
1252
- totalAmount: { type: Number, default: 0 },
1253
- onTokenizedBody: {
1254
- type: Function,
1255
- default: void 0
1256
- },
1257
- chv: { type: String, default: void 0 },
1258
- checkoutType: { type: String, default: void 0 },
1259
- checkoutLayout: { type: String, default: void 0 },
1260
- enabledPaymentMethodCountries: {
1261
- type: Object,
1262
- default: void 0
1263
- },
1264
- debug: { type: Boolean, default: false }
1265
- },
1266
- emits: {
1267
- complete: (_result) => true,
1268
- error: (_error) => true,
1269
- decline: (_decline) => true,
1270
- // React's `onCancel`: the direct PayPal button's buyer cancel, re-emitted once.
1271
- cancel: (_event) => true,
1272
- buttonClick: (_method) => true,
1273
- countryChange: (_country) => true,
1274
- // React's `onZipChange`.
1275
- zipChange: (_zip) => true,
1276
- // React's `onErrorChange`: the form's own error message changed (`null` when cleared).
1277
- errorChange: (_error) => true,
1278
- // React's `onCardFieldsReady`: the hosted card fields are interactive, once per card form.
1279
- cardFieldsReady: (_event) => true,
1280
- // React's `onCardFieldsFailed`: the card fields failed to load or timed out; not a decline.
1281
- cardFieldsFailed: (_event) => true
1282
- },
1283
- /**
1284
- * Slots (React's content props):
1285
- * - `cardButtonContent`: the buttons-layout card tile's content.
1286
- * - `cardBackButtonContent`: the label of the card view's back button.
1287
- * - `cardTitleContent`: the card-form title (default `Secure card checkout`).
1288
- * - `cardPreFormSlot`: content directly above the hosted card widget.
1289
- *
1290
- * An empty `cardBackButtonContent` or `cardTitleContent` slot hides that
1291
- * label, as React does for `''`, `null` or `false`.
1292
- */
1293
- setup(props, { emit, slots }) {
1294
- const provider = inject2(FLOPAY_CONTEXT, null);
1295
- const checkout = inject2(CHECKOUT_STATE, null);
1296
- const defaults = inject2(CHECKOUT_FORM_DEFAULTS, () => ({}));
1297
- const session = computed2(
1298
- () => props.session ?? defaults().session ?? checkout?.session ?? null
1299
- );
1300
- const sessionId = computed2(() => props.sessionId ?? defaults().sessionId ?? session.value?.id);
1301
- const nonce = computed2(
1302
- () => props.nonce ?? defaults().nonce ?? (session.value?.clientSecret || void 0)
1303
- );
1304
- const billingApiUrl = computed2(
1305
- () => resolveBillingApiUrl2(
1306
- props.billingApiUrl ?? defaults().billingApiUrl ?? provider?.billingApiUrl()
1307
- )
1308
- );
1309
- const submitLabel = computed2(
1310
- () => props.submitLabel === void 0 ? defaults().submitLabel : props.submitLabel
1311
- );
1312
- const pending = computed2(
1313
- () => props.dataAttachmentPending === true || defaults().dataAttachmentPending === true || checkout?.claimPending === true
1314
- );
1315
- const requiresIdentity = computed2(
1316
- () => props.dataAttachmentRequiresIdentity === true || checkout?.claimRequiresIdentity === true
1317
- );
1318
- const nonCardAttachmentBlocked = computed2(() => pending.value && !requiresIdentity.value);
1319
- const vaultMountContext = computed2(() => ({
1320
- billingApiUrl: billingApiUrl.value,
1321
- sessionId: sessionId.value,
1322
- nonce: nonce.value
1323
- }));
1324
- const embeddedVault = computed2(
1325
- () => resolveVaultMountOptions(session.value?.vault, vaultMountContext.value)
1326
- );
1327
- const deferredVaultAdvertised = computed2(() => {
1328
- const current = session.value;
1329
- if (!current || !props.showStripe || !sessionId.value) return false;
1330
- if (isMountableVaultBlock(current.vault)) return false;
1331
- const advertised = current.gateways?.stripe?.enabledPaymentMethods ?? props.enabledPaymentMethods;
1332
- return Boolean(advertised?.includes("card")) || canRecoverHostedCardForm(current) || Boolean(current.gateways?.pcivault);
1333
- });
1334
- const lazyVault = shallowRef2(null);
1335
- const vault = computed2(
1336
- () => embeddedVault.value ?? lazyVault.value
1337
- );
1338
- const vaultCapable = computed2(
1339
- () => Boolean(embeddedVault.value) || deferredVaultAdvertised.value
1340
- );
1341
- const themeBundle = computed2(() => resolveTheme(props.theme));
1342
- const bStyles = computed2(
1343
- () => resolveFormButtonsStyles(
1344
- themeBundle.value?.buttonsLayout,
1345
- props.buttonsTheme,
1346
- props.buttonsStyles
1347
- )
1348
- );
1349
- const appearance = computed2(() => props.appearance ?? themeBundle.value?.appearance);
1350
- const vaultTheme = computed2(
1351
- () => computeVaultCardThemeColors({
1352
- appearance: appearance.value,
1353
- buttonsStyles: bStyles.value,
1354
- layout: props.layout
1355
- })
1356
- );
1357
- const cardTileStyle = computed2(() => {
1358
- const vars = appearance.value?.variables;
1359
- const explicitPrimary = typeof vars?.colorPrimary === "string" ? vars.colorPrimary : void 0;
1360
- const radius = bStyles.value.cardButton?.borderRadius ?? vars?.borderRadius ?? "8px";
1361
- return {
1362
- width: "100%",
1363
- ...bStyles.value.cardButton,
1364
- ...derivePrimaryTileStyle({
1365
- themeBundle: themeBundle.value,
1366
- resolvedPrimaryColor: explicitPrimary ?? "#4A49FF",
1367
- resolvedBorderRadius: String(radius),
1368
- submitButtonStyle: bStyles.value.submitButton,
1369
- explicitPrimaryColor: explicitPrimary
1370
- }),
1371
- fontSize: bStyles.value.cardButtonFontSize ?? "0.95rem"
1372
- };
1373
- });
1374
- const directPaypalConfigured = computed2(() => Boolean(props.directPaypal?.clientId));
1375
- const directPaypal = computed2(
1376
- () => props.showPayPal && props.directPaypal?.clientId ? props.directPaypal : null
1377
- );
1378
- const directPayPalCanWaitForAttachment = computed2(
1379
- () => !nonCardAttachmentBlocked.value || checkout !== null
1380
- );
1381
- const stripePayPalReturnOwner = hasStripePayPalReturn();
1382
- const resolvedWalletPresentation = computed2(
1383
- () => props.walletPresentation ?? defaults().walletPresentation ?? "auto"
1384
- );
1385
- const stripePayPalPresentation = computed2(
1386
- () => stripePayPalReturnOwner ? "redirect" : resolveStripePayPalPresentation(
1387
- detectPayPalEnvironment2(typeof navigator === "undefined" ? "" : void 0),
1388
- resolvedWalletPresentation.value
1389
- )
1390
- );
1391
- const paypalRetry = shallowRef2(
1392
- props.directPaypal?.existingOrderId ? { orderId: props.directPaypal.existingOrderId, attempts: 0 } : null
1393
- );
1394
- const resolvedCurrency = computed2(() => props.currency ?? "usd");
1395
- const resolvedIsSubscription = computed2(() => props.isSubscription ?? false);
1396
- const directPaypalInitializationState = ref3("loading");
1397
- const directPaypalUnavailable = computed2(
1398
- () => directPaypalInitializationState.value === "retrying" || directPaypalInitializationState.value === "exhausted"
1399
- );
1400
- const stripeKey = computed2(
1401
- () => session.value?.gateways?.stripe?.publishableKey
1402
- );
1403
- const stripeMethods = computed2(() => {
1404
- if (!props.showStripe || !stripeKey.value) return [];
1405
- const listed = props.enabledPaymentMethods ?? session.value?.gateways?.stripe?.enabledPaymentMethods ?? [];
1406
- return listed.filter((method) => {
1407
- if (method === "card") return false;
1408
- if (method === "apple_pay") return props.showApplePay;
1409
- if (method === "google_pay") return props.showGooglePay;
1410
- if (method === "paypal") {
1411
- return props.showPayPal && (!directPaypal.value || directPaypalUnavailable.value);
1412
- }
1413
- return true;
1414
- });
1415
- });
1416
- const unsupported = computed2(
1417
- () => Boolean(session.value) && !vaultCapable.value && stripeMethods.value.length === 0 && !directPaypal.value
1418
- );
1419
- const apmCountry = computed2(() => avsConfig.value ? country.value : props.country);
1420
- const renderedStripeMethods = computed2(() => {
1421
- const others = stripeMethods.value.filter((method) => !isStripeExpressMethod(method));
1422
- const allowed = filterStripeMethodsByCountryGate(
1423
- others,
1424
- apmCountry.value,
1425
- props.enabledPaymentMethodCountries
1426
- );
1427
- return stripeMethods.value.filter(
1428
- (method) => isStripeExpressMethod(method) || allowed.includes(method)
1429
- );
1430
- });
1431
- const inAppBrowserDetected = () => typeof navigator === "undefined" ? void 0 : detectPayPalEnvironment2().inAppBrowser;
1432
- const cardOpen = ref3(props.layout !== "buttons" || props.initialCardOpen);
1433
- const capture = shallowRef2(null);
1434
- const failure = ref3(null);
1435
- const overlay = ref3(null);
1436
- watch2(overlay, (state) => {
1437
- if (state === "success") markSessionRecentlyCompleted(sessionId.value);
1438
- });
1439
- let overlayTimer = null;
1440
- const methodOverlay = ref3(null);
1441
- let methodOverlayTimer = null;
1442
- let methodCompleted = false;
1443
- let completed = false;
1444
- let detachOutcomes = null;
1445
- const avsConfig = computed2(() => resolveAVSConfig(props.enableAVS));
1446
- const country = ref3((props.country ?? session.value?.customer?.country ?? "").toUpperCase());
1447
- const zipCode = ref3(props.zip ?? session.value?.customer?.zip ?? "");
1448
- const addressLine1 = ref3(props.addressLine1 ?? "");
1449
- const addressLine2 = ref3(props.addressLine2 ?? "");
1450
- const city = ref3(props.city ?? "");
1451
- const region = ref3(props.state ?? "");
1452
- const editedAvs = /* @__PURE__ */ new Set();
1453
- const adoptAvs = (field, next, model, notify) => {
1454
- if (editedAvs.has(field)) return;
1455
- const value = next?.trim();
1456
- if (!value || value === model.value) return;
1457
- model.value = value;
1458
- if (notify) invokeMerchantCallback2(() => notify(value));
1459
- };
1460
- watch2(
1461
- () => props.country,
1462
- (next) => adoptAvs("country", next?.toUpperCase(), country, (value) => emit("countryChange", value))
1463
- );
1464
- watch2(
1465
- () => props.zip,
1466
- (next) => adoptAvs("postal_code", next, zipCode, (value) => emit("zipChange", value))
1467
- );
1468
- watch2(
1469
- () => props.addressLine1,
1470
- (next) => adoptAvs("address_line_1", next, addressLine1)
1471
- );
1472
- watch2(
1473
- () => props.addressLine2,
1474
- (next) => adoptAvs("address_line_2", next, addressLine2)
1475
- );
1476
- watch2(
1477
- () => props.city,
1478
- (next) => adoptAvs("city", next, city)
1479
- );
1480
- watch2(
1481
- () => props.state,
1482
- (next) => adoptAvs("state", next, region)
1483
- );
1484
- const externallyProcessing = computed2(() => props.isProcessing === true);
1485
- const displayError = computed2(() => props.error ?? failure.value);
1486
- watch2(failure, (message) => invokeMerchantCallback2(() => emit("errorChange", message)));
1487
- const avsVisible = (field) => {
1488
- const config = avsConfig.value;
1489
- return config ? isAVSFieldVisible(config[field], country.value.trim()) : false;
1490
- };
1491
- const avsInvalid = computed2(() => {
1492
- if (!avsConfig.value) return false;
1493
- const cc = country.value.trim();
1494
- if (avsVisible("country") && !cc) return true;
1495
- if (avsVisible("postal_code") && !isValidPostalCode(cc, zipCode.value.trim())) return true;
1496
- if (avsVisible("address_line_1") && !addressLine1.value.trim()) return true;
1497
- if (avsVisible("city") && !city.value.trim()) return true;
1498
- return avsVisible("state") && !region.value.trim();
1499
- });
1500
- const gateClosed = computed2(() => pending.value || avsInvalid.value);
1501
- const emitError = (error) => invokeMerchantCallback2(() => emit("error", error));
1502
- const emitDecline = (decline) => invokeMerchantCallback2(() => emit("decline", decline));
1503
- const accountPatch = shallowRef2(void 0);
1504
- const identityField = (key) => (accountPatch.value?.[key] ?? props[key] ?? session.value?.customer?.[key] ?? "").trim();
1505
- const billingName = computed2(
1506
- () => [identityField("firstName"), identityField("lastName")].filter(Boolean).join(" ")
1507
- );
1508
- const untilAttached = () => {
1509
- if (!pending.value) return Promise.resolve();
1510
- return new Promise((resolve) => {
1511
- const stop = watch2(pending, (isPending) => {
1512
- if (isPending) return;
1513
- stop();
1514
- resolve();
1515
- });
1516
- });
1517
- };
1518
- const runBeforeButtonClick = async (method) => {
1519
- if (method !== "card" && nonCardAttachmentBlocked.value) await untilAttached();
1520
- const hook = props.onBeforeButtonClick;
1521
- if (!hook) return { proceed: true };
1522
- try {
1523
- const result = await hook({
1524
- method,
1525
- sessionId: sessionId.value || void 0,
1526
- createSession: checkout?.inlineSessionDraft
1527
- });
1528
- if (result === false) return { proceed: false };
1529
- if (result && typeof result === "object") {
1530
- if (result.account) {
1531
- accountPatch.value = { ...accountPatch.value ?? {}, ...result.account };
1532
- }
1533
- return {
1534
- proceed: true,
1535
- accountPatch: result.account,
1536
- sessionId: sessionId.value,
1537
- nonce: nonce.value
1538
- };
1539
- }
1540
- return { proceed: true };
1541
- } catch (error) {
1542
- const failureError = normalizeBeforeButtonClickError(method, error);
1543
- failure.value = failureError.message;
1544
- emitError(failureError);
1545
- return { proceed: false };
1546
- }
1547
- };
1548
- const recoverStripePayPalAccount = async (returnSessionId) => {
1549
- const hook = props.onBeforeButtonClick;
1550
- if (!hook) return void 0;
1551
- try {
1552
- const result = await hook({
1553
- method: "paypal",
1554
- sessionId: returnSessionId || void 0,
1555
- createSession: checkout?.inlineSessionDraft
1556
- });
1557
- return result && typeof result === "object" ? result.account : void 0;
1558
- } catch {
1559
- return void 0;
1560
- }
1561
- };
1562
- const holdFailureOverlay = () => {
1563
- if (overlayTimer) clearTimeout(overlayTimer);
1564
- overlay.value = "failed";
1565
- overlayTimer = setTimeout(() => {
1566
- overlayTimer = null;
1567
- overlay.value = null;
1568
- }, ERROR_DELAY_MS);
1569
- };
1570
- const accountSnapshot = () => {
1571
- const email = identityField("email");
1572
- if (!isValidEmail3(email)) return null;
1573
- const cc = country.value.trim();
1574
- const config = avsConfig.value;
1575
- const visible = {
1576
- country: avsVisible("country"),
1577
- postal_code: avsVisible("postal_code"),
1578
- address_line_1: avsVisible("address_line_1"),
1579
- address_line_2: avsVisible("address_line_2"),
1580
- city: avsVisible("city"),
1581
- state: avsVisible("state")
1582
- };
1583
- const zip = zipCode.value.trim();
1584
- const derivedState = visible.address_line_1 && !visible.state && visible.postal_code ? getStateFromPostalCode(cc, zip) : null;
1585
- const state = visible.state ? region.value.trim() : derivedState;
1586
- const firstName = identityField("firstName");
1587
- const lastName = identityField("lastName");
1588
- const userId = accountPatch.value?.userId ?? (props.userId || defaults().userId) ?? "";
1589
- return {
1590
- accountData: {
1591
- userId,
1592
- email,
1593
- ...firstName ? { firstName } : {},
1594
- ...lastName ? { lastName } : {},
1595
- ...visible.postal_code && zip ? { zip } : {},
1596
- ...visible.city && city.value.trim() ? { city: city.value.trim() } : {},
1597
- ...state ? { state } : {},
1598
- ...visible.address_line_1 && addressLine1.value.trim() ? { addressLine1: addressLine1.value.trim() } : {},
1599
- ...visible.address_line_2 && addressLine2.value.trim() ? { addressLine2: addressLine2.value.trim() } : {},
1600
- ...cc ? { country: cc } : {}
1601
- },
1602
- // React sends `avsCheck` only when the prop is set (FloPayCheckout passes `!!enableAVS`).
1603
- ...props.avsCheck === void 0 ? {} : { avsCheck: props.avsCheck },
1604
- ...config ? { avsConfig: visible } : {}
1605
- };
1606
- };
1607
- const paypalOverlay = ref3(null);
1608
- let paypalOverlayTimer = null;
1609
- const stripeMethodsProcessing = computed2(
1610
- () => props.isProcessing ?? paypalOverlay.value === "processing"
1611
- );
1612
- let tokenizedProcessing = false;
1613
- const setPaypalOverlay = (state) => {
1614
- if (paypalOverlayTimer) clearTimeout(paypalOverlayTimer);
1615
- paypalOverlayTimer = null;
1616
- paypalOverlay.value = state;
1617
- };
1618
- const holdPaypalFailure = (message) => {
1619
- failure.value = message;
1620
- setPaypalOverlay("failed");
1621
- paypalOverlayTimer = setTimeout(() => {
1622
- paypalOverlayTimer = null;
1623
- paypalOverlay.value = null;
1624
- }, ERROR_DELAY_MS);
1625
- };
1626
- const processAvsInput = () => ({
1627
- avsConfig: avsConfig.value,
1628
- country: country.value,
1629
- zip: zipCode.value,
1630
- city: city.value,
1631
- state: region.value,
1632
- addressLine1: addressLine1.value,
1633
- addressLine2: addressLine2.value
1634
- });
1635
- const buildTokenizedProcessRequest = (body, overrides, effectiveSessionId) => {
1636
- const attemptPatch = overrides?.accountPatch;
1637
- const identity = (key) => attemptPatch?.[key] ?? identityField(key);
1638
- const userId = attemptPatch?.userId ?? accountPatch.value?.userId ?? (props.userId || defaults().userId) ?? "";
1639
- return {
1640
- userId,
1641
- params: {
1642
- sessionId: effectiveSessionId,
1643
- // The nonce stays paired with the (possibly overridden) session.
1644
- nonce: overrides?.nonce ?? nonce.value,
1645
- paymentMethodCategory: "paypal",
1646
- tokenizedData: body,
1647
- accountData: {
1648
- ...attemptPatch,
1649
- userId,
1650
- email: identity("email"),
1651
- firstName: identity("firstName") || void 0,
1652
- lastName: identity("lastName") || void 0,
1653
- ...buildProcessPaymentAvsAccount(processAvsInput())
1654
- },
1655
- ...buildCheckoutProcessMetadata({
1656
- ...processAvsInput(),
1657
- chv: props.chv,
1658
- avsCheck: props.avsCheck,
1659
- checkoutType: props.checkoutType,
1660
- checkoutLayout: props.checkoutLayout
1661
- })
1662
- }
1663
- };
1664
- };
1665
- const completeTokenizedProcess = (result, effectiveSessionId) => {
1666
- markSessionRecentlyCompleted(effectiveSessionId);
1667
- setPaypalOverlay("success");
1668
- const authorized = session.value?.captureMethod === "manual" || result?.status === "authorized";
1669
- const paymentId = typeof result?.paymentId === "string" ? result.paymentId : session.value?.paymentId;
1670
- const authorizationExpiresAt = typeof result?.authorizationExpiresAt === "string" ? result.authorizationExpiresAt : session.value?.authorizationExpiresAt;
1671
- const completion = authorized ? {
1672
- status: "authorized",
1673
- ...paymentId === void 0 ? {} : { paymentId },
1674
- sessionId: typeof result?.sessionId === "string" ? result.sessionId : effectiveSessionId,
1675
- ...authorizationExpiresAt === void 0 ? {} : { authorizationExpiresAt },
1676
- checkoutMethod: "paypal"
1677
- } : { status: "succeeded", checkoutMethod: "paypal" };
1678
- setTimeout(() => {
1679
- setPaypalOverlay(null);
1680
- invokeMerchantCallback2(() => emit("complete", completion));
1681
- }, SUCCESS_DELAY_MS);
1682
- };
1683
- const rebindDirectPayPal = (json, effectiveSessionId) => {
1684
- const orderId = typeof json.orderId === "string" ? json.orderId : "";
1685
- if (!orderId) {
1686
- holdPaypalFailure("PayPal retry required but no order id provided.");
1687
- return;
1688
- }
1689
- const attempts = paypalRetry.value?.attempts ?? 0;
1690
- if (attempts >= PAYPAL_DIRECT_RETRY_LIMIT) {
1691
- holdPaypalFailure("PayPal payment could not be completed after multiple attempts.");
1692
- emitDecline({
1693
- method: "paypal",
1694
- message: "paypal_direct_required retry limit exceeded",
1695
- ...effectiveSessionId ? { sessionId: effectiveSessionId } : {}
1696
- });
1697
- return;
1698
- }
1699
- paypalRetry.value = { orderId, attempts: attempts + 1 };
1700
- setPaypalOverlay(null);
1701
- };
1702
- const rejectTokenizedProcess = (json, effectiveSessionId) => {
1703
- if (json?.type === "paypal_direct_required") {
1704
- rebindDirectPayPal(json, effectiveSessionId);
1705
- return;
1706
- }
1707
- if (json?.type === "paypal_redirect_required") {
1708
- if (!json.threeDSecureToken) {
1709
- holdPaypalFailure("PayPal authorization required but no token provided.");
1710
- return;
1711
- }
1712
- failure.value = "PayPal is not available.";
1713
- setPaypalOverlay(null);
1714
- return;
1715
- }
1716
- const message = typeof json?.message === "string" ? json.message : "Payment failed. Please try again.";
1717
- const code = json?.code ?? json?.gatewayErrorCode;
1718
- const declineCode = json?.declineCode ?? json?.gatewayDeclineReason;
1719
- holdPaypalFailure(message);
1720
- emitDecline({
1721
- method: "paypal",
1722
- message,
1723
- ...code ? { code } : {},
1724
- ...declineCode ? { declineCode } : {},
1725
- ...effectiveSessionId ? { sessionId: effectiveSessionId } : {}
1726
- });
1727
- };
1728
- const processTokenizedBody = async (body, overrides) => {
1729
- if (tokenizedProcessing) return;
1730
- tokenizedProcessing = true;
1731
- setPaypalOverlay("processing");
1732
- failure.value = null;
1733
- const effectiveSessionId = overrides?.sessionId ?? sessionId.value ?? "";
1734
- const request = buildTokenizedProcessRequest(body, overrides, effectiveSessionId);
1735
- try {
1736
- const response = await new PaymentAPI2(billingApiUrl.value).processPayment(
1737
- request.userId,
1738
- request.params
1739
- );
1740
- if (response.ok) {
1741
- const result = response.status === 204 ? null : await response.json().catch(() => null);
1742
- completeTokenizedProcess(result, effectiveSessionId);
1743
- return;
1744
- }
1745
- const json = await response.json().catch(() => null);
1746
- rejectTokenizedProcess(json, effectiveSessionId);
1747
- } catch (error) {
1748
- holdPaypalFailure(error instanceof Error ? error.message : "An unexpected error occurred");
1749
- } finally {
1750
- tokenizedProcessing = false;
1751
- }
1752
- };
1753
- const dispatchTokenizedBody = (body, overrides) => {
1754
- if (props.onTokenizedBody) {
1755
- props.onTokenizedBody(body);
1756
- return;
1757
- }
1758
- void processTokenizedBody(body, overrides);
1759
- };
1760
- const onSubmitting = () => {
1761
- if (overlayTimer) clearTimeout(overlayTimer);
1762
- overlay.value = "processing";
1763
- failure.value = null;
1764
- const id = sessionId.value;
1765
- const token = nonce.value;
1766
- if (!id || !token) return;
1767
- const snapshot = accountSnapshot();
1768
- if (!snapshot) {
1769
- failure.value = "Enter a valid email address.";
1770
- overlay.value = null;
1771
- return;
1772
- }
1773
- void new PaymentAPI2(billingApiUrl.value).patchAccountSnapshot(id, token, snapshot, { telemetryMode: "best_effort" }).catch((error) => {
1774
- if (!isAccountValidationError(error)) return;
1775
- const message = error instanceof Error ? error.message : "Please check your billing address and try again.";
1776
- failure.value = message;
1777
- overlay.value = null;
1778
- emitError(error instanceof FloPayError3 ? error : new FloPayError3(message, "api_error"));
1779
- });
1780
- };
1781
- const bindOutcomes = (adapter) => {
1782
- const offSubmitting = adapter.on("submitting", onSubmitting);
1783
- const offComplete = adapter.on("complete", (event) => {
1784
- if (overlayTimer) clearTimeout(overlayTimer);
1785
- overlay.value = "success";
1786
- setTimeout(() => {
1787
- if (completed) return;
1788
- completed = true;
1789
- const authorized = event.outcome === "authorized" || session.value?.captureMethod === "manual";
1790
- const result = authorized ? {
1791
- status: "authorized",
1792
- paymentIntentId: event.intentId,
1793
- paymentId: event.paymentId ?? session.value?.paymentId,
1794
- sessionId: event.sessionId ?? sessionId.value,
1795
- authorizationExpiresAt: event.authorizationExpiresAt ?? session.value?.authorizationExpiresAt,
1796
- checkoutMethod: "card"
1797
- } : { status: "succeeded", paymentIntentId: event.intentId, checkoutMethod: "card" };
1798
- invokeMerchantCallback2(() => emit("complete", result));
1799
- }, SUCCESS_DELAY_MS);
1800
- });
1801
- const offDecline = adapter.on("decline", (event) => {
1802
- const message = event.message ?? "Your payment was declined. Please try another card or contact your bank.";
1803
- failure.value = message;
1804
- holdFailureOverlay();
1805
- const code = event.failureOutcome ?? event.declineReason ?? "authorization_declined";
1806
- emitDecline({
1807
- method: "card",
1808
- message,
1809
- code,
1810
- declineCode: code,
1811
- ...sessionId.value ? { sessionId: sessionId.value } : {}
1812
- });
1813
- });
1814
- const offError = adapter.on("error", (event) => {
1815
- const buyerEmailPrompt = buyerEmailRequiredPrompt(event.vaultOutcome);
1816
- if (buyerEmailPrompt !== null) {
1817
- if (overlayTimer) {
1818
- clearTimeout(overlayTimer);
1819
- overlayTimer = null;
1820
- }
1821
- overlay.value = null;
1822
- failure.value = buyerEmailPrompt;
1823
- emitError(
1824
- new FloPayError3(buyerEmailPrompt, "api_error", {
1825
- code: CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED
1826
- })
1827
- );
1828
- return;
1829
- }
1830
- const message = event.message ?? "There was a problem processing your card.";
1831
- failure.value = message;
1832
- holdFailureOverlay();
1833
- emitError(new FloPayError3(message, "api_error"));
1834
- });
1835
- return () => {
1836
- offSubmitting();
1837
- offComplete();
1838
- offDecline();
1839
- offError();
1840
- };
1841
- };
1842
- const cardRequested = ref3(cardOpen.value);
1843
- const vaultRecoveryAttempt = ref3(0);
1844
- let lazyVerificationShell = null;
1845
- let lazyVaultRequest = 0;
1846
- const recoverVault = () => {
1847
- const request = ++lazyVaultRequest;
1848
- const id = sessionId.value;
1849
- if (embeddedVault.value || !deferredVaultAdvertised.value || !id || !cardRequested.value) {
1850
- lazyVault.value = null;
1851
- return;
1852
- }
1853
- const context = { ...vaultMountContext.value, sessionId: id };
1854
- const shellKey = `${context.billingApiUrl}\0${id}\0${context.nonce ?? ""}`;
1855
- if (lazyVerificationShell?.key === shellKey) {
1856
- lazyVault.value = lazyVerificationShell.mount;
1857
- return;
1858
- }
1859
- lazyVault.value = null;
1860
- new PaymentAPI2(context.billingApiUrl).getVaultCapture(id, context.nonce).then((block) => {
1861
- if (request !== lazyVaultRequest) return;
1862
- const mount = resolveVaultMountOptions(block, context);
1863
- if (mount?.verificationRequired && !block.html) {
1864
- lazyVerificationShell = { key: shellKey, mount };
1865
- }
1866
- if (mount) lazyVault.value = mount;
1867
- else failure.value = "Failed to load the secure card form.";
1868
- }).catch((error) => {
1869
- if (request !== lazyVaultRequest) return;
1870
- failure.value = error instanceof Error ? error.message : "Failed to load the secure card form.";
1871
- });
1872
- };
1873
- const ensureCapture = () => {
1874
- detachOutcomes?.();
1875
- detachOutcomes = null;
1876
- capture.value = null;
1877
- const id = sessionId.value;
1878
- if (!vault.value || !id) return;
1879
- const captureMethod = session.value?.captureMethod;
1880
- const flopay = provider?.flopay.value;
1881
- const cardFieldsTimeoutMs = props.cardFieldsTimeoutMs;
1882
- const sessionToken = nonce.value;
1883
- const adapter = flopay ? flopay.cardCapture({
1884
- sessionId: id,
1885
- ...captureMethod ? { captureMethod } : {},
1886
- sessionToken,
1887
- cardFieldsTimeoutMs
1888
- }) : new PciVaultCardCapture({
1889
- sessionId: id,
1890
- ...captureMethod ? { captureMethod } : {},
1891
- billingApiUrl: billingApiUrl.value,
1892
- telemetry: props.telemetry,
1893
- sessionToken,
1894
- cardFieldsTimeoutMs
1895
- });
1896
- const detachAdapterOutcomes = bindOutcomes(adapter);
1897
- const detachCardFields = adapter.onCardFields?.((event) => {
1898
- provider?.emitInstrument(cardFieldsInstrumentSource(event));
1899
- if (event.type === "card_fields_ready") {
1900
- invokeMerchantCallback2(() => emit("cardFieldsReady", event));
1901
- } else {
1902
- invokeMerchantCallback2(() => emit("cardFieldsFailed", event));
1903
- }
1904
- });
1905
- detachOutcomes = () => {
1906
- detachAdapterOutcomes?.();
1907
- detachCardFields?.();
1908
- };
1909
- adapter.setSubmitGate?.(gateClosed.value);
1910
- capture.value = adapter;
1911
- };
1912
- onMounted2(() => {
1913
- watch2(
1914
- unsupported,
1915
- (isUnsupported) => {
1916
- if (isUnsupported) emitError(noVaultCapabilityError());
1917
- },
1918
- { immediate: true }
1919
- );
1920
- watch2(
1921
- () => [
1922
- embeddedVault.value,
1923
- deferredVaultAdvertised.value,
1924
- vaultMountContext.value.billingApiUrl,
1925
- sessionId.value,
1926
- nonce.value,
1927
- cardRequested.value,
1928
- vaultRecoveryAttempt.value
1929
- ],
1930
- recoverVault,
1931
- { immediate: true }
1932
- );
1933
- watch2(() => [sessionId.value, vault.value?.html], ensureCapture, { immediate: true });
1934
- watch2(
1935
- () => [capture.value, props.cardFieldOrder, avsConfig.value, props.cardAutoFocus],
1936
- ([adapter, order, avs, autoFocus]) => adapter?.setCardFieldOrder?.(order ?? null, autoFocus !== false && avs == null),
1937
- { immediate: true }
1938
- );
1939
- watch2(
1940
- () => [capture.value, props.showCardBrandIcons],
1941
- ([adapter, show]) => adapter?.setCardBrandIcons?.(show === true),
1942
- { immediate: true }
1943
- );
1944
- let showCardFieldLabelsSentTo = null;
1945
- watch2(
1946
- [() => capture.value, () => props.showCardFieldLabels],
1947
- ([adapter, show]) => {
1948
- if (!adapter) return;
1949
- if (show === void 0) {
1950
- if (showCardFieldLabelsSentTo !== adapter) return;
1951
- showCardFieldLabelsSentTo = null;
1952
- adapter.setShowCardFieldLabels?.(false);
1953
- return;
1954
- }
1955
- showCardFieldLabelsSentTo = adapter;
1956
- adapter.setShowCardFieldLabels?.(show === true);
1957
- },
1958
- { immediate: true }
1959
- );
1960
- const cardFieldLabelsKey = computed2(
1961
- () => props.cardFieldLabels === void 0 ? void 0 : JSON.stringify(buildCardFieldLabelsPayload(props.cardFieldLabels))
1962
- );
1963
- let cardFieldLabelsSentTo = null;
1964
- watch2(
1965
- [() => capture.value, cardFieldLabelsKey],
1966
- ([adapter, key]) => {
1967
- if (!adapter) return;
1968
- if (key === void 0) {
1969
- if (cardFieldLabelsSentTo !== adapter) return;
1970
- cardFieldLabelsSentTo = null;
1971
- adapter.setCardFieldLabels?.(null);
1972
- return;
1973
- }
1974
- cardFieldLabelsSentTo = adapter;
1975
- adapter.setCardFieldLabels?.(JSON.parse(key));
1976
- },
1977
- { immediate: true }
1978
- );
1979
- let placeholdersSentTo = null;
1980
- watch2(
1981
- [() => capture.value, () => cardFieldPlaceholdersContentKey(props.cardFieldPlaceholders)],
1982
- ([adapter, key]) => {
1983
- if (!adapter) return;
1984
- if (key === null) {
1985
- if (placeholdersSentTo !== adapter) return;
1986
- placeholdersSentTo = null;
1987
- adapter.setCardFieldPlaceholders?.(void 0);
1988
- return;
1989
- }
1990
- placeholdersSentTo = adapter;
1991
- adapter.setCardFieldPlaceholders?.(JSON.parse(key));
1992
- },
1993
- { immediate: true }
1994
- );
1995
- watch2(gateClosed, (closed) => capture.value?.setSubmitGate?.(closed));
1996
- });
1997
- onBeforeUnmount3(() => {
1998
- lazyVaultRequest += 1;
1999
- detachOutcomes?.();
2000
- detachOutcomes = null;
2001
- if (overlayTimer) clearTimeout(overlayTimer);
2002
- if (methodOverlayTimer) clearTimeout(methodOverlayTimer);
2003
- if (paypalOverlayTimer) clearTimeout(paypalOverlayTimer);
2004
- });
2005
- const avsInput = (field, label, model, autocomplete, onChange) => h3("label", { "data-testid": `flopay-avs-${field}` }, [
2006
- h3("span", label),
2007
- h3("input", {
2008
- name: field,
2009
- autocomplete,
2010
- value: model.value,
2011
- disabled: externallyProcessing.value,
2012
- "aria-invalid": field === "postal_code" && avsInvalid.value ? "true" : void 0,
2013
- onInput: (event) => {
2014
- const value = event.target.value;
2015
- editedAvs.add(field);
2016
- model.value = value;
2017
- onChange?.(model.value);
2018
- }
2019
- })
2020
- ]);
2021
- const countrySelect = () => h3("label", { "data-testid": "flopay-avs-country" }, [
2022
- h3("span", "Country"),
2023
- h3(
2024
- "select",
2025
- {
2026
- id: "flopay-billing-country",
2027
- name: "billing-country",
2028
- autocomplete: "billing country",
2029
- "data-testid": "flopay-country",
2030
- value: country.value,
2031
- disabled: externallyProcessing.value,
2032
- onChange: (event) => {
2033
- const value = event.target.value;
2034
- editedAvs.add("country");
2035
- country.value = value;
2036
- region.value = "";
2037
- invokeMerchantCallback2(() => emit("countryChange", value));
2038
- }
2039
- },
2040
- [
2041
- country.value === "" ? h3("option", { value: "" }, "Select country") : null,
2042
- ...COUNTRY_OPTIONS.map(
2043
- (option) => h3(
2044
- "option",
2045
- { key: option.code, value: option.code },
2046
- `${option.flag} ${option.name}`
2047
- )
2048
- )
2049
- ]
2050
- )
2051
- ]);
2052
- const avsFields = () => {
2053
- if (!avsConfig.value) return null;
2054
- return h3(
2055
- "div",
2056
- {
2057
- "data-testid": "flopay-avs-fields",
2058
- style: `display:flex;flex-wrap:wrap;gap:8px;flex-direction:${props.avsLayout === "column" ? "column" : "row"}`
2059
- },
2060
- [
2061
- avsVisible("country") ? countrySelect() : null,
2062
- avsVisible("address_line_1") ? avsInput("address_line_1", "Address", addressLine1, "address-line1") : null,
2063
- avsVisible("address_line_2") ? avsInput("address_line_2", "Apt, suite, etc.", addressLine2, "address-line2") : null,
2064
- avsVisible("city") ? avsInput("city", "City", city, "address-level2") : null,
2065
- avsVisible("state") ? avsInput("state", "State / Province", region, "address-level1") : null,
2066
- avsVisible("postal_code") ? avsInput(
2067
- "postal_code",
2068
- "ZIP / Postal code",
2069
- zipCode,
2070
- "postal-code",
2071
- (value) => invokeMerchantCallback2(() => emit("zipChange", value))
2072
- ) : null
2073
- ]
2074
- );
2075
- };
2076
- const OVERLAY_TEXT = {
2077
- processing: "Processing payment\u2026",
2078
- success: "Payment successful",
2079
- failed: "Payment failed"
2080
- };
2081
- const overlayNode = (state) => state ? h3(
2082
- "div",
2083
- {
2084
- role: "status",
2085
- "aria-live": "polite",
2086
- "data-testid": "flopay-processing-overlay",
2087
- "data-state": state
2088
- },
2089
- OVERLAY_TEXT[state]
2090
- ) : null;
2091
- const processingOverlay = () => overlayNode(overlay.value);
2092
- const setMethodOverlay = (state) => {
2093
- if (methodOverlayTimer) clearTimeout(methodOverlayTimer);
2094
- methodOverlayTimer = null;
2095
- methodOverlay.value = state;
2096
- };
2097
- const holdMethodFailure = () => {
2098
- setMethodOverlay("failed");
2099
- methodOverlayTimer = setTimeout(() => {
2100
- methodOverlayTimer = null;
2101
- methodOverlay.value = null;
2102
- }, ERROR_DELAY_MS);
2103
- };
2104
- let walletSheetRefusal = null;
2105
- const methodRelay = {
2106
- onSubmitting: () => setMethodOverlay("processing"),
2107
- onComplete: (result) => {
2108
- setMethodOverlay("success");
2109
- setTimeout(() => {
2110
- if (methodCompleted) return;
2111
- methodCompleted = true;
2112
- invokeMerchantCallback2(() => emit("complete", result));
2113
- }, SUCCESS_DELAY_MS);
2114
- },
2115
- onDecline: (decline) => {
2116
- holdMethodFailure();
2117
- emitDecline(decline);
2118
- },
2119
- onError: (error) => {
2120
- if (methodOverlay.value === "processing") holdMethodFailure();
2121
- if (error.details?.providerCode === WALLET_SHEET_WINDOW_TOO_SMALL_CODE) {
2122
- walletSheetRefusal = error.message;
2123
- failure.value = error.message;
2124
- }
2125
- emitError(error);
2126
- }
2127
- };
2128
- const runStripeBeforeButtonClick = (method) => {
2129
- if (walletSheetRefusal !== null && failure.value === walletSheetRefusal) {
2130
- failure.value = null;
2131
- }
2132
- walletSheetRefusal = null;
2133
- return runBeforeButtonClick(method);
2134
- };
2135
- const cardSection = () => {
2136
- if (!vaultCapable.value) return null;
2137
- const mount = vault.value;
2138
- const fields = cardOpen.value && capture.value && mount ? h3(VaultCardFields, {
2139
- capture: capture.value,
2140
- html: mount.html,
2141
- messageToken: mount.messageToken,
2142
- expectedOrigin: mount.expectedOrigin,
2143
- expiresAt: mount.expiresAt,
2144
- verificationRequired: mount.verificationRequired,
2145
- theme: vaultTheme.value,
2146
- submitLabel: submitLabel.value,
2147
- onError: (message) => {
2148
- failure.value = message;
2149
- },
2150
- onValidation: (message) => {
2151
- failure.value = message;
2152
- }
2153
- }) : null;
2154
- const isButtons = props.layout === "buttons";
2155
- const card = fields ? h3(
2156
- "div",
2157
- {
2158
- "data-testid": "flopay-card-container",
2159
- style: { ...bStyles.value.cardFormContainer, position: "relative" }
2160
- },
2161
- [
2162
- isButtons ? null : defaultLayoutTitle(),
2163
- slots.cardPreFormSlot ? h3(
2164
- "div",
2165
- { "data-testid": "flopay-card-pre-form", style: { width: "100%" } },
2166
- slots.cardPreFormSlot()
2167
- ) : null,
2168
- avsFields(),
2169
- fields,
2170
- processingOverlay()
2171
- ]
2172
- ) : null;
2173
- if (!isButtons) return card;
2174
- return h3("div", { "data-testid": "flopay-card-section" }, [cardHeader(), card]);
2175
- };
2176
- const slotContent = (slot, fallback) => {
2177
- if (!slot) return { content: fallback, empty: false };
2178
- const nodes = slot();
2179
- return { content: nodes, empty: isEmptySlotOutput(nodes) };
2180
- };
2181
- const defaultLayoutTitle = () => {
2182
- const title = slotContent(slots.cardTitleContent, "Secure card checkout");
2183
- if (title.empty) return null;
2184
- return h3(
2185
- "div",
2186
- {
2187
- "data-testid": "flopay-card-title",
2188
- style: {
2189
- textAlign: "center",
2190
- fontWeight: 600,
2191
- fontSize: "1.1rem",
2192
- padding: "0.5rem 0",
2193
- color: "#262833",
2194
- ...bStyles.value.title
2195
- }
2196
- },
2197
- title.content
2198
- );
2199
- };
2200
- const expandCard = () => {
2201
- if (cardOpen.value) return;
2202
- cardOpen.value = true;
2203
- cardRequested.value = true;
2204
- vaultRecoveryAttempt.value += 1;
2205
- failure.value = null;
2206
- provider?.emitInstrument({ class: "card_surface" });
2207
- invokeMerchantCallback2(() => emit("buttonClick", "card"));
2208
- };
2209
- const collapseToButtons = () => {
2210
- cardOpen.value = false;
2211
- failure.value = null;
2212
- };
2213
- const cardHeader = () => {
2214
- const back = slotContent(slots.cardBackButtonContent, "Go back");
2215
- const title = slotContent(slots.cardTitleContent, "Secure card checkout");
2216
- return h3(
2217
- "div",
2218
- {
2219
- "data-testid": "flopay-card-header",
2220
- style: { display: "flex", alignItems: "center", padding: "0.75rem 0 0.625rem" }
2221
- },
2222
- [
2223
- h3(
2224
- "button",
2225
- {
2226
- type: "button",
2227
- "aria-label": "Back to payment methods",
2228
- "data-testid": "flopay-card-back-button",
2229
- onClick: collapseToButtons,
2230
- style: {
2231
- display: "inline-flex",
2232
- alignItems: "center",
2233
- gap: back.empty ? 0 : "0.5rem",
2234
- background: "none",
2235
- border: "none",
2236
- cursor: "pointer",
2237
- color: "#4b5563",
2238
- fontSize: bStyles.value.backButtonFontSize ?? "0.85rem",
2239
- fontWeight: 500,
2240
- padding: 0,
2241
- flexShrink: 0,
2242
- ...bStyles.value.backButton
2243
- }
2244
- },
2245
- [
2246
- h3(
2247
- "span",
2248
- {
2249
- style: {
2250
- display: "inline-flex",
2251
- alignItems: "center",
2252
- justifyContent: "center",
2253
- width: "28px",
2254
- height: "28px",
2255
- borderRadius: "50%",
2256
- backgroundColor: "#f3f4f6",
2257
- ...bStyles.value.backButtonIcon
2258
- }
2259
- },
2260
- [
2261
- h3(
2262
- "svg",
2263
- {
2264
- "aria-hidden": "true",
2265
- width: "14",
2266
- height: "14",
2267
- viewBox: "0 0 24 24",
2268
- fill: "none",
2269
- stroke: "currentColor",
2270
- "stroke-width": "2.5",
2271
- "stroke-linecap": "round",
2272
- "stroke-linejoin": "round"
2273
- },
2274
- [h3("path", { d: "M15 18l-6-6 6-6" })]
2275
- )
2276
- ]
2277
- ),
2278
- back.empty ? null : back.content
2279
- ]
2280
- ),
2281
- title.empty ? h3("div", { style: { flex: 1 } }) : h3(
2282
- "div",
2283
- {
2284
- "data-testid": "flopay-card-title",
2285
- style: {
2286
- flex: 1,
2287
- textAlign: "center",
2288
- fontWeight: 600,
2289
- fontSize: bStyles.value.titleFontSize ?? "1.05rem",
2290
- color: "#262833",
2291
- paddingRight: "80px",
2292
- ...bStyles.value.title
2293
- }
2294
- },
2295
- title.content
2296
- )
2297
- ]
2298
- );
2299
- };
2300
- const cardTile = () => h3(
2301
- "button",
2302
- {
2303
- type: "button",
2304
- "aria-expanded": false,
2305
- "data-testid": "flopay-card-button",
2306
- disabled: externallyProcessing.value,
2307
- style: {
2308
- // React sizes the default tile to the other buttons; custom content pads instead.
2309
- ...slots.cardButtonContent ? { padding: "0.9rem 1rem" } : {
2310
- boxSizing: "border-box",
2311
- height: `${DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT}px`,
2312
- padding: "0 1rem"
2313
- },
2314
- ...cardTileStyle.value,
2315
- fontWeight: 600,
2316
- // React dims the tile and shows a not-allowed cursor while processing.
2317
- cursor: externallyProcessing.value ? "not-allowed" : "pointer",
2318
- ...externallyProcessing.value ? { opacity: 0.6 } : {},
2319
- display: "flex",
2320
- alignItems: "center",
2321
- justifyContent: "center",
2322
- gap: "0.625rem",
2323
- position: "relative"
2324
- },
2325
- onClick: () => {
2326
- if (externallyProcessing.value) return;
2327
- if (!props.onBeforeButtonClick) {
2328
- expandCard();
2329
- return;
2330
- }
2331
- void runBeforeButtonClick("card").then((beforeClick) => {
2332
- if (beforeClick.proceed) expandCard();
2333
- });
2334
- }
2335
- },
2336
- slots.cardButtonContent ? slots.cardButtonContent() : defaultCardButtonContent()
2337
- );
2338
- return () => {
2339
- if (!session.value && !sessionId.value) return h3("div", { "data-testid": "flopay-form" });
2340
- if (unsupported.value) {
2341
- return h3("div", { role: "alert", "data-testid": "flopay-form-error" }, [
2342
- noVaultCapabilityError().message
2343
- ]);
2344
- }
2345
- const relay = {
2346
- onComplete: (result) => invokeMerchantCallback2(() => emit("complete", result)),
2347
- onDecline: emitDecline,
2348
- onError: emitError
2349
- };
2350
- const paypalButton = directPaypal.value && sessionId.value && directPayPalCanWaitForAttachment.value ? h3(DirectPayPalButton, {
2351
- sessionId: sessionId.value,
2352
- nonce: nonce.value,
2353
- billingApiUrl: billingApiUrl.value,
2354
- email: accountPatch.value?.email ?? props.email,
2355
- // React's pass-through: identity, the click gate, the processing
2356
- // state, the click notice and the error channel.
2357
- billingName: billingName.value || void 0,
2358
- onBuyerIdentityReady: props.onBuyerIdentityReady,
2359
- runBeforeButtonClick,
2360
- isProcessing: externallyProcessing.value,
2361
- clientId: directPaypal.value.clientId,
2362
- environment: directPaypal.value.environment,
2363
- // React's `directPaypal` pass-through. The session's object type
2364
- // and presentation still win inside the button.
2365
- providerObjectType: directPaypal.value.providerObjectType,
2366
- approvalPresentation: directPaypal.value.approvalPresentation,
2367
- existingOrderId: paypalRetry.value?.orderId,
2368
- currency: resolvedCurrency.value.toUpperCase(),
2369
- isSubscription: resolvedIsSubscription.value,
2370
- session: session.value,
2371
- // React's `debug={debug}`: the button's lifecycle tracer.
2372
- debug: props.debug,
2373
- ...relay,
2374
- // React's `onTokenizedBody={dispatchTokenizedBody}`: the form
2375
- // continues the approval (or hands it to the host's handler).
2376
- onTokenizedBody: dispatchTokenizedBody,
2377
- onCancel: (event) => invokeMerchantCallback2(() => emit("cancel", event)),
2378
- onButtonClick: (method) => invokeMerchantCallback2(() => emit("buttonClick", method)),
2379
- onErrorChange: (message) => {
2380
- failure.value = message;
2381
- },
2382
- // React's `onInitializationStateChange={setDirectPaypalInitializationState}`.
2383
- onInitializationStateChange: (state) => {
2384
- directPaypalInitializationState.value = state;
2385
- }
2386
- }) : null;
2387
- const paypalNode = paypalButton ? h3(Fragment, null, [
2388
- paypalRetry.value?.orderId ? h3(
2389
- "div",
2390
- {
2391
- "data-testid": "flopay-paypal-direct-retry-notice",
2392
- style: {
2393
- padding: "8px 10px",
2394
- background: "#fef3c7",
2395
- border: "1px solid #fcd34d",
2396
- borderRadius: "6px",
2397
- color: "#78350f",
2398
- fontSize: "13px",
2399
- lineHeight: 1.4
2400
- }
2401
- },
2402
- "Please confirm your PayPal payment to complete checkout."
2403
- ) : null,
2404
- paypalButton,
2405
- overlayNode(paypalOverlay.value)
2406
- ]) : null;
2407
- const amountInCents = props.totalAmount || 100;
2408
- const renderStripe = renderedStripeMethods.value.length > 0 && Boolean(stripeKey.value) && Boolean(sessionId.value) && !nonCardAttachmentBlocked.value;
2409
- const stripeNode = renderStripe && stripeKey.value && sessionId.value ? h3("div", { style: "position:relative", "data-testid": "flopay-stripe-section" }, [
2410
- h3(StripePaymentMethods, {
2411
- // Stripe's Elements are created once per mount, so the row
2412
- // remounts when the direct PayPal fallback adds or removes
2413
- // Stripe PayPal.
2414
- key: renderedStripeMethods.value.includes("paypal") ? "stripe-with-paypal" : "stripe-without-paypal",
2415
- session: session.value,
2416
- sessionId: sessionId.value,
2417
- nonce: nonce.value,
2418
- billingApiUrl: billingApiUrl.value,
2419
- publishableKey: stripeKey.value,
2420
- methods: renderedStripeMethods.value,
2421
- currency: resolvedCurrency.value,
2422
- amount: amountInCents,
2423
- // The wallet row's mode follows the real total (React's
2424
- // `resolveWalletElementsMode(totalAmount, …)`).
2425
- totalAmount: props.totalAmount,
2426
- appearance: appearance.value,
2427
- // React's Stripe PayPal group: with a redirect presentation,
2428
- // PayPal leaves the wallet row for the redirect tile, which
2429
- // runs the click gate and continues on the form's `/process`.
2430
- paypalPresentation: stripePayPalPresentation.value,
2431
- runBeforeButtonClick: runStripeBeforeButtonClick,
2432
- onTokenizedBody: dispatchTokenizedBody,
2433
- // React's `isProcessing={isSubmitting}`.
2434
- isProcessing: stripeMethodsProcessing.value,
2435
- // React restores the click-time patch from storage; Vue asks
2436
- // the merchant's gate again on an authorized redirect return.
2437
- recoverAccountPatch: recoverStripePayPalAccount,
2438
- ...methodRelay
2439
- }),
2440
- overlayNode(methodOverlay.value)
2441
- ]) : null;
2442
- const failureNode = displayError.value ? h3("div", { role: "alert" }, displayError.value) : null;
2443
- const gateDebug = (suffix) => {
2444
- if (!props.debug) return [];
2445
- const listed = props.enabledPaymentMethods ?? session.value?.gateways?.stripe?.enabledPaymentMethods;
2446
- const express = renderedStripeMethods.value.filter(isStripeExpressMethod);
2447
- const listedOthers = stripeMethods.value.filter((m) => !isStripeExpressMethod(m));
2448
- const renderedOthers = renderedStripeMethods.value.filter((m) => !isStripeExpressMethod(m));
2449
- const panel = (testId, lines) => h3(
2450
- "pre",
2451
- { "data-testid": `${testId}${suffix}`, style: GATE_DEBUG_STYLE },
2452
- lines.join("\n")
2453
- );
2454
- return [
2455
- !props.showPayPal || !directPaypalConfigured.value ? panel("flopay-direct-paypal-gate-debug", ["FloPay/DirectPayPal-debug - not enabled"]) : panel("flopay-direct-paypal-gate-debug", [
2456
- "FloPay/DirectPayPal-debug (parent gate)",
2457
- ` showPayPal=${props.showPayPal}`,
2458
- ` directPaypalConfigured=${directPaypalConfigured.value}`,
2459
- ` inAppBrowserDetected=${String(inAppBrowserDetected())}`,
2460
- ` shouldRenderDirectPayPal=${Boolean(paypalButton)}`,
2461
- ` shouldRenderStripePayPal=${renderStripe && renderedStripeMethods.value.includes("paypal")}`
2462
- ]),
2463
- !props.showStripe || !stripeKey.value ? panel("flopay-stripe-gate-debug", ["FloPay/Stripe-debug - not enabled"]) : panel("flopay-stripe-gate-debug", [
2464
- "FloPay/Stripe-debug (parent gate)",
2465
- ` showStripe=${props.showStripe}`,
2466
- ` currency=${resolvedCurrency.value}`,
2467
- ` amountInCents=${amountInCents}`,
2468
- ` enabledPaymentMethods: ${JSON.stringify(listed ?? [])}`,
2469
- ` enabledPaymentMethodsProvided=${Array.isArray(listed)}`,
2470
- ` hasEnabledMethods=${Array.isArray(listed) && listed.length > 0}`,
2471
- ` expressMethods: ${JSON.stringify(express)}`,
2472
- ` paymentElementMethods: ${JSON.stringify(listedOthers)}`,
2473
- ` paymentElementMethodsForCurrency: ${JSON.stringify(renderedOthers)}`,
2474
- ` shouldRenderWallets=${renderStripe && express.length > 0}`,
2475
- ` shouldRenderPaymentElement=${renderStripe && renderedOthers.length > 0}`
2476
- ])
2477
- ];
2478
- };
2479
- if (props.layout !== "buttons") {
2480
- return h3("div", { "data-testid": "flopay-form", class: props.className }, [
2481
- failureNode,
2482
- ...gateDebug("-default"),
2483
- paypalNode,
2484
- stripeNode,
2485
- cardSection()
2486
- ]);
2487
- }
2488
- const cardView = cardOpen.value && vaultCapable.value;
2489
- return h3("div", { "data-testid": "flopay-form", class: props.className }, [
2490
- failureNode,
2491
- h3(
2492
- "div",
2493
- {
2494
- "data-testid": "flopay-buttons-panel",
2495
- "aria-hidden": cardView ? "true" : void 0,
2496
- style: cardView ? { display: "none" } : { display: "flex", flexDirection: "column", gap: "0.5rem" }
2497
- },
2498
- [...gateDebug(""), paypalNode, stripeNode, vaultCapable.value ? cardTile() : null]
2499
- ),
2500
- cardView ? cardSection() : null
2501
- ]);
2502
- };
2503
- }
2504
- });
2505
-
2506
- // src/flopay-checkout.ts
2507
- function toFloPayError(error, fallback) {
2508
- if (error instanceof FloPayError4) return error;
2509
- return new FloPayError4(error instanceof Error ? error.message : fallback, "api_error");
2510
- }
2511
- async function resolveInlineSession(api, params) {
2512
- const canonicalIdentity = serializeCreateParams(params);
2513
- const cacheKey = hashCreateParams(params);
2514
- const suppliedIdempotencyKey = params.idempotencyKey === void 0 ? void 0 : resolveIdempotencyKey(params.idempotencyKey);
2515
- const cached = readCachedInlineSession(cacheKey, canonicalIdentity);
2516
- let cachedIdempotency = readCachedInlineIdempotencyKey(cacheKey, canonicalIdentity);
2517
- if (cached?.canonicalIdentity === canonicalIdentity && cachedIdempotency && cachedIdempotency.canonicalIdentity === void 0) {
2518
- persistCachedInlineIdempotencyKey(
2519
- cacheKey,
2520
- canonicalIdentity,
2521
- cachedIdempotency.idempotencyKey
2522
- );
2523
- cachedIdempotency = { ...cachedIdempotency, canonicalIdentity };
2524
- }
2525
- let idempotencyKey = suppliedIdempotencyKey ?? (cachedIdempotency?.canonicalIdentity === canonicalIdentity ? cachedIdempotency.idempotencyKey : void 0);
2526
- let rotateIdempotencyKey = false;
2527
- if (cached) {
2528
- try {
2529
- const reused = await api.getUnifiedCheckoutSession(
2530
- cached.sid,
2531
- cached.nonce
2532
- );
2533
- let reusable = true;
2534
- if (cached.canonicalIdentity === void 0) {
2535
- if (legacyCachedSessionMatchesDraft(reused.data.session ?? void 0, params)) {
2536
- persistCachedInlineSession(
2537
- cacheKey,
2538
- canonicalIdentity,
2539
- cached.sid,
2540
- cached.nonce ?? reused.data.session?.clientSecret
2541
- );
2542
- if (cachedIdempotency && cachedIdempotency.canonicalIdentity === void 0) {
2543
- persistCachedInlineIdempotencyKey(
2544
- cacheKey,
2545
- canonicalIdentity,
2546
- cachedIdempotency.idempotencyKey
2547
- );
2548
- idempotencyKey ?? (idempotencyKey = cachedIdempotency.idempotencyKey);
2549
- }
2550
- } else {
2551
- clearCachedInlineCheckout(cacheKey, canonicalIdentity);
2552
- idempotencyKey = suppliedIdempotencyKey;
2553
- reusable = false;
2554
- }
2555
- }
2556
- if (reusable && reused.data.session?.status === "complete") {
2557
- if (wasSessionRecentlyCompleted(cached.sid)) return { result: reused };
2558
- clearCachedInlineCheckout(cacheKey, canonicalIdentity);
2559
- reusable = false;
2560
- rotateIdempotencyKey = true;
2561
- }
2562
- if (reusable) return { result: reused };
2563
- } catch {
2564
- if (cached.canonicalIdentity === void 0) {
2565
- clearCachedInlineCheckout(cacheKey, canonicalIdentity);
2566
- idempotencyKey = suppliedIdempotencyKey;
2567
- } else {
2568
- clearCachedInlineSession(cacheKey, canonicalIdentity);
2569
- }
2570
- }
2571
- }
2572
- if (!suppliedIdempotencyKey && (rotateIdempotencyKey || !idempotencyKey)) {
2573
- idempotencyKey = resolveIdempotencyKey();
2574
- }
2575
- if (idempotencyKey) {
2576
- persistCachedInlineIdempotencyKey(cacheKey, canonicalIdentity, idempotencyKey);
2577
- }
2578
- const createParams = { ...params, idempotencyKey };
2579
- if (!isDetachedSessionEligible(createParams)) {
2580
- const created = await api.createAndFetchSession(createParams);
2581
- const sid = created.data.session?.id;
2582
- if (sid) {
2583
- persistCachedInlineSession(
2584
- cacheKey,
2585
- canonicalIdentity,
2586
- sid,
2587
- created.data.session?.clientSecret
2588
- );
2589
- }
2590
- return { result: created };
2591
- }
2592
- const detached = await api.createDetachedSession({ ...createParams, deferDataAttachment: true });
2593
- const claimed = detached.claimed.then(
2594
- (claimedResult) => {
2595
- const claimedSid = claimedResult.data.session?.id ?? detached.sessionId;
2596
- if (claimedSid) {
2597
- persistCachedInlineSession(
2598
- cacheKey,
2599
- canonicalIdentity,
2600
- claimedSid,
2601
- claimedResult.data.session?.clientSecret ?? detached.nonce
2602
- );
2603
- }
2604
- return claimedResult;
2605
- },
2606
- (error) => {
2607
- clearCachedInlineSession(cacheKey, canonicalIdentity);
2608
- throw error;
2609
- }
2610
- );
2611
- return { result: detached.shell, claimed };
2612
- }
2613
- var FloPayCheckout = defineComponent4({
2614
- name: "FloPayCheckout",
2615
- props: {
2616
- sessionId: { type: String, default: void 0 },
2617
- nonce: { type: String, default: void 0 },
2618
- createSession: { type: Object, default: void 0 },
2619
- checkoutMode: { type: String, default: void 0 },
2620
- billingApiUrl: { type: String, default: void 0 },
2621
- telemetry: { type: Boolean, default: void 0 },
2622
- locale: { type: String, default: void 0 },
2623
- layout: { type: String, default: "default" },
2624
- /**
2625
- * React's `walletPresentation` (default `'auto'`): the preferred approval
2626
- * presentation for Stripe-routed PayPal, passed to the built-in form and
2627
- * to a custom-layout form that leaves its own unset.
2628
- */
2629
- walletPresentation: { type: String, default: "auto" },
2630
- showPayPal: { type: Boolean, default: true },
2631
- showStripe: { type: Boolean, default: true },
2632
- enabledPaymentMethods: { type: Array, default: void 0 },
2633
- /** @deprecated Session-driven visibility decides (React parity). */
2634
- showApplePay: { type: Boolean, default: true },
2635
- /** @deprecated Session-driven visibility decides (React parity). */
2636
- showGooglePay: { type: Boolean, default: true },
2637
- theme: { type: String, default: void 0 },
2638
- appearance: { type: Object, default: void 0 },
2639
- buttonsTheme: { type: String, default: void 0 },
2640
- buttonsStyles: { type: Object, default: void 0 },
2641
- className: { type: String, default: void 0 },
2642
- submitLabel: { type: String, default: void 0 },
2643
- enableAVS: {
2644
- type: [Boolean, Object],
2645
- default: void 0
2646
- },
2647
- avsLayout: { type: String, default: void 0 },
2648
- cardFieldOrder: { type: Array, default: void 0 },
2649
- showCardBrandIcons: { type: Boolean, default: false },
2650
- // `default: undefined` keeps an omitted prop `undefined` (Vue would cast an
2651
- // absent Boolean to `false`), so it is not forwarded to the card form.
2652
- showCardFieldLabels: { type: Boolean, default: void 0 },
2653
- cardFieldLabels: { type: Object, default: void 0 },
2654
- cardFieldPlaceholders: {
2655
- type: Object,
2656
- default: void 0
2657
- },
2658
- cardAutoFocus: { type: Boolean, default: true },
2659
- cardFieldsTimeoutMs: { type: Number, default: void 0 },
2660
- /** @deprecated Not rendered (React parity); see {@link FloPayCheckoutProps.showSecurityFooter}. */
2661
- showSecurityFooter: { type: Boolean, default: void 0 },
2662
- /** @deprecated Ignored (React parity); see {@link FloPayCheckoutProps.fallbackPublishableKey}. */
2663
- fallbackPublishableKey: { type: String, default: void 0 },
2664
- confirmLabel: { type: String, default: void 0 },
2665
- initialErrorMessage: { type: String, default: null },
2666
- /**
2667
- * React's `onBeforeButtonClick` (a function prop: its result is read),
2668
- * passed to the built-in `SplitCardForm`. It runs before the buttons-layout
2669
- * card tile opens and before PayPal creates its order.
2670
- */
2671
- onBeforeButtonClick: {
2672
- type: Function,
2673
- default: void 0
2674
- },
2675
- initialPayPalOrderId: { type: String, default: void 0 },
2676
- debug: { type: Boolean, default: false }
2677
- },
2678
- emits: {
2679
- complete: (_result) => true,
2680
- error: (_error) => true,
2681
- instrument: (_event) => true,
2682
- decline: (_decline) => true,
2683
- // React's `onCardFieldsReady` / `onCardFieldsFailed`: the hosted card-field lifecycle.
2684
- cardFieldsReady: (_event) => true,
2685
- cardFieldsFailed: (_event) => true,
2686
- // React's `onCancel`: a direct PayPal buyer cancel from the built-in form.
2687
- cancel: (_event) => true,
2688
- buttonClick: (_method) => true,
2689
- countryChange: (_country) => true,
2690
- // React's `onZipChange`.
2691
- zipChange: (_zip) => true,
2692
- // React's `onSessionCompleted`: the session was already paid when it loaded.
2693
- sessionCompleted: (_successUrl) => true
2694
- },
2695
- setup(props, { emit, slots }) {
2696
- const state = reactive({
2697
- session: null,
2698
- loading: true,
2699
- error: null,
2700
- claimPending: false,
2701
- // React's `claimRequiresIdentity`. React's checkout sets it from its
2702
- // session bootstrap, where the value is currently always `false`
2703
- // (`bootstrapClaimRequiresIdentity`), so it stays `false` here too.
2704
- claimRequiresIdentity: false,
2705
- inlineSessionDraft: props.createSession
2706
- });
2707
- watch3(
2708
- () => props.createSession,
2709
- (draft) => {
2710
- state.inlineSessionDraft = draft;
2711
- }
2712
- );
2713
- const flopay = shallowRef3(null);
2714
- const stripeKey = shallowRef3(void 0);
2715
- const stripeCountryGate = shallowRef3(void 0);
2716
- let active = true;
2717
- const billingApiUrl = () => resolveBillingApiUrl3(props.billingApiUrl);
2718
- const mode = ref4("full");
2719
- const modeError = ref4(props.initialErrorMessage ?? null);
2720
- const savedPaymentRunning = ref4(false);
2721
- const settled = ref4(false);
2722
- const lifecycle = new AbortController();
2723
- watch3(
2724
- () => props.initialErrorMessage,
2725
- (message) => {
2726
- modeError.value = message ?? null;
2727
- }
2728
- );
2729
- provide(CHECKOUT_STATE, state);
2730
- provide(CHECKOUT_FORM_DEFAULTS, () => ({
2731
- sessionId: state.session?.id ?? props.sessionId,
2732
- nonce: state.session?.clientSecret || props.nonce,
2733
- billingApiUrl: billingApiUrl(),
2734
- session: state.session,
2735
- submitLabel: props.submitLabel,
2736
- dataAttachmentPending: Boolean(state.claimPending),
2737
- // React's `SessionInjector`: `if (session?.customer) … injected.userId =
2738
- // session.customer.id` for a child whose own `userId` is empty.
2739
- userId: state.session?.customer?.id || void 0,
2740
- // React's `SessionInjector`: `if (existing.walletPresentation === undefined)
2741
- // injected.walletPresentation = walletPresentation`.
2742
- walletPresentation: props.walletPresentation
2743
- }));
2744
- const fail = (error) => {
2745
- if (!active) return;
2746
- const failure = toFloPayError(error, "Checkout failed to load.");
2747
- state.error = failure;
2748
- state.loading = false;
2749
- state.claimPending = false;
2750
- invokeMerchantCallback3(() => emit("error", failure));
2751
- };
2752
- const adopt = (result) => {
2753
- if (!active) return;
2754
- state.session = result.data.session ?? state.session;
2755
- stripeCountryGate.value = result.data.stripe?.enabledPaymentMethodCountries;
2756
- const publishableKey = result.data.stripe?.publishableKey ?? state.session?.gateways?.stripe?.publishableKey;
2757
- if (publishableKey && publishableKey !== stripeKey.value) {
2758
- stripeKey.value = publishableKey;
2759
- const loading = loadFloPay(publishableKey, {
2760
- billingApiUrl: billingApiUrl(),
2761
- ...props.locale ? { locale: props.locale } : {},
2762
- ...props.telemetry === void 0 ? {} : { telemetry: props.telemetry }
2763
- });
2764
- void loading.catch(() => {
2765
- });
2766
- flopay.value = loading;
2767
- }
2768
- };
2769
- const createApi = () => new PaymentAPI3(billingApiUrl(), props.telemetry === false ? { telemetry: false } : void 0);
2770
- const confirmReady = () => Boolean(
2771
- (state.session?.id || props.sessionId) && (state.session?.clientSecret || props.nonce)
2772
- );
2773
- const runSavedPayment = async (unified) => {
2774
- const session = state.session;
2775
- if (!session || savedPaymentRunning.value) return;
2776
- modeError.value = null;
2777
- savedPaymentRunning.value = true;
2778
- const sessionId = session.id || props.sessionId || null;
2779
- try {
2780
- const result = await chargeSavedPayment({
2781
- api: createApi(),
2782
- billingApiUrl: billingApiUrl(),
2783
- session,
2784
- nonce: session.clientSecret || props.nonce,
2785
- unified,
2786
- signal: lifecycle.signal
2787
- });
2788
- if (sessionId) markSessionRecentlyCompleted2(sessionId);
2789
- settled.value = true;
2790
- await new Promise((resolve) => setTimeout(resolve, SAVED_PAYMENT_SUCCESS_DELAY_MS));
2791
- invokeMerchantCallback3(() => emit("complete", result));
2792
- } catch (error) {
2793
- const failure = coerceError(error, "Payment failed. Please try again.");
2794
- if (failure.code === "three_ds_aborted") return;
2795
- modeError.value = failure.message;
2796
- mode.value = "full";
2797
- if (sessionId && isDeclineCallbackFailure(failure)) {
2798
- const decline = {
2799
- method: "card",
2800
- message: failure.message,
2801
- ...failure.code ? { code: failure.code } : {},
2802
- ...failure.declineCode ? { declineCode: failure.declineCode } : {},
2803
- sessionId
2804
- };
2805
- invokeMerchantCallback3(() => emit("decline", decline));
2806
- } else {
2807
- invokeMerchantCallback3(() => emit("error", failure));
2808
- }
2809
- } finally {
2810
- savedPaymentRunning.value = false;
2811
- }
2812
- };
2813
- const confirmPurchase = () => {
2814
- if (savedPaymentRunning.value || !confirmReady()) return;
2815
- void runSavedPayment();
2816
- };
2817
- const settleMode = async (result) => {
2818
- const session = state.session;
2819
- if (!active || !session) return;
2820
- const sessionMode = session.checkoutMode;
2821
- if (sessionMode === "setup") {
2822
- state.session = null;
2823
- throw new FloPayError4(
2824
- "This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.",
2825
- "validation_error",
2826
- { code: "InvalidCardSetupSurface", param: "sessionId" }
2827
- );
2828
- }
2829
- if (session.status === "authorized" || session.status === "complete") {
2830
- settled.value = true;
2831
- const successUrl = session.successUrl ?? "";
2832
- if (session.status === "authorized") {
2833
- const completed = terminalResult(session, session.id || props.sessionId || null);
2834
- invokeMerchantCallback3(() => emit("complete", completed));
2835
- }
2836
- invokeMerchantCallback3(() => emit("sessionCompleted", successUrl));
2837
- return;
2838
- }
2839
- mode.value = props.checkoutMode ?? sessionMode ?? "full";
2840
- const paypalReturn = typeof window !== "undefined" && new URLSearchParams(window.location.search).has("payment_intent");
2841
- if (mode.value === "auto" && !paypalReturn) {
2842
- await runSavedPayment(result);
2843
- }
2844
- };
2845
- let sessionResponseReceived = false;
2846
- const start = async () => {
2847
- const api = createApi();
2848
- if (props.sessionId) {
2849
- const result = await api.getUnifiedCheckoutSession(props.sessionId, props.nonce);
2850
- sessionResponseReceived = true;
2851
- adopt(result);
2852
- await settleMode(result);
2853
- return;
2854
- }
2855
- if (!props.createSession) {
2856
- throw new FloPayError4(
2857
- "FloPayCheckout requires a sessionId or createSession.",
2858
- "validation_error"
2859
- );
2860
- }
2861
- const params = {
2862
- ...props.createSession,
2863
- ...props.checkoutMode ? { checkoutMode: props.checkoutMode } : {}
2864
- };
2865
- Object.assign(params, {
2866
- checkoutType: "embedded_checkout",
2867
- // The API accepts only `default_layout` / `buttons_layout` /
2868
- // `custom_layout`: map the prop through the shared rule React uses for
2869
- // its create request (a filled `layout` slot is React's children).
2870
- checkoutLayout: resolveCheckoutLogLayout(Boolean(slots.layout), props.layout),
2871
- // AVS analytics metadata, as React sends it.
2872
- ...props.enableAVS ? {
2873
- avsCheck: true,
2874
- avsConfig: typeof props.enableAVS === "object" ? props.enableAVS : void 0
2875
- } : {}
2876
- });
2877
- const resolved = await resolveInlineSession(api, params);
2878
- sessionResponseReceived = true;
2879
- if (!resolved.claimed) {
2880
- adopt(resolved.result);
2881
- await settleMode(resolved.result);
2882
- return;
2883
- }
2884
- state.claimPending = true;
2885
- adopt(resolved.result);
2886
- resolved.claimed.then(
2887
- (claimed) => {
2888
- if (!active) return;
2889
- adopt(applyClaimAdvertisement(resolved.result, claimed));
2890
- state.claimPending = false;
2891
- },
2892
- (error) => fail(error)
2893
- );
2894
- };
2895
- onMounted3(() => {
2896
- start().then(
2897
- () => {
2898
- if (active) state.loading = false;
2899
- },
2900
- (error) => fail(
2901
- toPublicCheckoutInitError(error, {
2902
- stage: sessionResponseReceived ? "post_session" : "session_request",
2903
- sessionId: props.sessionId || state.session?.id || void 0
2904
- })
2905
- )
2906
- );
2907
- });
2908
- onBeforeUnmount4(() => {
2909
- active = false;
2910
- lifecycle.abort();
2911
- });
2912
- const clearModeError = () => {
2913
- modeError.value = null;
2914
- };
2915
- const relay = {
2916
- onComplete: (result) => {
2917
- clearModeError();
2918
- invokeMerchantCallback3(() => emit("complete", result));
2919
- },
2920
- onError: (error) => {
2921
- clearModeError();
2922
- invokeMerchantCallback3(() => emit("error", error));
2923
- },
2924
- onDecline: (decline) => {
2925
- clearModeError();
2926
- invokeMerchantCallback3(() => emit("decline", decline));
2927
- },
2928
- onButtonClick: (method) => {
2929
- clearModeError();
2930
- invokeMerchantCallback3(() => emit("buttonClick", method));
2931
- },
2932
- onCardFieldsReady: (event) => invokeMerchantCallback3(() => emit("cardFieldsReady", event)),
2933
- onCardFieldsFailed: (event) => invokeMerchantCallback3(() => emit("cardFieldsFailed", event))
2934
- };
2935
- const withProvider = (content) => h4(
2936
- FloPayProvider,
2937
- {
2938
- flopay: flopay.value,
2939
- options: { billingApiUrl: billingApiUrl() },
2940
- // React's `onInstrument`: the provider's privacy-safe instrument feed.
2941
- onInstrument: (event) => invokeMerchantCallback3(() => emit("instrument", event))
2942
- },
2943
- { default: content }
2944
- );
2945
- const confirmView = () => {
2946
- const unavailable = savedPaymentRunning.value || !confirmReady();
2947
- const button = slots.renderConfirmButton ? slots.renderConfirmButton({ onConfirm: confirmPurchase, isProcessing: unavailable }) : h4(
2948
- "button",
2949
- {
2950
- type: "button",
2951
- "data-testid": "flopay-confirm-button",
2952
- onClick: confirmPurchase,
2953
- disabled: unavailable,
2954
- style: {
2955
- width: "100%",
2956
- padding: "0.875rem",
2957
- backgroundColor: "#4A49FF",
2958
- color: "white",
2959
- border: "none",
2960
- borderRadius: "8px",
2961
- fontSize: "1rem",
2962
- fontWeight: 600,
2963
- cursor: unavailable ? "not-allowed" : "pointer",
2964
- opacity: unavailable ? 0.6 : 1
2965
- }
2966
- },
2967
- savedPaymentRunning.value ? "Processing..." : props.confirmLabel ?? "Confirm Purchase"
2968
- );
2969
- return h4("div", { class: props.className, "data-testid": "flopay-confirm" }, [
2970
- modeError.value ? h4(
2971
- "div",
2972
- {
2973
- role: "alert",
2974
- "data-testid": "flopay-mode-error",
2975
- style: {
2976
- color: "#dc2626",
2977
- fontSize: "0.875rem",
2978
- marginBottom: "0.75rem",
2979
- textAlign: "center"
2980
- }
2981
- },
2982
- modeError.value
2983
- ) : null,
2984
- button
2985
- ]);
2986
- };
2987
- return () => {
2988
- if (state.error && !state.session) {
2989
- if (slots.error) return slots.error({ error: state.error });
2990
- return h4("div", { role: "alert", "data-testid": "flopay-load-error" }, state.error.message);
2991
- }
2992
- if (!state.session || mode.value === "auto" && savedPaymentRunning.value) {
2993
- return h4(
2994
- "div",
2995
- { role: "status", "aria-busy": "true", "data-testid": "flopay-checkout-loading" },
2996
- slots.loading?.() ?? "Loading checkout\u2026"
2997
- );
2998
- }
2999
- if (settled.value) return null;
3000
- if (mode.value === "confirm") {
3001
- return withProvider(() => [slots.default?.(), confirmView()]);
3002
- }
3003
- const session = state.session;
3004
- const modeNotice = modeError.value ? h4(
3005
- "div",
3006
- {
3007
- role: "alert",
3008
- "data-testid": "flopay-mode-error",
3009
- style: {
3010
- padding: "0.75rem 1rem",
3011
- marginBottom: "0.75rem",
3012
- backgroundColor: "#FEF3C7",
3013
- border: "1px solid #F59E0B",
3014
- borderRadius: "8px",
3015
- color: "#92400E",
3016
- fontSize: "0.875rem"
3017
- }
3018
- },
3019
- modeError.value
3020
- ) : null;
3021
- const account = props.createSession?.account;
3022
- const layoutSlot = slots.layout?.();
3023
- const customLayout = layoutSlot && props.className ? h4("div", { class: props.className }, layoutSlot) : layoutSlot;
3024
- const cardSlots = Object.fromEntries(
3025
- Object.entries({
3026
- cardButtonContent: slots.cardButtonContent,
3027
- cardBackButtonContent: slots.cardBackButtonContent,
3028
- cardTitleContent: slots.cardTitleContent,
3029
- cardPreFormSlot: slots.cardPreFormSlot
3030
- }).filter(([, slot]) => slot !== void 0)
3031
- );
3032
- const form = customLayout ?? h4(
3033
- SplitCardForm,
3034
- {
3035
- sessionId: session.id || props.sessionId,
3036
- nonce: session.clientSecret || props.nonce,
3037
- billingApiUrl: billingApiUrl(),
3038
- telemetry: props.telemetry,
3039
- email: session.customer?.email || account?.email,
3040
- firstName: session.customer?.firstName || account?.firstName,
3041
- lastName: session.customer?.lastName || account?.lastName,
3042
- // React: `userId={session?.customer?.id || effectiveCreateSession?.account?.userId}`.
3043
- userId: session.customer?.id || account?.userId,
3044
- layout: props.layout,
3045
- showPayPal: props.showPayPal,
3046
- showStripe: props.showStripe,
3047
- enabledPaymentMethods: props.enabledPaymentMethods,
3048
- showApplePay: props.showApplePay,
3049
- showGooglePay: props.showGooglePay,
3050
- // React: the bundle comes through `theme`; an explicit `appearance`
3051
- // wins over the bundle's for the Stripe-side half.
3052
- theme: props.theme,
3053
- buttonsTheme: props.buttonsTheme,
3054
- buttonsStyles: props.buttonsStyles,
3055
- appearance: props.appearance ?? resolveTheme2(props.theme)?.appearance,
3056
- className: props.className,
3057
- submitLabel: props.submitLabel,
3058
- enableAVS: props.enableAVS,
3059
- // React: `avsCheck={!!enableAVS}`, reported in the `/account` snapshot.
3060
- avsCheck: !!props.enableAVS,
3061
- // React: `checkoutType={createSessionParams ? 'embedded_checkout' : 'standard_checkout'}`
3062
- // and `checkoutLayout={resolveCheckoutLogLayout(children, layout)}`, the
3063
- // analytics metadata on the form's own `/process`. The built-in form
3064
- // renders only without a custom layout, as in React.
3065
- checkoutType: props.createSession ? "embedded_checkout" : "standard_checkout",
3066
- checkoutLayout: resolveCheckoutLogLayout(false, props.layout),
3067
- avsLayout: props.avsLayout,
3068
- cardFieldOrder: props.cardFieldOrder,
3069
- showCardBrandIcons: props.showCardBrandIcons === true,
3070
- // Forwarded only when set, as React does: an omitted prop sends nothing.
3071
- ...props.showCardFieldLabels === void 0 ? {} : { showCardFieldLabels: props.showCardFieldLabels },
3072
- ...props.cardFieldLabels === void 0 ? {} : { cardFieldLabels: props.cardFieldLabels },
3073
- cardFieldPlaceholders: props.cardFieldPlaceholders,
3074
- cardAutoFocus: props.cardAutoFocus,
3075
- cardFieldsTimeoutMs: props.cardFieldsTimeoutMs,
3076
- session,
3077
- dataAttachmentPending: Boolean(state.claimPending),
3078
- dataAttachmentRequiresIdentity: Boolean(state.claimRequiresIdentity),
3079
- // React: `walletPresentation={walletPresentation}` on its built-in form.
3080
- walletPresentation: props.walletPresentation,
3081
- onBeforeButtonClick: props.onBeforeButtonClick,
3082
- // React fills these from the session for its built-in form only:
3083
- // `directPaypal={directPaypalConfig}`,
3084
- // `currency={session?.currency?.toLowerCase() ?? 'usd'}`,
3085
- // `isSubscription={session?.mode === 'subscription'}`, the Stripe
3086
- // country gate, and `debug={debug}`.
3087
- // The shared resolver React uses. React passes the normalized
3088
- // `data.paypal`, which `@flopay/js` copies field for field from
3089
- // this `gateways.paypal` when it has a client id.
3090
- directPaypal: resolveDirectPaypalConfig(
3091
- session.gateways?.paypal,
3092
- props.initialPayPalOrderId
3093
- ),
3094
- currency: session.currency?.toLowerCase() ?? "usd",
3095
- isSubscription: session.mode === "subscription",
3096
- // React: `totalAmount={session ? Math.round(buildCheckoutDisplayData(session).total * 100) : 0}`.
3097
- totalAmount: Math.round(buildCheckoutDisplayData(session).total * 100),
3098
- enabledPaymentMethodCountries: stripeCountryGate.value,
3099
- debug: props.debug,
3100
- ...relay,
3101
- // React's `onCancel={onCancel}`: the built-in form's direct PayPal
3102
- // cancel reaches the merchant once.
3103
- onCancel: (event) => invokeMerchantCallback3(() => emit("cancel", event)),
3104
- onCountryChange: (country) => invokeMerchantCallback3(() => emit("countryChange", country)),
3105
- onZipChange: (zip) => invokeMerchantCallback3(() => emit("zipChange", zip))
3106
- },
3107
- cardSlots
3108
- );
3109
- return withProvider(() => [slots.default?.(), modeNotice, form]);
3110
- };
3111
- }
3112
- });
5
+ FloPayRuntimeCardSetup
6
+ } from "./chunk-2VPPDVV7.mjs";
3113
7
 
3114
- // src/automatic-payment-button.ts
3115
- var SUCCESS_DELAY_MS2 = SAVED_PAYMENT_SUCCESS_DELAY_MS;
3116
- var GET_SESSION_TIMEOUT_MS = 15e3;
3117
- function sessionFetchFailed(message, cause) {
3118
- return new FloPayError5(message, "api_error", {
3119
- code: "session_fetch_failed",
3120
- ...cause === void 0 ? {} : { cause }
3121
- });
3122
- }
3123
- function settleUnlessAborted(promise, signal) {
3124
- return new Promise((resolve, reject) => {
3125
- const onAbort = () => reject(signal.reason);
3126
- if (signal.aborted) {
3127
- onAbort();
3128
- return;
3129
- }
3130
- signal.addEventListener("abort", onAbort, { once: true });
3131
- promise.then(
3132
- (value) => {
3133
- signal.removeEventListener("abort", onAbort);
3134
- resolve(value);
3135
- },
3136
- (error) => {
3137
- signal.removeEventListener("abort", onAbort);
3138
- reject(error);
3139
- }
3140
- );
3141
- });
3142
- }
3143
- function isOneClickSession(value) {
3144
- const session = value;
3145
- return typeof session?.sessionId === "string" && session.sessionId.length > 0 && typeof session.nonce === "string" && session.nonce.length > 0;
3146
- }
3147
- function resolveDraft(props) {
3148
- if (props.createSession) return { ...props.createSession, checkoutMode: "auto" };
3149
- if (!props.clientId || !props.account || !props.successUrl || !props.cancelUrl) return null;
3150
- const hasProducts = props.products != null;
3151
- return {
3152
- clientId: props.clientId,
3153
- products: props.products,
3154
- items: hasProducts ? void 0 : props.items,
3155
- subscriptions: hasProducts ? void 0 : props.subscriptions,
3156
- account: props.account,
3157
- successUrl: props.successUrl,
3158
- cancelUrl: props.cancelUrl,
3159
- couponCodes: props.couponCodes,
3160
- tagsData: props.tagsData,
3161
- utmMetadata: props.utmMetadata,
3162
- checkoutMode: "auto"
3163
- };
3164
- }
3165
- function canFallBack(error, sessionId) {
3166
- if (!sessionId || error.type === "validation_error") return false;
3167
- return error.code !== "stored_payment_method_unsupported";
3168
- }
3169
- var FloPayAutomaticPaymentButton = defineComponent5({
3170
- name: "FloPayAutomaticPaymentButton",
3171
- // The root is a fragment (button, notice, fallback checkout): native button
3172
- // attributes are bound to the `<button>` explicitly, as React spreads them.
3173
- inheritAttrs: false,
3174
- props: {
3175
- sessionId: { type: String, default: void 0 },
3176
- nonce: { type: String, default: void 0 },
3177
- createSession: { type: Object, default: void 0 },
3178
- getSession: { type: Function, default: void 0 },
3179
- // Deprecated and ignored, as in React (see the props interface).
3180
- paymentMethodId: { type: String, default: void 0 },
3181
- checkoutMethod: { type: String, default: void 0 },
3182
- clientId: { type: String, default: void 0 },
3183
- products: { type: Array, default: void 0 },
3184
- items: { type: Array, default: void 0 },
3185
- subscriptions: { type: Array, default: void 0 },
3186
- account: { type: Object, default: void 0 },
3187
- successUrl: { type: String, default: void 0 },
3188
- cancelUrl: { type: String, default: void 0 },
3189
- couponCodes: { type: Array, default: void 0 },
3190
- tagsData: { type: Object, default: void 0 },
3191
- utmMetadata: {
3192
- type: Object,
3193
- default: void 0
3194
- },
3195
- billingApiUrl: { type: String, default: void 0 },
3196
- locale: { type: String, default: void 0 },
3197
- disabled: { type: Boolean, default: false },
3198
- theme: { type: String, default: void 0 },
3199
- appearance: { type: Object, default: void 0 },
3200
- buttonsTheme: { type: String, default: void 0 },
3201
- buttonsStyles: { type: Object, default: void 0 }
3202
- },
3203
- emits: {
3204
- success: (_event) => true,
3205
- error: (_error) => true,
3206
- decline: (_decline) => true
3207
- },
3208
- setup(props, { attrs, emit, slots }) {
3209
- const processing = ref5(false);
3210
- const notice = ref5(null);
3211
- const fallback = ref5(null);
3212
- let mounted = true;
3213
- const lifecycle = new AbortController();
3214
- let sessionFetch = null;
3215
- onBeforeUnmount5(() => {
3216
- mounted = false;
3217
- lifecycle.abort();
3218
- sessionFetch?.abort();
3219
- });
3220
- const billingApiUrl = () => resolveBillingApiUrl4(props.billingApiUrl);
3221
- const themeBundle = computed3(() => resolveTheme3(props.theme));
3222
- const bStyles = computed3(() => {
3223
- const base = themeBundle.value?.buttonsLayout ?? resolveButtonsLayoutTheme2(props.buttonsTheme);
3224
- const override = props.buttonsStyles;
3225
- if (!override) return base;
3226
- return { ...base, ...override, cardButton: { ...base.cardButton, ...override.cardButton } };
3227
- });
3228
- const resolvedAppearance = computed3(() => {
3229
- const bundleAppearance = themeBundle.value?.appearance;
3230
- if (!props.appearance) return bundleAppearance;
3231
- if (!bundleAppearance) return props.appearance;
3232
- return {
3233
- ...bundleAppearance,
3234
- ...props.appearance,
3235
- variables: { ...bundleAppearance.variables, ...props.appearance.variables }
3236
- };
3237
- });
3238
- const tile = computed3(() => {
3239
- const vars = resolvedAppearance.value?.variables;
3240
- const explicitPrimary = typeof vars?.colorPrimary === "string" ? vars.colorPrimary : void 0;
3241
- const primary = explicitPrimary ?? "#4A49FF";
3242
- const hover = typeof vars?.colorPrimaryHover === "string" ? vars.colorPrimaryHover : darkenHex(primary, 0.12);
3243
- const radius = typeof vars?.borderRadius === "string" ? vars.borderRadius : "8px";
3244
- return {
3245
- primary,
3246
- hover,
3247
- // Only a primary-filled button (a bundle or an explicit colorPrimary) hovers.
3248
- hovers: Boolean(themeBundle.value || explicitPrimary),
3249
- style: {
3250
- width: "100%",
3251
- ...bStyles.value.cardButton,
3252
- ...derivePrimaryTileStyle2({
3253
- themeBundle: themeBundle.value,
3254
- resolvedPrimaryColor: primary,
3255
- resolvedBorderRadius: radius,
3256
- submitButtonStyle: bStyles.value.submitButton,
3257
- explicitPrimaryColor: explicitPrimary
3258
- }),
3259
- fontSize: bStyles.value.cardButtonFontSize ?? "0.95rem",
3260
- fontWeight: 600
3261
- }
3262
- };
3263
- });
3264
- const succeed = async (event) => {
3265
- await new Promise((resolve) => setTimeout(resolve, SUCCESS_DELAY_MS2));
3266
- invokeMerchantCallback4(() => emit("success", event));
3267
- };
3268
- const fail = (error, sessionId, nonce) => {
3269
- if (!mounted && error.code === "three_ds_aborted") return;
3270
- if (mounted) notice.value = error.message;
3271
- invokeMerchantCallback4(() => emit("error", error));
3272
- if (sessionId) {
3273
- const decline = {
3274
- method: "card",
3275
- message: error.message,
3276
- ...error.code ? { code: error.code } : {},
3277
- ...error.declineCode ? { declineCode: error.declineCode } : {},
3278
- sessionId
3279
- };
3280
- invokeMerchantCallback4(() => emit("decline", decline));
3281
- }
3282
- if (mounted && canFallBack(error, sessionId) && sessionId) {
3283
- fallback.value = { sessionId, ...nonce ? { nonce } : {} };
3284
- }
3285
- };
3286
- const fetchOneClickSession = async (getSession) => {
3287
- const controller = new AbortController();
3288
- sessionFetch = controller;
3289
- let timedOut = false;
3290
- const timer = setTimeout(() => {
3291
- timedOut = true;
3292
- controller.abort();
3293
- }, GET_SESSION_TIMEOUT_MS);
3294
- try {
3295
- const fetched = await settleUnlessAborted(
3296
- (async () => getSession({ signal: controller.signal }))(),
3297
- controller.signal
3298
- );
3299
- if (!mounted) return null;
3300
- if (!isOneClickSession(fetched)) {
3301
- throw sessionFetchFailed(
3302
- "getSession must resolve to a server-minted { sessionId, nonce }."
3303
- );
3304
- }
3305
- return { sessionId: fetched.sessionId, nonce: fetched.nonce };
3306
- } catch (error) {
3307
- if (!mounted) return null;
3308
- if (error instanceof FloPayError5 && error.code === "session_fetch_failed") throw error;
3309
- if (timedOut) {
3310
- throw sessionFetchFailed(
3311
- `getSession did not resolve within ${GET_SESSION_TIMEOUT_MS / 1e3} seconds.`
3312
- );
3313
- }
3314
- throw sessionFetchFailed("Could not fetch the one-click session.", error);
3315
- } finally {
3316
- clearTimeout(timer);
3317
- if (sessionFetch === controller) sessionFetch = null;
3318
- }
3319
- };
3320
- const run = async () => {
3321
- if (processing.value || props.disabled) return;
3322
- fallback.value = null;
3323
- notice.value = null;
3324
- const draft = resolveDraft(props);
3325
- const sourceCount = [props.sessionId, props.getSession, draft].filter(Boolean).length;
3326
- if (sourceCount !== 1) {
3327
- fail(
3328
- new FloPayError5(
3329
- sourceCount > 1 ? "Provide exactly one of sessionId, getSession or create-session props." : "Provide a sessionId or the props required to create an automatic payment session.",
3330
- "validation_error"
3331
- ),
3332
- null
3333
- );
3334
- return;
3335
- }
3336
- processing.value = true;
3337
- let sessionId = props.sessionId ?? null;
3338
- let nonce = props.nonce;
3339
- try {
3340
- const api = new PaymentAPI4(billingApiUrl());
3341
- let result;
3342
- if (props.sessionId) {
3343
- result = await api.getUnifiedCheckoutSession(props.sessionId, props.nonce);
3344
- } else if (props.getSession) {
3345
- const fetched = await fetchOneClickSession(props.getSession);
3346
- if (!fetched) return;
3347
- sessionId = fetched.sessionId;
3348
- nonce = fetched.nonce;
3349
- result = await api.getUnifiedCheckoutSession(fetched.sessionId, fetched.nonce);
3350
- } else {
3351
- try {
3352
- result = await api.createAndFetchSession(draft);
3353
- } catch (error) {
3354
- if (readErrorCode(error) === "session_auto_completed") {
3355
- await succeed({
3356
- result: { status: "succeeded" },
3357
- session: null,
3358
- sessionId: null,
3359
- autoCompleted: true
3360
- });
3361
- return;
3362
- }
3363
- throw error;
3364
- }
3365
- }
3366
- const session = result.data.session;
3367
- if (!session) throw new FloPayError5("The checkout session could not be read.", "api_error");
3368
- sessionId = session.id || sessionId;
3369
- nonce = nonce ?? (session.clientSecret || void 0);
3370
- if (isTerminalSuccess(session)) {
3371
- await succeed({
3372
- result: terminalResult(session, sessionId),
3373
- session,
3374
- sessionId,
3375
- autoCompleted: false
3376
- });
3377
- return;
3378
- }
3379
- if (session.status === "expired") {
3380
- throw new FloPayError5("This checkout session has expired.", "api_error", {
3381
- code: "session_expired"
3382
- });
3383
- }
3384
- const settled = await chargeSavedPayment({
3385
- api,
3386
- billingApiUrl: billingApiUrl(),
3387
- session,
3388
- nonce,
3389
- unified: result,
3390
- signal: lifecycle.signal
3391
- });
3392
- await succeed({ result: settled, session, sessionId, autoCompleted: false });
3393
- } catch (error) {
3394
- fail(coerceError(error, "Automatic payment failed. Please try again."), sessionId, nonce);
3395
- } finally {
3396
- if (mounted) processing.value = false;
3397
- }
3398
- };
3399
- const handleClick = (event) => {
3400
- const consumer = attrs.onClick;
3401
- for (const listener of [consumer].flat()) {
3402
- if (typeof listener === "function") listener(event);
3403
- }
3404
- if (event.defaultPrevented) return;
3405
- void run();
3406
- };
3407
- const runConsumer = (name, event) => {
3408
- const consumer = attrs[name];
3409
- for (const listener of [consumer].flat()) {
3410
- if (typeof listener === "function") listener(event);
3411
- }
3412
- };
3413
- const handleMouseEnter = (event) => {
3414
- runConsumer("onMouseenter", event);
3415
- if (event.defaultPrevented || props.disabled || processing.value || !tile.value.hovers)
3416
- return;
3417
- event.currentTarget.style.backgroundColor = tile.value.hover;
3418
- };
3419
- const handleMouseLeave = (event) => {
3420
- runConsumer("onMouseleave", event);
3421
- if (event.defaultPrevented || !tile.value.hovers) return;
3422
- event.currentTarget.style.backgroundColor = tile.value.primary;
3423
- };
3424
- return () => {
3425
- const {
3426
- onClick: _consumerClick,
3427
- onMouseenter: _consumerEnter,
3428
- onMouseleave: _consumerLeave,
3429
- style: consumerStyle,
3430
- ...buttonAttrs
3431
- } = attrs;
3432
- const busy = props.disabled || processing.value;
3433
- return [
3434
- h5(
3435
- "button",
3436
- {
3437
- // React's `type = 'button'` default, overridable like any attribute.
3438
- type: "button",
3439
- ...buttonAttrs,
3440
- // The theme first; the consumer's inline `style` still wins.
3441
- style: [
3442
- tile.value.style,
3443
- { cursor: busy ? "not-allowed" : "pointer", opacity: busy ? 0.6 : 1 },
3444
- consumerStyle
3445
- ],
3446
- disabled: busy,
3447
- "aria-busy": processing.value ? "true" : void 0,
3448
- onClick: handleClick,
3449
- onMouseenter: handleMouseEnter,
3450
- onMouseleave: handleMouseLeave
3451
- },
3452
- slots.default?.() ?? (processing.value ? "Processing\u2026" : "Pay now")
3453
- ),
3454
- notice.value ? h5("div", { role: "alert" }, notice.value) : null,
3455
- fallback.value ? h5(FloPayCheckout, {
3456
- sessionId: fallback.value.sessionId,
3457
- nonce: fallback.value.nonce,
3458
- billingApiUrl: billingApiUrl(),
3459
- // React: the modal inherits the button's look.
3460
- theme: props.theme,
3461
- ...resolvedAppearance.value ? { appearance: resolvedAppearance.value } : {},
3462
- buttonsTheme: props.buttonsTheme,
3463
- buttonsStyles: props.buttonsStyles,
3464
- onComplete: (result) => invokeMerchantCallback4(
3465
- () => emit("success", {
3466
- result,
3467
- session: null,
3468
- sessionId: fallback.value?.sessionId ?? null,
3469
- autoCompleted: false
3470
- })
3471
- ),
3472
- onError: (error) => invokeMerchantCallback4(() => emit("error", error)),
3473
- onDecline: (decline) => invokeMerchantCallback4(() => emit("decline", decline))
3474
- }) : null
3475
- ];
3476
- };
3477
- }
3478
- });
8
+ // src/index.ts
9
+ import { dropThirdPartyOnlyError } from "@flopay/shared";
3479
10
 
3480
- // src/flopay-runtime-card-setup.ts
3481
- import { loadCheckoutRuntime } from "@flopay/js";
3482
- import { FloPayError as FloPayError6 } from "@flopay/shared";
3483
- import {
3484
- defineComponent as defineComponent6,
3485
- getCurrentInstance,
3486
- h as h6,
3487
- onBeforeUnmount as onBeforeUnmount6,
3488
- onMounted as onMounted4,
3489
- ref as ref6,
3490
- watch as watch4
3491
- } from "vue";
3492
- var SETUP_CONTRACT_VERSION = "2.4.0";
3493
- function isRecord(value) {
3494
- return typeof value === "object" && value !== null && !Array.isArray(value);
3495
- }
3496
- var ERROR_TYPES = /* @__PURE__ */ new Set([
3497
- "validation_error",
3498
- "api_error",
3499
- "authentication_error",
3500
- "rate_limit_error",
3501
- "network_error"
3502
- ]);
3503
- function setupError(message, type, retryable, options = {}) {
3504
- return Object.assign(new FloPayError6(message, type, options), { retryable });
3505
- }
3506
- function errorFromPayload(payload) {
3507
- const record = isRecord(payload) ? payload : {};
3508
- const type = typeof record.type === "string" && ERROR_TYPES.has(record.type) ? record.type : "";
3509
- return setupError(
3510
- typeof record.message === "string" ? record.message : "The setup failed.",
3511
- type || "api_error",
3512
- record.retryable === true,
3513
- {
3514
- ...typeof record.code === "string" ? { code: record.code } : {},
3515
- ...typeof record.param === "string" ? { param: record.param } : {},
3516
- ...typeof record.statusCode === "number" ? { statusCode: record.statusCode } : {}
3517
- }
3518
- );
3519
- }
3520
- function loadError(caught) {
3521
- if (caught instanceof FloPayError6) {
3522
- return setupError(caught.message, caught.type, true, {
3523
- code: caught.code ?? "runtime_load_failed",
3524
- cause: caught
3525
- });
3526
- }
3527
- return setupError("The checkout runtime failed to load.", "network_error", true, {
3528
- code: "runtime_load_failed",
3529
- cause: caught
3530
- });
3531
- }
3532
- function setupConfig(props) {
3533
- return {
3534
- ...props.theme === void 0 ? {} : { theme: props.theme },
3535
- ...props.appearance === void 0 ? {} : { appearance: props.appearance },
3536
- ...props.buttonsStyles === void 0 ? {} : { buttonsStyles: props.buttonsStyles },
3537
- ...props.containerStyle === void 0 ? {} : { containerStyle: props.containerStyle },
3538
- ...props.strings === void 0 ? {} : { strings: props.strings }
3539
- };
3540
- }
3541
- var setupProps = {
3542
- sessionId: { type: String, required: true },
3543
- nonce: { type: String, required: true },
3544
- theme: {
3545
- type: [String, Object],
3546
- default: void 0
3547
- },
3548
- appearance: { type: Object, default: void 0 },
3549
- buttonsStyles: { type: Object, default: void 0 },
3550
- containerStyle: {
3551
- type: Object,
3552
- default: void 0
3553
- },
3554
- strings: { type: Object, default: void 0 },
3555
- runtimeUrl: { type: String, required: true },
3556
- runtimeTimeoutMs: { type: Number, default: void 0 }
3557
- };
3558
- var setupEmits = {
3559
- ready: () => true,
3560
- validation: (_message) => true,
3561
- complete: (_event) => true,
3562
- decline: (_event) => true,
3563
- cancel: (_event) => true,
3564
- error: (_error) => true
3565
- };
3566
- var LISTENERS = {
3567
- ready: "onReady",
3568
- validation: "onValidation",
3569
- complete: "onComplete",
3570
- decline: "onDecline",
3571
- cancel: "onCancel",
3572
- error: "onError"
3573
- };
3574
- function setupRuntimeSetup(kind, props, emit) {
3575
- const instance = getCurrentInstance();
3576
- const container = ref6(null);
3577
- let handle = null;
3578
- let generation = 0;
3579
- const deliver = (name, argument) => {
3580
- try {
3581
- if (instance?.isUnmounted) {
3582
- const listener = instance.vnode.props?.[LISTENERS[name]];
3583
- if (typeof listener === "function") listener(argument);
3584
- return;
3585
- }
3586
- emit(
3587
- name,
3588
- ...argument === void 0 ? [] : [argument]
3589
- );
3590
- } catch {
3591
- }
3592
- };
3593
- const onEvent = (event) => {
3594
- const payload = event.payload;
3595
- switch (event.name) {
3596
- case "setupReady":
3597
- deliver("ready");
3598
- return;
3599
- case "setupValidation":
3600
- deliver(
3601
- "validation",
3602
- isRecord(payload) && typeof payload.message === "string" ? payload.message : null
3603
- );
3604
- return;
3605
- case "complete":
3606
- case "decline":
3607
- case "cancel":
3608
- deliver(event.name, payload);
3609
- return;
3610
- case "error":
3611
- deliver("error", errorFromPayload(payload));
3612
- return;
3613
- default:
3614
- return;
3615
- }
3616
- };
3617
- const stop = () => {
3618
- generation += 1;
3619
- const current = handle;
3620
- handle = null;
3621
- current?.unmount();
3622
- };
3623
- const start = () => {
3624
- const element = container.value;
3625
- if (!element) return;
3626
- generation += 1;
3627
- const current = generation;
3628
- loadCheckoutRuntime({
3629
- runtimeUrl: props.runtimeUrl,
3630
- ...props.runtimeTimeoutMs === void 0 ? {} : { timeoutMs: props.runtimeTimeoutMs }
3631
- }).then(
3632
- (runtime) => {
3633
- if (current !== generation) return;
3634
- if (typeof runtime.mountSetup !== "function") {
3635
- deliver(
3636
- "error",
3637
- setupError(
3638
- "The checkout runtime on this page is too old to run setup.",
3639
- "api_error",
3640
- false,
3641
- { code: "runtime_setup_unsupported" }
3642
- )
3643
- );
3644
- return;
3645
- }
3646
- handle = runtime.mountSetup(element, {
3647
- setup: kind,
3648
- sessionId: props.sessionId,
3649
- nonce: props.nonce,
3650
- contractVersion: SETUP_CONTRACT_VERSION,
3651
- ...setupConfig(props),
3652
- onEvent
3653
- });
3654
- },
3655
- (caught) => {
3656
- if (current === generation) deliver("error", loadError(caught));
3657
- }
3658
- );
3659
- };
3660
- onMounted4(start);
3661
- watch4(
3662
- () => [props.sessionId, props.nonce, props.runtimeUrl, props.runtimeTimeoutMs],
3663
- () => {
3664
- stop();
3665
- start();
3666
- }
3667
- );
3668
- watch4(
3669
- () => JSON.stringify(setupConfig(props)),
3670
- () => {
3671
- handle?.update({
3672
- theme: props.theme,
3673
- appearance: props.appearance,
3674
- buttonsStyles: props.buttonsStyles,
3675
- containerStyle: props.containerStyle,
3676
- strings: props.strings
3677
- });
3678
- }
3679
- );
3680
- onBeforeUnmount6(stop);
3681
- return () => h6("div", { ref: container });
3682
- }
3683
- var FloPayRuntimeCardSetup = defineComponent6({
3684
- name: "FloPayRuntimeCardSetup",
3685
- props: setupProps,
3686
- emits: setupEmits,
3687
- setup(props, { emit }) {
3688
- return setupRuntimeSetup("card", props, emit);
3689
- }
3690
- });
11
+ // src/hosted-runtime-components.ts
12
+ import { defineComponent as defineComponent2, h as h2, inject, provide } from "vue";
3691
13
 
3692
14
  // src/flopay-runtime-checkout.ts
3693
- import { loadCheckoutRuntime as loadCheckoutRuntime2 } from "@flopay/js";
3694
- import { FloPayError as FloPayError7 } from "@flopay/shared";
3695
- import { defineComponent as defineComponent7, h as h7, onBeforeUnmount as onBeforeUnmount7, onMounted as onMounted5, ref as ref7, watch as watch5 } from "vue";
15
+ import { loadCheckoutRuntime } from "@flopay/js";
16
+ import { FloPayError } from "@flopay/shared";
17
+ import { defineComponent, h, onBeforeUnmount, onMounted, ref, watch } from "vue";
3696
18
  function asFloPayError(caught) {
3697
- if (caught instanceof FloPayError7) return caught;
3698
- return new FloPayError7("The checkout runtime failed to load.", "network_error", {
19
+ if (caught instanceof FloPayError) return caught;
20
+ return new FloPayError("The checkout runtime failed to load.", "network_error", {
3699
21
  code: "runtime_load_failed",
3700
22
  cause: caught
3701
23
  });
3702
24
  }
3703
25
  var RUNTIME_CONTRACT_VERSION = "2.2.0";
3704
26
  var SAVED_PAYMENT_CONTRACT_VERSION = "2.3.0";
27
+ var HIDDEN_PAYMENT_METHODS_CONTRACT_VERSION = "2.5.0";
28
+ function declaredContractVersion(savedPayment, extra) {
29
+ if (extra !== void 0 && "hiddenPaymentMethods" in extra) {
30
+ return HIDDEN_PAYMENT_METHODS_CONTRACT_VERSION;
31
+ }
32
+ return savedPayment ? SAVED_PAYMENT_CONTRACT_VERSION : RUNTIME_CONTRACT_VERSION;
33
+ }
3705
34
  function savedPaymentSetting(mode, supplier) {
3706
35
  const setting = { mode };
3707
36
  if (supplier) Object.defineProperty(setting, "getSession", { enumerable: true, get: supplier });
@@ -3713,7 +42,7 @@ function rulesKey(rules) {
3713
42
  function rulesFromKey(key) {
3714
43
  return key === void 0 ? void 0 : JSON.parse(key);
3715
44
  }
3716
- var FloPayRuntimeCheckout = defineComponent7({
45
+ var FloPayRuntimeCheckout = defineComponent({
3717
46
  name: "FloPayRuntimeCheckout",
3718
47
  props: {
3719
48
  publishableKey: { type: String, required: true },
@@ -3732,14 +61,15 @@ var FloPayRuntimeCheckout = defineComponent7({
3732
61
  default: void 0
3733
62
  },
3734
63
  runtimeUrl: { type: String, required: true },
3735
- runtimeTimeoutMs: { type: Number, default: void 0 }
64
+ runtimeTimeoutMs: { type: Number, default: void 0 },
65
+ extraMountOptions: { type: Object, default: void 0 }
3736
66
  },
3737
67
  emits: {
3738
68
  event: (_event) => true,
3739
69
  error: (_error) => true
3740
70
  },
3741
71
  setup(props, { emit }) {
3742
- const container = ref7(null);
72
+ const container = ref(null);
3743
73
  let handle = null;
3744
74
  let mountedLayoutRules;
3745
75
  let run = 0;
@@ -3751,13 +81,15 @@ var FloPayRuntimeCheckout = defineComponent7({
3751
81
  const start = () => {
3752
82
  stop();
3753
83
  const current = run;
3754
- loadCheckoutRuntime2({ runtimeUrl: props.runtimeUrl, timeoutMs: props.runtimeTimeoutMs }).then(
84
+ loadCheckoutRuntime({ runtimeUrl: props.runtimeUrl, timeoutMs: props.runtimeTimeoutMs }).then(
3755
85
  (runtime) => {
3756
86
  if (current !== run || !container.value) return;
3757
87
  mountedLayoutRules = rulesKey(props.paymentMethodLayout);
3758
88
  const mode = props.automaticPayment?.mode;
89
+ const extra = props.extraMountOptions === void 0 ? void 0 : JSON.parse(JSON.stringify(props.extraMountOptions));
3759
90
  handle = runtime.mount(container.value, {
3760
- contractVersion: mode ? SAVED_PAYMENT_CONTRACT_VERSION : RUNTIME_CONTRACT_VERSION,
91
+ ...extra,
92
+ contractVersion: declaredContractVersion(Boolean(mode), extra),
3761
93
  ...mode ? {
3762
94
  automaticPayment: savedPaymentSetting(
3763
95
  mode,
@@ -3780,8 +112,8 @@ var FloPayRuntimeCheckout = defineComponent7({
3780
112
  }
3781
113
  );
3782
114
  };
3783
- onMounted5(start);
3784
- watch5(
115
+ onMounted(start);
116
+ watch(
3785
117
  [
3786
118
  () => props.publishableKey,
3787
119
  () => props.sessionId,
@@ -3790,6 +122,7 @@ var FloPayRuntimeCheckout = defineComponent7({
3790
122
  () => props.createSession === void 0 ? void 0 : JSON.stringify(props.createSession),
3791
123
  () => props.runtimeUrl,
3792
124
  () => props.runtimeTimeoutMs,
125
+ () => props.extraMountOptions === void 0 ? void 0 : JSON.stringify(props.extraMountOptions),
3793
126
  // The runtime lays out its payment methods at mount, so a new layout mounts again.
3794
127
  () => props.layout,
3795
128
  // By value: an equal saved-payment setting in a new object does not mount again.
@@ -3798,19 +131,19 @@ var FloPayRuntimeCheckout = defineComponent7({
3798
131
  ],
3799
132
  () => start()
3800
133
  );
3801
- watch5(
134
+ watch(
3802
135
  () => props.appearance,
3803
136
  (appearance) => {
3804
137
  if (appearance !== void 0) handle?.update({ appearance });
3805
138
  }
3806
139
  );
3807
- watch5(
140
+ watch(
3808
141
  () => props.strings,
3809
142
  (strings) => {
3810
143
  if (strings !== void 0) handle?.update({ strings });
3811
144
  }
3812
145
  );
3813
- watch5(
146
+ watch(
3814
147
  // By value, so equal rules in a new (or reactive) object ask for no new layout.
3815
148
  () => rulesKey(props.paymentMethodLayout),
3816
149
  (key) => {
@@ -3819,48 +152,218 @@ var FloPayRuntimeCheckout = defineComponent7({
3819
152
  handle.update({ paymentMethodLayout: rulesFromKey(key) });
3820
153
  }
3821
154
  );
3822
- onBeforeUnmount7(stop);
3823
- return () => h7("div", { ref: container, "data-flopay-runtime-checkout": "" });
155
+ onBeforeUnmount(stop);
156
+ return () => h("div", { ref: container, "data-flopay-runtime-checkout": "" });
3824
157
  }
3825
158
  });
3826
159
 
3827
- // src/flopay-runtime-payment-method-setup.ts
3828
- import { defineComponent as defineComponent8 } from "vue";
3829
- var FloPayRuntimePaymentMethodSetup = defineComponent8({
3830
- name: "FloPayRuntimePaymentMethodSetup",
3831
- props: setupProps,
3832
- emits: setupEmits,
3833
- setup(props, { emit }) {
3834
- return setupRuntimeSetup("payment_method", props, emit);
3835
- }
3836
- });
160
+ // src/runtime-context.ts
161
+ var FLOPAY_RUNTIME_CONTEXT = /* @__PURE__ */ Symbol("flopay-runtime-context");
3837
162
 
3838
- // src/hooks.ts
3839
- import { inject as inject3, reactive as reactive2, shallowRef as shallowRef4 } from "vue";
3840
- function useFloPay() {
3841
- return inject3(FLOPAY_CONTEXT, null)?.flopay ?? shallowRef4(null);
3842
- }
3843
- function usePayPalFloPay() {
3844
- return inject3(FLOPAY_CONTEXT, null)?.paypalFlopay ?? shallowRef4(null);
163
+ // src/hosted-runtime-components.ts
164
+ var PRESENTATION_PROPS = [
165
+ "theme",
166
+ "showCardBrandIcons",
167
+ "showCardFieldLabels",
168
+ "cardFieldLabels",
169
+ "cardFieldPlaceholders",
170
+ "enabledPaymentMethods",
171
+ "initialPayPalOrderId"
172
+ ];
173
+ var CORE_PROPS = [
174
+ "sessionId",
175
+ "nonce",
176
+ "createSession",
177
+ "appearance",
178
+ "strings",
179
+ "paymentMethodLayout",
180
+ "layout",
181
+ "automaticPayment",
182
+ "runtimeTimeoutMs"
183
+ ];
184
+ var RELAYED_LISTENERS = {
185
+ complete: "onComplete",
186
+ decline: "onDecline",
187
+ cancel: "onCancel",
188
+ instruments: "onInstrument",
189
+ cardFieldsReady: "onCardFieldsReady",
190
+ cardFieldsFailed: "onCardFieldsFailed"
191
+ };
192
+ function isolated(call) {
193
+ try {
194
+ call();
195
+ } catch (caught) {
196
+ console.error("[FloPay] Merchant callback failed; checkout continued.", caught);
197
+ }
3845
198
  }
3846
- function useCheckout() {
3847
- return inject3(CHECKOUT_STATE, null) ?? reactive2({ session: null, loading: false, error: null });
199
+ function passThrough(props) {
200
+ const options = {};
201
+ for (const name of PRESENTATION_PROPS) {
202
+ if (props[name] !== void 0) options[name] = props[name];
203
+ }
204
+ const hidden = [...props.hiddenPaymentMethods ?? []];
205
+ if (props.showPayPal === false && !hidden.includes("paypal")) hidden.push("paypal");
206
+ if (props.hiddenPaymentMethods !== void 0 || hidden.length > 0) {
207
+ options.hiddenPaymentMethods = hidden;
208
+ }
209
+ return Object.keys(options).length === 0 ? void 0 : options;
3848
210
  }
211
+ var listener = { type: Function, default: void 0 };
212
+ var FloPayCheckout = defineComponent2({
213
+ name: "FloPayCheckout",
214
+ props: {
215
+ publishableKey: { type: String, default: void 0 },
216
+ runtimeUrl: { type: String, default: void 0 },
217
+ sessionId: { type: String, default: void 0 },
218
+ nonce: { type: String, default: void 0 },
219
+ createSession: { type: Object, default: void 0 },
220
+ appearance: { type: Object, default: void 0 },
221
+ strings: { type: Object, default: void 0 },
222
+ paymentMethodLayout: { type: Object, default: void 0 },
223
+ layout: { type: String, default: void 0 },
224
+ automaticPayment: {
225
+ type: Object,
226
+ default: void 0
227
+ },
228
+ runtimeTimeoutMs: { type: Number, default: void 0 },
229
+ hiddenPaymentMethods: { type: Array, default: void 0 },
230
+ showPayPal: { type: Boolean, default: void 0 },
231
+ theme: {
232
+ type: [String, Object],
233
+ default: void 0
234
+ },
235
+ showCardBrandIcons: { type: Boolean, default: void 0 },
236
+ showCardFieldLabels: { type: Boolean, default: void 0 },
237
+ cardFieldLabels: { type: Object, default: void 0 },
238
+ cardFieldPlaceholders: { type: Object, default: void 0 },
239
+ enabledPaymentMethods: { type: Array, default: void 0 },
240
+ initialPayPalOrderId: { type: String, default: void 0 },
241
+ // The 1.x listeners, as props so a throwing one never blocks the others.
242
+ onComplete: listener,
243
+ onDecline: listener,
244
+ onCancel: listener,
245
+ onInstrument: listener,
246
+ onCardFieldsReady: listener,
247
+ onCardFieldsFailed: listener
248
+ },
249
+ emits: {
250
+ event: (_event) => true,
251
+ error: (_error) => true
252
+ },
253
+ setup(props, { emit }) {
254
+ const provided = inject(FLOPAY_RUNTIME_CONTEXT, {});
255
+ const onEvent = (event) => {
256
+ isolated(() => emit("event", event));
257
+ if (event.name === "error") {
258
+ isolated(() => emit("error", event.payload));
259
+ return;
260
+ }
261
+ const name = RELAYED_LISTENERS[event.name];
262
+ const relay = name ? props[name] : void 0;
263
+ if (relay) isolated(() => relay(event.payload));
264
+ };
265
+ return () => {
266
+ const core = {};
267
+ for (const name of CORE_PROPS) if (props[name] !== void 0) core[name] = props[name];
268
+ return h2(FloPayRuntimeCheckout, {
269
+ ...core,
270
+ publishableKey: props.publishableKey ?? provided.publishableKey ?? "",
271
+ runtimeUrl: props.runtimeUrl ?? provided.runtimeUrl ?? "",
272
+ extraMountOptions: passThrough(props),
273
+ onEvent,
274
+ onError: (error) => emit("error", error)
275
+ });
276
+ };
277
+ }
278
+ });
279
+ var SplitCardForm = defineComponent2({
280
+ name: "SplitCardForm",
281
+ inheritAttrs: false,
282
+ setup(_props, { attrs }) {
283
+ return () => h2(FloPayCheckout, attrs);
284
+ }
285
+ });
286
+ var FloPayCardSetup = FloPayRuntimeCardSetup;
287
+ var FloPayPaymentMethodSetup = FloPayRuntimePaymentMethodSetup;
288
+ var FloPayProvider = defineComponent2({
289
+ name: "FloPayProvider",
290
+ props: {
291
+ publishableKey: { type: String, default: void 0 },
292
+ runtimeUrl: { type: String, default: void 0 },
293
+ /** Accepted so 1.x pages keep compiling; 2.0 holds no FloPay instance. */
294
+ flopay: { type: null, default: null }
295
+ },
296
+ setup(props, { slots }) {
297
+ provide(FLOPAY_RUNTIME_CONTEXT, {
298
+ get publishableKey() {
299
+ return props.publishableKey;
300
+ },
301
+ get runtimeUrl() {
302
+ return props.runtimeUrl;
303
+ }
304
+ });
305
+ return () => slots.default?.();
306
+ }
307
+ });
308
+ var ALL_BUT_PAYPAL = ["card", "apple_pay", "google_pay", "apms"];
309
+ var ALL_BUT_CARD = ["paypal", "apple_pay", "google_pay", "apms"];
310
+ var DirectPayPalButton = defineComponent2({
311
+ name: "DirectPayPalButton",
312
+ inheritAttrs: false,
313
+ setup(_props, { attrs }) {
314
+ return () => h2(FloPayCheckout, { ...attrs, hiddenPaymentMethods: ALL_BUT_PAYPAL });
315
+ }
316
+ });
317
+ var VaultCardFields = defineComponent2({
318
+ name: "VaultCardFields",
319
+ inheritAttrs: false,
320
+ setup(_props, { attrs }) {
321
+ return () => h2(FloPayCheckout, { ...attrs, hiddenPaymentMethods: ALL_BUT_CARD });
322
+ }
323
+ });
324
+ var FloPayAutomaticPaymentButton = defineComponent2({
325
+ name: "FloPayAutomaticPaymentButton",
326
+ inheritAttrs: false,
327
+ props: {
328
+ /** `automatic` (the default) or `confirm`; both pay only on the buyer's click. */
329
+ mode: {
330
+ type: String,
331
+ default: "automatic"
332
+ },
333
+ /** Called in this page when the buyer clicks, as in 1.x. */
334
+ getSession: {
335
+ type: Function,
336
+ default: void 0
337
+ },
338
+ /** A completed saved payment, with the runtime's payload unchanged. */
339
+ onSuccess: listener,
340
+ onComplete: listener
341
+ },
342
+ setup(props, { attrs }) {
343
+ return () => h2(FloPayCheckout, {
344
+ ...attrs,
345
+ automaticPayment: {
346
+ mode: props.mode,
347
+ ...props.getSession ? { getSession: props.getSession } : {}
348
+ },
349
+ onComplete: (payload) => {
350
+ isolated(() => props.onComplete?.(payload));
351
+ isolated(() => props.onSuccess?.(payload));
352
+ }
353
+ });
354
+ }
355
+ });
3849
356
  export {
3850
357
  DirectPayPalButton,
3851
358
  FloPayAutomaticPaymentButton,
3852
359
  FloPayCardSetup,
3853
- FloPayCardSetupError,
3854
360
  FloPayCheckout,
3855
361
  FloPayPaymentMethodSetup,
3856
362
  FloPayProvider,
3857
363
  FloPayRuntimeCardSetup,
3858
- FloPayRuntimeCheckout,
364
+ FloPayCheckout as FloPayRuntimeCheckout,
3859
365
  FloPayRuntimePaymentMethodSetup,
3860
366
  SplitCardForm,
3861
367
  VaultCardFields,
3862
- dropThirdPartyOnlyError,
3863
- useCheckout,
3864
- useFloPay,
3865
- usePayPalFloPay
368
+ dropThirdPartyOnlyError
3866
369
  };