@funnelsgrove/payments 0.73.0 → 0.75.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
@@ -128,6 +128,16 @@ dialog presentation. A PayPal-only Offer Set
128
128
  uses `PayPalCheckoutDialog` around the same native checkout, without creating a
129
129
  Stripe session. The funnel owns opening the dialog and post-success navigation.
130
130
 
131
+ A Paddle-only Offer Set uses `PaddleCheckoutDialog` around `PaddleCheckout`, with
132
+ `resolvePublishedBillingRuntime(...).paddleOptionsByPlanKey[planKey]` as its `option`.
133
+ Mounting it creates the attempt's Paddle transaction and opens it with Paddle.js inline
134
+ checkout (`customerEmail` prefills the buyer); reopening the same selection reuses the
135
+ recorded transaction. A declined card stays in Paddle's frame. Paddle's
136
+ `checkout.completed` only starts server status polling, and `onSuccess` runs once the
137
+ server reports `succeeded`. `onClose` closes the surface when the checkout cannot
138
+ continue. `readPendingPaddleCheckout` returns a paid but unconfirmed plan, which the paywall
139
+ keeps selected without offering another purchase. Paddle discounts are not mapped.
140
+
131
141
  Use `completeStripeOneClickPayment` for normal post-checkout one-click upsells. It delegates the charge to `funnelSdkService.chargeOneClickPayment` and owns any required Stripe confirmation. Pass its optional `checkoutAnalytics` context to let the shared package emit `checkout_completed` only after `succeeded`, including after required confirmation. The context uses `StripeSubscriptionCheckoutAnalyticsContext`; completion is deduplicated by PaymentIntent ID, and analytics failures do not fail the payment. Funnel code supplies the context and completes its step; the shared package owns the analytics callback. `chargeStripeOneClickPayment` remains the lower-level charge-only primitive.
132
142
 
133
143
  Solidgate browser checkout is available for controlled provider-routed funnels through
@@ -1 +1 @@
1
- export declare const PAYMENTS_PACKAGE_VERSION = "0.73.0";
1
+ export declare const PAYMENTS_PACKAGE_VERSION = "0.75.0";
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/generate-package-version.mjs.
2
- export const PAYMENTS_PACKAGE_VERSION = "0.73.0";
2
+ export const PAYMENTS_PACKAGE_VERSION = "0.75.0";
package/dist/index.d.ts CHANGED
@@ -24,3 +24,6 @@ export * from './components/CreatorCodeField.js';
24
24
  export { PayPalCheckoutDialog } from './providers/paypal/PayPalCheckoutDialog.js';
25
25
  export { PayPalCheckout, type PayPalCheckoutProps } from './providers/paypal/PayPalCheckout.js';
26
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';
package/dist/index.js CHANGED
@@ -25,3 +25,6 @@ export * from './components/CreatorCodeField.js';
25
25
  export { PayPalCheckoutDialog } from './providers/paypal/PayPalCheckoutDialog.js';
26
26
  export { PayPalCheckout } from './providers/paypal/PayPalCheckout.js';
27
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';
@@ -0,0 +1,18 @@
1
+ import { type PaddleCheckoutInput } from './paddleCheckout.service.js';
2
+ export type PaddleCheckoutProps = PaddleCheckoutInput & {
3
+ onSuccess: () => void;
4
+ /** Closes the surrounding checkout when this one cannot continue, e.g. an existing subscription. */
5
+ onClose: () => void;
6
+ /** Prefills Paddle's email step when the funnel already knows the buyer. */
7
+ customerEmail?: string | null;
8
+ /** Hide the plan caption when the surrounding surface already shows it. */
9
+ showSummary?: boolean;
10
+ /** True while a payment made in the frame awaits server confirmation. */
11
+ onPendingChange?: (pending: boolean) => void;
12
+ };
13
+ /**
14
+ * Paddle.js inline checkout for one attempt. The frame collects payment; only the
15
+ * server status read completes it (BILL-PADDLE-BR-004). A keyed instance owns one
16
+ * plan selection; reopening the same selection reuses the recorded transaction.
17
+ */
18
+ export declare function PaddleCheckout(props: PaddleCheckoutProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,218 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useId, useRef, useState } from 'react';
4
+ import { completePaywallCheckout, retainPaywallCheckout } from '@funnelsgrove/runtime';
5
+ import { CheckoutErrorOverlay } from '../../components/CheckoutErrorOverlay.js';
6
+ import { openPaddleCheckout } from './paddleSdk.js';
7
+ import { PaddleCheckoutRequestError, preparePaddleCheckout, readPendingPaddleCheckout, storePendingPaddleCheckout, verifyPaddleCheckout } from './paddleCheckout.service.js';
8
+ const POLL_ATTEMPTS = 20;
9
+ const POLL_INTERVAL_MS = 1500;
10
+ const UNAVAILABLE = { action: 'retry', category: 'platform_failure', message: 'Unable to load the secure checkout. Please try again.' };
11
+ const UNCONFIRMED = { action: 'check', category: 'platform_failure', message: 'We are still confirming your payment. Check its status before trying another purchase.' };
12
+ /**
13
+ * Paddle.js inline checkout for one attempt. The frame collects payment; only the
14
+ * server status read completes it (BILL-PADDLE-BR-004). A keyed instance owns one
15
+ * plan selection; reopening the same selection reuses the recorded transaction.
16
+ */
17
+ export function PaddleCheckout(props) {
18
+ const frameTarget = `fg-paddle-frame-${useId().replace(/[^a-zA-Z0-9_-]/g, '')}`;
19
+ const callbacks = useRef(props);
20
+ callbacks.current = props;
21
+ const [state, setState] = useState('loading');
22
+ const [problem, setProblem] = useState(null);
23
+ const [retry, setRetry] = useState(0);
24
+ const [summary, setSummary] = useState(props.option.summary);
25
+ const checkRef = useRef(null);
26
+ const inputKey = JSON.stringify([props.option, props.environment, props.funnelEndUserId, props.offerSetId, props.funnelPlanKey, props.checkoutType, props.runtimeConfig]);
27
+ useEffect(() => {
28
+ var _a, _b, _c;
29
+ const pending = readPendingPaddleCheckout(callbacks.current);
30
+ const input = pending
31
+ ? Object.assign(Object.assign({}, callbacks.current), { option: pending.option, offerSetId: pending.offerSetId, funnelPlanKey: pending.funnelPlanKey }) : callbacks.current;
32
+ setSummary(input.option.summary);
33
+ const controller = new AbortController();
34
+ const { signal } = controller;
35
+ const storageKey = `fg-paddle:${input.environment}:${((_a = input.runtimeConfig) === null || _a === void 0 ? void 0 : _a.funnelId) || ''}:${input.funnelEndUserId}:${input.offerSetId}:${input.funnelPlanKey}:${input.option.paymentProfileId}:${input.option.providerPlanId}`;
36
+ let idempotencyKey = crypto.randomUUID();
37
+ let attemptId = null;
38
+ let paid = false;
39
+ let finished = false;
40
+ let verifying = false;
41
+ let closeFrame = null;
42
+ try {
43
+ const saved = JSON.parse(sessionStorage.getItem(storageKey) || 'null');
44
+ if (saved && typeof saved === 'object') {
45
+ const { key, attemptId: savedAttemptId } = saved;
46
+ if (typeof key === 'string' && key)
47
+ idempotencyKey = key;
48
+ if (typeof savedAttemptId === 'string' && savedAttemptId)
49
+ attemptId = savedAttemptId;
50
+ }
51
+ }
52
+ catch ( /* The in-memory key still protects retries within this mount. */_d) { /* The in-memory key still protects retries within this mount. */ }
53
+ if (pending) {
54
+ idempotencyKey = pending.idempotencyKey;
55
+ attemptId = pending.attemptId;
56
+ paid = true;
57
+ }
58
+ const persist = () => {
59
+ try {
60
+ sessionStorage.setItem(storageKey, JSON.stringify({ key: idempotencyKey, attemptId }));
61
+ }
62
+ catch ( /* Optional persistence. */_a) { /* Optional persistence. */ }
63
+ storePendingPaddleCheckout(input, paid && attemptId ? {
64
+ option: input.option, offerSetId: input.offerSetId, funnelPlanKey: input.funnelPlanKey, attemptId, idempotencyKey,
65
+ } : null);
66
+ };
67
+ persist();
68
+ const fail = (next) => {
69
+ var _a, _b;
70
+ if (signal.aborted || finished)
71
+ return;
72
+ closeFrame === null || closeFrame === void 0 ? void 0 : closeFrame();
73
+ closeFrame = null;
74
+ setProblem(next);
75
+ setState('problem');
76
+ if (!paid)
77
+ (_b = (_a = callbacks.current).onPendingChange) === null || _b === void 0 ? void 0 : _b.call(_a, false);
78
+ };
79
+ const failRequest = (error, fallback) => {
80
+ if (!(error instanceof PaddleCheckoutRequestError)) {
81
+ fail(fallback);
82
+ return;
83
+ }
84
+ fail(error.code === 'checkout_outcome_unresolved' ? Object.assign(Object.assign({}, UNCONFIRMED), { message: error.message }) : { action: 'close', category: error.code === 'already_subscribed_to_product' ? 'existing_subscription' : 'session_failure', message: error.message });
85
+ };
86
+ const onEvent = (event) => {
87
+ var _a, _b, _c;
88
+ if (signal.aborted || finished)
89
+ return;
90
+ const name = (_a = event.name) !== null && _a !== void 0 ? _a : event.type;
91
+ // A declined card stays payable inside the frame; only completion or a frame error needs the server.
92
+ if (name === 'checkout.completed') {
93
+ paid = true;
94
+ persist();
95
+ (_c = (_b = callbacks.current).onPendingChange) === null || _c === void 0 ? void 0 : _c.call(_b, true);
96
+ void verify('poll');
97
+ }
98
+ else if (name === 'checkout.error') {
99
+ void verify('retry');
100
+ }
101
+ };
102
+ const open = async () => {
103
+ var _a;
104
+ setProblem(null);
105
+ setState('loading');
106
+ // The same idempotency key returns the recorded transaction, which also restores a lost initialization.
107
+ const attempt = await preparePaddleCheckout(input, idempotencyKey, signal);
108
+ if (signal.aborted)
109
+ return;
110
+ attemptId = attempt.attemptId;
111
+ persist();
112
+ retainPaywallCheckout('paddle', attempt.attemptId, input.option.paymentProfileId);
113
+ closeFrame === null || closeFrame === void 0 ? void 0 : closeFrame();
114
+ const email = (_a = callbacks.current.customerEmail) === null || _a === void 0 ? void 0 : _a.trim();
115
+ const close = await openPaddleCheckout({
116
+ clientToken: attempt.clientToken,
117
+ environment: input.option.environment,
118
+ onEvent,
119
+ options: Object.assign(Object.assign({ transactionId: attempt.transactionId }, (email ? { customer: { email } } : {})), { settings: {
120
+ displayMode: 'inline', frameTarget, frameInitialHeight: 450, variant: 'one-page',
121
+ frameStyle: 'width:100%; min-width:312px; background-color:transparent; border:none;',
122
+ } }),
123
+ });
124
+ if (signal.aborted) {
125
+ close();
126
+ return;
127
+ }
128
+ closeFrame = close;
129
+ setState('ready');
130
+ };
131
+ /** `whilePayable`: reopen the frame, offer a retry after a frame error, or keep polling after completion. */
132
+ const verify = async (whilePayable) => {
133
+ var _a, _b;
134
+ if (!attemptId || verifying || signal.aborted || finished)
135
+ return;
136
+ verifying = true;
137
+ setProblem(null);
138
+ setState('verifying');
139
+ try {
140
+ for (let index = 0; index < POLL_ATTEMPTS && !signal.aborted; index += 1) {
141
+ const status = await verifyPaddleCheckout(input, attemptId, signal);
142
+ if (signal.aborted)
143
+ return;
144
+ if (status === 'succeeded') {
145
+ const embedded = await completePaywallCheckout('paddle', attemptId, { signal });
146
+ if (signal.aborted)
147
+ return;
148
+ finished = true;
149
+ closeFrame === null || closeFrame === void 0 ? void 0 : closeFrame();
150
+ closeFrame = null;
151
+ setState('success');
152
+ storePendingPaddleCheckout(input, null);
153
+ try {
154
+ sessionStorage.removeItem(storageKey);
155
+ }
156
+ catch ( /* Optional persistence. */_c) { /* Optional persistence. */ }
157
+ (_b = (_a = callbacks.current).onPendingChange) === null || _b === void 0 ? void 0 : _b.call(_a, false);
158
+ if (!embedded)
159
+ callbacks.current.onSuccess();
160
+ return;
161
+ }
162
+ if (status === 'expired') {
163
+ // A canceled transaction cannot be paid; the next try starts a new attempt.
164
+ attemptId = null;
165
+ paid = false;
166
+ idempotencyKey = crypto.randomUUID();
167
+ persist();
168
+ fail({ action: 'retry', category: 'session_failure', message: 'This checkout expired before payment. Start again to pay.' });
169
+ return;
170
+ }
171
+ if (status === 'requires_payment' && !paid) {
172
+ if (whilePayable === 'retry') {
173
+ fail(UNAVAILABLE);
174
+ return;
175
+ }
176
+ if (whilePayable === 'open') {
177
+ verifying = false;
178
+ await open();
179
+ return;
180
+ }
181
+ }
182
+ await new Promise(resolve => {
183
+ const done = () => { clearTimeout(timeout); signal.removeEventListener('abort', done); resolve(); };
184
+ const timeout = setTimeout(done, POLL_INTERVAL_MS);
185
+ signal.addEventListener('abort', done, { once: true });
186
+ });
187
+ }
188
+ fail(UNCONFIRMED);
189
+ }
190
+ catch (error) {
191
+ failRequest(error, paid ? UNCONFIRMED : UNAVAILABLE);
192
+ }
193
+ finally {
194
+ verifying = false;
195
+ }
196
+ };
197
+ checkRef.current = () => { void verify('open'); };
198
+ if (attemptId) {
199
+ if (paid)
200
+ (_c = (_b = callbacks.current).onPendingChange) === null || _c === void 0 ? void 0 : _c.call(_b, true);
201
+ retainPaywallCheckout('paddle', attemptId, input.option.paymentProfileId);
202
+ void verify('open');
203
+ }
204
+ else {
205
+ void open().catch(error => failRequest(error, UNAVAILABLE));
206
+ }
207
+ return () => { controller.abort(); checkRef.current = null; closeFrame === null || closeFrame === void 0 ? void 0 : closeFrame(); };
208
+ }, [inputKey, retry, frameTarget]);
209
+ const primary = (problem === null || problem === void 0 ? void 0 : problem.action) === 'check' ? { label: 'Check payment status', onClick: () => { var _a; return (_a = checkRef.current) === null || _a === void 0 ? void 0 : _a.call(checkRef); } }
210
+ : (problem === null || problem === void 0 ? void 0 : problem.action) === 'close' ? { label: 'Close', onClick: () => callbacks.current.onClose() }
211
+ : { label: 'Try again', onClick: () => setRetry(value => value + 1) };
212
+ return _jsxs("section", { "aria-label": 'Secure payment', className: 'fg-paddle-checkout', "aria-busy": state === 'loading' || state === 'verifying', children: [props.showSummary !== false ? _jsx("p", { className: 'fg-paddle-checkout-summary', children: summary }) : null, _jsx("div", { className: frameTarget, hidden: state !== 'loading' && state !== 'ready' }), state === 'loading' ? _jsx("p", { className: 'fg-paddle-checkout-status', role: 'status', children: "Loading secure checkout\u2026" }) : null, state === 'verifying' ? _jsx("p", { className: 'fg-paddle-checkout-status', role: 'status', children: "Confirming your subscription\u2026" }) : null, state === 'success' ? _jsx("p", { className: 'fg-paddle-checkout-status', role: 'status', children: "Subscription confirmed." }) : null, state === 'problem' && problem ? _jsx(CheckoutErrorOverlay, { category: problem.category, message: problem.message, dismissible: false, primary: primary, onDismiss: () => undefined }) : null, _jsx("style", { children: paddleCheckoutStyles })] });
213
+ }
214
+ const paddleCheckoutStyles = `
215
+ .fg-paddle-checkout { position:relative; display:flex; flex-direction:column; gap:8px; min-height:450px; color:#303136; }
216
+ .fg-paddle-checkout-summary { margin:0; color:#020203; font-size:16px; font-weight:700; line-height:1.4; text-align:center; }
217
+ .fg-paddle-checkout-status { margin:0; padding:24px 8px; font-size:16px; line-height:1.5; text-align:center; }
218
+ `;
@@ -0,0 +1,8 @@
1
+ import { type ReactNode } from 'react';
2
+ /** The shared checkout surface for an Offer Set with only a Paddle binding; Paddle's frame lists its own payment methods. */
3
+ export declare function PaddleCheckoutDialog({ children, title, closeAriaLabel, onClose }: {
4
+ children: ReactNode;
5
+ title: string;
6
+ closeAriaLabel: string;
7
+ onClose: () => void;
8
+ }): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,19 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useEffect, useId } from 'react';
4
+ import { sharedStripeCheckoutV2Styles } from '../stripe/components/SharedStripeCheckoutV2.styles.js';
5
+ /** The shared checkout surface for an Offer Set with only a Paddle binding; Paddle's frame lists its own payment methods. */
6
+ export function PaddleCheckoutDialog({ children, title, closeAriaLabel, onClose }) {
7
+ const titleId = useId();
8
+ useEffect(() => {
9
+ const handleKey = (event) => { if (event.key === 'Escape')
10
+ onClose(); };
11
+ window.addEventListener('keydown', handleKey);
12
+ return () => window.removeEventListener('keydown', handleKey);
13
+ }, [onClose]);
14
+ return _jsxs(_Fragment, { children: [_jsx("div", { className: 'shared-checkout-v2-overlay', children: _jsx("div", { className: 'shared-checkout-v2-dialog', role: 'dialog', "aria-modal": 'true', "aria-labelledby": titleId, children: _jsxs("div", { className: 'shared-checkout-v2-shell', children: [_jsxs("header", { className: 'shared-checkout-v2-header', children: [_jsx("button", { type: 'button', className: 'shared-checkout-v2-close', "aria-label": closeAriaLabel, onClick: onClose, children: _jsx("span", { "aria-hidden": 'true' }) }), _jsx("h2", { id: titleId, children: title })] }), _jsx("div", { className: 'shared-checkout-v2-payment fg-paddle-dialog-payment', children: children })] }) }) }), _jsxs("style", { children: [sharedStripeCheckoutV2Styles, paddleDialogStyles] })] });
15
+ }
16
+ // Paddle's frame needs 312px; keep it inside a 320px viewport.
17
+ const paddleDialogStyles = `
18
+ @media (max-width: 345px) { .shared-checkout-v2-payment.fg-paddle-dialog-payment { padding-left:4px; padding-right:4px; } }
19
+ `;
@@ -0,0 +1,41 @@
1
+ import { type FunnelSdkRuntimeConfigOverrides } from '@funnelsgrove/runtime';
2
+ import type { PaddleBillingOption } from '../../services/publishedBillingRuntime.service.js';
3
+ export type PaddleCheckoutInput = {
4
+ option: PaddleBillingOption;
5
+ environment: 'test' | 'live';
6
+ funnelEndUserId: string;
7
+ offerSetId: string;
8
+ funnelPlanKey: string;
9
+ /** A plan without a billing interval is a one-time purchase (BILL-PADDLE-BR-004). */
10
+ checkoutType?: 'subscription' | 'one_time';
11
+ runtimeConfig?: FunnelSdkRuntimeConfigOverrides;
12
+ };
13
+ export type PaddleCheckoutAttempt = {
14
+ attemptId: string;
15
+ transactionId: string;
16
+ clientToken: string;
17
+ };
18
+ export type PaddleCheckoutStatus = 'succeeded' | 'requires_payment' | 'verifying' | 'preparing' | 'expired';
19
+ declare const checkoutErrorMessages: {
20
+ checkout_unavailable: string;
21
+ checkout_outcome_unresolved: string;
22
+ already_subscribed_to_product: string;
23
+ };
24
+ export declare class PaddleCheckoutRequestError extends Error {
25
+ readonly code: keyof typeof checkoutErrorMessages;
26
+ constructor(code: keyof typeof checkoutErrorMessages);
27
+ }
28
+ /** Creates the attempt's Paddle transaction, or returns the recorded one for the same idempotency key. */
29
+ export declare function preparePaddleCheckout(input: PaddleCheckoutInput, idempotencyKey: string, signal: AbortSignal): Promise<PaddleCheckoutAttempt>;
30
+ /** Only this server read proves payment (BILL-PADDLE-BR-004). */
31
+ export declare function verifyPaddleCheckout(input: PaddleCheckoutInput, attemptId: string, signal: AbortSignal): Promise<PaddleCheckoutStatus>;
32
+ /** A checkout paid inside Paddle.js whose outcome the server has not confirmed yet. */
33
+ export type PendingPaddleCheckout = Pick<PaddleCheckoutInput, 'option' | 'offerSetId' | 'funnelPlanKey'> & {
34
+ attemptId: string;
35
+ idempotencyKey: string;
36
+ };
37
+ type PendingScope = Pick<PaddleCheckoutInput, 'runtimeConfig' | 'environment' | 'funnelEndUserId'>;
38
+ /** The paywall keeps a paid-but-unconfirmed plan selected and offers no other purchase. */
39
+ export declare const readPendingPaddleCheckout: (scope: PendingScope) => PendingPaddleCheckout | null;
40
+ export declare const storePendingPaddleCheckout: (scope: PendingScope, value: PendingPaddleCheckout | null) => void;
41
+ export {};
@@ -0,0 +1,88 @@
1
+ import { FUNNEL_ID, FUNNEL_SDK_PUBLISHABLE_KEY, FUNNEL_VERSION_ID, buildMainApiUrl, resolvePreviewPaymentPublishableKey } from '@funnelsgrove/runtime';
2
+ const CLIENT_TOKEN_PREFIX = { sandbox: 'test_', production: 'live_' };
3
+ const record = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
4
+ const checkoutErrorMessages = {
5
+ checkout_unavailable: 'This checkout is no longer available. Please contact support before starting another purchase.',
6
+ checkout_outcome_unresolved: 'We are still checking this payment. Please wait or contact support before starting another purchase.',
7
+ already_subscribed_to_product: 'You already have an active subscription to this product.',
8
+ };
9
+ export class PaddleCheckoutRequestError extends Error {
10
+ constructor(code) {
11
+ super(checkoutErrorMessages[code]);
12
+ this.code = code;
13
+ this.name = 'PaddleCheckoutRequestError';
14
+ }
15
+ }
16
+ async function request(input, path, signal, body) {
17
+ var _a, _b, _c, _d;
18
+ const key = resolvePreviewPaymentPublishableKey((_b = (_a = input.runtimeConfig) === null || _a === void 0 ? void 0 : _a.funnelSdkPublishableKey) !== null && _b !== void 0 ? _b : FUNNEL_SDK_PUBLISHABLE_KEY);
19
+ const base = (_d = (_c = input.runtimeConfig) === null || _c === void 0 ? void 0 : _c.apiBaseUrl) === null || _d === void 0 ? void 0 : _d.trim().replace(/\/+$/, '');
20
+ const response = await fetch(base ? `${base}${path}` : buildMainApiUrl(path), Object.assign({ method: body ? 'POST' : 'GET', signal, headers: Object.assign(Object.assign({}, (body ? { 'content-type': 'application/json' } : {})), (key ? { 'x-sdk-publishable-key': key } : {})) }, (body ? { body: JSON.stringify(body) } : {})));
21
+ if (!response.ok) {
22
+ const failure = await response.json().catch(() => null);
23
+ if (record(failure) && (failure.code === 'checkout_unavailable'
24
+ || failure.code === 'checkout_outcome_unresolved' || failure.code === 'already_subscribed_to_product')) {
25
+ throw new PaddleCheckoutRequestError(failure.code);
26
+ }
27
+ throw new Error('Unable to reach checkout. Please try again.');
28
+ }
29
+ const result = await response.json();
30
+ if (!record(result))
31
+ throw new Error('Invalid checkout response.');
32
+ return result;
33
+ }
34
+ /** Creates the attempt's Paddle transaction, or returns the recorded one for the same idempotency key. */
35
+ export async function preparePaddleCheckout(input, idempotencyKey, signal) {
36
+ var _a, _b, _c, _d;
37
+ const funnelVersionId = ((_b = (_a = input.runtimeConfig) === null || _a === void 0 ? void 0 : _a.funnelVersionId) === null || _b === void 0 ? void 0 : _b.trim()) || FUNNEL_VERSION_ID.trim();
38
+ const result = await request(input, '/sdk/public/v2/payments/checkout-sessions', signal, Object.assign(Object.assign({ provider: 'paddle', checkoutType: (_c = input.checkoutType) !== null && _c !== void 0 ? _c : 'subscription', uiMode: 'custom', environment: input.environment, paymentProfileId: input.option.paymentProfileId, providerPlanId: input.option.providerPlanId, funnelId: ((_d = input.runtimeConfig) === null || _d === void 0 ? void 0 : _d.funnelId) || FUNNEL_ID }, (funnelVersionId ? { funnelVersionId } : {})), { funnelEndUserId: input.funnelEndUserId, offerSetId: input.offerSetId, planKey: input.funnelPlanKey, idempotencyKey, returnUrl: window.location.href, successUrl: window.location.href, failUrl: window.location.href }));
39
+ const initialization = result.initialization;
40
+ if (typeof result.attemptId !== 'string' || !result.attemptId || !record(initialization)
41
+ || initialization.kind !== 'paddle' || initialization.environment !== input.option.environment
42
+ // The server's token is current even if the seller rotated it after publish (BILL-PADDLE-BR-002).
43
+ || typeof initialization.clientToken !== 'string'
44
+ || !initialization.clientToken.startsWith(CLIENT_TOKEN_PREFIX[input.option.environment])
45
+ || typeof initialization.transactionId !== 'string' || !initialization.transactionId.startsWith('txn_'))
46
+ throw new Error('Invalid checkout response.');
47
+ return { attemptId: result.attemptId, transactionId: initialization.transactionId, clientToken: initialization.clientToken };
48
+ }
49
+ /** Only this server read proves payment (BILL-PADDLE-BR-004). */
50
+ export async function verifyPaddleCheckout(input, attemptId, signal) {
51
+ var _a;
52
+ const query = new URLSearchParams({ provider: 'paddle', funnelId: ((_a = input.runtimeConfig) === null || _a === void 0 ? void 0 : _a.funnelId) || FUNNEL_ID, funnelEndUserId: input.funnelEndUserId });
53
+ const result = await request(input, `/sdk/public/v2/payments/checkout-sessions/${encodeURIComponent(attemptId)}?${query}`, signal);
54
+ if (result.attemptId !== attemptId)
55
+ throw new Error('Invalid checkout response.');
56
+ if (result.status === 'failed')
57
+ throw new PaddleCheckoutRequestError('checkout_unavailable');
58
+ if (result.status !== 'succeeded' && result.status !== 'requires_payment' && result.status !== 'verifying'
59
+ && result.status !== 'preparing' && result.status !== 'expired')
60
+ throw new Error('Invalid checkout response.');
61
+ return result.status;
62
+ }
63
+ const pendingKey = (scope) => { var _a; return `fg-paddle-pending:${scope.environment}:${((_a = scope.runtimeConfig) === null || _a === void 0 ? void 0 : _a.funnelId) || FUNNEL_ID}:${scope.funnelEndUserId}`; };
64
+ /** The paywall keeps a paid-but-unconfirmed plan selected and offers no other purchase. */
65
+ export const readPendingPaddleCheckout = (scope) => {
66
+ try {
67
+ const value = JSON.parse(sessionStorage.getItem(pendingKey(scope)) || 'null');
68
+ if (!record(value) || !record(value.option)
69
+ || ![value.offerSetId, value.funnelPlanKey, value.idempotencyKey, value.attemptId, value.option.paymentProfileId,
70
+ value.option.providerPlanId, value.option.clientToken, value.option.environment, value.option.currency, value.option.summary]
71
+ .every(field => typeof field === 'string' && field.length > 0)
72
+ || typeof value.option.amountMinor !== 'number')
73
+ return null;
74
+ return value;
75
+ }
76
+ catch (_a) {
77
+ return null;
78
+ }
79
+ };
80
+ export const storePendingPaddleCheckout = (scope, value) => {
81
+ try {
82
+ if (value)
83
+ sessionStorage.setItem(pendingKey(scope), JSON.stringify(value));
84
+ else
85
+ sessionStorage.removeItem(pendingKey(scope));
86
+ }
87
+ catch ( /* Browser storage can be unavailable; the mounted checkout still retains ownership. */_a) { /* Browser storage can be unavailable; the mounted checkout still retains ownership. */ }
88
+ };
@@ -0,0 +1,40 @@
1
+ export type PaddleEvent = {
2
+ name?: string;
3
+ type?: string;
4
+ data?: unknown;
5
+ error?: unknown;
6
+ };
7
+ export type PaddleCheckoutOpenOptions = {
8
+ transactionId: string;
9
+ customer?: {
10
+ email: string;
11
+ };
12
+ settings: {
13
+ displayMode: 'inline';
14
+ frameTarget: string;
15
+ frameInitialHeight: number;
16
+ frameStyle: string;
17
+ variant: 'one-page';
18
+ };
19
+ };
20
+ export type PaddleSdk = {
21
+ Environment: {
22
+ set: (environment: 'sandbox') => void;
23
+ };
24
+ Initialize: (options: {
25
+ token: string;
26
+ eventCallback: (event: PaddleEvent) => void;
27
+ }) => void;
28
+ Checkout: {
29
+ open: (options: PaddleCheckoutOpenOptions) => void;
30
+ close: () => void;
31
+ };
32
+ };
33
+ export type PaddleEnvironment = 'sandbox' | 'production';
34
+ /** Opens one inline checkout; the returned function closes it and detaches its events. */
35
+ export declare function openPaddleCheckout(input: {
36
+ clientToken: string;
37
+ environment: PaddleEnvironment;
38
+ options: PaddleCheckoutOpenOptions;
39
+ onEvent: (event: PaddleEvent) => void;
40
+ }): Promise<() => void>;
@@ -0,0 +1,62 @@
1
+ const PADDLE_JS_URL = 'https://cdn.paddle.com/paddle/v2/paddle.js';
2
+ const readPaddle = () => window.Paddle;
3
+ let loading = null;
4
+ // Paddle.Initialize can run once per page, so one dispatcher serves the open checkout.
5
+ const initialized = new WeakMap();
6
+ function loadPaddleSdk() {
7
+ const existing = readPaddle();
8
+ if (existing === null || existing === void 0 ? void 0 : existing.Checkout)
9
+ return Promise.resolve(existing);
10
+ if (loading)
11
+ return loading;
12
+ loading = new Promise((resolve, reject) => {
13
+ const script = document.createElement('script');
14
+ script.src = PADDLE_JS_URL;
15
+ script.async = true;
16
+ const failed = () => { clearTimeout(timeout); script.remove(); reject(new Error('Unable to load Paddle. Please try again.')); };
17
+ const timeout = setTimeout(failed, 20000);
18
+ script.onerror = failed;
19
+ script.onload = () => {
20
+ clearTimeout(timeout);
21
+ const sdk = readPaddle();
22
+ if (!(sdk === null || sdk === void 0 ? void 0 : sdk.Checkout)) {
23
+ failed();
24
+ return;
25
+ }
26
+ resolve(sdk);
27
+ };
28
+ document.head.appendChild(script);
29
+ });
30
+ // Once loaded, `window.Paddle` is the cache; only an in-flight load is shared.
31
+ void loading.then(() => { loading = null; }, () => { loading = null; });
32
+ return loading;
33
+ }
34
+ /** Opens one inline checkout; the returned function closes it and detaches its events. */
35
+ export async function openPaddleCheckout(input) {
36
+ const sdk = await loadPaddleSdk();
37
+ let state = initialized.get(sdk);
38
+ if (!state) {
39
+ if (input.environment === 'sandbox')
40
+ sdk.Environment.set('sandbox');
41
+ const created = { token: input.clientToken, environment: input.environment, listener: null };
42
+ sdk.Initialize({ token: input.clientToken, eventCallback: event => { var _a; return (_a = created.listener) === null || _a === void 0 ? void 0 : _a.call(created, event); } });
43
+ initialized.set(sdk, created);
44
+ state = created;
45
+ }
46
+ else if (state.token !== input.clientToken || state.environment !== input.environment) {
47
+ throw new Error('This page already uses another Paddle account. Reload the page to continue.');
48
+ }
49
+ const current = state;
50
+ const listener = input.onEvent;
51
+ current.listener = listener;
52
+ sdk.Checkout.open(input.options);
53
+ return () => {
54
+ if (current.listener !== listener)
55
+ return;
56
+ current.listener = null;
57
+ try {
58
+ sdk.Checkout.close();
59
+ }
60
+ catch ( /* The frame may already be gone. */_a) { /* The frame may already be gone. */ }
61
+ };
62
+ }
@@ -2,6 +2,7 @@ import { type CSSProperties, type ReactNode } from 'react';
2
2
  import type { Stripe } from '@stripe/stripe-js';
3
3
  import type { StripeCheckoutErrorDetails } from '../services/stripeCheckoutError.js';
4
4
  import { type StripeSubscriptionCheckoutAnalyticsContext } from '../services/checkoutCompletionAnalytics.service.js';
5
+ import { type StripeWalletFirstCheckoutProps } from './StripeWalletFirstCheckout.js';
5
6
  import { type SharedStripeCheckoutV2Copy } from './checkout-v2.content.js';
6
7
  export type { SharedStripeCheckoutV2Copy } from './checkout-v2.content.js';
7
8
  export type SharedCheckoutV2CssVars = CSSProperties & {
@@ -36,6 +37,8 @@ export type SharedStripeCheckoutV2DialogProps = {
36
37
  onCustomerEmailCommit?: (email: string) => Promise<string | null | void>;
37
38
  onError?: (message: string | null, details?: StripeCheckoutErrorDetails) => void;
38
39
  onInactiveCheckoutSession?: () => void;
40
+ /** The selected payment method block, e.g. to show PayPal's own renewal terms while PayPal is selected. */
41
+ onMethodChange?: StripeWalletFirstCheckoutProps['onMethodChange'];
39
42
  onPaymentInfoSubmitted?: () => void | Promise<void>;
40
43
  onSuccess?: () => void | Promise<void>;
41
44
  paymentMethodLabels?: readonly string[];
@@ -44,6 +47,8 @@ export type SharedStripeCheckoutV2DialogProps = {
44
47
  paypalPending?: boolean;
45
48
  paypalButtonLabel: string;
46
49
  paypalLabel: string;
50
+ /** Total of the native PayPal plan, shown instead of `totalValue` and without the discount while PayPal is selected. */
51
+ paypalTotalValue?: string;
47
52
  promoActive?: boolean;
48
53
  processingLabel: string;
49
54
  promoCode: string;
@@ -66,6 +66,7 @@ export function SharedStripeCheckoutV2Dialog(_a) {
66
66
  // The inline form has no dialog to close: only an explicit wallet handler runs there.
67
67
  onCancel: presentation === 'inline' ? onWalletCancel : onWalletCancel !== null && onWalletCancel !== void 0 ? onWalletCancel : onClose,
68
68
  onError: props.onError,
69
+ onMethodChange: props.onMethodChange,
69
70
  onPaymentInfoSubmitted: props.onPaymentInfoSubmitted,
70
71
  onSuccess: props.onSuccess,
71
72
  initialWalletAvailable: props.initialWalletAvailable,
@@ -84,23 +85,26 @@ export function SharedStripeCheckoutV2Dialog(_a) {
84
85
  if (presentation === 'inline')
85
86
  return _jsx(InlineCheckout, { title: props.title, checkout: walletFirst });
86
87
  const promoActive = (_g = props.promoActive) !== null && _g !== void 0 ? _g : (props.discountPercent > 0 && props.promoCode.trim().length > 0);
87
- return (_jsx(StripeCheckoutDialog, Object.assign({}, walletFirst, { title: props.title, closeAriaLabel: props.closeAriaLabel, onClose: onClose, guaranteeLabel: props.secureLabel, summary: {
88
- promoActive,
89
- countdownLabel: `${props.discountPercent}% ${props.countdownLabel}`.trim(),
90
- remainingSeconds: props.remainingSeconds,
91
- // The compact variant never showed the satisfaction line.
92
- satisfactionPercent: variant === 'standard' ? props.satisfactionPercent : undefined,
93
- satisfactionLabel: variant === 'standard' ? props.satisfactionLabel : undefined,
94
- originalPriceLabel: props.originalPriceLabel,
95
- originalPriceValue: props.originalPriceValue,
96
- discountLabel: props.discountLabel,
97
- discountAmountLabel: props.discountAmountLabel,
98
- promoCodeLabel: props.promoCodeLabel,
99
- promoCode: props.promoCode,
100
- totalLabel: props.totalLabel,
101
- totalValue: props.totalValue,
102
- savedLabel: props.savedLabel,
103
- } })));
88
+ const summary = {
89
+ promoActive,
90
+ countdownLabel: `${props.discountPercent}% ${props.countdownLabel}`.trim(),
91
+ remainingSeconds: props.remainingSeconds,
92
+ // The compact variant never showed the satisfaction line.
93
+ satisfactionPercent: variant === 'standard' ? props.satisfactionPercent : undefined,
94
+ satisfactionLabel: variant === 'standard' ? props.satisfactionLabel : undefined,
95
+ originalPriceLabel: props.originalPriceLabel,
96
+ originalPriceValue: props.originalPriceValue,
97
+ discountLabel: props.discountLabel,
98
+ discountAmountLabel: props.discountAmountLabel,
99
+ promoCodeLabel: props.promoCodeLabel,
100
+ promoCode: props.promoCode,
101
+ totalLabel: props.totalLabel,
102
+ totalValue: props.totalValue,
103
+ savedLabel: props.savedLabel,
104
+ };
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 })));
104
108
  }
105
109
  /** The inline V2 form started the checkout when it rendered; the wallet-first block keeps that. */
106
110
  function InlineCheckout({ checkout, title }) {
@@ -22,10 +22,12 @@ export type StripeCheckoutDialogProps = Omit<StripeWalletFirstCheckoutProps, 'ch
22
22
  closeAriaLabel: string;
23
23
  onClose: () => void;
24
24
  summary: StripeCheckoutDialogSummary;
25
+ /** Shown in place of `summary` while PayPal is selected: the native PayPal plan's own terms (BILL-PAYPAL-BR-006). */
26
+ paypalSummary?: StripeCheckoutDialogSummary;
25
27
  /** Line under the payment methods, e.g. a money-back guarantee. */
26
28
  guaranteeLabel?: string;
27
29
  /** A failure outside the payment form, e.g. the Checkout Session could not be created. */
28
30
  error?: string | null;
29
31
  };
30
- export declare function StripeCheckoutDialog({ title, closeAriaLabel, onClose, summary, guaranteeLabel, error, ...checkout }: StripeCheckoutDialogProps): import("react/jsx-runtime").JSX.Element;
32
+ export declare function StripeCheckoutDialog({ title, closeAriaLabel, onClose, summary: checkoutSummary, paypalSummary, guaranteeLabel, error, ...checkout }: StripeCheckoutDialogProps): import("react/jsx-runtime").JSX.Element;
31
33
  export declare const stripeCheckoutDialogStyles = "\n.fgcd-overlay {\n --fgcd-soft: color-mix(in srgb, var(--fgcd-theme) 10%, #fff);\n --fgcd-bg: color-mix(in srgb, var(--fgcd-theme) 4%, #f6f6f9);\n --fgcd-border: color-mix(in srgb, var(--fgcd-theme) 12%, #e4e4ea);\n --fgcd-text: #101010;\n --fgcd-muted: #66646e;\n position: fixed; inset: 0; z-index: 80; display: flex; align-items: flex-end; justify-content: center;\n background: rgb(16 12 30 / 50%); animation: fgcd-fade-in .2s ease-out;\n}\n.fgcd-sheet {\n width: min(100%, 480px); max-height: calc(100dvh - 24px); overflow-y: auto; overscroll-behavior: contain;\n border-radius: 28px 28px 0 0; background: var(--fgcd-bg); box-sizing: border-box; color: var(--fgcd-text);\n animation: fgcd-sheet-up .32s cubic-bezier(.25, .8, .25, 1);\n}\n.fgcd-sheet *, .fgcd-sheet *::before, .fgcd-sheet *::after { box-sizing: border-box; }\n.fgcd-content { display: flex; flex-direction: column; gap: 14px; padding: 12px 24px calc(34px + env(safe-area-inset-bottom, 0px)); }\n@media (min-width: 640px) {\n .fgcd-overlay { align-items: center; padding: 24px; }\n .fgcd-sheet { max-height: calc(100dvh - 48px); border-radius: 28px; animation: fgcd-pop .24s cubic-bezier(.2, .9, .3, 1.1); }\n .fgcd-content { padding: 20px 28px 28px; }\n .fgcd-grabber { display: none; }\n}\n@keyframes fgcd-sheet-up { from { transform: translateY(100%); } }\n@keyframes fgcd-pop { from { opacity: 0; transform: translateY(12px) scale(.98); } }\n@keyframes fgcd-fade-in { from { opacity: 0; } }\n@media (prefers-reduced-motion: reduce) { .fgcd-sheet, .fgcd-overlay { animation: none; } }\n.fgcd-grabber { align-self: center; width: 40px; height: 5px; border-radius: 3px; background: color-mix(in srgb, var(--fgcd-theme) 18%, #ddd); }\n.fgcd-head { position: relative; display: flex; align-items: center; justify-content: center; min-height: 40px; padding: 0 44px; }\n.fgcd-head h2 { margin: 0; font-size: 20px; font-weight: 800; line-height: 1.2; text-align: center; }\n.fgcd-close { position: absolute; left: 0; top: 0; display: grid; place-items: center; width: 40px; height: 40px; padding: 0; border: 0; border-radius: 12px; background: #fff; cursor: pointer; }\n.fgcd-close svg { width: 16px; height: 16px; fill: none; stroke: #4a4660; stroke-width: 1.8; stroke-linecap: round; }\n.fgcd-close:focus-visible { outline: 3px solid var(--fgcd-theme); outline-offset: 2px; }\n.fgcd-timer { display: flex; align-items: center; justify-content: center; gap: 10px; margin: 0; padding: 10px 14px; border: 1px solid var(--fgcd-border); border-radius: 14px; background: #fff; box-shadow: 0 4px 12px rgb(16 12 30 / 6%); font-size: 15px; font-weight: 700; }\n.fgcd-timer > span:first-child { font-size: 18px; }\n.fgcd-timer-value { padding: 3px 8px; border-radius: 8px; background: var(--fgcd-soft); color: var(--fgcd-theme); font-size: 16px; font-weight: 800; letter-spacing: .32px; font-variant-numeric: tabular-nums; }\n.fgcd-proof { margin: 0; font-size: 15px; font-weight: 700; line-height: 21px; text-align: center; }\n.fgcd-proof strong { color: var(--fgcd-theme); }\n.fgcd-summary { display: flex; flex-direction: column; gap: 10px; padding: 14px 16px; border-radius: 16px; background: #fff; }\n.fgcd-summary hr { width: 100%; margin: 0; border: 0; border-top: 1px solid var(--fgcd-border); }\n.fgcd-row, .fgcd-promo, .fgcd-total { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 0; }\n.fgcd-row--muted { color: var(--fgcd-muted); font-size: 14px; }\n.fgcd-row--discount { font-size: 15px; font-weight: 700; }\n.fgcd-row--discount strong { color: #cc2b31; font-weight: 800; }\n.fgcd-promo { padding: 9px 12px; border-radius: 10px; background: var(--fgcd-soft); color: var(--fgcd-muted); font-size: 13px; }\n.fgcd-promo strong, .fgcd-total strong { display: inline-flex; align-items: center; gap: 6px; color: var(--fgcd-text); font-weight: 800; }\n.fgcd-promo strong { font-size: 14px; letter-spacing: .42px; text-transform: uppercase; }\n.fgcd-check { width: 13px; height: 13px; }\n.fgcd-total span { font-size: 20px; font-weight: 800; }\n.fgcd-total strong { font-size: 24px; }\n.fgcd-tag { width: 20px; height: 20px; }\n.fgcd-saved { display: inline-flex; align-self: flex-end; align-items: center; gap: 6px; margin: 0; padding: 6px 12px; border-radius: 99px; background: #fde3e4; color: #b4232a; font-size: 13px; font-weight: 700; }\n.fgcd-sheet .wfc { gap: 10px; }\n.fgcd-sheet .wfc-method { border-radius: 18px; box-shadow: 0 0 0 1px var(--fgcd-border); transition: box-shadow .2s ease; }\n.fgcd-sheet .wfc-method[data-checked='true'] { box-shadow: 0 0 0 2px var(--fgcd-theme); }\n.fgcd-sheet .wfc-method-head { min-height: 58px; padding: 16px; gap: 12px; border-radius: 18px; }\n.fgcd-sheet .wfc-mark { height: 26px; }\n.fgcd-sheet .wfc-brand { width: 42px; height: 28px; border-radius: 5px; }\n.fgcd-sheet .wfc-benefits:empty { display: none; }\n.fgcd-sheet .wfc-wallet-button, .fgcd-sheet .wfc-progress { border-radius: 14px; }\n.fgcd-sheet .wfc-secure { margin-top: 10px; color: var(--fgcd-muted); font-size: 13px; }\n.fgcd-sheet .wfc-card-form .wfc-secure { display: none; }\n.fgcd-sheet .wfc-submit { min-height: 56px; border-radius: 14px; font-size: 18px; font-weight: 700; }\n.fgcd-error { margin: 0; color: #c62828; font-size: 14px; text-align: center; }\n.fgcd-guarantee { display: flex; align-items: center; justify-content: center; gap: 8px; margin: 0; font-size: 15px; font-weight: 700; }\n.fgcd-guarantee svg { width: 18px; height: 18px; flex: none; }\n";
@@ -22,7 +22,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
22
22
  * pass its `clientSecret` as soon as it exists (it may be prepared before the
23
23
  * dialog opens) so the wallet button is ready on open.
24
24
  */
25
- import { useCallback, useEffect, useRef } from 'react';
25
+ import { useCallback, useEffect, useRef, useState } from 'react';
26
26
  import { StripeWalletFirstCheckout } from './StripeWalletFirstCheckout.js';
27
27
  import { queueStripeSubscriptionCheckoutStarted } from '../services/checkoutCompletionAnalytics.service.js';
28
28
  import { trackCheckoutCanceled } from '../../../services/checkoutObservability.service.js';
@@ -35,8 +35,11 @@ const formatCountdown = (remainingSeconds = 0) => {
35
35
  };
36
36
  export function StripeCheckoutDialog(_a) {
37
37
  var _b, _c;
38
- var { title, closeAriaLabel, onClose, summary, guaranteeLabel, error } = _a, checkout = __rest(_a, ["title", "closeAriaLabel", "onClose", "summary", "guaranteeLabel", "error"]);
38
+ var { title, closeAriaLabel, onClose, summary: checkoutSummary, paypalSummary, guaranteeLabel, error } = _a, checkout = __rest(_a, ["title", "closeAriaLabel", "onClose", "summary", "paypalSummary", "guaranteeLabel", "error"]);
39
39
  const sheetRef = useRef(null);
40
+ // A pending PayPal payment reopens on the PayPal block, so its terms show from the first paint.
41
+ const [method, setMethod] = useState(checkout.paypalPending && checkout.paypalCheckout ? 'paypal' : null);
42
+ const summary = method === 'paypal' && paypalSummary ? paypalSummary : checkoutSummary;
40
43
  const { checkoutAnalytics, checkoutSessionId } = checkout;
41
44
  const close = useCallback(() => {
42
45
  if (checkoutAnalytics) {
@@ -99,7 +102,7 @@ export function StripeCheckoutDialog(_a) {
99
102
  const promoCode = (_c = (_b = summary.promoCode) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : '';
100
103
  const style = { '--fgcd-theme': checkout.themeColor };
101
104
  return (_jsxs("div", { className: 'fgcd-overlay', style: style, onClick: (event) => { if (event.target === event.currentTarget)
102
- close(); }, children: [_jsx("section", { ref: sheetRef, className: 'fgcd-sheet', role: 'dialog', "aria-modal": 'true', "aria-labelledby": 'fgcd-title', children: _jsxs("div", { className: 'fgcd-content', children: [_jsx("span", { className: 'fgcd-grabber', "aria-hidden": 'true' }), _jsxs("header", { className: 'fgcd-head', children: [_jsx("button", { type: 'button', className: 'fgcd-close', "aria-label": closeAriaLabel, onClick: close, children: _jsx("svg", { viewBox: '0 0 16 16', "aria-hidden": 'true', children: _jsx("path", { d: 'M3.5 3.5 12.5 12.5M12.5 3.5 3.5 12.5' }) }) }), _jsx("h2", { id: 'fgcd-title', children: title })] }), promoActive && summary.countdownLabel ? (_jsxs("p", { className: 'fgcd-timer', children: [_jsx("span", { "aria-hidden": 'true', children: "\u23F0" }), summary.countdownLabel, _jsx("span", { className: 'fgcd-timer-value', children: formatCountdown(summary.remainingSeconds) })] })) : null, summary.satisfactionPercent || summary.satisfactionLabel ? (_jsxs("p", { className: 'fgcd-proof', children: [_jsx("strong", { children: summary.satisfactionPercent }), " ", summary.satisfactionLabel] })) : null, _jsxs("div", { className: 'fgcd-summary', children: [promoActive ? (_jsxs(_Fragment, { children: [summary.originalPriceValue ? (_jsxs("p", { className: 'fgcd-row fgcd-row--muted', children: [_jsx("span", { children: summary.originalPriceLabel }), _jsx("s", { children: summary.originalPriceValue })] })) : null, summary.discountAmountLabel ? (_jsxs("p", { className: 'fgcd-row fgcd-row--discount', children: [_jsx("span", { children: summary.discountLabel }), _jsx("strong", { children: summary.discountAmountLabel })] })) : null, promoCode ? (_jsxs("p", { className: 'fgcd-promo', children: [_jsx("span", { children: summary.promoCodeLabel }), _jsxs("strong", { children: [_jsx(CheckIcon, {}), promoCode] })] })) : null, _jsx("hr", {})] })) : null, _jsxs("p", { className: 'fgcd-total', children: [_jsx("span", { children: summary.totalLabel }), _jsxs("strong", { children: [_jsx(TagIcon, {}), summary.totalValue] })] }), promoActive && summary.savedLabel ? _jsxs("p", { className: 'fgcd-saved', children: [_jsx("span", { "aria-hidden": 'true', children: "\uD83D\uDD25" }), summary.savedLabel] }) : null] }), _jsx("div", { className: 'fgcd-methods', children: _jsx(StripeWalletFirstCheckout, Object.assign({}, checkout, { checkoutSurface: 'dialog' })) }), error ? _jsx("p", { className: 'fgcd-error', role: 'alert', children: error }) : null, guaranteeLabel ? _jsxs("p", { className: 'fgcd-guarantee', children: [_jsx(LockIcon, {}), guaranteeLabel] }) : null] }) }), _jsx("style", { children: stripeCheckoutDialogStyles })] }));
105
+ close(); }, children: [_jsx("section", { ref: sheetRef, className: 'fgcd-sheet', role: 'dialog', "aria-modal": 'true', "aria-labelledby": 'fgcd-title', children: _jsxs("div", { className: 'fgcd-content', children: [_jsx("span", { className: 'fgcd-grabber', "aria-hidden": 'true' }), _jsxs("header", { className: 'fgcd-head', children: [_jsx("button", { type: 'button', className: 'fgcd-close', "aria-label": closeAriaLabel, onClick: close, children: _jsx("svg", { viewBox: '0 0 16 16', "aria-hidden": 'true', children: _jsx("path", { d: 'M3.5 3.5 12.5 12.5M12.5 3.5 3.5 12.5' }) }) }), _jsx("h2", { id: 'fgcd-title', children: title })] }), promoActive && summary.countdownLabel ? (_jsxs("p", { className: 'fgcd-timer', children: [_jsx("span", { "aria-hidden": 'true', children: "\u23F0" }), summary.countdownLabel, _jsx("span", { className: 'fgcd-timer-value', children: formatCountdown(summary.remainingSeconds) })] })) : null, summary.satisfactionPercent || summary.satisfactionLabel ? (_jsxs("p", { className: 'fgcd-proof', children: [_jsx("strong", { children: summary.satisfactionPercent }), " ", summary.satisfactionLabel] })) : null, _jsxs("div", { className: 'fgcd-summary', children: [promoActive ? (_jsxs(_Fragment, { children: [summary.originalPriceValue ? (_jsxs("p", { className: 'fgcd-row fgcd-row--muted', children: [_jsx("span", { children: summary.originalPriceLabel }), _jsx("s", { children: summary.originalPriceValue })] })) : null, summary.discountAmountLabel ? (_jsxs("p", { className: 'fgcd-row fgcd-row--discount', children: [_jsx("span", { children: summary.discountLabel }), _jsx("strong", { children: summary.discountAmountLabel })] })) : null, promoCode ? (_jsxs("p", { className: 'fgcd-promo', children: [_jsx("span", { children: summary.promoCodeLabel }), _jsxs("strong", { children: [_jsx(CheckIcon, {}), promoCode] })] })) : null, _jsx("hr", {})] })) : null, _jsxs("p", { className: 'fgcd-total', children: [_jsx("span", { children: summary.totalLabel }), _jsxs("strong", { children: [_jsx(TagIcon, {}), summary.totalValue] })] }), promoActive && summary.savedLabel ? _jsxs("p", { className: 'fgcd-saved', children: [_jsx("span", { "aria-hidden": 'true', children: "\uD83D\uDD25" }), summary.savedLabel] }) : null] }), _jsx("div", { className: 'fgcd-methods', children: _jsx(StripeWalletFirstCheckout, Object.assign({}, checkout, { checkoutSurface: 'dialog', onMethodChange: (selected) => { var _a; setMethod(selected); (_a = checkout.onMethodChange) === null || _a === void 0 ? void 0 : _a.call(checkout, selected); } })) }), error ? _jsx("p", { className: 'fgcd-error', role: 'alert', children: error }) : null, guaranteeLabel ? _jsxs("p", { className: 'fgcd-guarantee', children: [_jsx(LockIcon, {}), guaranteeLabel] }) : null] }) }), _jsx("style", { children: stripeCheckoutDialogStyles })] }));
103
106
  }
104
107
  function CheckIcon() {
105
108
  return (_jsxs("svg", { className: 'fgcd-check', viewBox: '0 0 13 13', "aria-hidden": 'true', children: [_jsx("circle", { cx: '6.5', cy: '6.5', r: '5.7', fill: '#1e7019' }), _jsx("path", { d: 'M3.9 6.66 5.6 8.37 9.1 4.63', fill: 'none', stroke: '#fff', strokeWidth: '1.46', strokeLinecap: 'round', strokeLinejoin: 'round' })] }));
@@ -141,6 +141,8 @@ export type StripeWalletFirstCheckoutProps = {
141
141
  paypalLabel?: string;
142
142
  /** A PayPal payment is in flight: the PayPal block stays selected and every other block is locked. */
143
143
  paypalPending?: boolean;
144
+ /** The selected block, on mount and on each change, e.g. to show PayPal's own terms while PayPal is selected. */
145
+ onMethodChange?: (method: StripeWalletFirstMethod) => void;
144
146
  /** The Checkout Session expired; the caller replaces it instead of the visitor seeing Stripe's error. */
145
147
  onInactiveCheckoutSession?: () => void;
146
148
  /** Called after `add_payment_info`, before a card or wallet confirmation. */
@@ -134,6 +134,13 @@ export function StripeWalletFirstCheckout(props) {
134
134
  const [selected, setSelected] = useState(initialMethod);
135
135
  // A method inside the other block selects that block; a hidden block gives way to the first one.
136
136
  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;
137
+ const onMethodChangeRef = useRef(props.onMethodChange);
138
+ onMethodChangeRef.current = props.onMethodChange;
139
+ useEffect(() => {
140
+ var _a;
141
+ if (activeId)
142
+ (_a = onMethodChangeRef.current) === null || _a === void 0 ? void 0 : _a.call(onMethodChangeRef, activeId);
143
+ }, [activeId]);
137
144
  // A form that is open on mount has not been opened by the visitor yet.
138
145
  const [engaged, setEngaged] = useState(initialMethod === 'wallet');
139
146
  const select = (id) => {
@@ -1,4 +1,6 @@
1
1
  import { readCreatorReferralId } from '../../../../services/creatorReferral.js';
2
+ import { readExperimentExposureProperties } from '@funnelsgrove/runtime';
3
+ const STRIPE_METADATA_VALUE_LIMIT = 500;
2
4
  const isRecord = (value) => {
3
5
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
4
6
  };
@@ -97,7 +99,8 @@ export const normalizeAnalyticsMetadata = (metadata) => {
97
99
  const checkoutUrl = sanitizeCheckoutUrl(normalized.url) || currentCheckoutUrl();
98
100
  // Influencers Store: a creator referral from the URL or a redeemed creator code earns its creator.
99
101
  const creatorReferralId = asTrimmedStringOrNull(normalized.is_ref) || readCreatorReferralId();
100
- const withCheckoutUrl = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, normalized), (fbc ? { fbc } : {})), (fbp ? { fbp } : {})), (checkoutUrl ? { url: checkoutUrl } : {})), (creatorReferralId ? { is_ref: creatorReferralId } : {}));
102
+ const { experiments } = readExperimentExposureProperties(STRIPE_METADATA_VALUE_LIMIT);
103
+ const withCheckoutUrl = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, normalized), (fbc ? { fbc } : {})), (fbp ? { fbp } : {})), (checkoutUrl ? { url: checkoutUrl } : {})), (creatorReferralId ? { is_ref: creatorReferralId } : {})), (experiments ? { experiments } : {}));
101
104
  return Object.keys(withCheckoutUrl).length > 0 ? withCheckoutUrl : undefined;
102
105
  };
103
106
  export const normalizeCheckoutAnalyticsMetadata = (metadata, plan) => {
@@ -12,15 +12,27 @@ export type PayPalBillingOption = {
12
12
  discountKey?: string;
13
13
  discountOptionsByKey?: Readonly<Record<string, PayPalBillingOption>>;
14
14
  };
15
+ /** A mapped Paddle price; Paddle discounts are not mapped (BILL-PADDLE-BR-003). */
16
+ export type PaddleBillingOption = {
17
+ paymentProfileId: string;
18
+ /** Public Paddle.js client-side token of the profile's environment. */
19
+ clientToken: string;
20
+ environment: 'sandbox' | 'production';
21
+ providerPlanId: string;
22
+ amountMinor: number;
23
+ currency: string;
24
+ summary: string;
25
+ };
15
26
  export type ResolvedPublishedBillingRuntime = {
16
27
  paypalOptionsByPlanKey?: Readonly<Record<string, PayPalBillingOption>>;
28
+ paddleOptionsByPlanKey?: Readonly<Record<string, PaddleBillingOption>>;
17
29
  revisionId: string | null;
18
30
  sourceVersionId: string | null;
19
31
  paymentsApiVersion: 'v2';
20
32
  mode: RuntimeMode;
21
33
  offerSetId: string;
22
34
  paymentProfileId: string | null;
23
- provider: 'stripe' | 'solidgate' | 'paypal';
35
+ provider: 'stripe' | 'solidgate' | 'paypal' | 'paddle';
24
36
  stripePublishableKey: string | null;
25
37
  experimentId: string | null;
26
38
  variantKey: string | null;
@@ -29,7 +29,7 @@ const nativePayPalOption = (mapping, paymentProfileId, clientId) => {
29
29
  summary: mapping.checkoutSummaryLabel, amountMinor: mapping.amountCents, currency: mapping.currency };
30
30
  };
31
31
  export const resolvePublishedBillingRuntime = ({ config, featureFlags, mode, search = '', defaultOfferSetId, locale, country, baseCatalogsByMode, fallbackDiscounts, resolvedExperiments = resolvePublishedRuntimeExperiments(config), }) => {
32
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;
32
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1;
33
33
  const offerSets = (_a = config === null || config === void 0 ? void 0 : config.offerSets) !== null && _a !== void 0 ? _a : [];
34
34
  const selection = resolvePublishedOfferSetSelection({
35
35
  offerSets,
@@ -93,20 +93,37 @@ export const resolvePublishedBillingRuntime = ({ config, featureFlags, mode, sea
93
93
  }
94
94
  paypalOptionsByPlanKey[item.funnelPlanKey] = Object.assign(Object.assign({}, option), (Object.keys(discountOptionsByKey).length ? { discountOptionsByKey } : {}));
95
95
  }
96
+ const paddleOptionsByPlanKey = {};
97
+ // Paddle is native only: a Paddle-owned Offer Set, never a binding next to another provider.
98
+ for (const item of provider === 'paddle' ? ((_r = runtime.offerSet) === null || _r === void 0 ? void 0 : _r.items) || [] : []) {
99
+ const profileId = (_s = runtime.offerSet) === null || _s === void 0 ? void 0 : _s.paymentProfileId;
100
+ if (!profileId)
101
+ continue;
102
+ const mapping = (_t = item.providerMappingsByMode) === null || _t === void 0 ? void 0 : _t[mode];
103
+ 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)
105
+ continue;
106
+ if (!(mapping === null || mapping === void 0 ? void 0 : mapping.providerPlanId) || !mapping.checkoutSummaryLabel || mapping.amountCents == null || !mapping.currency)
107
+ continue;
108
+ paddleOptionsByPlanKey[item.funnelPlanKey] = { paymentProfileId: profileId, clientToken: profileConfig.paddleClientToken,
109
+ environment: profileConfig.paddleEnvironment, providerPlanId: mapping.providerPlanId, amountMinor: mapping.amountCents,
110
+ currency: mapping.currency, summary: mapping.checkoutSummaryLabel };
111
+ }
96
112
  const pinnedFeatureFlags = Object.assign(Object.assign({}, featureFlags), (selection.experimentId && selection.variantKey
97
113
  ? { [selection.experimentId]: selection.variantKey }
98
114
  : {}));
99
115
  return {
100
116
  paypalOptionsByPlanKey,
101
- revisionId: (_r = config === null || config === void 0 ? void 0 : config.revisionId) !== null && _r !== void 0 ? _r : null,
102
- sourceVersionId: (_s = config === null || config === void 0 ? void 0 : config.sourceVersionId) !== null && _s !== void 0 ? _s : null,
117
+ paddleOptionsByPlanKey,
118
+ revisionId: (_x = config === null || config === void 0 ? void 0 : config.revisionId) !== null && _x !== void 0 ? _x : null,
119
+ sourceVersionId: (_y = config === null || config === void 0 ? void 0 : config.sourceVersionId) !== null && _y !== void 0 ? _y : null,
103
120
  paymentsApiVersion: 'v2',
104
121
  mode,
105
122
  offerSetId: selection.offerSetId,
106
- paymentProfileId: ((_u = (_t = runtime.offerSet) === null || _t === void 0 ? void 0 : _t.paymentProfileId) === null || _u === void 0 ? void 0 : _u.trim()) || null,
123
+ paymentProfileId: ((_0 = (_z = runtime.offerSet) === null || _z === void 0 ? void 0 : _z.paymentProfileId) === null || _0 === void 0 ? void 0 : _0.trim()) || null,
107
124
  provider,
108
125
  stripePublishableKey: provider === 'stripe' && (paymentProviderConfig === null || paymentProviderConfig === void 0 ? void 0 : paymentProviderConfig.provider) === 'stripe'
109
- ? ((_v = paymentProviderConfig === null || paymentProviderConfig === void 0 ? void 0 : paymentProviderConfig.stripePublishableKey) === null || _v === void 0 ? void 0 : _v.trim()) || null
126
+ ? ((_1 = paymentProviderConfig === null || paymentProviderConfig === void 0 ? void 0 : paymentProviderConfig.stripePublishableKey) === null || _1 === void 0 ? void 0 : _1.trim()) || null
110
127
  : null,
111
128
  experimentId: selection.experimentId,
112
129
  variantKey: selection.variantKey,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funnelsgrove/payments",
3
- "version": "0.73.0",
3
+ "version": "0.75.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/The-Solid-Grove/funnelsgrove.git",
@@ -46,11 +46,11 @@
46
46
  "jsdom": "20.0.3",
47
47
  "typescript": "^5",
48
48
  "vitest": "^3.2.4",
49
- "@funnelsgrove/runtime": "0.46.0",
50
- "@funnelsgrove/analytics": "0.29.0"
49
+ "@funnelsgrove/runtime": "0.47.0",
50
+ "@funnelsgrove/analytics": "0.30.0"
51
51
  },
52
52
  "peerDependencies": {
53
- "@funnelsgrove/runtime": "^0.46.0",
54
- "@funnelsgrove/analytics": "^0.29.0"
53
+ "@funnelsgrove/runtime": "^0.47.0",
54
+ "@funnelsgrove/analytics": "^0.30.0"
55
55
  }
56
56
  }