@funnelsgrove/payments 0.68.0 → 0.70.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 (35) hide show
  1. package/README.md +31 -14
  2. package/dist/components/CheckoutErrorOverlay.d.ts +37 -0
  3. package/dist/components/CheckoutErrorOverlay.js +67 -0
  4. package/dist/generated/package-version.d.ts +1 -1
  5. package/dist/generated/package-version.js +1 -1
  6. package/dist/index.d.ts +1 -0
  7. package/dist/providers/stripe/components/SharedStripeCheckoutV2Dialog.d.ts +13 -4
  8. package/dist/providers/stripe/components/SharedStripeCheckoutV2Dialog.js +93 -88
  9. package/dist/providers/stripe/components/StripeCheckoutDialog.d.ts +31 -0
  10. package/dist/providers/stripe/components/StripeCheckoutDialog.js +179 -0
  11. package/dist/providers/stripe/components/StripeWalletFirstCheckout.d.ts +81 -7
  12. package/dist/providers/stripe/components/StripeWalletFirstCheckout.js +204 -56
  13. package/dist/providers/stripe/components/StripeWalletFirstCheckout.options.d.ts +10 -2
  14. package/dist/providers/stripe/components/StripeWalletFirstCheckout.options.js +4 -6
  15. package/dist/providers/stripe/components/StripeWalletFirstCheckout.styles.d.ts +1 -1
  16. package/dist/providers/stripe/components/StripeWalletFirstCheckout.styles.js +11 -1
  17. package/dist/providers/stripe/components/WalletButton.d.ts +3 -1
  18. package/dist/providers/stripe/components/WalletButton.js +3 -3
  19. package/dist/providers/stripe/components/checkout-v2.content.d.ts +3 -0
  20. package/dist/providers/stripe/components/index.d.ts +1 -0
  21. package/dist/providers/stripe/components/index.js +1 -0
  22. package/dist/providers/stripe/components/useCheckoutEmail.internal.d.ts +3 -1
  23. package/dist/providers/stripe/components/useCheckoutEmail.internal.js +8 -3
  24. package/dist/providers/stripe/hooks/checkoutPageAttention.d.ts +3 -0
  25. package/dist/providers/stripe/hooks/checkoutPageAttention.js +54 -0
  26. package/dist/providers/stripe/hooks/checkoutPreparationBackoff.d.ts +1 -0
  27. package/dist/providers/stripe/hooks/checkoutPreparationBackoff.js +5 -7
  28. package/dist/providers/stripe/hooks/useStripeSubscriptionCheckoutSession.js +39 -2
  29. package/package.json +1 -1
  30. package/dist/providers/stripe/components/SharedCheckoutPaymentMethods.internal.d.ts +0 -18
  31. package/dist/providers/stripe/components/SharedCheckoutPaymentMethods.internal.js +0 -15
  32. package/dist/providers/stripe/components/SharedStripeCheckoutV2Form.internal.d.ts +0 -7
  33. package/dist/providers/stripe/components/SharedStripeCheckoutV2Form.internal.js +0 -328
  34. package/dist/providers/stripe/components/SharedStripeCheckoutV2Summary.internal.d.ts +0 -7
  35. package/dist/providers/stripe/components/SharedStripeCheckoutV2Summary.internal.js +0 -19
@@ -12,6 +12,7 @@ export * from './StripePlanSelector.js';
12
12
  export * from './StripeSubscriptionWalletSurface.js';
13
13
  export * from './StripeWalletFirstCheckout.js';
14
14
  export * from './StripeCheckoutSheet.js';
15
+ export * from './StripeCheckoutDialog.js';
15
16
  export * from './WalletButton.js';
16
17
  export * from './WalletSubscriptionCheckoutSlot.js';
17
18
  export * from './walletPlatform.js';
@@ -12,6 +12,7 @@ export * from './StripePlanSelector.js';
12
12
  export * from './StripeSubscriptionWalletSurface.js';
13
13
  export * from './StripeWalletFirstCheckout.js';
14
14
  export * from './StripeCheckoutSheet.js';
15
+ export * from './StripeCheckoutDialog.js';
15
16
  export * from './WalletButton.js';
16
17
  export * from './WalletSubscriptionCheckoutSlot.js';
17
18
  export * from './walletPlatform.js';
@@ -3,8 +3,10 @@ type EmailInput = Pick<SharedStripeCheckoutV2DialogProps, 'customerEmail' | 'onC
3
3
  allowEmailEditing: boolean;
4
4
  customerEmailInvalidMessage: string;
5
5
  onError: (message: string) => void;
6
+ /** The Checkout Session the email belongs to; a replaced session starts from its own email. */
7
+ sessionKey?: string | null;
6
8
  };
7
- export declare function useCheckoutEmail({ customerEmail, allowEmailEditing, customerEmailInvalidMessage, onCustomerEmailCommit, onCustomerEmailChange, onError }: EmailInput): {
9
+ export declare function useCheckoutEmail({ customerEmail, allowEmailEditing, customerEmailInvalidMessage, onCustomerEmailCommit, onCustomerEmailChange, onError, sessionKey }: EmailInput): {
8
10
  initialCustomerEmail: string;
9
11
  resolvedCustomerEmail: string;
10
12
  customerEmailEditable: boolean;
@@ -1,12 +1,17 @@
1
1
  'use client';
2
2
  import { useRef, useState } from 'react';
3
3
  import { isValidCheckoutEmail as isValidEmail, normalizeCheckoutEmailResult } from '../../../services/checkoutEmail.js';
4
- export function useCheckoutEmail({ customerEmail, allowEmailEditing, customerEmailInvalidMessage, onCustomerEmailCommit, onCustomerEmailChange, onError }) {
4
+ export function useCheckoutEmail({ customerEmail, allowEmailEditing, customerEmailInvalidMessage, onCustomerEmailCommit, onCustomerEmailChange, onError, sessionKey = null }) {
5
5
  const initialCustomerEmail = (customerEmail === null || customerEmail === void 0 ? void 0 : customerEmail.trim()) || '';
6
- const sessionCustomerEmail = useRef(initialCustomerEmail).current;
7
- const emailSessionChanged = sessionCustomerEmail !== initialCustomerEmail;
6
+ const [session, setSession] = useState({ key: sessionKey, email: initialCustomerEmail });
8
7
  const [emailDraft, setEmailDraft] = useState(initialCustomerEmail);
9
8
  const [rejectedEmail, setRejectedEmail] = useState(null);
9
+ if (session.key !== sessionKey) {
10
+ setSession({ key: sessionKey, email: initialCustomerEmail });
11
+ setEmailDraft(initialCustomerEmail);
12
+ setRejectedEmail(null);
13
+ }
14
+ const emailSessionChanged = session.key === sessionKey && session.email !== initialCustomerEmail;
10
15
  const customerEmailEditable = allowEmailEditing || !isValidEmail(initialCustomerEmail) || rejectedEmail !== null;
11
16
  const resolvedCustomerEmail = customerEmailEditable
12
17
  ? emailDraft.trim()
@@ -0,0 +1,3 @@
1
+ export declare const isCheckoutPageAttended: () => boolean;
2
+ export declare function startCheckoutPageAttention(): void;
3
+ export declare const waitForCheckoutPageAttention: () => Promise<void>;
@@ -0,0 +1,54 @@
1
+ // FUN-479: automatic checkout preparation runs only while someone is at the page.
2
+ // A forgotten paywall tab otherwise creates a live Checkout Session every time its
3
+ // offer changes, and a request cut off by device sleep looks like a shown failure.
4
+ const IDLE_AFTER_MS = 15 * 60000;
5
+ const ACTIVITY_EVENTS = ['pointerdown', 'pointermove', 'keydown', 'touchstart', 'wheel', 'scroll', 'focus'];
6
+ let lastActivityAtMs = Date.now();
7
+ let listening = false;
8
+ const waiters = new Set();
9
+ const canListen = () => typeof window !== 'undefined'
10
+ && typeof window.addEventListener === 'function'
11
+ && typeof (document === null || document === void 0 ? void 0 : document.addEventListener) === 'function';
12
+ export const isCheckoutPageAttended = () => {
13
+ if (!canListen()) {
14
+ return true;
15
+ }
16
+ startCheckoutPageAttention();
17
+ return document.visibilityState !== 'hidden'
18
+ && navigator.onLine !== false
19
+ && Date.now() - lastActivityAtMs < IDLE_AFTER_MS;
20
+ };
21
+ const releaseWaiters = () => {
22
+ if (waiters.size === 0 || !isCheckoutPageAttended()) {
23
+ return;
24
+ }
25
+ const pending = [...waiters];
26
+ waiters.clear();
27
+ pending.forEach((resolve) => resolve());
28
+ };
29
+ const recordActivity = () => {
30
+ lastActivityAtMs = Date.now();
31
+ releaseWaiters();
32
+ };
33
+ // Started when the first checkout hook mounts, so the idle clock starts with the paywall.
34
+ export function startCheckoutPageAttention() {
35
+ if (listening || !canListen()) {
36
+ return;
37
+ }
38
+ listening = true;
39
+ lastActivityAtMs = Date.now();
40
+ for (const type of ACTIVITY_EVENTS) {
41
+ window.addEventListener(type, recordActivity, { capture: true, passive: true });
42
+ }
43
+ document.addEventListener('visibilitychange', () => {
44
+ if (document.visibilityState === 'visible') {
45
+ recordActivity();
46
+ }
47
+ });
48
+ window.addEventListener('online', releaseWaiters);
49
+ }
50
+ export const waitForCheckoutPageAttention = () => isCheckoutPageAttended()
51
+ ? Promise.resolve()
52
+ : new Promise((resolve) => {
53
+ waiters.add(resolve);
54
+ });
@@ -3,6 +3,7 @@ export type CheckoutPreparationFailure = {
3
3
  count: number;
4
4
  until: number;
5
5
  };
6
+ export declare const isAutomaticCheckoutPreparation: (source?: string) => boolean;
6
7
  export declare const recordCheckoutPreparationFailure: (previous: CheckoutPreparationFailure | null, failure: {
7
8
  intentKey: string;
8
9
  retryAfterMs?: number | null;
@@ -2,16 +2,14 @@ const BASE_WINDOW_MS = 2000;
2
2
  const MAX_WINDOW_MS = 30000;
3
3
  const MAX_RETRY_AFTER_MS = 60000;
4
4
  const AUTOMATIC_SOURCES = new Set(['checkout_render', 'wallet_render']);
5
+ export const isAutomaticCheckoutPreparation = (source) => AUTOMATIC_SOURCES.has(source !== null && source !== void 0 ? source : '');
5
6
  export const recordCheckoutPreparationFailure = (previous, failure, now) => {
6
7
  var _a;
7
8
  const count = (previous === null || previous === void 0 ? void 0 : previous.intentKey) === failure.intentKey ? previous.count + 1 : 1;
8
9
  const windowMs = Math.max(Math.min((_a = failure.retryAfterMs) !== null && _a !== void 0 ? _a : 0, MAX_RETRY_AFTER_MS), Math.min(BASE_WINDOW_MS * 2 ** (count - 1), MAX_WINDOW_MS));
9
10
  return { intentKey: failure.intentKey, count, until: now + windowMs };
10
11
  };
11
- export const blocksCheckoutPreparation = (failure, request, now) => {
12
- var _a;
13
- return !request.forceNew
14
- && AUTOMATIC_SOURCES.has((_a = request.source) !== null && _a !== void 0 ? _a : '')
15
- && (failure === null || failure === void 0 ? void 0 : failure.intentKey) === request.intentKey
16
- && now < failure.until;
17
- };
12
+ export const blocksCheckoutPreparation = (failure, request, now) => !request.forceNew
13
+ && isAutomaticCheckoutPreparation(request.source)
14
+ && (failure === null || failure === void 0 ? void 0 : failure.intentKey) === request.intentKey
15
+ && now < failure.until;
@@ -19,7 +19,8 @@ import { toAnalyticsPaymentMethod } from '../../../services/paymentMethodAnalyti
19
19
  import { resolveCheckoutObservabilityAnalyticsContext, trackCheckoutFailureShown, } from '../../../services/checkoutObservability.service.js';
20
20
  import { resolveStripeCheckoutAttempt, } from './checkoutAttempt.js';
21
21
  import { isStripeCheckoutIdentityReady } from './checkoutIdentity.js';
22
- import { blocksCheckoutPreparation, recordCheckoutPreparationFailure, } from './checkoutPreparationBackoff.js';
22
+ import { blocksCheckoutPreparation, isAutomaticCheckoutPreparation, recordCheckoutPreparationFailure, } from './checkoutPreparationBackoff.js';
23
+ import { isCheckoutPageAttended, startCheckoutPageAttention, waitForCheckoutPageAttention, } from './checkoutPageAttention.js';
23
24
  export { isStripeCheckoutIdentityReady as isStripeSubscriptionCheckoutIdentityReady, } from './checkoutIdentity.js';
24
25
  export function resolveStripeSubscriptionCheckoutPreparationOptions(source, options = {}) {
25
26
  var _a, _b;
@@ -140,6 +141,17 @@ export function useStripeSubscriptionCheckoutSession({ checkoutMode: nextCheckou
140
141
  const activePlanKey = clientSecretIntentKey === intentKey ? clientSecretPlanKey : null;
141
142
  const stripePromise = useMemo(() => getStripePromise(checkoutMode, runtimeStripePublishableKey !== null && runtimeStripePublishableKey !== void 0 ? runtimeStripePublishableKey : stripePublishableKey, stripeLocale), [checkoutMode, runtimeStripePublishableKey, stripePublishableKey, stripeLocale]);
142
143
  const previousIntentKeyRef = useRef(intentKey);
144
+ const latestIntentKeyRef = useRef(intentKey);
145
+ latestIntentKeyRef.current = intentKey;
146
+ const unattendedFailureIntentKeyRef = useRef(null);
147
+ const mountedRef = useRef(true);
148
+ useEffect(() => {
149
+ mountedRef.current = true;
150
+ startCheckoutPageAttention();
151
+ return () => {
152
+ mountedRef.current = false;
153
+ };
154
+ }, []);
143
155
  const analyticsMetadataRef = useRef(analyticsMetadata);
144
156
  useEffect(() => {
145
157
  analyticsMetadataRef.current = analyticsMetadata;
@@ -295,6 +307,13 @@ export function useStripeSubscriptionCheckoutSession({ checkoutMode: nextCheckou
295
307
  metadata: analyticsMetadataRef.current,
296
308
  runtimeConfig,
297
309
  });
310
+ // Nobody saw a background preparation fail once the buyer left or the device
311
+ // slept: show and report nothing; prepareCheckout retries when the buyer returns.
312
+ if (isAutomaticCheckoutPreparation(options.checkoutStartSource)
313
+ && !isCheckoutPageAttended()) {
314
+ unattendedFailureIntentKeyRef.current = requestKey;
315
+ return null;
316
+ }
298
317
  if (observabilityAnalytics
299
318
  && shouldReportStripeCheckoutFailureShown(message)) {
300
319
  trackCheckoutFailureShown({
@@ -370,7 +389,25 @@ export function useStripeSubscriptionCheckoutSession({ checkoutMode: nextCheckou
370
389
  setSourceLoading(source, true);
371
390
  setError(null);
372
391
  try {
373
- return await createCheckoutSubscription(preparationOptions);
392
+ const automatic = isAutomaticCheckoutPreparation(preparationOptions.checkoutStartSource);
393
+ const resumeWhenAttended = async () => {
394
+ await waitForCheckoutPageAttention();
395
+ return mountedRef.current && latestIntentKeyRef.current === intentKey;
396
+ };
397
+ if (automatic && !isCheckoutPageAttended() && !(await resumeWhenAttended())) {
398
+ return null;
399
+ }
400
+ const clientSecret = await createCheckoutSubscription(preparationOptions);
401
+ if (clientSecret || unattendedFailureIntentKeyRef.current !== intentKey) {
402
+ return clientSecret;
403
+ }
404
+ unattendedFailureIntentKeyRef.current = null;
405
+ if (!(await resumeWhenAttended())) {
406
+ return null;
407
+ }
408
+ // Inside the attempt retry window this reuses the idempotency key, so a session
409
+ // Stripe created before the failure is returned instead of a new one.
410
+ return await createCheckoutSubscription(Object.assign(Object.assign({}, preparationOptions), { forceNew: false }));
374
411
  }
375
412
  finally {
376
413
  setSourceLoading(source, false);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funnelsgrove/payments",
3
- "version": "0.68.0",
3
+ "version": "0.70.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/The-Solid-Grove/funnelsgrove.git",
@@ -1,18 +0,0 @@
1
- import type { PlatformWalletPaymentMethod } from './walletPlatform.js';
2
- type Props = {
3
- showWalletMethod: boolean;
4
- showPayPalMethod: boolean;
5
- selectedMethod: 'wallet' | 'card';
6
- disabled: boolean;
7
- /** `accordion`: only the wallet option; Stripe's accordion lists cards and other methods below it. */
8
- layout?: 'tabs' | 'accordion';
9
- paymentMethodLabel: string;
10
- cardLabel: string;
11
- walletAriaLabel: string;
12
- walletPaymentMethods: readonly PlatformWalletPaymentMethod[];
13
- cardBrandLabels: readonly string[];
14
- onWalletSelect: () => void;
15
- onCardSelect: () => void;
16
- };
17
- export declare function SharedCheckoutPaymentMethods({ showWalletMethod, showPayPalMethod, selectedMethod, disabled, layout, paymentMethodLabel, cardLabel, walletAriaLabel, walletPaymentMethods, cardBrandLabels, onWalletSelect, onCardSelect }: Props): import("react/jsx-runtime").JSX.Element;
18
- export {};
@@ -1,15 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { PaymentBrandMark } from './CheckoutBrandAssets.js';
3
- export function SharedCheckoutPaymentMethods({ showWalletMethod, showPayPalMethod, selectedMethod, disabled, layout = 'tabs', paymentMethodLabel, cardLabel, walletAriaLabel, walletPaymentMethods, cardBrandLabels, onWalletSelect, onCardSelect }) {
4
- return (_jsxs("div", { className: 'shared-checkout-v2-methods', "data-paypal": showPayPalMethod ? 'true' : undefined, "data-layout": layout, role: layout === 'accordion' ? 'radiogroup' : 'tablist', "aria-label": paymentMethodLabel, children: [showWalletMethod ? _jsxs("button", { type: 'button', disabled: disabled, className: [
5
- 'shared-checkout-v2-method',
6
- selectedMethod === 'wallet' ? 'is-selected' : '',
7
- ]
8
- .filter(Boolean)
9
- .join(' '), onClick: onWalletSelect, role: layout === 'accordion' ? 'radio' : 'tab', "aria-selected": layout === 'accordion' ? undefined : selectedMethod === 'wallet', "aria-checked": layout === 'accordion' ? selectedMethod === 'wallet' : undefined, children: [layout === 'accordion' ? _jsx("span", { className: 'shared-checkout-v2-method-radio', "aria-hidden": 'true' }) : null, _jsxs("span", { className: 'shared-checkout-v2-tab-wallets', "aria-hidden": 'true', children: [showPayPalMethod ? _jsx(PaymentBrandMark, { label: 'PayPal', className: 'shared-checkout-v2-tab-wallet' }) : null, walletPaymentMethods.includes('applePay') ? (_jsx(PaymentBrandMark, { label: 'Apple Pay', className: 'shared-checkout-v2-tab-wallet' })) : null, walletPaymentMethods.includes('googlePay') ? (_jsx(PaymentBrandMark, { label: 'Google Pay', className: 'shared-checkout-v2-tab-wallet' })) : null] }), _jsx("span", { className: 'shared-checkout-v2-sr-only', children: walletAriaLabel })] }) : null, layout === 'accordion' ? null : _jsxs("button", { type: 'button', className: [
10
- 'shared-checkout-v2-method',
11
- selectedMethod === 'card' ? 'is-selected' : '',
12
- ]
13
- .filter(Boolean)
14
- .join(' '), disabled: disabled, onClick: onCardSelect, role: 'tab', "aria-selected": selectedMethod === 'card', children: [_jsx("strong", { children: cardLabel }), _jsx("span", { className: 'shared-checkout-v2-tab-brands', "aria-hidden": 'true', children: cardBrandLabels.slice(0, 4).map((label) => (_jsx(PaymentBrandMark, { label: label, className: 'shared-checkout-v2-tab-brand' }, label))) })] })] }));
15
- }
@@ -1,7 +0,0 @@
1
- import type { SharedStripeCheckoutV2DialogProps } from './SharedStripeCheckoutV2Dialog.js';
2
- export declare const getFixedSupportedBillingCountry: (supportedCountries: readonly string[]) => string | null;
3
- type SharedStripeCheckoutV2FormProps = Omit<SharedStripeCheckoutV2DialogProps, 'stripePromise' | 'onClose'> & {
4
- onClose: () => void;
5
- };
6
- export declare function SharedStripeCheckoutV2CheckoutSessionForm({ copy, amountCents, buttonColor, cardSubmitLabel, closeAriaLabel, countdownLabel, checkoutAnalytics, checkoutSessionId, customerEmail, customerEmailEditable: allowEmailEditing, customerEmailLabel, customerEmailPlaceholder, customerEmailInvalidMessage, customerName, discountAmountLabel, discountLabel, discountPercent, initialWalletAvailable, onClose, onWalletCancel, onCustomerEmailChange, onCustomerEmailCommit, onError, onInactiveCheckoutSession, onPaymentInfoSubmitted, onSuccess, paymentMethodLabels, paypalCheckout, paypalPending, paypalLabel, promoActive, processingLabel, promoCode, promoCodeLabel, remainingSeconds, returnUrl, savedLabel, secureLabel, satisfactionLabel, satisfactionPercent, summaryLabel, supportedCountries, themeColor, title, totalLabel, totalValue, unsupportedCountryMessage, walletButtonLabel, originalPriceLabel, originalPriceValue, variant, presentation, }: SharedStripeCheckoutV2FormProps): import("react/jsx-runtime").JSX.Element;
7
- export {};
@@ -1,328 +0,0 @@
1
- 'use client';
2
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
- import { completePaywallCheckout } from '@funnelsgrove/runtime';
4
- import { useEffect, useMemo, useRef, useState } from 'react';
5
- import { PaymentElement, useCheckout } from '@stripe/react-stripe-js/checkout';
6
- import { isValidCheckoutEmail as isValidEmail, isCheckoutEmailError } from '../../../services/checkoutEmail.js';
7
- import { resolveCheckoutReturnUrl } from '../services/checkout/checkoutReturnUrl.js';
8
- import { PaymentBrandMark, SecurityLockIcon } from './CheckoutBrandAssets.js';
9
- import { StripeCheckoutExpressCheckoutButton } from './StripeCheckoutExpressCheckoutButton.js';
10
- import { getUnsupportedCheckoutCountryMessage, normalizeSupportedCheckoutCountries } from './checkoutCountries.js';
11
- import { isInactiveCheckoutSessionError } from '../hooks/useStripeSubscriptionCheckoutSession.js';
12
- import { getStripeWalletPaymentMethodOrder, usePlatformWalletPaymentMethods } from './walletPlatform.js';
13
- import { trackPaidStripeSubscriptionCheckoutCompleted, trackStripeSubscriptionPaymentInfoSubmitted } from '../services/checkoutCompletionAnalytics.service.js';
14
- import { trackCheckoutFailureShown } from '../../../services/checkoutObservability.service.js';
15
- import { isStripeCheckoutAlreadyPaidError, normalizeStripeCheckoutError } from '../services/stripeCheckoutError.js';
16
- import { SharedCheckoutPaymentMethods } from './SharedCheckoutPaymentMethods.internal.js';
17
- import { SharedStripeCheckoutV2Summary } from './SharedStripeCheckoutV2Summary.internal.js';
18
- import { useCheckoutEmail } from './useCheckoutEmail.internal.js';
19
- import { getCheckoutSessionPaymentMethodTypes } from '../services/checkoutSessionPaymentMethods.js';
20
- import { defaultCheckoutV2Copy } from './checkout-v2.content.js';
21
- const defaultPaymentMethodLabels = ['Visa', 'Mastercard', 'Maestro', 'Discover'];
22
- export const getFixedSupportedBillingCountry = (supportedCountries) => supportedCountries.length === 1 ? supportedCountries[0] : null;
23
- const getCheckoutCountryLabel = (countryCode, copy) => { var _a; return (_a = copy.countryNames[countryCode]) !== null && _a !== void 0 ? _a : countryCode; };
24
- function getFriendlyCardErrorMessage(error, fallback) {
25
- return error instanceof Error && error.message
26
- ? error.message
27
- : fallback;
28
- }
29
- export function SharedStripeCheckoutV2CheckoutSessionForm({ copy = defaultCheckoutV2Copy, amountCents, buttonColor, cardSubmitLabel, closeAriaLabel, countdownLabel, checkoutAnalytics, checkoutSessionId, customerEmail, customerEmailEditable: allowEmailEditing = false, customerEmailLabel = 'Email', customerEmailPlaceholder = 'Enter your email', customerEmailInvalidMessage = 'Enter a valid email address.', customerName, discountAmountLabel, discountLabel, discountPercent, initialWalletAvailable, onClose, onWalletCancel, onCustomerEmailChange, onCustomerEmailCommit, onError, onInactiveCheckoutSession, onPaymentInfoSubmitted, onSuccess, paymentMethodLabels = defaultPaymentMethodLabels, paypalCheckout, paypalPending = false, paypalLabel, promoActive, processingLabel, promoCode, promoCodeLabel, remainingSeconds, returnUrl, savedLabel, secureLabel, satisfactionLabel, satisfactionPercent, summaryLabel, supportedCountries, themeColor, title, totalLabel, totalValue, unsupportedCountryMessage, walletButtonLabel, originalPriceLabel, originalPriceValue, variant = 'standard', presentation = 'dialog', }) {
30
- const checkoutState = useCheckout();
31
- const walletPaymentMethods = usePlatformWalletPaymentMethods();
32
- const [selectedMethod, setSelectedMethod] = useState('wallet');
33
- const [walletAvailable, setWalletAvailable] = useState(initialWalletAvailable !== null && initialWalletAvailable !== void 0 ? initialWalletAvailable : null);
34
- const effectiveWalletAvailable = initialWalletAvailable === true && walletAvailable !== false
35
- ? true
36
- : walletAvailable;
37
- const [submitting, setSubmitting] = useState(false);
38
- const [walletConfirming, setWalletConfirming] = useState(false);
39
- const [completed, setCompleted] = useState(false);
40
- const [providerConfirmed, setProviderConfirmed] = useState(false);
41
- const submitInFlightRef = useRef(false);
42
- const [paymentElementReady, setPaymentElementReady] = useState(false);
43
- const [paymentElementComplete, setPaymentElementComplete] = useState(false);
44
- const paymentElementRef = useRef(null);
45
- const [stripeMethodType, setStripeMethodType] = useState('card');
46
- const [accordionExpanded, setAccordionExpanded] = useState(null);
47
- // CHECKOUT-BR-010: a session with methods beyond cards shows Stripe's accordion next to the wallet option.
48
- const accordionLayout = getCheckoutSessionPaymentMethodTypes(checkoutSessionId).some((type) => type !== 'card');
49
- const [error, setError] = useState(null);
50
- const [billingCountry, setBillingCountry] = useState(null);
51
- const { initialCustomerEmail, resolvedCustomerEmail, customerEmailEditable, emailDraft, setEmailDraft, rejectedEmail, setRejectedEmail, emailSaving, emailSessionChanged, commitEmailDraftIfValid, ensureCustomerEmail } = useCheckoutEmail({
52
- customerEmail, allowEmailEditing, customerEmailInvalidMessage,
53
- onCustomerEmailCommit, onCustomerEmailChange, onError: (message) => setSharedError(message),
54
- });
55
- const normalizedSupportedCountries = useMemo(() => normalizeSupportedCheckoutCountries(supportedCountries), [supportedCountries]);
56
- const fixedBillingCountry = getFixedSupportedBillingCountry(normalizedSupportedCountries);
57
- const fixedBillingCountryLabel = fixedBillingCountry
58
- ? getCheckoutCountryLabel(fixedBillingCountry, copy)
59
- : null;
60
- const cardBrandLabels = useMemo(() => paymentMethodLabels.length > 0 ? paymentMethodLabels : defaultPaymentMethodLabels, [paymentMethodLabels]);
61
- const normalizedPromoCode = promoCode.trim();
62
- const showPromo = promoActive !== null && promoActive !== void 0 ? promoActive : (discountPercent > 0 && normalizedPromoCode.length > 0);
63
- const emailFieldClassName = [
64
- 'shared-checkout-v2-email-field',
65
- customerEmailEditable ? '' : 'is-disabled',
66
- ]
67
- .filter(Boolean)
68
- .join(' ');
69
- const checkoutStyle = {
70
- '--shared-checkout-v2-theme-color': themeColor,
71
- '--shared-checkout-v2-button-color': buttonColor,
72
- };
73
- const expressCheckoutSummaryLabel = (summaryLabel === null || summaryLabel === void 0 ? void 0 : summaryLabel.trim()) || discountLabel || title;
74
- const showPayPalMethod = presentation === 'dialog' && Boolean(paypalCheckout);
75
- const walletAriaLabel = [
76
- ...(showPayPalMethod ? [paypalLabel] : []),
77
- ...walletPaymentMethods.map((method) => method === 'applePay' ? walletButtonLabel : 'Google Pay'),
78
- ].join(' / ');
79
- const walletEmailReady = !emailSessionChanged && isValidEmail(initialCustomerEmail)
80
- && rejectedEmail === null && resolvedCustomerEmail === initialCustomerEmail;
81
- const showPlatformWallets = presentation !== 'inline' && walletEmailReady
82
- && effectiveWalletAvailable !== false && walletPaymentMethods.length > 0;
83
- const showWalletMethod = showPlatformWallets || showPayPalMethod;
84
- const effectiveSelectedMethod = showWalletMethod && (paypalPending || selectedMethod === 'wallet') ? 'wallet' : 'card';
85
- const expressCheckoutOptions = useMemo(() => {
86
- return {
87
- buttonHeight: 55,
88
- buttonTheme: {
89
- applePay: 'black',
90
- googlePay: 'black',
91
- },
92
- buttonType: {
93
- applePay: 'subscribe',
94
- googlePay: 'subscribe',
95
- },
96
- layout: {
97
- maxColumns: 1,
98
- maxRows: 2,
99
- overflow: 'auto',
100
- },
101
- paymentMethodOrder: getStripeWalletPaymentMethodOrder(walletPaymentMethods),
102
- paymentMethods: {
103
- amazonPay: 'never',
104
- applePay: walletPaymentMethods.includes('applePay') ? 'always' : 'never',
105
- googlePay: walletPaymentMethods.includes('googlePay') ? 'always' : 'never',
106
- klarna: 'never',
107
- link: 'never',
108
- paypal: 'never',
109
- },
110
- };
111
- }, [walletPaymentMethods]);
112
- const paymentElementOptions = useMemo(() => {
113
- return Object.assign(Object.assign({ fields: {
114
- billingDetails: {
115
- name: 'never',
116
- email: 'never',
117
- address: {
118
- country: fixedBillingCountry ? 'never' : 'auto',
119
- },
120
- },
121
- }, layout: accordionLayout
122
- ? {
123
- type: 'accordion',
124
- defaultCollapsed: effectiveSelectedMethod === 'wallet',
125
- radios: true,
126
- spacedAccordionItems: true,
127
- visibleAccordionItemsCount: 0,
128
- }
129
- : 'tabs' }, (accordionLayout ? { paymentMethodOrder: ['card'] } : {})), { wallets: {
130
- applePay: 'never',
131
- googlePay: 'never',
132
- link: 'never',
133
- } });
134
- // The initial collapsed state is read once when Stripe mounts the element.
135
- // eslint-disable-next-line react-hooks/exhaustive-deps
136
- }, [accordionLayout, fixedBillingCountry]);
137
- const accordionStartsExpanded = typeof paymentElementOptions.layout === 'object'
138
- && paymentElementOptions.layout.defaultCollapsed === false;
139
- const showCardForm = accordionLayout
140
- ? (accordionExpanded !== null && accordionExpanded !== void 0 ? accordionExpanded : accordionStartsExpanded) && effectiveSelectedMethod === 'card'
141
- : true;
142
- const handleInactiveCheckoutSession = () => {
143
- setError(null);
144
- onInactiveCheckoutSession === null || onInactiveCheckoutSession === void 0 ? void 0 : onInactiveCheckoutSession();
145
- };
146
- const setSharedError = (message, alreadyTracked = false, details) => {
147
- const errorDetails = message ? details !== null && details !== void 0 ? details : normalizeStripeCheckoutError(message, undefined, 'card') : undefined;
148
- if (isCheckoutEmailError({ code: errorDetails === null || errorDetails === void 0 ? void 0 : errorDetails.providerErrorCode }) || isCheckoutEmailError(message)) {
149
- setRejectedEmail(initialCustomerEmail);
150
- setSelectedMethod('card');
151
- }
152
- if (isInactiveCheckoutSessionError(message)) {
153
- handleInactiveCheckoutSession();
154
- return;
155
- }
156
- if (message && checkoutAnalytics && !alreadyTracked) {
157
- trackCheckoutFailureShown(Object.assign({ analytics: checkoutAnalytics, checkoutSessionId, errorMessage: message, failureStage: 'card_form', provider: 'stripe' }, errorDetails));
158
- }
159
- setError(message);
160
- if (message)
161
- onError === null || onError === void 0 ? void 0 : onError(message, errorDetails);
162
- else
163
- onError === null || onError === void 0 ? void 0 : onError(message);
164
- };
165
- const selectWalletMethod = () => {
166
- var _a;
167
- if (showWalletMethod && !paypalPending && !submitting) {
168
- setSelectedMethod('wallet');
169
- if (accordionLayout)
170
- (_a = paymentElementRef.current) === null || _a === void 0 ? void 0 : _a.collapse();
171
- }
172
- };
173
- const selectCardMethod = () => { if (!paypalPending && !submitting)
174
- setSelectedMethod('card'); };
175
- const handleWalletAvailabilityChange = (available) => {
176
- setWalletAvailable(available);
177
- if (!available && !showPayPalMethod && selectedMethod === 'wallet') {
178
- setSelectedMethod('card');
179
- }
180
- };
181
- const getBillingCountryError = (country) => getUnsupportedCheckoutCountryMessage({
182
- billingCountry: country,
183
- message: unsupportedCountryMessage,
184
- supportedCountries: normalizedSupportedCountries,
185
- });
186
- const handlePaymentElementChange = (event) => {
187
- var _a, _b, _c;
188
- setPaymentElementComplete(event.complete);
189
- setStripeMethodType(event.value.type);
190
- if (accordionLayout)
191
- setAccordionExpanded(!event.collapsed);
192
- if (accordionLayout && !event.collapsed) {
193
- // While a wallet or PayPal payment is in flight the wallet option stays selected.
194
- if (paypalPending || walletConfirming)
195
- (_a = paymentElementRef.current) === null || _a === void 0 ? void 0 : _a.collapse();
196
- else
197
- setSelectedMethod('card');
198
- }
199
- setBillingCountry((_c = (_b = event.value.billingDetails) === null || _b === void 0 ? void 0 : _b.address.country) !== null && _c !== void 0 ? _c : fixedBillingCountry);
200
- };
201
- const trackCheckoutSuccess = async (embedded = false) => {
202
- if (checkoutAnalytics) {
203
- await trackPaidStripeSubscriptionCheckoutCompleted(Object.assign({ checkoutSessionId }, checkoutAnalytics));
204
- }
205
- if (!embedded)
206
- await (onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess());
207
- };
208
- const trackPaymentInfoSubmitted = async () => {
209
- if (checkoutAnalytics) {
210
- await trackStripeSubscriptionPaymentInfoSubmitted(Object.assign({ checkoutSessionId }, checkoutAnalytics)).catch(() => 'analytics_rejected');
211
- }
212
- await (onPaymentInfoSubmitted === null || onPaymentInfoSubmitted === void 0 ? void 0 : onPaymentInfoSubmitted());
213
- };
214
- useEffect(() => {
215
- if (effectiveSelectedMethod !== 'card' || typeof window === 'undefined') {
216
- return;
217
- }
218
- const resizeTimer = window.setTimeout(() => {
219
- window.dispatchEvent(new Event('resize'));
220
- }, 0);
221
- return () => window.clearTimeout(resizeTimer);
222
- }, [effectiveSelectedMethod]);
223
- const handleSubmit = async (event) => {
224
- event.preventDefault();
225
- if (paypalPending)
226
- return;
227
- if (submitInFlightRef.current || (emailSessionChanged && !providerConfirmed)) {
228
- return;
229
- }
230
- if (!providerConfirmed) {
231
- const billingCountryError = getBillingCountryError(billingCountry !== null && billingCountry !== void 0 ? billingCountry : fixedBillingCountry);
232
- if (billingCountryError) {
233
- setSharedError(billingCountryError);
234
- return;
235
- }
236
- if (checkoutState.type !== 'success') {
237
- setSharedError(checkoutState.type === 'error'
238
- ? checkoutState.error.message
239
- : copy.formNotReady);
240
- return;
241
- }
242
- if (!paymentElementReady) {
243
- setSharedError(copy.formNotReady, true);
244
- return;
245
- }
246
- }
247
- submitInFlightRef.current = true;
248
- setSubmitting(true);
249
- setSharedError(null);
250
- const finishSubmitting = () => {
251
- submitInFlightRef.current = false;
252
- setSubmitting(false);
253
- };
254
- let confirmed = providerConfirmed;
255
- try {
256
- if (!providerConfirmed && checkoutState.type === 'success') {
257
- const syncedEmail = await ensureCustomerEmail();
258
- if (!syncedEmail) {
259
- finishSubmitting();
260
- return;
261
- }
262
- if (paymentElementComplete) {
263
- await trackPaymentInfoSubmitted();
264
- }
265
- const result = await checkoutState.checkout.confirm({
266
- redirect: 'if_required',
267
- });
268
- if (result.type === 'error' && !isStripeCheckoutAlreadyPaidError(result.error)) {
269
- const message = result.error.message || copy.paymentFailed;
270
- setSharedError(message, false, normalizeStripeCheckoutError(message, result.error, 'card'));
271
- finishSubmitting();
272
- return;
273
- }
274
- confirmed = true;
275
- setProviderConfirmed(true);
276
- }
277
- if (typeof window !== 'undefined') {
278
- if (await completePaywallCheckout('stripe', checkoutSessionId || '', { beforeNotify: async () => {
279
- setCompleted(true);
280
- await trackCheckoutSuccess(true);
281
- } })) {
282
- return;
283
- }
284
- await trackCheckoutSuccess();
285
- window.location.assign(resolveCheckoutReturnUrl(returnUrl, checkoutSessionId));
286
- return;
287
- }
288
- finishSubmitting();
289
- }
290
- catch (submitError) {
291
- setSharedError(getFriendlyCardErrorMessage(submitError, copy.cardError), confirmed);
292
- finishSubmitting();
293
- }
294
- };
295
- const emailField = (_jsxs("label", { className: emailFieldClassName, children: [_jsx("span", { className: 'shared-checkout-v2-email-label', children: customerEmailLabel }), _jsx("span", { className: 'shared-checkout-v2-email-control', children: _jsx("input", { type: 'email', autoComplete: 'email', className: 'shared-checkout-v2-email-input', disabled: !customerEmailEditable || emailSaving, inputMode: 'email', readOnly: !customerEmailEditable, value: customerEmailEditable ? emailDraft : initialCustomerEmail, placeholder: customerEmailPlaceholder, onBlur: (event) => commitEmailDraftIfValid(event.currentTarget.value), onChange: (event) => {
296
- if (!customerEmailEditable) {
297
- return;
298
- }
299
- setEmailDraft(event.target.value);
300
- } }) })] }));
301
- const visibleError = error;
302
- if (providerConfirmed && !completed)
303
- return _jsxs("form", { onSubmit: handleSubmit, className: 'shared-checkout-v2-verifying', style: checkoutStyle, children: [_jsx("p", { role: error ? 'alert' : 'status', children: error || copy.verifyingPayment }), _jsx("button", { type: 'submit', disabled: submitting, className: 'shared-checkout-v2-status-button', children: copy.checkPaymentStatus })] });
304
- if (completed)
305
- return _jsx("div", { role: 'status', className: 'shared-checkout-v2-confirmed', style: checkoutStyle, children: copy.paymentConfirmed });
306
- return (_jsxs("div", { className: 'shared-checkout-v2-shell', "data-variant": variant, style: checkoutStyle, children: [presentation === 'dialog' ? _jsxs(_Fragment, { children: [_jsxs("header", { className: 'shared-checkout-v2-header', children: [_jsx("button", { type: 'button', className: 'shared-checkout-v2-close', onClick: onClose, "aria-label": closeAriaLabel, children: _jsx("span", { "aria-hidden": 'true' }) }), _jsx("h2", { id: 'shared-checkout-v2-title', children: title })] }), !(showPayPalMethod && effectiveSelectedMethod === 'wallet') ? _jsx(SharedStripeCheckoutV2Summary, { countdownUnit: copy.countdownUnit, discountPercent, countdownLabel, remainingSeconds, variant, satisfactionPercent, satisfactionLabel, originalPriceLabel, originalPriceValue, discountLabel, discountAmountLabel, promoCodeLabel, promoCode, totalLabel, totalValue, savedLabel, showPromo }) : null] }) : null, _jsxs("form", { className: 'shared-checkout-v2-payment', onSubmit: (event) => void handleSubmit(event), children: [showWalletMethod || showPayPalMethod ? (_jsx(SharedCheckoutPaymentMethods, { showWalletMethod: showWalletMethod, showPayPalMethod: showPayPalMethod, selectedMethod: effectiveSelectedMethod, disabled: paypalPending || submitting || walletConfirming, layout: accordionLayout ? 'accordion' : 'tabs', paymentMethodLabel: copy.paymentMethodLabel, cardLabel: copy.cardLabel, walletAriaLabel: walletAriaLabel, walletPaymentMethods: walletPaymentMethods, cardBrandLabels: cardBrandLabels, onWalletSelect: selectWalletMethod, onCardSelect: selectCardMethod })) : null, presentation === 'dialog' ? _jsxs("div", { hidden: effectiveSelectedMethod !== 'wallet', className: [
307
- 'shared-checkout-v2-wallet-panel',
308
- effectiveSelectedMethod === 'wallet' ? 'is-visible' : '',
309
- ]
310
- .filter(Boolean)
311
- .join(' '), children: [_jsxs("p", { className: 'shared-checkout-v2-secure-pill', children: [_jsx(SecurityLockIcon, { className: 'shared-checkout-v2-secure-pill-icon' }), secureLabel] }), showPayPalMethod && effectiveSelectedMethod === 'wallet' ? _jsx("div", { className: 'shared-checkout-v2-paypal-button', "aria-label": paypalLabel, inert: walletConfirming || submitting, children: paypalCheckout }) : null, _jsxs("div", { inert: paypalPending, hidden: !showPlatformWallets, className: 'shared-checkout-v2-wallet-shell', "aria-label": walletAriaLabel, children: [_jsx(StripeCheckoutExpressCheckoutButton, { amountCents: amountCents, availabilityPaymentMethods: walletPaymentMethods, beforeConfirm: async () => {
312
- if (paypalPending)
313
- return null;
314
- setWalletConfirming(true);
315
- const email = await ensureCustomerEmail();
316
- if (!email)
317
- setWalletConfirming(false);
318
- return email;
319
- }, checkoutAnalytics: checkoutAnalytics, checkoutSessionId: checkoutSessionId, className: 'shared-checkout-v2-express-buttons', confirmEmail: false, customerEmail: resolvedCustomerEmail, customerName: customerName, initialAvailable: initialWalletAvailable, keepInitialAvailableOnReady: initialWalletAvailable === true, onAvailabilityChange: handleWalletAvailabilityChange, onCancel: () => { setWalletConfirming(false); onWalletCancel === null || onWalletCancel === void 0 ? void 0 : onWalletCancel(); }, onError: (message, details) => setSharedError(message, true, details), onPaymentInfoSubmitted: onPaymentInfoSubmitted, onPaymentRejected: () => { setWalletConfirming(false); setSelectedMethod('card'); }, onSuccess: () => trackCheckoutSuccess(), onEmbeddedComplete: () => setCompleted(true), onVerificationPending: () => setProviderConfirmed(true), options: expressCheckoutOptions, returnUrl: returnUrl, summaryLabel: expressCheckoutSummaryLabel, supportedCountries: normalizedSupportedCountries, unsupportedCountryMessage: unsupportedCountryMessage }), _jsx("span", { className: 'shared-checkout-v2-sr-only', children: walletAriaLabel })] })] }) : null, _jsxs("div", { hidden: !accordionLayout && effectiveSelectedMethod !== 'card', className: [
320
- 'shared-checkout-v2-card-panel',
321
- accordionLayout || effectiveSelectedMethod === 'card' ? 'is-visible' : '',
322
- ]
323
- .filter(Boolean)
324
- .join(' '), children: [_jsxs("div", { className: 'shared-checkout-v2-card-box', children: [accordionLayout ? null : emailField, _jsx(PaymentElement, { options: paymentElementOptions, onChange: handlePaymentElementChange, onReady: (element) => {
325
- paymentElementRef.current = element;
326
- setPaymentElementReady(true);
327
- } }), accordionLayout && showCardForm ? emailField : null, fixedBillingCountry && fixedBillingCountryLabel ? (_jsxs("label", { className: 'shared-checkout-v2-country-field', children: [_jsx("span", { className: 'shared-checkout-v2-country-label', children: copy.billingCountryLabel }), _jsx("span", { className: 'shared-checkout-v2-country-control', children: _jsx("select", { "aria-label": copy.billingCountryLabel, className: 'shared-checkout-v2-country-select', value: fixedBillingCountry, onChange: () => setBillingCountry(fixedBillingCountry), children: _jsx("option", { value: fixedBillingCountry, children: fixedBillingCountryLabel }) }) })] })) : null] }), visibleError ? _jsx("p", { className: 'shared-checkout-v2-error', children: visibleError }) : null, showCardForm ? _jsxs(_Fragment, { children: [_jsxs("button", { type: 'submit', className: 'shared-checkout-v2-card-submit', disabled: submitting || emailSaving || emailSessionChanged || !paymentElementReady, children: [_jsx(SecurityLockIcon, { className: 'shared-checkout-v2-card-submit-icon' }), submitting || emailSaving || emailSessionChanged ? processingLabel : cardSubmitLabel] }), stripeMethodType === 'card' ? _jsx("div", { className: 'shared-checkout-v2-card-brands', "aria-hidden": 'true', children: cardBrandLabels.map((label) => (_jsx(PaymentBrandMark, { label: label, className: 'shared-checkout-v2-card-brand' }, label))) }) : null, _jsxs("p", { className: 'shared-checkout-v2-secure-pill shared-checkout-v2-secure-pill--card', children: [_jsx(SecurityLockIcon, { className: 'shared-checkout-v2-secure-pill-icon' }), secureLabel] })] }) : null] })] })] }));
328
- }
@@ -1,7 +0,0 @@
1
- import type { SharedStripeCheckoutV2DialogProps } from './SharedStripeCheckoutV2Dialog.js';
2
- type SummaryProps = Pick<SharedStripeCheckoutV2DialogProps, 'discountPercent' | 'countdownLabel' | 'remainingSeconds' | 'variant' | 'satisfactionPercent' | 'satisfactionLabel' | 'originalPriceLabel' | 'originalPriceValue' | 'discountLabel' | 'discountAmountLabel' | 'promoCodeLabel' | 'promoCode' | 'totalLabel' | 'totalValue' | 'savedLabel'> & {
3
- showPromo: boolean;
4
- countdownUnit: string;
5
- };
6
- export declare function SharedStripeCheckoutV2Summary({ discountPercent, countdownLabel, remainingSeconds, variant, satisfactionPercent, satisfactionLabel, originalPriceLabel, originalPriceValue, discountLabel, discountAmountLabel, promoCodeLabel, promoCode, totalLabel, totalValue, savedLabel, showPromo, countdownUnit }: SummaryProps): import("react/jsx-runtime").JSX.Element;
7
- export {};