@funnelsgrove/payments 0.80.0 → 0.82.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.
package/README.md CHANGED
@@ -29,9 +29,11 @@ Use these for new subscription paywalls:
29
29
  - `trackStripeSubscriptionPaymentInfoSubmitted`
30
30
 
31
31
  For an inline subscription form with the device wallet first and card last, use
32
- `StripeWalletFirstCheckout`. It shows one block per payment method: one wallet, Google Pay
33
- on Android and Apple Pay elsewhere, preselected, with Stripe's own button; every other
34
- method the offer supports (Pix, Klarna, …) as one block; and the card form.
32
+ `StripeWalletFirstCheckout`. It shows one block per payment method: the wallet,
33
+ preselected, with Stripe's own button (Google Pay on Android, Apple Pay on iPhone and iPad,
34
+ and on desktop Apple Pay followed by a Google Pay block, method id `google_pay`, that hides
35
+ where the browser cannot pay); every other method the offer supports (Pix, Klarna, …) as one
36
+ block; and the card form.
35
37
 
36
38
  - Pass the card hook's `clientSecret`, `checkoutSessionId` and `stripePromise`. While the
37
39
  Checkout Session is being created, pass `clientSecret={null}`: the full layout renders
@@ -297,6 +299,21 @@ When a live funnel still uses one of these, migrate the funnel deliberately with
297
299
  - `providers/solidgate/components/*`: the official-SDK checkout dialog and canonical verification lifecycle.
298
300
  - `components/ManageSubscriptionScreen`: provider-neutral subscription management UI.
299
301
 
302
+ ### Provider entry points
303
+
304
+ Stripe is the checkout every funnel has, so it stays in the root entry. Each other
305
+ provider has its own entry point; import it only in a funnel that offers that
306
+ provider, so the rest stay out of the bundle:
307
+
308
+ ```ts
309
+ import { PaddleCheckoutDialog } from '@funnelsgrove/payments/paddle';
310
+ import { PayPalCheckoutDialog } from '@funnelsgrove/payments/paypal';
311
+ import { SolidgateCheckoutDialog } from '@funnelsgrove/payments/solidgate';
312
+ ```
313
+
314
+ The root entry still exports the same names for funnels published before the
315
+ entry points existed.
316
+
300
317
  Funnels should call `resolvePublishedBillingRuntime` once at their runtime-provider boundary. Screens consume its resolved view and should not parse offer sets or pricing-experiment variants themselves. Pass the resolved `stripePublishableKey` into shared Stripe checkout hooks so Stripe.js can load while the Checkout Session request is still in flight; the key returned by that request remains the compatibility fallback.
301
318
 
302
319
  The resolved `provider` is `'stripe' | 'solidgate' | 'paypal' | 'paddle'`; `'paddle'` was added in payments 0.75.0 with runtime 0.47.0. Type funnel props that receive it as `ResolvedPublishedBillingRuntime['provider']` instead of a literal union, so a new provider does not break the funnel build.
@@ -0,0 +1,2 @@
1
+ /** True where a card block sits beside the PayPal button, so PayPal may point the visitor to it. Internal to the package. */
2
+ export declare const PayPalCardFallbackContext: import("react").Context<boolean>;
@@ -0,0 +1,3 @@
1
+ import { createContext } from 'react';
2
+ /** True where a card block sits beside the PayPal button, so PayPal may point the visitor to it. Internal to the package. */
3
+ export const PayPalCardFallbackContext = createContext(false);
@@ -14,3 +14,5 @@ export declare function GooglePayMark(): import("react/jsx-runtime").JSX.Element
14
14
  export declare function CardBrandMarks(): import("react/jsx-runtime").JSX.Element;
15
15
  /** Google Pay on Android, Apple Pay everywhere else — read synchronously from the browser. */
16
16
  export declare function usePlatformWallet(): PlatformWalletPaymentMethod;
17
+ /** Apple Pay then Google Pay on desktop, the platform's own wallet on a phone or tablet. */
18
+ export declare function usePlatformWallets(): readonly PlatformWalletPaymentMethod[];
@@ -2,7 +2,7 @@
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  /** Building blocks shared by the wallet-first Stripe and Solidgate checkouts. Internal to the package. */
4
4
  import { useSyncExternalStore } from 'react';
5
- import { resolveWalletPlatform } from '../providers/stripe/components/walletPlatform.js';
5
+ import { getPlatformWalletPaymentMethods, resolveWalletPlatform } from '../providers/stripe/components/walletPlatform.js';
6
6
  export function MethodCard({ checked, children, disabled, header, label, onSelect }) {
7
7
  return (_jsxs("section", { className: 'wfc-method', "data-checked": checked, children: [_jsxs("button", { type: 'button', role: 'radio', "aria-checked": checked, "aria-label": label, className: 'wfc-method-head', disabled: disabled, onClick: onSelect, children: [_jsx("span", { className: 'wfc-radio', "aria-hidden": 'true' }), header] }), _jsx("div", { className: 'wfc-method-body', "data-open": checked, inert: !checked, "aria-hidden": !checked, children: _jsx("div", { className: 'wfc-method-clip', children: _jsx("div", { className: 'wfc-method-content', children: children }) }) })] }));
8
8
  }
@@ -15,8 +15,12 @@ export function GooglePayMark() {
15
15
  export function CardBrandMarks() {
16
16
  return (_jsxs("span", { className: 'wfc-card-marks', "aria-hidden": 'true', children: [_jsx("svg", { viewBox: '0 0 48 30', className: 'wfc-brand', children: _jsx("text", { x: '24', y: '21', textAnchor: 'middle', fontSize: '17', fontWeight: '800', fontStyle: 'italic', fill: '#1a1f71', fontFamily: 'Arial, sans-serif', children: "VISA" }) }), _jsxs("svg", { viewBox: '0 0 48 30', className: 'wfc-brand', children: [_jsx("circle", { cx: '19', cy: '15', r: '10', fill: '#eb001b' }), _jsx("circle", { cx: '29', cy: '15', r: '10', fill: '#f79e1b', fillOpacity: '.9' })] }), _jsxs("svg", { viewBox: '0 0 48 30', className: 'wfc-brand wfc-brand--box', style: { background: '#1b4fa0' }, children: [_jsx("circle", { cx: '19', cy: '15', r: '9', fill: '#0099df' }), _jsx("circle", { cx: '29', cy: '15', r: '9', fill: '#e60014', fillOpacity: '.85' })] }), _jsx("svg", { viewBox: '0 0 48 30', className: 'wfc-brand wfc-brand--box', style: { background: '#2e77bc' }, children: _jsx("text", { x: '24', y: '19', textAnchor: 'middle', fontSize: '10', fontWeight: '800', fill: '#fff', fontFamily: 'Arial, sans-serif', children: "AMEX" }) })] }));
17
17
  }
18
+ const useWalletPlatform = () => useSyncExternalStore(() => () => undefined, () => resolveWalletPlatform({ maxTouchPoints: navigator.maxTouchPoints, userAgent: navigator.userAgent }), () => 'ios');
18
19
  /** Google Pay on Android, Apple Pay everywhere else — read synchronously from the browser. */
19
20
  export function usePlatformWallet() {
20
- const platform = useSyncExternalStore(() => () => undefined, () => resolveWalletPlatform({ maxTouchPoints: navigator.maxTouchPoints, userAgent: navigator.userAgent }), () => 'ios');
21
- return platform === 'android' ? 'googlePay' : 'applePay';
21
+ return useWalletPlatform() === 'android' ? 'googlePay' : 'applePay';
22
+ }
23
+ /** Apple Pay then Google Pay on desktop, the platform's own wallet on a phone or tablet. */
24
+ export function usePlatformWallets() {
25
+ return getPlatformWalletPaymentMethods(useWalletPlatform());
22
26
  }
@@ -1 +1 @@
1
- export declare const PAYMENTS_PACKAGE_VERSION = "0.80.0";
1
+ export declare const PAYMENTS_PACKAGE_VERSION = "0.82.0";
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/generate-package-version.mjs.
2
- export const PAYMENTS_PACKAGE_VERSION = "0.80.0";
2
+ export const PAYMENTS_PACKAGE_VERSION = "0.82.0";
package/dist/index.d.ts CHANGED
@@ -13,7 +13,6 @@ export * from './services/paymentMethodAnalytics.service.js';
13
13
  export * from './services/checkoutObservability.service.js';
14
14
  export * from './providers/paymentProvider.types.js';
15
15
  export * from './providers/stripe/index.js';
16
- export * from './providers/solidgate/index.js';
17
16
  export { ManageSubscriptionScreen, type ManageSubscriptionContent, type ManageSubscriptionScreenProps, type ManageSubscriptionLabels, } from './components/ManageSubscriptionScreen.js';
18
17
  export { CheckoutSheet, type CheckoutSheetProps, type CheckoutSheetSummary } from './components/CheckoutSheet.js';
19
18
  export type { CheckoutErrorOverlayCopy } from './components/CheckoutErrorOverlay.js';
@@ -21,9 +20,6 @@ export { isCheckoutEmailError, isValidCheckoutEmail } from './services/checkoutE
21
20
  export * from './components/CheckoutEmailDialog.js';
22
21
  export * from './components/CreatorDealBanner.js';
23
22
  export * from './components/CreatorCodeField.js';
24
- export { PayPalCheckoutDialog } from './providers/paypal/PayPalCheckoutDialog.js';
25
- export { PayPalCheckout, type PayPalCheckoutProps } from './providers/paypal/PayPalCheckout.js';
26
- export { readPendingPayPalCheckout } from './providers/paypal/paypalCheckout.service.js';
27
- export { PaddleCheckoutDialog } from './providers/paddle/PaddleCheckoutDialog.js';
28
- export { PaddleCheckout, type PaddleCheckoutProps } from './providers/paddle/PaddleCheckout.js';
29
- export { readPendingPaddleCheckout, type PendingPaddleCheckout } from './providers/paddle/paddleCheckout.service.js';
23
+ export * from './solidgate.js';
24
+ export * from './paypal.js';
25
+ export * from './paddle.js';
package/dist/index.js CHANGED
@@ -12,9 +12,8 @@ export * from './services/creatorDeal.service.js';
12
12
  export * from './services/paymentMethodAnalytics.service.js';
13
13
  export * from './services/checkoutObservability.service.js';
14
14
  export * from './providers/paymentProvider.types.js';
15
- // Provider-specific integrations are grouped behind provider barrels.
15
+ // Stripe is the checkout every funnel has.
16
16
  export * from './providers/stripe/index.js';
17
- export * from './providers/solidgate/index.js';
18
17
  // Provider-neutral subscription management UI.
19
18
  export { ManageSubscriptionScreen, } from './components/ManageSubscriptionScreen.js';
20
19
  export { CheckoutSheet } from './components/CheckoutSheet.js';
@@ -22,9 +21,8 @@ export { isCheckoutEmailError, isValidCheckoutEmail } from './services/checkoutE
22
21
  export * from './components/CheckoutEmailDialog.js';
23
22
  export * from './components/CreatorDealBanner.js';
24
23
  export * from './components/CreatorCodeField.js';
25
- export { PayPalCheckoutDialog } from './providers/paypal/PayPalCheckoutDialog.js';
26
- export { PayPalCheckout } from './providers/paypal/PayPalCheckout.js';
27
- export { readPendingPayPalCheckout } from './providers/paypal/paypalCheckout.service.js';
28
- export { PaddleCheckoutDialog } from './providers/paddle/PaddleCheckoutDialog.js';
29
- export { PaddleCheckout } from './providers/paddle/PaddleCheckout.js';
30
- export { readPendingPaddleCheckout } from './providers/paddle/paddleCheckout.service.js';
24
+ // The other providers live at `@funnelsgrove/payments/<provider>`. They stay
25
+ // exported here for published funnels; new funnel code imports the provider entry.
26
+ export * from './solidgate.js';
27
+ export * from './paypal.js';
28
+ export * from './paddle.js';
@@ -0,0 +1,3 @@
1
+ export { PaddleCheckoutDialog } from './providers/paddle/PaddleCheckoutDialog.js';
2
+ export { PaddleCheckout, type PaddleCheckoutProps } from './providers/paddle/PaddleCheckout.js';
3
+ export { readPendingPaddleCheckout, type PendingPaddleCheckout } from './providers/paddle/paddleCheckout.service.js';
package/dist/paddle.js ADDED
@@ -0,0 +1,4 @@
1
+ // `@funnelsgrove/payments/paddle`: the Paddle checkout, loaded only by funnels that offer it.
2
+ export { PaddleCheckoutDialog } from './providers/paddle/PaddleCheckoutDialog.js';
3
+ export { PaddleCheckout } from './providers/paddle/PaddleCheckout.js';
4
+ export { readPendingPaddleCheckout } from './providers/paddle/paddleCheckout.service.js';
@@ -0,0 +1,3 @@
1
+ export { PayPalCheckoutDialog } from './providers/paypal/PayPalCheckoutDialog.js';
2
+ export { PayPalCheckout, type PayPalCheckoutProps } from './providers/paypal/PayPalCheckout.js';
3
+ export { readPendingPayPalCheckout } from './providers/paypal/paypalCheckout.service.js';
package/dist/paypal.js ADDED
@@ -0,0 +1,4 @@
1
+ // `@funnelsgrove/payments/paypal`: the PayPal checkout, loaded only by funnels that offer it.
2
+ export { PayPalCheckoutDialog } from './providers/paypal/PayPalCheckoutDialog.js';
3
+ export { PayPalCheckout } from './providers/paypal/PayPalCheckout.js';
4
+ export { readPendingPayPalCheckout } from './providers/paypal/paypalCheckout.service.js';
@@ -1,8 +1,13 @@
1
1
  import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
2
- import { useEffect, useRef, useState } from 'react';
2
+ import { useContext, useEffect, useRef, useState } from 'react';
3
3
  import { completePaywallCheckout, retainPaywallCheckout } from '@funnelsgrove/runtime';
4
+ import { PayPalCardFallbackContext } from '../../components/paypalCardFallback.js';
4
5
  import { loadPayPalSdk } from './paypalSdk.js';
5
6
  import { PayPalCheckoutRequestError, readPendingPayPalCheckout, storePendingPayPalCheckout, preparePayPalCheckout, verifyPayPalCheckout } from './paypalCheckout.service.js';
7
+ const UNAVAILABLE_MESSAGE = 'PayPal is temporarily unavailable. Try again, or pay by card instead.';
8
+ const RETRY_MESSAGE = 'PayPal is temporarily unavailable. Please try again.';
9
+ const CARD_NEXT_STEP = 'Please pay by card instead.';
10
+ const CLOSED_NOTE = 'PayPal was closed. You can also pay by card.';
6
11
  /** A keyed instance owns one merchant/plan selection throughout buyer approval. */
7
12
  export function PayPalCheckout(props) {
8
13
  const container = useRef(null);
@@ -12,7 +17,12 @@ export function PayPalCheckout(props) {
12
17
  const [error, setError] = useState(null);
13
18
  const [state, setState] = useState('loading');
14
19
  const [retry, setRetry] = useState(0);
20
+ const [slowConfirmation, setSlowConfirmation] = useState(false);
15
21
  const [summary, setSummary] = useState(props.option.summary);
22
+ const [closed, setClosed] = useState(false);
23
+ const cardFallback = useContext(PayPalCardFallbackContext);
24
+ const cardFallbackRef = useRef(cardFallback);
25
+ cardFallbackRef.current = cardFallback;
16
26
  const verifyRef = useRef(null);
17
27
  const inputKey = JSON.stringify([props.option, props.environment, props.funnelEndUserId, props.offerSetId, props.funnelPlanKey, props.runtimeConfig]);
18
28
  useEffect(() => {
@@ -67,15 +77,29 @@ export function PayPalCheckout(props) {
67
77
  if (!attempt)
68
78
  (_b = (_a = callbacks.current).onPendingChange) === null || _b === void 0 ? void 0 : _b.call(_a, false);
69
79
  };
80
+ // While an attempt is open the card stays locked, so only an attempt-free failure beside a card block points to it.
81
+ const unavailableMessage = () => attempt || !cardFallbackRef.current ? RETRY_MESSAGE : UNAVAILABLE_MESSAGE;
70
82
  const showRequestError = (error, fallback) => {
71
- var _a, _b;
83
+ var _a, _b, _c, _d;
72
84
  if (controller.signal.aborted || completed)
73
85
  return;
86
+ if (error instanceof PayPalCheckoutRequestError && error.code === 'checkout_declined' && !attempt) {
87
+ // Nothing was created at PayPal, so release the checkout.
88
+ blocked = true;
89
+ try {
90
+ sessionStorage.removeItem(storageKey);
91
+ }
92
+ catch ( /* Optional persistence. */_e) { /* Optional persistence. */ }
93
+ setError(cardFallbackRef.current ? `${error.message} ${CARD_NEXT_STEP}` : error.message);
94
+ setState('declined');
95
+ (_b = (_a = callbacks.current).onPendingChange) === null || _b === void 0 ? void 0 : _b.call(_a, false);
96
+ return;
97
+ }
74
98
  if (error instanceof PayPalCheckoutRequestError) {
75
99
  blocked = true;
76
100
  setError(error.message);
77
101
  setState('blocked');
78
- (_b = (_a = callbacks.current).onPendingChange) === null || _b === void 0 ? void 0 : _b.call(_a, true);
102
+ (_d = (_c = callbacks.current).onPendingChange) === null || _d === void 0 ? void 0 : _d.call(_c, true);
79
103
  return;
80
104
  }
81
105
  showError(fallback);
@@ -87,6 +111,10 @@ export function PayPalCheckout(props) {
87
111
  verifying = true;
88
112
  setError(null);
89
113
  setState('verifying');
114
+ setSlowConfirmation(false);
115
+ // After buyer approval the payment went through; a slow confirmation must not read as a failure.
116
+ const slowTimer = approved ? setTimeout(() => { if (!controller.signal.aborted)
117
+ setSlowConfirmation(true); }, 5000) : undefined;
90
118
  try {
91
119
  // Polling is bounded; a pending payment retains the same attempt for a manual recheck.
92
120
  for (let index = 0; index < 20 && !controller.signal.aborted; index += 1) {
@@ -126,11 +154,13 @@ export function PayPalCheckout(props) {
126
154
  }
127
155
  finally {
128
156
  verifying = false;
157
+ clearTimeout(slowTimer);
129
158
  }
130
159
  };
131
160
  verifyRef.current = verify;
132
161
  setState('loading');
133
162
  setError(null);
163
+ setClosed(false);
134
164
  const renderButton = async () => {
135
165
  if (controller.signal.aborted)
136
166
  return;
@@ -150,6 +180,7 @@ export function PayPalCheckout(props) {
150
180
  (_b = (_a = callbacks.current).onPreparationStart) === null || _b === void 0 ? void 0 : _b.call(_a);
151
181
  (_d = (_c = callbacks.current).onPendingChange) === null || _d === void 0 ? void 0 : _d.call(_c, true);
152
182
  setError(null);
183
+ setClosed(false);
153
184
  setState('approving');
154
185
  try {
155
186
  if (attempt) {
@@ -167,7 +198,7 @@ export function PayPalCheckout(props) {
167
198
  return attempt.subscriptionId;
168
199
  }
169
200
  catch (error) {
170
- showRequestError(error, 'PayPal is temporarily unavailable. Please try again.');
201
+ showRequestError(error, unavailableMessage());
171
202
  throw error;
172
203
  }
173
204
  },
@@ -180,16 +211,25 @@ export function PayPalCheckout(props) {
180
211
  }
181
212
  approved = true;
182
213
  persist();
183
- await verify();
214
+ // PayPal keeps its window open until onApprove settles; confirm behind our own status instead.
215
+ void verify();
184
216
  },
185
- onCancel: () => { var _a, _b; if (!controller.signal.aborted && !approved && !completed && !blocked) {
217
+ onCancel: () => {
218
+ var _a, _b, _c;
219
+ if (controller.signal.aborted || approved || completed || blocked)
220
+ return;
186
221
  attempt = null;
187
222
  persist();
188
223
  storePendingPayPalCheckout(input, null);
189
224
  setState('ready');
225
+ setClosed(true);
190
226
  (_b = (_a = callbacks.current).onPendingChange) === null || _b === void 0 ? void 0 : _b.call(_a, false);
191
- } },
192
- onError: () => showError('PayPal is temporarily unavailable. Please try again.'),
227
+ // The browser refocuses PayPal's button when its window closes, and PayPal draws a heavy ring we cannot style.
228
+ const focused = document.activeElement;
229
+ if (focused instanceof HTMLElement && ((_c = container.current) === null || _c === void 0 ? void 0 : _c.contains(focused)))
230
+ focused.blur();
231
+ },
232
+ onError: () => showError(unavailableMessage()),
193
233
  });
194
234
  await button.render(container.current);
195
235
  if (!controller.signal.aborted)
@@ -201,10 +241,18 @@ export function PayPalCheckout(props) {
201
241
  void verify();
202
242
  }
203
243
  else {
204
- void renderButton().catch(() => showError('Unable to load PayPal. Please try again.'));
244
+ void renderButton().catch(() => showError(unavailableMessage()));
205
245
  }
206
246
  return () => { controller.abort(); verifyRef.current = null; void (button === null || button === void 0 ? void 0 : button.close().catch(() => undefined)); };
207
247
  }, [inputKey, retry]);
208
- return _jsxs("section", { "aria-label": 'PayPal payment', className: 'space-y-3', children: [props.showSummary !== false ? _jsxs("p", { className: 'text-sm', children: ["PayPal \u00B7 ", summary] }) : null, _jsx("div", { ref: container, hidden: state === 'blocked' || state === 'pending' || state === 'verifying' || state === 'success' }), state === 'loading' ? _jsx("p", { role: 'status', children: "Loading PayPal\u2026" }) : null, state === 'verifying' ? _jsx("p", { role: 'status', children: "Confirming your subscription\u2026" }) : null, state === 'success' ? _jsx("p", { role: 'status', children: "Subscription confirmed." }) : null, error ? _jsx("p", { role: 'alert', children: error }) : null, state === 'pending' ? _jsx("button", { type: 'button', onClick: () => { var _a; return void ((_a = verifyRef.current) === null || _a === void 0 ? void 0 : _a.call(verifyRef)); }, children: "Check payment status" })
209
- : error && state !== 'blocked' ? _jsx("button", { type: 'button', onClick: () => setRetry(value => value + 1), children: "Retry PayPal" }) : null] });
248
+ return _jsxs("section", { "aria-label": 'PayPal payment', className: 'space-y-3', children: [props.showSummary !== false ? _jsxs("p", { className: 'text-sm', children: ["PayPal \u00B7 ", summary] }) : null, _jsx("div", { ref: container, hidden: state === 'blocked' || state === 'declined' || state === 'pending' || state === 'verifying' || state === 'success' }), state === 'loading' ? _jsx("p", { role: 'status', children: "Loading PayPal\u2026" }) : null, state === 'verifying' ? _jsxs("div", { className: 'fg-paypal-checkout-status', role: 'status', children: [_jsx("span", { className: 'fg-paypal-checkout-spinner', "aria-hidden": 'true' }), _jsx("p", { children: "Confirming your payment\u2026" }), slowConfirmation ? _jsx("p", { children: "Your payment went through and is being confirmed. Please keep this page open." }) : null] }) : null, state === 'success' ? _jsx("p", { className: 'fg-paypal-checkout-status', role: 'status', children: "Subscription confirmed." }) : null, closed && cardFallback && state === 'ready' && !error ? _jsx("p", { className: 'fg-paypal-checkout-note', role: 'status', children: CLOSED_NOTE }) : null, error ? _jsx("p", { role: 'alert', children: error }) : null, state === 'pending' ? _jsx("button", { type: 'button', onClick: () => { var _a; return void ((_a = verifyRef.current) === null || _a === void 0 ? void 0 : _a.call(verifyRef)); }, children: "Check payment status" })
249
+ : error && state !== 'blocked' && state !== 'declined' ? _jsx("button", { type: 'button', onClick: () => setRetry(value => value + 1), children: "Retry PayPal" }) : null, _jsx("style", { children: paypalCheckoutStyles })] });
210
250
  }
251
+ const paypalCheckoutStyles = `
252
+ .fg-paypal-checkout-status { display:flex; flex-direction:column; align-items:center; gap:12px; margin:0; padding:32px 8px; color:#303136; font-size:16px; line-height:1.5; text-align:center; }
253
+ .fg-paypal-checkout-status p { margin:0; }
254
+ .fg-paypal-checkout-note { margin:10px 0 0; color:#66646e; font-size:14px; line-height:1.4; text-align:center; }
255
+ .fg-paypal-checkout-spinner { width:32px; height:32px; box-sizing:border-box; border:3px solid #e3e5ec; border-top-color:#0070ba; border-radius:50%; animation:fg-paypal-checkout-spin .8s linear infinite; }
256
+ @keyframes fg-paypal-checkout-spin { to { transform:rotate(360deg); } }
257
+ @media (prefers-reduced-motion: reduce) { .fg-paypal-checkout-spinner { animation-duration:2.4s; } }
258
+ `;
@@ -16,6 +16,7 @@ declare const checkoutErrorMessages: {
16
16
  checkout_unavailable: string;
17
17
  checkout_outcome_unresolved: string;
18
18
  already_subscribed_to_product: string;
19
+ checkout_declined: string;
19
20
  };
20
21
  export declare class PayPalCheckoutRequestError extends Error {
21
22
  readonly code: keyof typeof checkoutErrorMessages;
@@ -4,6 +4,7 @@ const checkoutErrorMessages = {
4
4
  checkout_unavailable: 'This PayPal checkout is no longer available. Please contact support before starting another purchase.',
5
5
  checkout_outcome_unresolved: 'We are still checking this PayPal checkout. Please wait or contact support before starting another purchase.',
6
6
  already_subscribed_to_product: 'You already have an active subscription to this product.',
7
+ checkout_declined: 'PayPal can\'t take this payment.',
7
8
  };
8
9
  export class PayPalCheckoutRequestError extends Error {
9
10
  constructor(code) {
@@ -20,7 +21,8 @@ async function request(input, path, signal, body) {
20
21
  if (!response.ok) {
21
22
  const failure = await response.json().catch(() => null);
22
23
  if (record(failure) && (failure.code === 'checkout_unavailable'
23
- || failure.code === 'checkout_outcome_unresolved' || failure.code === 'already_subscribed_to_product')) {
24
+ || failure.code === 'checkout_outcome_unresolved' || failure.code === 'already_subscribed_to_product'
25
+ || failure.code === 'checkout_declined')) {
24
26
  throw new PayPalCheckoutRequestError(failure.code);
25
27
  }
26
28
  throw new Error('Unable to confirm with PayPal. Please try again.');
@@ -4,6 +4,7 @@ import type { StripeCheckoutErrorDetails } from '../services/stripeCheckoutError
4
4
  import { type StripeSubscriptionCheckoutAnalyticsContext } from '../services/checkoutCompletionAnalytics.service.js';
5
5
  import { type StripeWalletFirstCheckoutProps } from './StripeWalletFirstCheckout.js';
6
6
  import { type SharedStripeCheckoutV2Copy } from './checkout-v2.content.js';
7
+ import { type PayPalBillingOption } from '../../../services/publishedBillingRuntime.service.js';
7
8
  export type { SharedStripeCheckoutV2Copy } from './checkout-v2.content.js';
8
9
  export type SharedCheckoutV2CssVars = CSSProperties & {
9
10
  '--shared-checkout-v2-theme-color': string;
@@ -49,6 +50,11 @@ export type SharedStripeCheckoutV2DialogProps = {
49
50
  paypalLabel: string;
50
51
  /** Total of the native PayPal plan, shown instead of `totalValue` and without the discount while PayPal is selected. */
51
52
  paypalTotalValue?: string;
53
+ /**
54
+ * The selected native PayPal option; takes precedence over `paypalTotalValue`. A mapped discount plan
55
+ * (`discountKey`) keeps the discount line with the PayPal plan's own amounts (BILL-PAYPAL-BR-009).
56
+ */
57
+ paypalOption?: Pick<PayPalBillingOption, 'amountMinor' | 'currency' | 'summary' | 'discountKey'> | null;
52
58
  promoActive?: boolean;
53
59
  processingLabel: string;
54
60
  promoCode: string;
@@ -17,6 +17,7 @@ import { StripeCheckoutDialog } from './StripeCheckoutDialog.js';
17
17
  import { StripeWalletFirstCheckout } from './StripeWalletFirstCheckout.js';
18
18
  import { sharedStripeCheckoutV2Styles } from './SharedStripeCheckoutV2.styles.js';
19
19
  import { defaultCheckoutV2Copy } from './checkout-v2.content.js';
20
+ import { describePayPalCheckoutPrices } from '../../../services/publishedBillingRuntime.service.js';
20
21
  const defaultPaymentMethodLabels = ['Visa', 'Mastercard', 'Maestro', 'Discover'];
21
22
  /**
22
23
  * The V2 checkout, kept for funnels that import it: a dialog renders
@@ -102,9 +103,17 @@ export function SharedStripeCheckoutV2Dialog(_a) {
102
103
  totalValue: props.totalValue,
103
104
  savedLabel: props.savedLabel,
104
105
  };
105
- return (_jsx(StripeCheckoutDialog, Object.assign({}, walletFirst, { title: props.title, closeAriaLabel: props.closeAriaLabel, onClose: onClose, guaranteeLabel: props.secureLabel, summary: summary,
106
- // PayPal charges its native plan; the Stripe discount does not apply to it (BILL-PAYPAL-BR-009).
107
- paypalSummary: props.paypalTotalValue ? Object.assign(Object.assign({}, summary), { promoActive: false, totalValue: props.paypalTotalValue }) : undefined })));
106
+ return (_jsx(StripeCheckoutDialog, Object.assign({}, walletFirst, { title: props.title, closeAriaLabel: props.closeAriaLabel, onClose: onClose, guaranteeLabel: props.secureLabel, summary: summary, paypalSummary: paypalSummary(summary, props) })));
107
+ }
108
+ // PayPal charges its native plan; the Stripe discount applies only through a mapped PayPal discount plan (BILL-PAYPAL-BR-009).
109
+ function paypalSummary(summary, props) {
110
+ if (!props.paypalOption)
111
+ return props.paypalTotalValue ? Object.assign(Object.assign({}, summary), { promoActive: false, totalValue: props.paypalTotalValue }) : undefined;
112
+ const prices = describePayPalCheckoutPrices(props.paypalOption);
113
+ if (!prices.originalPriceValue)
114
+ return Object.assign(Object.assign({}, summary), { promoActive: false, totalValue: prices.totalValue });
115
+ // The saved line is the page's copy with the main provider's amounts, so PayPal leaves it out.
116
+ return Object.assign(Object.assign(Object.assign(Object.assign({}, summary), { promoActive: true }), prices), { savedLabel: undefined });
108
117
  }
109
118
  /** The inline V2 form started the checkout when it rendered; the wallet-first block keeps that. */
110
119
  function InlineCheckout({ checkout, title }) {
@@ -0,0 +1,22 @@
1
+ /** Which payment method blocks the wallet-first checkout shows, in order (CHECKOUT-BR-010). Internal to the package. */
2
+ import type { PlatformWalletPaymentMethod } from './walletPlatform.js';
3
+ import type { StripeWalletFirstMethod } from './StripeWalletFirstCheckout.js';
4
+ export type MethodBlock = {
5
+ id: string;
6
+ kind: 'wallet';
7
+ wallet: PlatformWalletPaymentMethod;
8
+ } | {
9
+ id: 'card';
10
+ kind: 'card';
11
+ } | {
12
+ id: 'paypal';
13
+ kind: 'paypal';
14
+ } | {
15
+ id: string;
16
+ kind: 'session';
17
+ types: readonly string[];
18
+ };
19
+ export declare const DEFAULT_METHODS: readonly StripeWalletFirstMethod[];
20
+ /** Only methods the offer supports become blocks; unnamed extras share the `'other'` block. */
21
+ export declare function resolveMethodBlocks(methods: readonly StripeWalletFirstMethod[], wallets: readonly PlatformWalletPaymentMethod[], availablePaymentMethodTypes: readonly string[] | null | undefined, canCreateSessions: boolean, hasPayPal: boolean): MethodBlock[];
22
+ export declare const walletPaymentMethod: (wallet: PlatformWalletPaymentMethod) => "apple_pay" | "google_pay";
@@ -0,0 +1,36 @@
1
+ export const DEFAULT_METHODS = ['wallet', 'other', 'card'];
2
+ const RESERVED_METHODS = new Set(['wallet', 'card', 'other', 'paypal']);
3
+ /** Only methods the offer supports become blocks; unnamed extras share the `'other'` block. */
4
+ export function resolveMethodBlocks(methods, wallets, availablePaymentMethodTypes, canCreateSessions, hasPayPal) {
5
+ const extras = (availablePaymentMethodTypes !== null && availablePaymentMethodTypes !== void 0 ? availablePaymentMethodTypes : []).filter((type) => type !== 'card');
6
+ const named = methods.filter((method) => !RESERVED_METHODS.has(method));
7
+ const blocks = [];
8
+ for (const method of new Set(methods)) {
9
+ if (method === 'wallet') {
10
+ wallets.forEach((wallet, index) => blocks.push({ id: index === 0 ? 'wallet' : walletPaymentMethod(wallet), kind: 'wallet', wallet }));
11
+ }
12
+ else if (method === 'card') {
13
+ blocks.push({ id: 'card', kind: 'card' });
14
+ }
15
+ else if (method === 'paypal') {
16
+ if (hasPayPal)
17
+ blocks.push({ id: 'paypal', kind: 'paypal' });
18
+ }
19
+ else if (!canCreateSessions) {
20
+ continue;
21
+ }
22
+ else if (method === 'other') {
23
+ const types = extras.filter((type) => !named.includes(type));
24
+ if (types.length)
25
+ blocks.push({ id: 'other', kind: 'session', types });
26
+ }
27
+ else if (extras.includes(method)) {
28
+ blocks.push({ id: method, kind: 'session', types: [method] });
29
+ }
30
+ }
31
+ if (hasPayPal && !methods.includes('paypal')) {
32
+ blocks.splice(blocks.map((block) => block.kind).lastIndexOf('wallet') + 1, 0, { id: 'paypal', kind: 'paypal' });
33
+ }
34
+ return blocks;
35
+ }
36
+ export const walletPaymentMethod = (wallet) => wallet === 'applePay' ? 'apple_pay' : 'google_pay';
@@ -2,19 +2,23 @@
2
2
  * Wallet-first inline Stripe checkout (Checkout Sessions), one block per
3
3
  * payment method (CHECKOUT-BR-010).
4
4
  *
5
- * One platform wallet is the first, preselected method: Google Pay on Android,
6
- * Apple Pay everywhere else, shown with Stripe's own wallet button. Card
7
- * payment is the last method. Between them, every other method the offer
8
- * supports (Pix, Klarna, …) forms one block, or its own block when `methods`
9
- * names it; a native PayPal checkout passed as `paypalCheckout` follows the
10
- * wallet. The wallet and the card share the caller's Checkout Session; every
5
+ * The platform wallet is the first, preselected method: Google Pay on Android,
6
+ * Apple Pay on iPhone and iPad, and on desktop Apple Pay followed by a Google
7
+ * Pay block, each shown with Stripe's own wallet button. Card payment is the
8
+ * last method. Between them, every other method the offer supports (Pix,
9
+ * Klarna, …) forms one block, or its own block when `methods` names it; a
10
+ * native PayPal checkout passed as `paypalCheckout` follows the wallets. The
11
+ * wallets and the card share the caller's Checkout Session; every
11
12
  * other Stripe block owns a Checkout Session restricted to its methods, created
12
13
  * when the block is selected. The whole layout renders immediately, even before
13
14
  * the checkout session exists; the wallet slot holds a progress bar at the
14
15
  * exact button height until Stripe's button replaces it, so nothing moves.
15
- * Where the wallet cannot pay, the same slot explains that (or the block hides
16
- * with `hideUnavailableWallet`). The card form has no email or terms text: the
17
- * session carries the email, unless `email` asks the visitor for it. Stripe
16
+ * Where the platform wallet cannot pay, the same slot explains that (or the
17
+ * block hides with `hideUnavailableWallet`); the desktop Google Pay block
18
+ * hides. On desktop a wallet block may therefore leave once Stripe answers,
19
+ * since the caller's hint cannot say which wallet works. The card form has no
20
+ * email or terms text: the session carries the email, unless `email` asks the
21
+ * visitor for it. Stripe
18
22
  * asks for the postal code only for card countries that use it (US, CA, UK).
19
23
  * `paymentElementOptions` overrides these card form defaults. `initialMethod`
20
24
  * opens another block first, e.g. `'card'` for a bottom-of-page "complete your
@@ -64,7 +68,8 @@ export type StripeWalletFirstCheckoutEmail = {
64
68
  };
65
69
  /**
66
70
  * A payment method block: the platform wallet, the card form, PayPal, one block with every other
67
- * method the offer supports (`'other'`), or one Stripe method type such as `'pix'`.
71
+ * method the offer supports (`'other'`), or one Stripe method type such as `'pix'`. On desktop the
72
+ * Google Pay block that follows the platform wallet is `'google_pay'`.
68
73
  */
69
74
  export type StripeWalletFirstMethod = 'wallet' | 'card' | 'other' | 'paypal' | (string & {});
70
75
  /**
@@ -15,19 +15,23 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
15
15
  * Wallet-first inline Stripe checkout (Checkout Sessions), one block per
16
16
  * payment method (CHECKOUT-BR-010).
17
17
  *
18
- * One platform wallet is the first, preselected method: Google Pay on Android,
19
- * Apple Pay everywhere else, shown with Stripe's own wallet button. Card
20
- * payment is the last method. Between them, every other method the offer
21
- * supports (Pix, Klarna, …) forms one block, or its own block when `methods`
22
- * names it; a native PayPal checkout passed as `paypalCheckout` follows the
23
- * wallet. The wallet and the card share the caller's Checkout Session; every
18
+ * The platform wallet is the first, preselected method: Google Pay on Android,
19
+ * Apple Pay on iPhone and iPad, and on desktop Apple Pay followed by a Google
20
+ * Pay block, each shown with Stripe's own wallet button. Card payment is the
21
+ * last method. Between them, every other method the offer supports (Pix,
22
+ * Klarna, …) forms one block, or its own block when `methods` names it; a
23
+ * native PayPal checkout passed as `paypalCheckout` follows the wallets. The
24
+ * wallets and the card share the caller's Checkout Session; every
24
25
  * other Stripe block owns a Checkout Session restricted to its methods, created
25
26
  * when the block is selected. The whole layout renders immediately, even before
26
27
  * the checkout session exists; the wallet slot holds a progress bar at the
27
28
  * exact button height until Stripe's button replaces it, so nothing moves.
28
- * Where the wallet cannot pay, the same slot explains that (or the block hides
29
- * with `hideUnavailableWallet`). The card form has no email or terms text: the
30
- * session carries the email, unless `email` asks the visitor for it. Stripe
29
+ * Where the platform wallet cannot pay, the same slot explains that (or the
30
+ * block hides with `hideUnavailableWallet`); the desktop Google Pay block
31
+ * hides. On desktop a wallet block may therefore leave once Stripe answers,
32
+ * since the caller's hint cannot say which wallet works. The card form has no
33
+ * email or terms text: the session carries the email, unless `email` asks the
34
+ * visitor for it. Stripe
31
35
  * asks for the postal code only for card countries that use it (US, CA, UK).
32
36
  * `paymentElementOptions` overrides these card form defaults. `initialMethod`
33
37
  * opens another block first, e.g. `'card'` for a bottom-of-page "complete your
@@ -41,12 +45,14 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
41
45
  import { useEffect, useMemo, useRef, useState } from 'react';
42
46
  import { CheckoutProvider, PaymentElement, useCheckout } from '@stripe/react-stripe-js/checkout';
43
47
  import { completePaywallCheckout } from '@funnelsgrove/runtime';
44
- import { ApplePayMark, CardBrandMarks, GooglePayMark, MethodCard, usePlatformWallet } from '../../../components/walletFirstParts.js';
48
+ import { ApplePayMark, CardBrandMarks, GooglePayMark, MethodCard, usePlatformWallets } from '../../../components/walletFirstParts.js';
45
49
  import { stripeWalletFirstCheckoutStyles } from './StripeWalletFirstCheckout.styles.js';
46
50
  import { CheckoutErrorOverlay } from '../../../components/CheckoutErrorOverlay.js';
47
51
  import { PaymentBrandMark } from './CheckoutBrandAssets.js';
52
+ import { PayPalCardFallbackContext } from '../../../components/paypalCardFallback.js';
48
53
  import { WalletButton } from './WalletButton.js';
49
54
  import { buildWalletFirstCheckoutOptions } from './StripeWalletFirstCheckout.options.js';
55
+ import { DEFAULT_METHODS, resolveMethodBlocks, walletPaymentMethod } from './StripeWalletFirstCheckout.blocks.js';
50
56
  import { getUnsupportedCheckoutCountryMessage, normalizeSupportedCheckoutCountries } from './checkoutCountries.js';
51
57
  import { useCheckoutEmail } from './useCheckoutEmail.internal.js';
52
58
  import { isCheckoutEmailError, isValidCheckoutEmail } from '../../../services/checkoutEmail.js';
@@ -57,46 +63,11 @@ import { trackCheckoutFailureShown } from '../../../services/checkoutObservabili
57
63
  import { useCheckoutShownOnce } from '../hooks/useCheckoutShownOnce.js';
58
64
  import { isInactiveCheckoutSessionError, useStripeSubscriptionCheckoutSession, } from '../hooks/useStripeSubscriptionCheckoutSession.js';
59
65
  import { isStripeCheckoutAlreadyPaidError, normalizeStripeCheckoutError } from '../services/stripeCheckoutError.js';
60
- const DEFAULT_METHODS = ['wallet', 'other', 'card'];
61
- const RESERVED_METHODS = new Set(['wallet', 'card', 'other', 'paypal']);
62
- /** Only methods the offer supports become blocks; unnamed extras share the `'other'` block. */
63
- function resolveMethodBlocks(methods, availablePaymentMethodTypes, canCreateSessions, hasPayPal) {
64
- const extras = (availablePaymentMethodTypes !== null && availablePaymentMethodTypes !== void 0 ? availablePaymentMethodTypes : []).filter((type) => type !== 'card');
65
- const named = methods.filter((method) => !RESERVED_METHODS.has(method));
66
- const blocks = [];
67
- for (const method of new Set(methods)) {
68
- if (method === 'wallet') {
69
- blocks.push({ id: 'wallet', kind: 'wallet' });
70
- }
71
- else if (method === 'card') {
72
- blocks.push({ id: 'card', kind: 'card' });
73
- }
74
- else if (method === 'paypal') {
75
- if (hasPayPal)
76
- blocks.push({ id: 'paypal', kind: 'paypal' });
77
- }
78
- else if (!canCreateSessions) {
79
- continue;
80
- }
81
- else if (method === 'other') {
82
- const types = extras.filter((type) => !named.includes(type));
83
- if (types.length)
84
- blocks.push({ id: 'other', kind: 'session', types });
85
- }
86
- else if (extras.includes(method)) {
87
- blocks.push({ id: method, kind: 'session', types: [method] });
88
- }
89
- }
90
- if (hasPayPal && !methods.includes('paypal')) {
91
- blocks.splice(blocks.findIndex((block) => block.kind === 'wallet') + 1, 0, { id: 'paypal', kind: 'paypal' });
92
- }
93
- return blocks;
94
- }
95
66
  const methodLabel = (type, copy) => { var _a, _b; return (_b = (_a = copy.methodLabels) === null || _a === void 0 ? void 0 : _a[type]) !== null && _b !== void 0 ? _b : type.replace(/_/g, ' ').replace(/^./, (first) => first.toUpperCase()); };
96
67
  export function StripeWalletFirstCheckout(props) {
97
68
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
98
69
  const { availablePaymentMethodTypes, buttonColor, checkoutAnalytics, checkoutSessionId, clientSecret, copy, initialMethod = 'wallet', methods = DEFAULT_METHODS, methodSessionInput, onError, onSuccess, stripePromise, themeColor, paypalPending = false, } = props;
99
- const wallet = usePlatformWallet();
70
+ const wallets = usePlatformWallets();
100
71
  const [error, setError] = useState(null);
101
72
  const [failure, setFailure] = useState(null);
102
73
  const email = useCheckoutEmail({
@@ -113,9 +84,12 @@ export function StripeWalletFirstCheckout(props) {
113
84
  // Wallets confirm with the session's email, so they show only while the visitor keeps it.
114
85
  const walletEmailReady = !emailController || (!email.emailSessionChanged && isValidCheckoutEmail(email.initialCustomerEmail)
115
86
  && email.rejectedEmail === null && email.resolvedCustomerEmail === email.initialCustomerEmail);
116
- const [walletAvailable, setWalletAvailable] = useState((_f = props.initialWalletAvailable) !== null && _f !== void 0 ? _f : null);
87
+ // The caller's hint says whether any wallet can pay: it fits one wallet, while on desktop only "none" applies to each.
88
+ const initialWalletAvailable = wallets.length === 1 || props.initialWalletAvailable === false ? (_f = props.initialWalletAvailable) !== null && _f !== void 0 ? _f : null : null;
89
+ const [walletAvailability, setWalletAvailability] = useState({});
90
+ const walletUnavailable = (block) => { var _a; return block.kind === 'wallet' && ((_a = walletAvailability[block.id]) !== null && _a !== void 0 ? _a : initialWalletAvailable) === false; };
117
91
  // A wallet this browser cannot use stays mounted but hidden, so a later availability report brings it back.
118
- const walletHidden = Boolean(props.hideUnavailableWallet && walletAvailable === false);
92
+ const walletHidden = (block) => walletUnavailable(block) && (Boolean(props.hideUnavailableWallet) || block.id !== 'wallet');
119
93
  const supportedCountriesKey = (_h = (_g = props.supportedCountries) === null || _g === void 0 ? void 0 : _g.join(',')) !== null && _h !== void 0 ? _h : '';
120
94
  const countries = useMemo(() => {
121
95
  const supported = normalizeSupportedCheckoutCountries(supportedCountriesKey.split(','));
@@ -127,10 +101,12 @@ export function StripeWalletFirstCheckout(props) {
127
101
  const hasPayPal = Boolean(props.paypalCheckout);
128
102
  // Keyed by content so inline arrays from the caller keep each block's `types` identity stable.
129
103
  const methodsKey = methods.join(',');
104
+ const walletsKey = wallets.join(',');
130
105
  const availableKey = (_j = availablePaymentMethodTypes === null || availablePaymentMethodTypes === void 0 ? void 0 : availablePaymentMethodTypes.join(',')) !== null && _j !== void 0 ? _j : null;
131
- const allBlocks = useMemo(() => resolveMethodBlocks(methodsKey.split(',').filter(Boolean), availableKey === null ? null : availableKey.split(',').filter(Boolean), canCreateSessions, hasPayPal), [methodsKey, availableKey, canCreateSessions, hasPayPal]);
106
+ const allBlocks = useMemo(() => resolveMethodBlocks(methodsKey.split(',').filter(Boolean), walletsKey.split(','), availableKey === null ? null : availableKey.split(',').filter(Boolean), canCreateSessions, hasPayPal), [methodsKey, walletsKey, availableKey, canCreateSessions, hasPayPal]);
132
107
  const renderedBlocks = walletEmailReady ? allBlocks : allBlocks.filter((block) => block.kind !== 'wallet');
133
- const blocks = walletHidden ? renderedBlocks.filter((block) => block.kind !== 'wallet') : renderedBlocks;
108
+ const blocks = renderedBlocks.filter((block) => !walletHidden(block));
109
+ const hasCard = blocks.some((block) => block.kind === 'card');
134
110
  const [selected, setSelected] = useState(initialMethod);
135
111
  // A method inside the other block selects that block; a hidden block gives way to the first one.
136
112
  const activeId = paypalPending && hasPayPal ? 'paypal' : (_m = ((_l = (_k = blocks.find((block) => block.id === selected)) !== null && _k !== void 0 ? _k : blocks.find((block) => block.kind === 'session' && block.types.includes(selected))) !== null && _l !== void 0 ? _l : blocks[0])) === null || _m === void 0 ? void 0 : _m.id;
@@ -144,7 +120,8 @@ export function StripeWalletFirstCheckout(props) {
144
120
  // A form that is open on mount has not been opened by the visitor yet.
145
121
  const [engaged, setEngaged] = useState(initialMethod === 'wallet');
146
122
  const select = (id) => {
147
- if (id !== 'wallet')
123
+ var _a;
124
+ if (((_a = allBlocks.find((block) => block.id === id)) === null || _a === void 0 ? void 0 : _a.kind) !== 'wallet')
148
125
  setEngaged(true);
149
126
  setSelected(id);
150
127
  };
@@ -225,10 +202,12 @@ export function StripeWalletFirstCheckout(props) {
225
202
  var _a, _b;
226
203
  const checked = activeId === block.id;
227
204
  if (block.kind === 'wallet') {
228
- const walletPayment = { checkoutSessionId, paymentMethod: wallet === 'applePay' ? 'apple_pay' : 'google_pay' };
205
+ const { wallet } = block;
206
+ const walletPayment = { checkoutSessionId, paymentMethod: walletPaymentMethod(wallet) };
229
207
  const WalletMark = wallet === 'applePay' ? ApplePayMark : GooglePayMark;
230
208
  const walletNote = checked ? status.paymentStatus : null;
231
- return (_jsxs(MethodCard, { checked: checked, disabled: disabled, label: copy.walletLabels[wallet], onSelect: () => select('wallet'), header: _jsx(WalletMark, {}), children: [_jsx("ul", { className: 'wfc-benefits', children: copy.walletBenefits[wallet].map((item) => _jsxs("li", { children: [_jsx(CheckIcon, {}), item] }, item)) }), live ? _jsx("div", { className: 'wfc-wallet-confirm', inert: confirmed || completed, children: _jsx(WalletButton, { amountCents: props.amountCents, beforeConfirm: async () => {
209
+ const platformWallet = block.id === 'wallet';
210
+ return (_jsxs(MethodCard, { checked: checked, disabled: disabled, label: copy.walletLabels[wallet], onSelect: () => select(block.id), header: _jsx(WalletMark, {}), children: [_jsx("ul", { className: 'wfc-benefits', children: copy.walletBenefits[wallet].map((item) => _jsxs("li", { children: [_jsx(CheckIcon, {}), item] }, item)) }), live ? _jsx("div", { className: 'wfc-wallet-confirm', inert: confirmed || completed, children: _jsx(WalletButton, { amountCents: props.amountCents, beforeConfirm: async () => {
232
211
  setBusy(true);
233
212
  if (!emailController)
234
213
  return props.customerEmail || null;
@@ -236,7 +215,9 @@ export function StripeWalletFirstCheckout(props) {
236
215
  if (!confirmedEmail)
237
216
  setBusy(false);
238
217
  return confirmedEmail;
239
- }, checkoutAnalytics: checkoutAnalytics, checkoutSessionId: checkoutSessionId, customerEmail: emailController ? email.resolvedCustomerEmail : props.customerEmail, customerName: props.customerName, initialAvailable: props.initialWalletAvailable, onAvailabilityChange: setWalletAvailable, onCancel: () => { var _a; setBusy(false); (_a = props.onCancel) === null || _a === void 0 ? void 0 : _a.call(props); }, onEmbeddedComplete: () => setCompleted(true), onError: (message, details) => { setBusy(false); status.showError(message, { blockId: 'wallet', checkoutSessionId, failureStage: 'wallet', paymentMethod: wallet }, details, true); }, onPaymentInfoSubmitted: props.onPaymentInfoSubmitted, onPaymentRejected: () => { setBusy(false); select('card'); }, onSuccess: async () => { await status.trackSuccess(walletPayment); }, onVerificationPending: () => status.markConfirmed(walletPayment), processingLabel: copy.processingLabel, returnUrl: props.returnUrl, stripePromise: stripePromise, summaryLabel: props.summaryLabel, supportedCountries: countries.supported, unavailableNote: copy.walletUnavailableNote.replace('{wallet}', copy.walletLabels[wallet]), unsupportedCountryMessage: countries.message, wallet: wallet }) }) : _jsx("div", { className: 'wfc-wallet-slot', children: _jsx("span", { className: 'wfc-progress', role: 'status', "aria-label": copy.processingLabel }) }), _jsx("p", { className: walletNote ? 'wfc-secure is-status' : 'wfc-secure', role: walletNote ? 'status' : undefined, children: walletNote || copy.secureNote })] }, 'wallet'));
218
+ }, checkoutAnalytics: checkoutAnalytics, checkoutSessionId: checkoutSessionId, customerEmail: emailController ? email.resolvedCustomerEmail : props.customerEmail, customerName: props.customerName, initialAvailable: initialWalletAvailable, onAvailabilityChange: (available) => setWalletAvailability((current) => (Object.assign(Object.assign({}, current), { [block.id]: available }))), onCancel: () => { var _a; setBusy(false); (_a = props.onCancel) === null || _a === void 0 ? void 0 : _a.call(props); }, onEmbeddedComplete: () => setCompleted(true), onError: (message, details) => { setBusy(false); status.showError(message, { blockId: block.id, checkoutSessionId, failureStage: 'wallet', paymentMethod: wallet }, details, true); }, onPaymentInfoSubmitted: props.onPaymentInfoSubmitted, onPaymentRejected: () => { setBusy(false); select('card'); }, onSuccess: async () => { await status.trackSuccess(walletPayment); }, onVerificationPending: () => status.markConfirmed(walletPayment), processingLabel: copy.processingLabel, returnUrl: props.returnUrl,
219
+ // Stripe mounts one wallet button per Checkout scope, so the Google Pay block opens its own on the same session.
220
+ session: platformWallet ? undefined : { clientSecret, stripePromise, themeColor }, stripePromise: stripePromise, summaryLabel: props.summaryLabel, supportedCountries: countries.supported, unavailableNote: copy.walletUnavailableNote.replace('{wallet}', copy.walletLabels[wallet]), unsupportedCountryMessage: countries.message, wallet: wallet }) }) : _jsx("div", { className: 'wfc-wallet-slot', children: _jsx("span", { className: 'wfc-progress', role: 'status', "aria-label": copy.processingLabel }) }), _jsx("p", { className: walletNote ? 'wfc-secure is-status' : 'wfc-secure', role: walletNote ? 'status' : undefined, children: walletNote || copy.secureNote })] }, block.id));
240
221
  }
241
222
  if (block.kind === 'card') {
242
223
  const brands = ((_a = props.cardBrandLabels) === null || _a === void 0 ? void 0 : _a.length)
@@ -248,7 +229,7 @@ export function StripeWalletFirstCheckout(props) {
248
229
  }
249
230
  if (block.kind === 'paypal') {
250
231
  const label = (_b = props.paypalLabel) !== null && _b !== void 0 ? _b : 'PayPal';
251
- return (_jsx(MethodCard, { checked: checked, disabled: disabled, label: label, onSelect: () => select('paypal'), header: _jsx(PaymentBrandMark, { label: 'PayPal', className: 'wfc-brand wfc-brand--paypal' }), children: _jsx("div", { className: 'wfc-paypal', inert: busy || confirmed, children: checked ? props.paypalCheckout : null }) }, 'paypal'));
232
+ return (_jsx(MethodCard, { checked: checked, disabled: disabled, label: label, onSelect: () => select('paypal'), header: _jsxs(_Fragment, { children: [_jsx(PaymentBrandMark, { label: 'PayPal', className: 'wfc-brand wfc-brand--paypal' }), _jsx("span", { className: 'wfc-method-label', children: label })] }), children: _jsx("div", { className: 'wfc-paypal', inert: busy || confirmed, children: _jsx(PayPalCardFallbackContext.Provider, { value: hasCard, children: checked ? props.paypalCheckout : null }) }) }, 'paypal'));
252
233
  }
253
234
  return methodSessionInput ? (_jsx(SessionMethodBlock, Object.assign({}, formProps, { block: block, checked: checked, disabled: disabled, onSelect: () => select(block.id), sessionInput: methodSessionInput, themeColor: themeColor }), block.id)) : null;
254
235
  };
@@ -282,18 +263,17 @@ export function StripeWalletFirstCheckout(props) {
282
263
  const dismissFailure = () => status.showError(null, { blockId: activeId !== null && activeId !== void 0 ? activeId : 'card', checkoutSessionId, failureStage: 'dismiss' });
283
264
  // Only a method this browser can pay with is offered as the way out of a decline.
284
265
  const alternativeBlock = !confirmed && (overlayFailure === null || overlayFailure === void 0 ? void 0 : overlayFailure.details.category) === 'payment_rejection'
285
- ? blocks.find((block) => block.id === (overlayFailure.blockId === 'card' ? 'wallet' : 'card')
286
- && !(block.kind === 'wallet' && walletAvailable === false))
266
+ ? blocks.find((block) => (overlayFailure.blockId === 'card' ? block.kind === 'wallet' : block.id === 'card') && !walletUnavailable(block))
287
267
  : undefined;
288
268
  const blockLabel = (block) => {
289
269
  var _a;
290
- return block.kind === 'wallet' ? copy.walletLabels[wallet]
270
+ return block.kind === 'wallet' ? copy.walletLabels[block.wallet]
291
271
  : block.kind === 'card' ? copy.cardLabel
292
272
  : block.kind === 'paypal' ? (_a = props.paypalLabel) !== null && _a !== void 0 ? _a : 'PayPal'
293
273
  : block.types.map((type) => methodLabel(type, copy)).join(' · ');
294
274
  };
295
- const layout = (_jsxs("div", { className: 'wfc', style: style, children: [renderedBlocks.map((block) => block.kind === 'wallet' && walletHidden
296
- ? _jsx("div", { hidden: true, children: renderBlock(block) }, 'wallet')
275
+ const layout = (_jsxs("div", { className: 'wfc', style: style, children: [renderedBlocks.map((block) => walletHidden(block)
276
+ ? _jsx("div", { hidden: true, children: renderBlock(block) }, block.id)
297
277
  : renderBlock(block)), error && !overlayFailure ? _jsx("p", { className: 'wfc-error', role: 'alert', children: error }) : null, overlayFailure && error ? (_jsx(CheckoutErrorOverlay, { category: overlayFailure.details.category, copy: copy.errors, message: error, onDismiss: dismissFailure, title: confirmed ? copy.verifyingPayment : undefined, dismissible: !confirmed, primary: confirmed ? { label: (_q = (_p = copy.errors) === null || _p === void 0 ? void 0 : _p.checkStatusLabel) !== null && _q !== void 0 ? _q : 'Check payment status', onClick: () => void checkPaymentStatus() } : undefined, alternative: alternativeBlock ? { label: blockLabel(alternativeBlock), onSelect: () => { select(alternativeBlock.id); dismissFailure(); } } : null }, `${overlayFailure.blockId}:${error}`)) : null] }));
298
278
  return (_jsxs(_Fragment, { children: [options && stripePromise ? (_jsx(CheckoutProvider, { stripe: stripePromise, options: options, children: layout }, options.clientSecret)) : layout, _jsx("style", { children: stripeWalletFirstCheckoutStyles })] }));
299
279
  }
@@ -1,4 +1,4 @@
1
- import { type FunnelExperimentDefinition, type FunnelManifestExperiment, type OfferSetRuntimePlanOverrides, type ResolvedFunnelRuntimeConfig, type ResolvedPublishedExperiments, type RuntimeMode } from '@funnelsgrove/runtime';
1
+ import { type FunnelExperimentDefinition, type FunnelManifestExperiment, type OfferSetRuntimePlanOverrides, type ResolvedFunnelRuntimeConfig, type ResolvedPublishedExperiments, type RuntimeMode, type RuntimePaymentProvider } from '@funnelsgrove/runtime';
2
2
  import type { BillingDiscountCatalog, BillingDiscountList, BillingFallbackPlanConfig, BillingPlanCatalog } from '../config/billing.config.js';
3
3
  import { type PaywallPlan } from './paywallPlans.service.js';
4
4
  export type PublishedBillingPlan = BillingFallbackPlanConfig & OfferSetRuntimePlanOverrides;
@@ -32,7 +32,7 @@ export type ResolvedPublishedBillingRuntime = {
32
32
  mode: RuntimeMode;
33
33
  offerSetId: string;
34
34
  paymentProfileId: string | null;
35
- provider: 'stripe' | 'solidgate' | 'paypal' | 'paddle';
35
+ provider: RuntimePaymentProvider;
36
36
  stripePublishableKey: string | null;
37
37
  experimentId: string | null;
38
38
  variantKey: string | null;
@@ -53,6 +53,15 @@ export type ResolvedPublishedBillingRuntime = {
53
53
  export declare const EMPTY_PUBLISHED_BILLING_RUNTIME: ResolvedPublishedBillingRuntime;
54
54
  /** Select native terms without applying another provider's percentage to PayPal. */
55
55
  export declare const resolvePayPalBillingOption: (runtime: Pick<ResolvedPublishedBillingRuntime, "paypalOptionsByPlanKey" | "discounts">, funnelPlanKey: string, discountKeyOrCouponId?: string | null) => PayPalBillingOption | null;
56
+ /**
57
+ * Checkout summary amounts of a native PayPal plan: the first-period price as the total and, for a
58
+ * mapped discount plan (`discountKey`), the regular-cycle price and the difference (BILL-PAYPAL-BR-009).
59
+ */
60
+ export declare const describePayPalCheckoutPrices: (option: Pick<PayPalBillingOption, "amountMinor" | "currency" | "summary" | "discountKey">) => {
61
+ totalValue: string;
62
+ originalPriceValue?: string;
63
+ discountAmountLabel?: string;
64
+ };
56
65
  export declare const resolvePublishedBillingRuntime: ({ config, featureFlags, mode, search, defaultOfferSetId, locale, country, baseCatalogsByMode, fallbackDiscounts, resolvedExperiments, }: {
57
66
  config: ResolvedFunnelRuntimeConfig | null;
58
67
  featureFlags: Readonly<Record<string, string | boolean>>;
@@ -21,6 +21,30 @@ export const resolvePayPalBillingOption = (runtime, funnelPlanKey, discountKeyOr
21
21
  return option.discountOptionsByKey && Object.hasOwn(option.discountOptionsByKey, discountKey)
22
22
  ? option.discountOptionsByKey[discountKey] : option;
23
23
  };
24
+ const leadingPrice = (label) => { var _a; return (_a = label === null || label === void 0 ? void 0 : label.trim().match(/^\D*\d[\d,]*(?:\.(\d+))?/)) !== null && _a !== void 0 ? _a : null; };
25
+ /**
26
+ * Checkout summary amounts of a native PayPal plan: the first-period price as the total and, for a
27
+ * mapped discount plan (`discountKey`), the regular-cycle price and the difference (BILL-PAYPAL-BR-009).
28
+ */
29
+ export const describePayPalCheckoutPrices = (option) => {
30
+ var _a, _b;
31
+ const total = leadingPrice(option.summary);
32
+ const totalValue = (total === null || total === void 0 ? void 0 : total[0]) || option.summary;
33
+ if (!option.discountKey)
34
+ return { totalValue };
35
+ const regular = leadingPrice(option.summary.split(', then ').at(-1));
36
+ if (!regular)
37
+ return { totalValue };
38
+ const exponent = (_b = (_a = regular[1]) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
39
+ const regularMinor = Number(regular[0].replace(/\D/g, ''));
40
+ const discountMinor = regularMinor - option.amountMinor;
41
+ if (!(discountMinor > 0))
42
+ return { totalValue };
43
+ const discount = new Intl.NumberFormat('en-US', {
44
+ style: 'currency', currency: option.currency, minimumFractionDigits: exponent, maximumFractionDigits: exponent,
45
+ }).format(discountMinor / 10 ** exponent);
46
+ return { totalValue, originalPriceValue: regular[0], discountAmountLabel: `-${discount}` };
47
+ };
24
48
  const isRecord = (value) => (Boolean(value) && typeof value === 'object' && !Array.isArray(value));
25
49
  const nativePayPalOption = (mapping, paymentProfileId, clientId) => {
26
50
  if (!(mapping === null || mapping === void 0 ? void 0 : mapping.providerPlanId) || !mapping.checkoutSummaryLabel || mapping.amountCents == null || !mapping.currency)
@@ -101,12 +125,15 @@ export const resolvePublishedBillingRuntime = ({ config, featureFlags, mode, sea
101
125
  continue;
102
126
  const mapping = (_t = item.providerMappingsByMode) === null || _t === void 0 ? void 0 : _t[mode];
103
127
  const profileConfig = ((_w = (_v = (_u = runtime.offerSet) === null || _u === void 0 ? void 0 : _u.paymentProviderConfigByProfileId) === null || _v === void 0 ? void 0 : _v[profileId]) === null || _w === void 0 ? void 0 : _w[mode]) || paymentProviderConfig;
104
- if ((profileConfig === null || profileConfig === void 0 ? void 0 : profileConfig.provider) !== 'paddle' || !profileConfig.paddleClientToken || !profileConfig.paddleEnvironment)
128
+ if ((profileConfig === null || profileConfig === void 0 ? void 0 : profileConfig.provider) !== 'paddle' || !profileConfig.paddleClientToken)
129
+ continue;
130
+ const environment = profileConfig.paddleEnvironment;
131
+ if (environment !== 'sandbox' && environment !== 'production')
105
132
  continue;
106
133
  if (!(mapping === null || mapping === void 0 ? void 0 : mapping.providerPlanId) || !mapping.checkoutSummaryLabel || mapping.amountCents == null || !mapping.currency)
107
134
  continue;
108
135
  paddleOptionsByPlanKey[item.funnelPlanKey] = { paymentProfileId: profileId, clientToken: profileConfig.paddleClientToken,
109
- environment: profileConfig.paddleEnvironment, providerPlanId: mapping.providerPlanId, amountMinor: mapping.amountCents,
136
+ environment, providerPlanId: mapping.providerPlanId, amountMinor: mapping.amountCents,
110
137
  currency: mapping.currency, summary: mapping.checkoutSummaryLabel };
111
138
  }
112
139
  const pinnedFeatureFlags = Object.assign(Object.assign({}, featureFlags), (selection.experimentId && selection.variantKey
@@ -0,0 +1 @@
1
+ export * from './providers/solidgate/index.js';
@@ -0,0 +1,2 @@
1
+ // `@funnelsgrove/payments/solidgate`: the Solidgate checkout, loaded only by funnels that offer it.
2
+ export * from './providers/solidgate/index.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funnelsgrove/payments",
3
- "version": "0.80.0",
3
+ "version": "0.82.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/The-Solid-Grove/funnelsgrove.git",
@@ -11,11 +11,27 @@
11
11
  "main": "./dist/index.js",
12
12
  "module": "./dist/index.js",
13
13
  "types": "./dist/index.d.ts",
14
+ "sideEffects": false,
14
15
  "exports": {
15
16
  ".": {
16
17
  "types": "./dist/index.d.ts",
17
18
  "import": "./dist/index.js",
18
19
  "default": "./dist/index.js"
20
+ },
21
+ "./paddle": {
22
+ "types": "./dist/paddle.d.ts",
23
+ "import": "./dist/paddle.js",
24
+ "default": "./dist/paddle.js"
25
+ },
26
+ "./paypal": {
27
+ "types": "./dist/paypal.d.ts",
28
+ "import": "./dist/paypal.js",
29
+ "default": "./dist/paypal.js"
30
+ },
31
+ "./solidgate": {
32
+ "types": "./dist/solidgate.d.ts",
33
+ "import": "./dist/solidgate.js",
34
+ "default": "./dist/solidgate.js"
19
35
  }
20
36
  },
21
37
  "files": [
@@ -48,11 +64,11 @@
48
64
  "playwright": "1.58.2",
49
65
  "typescript": "^5",
50
66
  "vitest": "^3.2.4",
51
- "@funnelsgrove/runtime": "0.49.0",
52
- "@funnelsgrove/analytics": "0.32.0"
67
+ "@funnelsgrove/runtime": "0.50.0",
68
+ "@funnelsgrove/analytics": "0.33.0"
53
69
  },
54
70
  "peerDependencies": {
55
- "@funnelsgrove/runtime": "^0.49.0",
56
- "@funnelsgrove/analytics": "^0.32.0"
71
+ "@funnelsgrove/runtime": "^0.50.0",
72
+ "@funnelsgrove/analytics": "^0.33.0"
57
73
  }
58
74
  }