@funnelsgrove/payments 0.69.0 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- export declare const PAYMENTS_PACKAGE_VERSION = "0.69.0";
1
+ export declare const PAYMENTS_PACKAGE_VERSION = "0.70.0";
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/generate-package-version.mjs.
2
- export const PAYMENTS_PACKAGE_VERSION = "0.69.0";
2
+ export const PAYMENTS_PACKAGE_VERSION = "0.70.0";
@@ -67,6 +67,15 @@ export type StripeWalletFirstCheckoutEmail = {
67
67
  * method the offer supports (`'other'`), or one Stripe method type such as `'pix'`.
68
68
  */
69
69
  export type StripeWalletFirstMethod = 'wallet' | 'card' | 'other' | 'paypal' | (string & {});
70
+ /**
71
+ * The paid Checkout Session and how it was paid (CHECKOUT-SC-031). A method block pays in its own
72
+ * session, so this may differ from the card session. `paymentMethod` is a Stripe method type such as
73
+ * `'card'`, `'apple_pay'`, `'google_pay'` or `'pix'`; null when Stripe did not report it.
74
+ */
75
+ export type StripeWalletFirstPayment = {
76
+ checkoutSessionId: string | null;
77
+ paymentMethod: string | null;
78
+ };
70
79
  export type StripeWalletFirstCheckoutProps = {
71
80
  amountCents: number;
72
81
  buttonColor: string;
@@ -81,10 +90,11 @@ export type StripeWalletFirstCheckoutProps = {
81
90
  onCancel?: () => void;
82
91
  onError?: (message: string | null, details?: StripeCheckoutErrorDetails) => void;
83
92
  /**
84
- * Called after a paid checkout. Return `true` when the caller has already moved the visitor on
85
- * (e.g. client-side navigation to the next step); a card payment then skips the `returnUrl` reload.
93
+ * Called after a paid checkout with the paid session and method, e.g. to offer a one-click upsell
94
+ * only after a method that can be charged again. Return `true` when the caller has already moved the
95
+ * visitor on (e.g. client-side navigation to the next step); a card payment then skips the `returnUrl` reload.
86
96
  */
87
- onSuccess?: () => void | boolean | Promise<void | boolean>;
97
+ onSuccess?: (payment: StripeWalletFirstPayment) => void | boolean | Promise<void | boolean>;
88
98
  returnUrl: string;
89
99
  stripePromise: Promise<Stripe | null> | null;
90
100
  summaryLabel: string;
@@ -144,7 +144,7 @@ export function StripeWalletFirstCheckout(props) {
144
144
  const engage = () => setEngaged(true);
145
145
  const [busy, setBusy] = useState(false);
146
146
  const [confirmed, setConfirmed] = useState(false);
147
- const [confirmedSessionId, setConfirmedSessionId] = useState(null);
147
+ const [confirmedPayment, setConfirmedPayment] = useState(null);
148
148
  const [completed, setCompleted] = useState(false);
149
149
  // A replaced card session starts clean, as its remounted form did before.
150
150
  const [seenClientSecret, setSeenClientSecret] = useState(clientSecret);
@@ -154,7 +154,7 @@ export function StripeWalletFirstCheckout(props) {
154
154
  setFailure(null);
155
155
  setBusy(false);
156
156
  setConfirmed(false);
157
- setConfirmedSessionId(null);
157
+ setConfirmedPayment(null);
158
158
  setCompleted(false);
159
159
  }
160
160
  const paymentStatus = completed ? copy.paymentConfirmed : confirmed ? copy.verifyingPayment : null;
@@ -164,7 +164,7 @@ export function StripeWalletFirstCheckout(props) {
164
164
  locked: Boolean(paymentStatus) && !error,
165
165
  error,
166
166
  setBusy,
167
- markConfirmed: (confirmedId) => { setConfirmed(true); setConfirmedSessionId(confirmedId); },
167
+ markConfirmed: (payment) => { setConfirmed(true); setConfirmedPayment(payment); },
168
168
  markCompleted: () => setCompleted(true),
169
169
  showError: (message, context, details, alreadyTracked = false) => {
170
170
  // An expired session is replaced by the caller; Stripe's stale-session message never shows.
@@ -190,12 +190,12 @@ export function StripeWalletFirstCheckout(props) {
190
190
  else
191
191
  onError === null || onError === void 0 ? void 0 : onError(message);
192
192
  },
193
- trackSuccess: async (paidCheckoutSessionId, embedded = false) => {
193
+ trackSuccess: async (payment, embedded = false) => {
194
194
  if (checkoutAnalytics)
195
- await trackPaidStripeSubscriptionCheckoutCompleted(Object.assign(Object.assign({}, checkoutAnalytics), { checkoutSessionId: paidCheckoutSessionId }));
195
+ await trackPaidStripeSubscriptionCheckoutCompleted(Object.assign(Object.assign({}, checkoutAnalytics), { checkoutSessionId: payment.checkoutSessionId }));
196
196
  if (embedded)
197
197
  return false;
198
- return (await (onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess())) === true;
198
+ return (await (onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(payment))) === true;
199
199
  },
200
200
  };
201
201
  // Once any block confirmed a payment, no other block may start a second one.
@@ -218,6 +218,7 @@ export function StripeWalletFirstCheckout(props) {
218
218
  var _a, _b;
219
219
  const checked = activeId === block.id;
220
220
  if (block.kind === 'wallet') {
221
+ const walletPayment = { checkoutSessionId, paymentMethod: wallet === 'applePay' ? 'apple_pay' : 'google_pay' };
221
222
  const WalletMark = wallet === 'applePay' ? ApplePayMark : GooglePayMark;
222
223
  const walletNote = checked ? status.paymentStatus : null;
223
224
  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 () => {
@@ -228,7 +229,7 @@ export function StripeWalletFirstCheckout(props) {
228
229
  if (!confirmedEmail)
229
230
  setBusy(false);
230
231
  return confirmedEmail;
231
- }, 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(checkoutSessionId); }, onVerificationPending: () => status.markConfirmed(checkoutSessionId), processingLabel: copy.processingLabel, returnUrl: props.returnUrl, 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'));
232
+ }, 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, 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'));
232
233
  }
233
234
  if (block.kind === 'card') {
234
235
  const brands = ((_a = props.cardBrandLabels) === null || _a === void 0 ? void 0 : _a.length)
@@ -247,16 +248,17 @@ export function StripeWalletFirstCheckout(props) {
247
248
  // A confirmed payment that failed to verify is checked again, never paid again.
248
249
  const checkPaymentStatus = async () => {
249
250
  var _a;
250
- const paidSessionId = confirmedSessionId !== null && confirmedSessionId !== void 0 ? confirmedSessionId : checkoutSessionId;
251
+ const payment = confirmedPayment !== null && confirmedPayment !== void 0 ? confirmedPayment : { checkoutSessionId, paymentMethod: null };
252
+ const paidSessionId = payment.checkoutSessionId;
251
253
  const context = { blockId: (_a = failure === null || failure === void 0 ? void 0 : failure.blockId) !== null && _a !== void 0 ? _a : 'card', checkoutSessionId: paidSessionId, failureStage: 'verification' };
252
254
  status.showError(null, context);
253
255
  setBusy(true);
254
256
  try {
255
257
  if (await completePaywallCheckout('stripe', paidSessionId || '', {
256
- beforeNotify: async () => { setCompleted(true); await status.trackSuccess(paidSessionId, true); },
258
+ beforeNotify: async () => { setCompleted(true); await status.trackSuccess(payment, true); },
257
259
  }))
258
260
  return;
259
- if (await status.trackSuccess(paidSessionId))
261
+ if (await status.trackSuccess(payment))
260
262
  return;
261
263
  window.location.assign(resolveCheckoutReturnUrl(props.returnUrl, paidSessionId));
262
264
  }
@@ -340,12 +342,13 @@ function MethodForm({ blockId, checkoutAnalytics, checkoutSessionId, copy, count
340
342
  }, [selected]);
341
343
  const failure = { blockId, checkoutSessionId, failureStage, paymentMethod: method };
342
344
  const showError = (message, details, alreadyTracked = false) => status.showError(message, failure, details, alreadyTracked);
345
+ const payment = { checkoutSessionId, paymentMethod: method !== null && method !== void 0 ? method : null };
343
346
  const finishPaidCheckout = async () => {
344
347
  if (await completePaywallCheckout('stripe', checkoutSessionId || '', {
345
- beforeNotify: async () => { status.markCompleted(); await status.trackSuccess(checkoutSessionId, true); },
348
+ beforeNotify: async () => { status.markCompleted(); await status.trackSuccess(payment, true); },
346
349
  }))
347
350
  return;
348
- if (await status.trackSuccess(checkoutSessionId))
351
+ if (await status.trackSuccess(payment))
349
352
  return;
350
353
  window.location.assign(resolveCheckoutReturnUrl(returnUrl, checkoutSessionId));
351
354
  };
@@ -409,7 +412,7 @@ function MethodForm({ blockId, checkoutAnalytics, checkoutSessionId, copy, count
409
412
  }
410
413
  confirmed = true;
411
414
  setProviderConfirmed(true);
412
- status.markConfirmed(checkoutSessionId);
415
+ status.markConfirmed(payment);
413
416
  }
414
417
  await finishPaidCheckout();
415
418
  }
@@ -0,0 +1,3 @@
1
+ export declare const isCheckoutPageAttended: () => boolean;
2
+ export declare function startCheckoutPageAttention(): void;
3
+ export declare const waitForCheckoutPageAttention: () => Promise<void>;
@@ -0,0 +1,54 @@
1
+ // FUN-479: automatic checkout preparation runs only while someone is at the page.
2
+ // A forgotten paywall tab otherwise creates a live Checkout Session every time its
3
+ // offer changes, and a request cut off by device sleep looks like a shown failure.
4
+ const IDLE_AFTER_MS = 15 * 60000;
5
+ const ACTIVITY_EVENTS = ['pointerdown', 'pointermove', 'keydown', 'touchstart', 'wheel', 'scroll', 'focus'];
6
+ let lastActivityAtMs = Date.now();
7
+ let listening = false;
8
+ const waiters = new Set();
9
+ const canListen = () => typeof window !== 'undefined'
10
+ && typeof window.addEventListener === 'function'
11
+ && typeof (document === null || document === void 0 ? void 0 : document.addEventListener) === 'function';
12
+ export const isCheckoutPageAttended = () => {
13
+ if (!canListen()) {
14
+ return true;
15
+ }
16
+ startCheckoutPageAttention();
17
+ return document.visibilityState !== 'hidden'
18
+ && navigator.onLine !== false
19
+ && Date.now() - lastActivityAtMs < IDLE_AFTER_MS;
20
+ };
21
+ const releaseWaiters = () => {
22
+ if (waiters.size === 0 || !isCheckoutPageAttended()) {
23
+ return;
24
+ }
25
+ const pending = [...waiters];
26
+ waiters.clear();
27
+ pending.forEach((resolve) => resolve());
28
+ };
29
+ const recordActivity = () => {
30
+ lastActivityAtMs = Date.now();
31
+ releaseWaiters();
32
+ };
33
+ // Started when the first checkout hook mounts, so the idle clock starts with the paywall.
34
+ export function startCheckoutPageAttention() {
35
+ if (listening || !canListen()) {
36
+ return;
37
+ }
38
+ listening = true;
39
+ lastActivityAtMs = Date.now();
40
+ for (const type of ACTIVITY_EVENTS) {
41
+ window.addEventListener(type, recordActivity, { capture: true, passive: true });
42
+ }
43
+ document.addEventListener('visibilitychange', () => {
44
+ if (document.visibilityState === 'visible') {
45
+ recordActivity();
46
+ }
47
+ });
48
+ window.addEventListener('online', releaseWaiters);
49
+ }
50
+ export const waitForCheckoutPageAttention = () => isCheckoutPageAttended()
51
+ ? Promise.resolve()
52
+ : new Promise((resolve) => {
53
+ waiters.add(resolve);
54
+ });
@@ -3,6 +3,7 @@ export type CheckoutPreparationFailure = {
3
3
  count: number;
4
4
  until: number;
5
5
  };
6
+ export declare const isAutomaticCheckoutPreparation: (source?: string) => boolean;
6
7
  export declare const recordCheckoutPreparationFailure: (previous: CheckoutPreparationFailure | null, failure: {
7
8
  intentKey: string;
8
9
  retryAfterMs?: number | null;
@@ -2,16 +2,14 @@ const BASE_WINDOW_MS = 2000;
2
2
  const MAX_WINDOW_MS = 30000;
3
3
  const MAX_RETRY_AFTER_MS = 60000;
4
4
  const AUTOMATIC_SOURCES = new Set(['checkout_render', 'wallet_render']);
5
+ export const isAutomaticCheckoutPreparation = (source) => AUTOMATIC_SOURCES.has(source !== null && source !== void 0 ? source : '');
5
6
  export const recordCheckoutPreparationFailure = (previous, failure, now) => {
6
7
  var _a;
7
8
  const count = (previous === null || previous === void 0 ? void 0 : previous.intentKey) === failure.intentKey ? previous.count + 1 : 1;
8
9
  const windowMs = Math.max(Math.min((_a = failure.retryAfterMs) !== null && _a !== void 0 ? _a : 0, MAX_RETRY_AFTER_MS), Math.min(BASE_WINDOW_MS * 2 ** (count - 1), MAX_WINDOW_MS));
9
10
  return { intentKey: failure.intentKey, count, until: now + windowMs };
10
11
  };
11
- export const blocksCheckoutPreparation = (failure, request, now) => {
12
- var _a;
13
- return !request.forceNew
14
- && AUTOMATIC_SOURCES.has((_a = request.source) !== null && _a !== void 0 ? _a : '')
15
- && (failure === null || failure === void 0 ? void 0 : failure.intentKey) === request.intentKey
16
- && now < failure.until;
17
- };
12
+ export const blocksCheckoutPreparation = (failure, request, now) => !request.forceNew
13
+ && isAutomaticCheckoutPreparation(request.source)
14
+ && (failure === null || failure === void 0 ? void 0 : failure.intentKey) === request.intentKey
15
+ && now < failure.until;
@@ -19,7 +19,8 @@ import { toAnalyticsPaymentMethod } from '../../../services/paymentMethodAnalyti
19
19
  import { resolveCheckoutObservabilityAnalyticsContext, trackCheckoutFailureShown, } from '../../../services/checkoutObservability.service.js';
20
20
  import { resolveStripeCheckoutAttempt, } from './checkoutAttempt.js';
21
21
  import { isStripeCheckoutIdentityReady } from './checkoutIdentity.js';
22
- import { blocksCheckoutPreparation, recordCheckoutPreparationFailure, } from './checkoutPreparationBackoff.js';
22
+ import { blocksCheckoutPreparation, isAutomaticCheckoutPreparation, recordCheckoutPreparationFailure, } from './checkoutPreparationBackoff.js';
23
+ import { isCheckoutPageAttended, startCheckoutPageAttention, waitForCheckoutPageAttention, } from './checkoutPageAttention.js';
23
24
  export { isStripeCheckoutIdentityReady as isStripeSubscriptionCheckoutIdentityReady, } from './checkoutIdentity.js';
24
25
  export function resolveStripeSubscriptionCheckoutPreparationOptions(source, options = {}) {
25
26
  var _a, _b;
@@ -140,6 +141,17 @@ export function useStripeSubscriptionCheckoutSession({ checkoutMode: nextCheckou
140
141
  const activePlanKey = clientSecretIntentKey === intentKey ? clientSecretPlanKey : null;
141
142
  const stripePromise = useMemo(() => getStripePromise(checkoutMode, runtimeStripePublishableKey !== null && runtimeStripePublishableKey !== void 0 ? runtimeStripePublishableKey : stripePublishableKey, stripeLocale), [checkoutMode, runtimeStripePublishableKey, stripePublishableKey, stripeLocale]);
142
143
  const previousIntentKeyRef = useRef(intentKey);
144
+ const latestIntentKeyRef = useRef(intentKey);
145
+ latestIntentKeyRef.current = intentKey;
146
+ const unattendedFailureIntentKeyRef = useRef(null);
147
+ const mountedRef = useRef(true);
148
+ useEffect(() => {
149
+ mountedRef.current = true;
150
+ startCheckoutPageAttention();
151
+ return () => {
152
+ mountedRef.current = false;
153
+ };
154
+ }, []);
143
155
  const analyticsMetadataRef = useRef(analyticsMetadata);
144
156
  useEffect(() => {
145
157
  analyticsMetadataRef.current = analyticsMetadata;
@@ -295,6 +307,13 @@ export function useStripeSubscriptionCheckoutSession({ checkoutMode: nextCheckou
295
307
  metadata: analyticsMetadataRef.current,
296
308
  runtimeConfig,
297
309
  });
310
+ // Nobody saw a background preparation fail once the buyer left or the device
311
+ // slept: show and report nothing; prepareCheckout retries when the buyer returns.
312
+ if (isAutomaticCheckoutPreparation(options.checkoutStartSource)
313
+ && !isCheckoutPageAttended()) {
314
+ unattendedFailureIntentKeyRef.current = requestKey;
315
+ return null;
316
+ }
298
317
  if (observabilityAnalytics
299
318
  && shouldReportStripeCheckoutFailureShown(message)) {
300
319
  trackCheckoutFailureShown({
@@ -370,7 +389,25 @@ export function useStripeSubscriptionCheckoutSession({ checkoutMode: nextCheckou
370
389
  setSourceLoading(source, true);
371
390
  setError(null);
372
391
  try {
373
- return await createCheckoutSubscription(preparationOptions);
392
+ const automatic = isAutomaticCheckoutPreparation(preparationOptions.checkoutStartSource);
393
+ const resumeWhenAttended = async () => {
394
+ await waitForCheckoutPageAttention();
395
+ return mountedRef.current && latestIntentKeyRef.current === intentKey;
396
+ };
397
+ if (automatic && !isCheckoutPageAttended() && !(await resumeWhenAttended())) {
398
+ return null;
399
+ }
400
+ const clientSecret = await createCheckoutSubscription(preparationOptions);
401
+ if (clientSecret || unattendedFailureIntentKeyRef.current !== intentKey) {
402
+ return clientSecret;
403
+ }
404
+ unattendedFailureIntentKeyRef.current = null;
405
+ if (!(await resumeWhenAttended())) {
406
+ return null;
407
+ }
408
+ // Inside the attempt retry window this reuses the idempotency key, so a session
409
+ // Stripe created before the failure is returned instead of a new one.
410
+ return await createCheckoutSubscription(Object.assign(Object.assign({}, preparationOptions), { forceNew: false }));
374
411
  }
375
412
  finally {
376
413
  setSourceLoading(source, false);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funnelsgrove/payments",
3
- "version": "0.69.0",
3
+ "version": "0.70.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/The-Solid-Grove/funnelsgrove.git",