@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
@@ -1,923 +0,0 @@
1
- // src/stripe-elements.ts
2
- import { PaymentAPI } from "@flopay/js/card-setup";
3
- import {
4
- buildWalletSheetWindowMessage,
5
- classifyPaymentRejection,
6
- denyPaymentPermissionToNewFrames,
7
- detectPayPalEnvironment,
8
- FloPayError,
9
- invokeMerchantCallback as invokeMerchantCallback2,
10
- isProviderDecline,
11
- isSettledSessionIntent,
12
- isWalletSheetRefusedForWindowSize,
13
- readStripeRedirectParams as readStripeRedirectParams2,
14
- resolveSetupFutureUsage,
15
- resolveWalletModeOptions,
16
- settledSessionIntentError,
17
- shouldPreferWalletPopup,
18
- stripeExpressMethodToOptionKey,
19
- toStripeAppearance,
20
- WALLET_SHEET_WINDOW_TOO_SMALL_CODE
21
- } from "@flopay/shared";
22
- import { defineComponent as defineComponent2, h, inject, onBeforeUnmount, onMounted as onMounted2, ref } from "vue";
23
-
24
- // src/context.ts
25
- var FLOPAY_CONTEXT = /* @__PURE__ */ Symbol("flopay.vue.provider");
26
- var CHECKOUT_STATE = /* @__PURE__ */ Symbol("flopay.vue.checkout");
27
- var CHECKOUT_FORM_DEFAULTS = /* @__PURE__ */ Symbol(
28
- "flopay.vue.checkout-form-defaults"
29
- );
30
-
31
- // src/provider.ts
32
- import {
33
- FLO_INSTRUMENT_ONCE_NAMES,
34
- invokeMerchantCallback,
35
- isCardFieldsInstrumentSource,
36
- projectFloInstrument,
37
- resolveBillingApiUrl
38
- } from "@flopay/shared";
39
- import {
40
- defineComponent,
41
- getCurrentInstance,
42
- nextTick,
43
- onMounted,
44
- provide,
45
- shallowRef,
46
- watch
47
- } from "vue";
48
- var FLOPAY_TELEMETRY_BRIDGE = /* @__PURE__ */ Symbol.for("@flopay/js.telemetry.bridge.v1");
49
- function telemetryBridge(flopay) {
50
- return flopay[FLOPAY_TELEMETRY_BRIDGE];
51
- }
52
- function isPromiseLike(value) {
53
- return typeof value?.then === "function";
54
- }
55
- function createInstrumentEmitter(notify) {
56
- const emittedOnce = /* @__PURE__ */ new Set();
57
- return (source) => {
58
- const event = projectFloInstrument(source);
59
- if (!event) return;
60
- if (FLO_INSTRUMENT_ONCE_NAMES.has(event.name)) {
61
- if (emittedOnce.has(event.name)) return;
62
- emittedOnce.add(event.name);
63
- }
64
- invokeMerchantCallback(() => notify(event));
65
- };
66
- }
67
- var FloPayProvider = defineComponent({
68
- name: "FloPayProvider",
69
- props: {
70
- flopay: {
71
- type: [Object, Promise],
72
- default: null
73
- },
74
- paypalFlopay: {
75
- type: [Object, Promise],
76
- default: null
77
- },
78
- options: { type: Object, default: void 0 }
79
- },
80
- emits: { instrument: (_event) => true },
81
- setup(props, { emit, slots }) {
82
- const initial = (source) => isPromiseLike(source) ? null : source ?? null;
83
- const flopay = shallowRef(initial(props.flopay));
84
- const paypalFlopay = shallowRef(initial(props.paypalFlopay));
85
- const component = getCurrentInstance();
86
- const emitInstrument = createInstrumentEmitter((event) => {
87
- const listener = component?.vnode.props?.onInstrument;
88
- if (!listener) return emit("instrument", event);
89
- for (const handler of [listener].flat()) handler(event);
90
- });
91
- const emitTelemetryInstrument = (source) => {
92
- if (!isCardFieldsInstrumentSource(source)) emitInstrument(source);
93
- };
94
- provide(FLOPAY_CONTEXT, {
95
- flopay,
96
- paypalFlopay,
97
- billingApiUrl: () => resolveBillingApiUrl(props.options?.billingApiUrl),
98
- emitInstrument
99
- });
100
- const follow = (read, target, provider) => watch(
101
- read,
102
- (source, _previous, onCleanup) => {
103
- let active = true;
104
- onCleanup(() => {
105
- active = false;
106
- });
107
- if (!isPromiseLike(source)) {
108
- target.value = source ?? null;
109
- return;
110
- }
111
- if (provider === "paypal") target.value = null;
112
- source.then(
113
- (instance) => {
114
- if (active) target.value = instance;
115
- },
116
- () => {
117
- if (!active) return;
118
- emitInstrument({
119
- class: "technical_error",
120
- errorCode: "SDK_INITIALIZATION_FAILED",
121
- ...provider ? { provider } : {}
122
- });
123
- }
124
- );
125
- },
126
- { immediate: true }
127
- );
128
- onMounted(() => {
129
- emitInstrument({ class: "lifecycle", name: "checkout.mount" });
130
- follow(() => props.flopay, flopay);
131
- follow(() => props.paypalFlopay, paypalFlopay, "paypal");
132
- watch(
133
- flopay,
134
- (instance, _previous, onCleanup) => {
135
- if (!instance) return;
136
- emitInstrument({ class: "lifecycle", name: "sdk.initialize.ready" });
137
- const unsubscribe = telemetryBridge(instance)?.subscribe?.(emitTelemetryInstrument);
138
- onCleanup(() => unsubscribe?.());
139
- void nextTick(() => emitInstrument({ class: "lifecycle", name: "checkout.rendered" }));
140
- },
141
- { immediate: true }
142
- );
143
- watch(paypalFlopay, (instance, _previous, onCleanup) => {
144
- if (!instance || instance === flopay.value) return;
145
- const unsubscribe = telemetryBridge(instance)?.subscribe?.(emitTelemetryInstrument);
146
- onCleanup(() => unsubscribe?.());
147
- });
148
- });
149
- return () => slots.default?.();
150
- }
151
- });
152
-
153
- // src/stripe-paypal-continuation.ts
154
- import { readStripeRedirectParams, stripeRedirectReturnUrl } from "@flopay/shared";
155
- var STRIPE_PAYPAL_CONTINUATION_KEY = "flopay_vue_paypal_resume";
156
- var STRIPE_PAYPAL_ATTEMPT_PARAM = "flopay_paypal_attempt";
157
- function sessionStore() {
158
- if (typeof window === "undefined") return null;
159
- try {
160
- return window.sessionStorage;
161
- } catch {
162
- return null;
163
- }
164
- }
165
- function createStripePayPalAttempt() {
166
- const random = globalThis.crypto?.randomUUID?.();
167
- if (random) return random;
168
- return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`;
169
- }
170
- function saveStripePayPalContinuation(continuation) {
171
- const store = sessionStore();
172
- if (!store) return false;
173
- try {
174
- store.setItem(
175
- STRIPE_PAYPAL_CONTINUATION_KEY,
176
- JSON.stringify({
177
- attempt: continuation.attempt,
178
- sessionId: continuation.sessionId,
179
- ...continuation.nonce ? { nonce: continuation.nonce } : {}
180
- })
181
- );
182
- return true;
183
- } catch {
184
- return false;
185
- }
186
- }
187
- function clearStripePayPalContinuation() {
188
- try {
189
- sessionStore()?.removeItem(STRIPE_PAYPAL_CONTINUATION_KEY);
190
- } catch {
191
- }
192
- }
193
- function stripePayPalReturnUrl(attempt) {
194
- const url = new URL(stripeRedirectReturnUrl());
195
- url.searchParams.delete(STRIPE_PAYPAL_ATTEMPT_PARAM);
196
- if (attempt) url.searchParams.set(STRIPE_PAYPAL_ATTEMPT_PARAM, attempt);
197
- return url.toString();
198
- }
199
- function readStripePayPalReturnContinuation() {
200
- if (typeof window === "undefined") return null;
201
- const [paymentIntentId] = readStripeRedirectParams();
202
- if (!paymentIntentId) return null;
203
- const attempt = new URLSearchParams(window.location.search).get(STRIPE_PAYPAL_ATTEMPT_PARAM);
204
- if (!attempt) return null;
205
- try {
206
- const raw = sessionStore()?.getItem(STRIPE_PAYPAL_CONTINUATION_KEY);
207
- if (!raw) return null;
208
- const parsed = JSON.parse(raw);
209
- if (!parsed || parsed.attempt !== attempt || typeof parsed.sessionId !== "string") return null;
210
- return {
211
- attempt,
212
- sessionId: parsed.sessionId,
213
- ...typeof parsed.nonce === "string" ? { nonce: parsed.nonce } : {}
214
- };
215
- } catch {
216
- return null;
217
- }
218
- }
219
- function hasStripePayPalReturn() {
220
- return readStripePayPalReturnContinuation() !== null;
221
- }
222
- function consumeStripePayPalReturn() {
223
- clearStripePayPalContinuation();
224
- window.history.replaceState({}, "", stripePayPalReturnUrl());
225
- }
226
-
227
- // src/stripe-elements.ts
228
- var WALLET_METHODS = /* @__PURE__ */ new Set(["apple_pay", "google_pay", "link", "paypal", "amazon_pay"]);
229
- function buildExpressMethodMap(wallets) {
230
- const enabledKeys = new Set(wallets.map(stripeExpressMethodToOptionKey));
231
- return Object.fromEntries(
232
- ["applePay", "googlePay", "paypal", "link", "amazonPay", "klarna"].map((key) => [
233
- key,
234
- enabledKeys.has(key) ? "auto" : "never"
235
- ])
236
- );
237
- }
238
- var EXPRESS_CHECKOUT_CLICK_BUDGET_MS = 900;
239
- function checkoutButtonMethodFromProviderMethod(method) {
240
- if (method === "paypal") return "paypal";
241
- if (method === "apple_pay") return "apple_pay";
242
- return "google_pay";
243
- }
244
- var PAYPAL_REDIRECT_TILE_HEIGHT = 44;
245
- var stripePayPalResumeAttempts = /* @__PURE__ */ new Map();
246
- function walletClockNow() {
247
- return globalThis.performance?.now() ?? Date.now();
248
- }
249
- function stripeMethodCategory(method) {
250
- return WALLET_METHODS.has(method) ? "wallet" : "apm";
251
- }
252
- function declineReason(error) {
253
- return error.decline_code ?? error.code ?? "provider_declined";
254
- }
255
- var SETTLED_ACTION_REQUIRED_CODES = /* @__PURE__ */ new Map([
256
- ["3ds_required", "authentication_required"],
257
- ["paypal_direct_required", "paypal_direct_required"]
258
- ]);
259
- async function reportSettledIntentVerdict(response, method, sessionId, session, outcomes) {
260
- const json = response.status === 204 ? null : await response.json().catch(() => null);
261
- if (response.ok) {
262
- const authorized = session?.captureMethod === "manual" || json?.status === "authorized";
263
- const paymentId = typeof json?.paymentId === "string" ? json.paymentId : session?.paymentId;
264
- const authorizationExpiresAt = typeof json?.authorizationExpiresAt === "string" ? json.authorizationExpiresAt : session?.authorizationExpiresAt;
265
- outcomes.complete(
266
- authorized ? {
267
- status: "authorized",
268
- ...paymentId ? { paymentId } : {},
269
- sessionId: typeof json?.sessionId === "string" ? json.sessionId : sessionId,
270
- ...authorizationExpiresAt ? { authorizationExpiresAt } : {},
271
- checkoutMethod: method
272
- } : { status: "succeeded", checkoutMethod: method }
273
- );
274
- return;
275
- }
276
- const type = typeof json?.type === "string" ? json.type : void 0;
277
- const message = typeof json?.message === "string" ? json.message : void 0;
278
- const code = typeof json?.code === "string" ? json.code : void 0;
279
- const actionCode = type === void 0 ? void 0 : SETTLED_ACTION_REQUIRED_CODES.get(type);
280
- if (actionCode === void 0 && classifyPaymentRejection(response.status, json) === "payment_declined") {
281
- outcomes.decline({
282
- method,
283
- message: message ?? "Your payment was declined.",
284
- code,
285
- declineCode: typeof json?.declineCode === "string" ? json.declineCode : code,
286
- sessionId
287
- });
288
- return;
289
- }
290
- outcomes.error(
291
- new FloPayError(message ?? "Payment could not be completed. Please try again.", "api_error", {
292
- code: actionCode ?? code ?? "payment_processing_error",
293
- statusCode: response.status,
294
- sessionId
295
- })
296
- );
297
- }
298
- var StripePaymentMethods = defineComponent2({
299
- name: "FloPayStripePaymentMethods",
300
- props: {
301
- session: { type: Object, default: null },
302
- sessionId: { type: String, required: true },
303
- nonce: { type: String, default: void 0 },
304
- billingApiUrl: { type: String, required: true },
305
- publishableKey: { type: String, required: true },
306
- methods: { type: Array, required: true },
307
- /** `payment` for checkout, `setup` for payment-method setup. */
308
- intentKind: { type: String, default: "payment" },
309
- currency: { type: String, default: void 0 },
310
- amount: { type: Number, default: 0 },
311
- /**
312
- * React's `totalAmount`: the cart total due today, in minor units. When it
313
- * is given on a checkout (`intentKind: 'payment'`), the wallet row follows
314
- * React's wallet group: its Elements mode, amount and capture method come
315
- * from the shared `resolveWalletModeOptions` (setup mode for a $0 total),
316
- * and its intent is `totalAmount > 0 ? 'payment' : 'setup'`.
317
- */
318
- totalAmount: { type: Number, default: void 0 },
319
- returnUrl: { type: String, default: void 0 },
320
- /** The theme's appearance, normalized for Stripe Elements (React's setup branch does the same). */
321
- appearance: { type: Object, default: void 0 },
322
- /**
323
- * React's `stripePayPalPresentation`, which the form resolves from its
324
- * `walletPresentation` prop through the shared
325
- * `resolveStripePayPalPresentation`. With `redirect`, Stripe-routed PayPal
326
- * leaves the wallet row and renders as React's full-page "Pay with PayPal"
327
- * redirect tile, which resumes the payment when the buyer returns.
328
- */
329
- paypalPresentation: { type: String, default: "popup" },
330
- /**
331
- * The form's click gate (React's `runBeforeButtonClick`), run by the
332
- * redirect tile and by the wallet row's Express Checkout click.
333
- */
334
- runBeforeButtonClick: {
335
- type: Function,
336
- default: void 0
337
- },
338
- /**
339
- * React's `onTokenizedBody={dispatchTokenizedBody}` for the redirect tile:
340
- * the form posts `/process` with the approved payment. Without it, the
341
- * tile reports `complete` itself, as this component's wallet row does.
342
- */
343
- onTokenizedBody: {
344
- type: Function,
345
- default: void 0
346
- },
347
- /**
348
- * React's `isProcessing={isSubmitting}`: while the form is processing, the
349
- * PayPal redirect tile and the APM button are disabled and ignore clicks.
350
- */
351
- isProcessing: { type: Boolean, default: false },
352
- /**
353
- * The form's storage-free stand-in for the click-time account patch React
354
- * restores from its `localStorage` continuation (issue #410, triage AC 4:
355
- * Vue never stores it). On an authorized redirect return it is asked once
356
- * for the account, with the returned session id; what it answers goes to
357
- * `onTokenizedBody` as the attempt's `accountPatch`. A throw or no answer
358
- * continues without one, because the payment is already authorized.
359
- */
360
- recoverAccountPatch: {
361
- type: Function,
362
- default: void 0
363
- }
364
- },
365
- emits: {
366
- /** The buyer confirmed a wallet or APM and its element validated: the attempt starts. */
367
- submitting: () => true,
368
- complete: (_result) => true,
369
- decline: (_decline) => true,
370
- error: (_error) => true
371
- },
372
- setup(props, { emit }) {
373
- const walletContainer = ref(null);
374
- const apmContainer = ref(null);
375
- const processing = ref(false);
376
- const busy = () => processing.value || props.isProcessing;
377
- const cleanups = [];
378
- let apmElements = null;
379
- let stripe = null;
380
- const elementsOptions = (methods, surface) => {
381
- const setupFutureUsage = resolveSetupFutureUsage(props.session, methods, surface);
382
- const currency = (props.currency ?? props.session?.currency ?? "usd").toLowerCase();
383
- const appearance = props.appearance ? { appearance: toStripeAppearance(props.appearance) } : {};
384
- return props.intentKind === "setup" ? { mode: "setup", currency, allowedPaymentMethodTypes: methods, ...appearance } : {
385
- mode: props.session?.mode === "subscription" ? "subscription" : "payment",
386
- amount: props.amount,
387
- currency,
388
- // Stripe.js Endive (@stripe/stripe-js 10) removed the Elements
389
- // `paymentMethodTypes` option; `allowedPaymentMethodTypes` replaces it.
390
- allowedPaymentMethodTypes: methods,
391
- ...setupFutureUsage ? { setupFutureUsage } : {},
392
- ...appearance
393
- };
394
- };
395
- const walletFollowsTotal = () => props.intentKind === "payment" && typeof props.totalAmount === "number";
396
- const walletIntentKind = () => {
397
- if (!walletFollowsTotal()) return props.intentKind;
398
- return (props.totalAmount ?? 0) > 0 ? "payment" : "setup";
399
- };
400
- const walletElementsOptions = (methods) => {
401
- if (!walletFollowsTotal()) return elementsOptions(methods, "wallet");
402
- const setupFutureUsage = resolveSetupFutureUsage(props.session, methods, "wallet");
403
- const currency = (props.currency ?? props.session?.currency ?? "usd").toLowerCase();
404
- return {
405
- ...resolveWalletModeOptions(props.totalAmount, props.session?.captureMethod),
406
- currency,
407
- allowedPaymentMethodTypes: methods,
408
- ...setupFutureUsage ? { setupFutureUsage } : {},
409
- ...props.appearance ? { appearance: toStripeAppearance(props.appearance) } : {}
410
- };
411
- };
412
- let walletAttempt = null;
413
- const floPayContext = inject(FLOPAY_CONTEXT, null);
414
- const walletTelemetry = () => {
415
- const instance = floPayContext?.flopay.value;
416
- return instance ? telemetryBridge(instance) : void 0;
417
- };
418
- let walletSheetClick = null;
419
- let walletSheetAttempts = 0;
420
- const endWalletSheetClick = () => {
421
- walletSheetClick?.stopObserving();
422
- walletSheetClick = null;
423
- };
424
- const observeWalletSheetClick = (method, startedAt) => {
425
- endWalletSheetClick();
426
- walletSheetAttempts += 1;
427
- const click = {
428
- attempt: walletSheetAttempts,
429
- method,
430
- startedAt,
431
- handoffObserved: false,
432
- stopObserving: () => {
433
- }
434
- };
435
- const onBlur = () => {
436
- click.handoffObserved = true;
437
- };
438
- const onVisibilityChange = () => {
439
- if (document.visibilityState === "hidden") click.handoffObserved = true;
440
- };
441
- window.addEventListener("blur", onBlur);
442
- document.addEventListener("visibilitychange", onVisibilityChange);
443
- click.stopObserving = () => {
444
- window.removeEventListener("blur", onBlur);
445
- document.removeEventListener("visibilitychange", onVisibilityChange);
446
- };
447
- walletSheetClick = click;
448
- };
449
- cleanups.push(endWalletSheetClick);
450
- const reportWalletSheetRefusal = (click) => {
451
- const environment = detectPayPalEnvironment();
452
- walletTelemetry()?.error?.({
453
- errorCode: "PROVIDER_RUNTIME_FAILED",
454
- failureCategory: "provider_runtime",
455
- stage: "overlay_open",
456
- provider: "stripe",
457
- paymentMethodCategory: "wallet",
458
- requestCategory: "provider_sdk",
459
- terminalReason: "provider_error",
460
- attempt: click.attempt,
461
- walletType: "google_pay",
462
- ...environment,
463
- presentationMode: "popup"
464
- });
465
- const failure = new FloPayError(buildWalletSheetWindowMessage("Google Pay"), "api_error", {
466
- code: "external_payment_method_failed",
467
- param: click.method,
468
- details: {
469
- providerCode: WALLET_SHEET_WINDOW_TOO_SMALL_CODE,
470
- popupBlocked: false,
471
- ...environment,
472
- presentationMode: "popup"
473
- }
474
- });
475
- invokeMerchantCallback2(() => emit("error", failure));
476
- };
477
- const gateWalletClick = async (event) => {
478
- const clickStartedAt = walletClockNow();
479
- walletAttempt = null;
480
- endWalletSheetClick();
481
- const gate = props.runBeforeButtonClick;
482
- if (!gate) {
483
- observeWalletSheetClick(event.expressPaymentType, clickStartedAt);
484
- event.resolve();
485
- return;
486
- }
487
- let clickActive = true;
488
- const clickTimer = setTimeout(() => {
489
- clickActive = false;
490
- event.reject();
491
- }, EXPRESS_CHECKOUT_CLICK_BUDGET_MS);
492
- let beforeClick;
493
- try {
494
- beforeClick = await gate(checkoutButtonMethodFromProviderMethod(event.expressPaymentType));
495
- } catch {
496
- beforeClick = { proceed: false };
497
- } finally {
498
- clearTimeout(clickTimer);
499
- }
500
- if (!clickActive) return;
501
- if (!beforeClick.proceed) {
502
- event.reject();
503
- return;
504
- }
505
- walletAttempt = {
506
- method: event.expressPaymentType,
507
- ...beforeClick.sessionId ? { sessionId: beforeClick.sessionId } : {},
508
- ...beforeClick.nonce ? { nonce: beforeClick.nonce } : {}
509
- };
510
- observeWalletSheetClick(event.expressPaymentType, clickStartedAt);
511
- event.resolve();
512
- };
513
- const settledVerdictOutcomes = {
514
- complete: (result) => invokeMerchantCallback2(() => emit("complete", result)),
515
- decline: (decline) => invokeMerchantCallback2(() => emit("decline", decline)),
516
- error: (failure) => invokeMerchantCallback2(() => emit("error", failure))
517
- };
518
- const confirm = async (elements, method, intentKind = props.intentKind, attempt = null) => {
519
- if (!stripe || processing.value) return;
520
- processing.value = true;
521
- const api = new PaymentAPI(props.billingApiUrl, { telemetry: false });
522
- const category = stripeMethodCategory(method);
523
- const sessionId = attempt?.sessionId ?? props.sessionId;
524
- const nonce = attempt?.nonce ?? props.nonce;
525
- try {
526
- const submitted = await elements.submit();
527
- if (submitted.error) return;
528
- invokeMerchantCallback2(() => emit("submitting"));
529
- const intent = await api.createSessionIntent(sessionId, nonce ?? "", {
530
- provider: "stripe",
531
- paymentMethodCategory: category,
532
- paymentMethodType: method,
533
- paymentMethodId: null,
534
- intentKind
535
- });
536
- if (isSettledSessionIntent(intent)) {
537
- if (intentKind === "setup") throw settledSessionIntentError(sessionId);
538
- await reportSettledIntentVerdict(
539
- intent.response,
540
- method,
541
- sessionId,
542
- props.session,
543
- settledVerdictOutcomes
544
- );
545
- return;
546
- }
547
- const clientSecret = intent.clientSecret ?? "";
548
- const returnUrl = props.returnUrl ?? window.location.href;
549
- const { error } = intentKind === "setup" ? await stripe.confirmSetup({
550
- elements,
551
- clientSecret,
552
- confirmParams: { return_url: returnUrl },
553
- redirect: "if_required"
554
- }) : await stripe.confirmPayment({
555
- elements,
556
- clientSecret,
557
- confirmParams: { return_url: returnUrl },
558
- redirect: "if_required"
559
- });
560
- if (error) {
561
- if (intentKind === "payment") {
562
- void api.reportSessionIntentDecline(sessionId, nonce ?? "", {
563
- provider: "stripe",
564
- paymentMethodCategory: category,
565
- paymentMethodType: method,
566
- providerDeclineReason: declineReason(error),
567
- providerIntentId: intent.providerObjectId
568
- }).catch(() => {
569
- });
570
- }
571
- const decline = {
572
- method,
573
- message: error.message ?? "Your payment was declined.",
574
- code: error.code,
575
- declineCode: error.decline_code ?? error.code,
576
- sessionId
577
- };
578
- invokeMerchantCallback2(() => emit("decline", decline));
579
- return;
580
- }
581
- const result = {
582
- status: "succeeded",
583
- paymentIntentId: intent.providerObjectId,
584
- checkoutMethod: method
585
- };
586
- invokeMerchantCallback2(() => emit("complete", result));
587
- } catch (error) {
588
- const failure = error instanceof FloPayError ? error : new FloPayError(
589
- error instanceof Error ? error.message : "Payment failed.",
590
- "api_error"
591
- );
592
- invokeMerchantCallback2(() => emit("error", failure));
593
- } finally {
594
- processing.value = false;
595
- }
596
- };
597
- const paypalRedirect = () => props.paypalPresentation === "redirect" && props.intentKind === "payment" && props.methods.includes("paypal");
598
- let active = true;
599
- const emitPayPalDecline = (message, sessionId, error) => {
600
- const decline = {
601
- method: "paypal",
602
- message,
603
- ...error ? { code: error.code, declineCode: error.decline_code ?? error.code } : {},
604
- sessionId
605
- };
606
- invokeMerchantCallback2(() => emit("decline", decline));
607
- };
608
- const emitPayPalFailure = (message, code) => {
609
- const failure = new FloPayError(message, "api_error", code ? { code } : void 0);
610
- invokeMerchantCallback2(() => emit("error", failure));
611
- };
612
- const handOffPayPal = (body, overrides) => {
613
- if (props.onTokenizedBody) {
614
- props.onTokenizedBody(body, overrides);
615
- return;
616
- }
617
- const result = {
618
- status: "succeeded",
619
- paymentIntentId: body.threeDSecureActionResultTokenId,
620
- checkoutMethod: "paypal"
621
- };
622
- invokeMerchantCallback2(() => emit("complete", result));
623
- };
624
- const redirectToPayPal = async () => {
625
- if (!stripe || busy()) return;
626
- processing.value = true;
627
- const api = new PaymentAPI(props.billingApiUrl, { telemetry: false });
628
- let sessionId = props.sessionId;
629
- try {
630
- const beforeClick = props.runBeforeButtonClick ? await props.runBeforeButtonClick("paypal") : { proceed: true };
631
- if (!beforeClick.proceed) return;
632
- sessionId = beforeClick.sessionId ?? props.sessionId;
633
- const nonce = beforeClick.nonce ?? props.nonce;
634
- const createPaymentMethod = stripe.createPaymentMethod;
635
- const { error: pmError, paymentMethod } = await createPaymentMethod.call(stripe, {
636
- type: "paypal"
637
- });
638
- if (pmError) {
639
- emitPayPalFailure(
640
- pmError.message ?? "PayPal could not be started.",
641
- "stripe_paypal_create_payment_method_failed"
642
- );
643
- return;
644
- }
645
- const intent = await api.createSessionIntent(sessionId, nonce ?? "", {
646
- provider: "stripe",
647
- paymentMethodCategory: "wallet",
648
- paymentMethodType: "paypal",
649
- paymentMethodId: paymentMethod?.id ?? null,
650
- intentKind: "payment"
651
- });
652
- if (isSettledSessionIntent(intent)) {
653
- await reportSettledIntentVerdict(
654
- intent.response,
655
- "paypal",
656
- sessionId,
657
- props.session,
658
- settledVerdictOutcomes
659
- );
660
- return;
661
- }
662
- if (intent.provider !== "stripe") {
663
- throw new Error("Invalid provider returned for PayPal intent");
664
- }
665
- const clientSecret = intent.clientSecret ?? "";
666
- const attempt = createStripePayPalAttempt();
667
- const continuationSaved = saveStripePayPalContinuation({ attempt, sessionId, nonce });
668
- if (!continuationSaved) {
669
- throw new Error("Unable to save PayPal checkout progress. Please try again.");
670
- }
671
- const { error, paymentIntent } = await stripe.confirmPayment({
672
- clientSecret,
673
- confirmParams: {
674
- return_url: stripePayPalReturnUrl(attempt),
675
- ...paymentMethod?.id ? { payment_method: paymentMethod.id } : {}
676
- },
677
- redirect: "if_required"
678
- });
679
- clearStripePayPalContinuation();
680
- if (error) {
681
- if (isProviderDecline(error)) {
682
- void api.reportSessionIntentDecline(sessionId, nonce ?? "", {
683
- provider: "stripe",
684
- paymentMethodCategory: "wallet",
685
- paymentMethodType: "paypal",
686
- providerDeclineReason: error.code ?? "provider_declined",
687
- providerIntentId: intent.providerObjectId
688
- }).catch(() => {
689
- });
690
- emitPayPalDecline(error.message ?? "Your payment was declined.", sessionId, error);
691
- return;
692
- }
693
- emitPayPalFailure(
694
- error.message ?? "PayPal payment failed.",
695
- "stripe_paypal_confirm_failed"
696
- );
697
- return;
698
- }
699
- const paymentMethodId = typeof paymentIntent?.payment_method === "string" ? paymentIntent.payment_method : paymentIntent?.payment_method?.id;
700
- handOffPayPal(
701
- {
702
- id: paymentMethodId ?? paymentIntent?.id,
703
- type: "card",
704
- threeDSecureActionResultTokenId: paymentIntent?.id,
705
- isPaypal: true
706
- },
707
- {
708
- accountPatch: beforeClick.accountPatch,
709
- paymentMethodCategory: "paypal",
710
- presentationMode: "redirect",
711
- sessionId,
712
- nonce
713
- }
714
- );
715
- } catch (error) {
716
- emitPayPalFailure(
717
- error instanceof Error ? error.message : "PayPal payment failed.",
718
- "stripe_paypal_failed"
719
- );
720
- } finally {
721
- processing.value = false;
722
- }
723
- };
724
- const recoverReturnAccount = async (sessionId) => {
725
- const recover = props.recoverAccountPatch;
726
- if (!recover) return void 0;
727
- try {
728
- return await recover(sessionId) ?? void 0;
729
- } catch {
730
- return void 0;
731
- }
732
- };
733
- const continueAuthorizedReturn = async (paymentIntent, continuation) => {
734
- const paymentMethodId = typeof paymentIntent.payment_method === "string" ? paymentIntent.payment_method : paymentIntent.payment_method?.id;
735
- const accountPatch = await recoverReturnAccount(continuation.sessionId);
736
- if (!active) return;
737
- handOffPayPal(
738
- {
739
- id: paymentMethodId ?? paymentIntent.id,
740
- type: "card",
741
- threeDSecureActionResultTokenId: paymentIntent.id,
742
- isPaypal: true
743
- },
744
- {
745
- ...accountPatch ? { accountPatch } : {},
746
- sessionId: continuation.sessionId,
747
- nonce: continuation.nonce,
748
- presentationMode: "redirect"
749
- }
750
- );
751
- };
752
- const resumeStripePayPal = async (provider) => {
753
- const [paymentIntentId, clientSecret, redirectStatus] = readStripeRedirectParams2();
754
- if (!paymentIntentId || !clientSecret) return;
755
- const continuation = readStripePayPalReturnContinuation();
756
- if (!continuation) return;
757
- const sessionId = continuation.sessionId;
758
- const retrievalKey = continuation.attempt;
759
- let retrieval = stripePayPalResumeAttempts.get(retrievalKey);
760
- if (!retrieval) {
761
- retrieval = redirectStatus === "failed" ? Promise.resolve(null) : Promise.resolve().then(() => provider.retrievePaymentIntent(clientSecret));
762
- stripePayPalResumeAttempts.set(retrievalKey, retrieval);
763
- }
764
- processing.value = true;
765
- try {
766
- const result = await retrieval;
767
- if (!active) return;
768
- if (result?.error) {
769
- stripePayPalResumeAttempts.delete(retrievalKey);
770
- emitPayPalFailure(
771
- result.error.message ?? "Failed to retrieve PayPal payment status.",
772
- "REDIRECT_RESUME_FAILED"
773
- );
774
- return;
775
- }
776
- consumeStripePayPalReturn();
777
- stripePayPalResumeAttempts.delete(retrievalKey);
778
- if (redirectStatus === "failed") {
779
- emitPayPalDecline("PayPal payment was declined. Please try again.", sessionId);
780
- return;
781
- }
782
- const paymentIntent = result?.paymentIntent;
783
- if (paymentIntent && paymentIntent.id !== paymentIntentId) {
784
- emitPayPalFailure(
785
- "Failed to match the returned PayPal payment.",
786
- "REDIRECT_RESUME_FAILED"
787
- );
788
- return;
789
- }
790
- if (paymentIntent && (paymentIntent.status === "requires_capture" || paymentIntent.status === "succeeded")) {
791
- await continueAuthorizedReturn(paymentIntent, continuation);
792
- return;
793
- }
794
- emitPayPalDecline("PayPal payment was not completed. Please try again.", sessionId);
795
- } catch (error) {
796
- if (!active) return;
797
- stripePayPalResumeAttempts.delete(retrievalKey);
798
- emitPayPalFailure(
799
- error instanceof Error ? error.message : "Failed to complete PayPal payment.",
800
- "REDIRECT_RESUME_FAILED"
801
- );
802
- } finally {
803
- if (active) processing.value = false;
804
- }
805
- };
806
- onMounted2(async () => {
807
- const wallets = props.methods.filter(
808
- (method) => WALLET_METHODS.has(method) && !(method === "paypal" && paypalRedirect())
809
- );
810
- const apms = props.methods.filter((method) => !WALLET_METHODS.has(method));
811
- try {
812
- const { loadStripe } = await import("@stripe/stripe-js");
813
- stripe = await loadStripe(props.publishableKey);
814
- if (!stripe) throw new Error("Stripe.js did not initialize.");
815
- if (paypalRedirect()) void resumeStripePayPal(stripe);
816
- if (wallets.length > 0 && walletContainer.value) {
817
- if (shouldPreferWalletPopup()) cleanups.push(denyPaymentPermissionToNewFrames(document));
818
- const elements = stripe.elements(walletElementsOptions(wallets));
819
- const express = elements.create("expressCheckout", {
820
- paymentMethods: buildExpressMethodMap(wallets)
821
- });
822
- express.on("click", (event) => gateWalletClick(event));
823
- express.on("confirm", (event) => {
824
- const attempt = walletAttempt;
825
- walletAttempt = null;
826
- endWalletSheetClick();
827
- void confirm(elements, event.expressPaymentType, walletIntentKind(), attempt);
828
- });
829
- express.on("cancel", () => {
830
- walletAttempt = null;
831
- const click = walletSheetClick;
832
- endWalletSheetClick();
833
- if (click && isWalletSheetRefusedForWindowSize({
834
- method: click.method,
835
- elapsedMs: walletClockNow() - click.startedAt,
836
- handoffObserved: click.handoffObserved
837
- })) {
838
- reportWalletSheetRefusal(click);
839
- }
840
- });
841
- express.mount(walletContainer.value);
842
- cleanups.push(() => express.destroy());
843
- }
844
- if (apms.length > 0 && apmContainer.value) {
845
- apmElements = stripe.elements(elementsOptions(apms, "inline_apm"));
846
- const payment = apmElements.create("payment", { layout: "accordion" });
847
- payment.mount(apmContainer.value);
848
- cleanups.push(() => payment.destroy());
849
- }
850
- } catch (error) {
851
- const failure = new FloPayError(
852
- error instanceof Error ? error.message : "Payment methods failed to load.",
853
- "api_error",
854
- { code: "PROVIDER_LOAD_FAILED" }
855
- );
856
- invokeMerchantCallback2(() => emit("error", failure));
857
- }
858
- });
859
- onBeforeUnmount(() => {
860
- active = false;
861
- for (const cleanup of cleanups.splice(0)) cleanup();
862
- });
863
- return () => h("div", { "data-testid": "flopay-stripe-methods" }, [
864
- // React renders the Stripe PayPal group above the wallet row.
865
- paypalRedirect() ? h(
866
- "div",
867
- {
868
- role: "group",
869
- "aria-label": "PayPal payment method",
870
- "data-testid": "flopay-paypal-focus-target",
871
- style: { borderRadius: "8px" }
872
- },
873
- [
874
- h(
875
- "button",
876
- {
877
- type: "button",
878
- "data-testid": "flopay-stripe-paypal-redirect",
879
- disabled: busy(),
880
- onClick: () => void redirectToPayPal(),
881
- style: {
882
- width: "100%",
883
- minHeight: `${PAYPAL_REDIRECT_TILE_HEIGHT}px`,
884
- border: "1px solid #d1d5db",
885
- borderRadius: "8px",
886
- background: "#ffc439",
887
- color: "#111827",
888
- cursor: busy() ? "not-allowed" : "pointer",
889
- fontSize: "1rem",
890
- fontWeight: 700
891
- }
892
- },
893
- "Pay with PayPal"
894
- )
895
- ]
896
- ) : null,
897
- h("div", { ref: walletContainer, "data-testid": "flopay-express-checkout" }),
898
- h("div", { ref: apmContainer, "data-testid": "flopay-payment-element" }),
899
- props.methods.some((method) => !WALLET_METHODS.has(method)) ? h(
900
- "button",
901
- {
902
- type: "button",
903
- disabled: busy(),
904
- onClick: () => {
905
- if (props.isProcessing) return;
906
- const method = props.methods.find((candidate) => !WALLET_METHODS.has(candidate));
907
- if (apmElements && method) void confirm(apmElements, method);
908
- }
909
- },
910
- processing.value ? "Processing\u2026" : "Continue"
911
- ) : null
912
- ]);
913
- }
914
- });
915
-
916
- export {
917
- FLOPAY_CONTEXT,
918
- CHECKOUT_STATE,
919
- CHECKOUT_FORM_DEFAULTS,
920
- FloPayProvider,
921
- hasStripePayPalReturn,
922
- StripePaymentMethods
923
- };