Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
test(cypress): affirm refund flow coverage (#12000)
HS-QUALIBOTb1cbbf26e424
diff --git a/cypress-tests/cypress/e2e/configs/Payment/Affirm.js b/cypress-tests/cypress/e2e/configs/Payment/Affirm.jsnew file mode 100644index 0000000000..1c42b7eb84--- /dev/null+++ b/cypress-tests/cypress/e2e/configs/Payment/Affirm.js@@ -0,0 +1,110 @@+import { customerAcceptance } from "./Commons";++export const connectorDetails = {+ pay_later_pm: {+ PaymentIntent: {+ Request: {+ currency: "USD",+ customer_acceptance: customerAcceptance,+ setup_future_usage: "on_session",+ },+ Response: {+ status: 200,+ body: {+ status: "requires_payment_method",+ setup_future_usage: "on_session",+ },+ },+ },+ AffirmManualCapture: {+ Request: {+ payment_method: "pay_later",+ payment_method_type: "affirm",+ payment_experience: "redirect_to_url",+ payment_method_data: {+ pay_later: {+ affirm_redirect: {+ billing_email: "[email protected]",+ billing_country: "US",+ },+ },+ },+ billing: {+ email: "[email protected]",+ address: {+ line1: "1467",+ line2: "Harrison Street",+ line3: "Harrison Street",+ city: "San Francisco",+ state: "California",+ zip: "94122",+ country: "US",+ first_name: "joseph",+ last_name: "Doe",+ },+ phone: {+ number: "8056599999",+ country_code: "+1",+ },+ },+ order_details: [+ {+ product_name: "Test Product",+ quantity: 1,+ amount: 6000,+ },+ ],+ },+ Response: {+ status: 200,+ body: {+ status: "requires_customer_action",+ },+ },+ },+ Capture: {+ Request: {+ amount_to_capture: 6000,+ },+ Response: {+ status: 200,+ body: {+ status: "succeeded",+ amount_received: 6000,+ },+ },+ },+ Refund: {+ Request: {+ amount: 6000,+ },+ Response: {+ status: 200,+ body: {+ status: "succeeded",+ amount: 6000,+ },+ },+ },+ PartialRefund: {+ Request: {+ amount: 2000,+ },+ Response: {+ status: 200,+ body: {+ status: "succeeded",+ amount: 2000,+ },+ },+ },+ SyncRefund: {+ Response: {+ status: 200,+ body: {+ status: "succeeded",+ },+ },+ },+ },+};diff --git a/cypress-tests/cypress/e2e/configs/Payment/Commons.js b/cypress-tests/cypress/e2e/configs/Payment/Commons.jsindex dafab3127a..aaf64f5722 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Commons.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Commons.js@@ -1387,6 +1387,46 @@ export const connectorDetails = {},},}),+ AffirmManualCapture: getCustomExchange({+ Request: {+ payment_method: "pay_later",+ payment_method_type: "affirm",+ payment_experience: "redirect_to_url",+ payment_method_data: {+ pay_later: {+ affirm_redirect: {+ billing_email: "[email protected]",+ billing_country: "US",+ },+ },+ },+ billing: {+ email: "[email protected]",+ address: {+ line1: "1467",+ line2: "Harrison Street",+ line3: "Harrison Street",+ city: "San Francisco",+ state: "California",+ zip: "94122",+ country: "US",+ first_name: "joseph",+ last_name: "Doe",+ },+ phone: {+ number: "8056599999",+ country_code: "+1",+ },+ },+ order_details: [+ {+ product_name: "Test Product",+ quantity: 1,+ amount: 6000,+ },+ ],+ },+ }),Capture: getCustomExchange({Request: {amount_to_capture: 6000,diff --git a/cypress-tests/cypress/e2e/configs/Payment/Utils.js b/cypress-tests/cypress/e2e/configs/Payment/Utils.jsindex ccaea8a99f..0ed410482d 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Utils.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Utils.js@@ -4,6 +4,7 @@ import { updateDefaultStatusCode } from "./Modifiers.js";import { connectorDetails as aciConnectorDetails } from "./Aci.js";import { connectorDetails as adyenConnectorDetails } from "./Adyen.js";+import { connectorDetails as affirmConnectorDetails } from "./Affirm.js";import { connectorDetails as airwallexConnectorDetails } from "./Airwallex.js";import { connectorDetails as archipelConnectorDetails } from "./Archipel.js";import { connectorDetails as authipayConnectorDetails } from "./Authipay.js";@@ -80,6 +81,7 @@ import { connectorDetails as mifinityConnectorDetails } from "./Mifinity.js";const connectorDetails = {aci: aciConnectorDetails,adyen: adyenConnectorDetails,+ affirm: affirmConnectorDetails,airwallex: airwallexConnectorDetails,archipel: archipelConnectorDetails,authipay: authipayConnectorDetails,@@ -567,10 +569,19 @@ export const CONNECTOR_LISTS = {],EXTERNAL_THREE_DS: ["stripe", "finix"],PARTNER_MERCHANT_IDENTIFIER: ["adyen", "checkout"],+ AFFIRM_PAY_LATER: ["affirm"],EXTEND_AUTHORIZATION: ["adyen", "paypal"],GIFT_CARD: ["adyen"],RELAY_OPERATIONS: ["bankofamerica"],- PAY_LATER: ["klarna", "adyen", "aci", "stripe", "airwallex", "mollie"],+ PAY_LATER: [+ "klarna",+ "adyen",+ "aci",+ "stripe",+ "airwallex",+ "mollie",+ "affirm",+ ],AFFIRM: ["stripe"],AUTH_SERVICE_ELIGIBILITY: ["stripe", "cybersource"],STEP_UP_AUTH: ["cybersource"],diff --git a/cypress-tests/cypress/e2e/spec/Payment/43-PayLater.cy.js b/cypress-tests/cypress/e2e/spec/Payment/43-PayLater.cy.jsindex f2b230f754..10dcb10a1e 100644--- a/cypress-tests/cypress/e2e/spec/Payment/43-PayLater.cy.js+++ b/cypress-tests/cypress/e2e/spec/Payment/43-PayLater.cy.js@@ -367,4 +367,267 @@ describe("PayLater tests", () => {});});});++ context("Affirm - Full Payment and Refund Flow", () => {+ beforeEach(function () {+ if (+ shouldIncludeConnector(+ globalState.get("connectorId"),+ CONNECTOR_LISTS.INCLUDE.AFFIRM_PAY_LATER+ )+ ) {+ this.skip();+ }+ });++ it("Create Payment Intent -> Payment Methods Call -> Confirm Payment Intent -> Handle Redirection -> Retrieve Payment -> Refund Payment -> Sync Refund", () => {+ let shouldContinue = true;++ cy.step("Create Payment Intent", () => {+ const data = getConnectorDetails(globalState.get("connectorId"))[+ "pay_later_pm"+ ]["PaymentIntent"];+ cy.createPaymentIntentTest(+ fixtures.createPaymentBody,+ data,+ "no_three_ds",+ "manual",+ globalState+ );+ if (!utils.should_continue_further(data)) {+ shouldContinue = false;+ }+ });++ cy.step("Payment Methods Call", () => {+ if (!shouldContinue) {+ cy.task("cli_log", "Skipping step: Payment Methods Call");+ return;+ }+ cy.paymentMethodsCallTest(globalState);+ });++ cy.step("Confirm Payment Intent", () => {+ if (!shouldContinue) {+ cy.task("cli_log", "Skipping step: Confirm Payment Intent");+ return;+ }+ const confirmData = getConnectorDetails(globalState.get("connectorId"))[+ "pay_later_pm"+ ]["AffirmManualCapture"];+ cy.confirmBankRedirectCallTest(+ fixtures.confirmBody,+ confirmData,+ true,+ globalState+ );+ if (!utils.should_continue_further(confirmData)) {+ shouldContinue = false;+ }+ });++ cy.step("Handle Redirection", () => {+ if (!shouldContinue) {+ cy.task("cli_log", "Skipping step: Handle Redirection");+ return;+ }+ const expected_redirection =+ globalState.get("baseUrl") + "/payments/completion";+ const payment_method_type = globalState.get("paymentMethodType");+ cy.handleAffirmRedirection(+ globalState,+ payment_method_type,+ expected_redirection+ );+ cy.task("cli_log", "Affirm redirection handler completed");+ });++ cy.step("Retrieve Payment after Confirmation", () => {+ if (!shouldContinue) {+ cy.task(+ "cli_log",+ "Skipping step: Retrieve Payment after Confirmation"+ );+ return;+ }+ const confirmData = getConnectorDetails(globalState.get("connectorId"))[+ "pay_later_pm"+ ]["AffirmManualCapture"];+ cy.retrievePaymentCallTest({ globalState, data: confirmData });+ if (!utils.should_continue_further(confirmData)) {+ shouldContinue = false;+ }+ });++ cy.step("Capture Payment", () => {+ if (!shouldContinue) {+ cy.task("cli_log", "Skipping step: Capture Payment");+ return;+ }+ const captureData = getConnectorDetails(globalState.get("connectorId"))[+ "pay_later_pm"+ ]["Capture"];+ cy.captureCallTest(fixtures.captureBody, captureData, globalState);+ if (!utils.should_continue_further(captureData)) {+ shouldContinue = false;+ }+ });++ cy.step("Refund Payment", () => {+ if (!shouldContinue) {+ cy.task("cli_log", "Skipping step: Refund Payment");+ return;+ }+ const refundData = getConnectorDetails(globalState.get("connectorId"))[+ "pay_later_pm"+ ]["Refund"];+ cy.refundCallTest(fixtures.refundBody, refundData, globalState);+ if (!utils.should_continue_further(refundData)) {+ shouldContinue = false;+ }+ });++ cy.step("Sync Refund Payment", () => {+ if (!shouldContinue) {+ cy.task("cli_log", "Skipping step: Sync Refund Payment");+ return;+ }+ const syncRefundData = getConnectorDetails(+ globalState.get("connectorId")+ )["pay_later_pm"]["SyncRefund"];+ cy.syncRefundCallTest(syncRefundData, globalState);+ });+ });+ });++ context("Affirm - Partial Refund Flow", () => {+ beforeEach(function () {+ if (+ shouldIncludeConnector(+ globalState.get("connectorId"),+ CONNECTOR_LISTS.INCLUDE.AFFIRM_PAY_LATER+ )+ ) {+ this.skip();+ }+ });++ it("Create Payment Intent -> Payment Methods Call -> Confirm Payment Intent -> Handle Redirection -> Retrieve Payment -> Partial Refund -> Sync Refund", () => {+ let shouldContinue = true;++ cy.step("Create Payment Intent", () => {+ const data = getConnectorDetails(globalState.get("connectorId"))[+ "pay_later_pm"+ ]["PaymentIntent"];+ cy.createPaymentIntentTest(+ fixtures.createPaymentBody,+ data,+ "no_three_ds",+ "manual",+ globalState+ );+ if (!utils.should_continue_further(data)) {+ shouldContinue = false;+ }+ });++ cy.step("Payment Methods Call", () => {+ if (!shouldContinue) {+ cy.task("cli_log", "Skipping step: Payment Methods Call");+ return;+ }+ cy.paymentMethodsCallTest(globalState);+ });++ cy.step("Confirm Payment Intent", () => {+ if (!shouldContinue) {+ cy.task("cli_log", "Skipping step: Confirm Payment Intent");+ return;+ }+ const confirmData = getConnectorDetails(globalState.get("connectorId"))[+ "pay_later_pm"+ ]["AffirmManualCapture"];+ cy.confirmBankRedirectCallTest(+ fixtures.confirmBody,+ confirmData,+ true,+ globalState+ );+ if (!utils.should_continue_further(confirmData)) {+ shouldContinue = false;+ }+ });++ cy.step("Handle Redirection", () => {+ if (!shouldContinue) {+ cy.task("cli_log", "Skipping step: Handle Redirection");+ return;+ }+ const expected_redirection =+ globalState.get("baseUrl") + "/payments/completion";+ const payment_method_type = globalState.get("paymentMethodType");+ cy.handleAffirmRedirection(+ globalState,+ payment_method_type,+ expected_redirection+ );+ });++ cy.step("Retrieve Payment after Confirmation", () => {+ if (!shouldContinue) {+ cy.task(+ "cli_log",+ "Skipping step: Retrieve Payment after Confirmation"+ );+ return;+ }+ const confirmData = getConnectorDetails(globalState.get("connectorId"))[+ "pay_later_pm"+ ]["AffirmManualCapture"];+ cy.retrievePaymentCallTest({ globalState, data: confirmData });+ if (!utils.should_continue_further(confirmData)) {+ shouldContinue = false;+ }+ });++ cy.step("Capture Payment", () => {+ if (!shouldContinue) {+ cy.task("cli_log", "Skipping step: Capture Payment");+ return;+ }+ const captureData = getConnectorDetails(globalState.get("connectorId"))[+ "pay_later_pm"+ ]["Capture"];+ cy.captureCallTest(fixtures.captureBody, captureData, globalState);+ if (!utils.should_continue_further(captureData)) {+ shouldContinue = false;+ }+ });++ cy.step("Partial Refund Payment", () => {+ if (!shouldContinue) {+ cy.task("cli_log", "Skipping step: Partial Refund Payment");+ return;+ }+ const partialRefundData = getConnectorDetails(+ globalState.get("connectorId")+ )["pay_later_pm"]["PartialRefund"];+ cy.refundCallTest(fixtures.refundBody, partialRefundData, globalState);+ if (!utils.should_continue_further(partialRefundData)) {+ shouldContinue = false;+ }+ });++ cy.step("Sync Refund Payment", () => {+ if (!shouldContinue) {+ cy.task("cli_log", "Skipping step: Sync Refund Payment");+ return;+ }+ const syncRefundData = getConnectorDetails(+ globalState.get("connectorId")+ )["pay_later_pm"]["SyncRefund"];+ cy.syncRefundCallTest(syncRefundData, globalState);+ });+ });+ });});diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.jsindex 356546916e..2cc218e18a 100644--- a/cypress-tests/cypress/support/commands.js+++ b/cypress-tests/cypress/support/commands.js@@ -1,4 +1,5 @@// ***********************************************+// This example commands.js shows you how to// create various custom commands and overwrite// existing commands.@@ -2818,6 +2819,19 @@ Cypress.Commands.add();}} else if (response.body.authentication_type === "no_three_ds") {+ // Handle pay later methods that require redirect (Affirm, Klarna, etc.)+ const nextAction = response.body.next_action;+ if (nextAction) {+ // Try multiple possible field names+ const redirectUrl =+ nextAction.redirect_to_url ||+ nextAction.url ||+ nextAction.redirect_url;+ if (redirectUrl) {+ globalState.set("nextActionUrl", redirectUrl);+ globalState.set("nextActionType", "redirect_to_url");+ }+ }if (response.body.next_action) {expect(response.body).to.have.property("next_action")@@ -2887,6 +2901,7 @@ Cypress.Commands.add();}} else if (response.body.authentication_type === "no_three_ds") {+ // Handle pay later methods that require redirect (Affirm, Klarna, etc.)if (response.body.next_action) {expect(response.body).to.have.property("next_action")@@ -2895,6 +2910,7 @@ Cypress.Commands.add("nextActionUrl",response.body.next_action.redirect_to_url);+ globalState.set("nextActionType", "redirect_to_url");}for (const key in resData.body) {expect(resData.body[key], [key]).to.deep.equal(@@ -3123,6 +3139,83 @@ Cypress.Commands.add(});+Cypress.Commands.add(+ "confirmPayLaterCallTest",+ (confirmBody, data, confirm, globalState) => {+ const {+ Configs: configs = {},+ Request: reqData,+ Response: resData,+ } = data || {};++ const configInfo = execConfig(validateConfig(configs));+ const paymentIntentId = globalState.get("paymentID");+ const profile_id = globalState.get(`${configInfo.profilePrefix}Id`);+ const customer_id = globalState.get("customerId");++ for (const key in reqData) {+ confirmBody[key] = reqData[key];+ }+ confirmBody.client_secret = globalState.get("clientSecret");+ confirmBody.confirm = confirm;+ confirmBody.profile_id = profile_id;+ confirmBody.customer_id = customer_id;++ cy.request({+ method: "POST",+ url: `${globalState.get("baseUrl")}/payments/${paymentIntentId}/confirm`,+ headers: {+ "Content-Type": "application/json",+ "api-key": globalState.get("publishableKey"),+ },+ failOnStatusCode: false,+ body: confirmBody,+ }).then((response) => {+ logRequestId(response.headers["x-request-id"]);++ cy.wrap(response).then(() => {+ expect(response.headers["content-type"]).to.include("application/json");+ if (response.status === 200) {+ globalState.set("paymentID", paymentIntentId);+ updateConnectorState(globalState, response.body.connector);+ globalState.set("paymentMethodType", confirmBody.payment_method_type);++ validateErrorMessage(response, resData);++ if (+ response.body.capture_method === "automatic" ||+ response.body.capture_method === "manual"+ ) {+ // Pay later methods typically have redirect_to_url in next_action+ if (response.body.next_action?.redirect_to_url) {+ globalState.set(+ "nextActionUrl",+ response.body.next_action.redirect_to_url+ );+ globalState.set("nextActionType", "redirect_to_url");+ } else if (response.body.next_action?.url) {+ globalState.set("nextActionUrl", response.body.next_action.url);+ globalState.set("nextActionType", "redirect_to_url");+ }++ for (const key in resData.body) {+ expect(resData.body[key], [key]).to.deep.equal(+ response.body[key]+ );+ }+ } else {+ throw new Error(+ `Invalid capture method ${response.body.capture_method}`+ );+ }+ } else {+ defaultErrorHandler(response, resData);+ }+ });+ });+ }+);+Cypress.Commands.add("confirmBankTransferCallTest",(confirmBody, data, confirm, globalState) => {@@ -3203,6 +3296,25 @@ Cypress.Commands.add();}+ break;+ case "affirm":+ case "klarna":+ case "afterpay":+ case "pay_later":+ // Pay later methods typically have redirect_to_url in next_action+ if (response.body.next_action?.redirect_to_url) {+ globalState.set(+ "nextActionUrl",+ response.body.next_action.redirect_to_url+ );+ globalState.set("nextActionType", "redirect_to_url");+ } else if (response.body.next_action?.url) {+ globalState.set(+ "nextActionUrl",+ response.body.next_action.url+ );+ globalState.set("nextActionType", "redirect_to_url");+ }break;default:expect(response.body)@@ -4984,6 +5096,50 @@ Cypress.Commands.add(});+Cypress.Commands.add(+ "handlePayLaterRedirection",+ (globalState, paymentMethodType, expectedRedirection) => {+ const connectorId = globalState.get("connectorId");+ const nextActionUrl = globalState.get("nextActionUrl");++ // Support calling with just globalState (defaults used when spec omits extra args)+ const resolvedPaymentMethodType =+ paymentMethodType || globalState.get("paymentMethodType");+ const resolvedExpectedRedirection =+ expectedRedirection || "https://example.com";++ const expectedUrl = new URL(resolvedExpectedRedirection);+ const redirectionUrl = new URL(nextActionUrl);++ handleRedirection(+ "pay_later",+ { redirectionUrl, expectedUrl },+ connectorId,+ resolvedPaymentMethodType,+ { globalState }+ );+ }+);++Cypress.Commands.add(+ "handleAffirmRedirection",+ (globalState, paymentMethodType, expectedRedirection) => {+ const connectorId = globalState.get("connectorId");+ const nextActionUrl = globalState.get("nextActionUrl");++ const expectedUrl = new URL(expectedRedirection);+ const redirectionUrl = new URL(nextActionUrl);++ handleRedirection(+ "affirm_pay_later",+ { redirectionUrl, expectedUrl },+ connectorId,+ paymentMethodType,+ { globalState }+ );+ }+);+Cypress.Commands.add("handlePaymentLinkCardRedirection",(globalState, cardData, expectedOutcome = "success") => {@@ -5192,24 +5348,6 @@ Cypress.Commands.add(});-Cypress.Commands.add(- "handlePayLaterRedirection",- (globalState, paymentMethodType, expected_redirection) => {- const connectorId = globalState.get("connectorId");- const nextActionUrl = globalState.get("nextActionUrl");-- const expectedUrl = new URL(expected_redirection);- const redirectionUrl = new URL(nextActionUrl);-- handleRedirection(- "pay_later",- { redirectionUrl, expectedUrl },- connectorId,- paymentMethodType- );- }-);-Cypress.Commands.add("listCustomerPMCallTest", (globalState, order = 0) => {const apiKey = globalState.get("apiKey");const baseUrl = globalState.get("baseUrl");diff --git a/cypress-tests/cypress/support/redirectionHandler.js b/cypress-tests/cypress/support/redirectionHandler.jsindex 1146e6a9cb..b432a8dff0 100644--- a/cypress-tests/cypress/support/redirectionHandler.js+++ b/cypress-tests/cypress/support/redirectionHandler.js@@ -93,7 +93,17 @@ export function handleRedirection(urls.redirectionUrl,urls.expectedUrl,resolvedConnectorId,- paymentMethodType+ paymentMethodType,+ handlerMetadata?.globalState+ );+ break;+ case "affirm_pay_later":+ affirmPayLaterRedirection(+ urls.redirectionUrl,+ urls.expectedUrl,+ resolvedConnectorId,+ paymentMethodType,+ handlerMetadata?.globalState);break;case "payment_link_card":@@ -448,6 +458,422 @@ function payLaterRedirection(});}+function affirmPayLaterRedirection(+ redirectionUrl,+ expectedUrl,+ connectorId,+ paymentMethodType,+ globalState+) {+ const verifyUrl = false;++ if (redirectionUrl && redirectionUrl.href) {+ cy.visit(redirectionUrl.href);+ cy.log("Affirm flow - starting checkout automation");++ cy.on("uncaught:exception", (err) => {+ if (+ err.message.includes("Cannot read properties of null") ||+ err.message.includes("postMessage")+ ) {+ return false;+ }+ return true;+ });++ cy.url().then((initialUrl) => {+ const affirmOrigin = new URL(initialUrl).origin;+ cy.log("Affirm pay later flow - handling on origin: " + affirmOrigin);++ const waitTime = CONSTANTS.WAIT_TIME;++ const determineAffirmStep = (doc, bodyText, currentUrl) => {+ if (currentUrl.includes("/payments/completion")) return "done";++ const hasPinInput = doc.querySelector(+ '[data-testid="phone-pin-field"]:not([aria-hidden="true"])'+ );+ if (hasPinInput) return "pin";++ if (+ bodyText.includes("phone") ||+ bodyText.includes("mobile") ||+ bodyText.includes("cell")+ )+ return "phone";+ if (bodyText.includes("continue to plans")) return "continue_to_plans";+ if (+ bodyText.includes("social") ||+ bodyText.includes("ssn") ||+ bodyText.includes("last 4")+ )+ return "ssn";+ if (bodyText.includes("first name") || bodyText.includes("legal name"))+ return "first_name";+ if (bodyText.includes("last name") || bodyText.includes("surname"))+ return "last_name";+ if (+ bodyText.includes("date of birth") ||+ bodyText.includes("birthday") ||+ bodyText.includes("dob") ||+ bodyText.includes("birth date")+ )+ return "dob";+ if (bodyText.includes("email") || bodyText.includes("e-mail"))+ return "email";+ if (+ bodyText.includes("continue to plans") ||+ (bodyText.includes("creating an account") &&+ bodyText.includes("agree"))+ )+ return "consent";+ if (+ bodyText.includes("pick a plan") ||+ bodyText.includes("choose a payment plan") ||+ bodyText.includes("payment plan") ||+ bodyText.includes("choose this plan") ||+ bodyText.includes("every month") ||+ bodyText.includes("total of payments")+ )+ return "plan";+ if (+ bodyText.includes("review") ||+ bodyText.includes("confirm") ||+ bodyText.includes("autopay") ||+ bodyText.includes("terms")+ )+ return "review";+ return "fallback";+ };++ const handleAffirmStep = () => {+ cy.wait(waitTime / 5);++ cy.document().then((doc) => {+ const bodyText = doc.body.innerText.toLowerCase();+ const pageTitle = doc.title || "No title";+ const currentUrl = doc.location?.href || "Unknown URL";++ cy.log(`Affirm Page: ${pageTitle}`);+ cy.log(`URL: ${currentUrl}`);+ cy.log(`Page content preview: ${bodyText.substring(0, 200)}...`);++ const step = determineAffirmStep(doc, bodyText, currentUrl);+ cy.log(`Determined Affirm step: ${step}`);++ switch (step) {+ case "done":+ cy.log("Reached return URL, done");+ break;++ case "phone":+ cy.get("body").then(($body) => {+ const phoneInputs = $body.find(+ 'input[type="tel"]:visible, input[autocomplete="tel"]:visible, input[name*="phone"]:visible'+ );+ if (phoneInputs.length > 0) {+ cy.wrap(phoneInputs.first()).clear().type("4155551234");+ cy.log("Entered phone number");++ const sendBtn = $body+ .find("button:visible")+ .filter((i, btn) =>+ /send|submit|continue|next/i.test(+ btn.innerText.toLowerCase()+ )+ );+ if (sendBtn.length > 0) {+ cy.wrap(sendBtn.first()).click({ force: true });+ cy.log("Clicked send/submit after phone");+ }+ }+ });+ break;++ case "pin":+ cy.get("body").then(($body) => {+ const pinInput = $body+ .find(+ 'input[data-testid="phone-pin-field"]:visible, input[placeholder="000000"]:visible, input[autocomplete="one-time-code"]:visible, input[inputmode="numeric"]:visible'+ )+ .first();++ if (pinInput.length > 0) {+ cy.wrap(pinInput).clear().type("123456", { delay: 100 });+ cy.log("Entered PIN 123456 into phone-pin-field");++ cy.wait(1000);++ const verifyBtn = $body+ .find("button:visible")+ .filter((i, btn) =>+ /verify|confirm|continue/i.test(+ btn.innerText.toLowerCase()+ )+ );+ if (verifyBtn.length > 0) {+ cy.wrap(verifyBtn.first()).click({ force: true });+ cy.log("Clicked verify/continue after PIN");+ }+ } else {+ cy.log(+ "PIN input not found - looking for phone-pin-field or placeholder 000000"+ );+ }+ });+ break;++ case "continue_to_plans":+ cy.get("body").then(($body) => {+ const continueBtn = $body+ .find("button:visible")+ .filter((i, btn) =>+ /continue to plans/i.test(btn.innerText.toLowerCase())+ );+ if (continueBtn.length > 0) {+ cy.wrap(continueBtn.first()).click({ force: true });+ cy.log("Clicked Continue to plans");+ }+ });+ break;++ case "ssn":+ cy.get("body").then(($body) => {+ const ssnInputs = $body.find(+ 'input[type="password"][maxlength="4"]:visible, input[name*="ssn"]:visible, input[placeholder*="last 4"]:visible'+ );+ if (ssnInputs.length > 0) {+ cy.wrap(ssnInputs.first()).clear().type("5678");+ cy.log("Entered SSN last 4");++ const continueBtn = $body+ .find("button:visible")+ .filter((i, btn) =>+ /continue|next|submit/i.test(btn.innerText.toLowerCase())+ );+ if (continueBtn.length > 0) {+ cy.wrap(continueBtn.first()).click({ force: true });+ cy.log("Clicked continue after SSN");+ }+ }+ });+ break;++ case "first_name":+ cy.get("body").then(($body) => {+ const firstNameInputs = $body.find(+ 'input[name*="first"]:visible, input[id*="first"]:visible, input[autocomplete*="given-name"]:visible'+ );+ if (firstNameInputs.length > 0) {+ cy.wrap(firstNameInputs.first())+ .clear()+ .invoke("val", "Joseph")+ .trigger("input");+ cy.log("Entered first name Joseph");+ }+ });+ break;++ case "last_name":+ cy.get("body").then(($body) => {+ const lastNameInputs = $body.find(+ 'input[name*="last"]:visible, input[id*="last"]:visible, input[autocomplete*="family-name"]:visible'+ );+ if (lastNameInputs.length > 0) {+ cy.wrap(lastNameInputs.first())+ .clear()+ .invoke("val", "Doe")+ .trigger("input");+ cy.log("Entered last name Doe");+ }+ });+ break;++ case "dob":+ cy.get("body").then(($body) => {+ const dobInputs = $body.find(+ 'input[data-testid*="dob"]:visible, input[aria-label*="Birth"]:visible, input[placeholder*="mm"]:visible, input[name*="dob"]:visible, input[name*="birth"]:visible'+ );+ if (dobInputs.length > 0) {+ cy.wrap(dobInputs.first())+ .click()+ .clear()+ .type("01/01/1990", { delay: 50 });+ cy.log("Entered DOB 01/01/1990");+ }+ });+ break;++ case "email":+ cy.get("body").then(($body) => {+ const emailInputs = $body.find(+ 'input[data-testid*="email"]:visible, input[type="email"]:visible, input[autocomplete="email"]:visible'+ );+ if (emailInputs.length > 0) {+ cy.wrap(emailInputs.first())+ .click()+ .clear()+ .type("[email protected]", { delay: 50 });+ cy.log("Entered email [email protected]");+ }+ });+ break;++ case "consent":+ cy.get("body").then(($body) => {+ const consentCheckbox = $body+ .find('input[type="checkbox"]:not(:checked):visible')+ .first();+ if (consentCheckbox.length > 0) {+ cy.wrap(consentCheckbox).click({ force: true });+ cy.log("Checked consent checkbox");+ }++ const continueBtn = $body+ .find("button:visible")+ .filter((i, btn) =>+ /continue to plans/i.test(btn.innerText.toLowerCase())+ );+ if (continueBtn.length > 0) {+ cy.wrap(continueBtn.first()).click({ force: true });+ cy.log("Clicked Continue to plans");+ }+ });+ break;++ case "plan":+ {+ const planRadio = doc.querySelector(+ 'input[type="radio"][name="selectedTermIndex"]'+ );+ if (planRadio) {+ planRadio.checked = true;+ planRadio.dispatchEvent(+ new Event("change", { bubbles: true })+ );+ cy.log("Selected payment plan via DOM");+ }++ const planBtn = doc.querySelector(+ 'button[data-testid="continue-with-selected-term-button"]'+ );+ if (planBtn) {+ planBtn.dispatchEvent(+ new MouseEvent("click", { bubbles: true })+ );+ cy.log("Clicked Choose this plan via DOM");+ }++ cy.wait(2000).then(() => {+ const indicator = doc.querySelector(+ '[data-testid="disclosure-checkbox-indicator"]'+ );+ if (indicator) {+ const label = indicator.closest("label");+ (label || indicator).dispatchEvent(+ new MouseEvent("click", { bubbles: true })+ );+ cy.log("Clicked disclosure checkbox");+ }++ const submitBtn = doc.querySelector(+ 'button[data-testid="submit-button"]'+ );+ if (submitBtn) {+ submitBtn.dispatchEvent(+ new MouseEvent("click", { bubbles: true })+ );+ cy.log("Clicked Confirm button");+ }+ });+ }+ break;++ case "review":+ cy.get('[data-testid="disclosure-checkbox-indicator"]')+ .closest("label")+ .click({ force: true });+ cy.log("Clicked disclosure checkbox label");++ cy.wait(1000);++ cy.get('button[data-testid="submit-button"]').click({+ force: true,+ });+ cy.log("Clicked Confirm button");+ break;++ case "fallback":+ default:+ cy.get("body").then(($body) => {+ const buttons = $body.find("button:visible");+ for (let i = 0; i < buttons.length; i++) {+ const btnText = buttons[i].innerText.toLowerCase();+ if (+ /continue|submit|verify|next|pay|confirm|agree/i.test(+ btnText+ )+ ) {+ cy.wrap(buttons[i]).click({ force: true });+ cy.log("Clicked button: " + btnText);+ break;+ }+ }+ });+ break;+ }+ });+ };++ function runUntilComplete(maxSteps, delay) {+ if (maxSteps <= 0) {+ cy.log("Max steps reached, stopping");+ return;+ }++ cy.url().then((currentUrl) => {+ cy.log(`Step remaining: ${maxSteps} | Current URL: ${currentUrl}`);++ handleAffirmStep();++ cy.wait(delay).then(() => {+ runUntilComplete(maxSteps - 1, delay);+ });+ });+ }++ runUntilComplete(3, 6000);+ });+ } else {+ cy.log("Skipping Affirm redirection - no valid redirect URL provided");+ }++ cy.then(() => {+ verifyReturnUrl(redirectionUrl, expectedUrl, verifyUrl);++ if (globalState) {+ cy.url().then((currentUrl) => {+ try {+ const urlObj = new URL(currentUrl);+ const urlParams = new URLSearchParams(urlObj.search);+ const paymentId = urlParams.get("payment_id");++ if (paymentId) {+ cy.log(`Extracted payment_id from return URL: ${paymentId}`);+ globalState.set("paymentID", paymentId);+ } else {+ cy.log(+ "No payment_id found in return URL - using existing paymentID from globalState"+ );+ }+ } catch (error) {+ cy.log(`Error extracting payment_id from URL: ${error.message}`);+ }+ });+ }+ });+}+function bankTransferRedirection(redirectionUrl,expectedUrl,