diff --git a/package.json b/package.json index 68c44727..5b4c0e15 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "processout.js", - "version": "1.9.21", + "version": "1.9.22", "description": "ProcessOut.js is a JavaScript library for ProcessOut's payment processing API.", "scripts": { "build:processout": "tsc -p src/processout && uglifyjs --compress --keep-fnames --ie8 dist/processout.js -o dist/processout.js", diff --git a/src/dynamic-checkout/payment-methods/apm.ts b/src/dynamic-checkout/payment-methods/apm.ts index 052c71d9..bf936d4b 100644 --- a/src/dynamic-checkout/payment-methods/apm.ts +++ b/src/dynamic-checkout/payment-methods/apm.ts @@ -102,10 +102,11 @@ module ProcessOut { const { apm } = this.paymentMethod const additionalData = this.paymentConfig.getAdditionalDataForGateway(apm.gateway_name) - const redirectUrl = + const redirectUrl = DynamicCheckoutOpenerLossUtils.markRedirectUrl( Object.keys(additionalData).length > 0 ? this.processOutInstance.appendAdditionalDataToUrl(apm.redirect_url, additionalData) - : apm.redirect_url + : apm.redirect_url, + ) DynamicCheckoutEventsUtils.dispatchPaymentSubmittedEvent({ payment_method_name: apm.gateway_name, @@ -114,6 +115,7 @@ module ProcessOut { return_url: this.paymentConfig.invoiceDetails.return_url || null, }) + const actionStartedAt = Date.now() this.processOutInstance.handleAction( redirectUrl, paymentToken => { @@ -183,6 +185,10 @@ module ProcessOut { ) }, error => { + if (this.handleOpenerLoss(error, actionStartedAt)) { + return + } + if (error.code === "customer.canceled") { this.resetContainerHtml().appendChild( new DynamicCheckoutPaymentCancelledView(this.processOutInstance, this.paymentConfig) @@ -280,6 +286,7 @@ module ProcessOut { return } + const actionStartedAt = Date.now() this.processOutInstance.handleAction( data.customer_action.value, paymentToken => { @@ -371,6 +378,10 @@ module ProcessOut { ) }, error => { + if (this.handleOpenerLoss(error, actionStartedAt)) { + return + } + if (error.code === "customer.canceled") { this.resetContainerHtml().appendChild( new DynamicCheckoutPaymentCancelledView( @@ -448,6 +459,32 @@ module ProcessOut { ) } + /** + * Must run first in the handleAction error callback: PO.js refocuses the window right after it. + * Returns true when the tab_closed was a lost opener and DC shows pending instead of cancelled. + */ + private handleOpenerLoss(error: Exception, actionStartedAt: number): boolean { + const { apm } = this.paymentMethod + const isOpenerLoss = DynamicCheckoutOpenerLossUtils.isOpenerLoss( + this.processOutInstance, + error, + { + mode: apm.opener_loss_handling, + gatewayName: apm.gateway_name, + invoiceId: this.paymentConfig.invoiceId, + actionStartedAt, + }, + ) + if (!isOpenerLoss) { + return false + } + + this.resetContainerHtml().appendChild( + new DynamicCheckoutPaymentPendingView(this.processOutInstance, this.paymentConfig).element, + ) + return true + } + private getChildrenElement() { const saveForFutureAttributes: Record = { type: "checkbox", diff --git a/src/dynamic-checkout/payment-methods/saved-apm.ts b/src/dynamic-checkout/payment-methods/saved-apm.ts index acbc01f1..140fdd5d 100644 --- a/src/dynamic-checkout/payment-methods/saved-apm.ts +++ b/src/dynamic-checkout/payment-methods/saved-apm.ts @@ -72,12 +72,14 @@ module ProcessOut { apm_customer_token.gateway_name, ) - const redirectUrl = Object.keys(additionalData).length > 0 - ? this.processOutInstance.appendAdditionalDataToUrl( - apm_customer_token.redirect_url, - additionalData, - ) - : apm_customer_token.redirect_url + const redirectUrl = DynamicCheckoutOpenerLossUtils.markRedirectUrl( + Object.keys(additionalData).length > 0 + ? this.processOutInstance.appendAdditionalDataToUrl( + apm_customer_token.redirect_url, + additionalData, + ) + : apm_customer_token.redirect_url, + ) DynamicCheckoutEventsUtils.dispatchPaymentSubmittedEvent({ payment_method_name: apm_customer_token.gateway_name, @@ -87,6 +89,7 @@ module ProcessOut { customer_token_id: apm_customer_token.customer_token_id, }) + const actionStartedAt = Date.now() return this.processOutInstance.handleAction( redirectUrl, paymentToken => { @@ -168,6 +171,10 @@ module ProcessOut { ) }, error => { + if (this.handleOpenerLoss(error, actionStartedAt)) { + return + } + if (error.code === "customer.canceled") { this.resetContainerHtml().appendChild( new DynamicCheckoutPaymentCancelledView( @@ -226,6 +233,32 @@ module ProcessOut { ) } + /** + * Must run first in the handleAction error callback: PO.js refocuses the window right after it. + * Returns true when the tab_closed was a lost opener and DC shows pending instead of cancelled. + */ + private handleOpenerLoss(error: Exception, actionStartedAt: number): boolean { + const { apm_customer_token } = this.paymentMethod + const isOpenerLoss = DynamicCheckoutOpenerLossUtils.isOpenerLoss( + this.processOutInstance, + error, + { + mode: apm_customer_token.opener_loss_handling, + gatewayName: apm_customer_token.gateway_name, + invoiceId: this.paymentConfig.invoiceId, + actionStartedAt, + }, + ) + if (!isOpenerLoss) { + return false + } + + this.resetContainerHtml().appendChild( + new DynamicCheckoutPaymentPendingView(this.processOutInstance, this.paymentConfig).element, + ) + return true + } + private handlePaymentSuccess(invoiceId: string, data) { this.resetContainerHtml().appendChild( new DynamicCheckoutPaymentSuccessView(this.processOutInstance, this.paymentConfig).element, diff --git a/src/dynamic-checkout/references.ts b/src/dynamic-checkout/references.ts index f8d3b210..72faca29 100644 --- a/src/dynamic-checkout/references.ts +++ b/src/dynamic-checkout/references.ts @@ -60,6 +60,7 @@ /// /// /// +/// /// /// /// diff --git a/src/dynamic-checkout/types/api.ts b/src/dynamic-checkout/types/api.ts index 01bad528..60136dd2 100644 --- a/src/dynamic-checkout/types/api.ts +++ b/src/dynamic-checkout/types/api.ts @@ -93,6 +93,8 @@ type Apm = { redirect_url?: string customer_token_id?: string gateway_name?: string + // "off" | "shadow" | "on"; see DynamicCheckoutOpenerLossUtils + opener_loss_handling?: string gateway_logo: { light_url: { raster: string diff --git a/src/dynamic-checkout/utils/opener-loss.ts b/src/dynamic-checkout/utils/opener-loss.ts new file mode 100644 index 00000000..53f816a5 --- /dev/null +++ b/src/dynamic-checkout/utils/opener-loss.ts @@ -0,0 +1,120 @@ +module ProcessOut { + /** + * Rollout mode for treating a `tab_closed` as a lost opener (e.g. after a COOP page) instead of a cancel. + * Sent by the API per APM payment method; a missing value means "off". + */ + export type OpenerLossHandling = "off" | "shadow" | "on" + + export type OpenerLossVerdict = "real_close" | "severed_link" + + export type OpenerLossPageState = { + hasFocus: boolean + visibilityState: string + } + + export type OpenerLossContext = { + mode?: string + gatewayName?: string + invoiceId?: string + actionStartedAt?: number + } + + const OPENER_LOSS_MODES: OpenerLossHandling[] = ["off", "shadow", "on"] + // Read by checkout /redirect, so /continue can show a "you can close this tab" landing instead of + // forwarding to the merchant when the PSP tab lost its link to the checkout. + const DYNAMIC_CHECKOUT_FLOW_QUERY = "po_flow=dynamic-checkout" + const OPENER_LOSS_TELEMETRY_MESSAGE = "dynamic checkout opener loss verdict" + + export class DynamicCheckoutOpenerLossUtils { + static markRedirectUrl(url: string): string { + if (!url) { + return url + } + return url + (url.indexOf("?") === -1 ? "?" : "&") + DYNAMIC_CHECKOUT_FLOW_QUERY + } + + static getMode(value?: string): OpenerLossHandling { + return OPENER_LOSS_MODES.indexOf(value as OpenerLossHandling) !== -1 + ? (value as OpenerLossHandling) + : "off" + } + + static readPageState(doc: Document = document): OpenerLossPageState { + return { + hasFocus: doc.hasFocus(), + visibilityState: doc.visibilityState, + } + } + + /** + * After a real close the browser activates the DC page before PO.js notices the closed tab. + * A severed opener leaves the shopper on the PSP tab, so the DC page is hidden or unfocused. + */ + static getVerdict(state: OpenerLossPageState): OpenerLossVerdict { + return state.hasFocus && state.visibilityState === "visible" ? "real_close" : "severed_link" + } + + /** + * Decides how DC handles a `customer.canceled` with reason `tab_closed`. It must run synchronously at the start of the error + * callback: PO.js calls `window.focus()` right after it, which would change the page state. + * Returns true when DC should treat the payment as pending instead of cancelled. + */ + static isOpenerLoss( + processOutInstance: ProcessOut, + error: Exception, + context: OpenerLossContext, + doc: Document = document, + ): boolean { + if ( + error.code !== "customer.canceled" || + !error.metadata || + error.metadata.reason !== "tab_closed" + ) { + return false + } + + const mode = DynamicCheckoutOpenerLossUtils.getMode(context.mode) + if (mode === "off") { + return false + } + + const state = DynamicCheckoutOpenerLossUtils.readPageState(doc) + const verdict = DynamicCheckoutOpenerLossUtils.getVerdict(state) + + DynamicCheckoutOpenerLossUtils.report(processOutInstance, context, mode, verdict, state) + + return mode === "on" && verdict === "severed_link" + } + + private static report( + processOutInstance: ProcessOut, + context: OpenerLossContext, + mode: OpenerLossHandling, + verdict: OpenerLossVerdict, + state: OpenerLossPageState, + ) { + processOutInstance.telemetryClient.report( + { + host: window && window.location ? window.location.host : "", + fileName: "dynamic-checkout/utils/opener-loss.ts", + lineNumber: 0, + message: OPENER_LOSS_TELEMETRY_MESSAGE, + category: "dynamic-checkout", + invoiceId: context.invoiceId, + data: { + mode: mode, + verdict: verdict, + gateway_name: context.gatewayName || "", + has_focus: state.hasFocus, + visibility_state: state.visibilityState, + ms_since_action_start: context.actionStartedAt + ? Date.now() - context.actionStartedAt + : null, + user_agent: typeof navigator !== "undefined" ? navigator.userAgent : "", + }, + }, + "info", + ) + } + } +} diff --git a/test/dynamic-checkout/opener-loss.test.ts b/test/dynamic-checkout/opener-loss.test.ts new file mode 100644 index 00000000..82d094e1 --- /dev/null +++ b/test/dynamic-checkout/opener-loss.test.ts @@ -0,0 +1,155 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" +import { loadOpenerLoss } from "../support/loadNamespace" + +let OpenerLoss: Record + +beforeEach(() => { + OpenerLoss = loadOpenerLoss().DynamicCheckoutOpenerLossUtils +}) + +const tabClosed = { code: "customer.canceled", metadata: { reason: "tab_closed" } } +const overlayCancel = { code: "customer.canceled" } + +function fakeDocument(hasFocus: boolean, visibilityState: string) { + return { hasFocus: () => hasFocus, visibilityState } +} + +function fakeProcessOut() { + return { telemetryClient: { report: vi.fn() } } +} + +describe("DynamicCheckoutOpenerLossUtils.getMode", () => { + it.each([ + ["off", "off"], + ["shadow", "shadow"], + ["on", "on"], + [undefined, "off"], + ["", "off"], + ["ON", "off"], + ["unexpected", "off"], + ])("maps %s to %s", (input, expected) => { + expect(OpenerLoss.getMode(input)).toBe(expected) + }) +}) + +describe("DynamicCheckoutOpenerLossUtils.getVerdict", () => { + it.each([ + [true, "visible", "real_close"], + [false, "visible", "severed_link"], + [true, "hidden", "severed_link"], + [false, "hidden", "severed_link"], + ])("hasFocus=%s visibility=%s is %s", (hasFocus, visibilityState, expected) => { + expect(OpenerLoss.getVerdict({ hasFocus, visibilityState })).toBe(expected) + }) +}) + +describe("DynamicCheckoutOpenerLossUtils.isOpenerLoss", () => { + const context = { gatewayName: "mercadopagomxcashinaccount", invoiceId: "iv_test" } + + it.each([ + // mode, hasFocus, visibility, expected pending, expected telemetry + ["off", false, "hidden", false, false], + [undefined, false, "hidden", false, false], + ["shadow", false, "hidden", false, true], + ["shadow", true, "visible", false, true], + ["on", false, "hidden", true, true], + ["on", true, "visible", false, true], + ])( + "mode=%s hasFocus=%s visibility=%s -> pending=%s, telemetry=%s", + (mode, hasFocus, visibilityState, expectedPending, expectedTelemetry) => { + const processOut = fakeProcessOut() + + const pending = OpenerLoss.isOpenerLoss( + processOut, + tabClosed, + { ...context, mode }, + fakeDocument(hasFocus, visibilityState), + ) + + expect(pending).toBe(expectedPending) + expect(processOut.telemetryClient.report).toHaveBeenCalledTimes(expectedTelemetry ? 1 : 0) + }, + ) + + it("ignores a cancel that isn't a closed tab, even in on mode", () => { + const processOut = fakeProcessOut() + const doc = fakeDocument(false, "hidden") + + expect( + OpenerLoss.isOpenerLoss(processOut, overlayCancel, { ...context, mode: "on" }, doc), + ).toBe(false) + expect( + OpenerLoss.isOpenerLoss( + processOut, + { code: "card.declined" }, + { ...context, mode: "on" }, + doc, + ), + ).toBe(false) + expect(processOut.telemetryClient.report).not.toHaveBeenCalled() + }) + + it("reads the page state once, when it is called", () => { + const processOut = fakeProcessOut() + const hasFocus = vi.fn(() => false) + + OpenerLoss.isOpenerLoss( + processOut, + tabClosed, + { ...context, mode: "on" }, + { + hasFocus, + visibilityState: "hidden", + }, + ) + + expect(hasFocus).toHaveBeenCalledOnce() + }) + + it("reports the verdict, page state and gateway at info level", () => { + const processOut = fakeProcessOut() + vi.spyOn(Date, "now").mockReturnValue(10_000) + + OpenerLoss.isOpenerLoss( + processOut, + tabClosed, + { ...context, mode: "shadow", actionStartedAt: 7_500 }, + fakeDocument(false, "hidden"), + ) + + expect(processOut.telemetryClient.report).toHaveBeenCalledWith( + expect.objectContaining({ + host: "merchant.test", + message: "dynamic checkout opener loss verdict", + invoiceId: "iv_test", + data: { + mode: "shadow", + verdict: "severed_link", + gateway_name: "mercadopagomxcashinaccount", + has_focus: false, + visibility_state: "hidden", + ms_since_action_start: 2_500, + user_agent: "test-agent", + }, + }), + "info", + ) + vi.restoreAllMocks() + }) +}) + +describe("DynamicCheckoutOpenerLossUtils.markRedirectUrl", () => { + it.each([ + [ + "https://checkout.processout.com/proj_1/iv_1/redirect/gway_conf_1", + "https://checkout.processout.com/proj_1/iv_1/redirect/gway_conf_1?po_flow=dynamic-checkout", + ], + [ + "https://checkout.processout.com/proj_1/iv_1/redirect/gway_conf_1?additional_data[a]=b", + "https://checkout.processout.com/proj_1/iv_1/redirect/gway_conf_1?additional_data[a]=b&po_flow=dynamic-checkout", + ], + ["", ""], + ])("marks %s", (input, expected) => { + expect(OpenerLoss.markRedirectUrl(input)).toBe(expected) + }) +}) diff --git a/test/support/loadNamespace.ts b/test/support/loadNamespace.ts index 48792f71..f209a459 100644 --- a/test/support/loadNamespace.ts +++ b/test/support/loadNamespace.ts @@ -269,3 +269,25 @@ export function loadActionHandler(): { run(moduleShim, moduleShim.exports, documentShim, windowShim, { userAgent: "" }, translatorShim) return { namespace: moduleShim.exports, createdElements } } + +/** + * Load `src/dynamic-checkout/utils/opener-loss.ts` and return its `ProcessOut` namespace. + * `window` and `navigator` are injected so the telemetry fields are deterministic. + */ +export function loadOpenerLoss( + windowShim: unknown = { location: { host: "merchant.test" } }, + navigatorShim: unknown = { userAgent: "test-agent" }, +): Record { + const js = compile("src/dynamic-checkout/utils/opener-loss.ts") + const moduleShim = { exports: {} as Record } + const run = new Function( + "module", + "exports", + "window", + "navigator", + "document", + `${js}\nmodule.exports = ProcessOut;`, + ) + run(moduleShim, moduleShim.exports, windowShim, navigatorShim, undefined) + return moduleShim.exports +}