@funnelsgrove/payments 0.54.0 → 0.56.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
@@ -43,6 +43,14 @@ elsewhere, preselected, with Stripe's own button, and the card form as the secon
43
43
  - The card form has no ZIP or terms text.
44
44
  - `onCancel` runs when the visitor closes the Apple Pay or Google Pay sheet without paying,
45
45
  for example to show an extra discount. The form is unlocked again by then.
46
+ - `onError(message, details?)` preserves the existing message argument and adds exported
47
+ `StripeCheckoutErrorDetails`: `category`, `paymentMethod`, `providerDeclineCode`,
48
+ `providerErrorCode`, and `providerErrorType`. The same callback contract applies to
49
+ `SharedStripeCheckoutV2Dialog` and `StripeCheckoutExpressCheckoutButton`. Provider fields
50
+ and payment method are present when known; clearing calls `onError(null)` without details.
51
+ Use `details.category === 'payment_rejection'` and `details.paymentMethod` to distinguish
52
+ a card, Apple Pay, or Google Pay refusal. Wallet refusals are reported before the existing
53
+ card fallback; wallet cancellation continues through `onCancel`.
46
54
  - Where the browser cannot pay with that wallet, the wallet stays first and its slot shows
47
55
  `walletUnavailableNote` (`{wallet}` is replaced with the wallet name). The card remains
48
56
  one tap away. This is deliberate: the layout must not move.
@@ -1 +1 @@
1
- export declare const PAYMENTS_PACKAGE_VERSION = "0.54.0";
1
+ export declare const PAYMENTS_PACKAGE_VERSION = "0.56.0";
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/generate-package-version.mjs.
2
- export const PAYMENTS_PACKAGE_VERSION = "0.54.0";
2
+ export const PAYMENTS_PACKAGE_VERSION = "0.56.0";
@@ -1,4 +1,4 @@
1
- import { paywallCheckoutReturnUrl, retainPaywallCheckout, FUNNEL_ID, FUNNEL_SDK_PUBLISHABLE_KEY, buildMainApiUrl, resolvePreviewPaymentPublishableKey, } from '@funnelsgrove/runtime';
1
+ import { paywallCheckoutReturnUrl, retainPaywallCheckout, FUNNEL_ID, FUNNEL_SDK_PUBLISHABLE_KEY, buildMainApiUrl, funnelSdkService, getCheckoutIdentityToken, resolvePreviewPaymentPublishableKey, retainCheckoutIdentityToken, } from '@funnelsgrove/runtime';
2
2
  import { trackSolidgateCheckoutEvent } from './solidgateCheckoutAnalytics.service.js';
3
3
  export class SolidgateExistingSubscriptionError extends Error {
4
4
  constructor() {
@@ -15,6 +15,24 @@ export class SolidgateSavedPaymentMethodUnavailableError extends Error {
15
15
  this.name = 'SolidgateSavedPaymentMethodUnavailableError';
16
16
  }
17
17
  }
18
+ /** The server rejected the bootstrap identity proof as expired; refresh it and resend once. */
19
+ class SolidgateCheckoutIdentityExpiredError extends Error {
20
+ constructor() {
21
+ super('Checkout identity has expired');
22
+ this.name = 'SolidgateCheckoutIdentityExpiredError';
23
+ }
24
+ }
25
+ const MAX_CHECKOUT_PROOF_LENGTH = 4096;
26
+ /** Checkout access tokens issued by the create response, keyed by attempt id (memory only, like Stripe). */
27
+ const checkoutAccessTokens = new Map();
28
+ const retainCheckoutAccessToken = (attemptId, token) => {
29
+ const normalized = typeof token === 'string' ? token.trim() : '';
30
+ if (!normalized || normalized.length > MAX_CHECKOUT_PROOF_LENGTH) {
31
+ checkoutAccessTokens.delete(attemptId);
32
+ return;
33
+ }
34
+ checkoutAccessTokens.set(attemptId, normalized);
35
+ };
18
36
  const trimTrailingSlash = (value) => value.replace(/\/+$/, '');
19
37
  const requiredString = (value, name) => {
20
38
  const normalized = typeof value === 'string' ? value.trim() : '';
@@ -44,26 +62,28 @@ const postJson = async (path, body, runtimeConfig, signal) => {
44
62
  signal,
45
63
  });
46
64
  if (!response.ok) {
47
- if (response.status === 409) {
65
+ if (response.status === 409 || response.status === 401) {
48
66
  const payload = await response.json().catch(() => null);
49
- if (payload && typeof payload === 'object' && 'code' in payload
50
- && payload.code === 'already_subscribed_to_product') {
67
+ const code = payload && typeof payload === 'object' && 'code' in payload ? payload.code : null;
68
+ if (response.status === 409 && code === 'already_subscribed_to_product') {
51
69
  throw new SolidgateExistingSubscriptionError();
52
70
  }
53
- if (payload && typeof payload === 'object' && 'code' in payload
54
- && payload.code === 'saved_payment_method_unavailable') {
71
+ if (response.status === 409 && code === 'saved_payment_method_unavailable') {
55
72
  throw new SolidgateSavedPaymentMethodUnavailableError();
56
73
  }
74
+ if (response.status === 401 && code === 'checkout_identity_expired') {
75
+ throw new SolidgateCheckoutIdentityExpiredError();
76
+ }
57
77
  }
58
78
  throw new Error('Solidgate checkout is temporarily unavailable');
59
79
  }
60
80
  return response.json();
61
81
  };
62
- const getJson = async (path, runtimeConfig, signal) => {
82
+ const getJson = async (path, headers, runtimeConfig, signal) => {
63
83
  const publishableKey = resolvePublishableKey(runtimeConfig);
64
84
  const response = await fetch(resolveApiUrl(path, runtimeConfig), {
65
85
  method: 'GET',
66
- headers: Object.assign({}, (publishableKey ? { 'x-sdk-publishable-key': publishableKey } : {})),
86
+ headers: Object.assign(Object.assign({}, (publishableKey ? { 'x-sdk-publishable-key': publishableKey } : {})), headers),
67
87
  signal,
68
88
  });
69
89
  if (!response.ok) {
@@ -72,6 +92,41 @@ const getJson = async (path, runtimeConfig, signal) => {
72
92
  return response.json();
73
93
  };
74
94
  const isRecord = (value) => (Boolean(value) && typeof value === 'object' && !Array.isArray(value));
95
+ const refreshCheckoutIdentity = async (userId, idempotencyKey, runtimeConfig, signal) => {
96
+ const payload = await funnelSdkService.bootstrapUser({
97
+ userId, idempotencyKey, runtimeConfig, signal,
98
+ });
99
+ const token = typeof payload.checkoutIdentityToken === 'string' ? payload.checkoutIdentityToken.trim() : '';
100
+ if (!token) {
101
+ throw new Error('Solidgate checkout is temporarily unavailable');
102
+ }
103
+ retainCheckoutIdentityToken(userId, token);
104
+ return token;
105
+ };
106
+ /**
107
+ * Sends the request with the runtime's bootstrap identity proof when it holds one.
108
+ * Mirrors the Stripe path: an expired proof is refreshed through bootstrap and the
109
+ * same attempt is sent once more. The server still verifies every proof.
110
+ */
111
+ const postWithCheckoutIdentity = async (identity, send) => {
112
+ const checkoutIdentityToken = getCheckoutIdentityToken(identity.userId);
113
+ try {
114
+ return await send(checkoutIdentityToken ? { checkoutIdentityToken } : {});
115
+ }
116
+ catch (error) {
117
+ if (!(error instanceof SolidgateCheckoutIdentityExpiredError)) {
118
+ throw error;
119
+ }
120
+ }
121
+ const refreshed = await refreshCheckoutIdentity(identity.userId, identity.idempotencyKey, identity.runtimeConfig, identity.signal);
122
+ try {
123
+ return await send({ checkoutIdentityToken: refreshed });
124
+ }
125
+ catch (error) {
126
+ throw error instanceof SolidgateCheckoutIdentityExpiredError
127
+ ? new Error('Solidgate checkout is temporarily unavailable') : error;
128
+ }
129
+ };
75
130
  const parsePreparation = (value) => {
76
131
  if (!isRecord(value) || !isRecord(value.display) || !isRecord(value.initialization)) {
77
132
  throw new Error('Solidgate checkout returned an invalid response');
@@ -134,7 +189,7 @@ const parseStatus = (value) => {
134
189
  && /^\d\.\d{2}$/.test(value.failureCode) ? { failureCode: value.failureCode } : {}));
135
190
  };
136
191
  export const prepareSolidgateCheckout = async (input) => {
137
- var _a, _b, _c;
192
+ var _a, _b;
138
193
  const paymentProfileId = ((_a = input.paymentProfileId) === null || _a === void 0 ? void 0 : _a.trim()) || null;
139
194
  const providerPlanId = ((_b = input.providerPlanId) === null || _b === void 0 ? void 0 : _b.trim()) || null;
140
195
  const checkoutType = input.checkoutType || null;
@@ -142,8 +197,15 @@ export const prepareSolidgateCheckout = async (input) => {
142
197
  if (!paymentProfileId || !providerPlanId || !checkoutType || !environment) {
143
198
  throw new Error('Solidgate V2 checkout selection is incomplete');
144
199
  }
145
- const result = parsePreparation(await postJson('/sdk/public/v2/payments/checkout-sessions', Object.assign(Object.assign(Object.assign({ checkoutType, uiMode: 'custom', environment,
146
- paymentProfileId, provider: 'solidgate', providerPlanId, planKey: requiredString(input.funnelPlanKey, 'funnelPlanKey'), funnelId: resolveFunnelId(input.funnelId, input.runtimeConfig), funnelEndUserId: requiredString(input.funnelEndUserId, 'funnelEndUserId'), offerSetId: requiredString(input.offerSetId, 'offerSetId'), idempotencyKey: requiredString(input.idempotencyKey, 'idempotencyKey') }, (input.language != null ? { language: input.language } : {})), (input.retryAttemptId ? { retryAttemptId: input.retryAttemptId } : {})), { couponId: ((_c = input.discountKeyOrProviderId) === null || _c === void 0 ? void 0 : _c.trim()) || null, returnUrl: paywallCheckoutReturnUrl(requiredString(input.returnUrl, 'returnUrl'), 'solidgate'), successUrl: paywallCheckoutReturnUrl(requiredString(input.successUrl, 'successUrl'), 'solidgate'), failUrl: paywallCheckoutReturnUrl(requiredString(input.failUrl, 'failUrl'), 'solidgate', true) }), input.runtimeConfig, input.signal));
200
+ const funnelEndUserId = requiredString(input.funnelEndUserId, 'funnelEndUserId');
201
+ const idempotencyKey = requiredString(input.idempotencyKey, 'idempotencyKey');
202
+ const response = await postWithCheckoutIdentity({ userId: funnelEndUserId, idempotencyKey, runtimeConfig: input.runtimeConfig, signal: input.signal }, (proof) => {
203
+ var _a;
204
+ return postJson('/sdk/public/v2/payments/checkout-sessions', Object.assign(Object.assign(Object.assign(Object.assign({ checkoutType, uiMode: 'custom', environment,
205
+ paymentProfileId, provider: 'solidgate', providerPlanId, planKey: requiredString(input.funnelPlanKey, 'funnelPlanKey'), funnelId: resolveFunnelId(input.funnelId, input.runtimeConfig), funnelEndUserId, offerSetId: requiredString(input.offerSetId, 'offerSetId'), idempotencyKey }, proof), (input.language != null ? { language: input.language } : {})), (input.retryAttemptId ? { retryAttemptId: input.retryAttemptId } : {})), { couponId: ((_a = input.discountKeyOrProviderId) === null || _a === void 0 ? void 0 : _a.trim()) || null, returnUrl: paywallCheckoutReturnUrl(requiredString(input.returnUrl, 'returnUrl'), 'solidgate'), successUrl: paywallCheckoutReturnUrl(requiredString(input.successUrl, 'successUrl'), 'solidgate'), failUrl: paywallCheckoutReturnUrl(requiredString(input.failUrl, 'failUrl'), 'solidgate', true) }), input.runtimeConfig, input.signal);
206
+ });
207
+ const result = parsePreparation(response);
208
+ retainCheckoutAccessToken(result.attemptId, isRecord(response) ? response.checkoutAccessToken : null);
147
209
  retainPaywallCheckout('solidgate', result.attemptId);
148
210
  return result;
149
211
  };
@@ -151,7 +213,9 @@ export const retrieveSolidgateCheckoutStatus = async (input) => {
151
213
  const attemptId = requiredString(input.attemptId, 'attemptId');
152
214
  const funnelId = resolveFunnelId(input.funnelId, input.runtimeConfig);
153
215
  const funnelEndUserId = requiredString(input.funnelEndUserId, 'funnelEndUserId');
154
- const result = parseStatus(await getJson(`/sdk/public/v2/payments/checkout-sessions/${encodeURIComponent(attemptId)}?provider=solidgate&funnelId=${encodeURIComponent(funnelId)}&funnelEndUserId=${encodeURIComponent(funnelEndUserId)}`, input.runtimeConfig, input.signal));
216
+ const checkoutIdentityToken = getCheckoutIdentityToken(funnelEndUserId);
217
+ const checkoutAccessToken = checkoutAccessTokens.get(attemptId);
218
+ const result = parseStatus(await getJson(`/sdk/public/v2/payments/checkout-sessions/${encodeURIComponent(attemptId)}?provider=solidgate&funnelId=${encodeURIComponent(funnelId)}&funnelEndUserId=${encodeURIComponent(funnelEndUserId)}`, Object.assign(Object.assign({}, (checkoutIdentityToken ? { 'x-funnelsgrove-checkout-identity-token': checkoutIdentityToken } : {})), (checkoutAccessToken ? { 'x-funnelsgrove-checkout-access-token': checkoutAccessToken } : {})), input.runtimeConfig, input.signal));
155
219
  if (result.attemptId !== attemptId) {
156
220
  throw new Error('Solidgate checkout status returned the wrong attempt');
157
221
  }
@@ -231,18 +295,9 @@ export const pollSolidgateCheckoutStatus = async (input, options = {}) => {
231
295
  const oneClickStatuses = new Set(['verifying', 'succeeded', 'failed']);
232
296
  /** Charges a one-time offer to the instrument saved by the user's paid Solidgate checkout. */
233
297
  export const chargeSolidgateOneClickPayment = async (input) => {
234
- const value = await postJson('/sdk/public/v2/payments/one-click', {
235
- provider: 'solidgate',
236
- environment: input.environment,
237
- funnelId: resolveFunnelId(input.funnelId, input.runtimeConfig),
238
- offerSetId: requiredString(input.offerSetId, 'offerSetId'),
239
- paymentProfileId: requiredString(input.paymentProfileId, 'paymentProfileId'),
240
- providerPlanId: requiredString(input.providerPlanId, 'providerPlanId'),
241
- planKey: requiredString(input.funnelPlanKey, 'funnelPlanKey'),
242
- userId: requiredString(input.userId, 'userId'),
243
- checkoutSessionId: requiredString(input.checkoutSessionId, 'checkoutSessionId'),
244
- idempotencyKey: requiredString(input.idempotencyKey, 'idempotencyKey'),
245
- }, input.runtimeConfig, input.signal);
298
+ const userId = requiredString(input.userId, 'userId');
299
+ const idempotencyKey = requiredString(input.idempotencyKey, 'idempotencyKey');
300
+ const value = await postWithCheckoutIdentity({ userId, idempotencyKey, runtimeConfig: input.runtimeConfig, signal: input.signal }, (proof) => postJson('/sdk/public/v2/payments/one-click', Object.assign({ provider: 'solidgate', environment: input.environment, funnelId: resolveFunnelId(input.funnelId, input.runtimeConfig), offerSetId: requiredString(input.offerSetId, 'offerSetId'), paymentProfileId: requiredString(input.paymentProfileId, 'paymentProfileId'), providerPlanId: requiredString(input.providerPlanId, 'providerPlanId'), planKey: requiredString(input.funnelPlanKey, 'funnelPlanKey'), userId, checkoutSessionId: requiredString(input.checkoutSessionId, 'checkoutSessionId'), idempotencyKey }, proof), input.runtimeConfig, input.signal));
246
301
  if (!isRecord(value) || value.provider !== 'solidgate' || typeof value.status !== 'string'
247
302
  || !oneClickStatuses.has(value.status)) {
248
303
  throw new Error('Solidgate one-click returned an invalid response');
@@ -1,4 +1,5 @@
1
1
  import { type CSSProperties, type ReactNode } from 'react';
2
+ import type { StripeCheckoutErrorDetails } from '../services/stripeCheckoutError.js';
2
3
  import type { Stripe } from '@stripe/stripe-js';
3
4
  import { type StripeSubscriptionCheckoutAnalyticsContext } from '../services/checkoutCompletionAnalytics.service.js';
4
5
  import type { SharedStripeCheckoutV2Copy } from './checkout-v2.content.js';
@@ -33,7 +34,7 @@ export type SharedStripeCheckoutV2DialogProps = {
33
34
  onWalletCancel?: () => void;
34
35
  onCustomerEmailChange?: (value: string) => void;
35
36
  onCustomerEmailCommit?: (email: string) => Promise<string | null | void>;
36
- onError?: (message: string | null) => void;
37
+ onError?: (message: string | null, details?: StripeCheckoutErrorDetails) => void;
37
38
  onInactiveCheckoutSession?: () => void;
38
39
  onPaymentInfoSubmitted?: () => void | Promise<void>;
39
40
  onSuccess?: () => void | Promise<void>;
@@ -11,6 +11,7 @@ import { isInactiveCheckoutSessionError } from '../hooks/useStripeSubscriptionCh
11
11
  import { getStripeWalletPaymentMethodOrder, usePlatformWalletPaymentMethods } from './walletPlatform.js';
12
12
  import { trackPaidStripeSubscriptionCheckoutCompleted, trackStripeSubscriptionPaymentInfoSubmitted } from '../services/checkoutCompletionAnalytics.service.js';
13
13
  import { trackCheckoutFailureShown } from '../../../services/checkoutObservability.service.js';
14
+ import { normalizeStripeCheckoutError } from '../services/stripeCheckoutError.js';
14
15
  import { SharedCheckoutPaymentMethods } from './SharedCheckoutPaymentMethods.internal.js';
15
16
  import { SharedStripeCheckoutV2Summary } from './SharedStripeCheckoutV2Summary.internal.js';
16
17
  import { useCheckoutEmail } from './useCheckoutEmail.internal.js';
@@ -124,8 +125,9 @@ export function SharedStripeCheckoutV2CheckoutSessionForm({ copy = defaultChecko
124
125
  setError(null);
125
126
  onInactiveCheckoutSession === null || onInactiveCheckoutSession === void 0 ? void 0 : onInactiveCheckoutSession();
126
127
  };
127
- const setSharedError = (message, alreadyTracked = false, providerError) => {
128
- if (isCheckoutEmailError(providerError) || isCheckoutEmailError(message)) {
128
+ const setSharedError = (message, alreadyTracked = false, details) => {
129
+ const errorDetails = message ? details !== null && details !== void 0 ? details : normalizeStripeCheckoutError(message, undefined, 'card') : undefined;
130
+ if (isCheckoutEmailError({ code: errorDetails === null || errorDetails === void 0 ? void 0 : errorDetails.providerErrorCode }) || isCheckoutEmailError(message)) {
129
131
  setRejectedEmail(initialCustomerEmail);
130
132
  setSelectedMethod('card');
131
133
  }
@@ -134,20 +136,13 @@ export function SharedStripeCheckoutV2CheckoutSessionForm({ copy = defaultChecko
134
136
  return;
135
137
  }
136
138
  if (message && checkoutAnalytics && !alreadyTracked) {
137
- trackCheckoutFailureShown({
138
- analytics: checkoutAnalytics,
139
- checkoutSessionId,
140
- errorMessage: message,
141
- failureStage: 'card_form',
142
- paymentMethod: 'card',
143
- provider: 'stripe',
144
- providerDeclineCode: providerError === null || providerError === void 0 ? void 0 : providerError.decline_code,
145
- providerErrorCode: providerError === null || providerError === void 0 ? void 0 : providerError.code,
146
- providerErrorType: providerError === null || providerError === void 0 ? void 0 : providerError.type,
147
- });
139
+ trackCheckoutFailureShown(Object.assign({ analytics: checkoutAnalytics, checkoutSessionId, errorMessage: message, failureStage: 'card_form', provider: 'stripe' }, errorDetails));
148
140
  }
149
141
  setError(message);
150
- onError === null || onError === void 0 ? void 0 : onError(message);
142
+ if (message)
143
+ onError === null || onError === void 0 ? void 0 : onError(message, errorDetails);
144
+ else
145
+ onError === null || onError === void 0 ? void 0 : onError(message);
151
146
  };
152
147
  const selectWalletMethod = () => {
153
148
  if (showWalletMethod && !paypalPending && !submitting) {
@@ -241,7 +236,7 @@ export function SharedStripeCheckoutV2CheckoutSessionForm({ copy = defaultChecko
241
236
  });
242
237
  if (result.type === 'error') {
243
238
  const message = result.error.message || copy.paymentFailed;
244
- setSharedError(message, false, result.error);
239
+ setSharedError(message, false, normalizeStripeCheckoutError(message, result.error, 'card'));
245
240
  finishSubmitting();
246
241
  return;
247
242
  }
@@ -284,7 +279,7 @@ export function SharedStripeCheckoutV2CheckoutSessionForm({ copy = defaultChecko
284
279
  if (!email)
285
280
  setWalletConfirming(false);
286
281
  return email;
287
- }, checkoutAnalytics: checkoutAnalytics, checkoutSessionId: checkoutSessionId, className: 'shared-checkout-v2-express-buttons', confirmEmail: false, customerEmail: resolvedCustomerEmail, customerName: customerName, initialAvailable: initialWalletAvailable, keepInitialAvailableOnReady: initialWalletAvailable === true, onAvailabilityChange: handleWalletAvailabilityChange, onCancel: () => { setWalletConfirming(false); onWalletCancel === null || onWalletCancel === void 0 ? void 0 : onWalletCancel(); }, onError: (message) => setSharedError(message, true), onPaymentInfoSubmitted: onPaymentInfoSubmitted, onPaymentRejected: () => { setWalletConfirming(false); setSelectedMethod('card'); }, onSuccess: () => trackCheckoutSuccess(), onEmbeddedComplete: () => setCompleted(true), onVerificationPending: () => setProviderConfirmed(true), options: expressCheckoutOptions, returnUrl: returnUrl, summaryLabel: expressCheckoutSummaryLabel, supportedCountries: normalizedSupportedCountries, unsupportedCountryMessage: unsupportedCountryMessage }), _jsx("span", { className: 'shared-checkout-v2-sr-only', children: walletAriaLabel })] })] }) : null, _jsxs("div", { hidden: effectiveSelectedMethod !== 'card', className: [
282
+ }, checkoutAnalytics: checkoutAnalytics, checkoutSessionId: checkoutSessionId, className: 'shared-checkout-v2-express-buttons', confirmEmail: false, customerEmail: resolvedCustomerEmail, customerName: customerName, initialAvailable: initialWalletAvailable, keepInitialAvailableOnReady: initialWalletAvailable === true, onAvailabilityChange: handleWalletAvailabilityChange, onCancel: () => { setWalletConfirming(false); onWalletCancel === null || onWalletCancel === void 0 ? void 0 : onWalletCancel(); }, onError: (message, details) => setSharedError(message, true, details), onPaymentInfoSubmitted: onPaymentInfoSubmitted, onPaymentRejected: () => { setWalletConfirming(false); setSelectedMethod('card'); }, onSuccess: () => trackCheckoutSuccess(), onEmbeddedComplete: () => setCompleted(true), onVerificationPending: () => setProviderConfirmed(true), options: expressCheckoutOptions, returnUrl: returnUrl, summaryLabel: expressCheckoutSummaryLabel, supportedCountries: normalizedSupportedCountries, unsupportedCountryMessage: unsupportedCountryMessage }), _jsx("span", { className: 'shared-checkout-v2-sr-only', children: walletAriaLabel })] })] }) : null, _jsxs("div", { hidden: effectiveSelectedMethod !== 'card', className: [
288
283
  'shared-checkout-v2-card-panel',
289
284
  effectiveSelectedMethod === 'card' ? 'is-visible' : '',
290
285
  ]
@@ -1,5 +1,6 @@
1
1
  import type { AvailablePaymentMethods, StripeCheckoutExpressCheckoutElementOptions } from '@stripe/stripe-js';
2
2
  import { type StripeSubscriptionCheckoutAnalyticsContext } from '../services/checkoutCompletionAnalytics.service.js';
3
+ import { type StripeCheckoutErrorDetails } from '../services/stripeCheckoutError.js';
3
4
  export type StripeWalletCheckoutSuccess = {
4
5
  checkoutSessionId: string | null;
5
6
  };
@@ -25,7 +26,7 @@ export type StripeCheckoutExpressCheckoutButtonProps = {
25
26
  onElementMount?: () => void;
26
27
  onElementRetry?: () => void;
27
28
  onCancel?: () => void;
28
- onError?: (message: string | null) => void;
29
+ onError?: (message: string | null, details?: StripeCheckoutErrorDetails) => void;
29
30
  onPaymentInfoSubmitted?: () => void | Promise<void>;
30
31
  onPaymentRejected?: (input: {
31
32
  declineCode?: string;
@@ -6,8 +6,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
6
6
  import { ExpressCheckoutElement, useCheckout, } from '@stripe/react-stripe-js/checkout';
7
7
  import { queueStripeSubscriptionCheckoutStarted, trackPaidStripeSubscriptionCheckoutCompleted, trackStripeSubscriptionPaymentInfoSubmitted, } from '../services/checkoutCompletionAnalytics.service.js';
8
8
  import { getUnsupportedCheckoutCountryMessage, normalizeSupportedCheckoutCountries, } from './checkoutCountries.js';
9
- import { classifyCheckoutFailure, trackCheckoutCanceled, trackCheckoutFailureShown, } from '../../../services/checkoutObservability.service.js';
10
- import { toAnalyticsPaymentMethod } from '../../../services/paymentMethodAnalytics.service.js';
9
+ import { trackCheckoutCanceled, trackCheckoutFailureShown, } from '../../../services/checkoutObservability.service.js';
10
+ import { normalizeStripeCheckoutError } from '../services/stripeCheckoutError.js';
11
11
  const ExpressCheckoutElementWithCancel = ExpressCheckoutElement;
12
12
  const buildDefaultOptions = () => ({
13
13
  buttonHeight: 55,
@@ -32,27 +32,6 @@ const buildDefaultOptions = () => ({
32
32
  paypal: 'never',
33
33
  },
34
34
  });
35
- const normalizeStripeCheckoutProviderError = (error) => {
36
- if (!error || typeof error !== 'object') {
37
- return {};
38
- }
39
- const record = error;
40
- const paymentFailed = record.paymentFailed && typeof record.paymentFailed === 'object'
41
- ? record.paymentFailed
42
- : null;
43
- return {
44
- code: typeof record.code === 'string' ? record.code : undefined,
45
- decline_code: typeof record.decline_code === 'string' ? record.decline_code : undefined,
46
- paymentFailed: paymentFailed
47
- ? {
48
- declineCode: typeof paymentFailed.declineCode === 'string'
49
- ? paymentFailed.declineCode
50
- : undefined,
51
- }
52
- : undefined,
53
- type: typeof record.type === 'string' ? record.type : undefined,
54
- };
55
- };
56
35
  export function StripeCheckoutExpressCheckoutButton({ beforeConfirm, checkoutAnalytics, checkoutSessionId, returnUrl, confirmEmail = true, customerEmail, className, options, availabilityPaymentMethods = ['applePay'], initialAvailable, keepInitialAvailableOnReady = false, serverUpdateKey, supportedCountries, onServerUpdate, onAvailabilityChange, onElementMount, onElementRetry, onCancel, onError, onPaymentInfoSubmitted, onPaymentRejected, onSuccess, onEmbeddedComplete, onVerificationPending, unsupportedCountryMessage, }) {
57
36
  const checkoutState = useCheckout();
58
37
  const [completed, setCompleted] = useState(false);
@@ -129,17 +108,11 @@ export function StripeCheckoutExpressCheckoutButton({ beforeConfirm, checkoutAna
129
108
  return false;
130
109
  }
131
110
  const message = updateResult.error.message || 'Unable to update checkout session.';
111
+ const details = normalizeStripeCheckoutError(message, updateResult.error, paymentMethod);
132
112
  if (checkoutAnalytics) {
133
- trackCheckoutFailureShown({
134
- analytics: checkoutAnalytics,
135
- checkoutSessionId,
136
- errorMessage: message,
137
- failureStage: 'wallet_session_update',
138
- paymentMethod,
139
- provider: 'stripe',
140
- });
113
+ trackCheckoutFailureShown(Object.assign({ analytics: checkoutAnalytics, checkoutSessionId, errorMessage: message, failureStage: 'wallet_session_update', provider: 'stripe' }, details));
141
114
  }
142
- onError === null || onError === void 0 ? void 0 : onError(message);
115
+ onError === null || onError === void 0 ? void 0 : onError(message, details);
143
116
  return false;
144
117
  }
145
118
  appliedServerUpdateKeyRef.current = normalizedServerUpdateKey;
@@ -188,23 +161,14 @@ export function StripeCheckoutExpressCheckoutButton({ beforeConfirm, checkoutAna
188
161
  paymentMethod }));
189
162
  };
190
163
  const reportFailure = (message, failureStage, paymentMethod, providerError) => {
191
- var _a, _b;
164
+ const details = normalizeStripeCheckoutError(message, providerError, paymentMethod);
192
165
  if (checkoutAnalytics) {
193
- trackCheckoutFailureShown({
194
- analytics: checkoutAnalytics,
195
- checkoutSessionId,
196
- errorMessage: message,
197
- failureStage,
198
- paymentMethod,
199
- provider: 'stripe',
200
- providerDeclineCode: (_a = providerError === null || providerError === void 0 ? void 0 : providerError.decline_code) !== null && _a !== void 0 ? _a : (_b = providerError === null || providerError === void 0 ? void 0 : providerError.paymentFailed) === null || _b === void 0 ? void 0 : _b.declineCode,
201
- providerErrorCode: providerError === null || providerError === void 0 ? void 0 : providerError.code,
202
- providerErrorType: providerError === null || providerError === void 0 ? void 0 : providerError.type,
203
- });
166
+ trackCheckoutFailureShown(Object.assign({ analytics: checkoutAnalytics, checkoutSessionId, errorMessage: message, failureStage, provider: 'stripe' }, details));
204
167
  }
205
- onError === null || onError === void 0 ? void 0 : onError(isCheckoutEmailError(providerError) ? 'Enter a valid email address to continue.' : message);
168
+ onError === null || onError === void 0 ? void 0 : onError(isCheckoutEmailError(providerError) ? 'Enter a valid email address to continue.' : message, details);
169
+ return details;
206
170
  };
207
- const verifyPaywall = async () => {
171
+ const verifyPaywall = async (paymentMethod) => {
208
172
  if (verificationInFlightRef.current || completedRef.current)
209
173
  return true;
210
174
  verificationInFlightRef.current = true;
@@ -220,7 +184,7 @@ export function StripeCheckoutExpressCheckoutButton({ beforeConfirm, checkoutAna
220
184
  catch (error) {
221
185
  const message = error instanceof Error ? error.message : 'Unable to confirm payment';
222
186
  setVerificationError(message);
223
- onError === null || onError === void 0 ? void 0 : onError(message);
187
+ onError === null || onError === void 0 ? void 0 : onError(message, normalizeStripeCheckoutError(message, error, paymentMethod));
224
188
  onVerificationPending === null || onVerificationPending === void 0 ? void 0 : onVerificationPending();
225
189
  return true;
226
190
  }
@@ -230,7 +194,7 @@ export function StripeCheckoutExpressCheckoutButton({ beforeConfirm, checkoutAna
230
194
  }
231
195
  };
232
196
  const handleConfirm = async (event) => {
233
- var _a, _b, _c, _d, _e, _f;
197
+ var _a, _b, _c;
234
198
  if (completedRef.current)
235
199
  return;
236
200
  // Checkout Sessions omits the Express Checkout onClick callback. Confirmation
@@ -294,7 +258,7 @@ export function StripeCheckoutExpressCheckoutButton({ beforeConfirm, checkoutAna
294
258
  if ((preparedCustomerEmail === null || preparedCustomerEmail === void 0 ? void 0 : preparedCustomerEmail.trim()) !== (customerEmail === null || customerEmail === void 0 ? void 0 : customerEmail.trim())) {
295
259
  const message = 'Your email was updated. Please select your payment method again.';
296
260
  event.paymentFailed({ reason: 'invalid_payment_data', message });
297
- onError === null || onError === void 0 ? void 0 : onError(message);
261
+ onError === null || onError === void 0 ? void 0 : onError(message, normalizeStripeCheckoutError(message, undefined, event.expressPaymentType));
298
262
  return;
299
263
  }
300
264
  if (checkoutAnalytics) {
@@ -306,20 +270,12 @@ export function StripeCheckoutExpressCheckoutButton({ beforeConfirm, checkoutAna
306
270
  : {})), { expressCheckoutConfirmEvent: event, redirect: 'if_required' }));
307
271
  if (result.type === 'error') {
308
272
  const message = result.error.message || 'Wallet checkout failed.';
309
- const providerError = normalizeStripeCheckoutProviderError(result.error);
310
- reportFailure(message, 'wallet_confirmation', event.expressPaymentType, providerError);
311
- const declineCode = (_f = (_d = providerError.decline_code) !== null && _d !== void 0 ? _d : (_e = providerError.paymentFailed) === null || _e === void 0 ? void 0 : _e.declineCode) !== null && _f !== void 0 ? _f : undefined;
312
- if (classifyCheckoutFailure({
313
- errorMessage: message,
314
- provider: 'stripe',
315
- providerDeclineCode: declineCode,
316
- providerErrorCode: providerError.code,
317
- providerErrorType: providerError.type,
318
- }) === 'payment_rejection') {
273
+ const details = reportFailure(message, 'wallet_confirmation', event.expressPaymentType, result.error);
274
+ if (details.category === 'payment_rejection') {
319
275
  onPaymentRejected === null || onPaymentRejected === void 0 ? void 0 : onPaymentRejected({
320
- declineCode,
276
+ declineCode: details.providerDeclineCode,
321
277
  message,
322
- paymentMethod: toAnalyticsPaymentMethod(event.expressPaymentType) || undefined,
278
+ paymentMethod: details.paymentMethod,
323
279
  });
324
280
  }
325
281
  event.paymentFailed({ reason: 'fail', message });
@@ -327,7 +283,7 @@ export function StripeCheckoutExpressCheckoutButton({ beforeConfirm, checkoutAna
327
283
  }
328
284
  onError === null || onError === void 0 ? void 0 : onError(null);
329
285
  if (typeof window !== 'undefined') {
330
- if (await verifyPaywall())
286
+ if (await verifyPaywall(event.expressPaymentType))
331
287
  return;
332
288
  await trackCheckoutSuccess();
333
289
  window.location.assign(returnUrl);
@@ -1,6 +1,7 @@
1
1
  import type { Stripe } from '@stripe/stripe-js';
2
2
  import { type PlatformWalletPaymentMethod } from './walletPlatform.js';
3
3
  import { type StripeSubscriptionCheckoutAnalyticsContext } from '../services/checkoutCompletionAnalytics.service.js';
4
+ import { type StripeCheckoutErrorDetails } from '../services/stripeCheckoutError.js';
4
5
  export type StripeWalletFirstCheckoutCopy = {
5
6
  /** Benefit bullets under the wallet header, per wallet. */
6
7
  walletBenefits: Record<PlatformWalletPaymentMethod, readonly string[]>;
@@ -28,7 +29,7 @@ export type StripeWalletFirstCheckoutProps = {
28
29
  customerName?: string | null;
29
30
  /** The visitor closed the Apple Pay or Google Pay sheet without paying, e.g. to offer a discount. */
30
31
  onCancel?: () => void;
31
- onError?: (message: string | null) => void;
32
+ onError?: (message: string | null, details?: StripeCheckoutErrorDetails) => void;
32
33
  /**
33
34
  * Called after a paid checkout. Return `true` when the caller has already moved the visitor on
34
35
  * (e.g. client-side navigation to the next step); a card payment then skips the `returnUrl` reload.
@@ -25,6 +25,7 @@ import { stripeWalletFirstCheckoutStyles } from './StripeWalletFirstCheckout.sty
25
25
  import { queueStripeSubscriptionCheckoutStarted, trackPaidStripeSubscriptionCheckoutCompleted, trackStripeCheckoutShown, trackStripeSubscriptionPaymentInfoSubmitted, } from '../services/checkoutCompletionAnalytics.service.js';
26
26
  import { trackCheckoutFailureShown } from '../../../services/checkoutObservability.service.js';
27
27
  import { useCheckoutShownOnce } from '../hooks/useCheckoutShownOnce.js';
28
+ import { normalizeStripeCheckoutError } from '../services/stripeCheckoutError.js';
28
29
  const appearance = {
29
30
  labels: 'above',
30
31
  variables: {
@@ -102,16 +103,16 @@ function StripeWalletFirstCheckoutForm({ amountCents, checkoutAnalytics, checkou
102
103
  const timer = window.setTimeout(() => window.dispatchEvent(new Event('resize')), 0);
103
104
  return () => window.clearTimeout(timer);
104
105
  }, [selected]);
105
- const showError = (message, providerError, alreadyTracked = false) => {
106
+ const showError = (message, details, alreadyTracked = false) => {
107
+ const errorDetails = message ? details !== null && details !== void 0 ? details : normalizeStripeCheckoutError(message, undefined, 'card') : undefined;
106
108
  if (message && checkoutAnalytics && !alreadyTracked) {
107
- trackCheckoutFailureShown({
108
- analytics: checkoutAnalytics, checkoutSessionId, errorMessage: message,
109
- failureStage: 'card_form', paymentMethod: 'card', provider: 'stripe',
110
- providerDeclineCode: providerError === null || providerError === void 0 ? void 0 : providerError.decline_code, providerErrorCode: providerError === null || providerError === void 0 ? void 0 : providerError.code, providerErrorType: providerError === null || providerError === void 0 ? void 0 : providerError.type,
111
- });
109
+ trackCheckoutFailureShown(Object.assign({ analytics: checkoutAnalytics, checkoutSessionId, errorMessage: message, failureStage: 'card_form', provider: 'stripe' }, errorDetails));
112
110
  }
113
111
  setError(message);
114
- onError === null || onError === void 0 ? void 0 : onError(message);
112
+ if (message)
113
+ onError === null || onError === void 0 ? void 0 : onError(message, errorDetails);
114
+ else
115
+ onError === null || onError === void 0 ? void 0 : onError(message);
115
116
  };
116
117
  /** Resolves true when the caller's onSuccess handled the navigation itself. */
117
118
  const trackSuccess = async (embedded = false) => {
@@ -161,7 +162,8 @@ function StripeWalletFirstCheckoutForm({ amountCents, checkoutAnalytics, checkou
161
162
  }
162
163
  const result = await checkout.confirm({ redirect: 'if_required' });
163
164
  if (result.type === 'error') {
164
- showError(result.error.message || copy.paymentFailed, result.error);
165
+ const message = result.error.message || copy.paymentFailed;
166
+ showError(message, normalizeStripeCheckoutError(message, result.error, 'card'));
165
167
  submitInFlight.current = false;
166
168
  setSubmitting(false);
167
169
  return;
@@ -181,7 +183,7 @@ function StripeWalletFirstCheckoutForm({ amountCents, checkoutAnalytics, checkou
181
183
  // where the customer paid, until the success screen takes over.
182
184
  const paymentStatus = completed ? copy.paymentConfirmed : providerConfirmed ? copy.verifyingPayment : null;
183
185
  const locked = Boolean(paymentStatus) && !error;
184
- return (_jsx(CheckoutLayout, { copy: copy, wallet: wallet, selected: selected, onSelect: onSelect, disabled: submitting || walletConfirming || locked, style: style, walletNote: selected === 'wallet' ? paymentStatus : null, walletSlot: _jsxs(_Fragment, { children: [_jsx("div", { className: 'wfc-wallet-button', "data-ready": walletAvailable === true, children: _jsx(StripeCheckoutExpressCheckoutButton, { amountCents: amountCents, availabilityPaymentMethods: [wallet], beforeConfirm: async () => { setWalletConfirming(true); return customerEmail || null; }, checkoutAnalytics: checkoutAnalytics, checkoutSessionId: checkoutSessionId, confirmEmail: false, customerEmail: customerEmail, customerName: customerName, onAvailabilityChange: setWalletAvailable, onCancel: () => { setWalletConfirming(false); onCancel === null || onCancel === void 0 ? void 0 : onCancel(); }, onEmbeddedComplete: () => setCompleted(true), onError: message => { setWalletConfirming(false); showError(message, undefined, true); }, onPaymentRejected: () => { setWalletConfirming(false); onSelect('card'); }, onSuccess: async () => { await trackSuccess(); }, onVerificationPending: () => setProviderConfirmed(true), options: expressOptions, returnUrl: returnUrl, summaryLabel: summaryLabel }) }), walletAvailable === null ? _jsx("span", { className: 'wfc-progress wfc-progress--overlay', role: 'status', "aria-label": copy.processingLabel }) : null, walletAvailable === false ? _jsx("p", { className: 'wfc-wallet-unavailable', role: 'status', children: copy.walletUnavailableNote.replace('{wallet}', copy.walletLabels[wallet]) }) : null] }), cardBody: _jsxs("form", { className: 'wfc-card-form', onSubmit: event => void submitCard(event), children: [_jsx(PaymentElement, { options: paymentElementOptions, onChange: event => { setPaymentElementComplete(event.complete); if (!event.empty)
186
+ return (_jsx(CheckoutLayout, { copy: copy, wallet: wallet, selected: selected, onSelect: onSelect, disabled: submitting || walletConfirming || locked, style: style, walletNote: selected === 'wallet' ? paymentStatus : null, walletSlot: _jsxs(_Fragment, { children: [_jsx("div", { className: 'wfc-wallet-button', "data-ready": walletAvailable === true, children: _jsx(StripeCheckoutExpressCheckoutButton, { amountCents: amountCents, availabilityPaymentMethods: [wallet], beforeConfirm: async () => { setWalletConfirming(true); return customerEmail || null; }, checkoutAnalytics: checkoutAnalytics, checkoutSessionId: checkoutSessionId, confirmEmail: false, customerEmail: customerEmail, customerName: customerName, onAvailabilityChange: setWalletAvailable, onCancel: () => { setWalletConfirming(false); onCancel === null || onCancel === void 0 ? void 0 : onCancel(); }, onEmbeddedComplete: () => setCompleted(true), onError: (message, details) => { setWalletConfirming(false); showError(message, details, true); }, onPaymentRejected: () => { setWalletConfirming(false); onSelect('card'); }, onSuccess: async () => { await trackSuccess(); }, onVerificationPending: () => setProviderConfirmed(true), options: expressOptions, returnUrl: returnUrl, summaryLabel: summaryLabel }) }), walletAvailable === null ? _jsx("span", { className: 'wfc-progress wfc-progress--overlay', role: 'status', "aria-label": copy.processingLabel }) : null, walletAvailable === false ? _jsx("p", { className: 'wfc-wallet-unavailable', role: 'status', children: copy.walletUnavailableNote.replace('{wallet}', copy.walletLabels[wallet]) }) : null] }), cardBody: _jsxs("form", { className: 'wfc-card-form', onSubmit: event => void submitCard(event), children: [_jsx(PaymentElement, { options: paymentElementOptions, onChange: event => { setPaymentElementComplete(event.complete); if (!event.empty)
185
187
  onCardEngaged(); }, onReady: () => setPaymentElementReady(true) }), _jsx("button", { type: 'submit', className: 'wfc-submit', disabled: locked || submitting || !paymentElementReady, "aria-live": 'polite', children: locked && paymentStatus ? paymentStatus : submitting ? copy.processingLabel : copy.cardSubmitLabel }), _jsx("p", { className: 'wfc-secure', children: copy.secureNote })] }), footer: error ? _jsx("p", { className: 'wfc-error', role: 'alert', children: error }) : null }));
186
188
  }
187
189
  /** Shared by the loading and live states so switching between them moves nothing. */
@@ -1,2 +1,3 @@
1
1
  export * from './checkoutCompletionAnalytics.service.js';
2
2
  export * from './stripe.service.js';
3
+ export type { StripeCheckoutErrorDetails } from './stripeCheckoutError.js';
@@ -0,0 +1,10 @@
1
+ import { type CheckoutFailureCategory } from '../../../services/checkoutObservability.service.js';
2
+ import { type AnalyticsPaymentMethod } from '../../../services/paymentMethodAnalytics.service.js';
3
+ export type StripeCheckoutErrorDetails = {
4
+ category: CheckoutFailureCategory;
5
+ paymentMethod?: AnalyticsPaymentMethod;
6
+ providerDeclineCode?: string;
7
+ providerErrorCode?: string;
8
+ providerErrorType?: string;
9
+ };
10
+ export declare function normalizeStripeCheckoutError(message: string, error?: unknown, paymentMethod?: unknown): StripeCheckoutErrorDetails;
@@ -0,0 +1,14 @@
1
+ import { classifyCheckoutFailure } from '../../../services/checkoutObservability.service.js';
2
+ import { toAnalyticsPaymentMethod } from '../../../services/paymentMethodAnalytics.service.js';
3
+ const asRecord = (value) => value && typeof value === 'object' ? value : {};
4
+ const asCode = (value) => typeof value === 'string' && value.trim() ? value.trim() : undefined;
5
+ export function normalizeStripeCheckoutError(message, error, paymentMethod) {
6
+ var _a;
7
+ const record = asRecord(error);
8
+ const providerFields = {
9
+ providerDeclineCode: (_a = asCode(record.decline_code)) !== null && _a !== void 0 ? _a : asCode(asRecord(record.paymentFailed).declineCode),
10
+ providerErrorCode: asCode(record.code),
11
+ providerErrorType: asCode(record.type),
12
+ };
13
+ return Object.assign(Object.assign({}, providerFields), { category: classifyCheckoutFailure(Object.assign({ errorMessage: message, provider: 'stripe' }, providerFields)), paymentMethod: toAnalyticsPaymentMethod(paymentMethod) });
14
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funnelsgrove/payments",
3
- "version": "0.54.0",
3
+ "version": "0.56.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/The-Solid-Grove/funnelsgrove.git",