diff --git a/docs/adr/BILLING-CHECKOUT-0031-checkout-journey-instrumentation-contract.md b/docs/adr/BILLING-CHECKOUT-0031-checkout-journey-instrumentation-contract.md index a1998bdef76..8937da8d7db 100644 --- a/docs/adr/BILLING-CHECKOUT-0031-checkout-journey-instrumentation-contract.md +++ b/docs/adr/BILLING-CHECKOUT-0031-checkout-journey-instrumentation-contract.md @@ -59,7 +59,11 @@ Every event carries a frozen `CheckoutJourneyContext`: `checkout_journey_id`, `checkout_entered_at` (UTC), `assignment_status`, optional `assigned_arm`, `entry_flow`, `entry_source`, and optional `ui_mode`/`billing_op_id`. `ui_mode` records the checkout UI the user actually saw (`embedded`/`hosted`), -so a frozen arm can be reconciled against real experience. `schema_version` is +so a frozen arm can be reconciled against real experience. The two +`payment_element_*` phases additionally carry `element` (`payment`/`address`), +because the shared Elements group mounts more than one element and a funnel +that counts readiness or attributes a mount failure must know which one +reported it. `schema_version` is stamped on every payload. Correlation rides on `checkout_journey_id` (all events) and `billing_op_id` (from `operation_linked` onward, the join to the terminal `billing.*` taxonomy), plus each provider's own native event id diff --git a/src/locales/en/main.json b/src/locales/en/main.json index d05c5564453..60f55ebc04c 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -3127,6 +3127,7 @@ "confirmChangeTitle": "Review your scheduled change", "paymentPopupBlocked": "Couldn't open the payment page — please allow popups and try again.", "paymentMethod": "Payment method", + "billingAddress": "Billing address", "stripeMethodChoice": "Your payment details are handled securely by Stripe.", "alipayRenewalNote": "Alipay authorization will also be used for automatic renewals and future purchases.", "payAndSubscribe": "Pay and subscribe", diff --git a/src/platform/telemetry/checkoutJourneyEvent.test.ts b/src/platform/telemetry/checkoutJourneyEvent.test.ts index d1fa486d949..e696b73d966 100644 --- a/src/platform/telemetry/checkoutJourneyEvent.test.ts +++ b/src/platform/telemetry/checkoutJourneyEvent.test.ts @@ -110,15 +110,19 @@ describe('getCheckoutJourneyTelemetryEventPayload', () => { }) }) - it('distinguishes the element failure phase', () => { + it('distinguishes the failing element from the failure phase', () => { const event: CheckoutJourneyTelemetryEvent = { ...baseContext, phase: 'payment_element_failed', assignment_status: 'resolved', assigned_arm: 'treatment', + element: 'address', element_phase: 'mount' } const payload = getCheckoutJourneyTelemetryEventPayload(event) - expect(payload).toMatchObject({ element_phase: 'mount' }) + expect(payload).toMatchObject({ + element: 'address', + element_phase: 'mount' + }) }) }) diff --git a/src/platform/telemetry/types.ts b/src/platform/telemetry/types.ts index 412400deb0f..367a4f81728 100644 --- a/src/platform/telemetry/types.ts +++ b/src/platform/telemetry/types.ts @@ -1017,6 +1017,8 @@ export type CheckoutEntrySource = | 'other' | 'unknown' type CheckoutElementPhase = 'init' | 'mount' | 'update' +/** Which Stripe element in the shared group the observation came from. */ +type CheckoutElementKind = 'payment' | 'address' type CheckoutSubmitPhase = 'validation' | 'token_creation' /** @@ -1054,9 +1056,13 @@ type CheckoutJourneyPreviewFailed = { error_code?: BillingErrorCode preview_revision?: string } -type CheckoutJourneyPaymentElementReady = { phase: 'payment_element_ready' } +type CheckoutJourneyPaymentElementReady = { + phase: 'payment_element_ready' + element: CheckoutElementKind +} type CheckoutJourneyPaymentElementFailed = { phase: 'payment_element_failed' + element: CheckoutElementKind element_phase: CheckoutElementPhase error_code?: string } @@ -1146,6 +1152,7 @@ export function getCheckoutJourneyTelemetryEventPayload( }), ...('error_code' in event && event.error_code !== undefined && { error_code: event.error_code }), + ...('element' in event && { element: event.element }), ...('element_phase' in event && { element_phase: event.element_phase }), ...('submit_phase' in event && { submit_phase: event.submit_phase }) } diff --git a/src/platform/workspace/components/UnifiedStripePaymentSelector.test.ts b/src/platform/workspace/components/UnifiedStripePaymentSelector.test.ts index b21220af129..bc4c36b37e2 100644 --- a/src/platform/workspace/components/UnifiedStripePaymentSelector.test.ts +++ b/src/platform/workspace/components/UnifiedStripePaymentSelector.test.ts @@ -24,9 +24,20 @@ const stripeMocks = vi.hoisted(() => { const mount = vi.fn() const destroy = vi.fn() const on = vi.fn() + const addressMount = vi.fn() + const addressDestroy = vi.fn() + const addressOn = vi.fn() const submit = vi.fn() const update = vi.fn() - const create = vi.fn(() => ({ mount, destroy, on })) + const paymentElement = { mount, destroy, on } + const addressElement = { + mount: addressMount, + destroy: addressDestroy, + on: addressOn + } + const create = vi.fn((type: string) => + type === 'address' ? addressElement : paymentElement + ) const elements = { submit, create, update } const createConfirmationToken = vi.fn() const stripe = { @@ -37,6 +48,9 @@ const stripeMocks = vi.hoisted(() => { mount, destroy, on, + addressMount, + addressDestroy, + addressOn, submit, update, create, @@ -60,6 +74,7 @@ const i18n = createI18n({ subscription: { preview: { paymentMethod: 'Payment method', + billingAddress: 'Billing address', stripeMethodChoice: 'Choose a payment method', alipayRenewalNote: 'Alipay renewal note', payAndSubscribe: 'Pay and subscribe', @@ -92,6 +107,13 @@ describe('UnifiedStripePaymentSelector', () => { handler?.[1]?.(arg) } + function fireAddressElementEvent(name: string, arg?: unknown) { + const handler = stripeMocks.addressOn.mock.calls.find( + ([event]) => event === name + ) + handler?.[1]?.(arg) + } + let seededJourneyId = '' beforeEach(() => { @@ -109,11 +131,19 @@ describe('UnifiedStripePaymentSelector', () => { vi.stubEnv('VITE_STRIPE_PUBLISHABLE_KEY', 'pk_test_example') stripeMocks.loadStripe.mockResolvedValue(stripeMocks.stripe) stripeMocks.stripe.elements.mockReturnValue(stripeMocks.elements) - stripeMocks.create.mockReturnValue({ - mount: stripeMocks.mount, - destroy: stripeMocks.destroy, - on: stripeMocks.on - }) + stripeMocks.create.mockImplementation((type: string) => + type === 'address' + ? { + mount: stripeMocks.addressMount, + destroy: stripeMocks.addressDestroy, + on: stripeMocks.addressOn + } + : { + mount: stripeMocks.mount, + destroy: stripeMocks.destroy, + on: stripeMocks.on + } + ) stripeMocks.submit.mockResolvedValue({}) stripeMocks.update.mockResolvedValue(undefined) stripeMocks.createConfirmationToken.mockResolvedValue({ @@ -123,6 +153,23 @@ describe('UnifiedStripePaymentSelector', () => { afterEach(cleanup) + it('leaves billing address collection to the Address Element alone', async () => { + renderSelector() + await waitFor(() => expect(stripeMocks.mount).toHaveBeenCalled()) + + // Two address forms in one group can disagree, and the one the issuer sees + // would then contradict the one collected for AVS. + expect(stripeMocks.create).toHaveBeenCalledWith( + 'payment', + expect.objectContaining({ + fields: { billingDetails: { address: 'never' } } + }) + ) + expect(stripeMocks.create).toHaveBeenCalledWith('address', { + mode: 'billing' + }) + }) + describe('checkout journey instrumentation', () => { it('emits payment_element_ready on the ready callback for the live mount', async () => { renderSelector() @@ -131,10 +178,29 @@ describe('UnifiedStripePaymentSelector', () => { fireStripeElementEvent('ready') expect(mockTrackCheckoutJourneyEvent).toHaveBeenCalledWith( - expect.objectContaining({ phase: 'payment_element_ready' }) + expect.objectContaining({ + phase: 'payment_element_ready', + element: 'payment' + }) ) }) + it('distinguishes the address readiness from the payment element', async () => { + renderSelector() + await waitFor(() => + expect(stripeMocks.addressMount).toHaveBeenCalledTimes(1) + ) + + fireStripeElementEvent('ready') + fireAddressElementEvent('ready') + + const readyElements = mockTrackCheckoutJourneyEvent.mock.calls + .map(([event]) => event) + .filter((event) => event.phase === 'payment_element_ready') + .map((event) => event.element) + expect(readyElements).toStrictEqual(['payment', 'address']) + }) + it('reports a mount failure with a safe code from loaderror', async () => { renderSelector() await waitFor(() => expect(stripeMocks.mount).toHaveBeenCalled()) @@ -147,6 +213,27 @@ describe('UnifiedStripePaymentSelector', () => { expect.objectContaining({ checkout_journey_id: seededJourneyId, phase: 'payment_element_failed', + element: 'payment', + element_phase: 'mount', + error_code: 'invalid_request' + }) + ) + }) + + it('reports an Address Element load failure as a mount failure', async () => { + renderSelector() + await waitFor(() => + expect(stripeMocks.addressMount).toHaveBeenCalledTimes(1) + ) + + fireAddressElementEvent('loaderror', { + error: { code: 'invalid_request' } + }) + + expect(mockTrackCheckoutJourneyEvent).toHaveBeenCalledWith( + expect.objectContaining({ + phase: 'payment_element_failed', + element: 'address', element_phase: 'mount', error_code: 'invalid_request' }) @@ -261,6 +348,7 @@ describe('UnifiedStripePaymentSelector', () => { radios: 'always', spacedAccordionItems: true }, + fields: { billingDetails: { address: 'never' } }, terms: { card: 'never' } }) expect(stripeMocks.mount).toHaveBeenCalledTimes(1) @@ -278,6 +366,34 @@ describe('UnifiedStripePaymentSelector', () => { expect(emitted().confirm).toEqual([['ctoken_1']]) }) + it('collects a billing address alongside the payment element', async () => { + renderSelector() + + await waitFor(() => + expect(stripeMocks.create).toHaveBeenCalledWith('address', { + mode: 'billing' + }) + ) + expect(stripeMocks.addressMount).toHaveBeenCalledTimes(1) + }) + + it('blocks submission until the billing address is valid', async () => { + const user = userEvent.setup() + stripeMocks.submit.mockResolvedValue({ + error: { code: 'incomplete_address', message: 'Enter your address' } + }) + const { emitted } = renderSelector() + + await waitFor(() => + expect(stripeMocks.addressMount).toHaveBeenCalledTimes(1) + ) + await user.click(screen.getByRole('button', { name: 'Pay and subscribe' })) + + expect(await screen.findByText('Enter your address')).toBeTruthy() + expect(stripeMocks.createConfirmationToken).not.toHaveBeenCalled() + expect(emitted().confirm).toBeUndefined() + }) + it('keeps the customer in the form when Stripe rejects its contents', async () => { const user = userEvent.setup() stripeMocks.submit.mockResolvedValue({ @@ -370,13 +486,16 @@ describe('UnifiedStripePaymentSelector', () => { }) }) - it('destroys the Stripe element when the preview unmounts', async () => { + it('destroys the Stripe elements when the preview unmounts', async () => { const { unmount } = renderSelector() - await waitFor(() => expect(stripeMocks.mount).toHaveBeenCalledTimes(1)) + await waitFor(() => + expect(stripeMocks.addressMount).toHaveBeenCalledTimes(1) + ) unmount() expect(stripeMocks.destroy).toHaveBeenCalledTimes(1) + expect(stripeMocks.addressDestroy).toHaveBeenCalledTimes(1) }) }) @@ -385,11 +504,19 @@ describe('UnifiedStripePaymentSelector payment method configuration', () => { vi.stubEnv('VITE_STRIPE_PUBLISHABLE_KEY', 'pk_test_example') stripeMocks.loadStripe.mockResolvedValue(stripeMocks.stripe) stripeMocks.stripe.elements.mockReturnValue(stripeMocks.elements) - stripeMocks.create.mockReturnValue({ - mount: stripeMocks.mount, - destroy: stripeMocks.destroy, - on: stripeMocks.on - }) + stripeMocks.create.mockImplementation((type: string) => + type === 'address' + ? { + mount: stripeMocks.addressMount, + destroy: stripeMocks.addressDestroy, + on: stripeMocks.addressOn + } + : { + mount: stripeMocks.mount, + destroy: stripeMocks.destroy, + on: stripeMocks.on + } + ) }) it('mounts against the served configuration instead of a hardcoded method list', async () => { diff --git a/src/platform/workspace/components/UnifiedStripePaymentSelector.vue b/src/platform/workspace/components/UnifiedStripePaymentSelector.vue index b9c0519e222..5d370e9ca2f 100644 --- a/src/platform/workspace/components/UnifiedStripePaymentSelector.vue +++ b/src/platform/workspace/components/UnifiedStripePaymentSelector.vue @@ -22,6 +22,12 @@ class="flex flex-col gap-6 xl:min-h-0 xl:flex-1 xl:overflow-x-hidden xl:overflow-y-auto xl:pr-1" >
+
+

+ {{ $t('subscription.preview.billingAddress') }} +

+
+
import type { Stripe, + StripeAddressElement, StripeElements, StripePaymentElement } from '@stripe/stripe-js' @@ -107,29 +114,103 @@ function emitPaymentJourneyPhase(phase: CheckoutJourneyPhaseEvent): void { } const paymentElementTarget = ref() +const addressElementTarget = ref() const stripeElements = ref() const configurationError = ref('') const isSubmitting = ref(false) const selectedMethodType = ref('') let stripe: Stripe | null = null let paymentElement: StripePaymentElement | undefined +let addressElement: StripeAddressElement | undefined -onMounted(async () => { - const publishableKey = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY - if (!publishableKey) { - configurationError.value = t('subscription.preview.stripeUnavailable') +function failElementInit(): void { + configurationError.value = t('subscription.preview.stripeUnavailable') + if (isUnmounted) return + emitPaymentJourneyPhase({ + phase: 'payment_element_failed', + element: 'payment', + element_phase: 'init' + }) +} + +function mountPaymentElement( + elements: StripeElements, + target: HTMLDivElement +): void { + paymentElement = elements.create('payment', { + layout: { + type: 'accordion', + defaultCollapsed: false, + radios: 'always', + spacedAccordionItems: true + }, + // The Address Element below is the single source of billing address. + // Left at the default, card would also render its own country/postal + // inputs, and a customer who filled the two differently would send the + // issuer an address that contradicts the one we collected for AVS. + fields: { billingDetails: { address: 'never' } }, + // Our terms note carries the recurring-charge authorization; Stripe's + // card mandate text would say it twice. + terms: { card: 'never' } + }) + paymentElement.mount(target) + paymentElement.on('ready', () => { + if (isUnmounted) return + emitPaymentJourneyPhase({ + phase: 'payment_element_ready', + element: 'payment' + }) + }) + paymentElement.on('loaderror', (event) => { + if (isUnmounted) return emitPaymentJourneyPhase({ phase: 'payment_element_failed', - element_phase: 'init' + element: 'payment', + element_phase: 'mount', + ...(event.error?.code && { error_code: event.error.code }) }) - return - } - if (!paymentMethodConfigurationId) { - configurationError.value = t('subscription.preview.stripeUnavailable') + }) + // Method-specific notes (e.g. the Alipay auto-renewal disclosure) key off + // whichever payment method the user has selected inside the element. + paymentElement.on('change', (event) => { + selectedMethodType.value = event.value?.type ?? '' + }) +} + +/** + * A full billing address feeds AVS to the issuer and Radar. In billing mode + * every field is required, and because the address shares the Payment + * Element's group, createConfirmationToken folds it into the token's + * billing_details. + */ +function mountAddressElement( + elements: StripeElements, + target: HTMLDivElement +): void { + addressElement = elements.create('address', { mode: 'billing' }) + addressElement.mount(target) + addressElement.on('ready', () => { + if (isUnmounted) return + emitPaymentJourneyPhase({ + phase: 'payment_element_ready', + element: 'address' + }) + }) + addressElement.on('loaderror', (event) => { + if (isUnmounted) return emitPaymentJourneyPhase({ phase: 'payment_element_failed', - element_phase: 'init' + element: 'address', + element_phase: 'mount', + ...(event.error?.code && { error_code: event.error.code }) }) + }) +} + +onMounted(async () => { + const publishableKey = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY + if (!publishableKey || !paymentMethodConfigurationId) { + failElementInit() return } // A non-positive amount means the caller mounted this before its quote @@ -141,21 +222,11 @@ onMounted(async () => { try { stripe = await loadStripe(publishableKey) } catch { - configurationError.value = t('subscription.preview.stripeUnavailable') - emitPaymentJourneyPhase({ - phase: 'payment_element_failed', - element_phase: 'init' - }) + failElementInit() return } if (!stripe || !paymentElementTarget.value || isUnmounted) { - configurationError.value = t('subscription.preview.stripeUnavailable') - if (!isUnmounted) { - emitPaymentJourneyPhase({ - phase: 'payment_element_failed', - element_phase: 'init' - }) - } + failElementInit() return } @@ -211,35 +282,10 @@ onMounted(async () => { } } }) - paymentElement = stripeElements.value.create('payment', { - layout: { - type: 'accordion', - defaultCollapsed: false, - radios: 'always', - spacedAccordionItems: true - }, - // Our terms note carries the recurring-charge authorization; Stripe's - // card mandate text would say it twice. - terms: { card: 'never' } - }) - paymentElement.mount(paymentElementTarget.value) - paymentElement.on('ready', () => { - if (isUnmounted) return - emitPaymentJourneyPhase({ phase: 'payment_element_ready' }) - }) - paymentElement.on('loaderror', (event) => { - if (isUnmounted) return - emitPaymentJourneyPhase({ - phase: 'payment_element_failed', - element_phase: 'mount', - ...(event.error?.code && { error_code: event.error.code }) - }) - }) - // Method-specific notes (e.g. the Alipay auto-renewal disclosure) key off - // whichever payment method the user has selected inside the element. - paymentElement.on('change', (event) => { - selectedMethodType.value = event.value?.type ?? '' - }) + mountPaymentElement(stripeElements.value, paymentElementTarget.value) + if (addressElementTarget.value) { + mountAddressElement(stripeElements.value, addressElementTarget.value) + } }) watch([() => amountCents, () => currency], ([amount, nextCurrency]) => { @@ -252,6 +298,7 @@ watch([() => amountCents, () => currency], ([amount, nextCurrency]) => { configurationError.value = t('g.error') emitPaymentJourneyPhase({ phase: 'payment_element_failed', + element: 'payment', element_phase: 'update' }) }) @@ -260,6 +307,7 @@ watch([() => amountCents, () => currency], ([amount, nextCurrency]) => { onBeforeUnmount(() => { isUnmounted = true paymentElement?.destroy() + addressElement?.destroy() }) async function submit() {