From 6e513a3bab9444a75dbc976945ab3113ced76b51 Mon Sep 17 00:00:00 2001 From: ArushKapoorJuspay <121166031+ArushKapoorJuspay@users.noreply.github.com> Date: Thu, 10 Oct 2024 11:03:57 +0530 Subject: [PATCH 01/35] fix: fixed applePay for headless fow (#725) --- src/Types/ApplePayTypes.res | 10 ++++++++++ src/orca-loader/PaymentSessionMethods.res | 11 +++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/Types/ApplePayTypes.res b/src/Types/ApplePayTypes.res index 29b00e88c..998f42fcf 100644 --- a/src/Types/ApplePayTypes.res +++ b/src/Types/ApplePayTypes.res @@ -74,6 +74,16 @@ type paymentRequestData = { @optional merchantIdentifier: string, } +type headlessApplePayToken = { + paymentRequestData: JSON.t, + sessionTokenData: option, +} + +let defaultHeadlessApplePayToken: headlessApplePayToken = { + paymentRequestData: JSON.Encode.null, + sessionTokenData: None, +} + let jsonToPaymentRequestDataType: Dict.t => paymentRequestData = jsonDict => { let clientTimeZone = CardUtils.dateTimeFormat().resolvedOptions().timeZone let clientCountry = getClientCountry(clientTimeZone) diff --git a/src/orca-loader/PaymentSessionMethods.res b/src/orca-loader/PaymentSessionMethods.res index 0130a64d7..60e54b844 100644 --- a/src/orca-loader/PaymentSessionMethods.res +++ b/src/orca-loader/PaymentSessionMethods.res @@ -35,7 +35,7 @@ let getCustomerSavedPaymentMethods = ( customerPaymentMethods->Array.sort((a, b) => compareLogic(a.lastUsedAt, b.lastUsedAt)) let customerPaymentMethodsRef = ref(customerPaymentMethods) - let applePayTokenRef = ref(JSON.Encode.null) + let applePayTokenRef = ref(defaultHeadlessApplePayToken) let googlePayTokenRef = ref(JSON.Encode.null) let isApplePayPresent = @@ -187,9 +187,9 @@ let getCustomerSavedPaymentMethods = ( } ApplePayHelpers.startApplePaySession( - ~paymentRequest=applePayTokenRef.contents, + ~paymentRequest=applePayTokenRef.contents.paymentRequestData, ~applePaySessionRef, - ~applePayPresent=Some(applePayTokenRef.contents), + ~applePayPresent=applePayTokenRef.contents.sessionTokenData, ~logger, ~callBackFunc=processPayment, ~clientSecret, @@ -425,7 +425,10 @@ let getCustomerSavedPaymentMethods = ( ~sessionObj=optToken, ~componentName, ) - applePayTokenRef := paymentRequest + applePayTokenRef := { + paymentRequestData: paymentRequest, + sessionTokenData: optToken, + } } | _ => updateCustomerPaymentMethodsRef(~isFilterApplePay=true) } From dc97235ac66d724632fc5feb79a54e71d193d25c Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 10 Oct 2024 05:35:57 +0000 Subject: [PATCH 02/35] chore(release): 0.91.10 [skip ci] ## [0.91.10](https://github.com/juspay/hyperswitch-web/compare/v0.91.9...v0.91.10) (2024-10-10) ### Bug Fixes * fixed applePay for headless fow ([#725](https://github.com/juspay/hyperswitch-web/issues/725)) ([6e513a3](https://github.com/juspay/hyperswitch-web/commit/6e513a3bab9444a75dbc976945ab3113ced76b51)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 657b56bd3..3669a11d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [0.91.10](https://github.com/juspay/hyperswitch-web/compare/v0.91.9...v0.91.10) (2024-10-10) + + +### Bug Fixes + +* fixed applePay for headless fow ([#725](https://github.com/juspay/hyperswitch-web/issues/725)) ([6e513a3](https://github.com/juspay/hyperswitch-web/commit/6e513a3bab9444a75dbc976945ab3113ced76b51)) + ## [0.91.9](https://github.com/juspay/hyperswitch-web/compare/v0.91.8...v0.91.9) (2024-10-07) diff --git a/package-lock.json b/package-lock.json index 148c04525..ce9731449 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.91.9", + "version": "0.91.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.91.9", + "version": "0.91.10", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index dbd504b7b..72bcd091a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.91.9", + "version": "0.91.10", "main": "index.js", "private": true, "dependencies": { From 7df22f3f9c0dd1c8687d67e64faf7a0591e3e59b Mon Sep 17 00:00:00 2001 From: aritro2002 Date: Thu, 10 Oct 2024 11:11:35 +0530 Subject: [PATCH 03/35] feat: added bubblegum theme (#723) Co-authored-by: Pritish Budhiraja --- src/BubblegumTheme.res | 224 ++++++++++++++++++++++++++++++++++++ src/CardTheme.res | 3 +- src/Types/CardThemeType.res | 2 +- 3 files changed, 227 insertions(+), 2 deletions(-) create mode 100644 src/BubblegumTheme.res diff --git a/src/BubblegumTheme.res b/src/BubblegumTheme.res new file mode 100644 index 000000000..b380e7d67 --- /dev/null +++ b/src/BubblegumTheme.res @@ -0,0 +1,224 @@ +open CardThemeType +let bubblegum = { + fontFamily: "", + fontSizeBase: "1rem", + colorPrimary: "#f360a6", + colorBackground: "#ffffff", + colorText: "#545454", + colorDanger: "#fd1717", + colorDangerText: "#fd1717", + borderRadius: "2px", + fontVariantLigatures: "", + fontVariationSettings: "", + spacingUnit: "11px", + fontWeightLight: "400", + fontWeightNormal: "500", + fontWeightMedium: "600", + fontWeightBold: "700", + fontLineHeight: "", + fontSize2Xl: "24px", + fontSizeXl: "16px", + fontSizeLg: "14px", + fontSizeSm: "12px", + fontSizeXs: "10px", + fontSize2Xs: "8px", + fontSize3Xs: "6px", + colorSuccess: "", + colorWarning: "", + colorPrimaryText: "#5469d4", + colorBackgroundText: "", + colorSuccessText: "", + colorWarningText: "", + colorTextSecondary: "#6d6e78", + colorTextPlaceholder: "", + spacingTab: "12px", + borderColor: "#e6e6e6", + spacingAccordionItem: "10px", + colorIconCardCvc: "", + colorIconCardCvcError: "#fd1717", + colorIconCardError: "#fd1717", + spacingGridColumn: "20px", + spacingGridRow: "20px", + buttonBackgroundColor: "#006df9", + buttonHeight: "48px", + buttonWidth: "100%", + buttonBorderRadius: "4px", + buttonBorderColor: "#ffffff", + buttonTextColor: "#ffffff", + buttonTextFontSize: "16px", + buttonTextFontWeight: "500", + buttonBorderWidth: "0px", +} +let bubblegumRules = theme => + { + ".Tab": { + "border": "0", + "borderRadius": theme.borderRadius, + "backgroundColor": theme.colorBackground, + "color": theme.colorTextSecondary, + "alignItems": "start", + "transition": "background .15s ease, border .15s ease, box-shadow .15s ease", + "boxShadow": "0px 3px 10px rgba(18, 42, 66, 0.08)" + }, + ".Tab:hover": { + "border": "0", + "color": theme.colorText, + }, + ".Tab:focus":{ + "border": "0" + }, + ".Label": { + "color": theme.colorText, + "opacity": "10", + "textAlign": "left", + }, + ".Tab--selected": { + "color": "#fff", + "backgroundColor": "#f360a6", + "boxShadow": `0px 1px 1px rgba(0, 0, 0, 0.03), 0px 3px 6px rgba(18, 42, 66, 0.02), 0 0 0 2px ${theme.colorPrimary}`, + }, + ".Tab--selected:hover": { + "color": "#fff", + "backgroundColor": "#f360a6", + "boxShadow": `0px 1px 1px rgba(0, 0, 0, 0.03), 0px 3px 6px rgba(18, 42, 66, 0.02), 0 0 0 2px ${theme.colorPrimary}`, + }, + ".Tab--selected:focus": { + "color": "#fff", + "backgroundColor": "#f360a6", + "boxShadow": `0 0 0 2px ${theme.colorPrimary}4c, 0 1px 1px 0 ${theme.colorBackground}, 0 0 0 1px ${theme.colorPrimary}4c`, + }, + ".TabMore:focus": { + "border": `1px solid ${theme.colorPrimary}`, + "boxShadow": `${theme.colorPrimary}4c 0px 0px 0px 3px`, + }, + ".TabMore": { + "border": `1px solid ${theme.borderColor}`, + }, + ".Input": { + "border": `1px solid #e6e6e6`, + "color": theme.colorText, + "fontWeight": theme.fontWeightLight, + "borderRadius": theme.borderRadius, + "boxShadow": "0px 3px 10px rgba(18, 42, 66, 0.08)", + "transition": "background 0.15s ease, border 0.15s ease, box-shadow 0.15s ease, color 0.15s ease", + }, + ".Input-Compressed": { + "border": `1px solid #e6e6e6`, + "color": theme.colorText, + "fontWeight": theme.fontWeightLight, + "boxShadow": `0px 1px 1px rgb(0 0 0 / 3%), 0px 3px 6px rgb(0 0 0 / 2%)`, + "transition": "background 0.15s ease, border 0.15s ease, box-shadow 0.15s ease, color 0.15s ease", + }, + ".Input:-webkit-autofill": { + "transition": "background-color 5000s ease-in-out 0s", + "-webkitTextFillColor": `${theme.colorText} !important`, + }, + ".Input:focus": { + "border": `1px solid ${theme.colorPrimary}`, + "boxShadow": `${theme.colorPrimary}4c 0px 0px 0px 3px`, + }, + ".Input-Compressed:focus": { + "border": `1px solid ${theme.colorPrimary}`, + "boxShadow": `${theme.colorPrimary}4c 0px 0px 0px 2px`, + "position": "relative", + "zIndex": "2", + }, + ".Input--invalid": { + "color": theme.colorDanger, + "border": `1px solid ${theme.colorDanger}`, + "transition": "border 0.15s ease, box-shadow 0.15s ease, color 0.15s ease", + }, + ".Input::placeholder": { + "fontWeight": theme.fontWeightLight, + "color": theme.colorTextPlaceholder, + }, + ".TabLabel": { + "transition": "color .1s ease", + "textAlign": "start", + }, + ".TabIcon": { + "transition": "color .1s ease", + }, + ".Block": { + "backgroundColor": theme.colorBackground, + "borderRadius": theme.borderRadius, + // "border": `1px solid ${theme.borderColor}`, + "borderColor": "transparent", + "boxShadow": "0px 3px 10px rgba(18, 42, 66, 0.08)" + }, + ".BlockDivider": { + "backgroundColor": "#ebebeb", + // "border": `1px solid ${theme.borderColor}`, + }, + ".AccordionItem": { + "backgroundColor": theme.colorBackground, + "color": theme.colorTextSecondary, + "transition": "height 1s ease", + "boxShadow": "0px 1px 1px rgb(0 0 0 / 3%), 0px 3px 6px rgb(0 0 0 / 2%)", + "padding": "20px", + }, + ".AccordionMore": { + "backgroundColor": theme.colorBackground, + "color": theme.colorTextSecondary, + "border": `1px solid ${theme.borderColor}`, + }, + ".AccordionMore:hover": { + "color": theme.colorText, + }, + ".AccordionItem:hover": { + "color": theme.colorText, + }, + ".AccordionItem--selected": { + "color": theme.colorPrimary, + }, + ".AccordionItem--selected:hover": { + "color": theme.colorPrimary, + }, + ".AccordionItemLabel": { + "transition": "color .1s ease", + }, + ".AccordionItemLabel--selected": { + "color": theme.colorPrimary, + }, + ".AccordionItemIcon--selected": { + "color": theme.colorPrimary, + }, + ".PickerItem": { + "backgroundColor": theme.colorBackground, + "borderRadius": theme.borderRadius, + "border": `1px solid ${theme.borderColor}`, + "color": theme.colorTextSecondary, + "padding": theme.spacingUnit, + "transition": "height 1s ease", + "boxShadow": "0px 1px 1px rgb(0 0 0 / 3%), 0px 3px 6px rgb(0 0 0 / 2%)", + }, + ".PickerItem:hover": { + "color": theme.colorText, + }, + ".PickerItem--selected": { + "color": theme.colorPrimary, + "border": `1px solid ${theme.colorPrimary}`, + "boxShadow": `${theme.colorPrimary}4c 0px 0px 0px 3px`, + }, + ".PickerItem--selected:hover": { + "color": theme.colorPrimary, + "border": `1px solid ${theme.colorPrimary}`, + "boxShadow": `${theme.colorPrimary}4c 0px 0px 0px 3px`, + }, + ".Checkbox": { + "fontWeight": theme.fontWeightLight, + "fontSize": theme.fontSizeLg, + }, + ".CheckboxInput":{ + "boxShadow": "0px 3px 10px rgba(18, 42, 66, 0.08)" + }, + ".PaymentMethodsHeaderLabel": { + "color": theme.colorText, + "fontSize": theme.fontSize2Xl, + "fontWeight": theme.fontWeightMedium, + "marginBottom": "1.5rem", + }, + }->Identity.anyTypeToJson + +let default = bubblegum +let defaultRules = bubblegumRules diff --git a/src/CardTheme.res b/src/CardTheme.res index 17f9fd8ec..28aa2a226 100644 --- a/src/CardTheme.res +++ b/src/CardTheme.res @@ -9,10 +9,11 @@ let getTheme = (val, logger) => { | "midnight" => Midnight | "charcoal" => Charcoal | "soft" => Soft + | "bubblegum" => Bubblegum | "none" => NONE | str => { str->unknownPropValueWarning( - ["default", "midnight", "brutal", "charcoal", "soft", "none"], + ["default", "midnight", "brutal", "charcoal", "soft", "bubblegum", "none"], "appearance.theme", ~logger, ) diff --git a/src/Types/CardThemeType.res b/src/Types/CardThemeType.res index 3db3322ed..0757c848e 100644 --- a/src/Types/CardThemeType.res +++ b/src/Types/CardThemeType.res @@ -1,4 +1,4 @@ -type theme = Default | Brutal | Midnight | Soft | Charcoal | NONE +type theme = Default | Brutal | Midnight | Soft | Charcoal| Bubblegum | NONE type innerLayout = Spaced | Compressed From eaa9a22b89bc6bada2d1c9053783f57689afb0e0 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 10 Oct 2024 05:43:45 +0000 Subject: [PATCH 04/35] chore(release): 0.92.0 [skip ci] # [0.92.0](https://github.com/juspay/hyperswitch-web/compare/v0.91.10...v0.92.0) (2024-10-10) ### Features * added bubblegum theme ([#723](https://github.com/juspay/hyperswitch-web/issues/723)) ([7df22f3](https://github.com/juspay/hyperswitch-web/commit/7df22f3f9c0dd1c8687d67e64faf7a0591e3e59b)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3669a11d9..17fc2e8ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# [0.92.0](https://github.com/juspay/hyperswitch-web/compare/v0.91.10...v0.92.0) (2024-10-10) + + +### Features + +* added bubblegum theme ([#723](https://github.com/juspay/hyperswitch-web/issues/723)) ([7df22f3](https://github.com/juspay/hyperswitch-web/commit/7df22f3f9c0dd1c8687d67e64faf7a0591e3e59b)) + ## [0.91.10](https://github.com/juspay/hyperswitch-web/compare/v0.91.9...v0.91.10) (2024-10-10) diff --git a/package-lock.json b/package-lock.json index ce9731449..c183f67f0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.91.10", + "version": "0.92.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.91.10", + "version": "0.92.0", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index 72bcd091a..0ce53a1d7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.91.10", + "version": "0.92.0", "main": "index.js", "private": true, "dependencies": { From ecf0db3d2fdb811f572bdffb5a61e468284a1c51 Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja Date: Thu, 10 Oct 2024 12:36:48 +0530 Subject: [PATCH 05/35] fix: web package added (#726) --- webpack.common.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webpack.common.js b/webpack.common.js index fdd7f08e3..981f2a979 100644 --- a/webpack.common.js +++ b/webpack.common.js @@ -22,7 +22,7 @@ const repoVersion = require("./package.json").version; const majorVersion = "v" + repoVersion.split(".")[0]; const repoName = require("./package.json").name; const repoPublicPath = - sdkEnv === "local" ? "" : `/${repoVersion}/${majorVersion}`; + sdkEnv === "local" ? "" : `/web/${repoVersion}/${majorVersion}`; const getSdkUrl = (env, customUrl) => { if (customUrl) return customUrl; From 81f1776a84b352afeb9a27bc005ceedd1ab93a53 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 10 Oct 2024 07:08:44 +0000 Subject: [PATCH 06/35] chore(release): 0.92.1 [skip ci] ## [0.92.1](https://github.com/juspay/hyperswitch-web/compare/v0.92.0...v0.92.1) (2024-10-10) ### Bug Fixes * web package added ([#726](https://github.com/juspay/hyperswitch-web/issues/726)) ([ecf0db3](https://github.com/juspay/hyperswitch-web/commit/ecf0db3d2fdb811f572bdffb5a61e468284a1c51)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17fc2e8ad..627e0d630 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [0.92.1](https://github.com/juspay/hyperswitch-web/compare/v0.92.0...v0.92.1) (2024-10-10) + + +### Bug Fixes + +* web package added ([#726](https://github.com/juspay/hyperswitch-web/issues/726)) ([ecf0db3](https://github.com/juspay/hyperswitch-web/commit/ecf0db3d2fdb811f572bdffb5a61e468284a1c51)) + # [0.92.0](https://github.com/juspay/hyperswitch-web/compare/v0.91.10...v0.92.0) (2024-10-10) diff --git a/package-lock.json b/package-lock.json index c183f67f0..2d1564c42 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.92.0", + "version": "0.92.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.92.0", + "version": "0.92.1", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index 0ce53a1d7..7780a714e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.92.0", + "version": "0.92.1", "main": "index.js", "private": true, "dependencies": { From 4f65ecbeb48022dbe9da507d98344e43c308b691 Mon Sep 17 00:00:00 2001 From: sakksham7 <130480324+sakksham7@users.noreply.github.com> Date: Tue, 15 Oct 2024 16:52:07 +0530 Subject: [PATCH 07/35] feat: added confirm handler (#731) --- src/LoaderController.res | 7 ++++++ src/Payments/PaypalSDK.res | 2 ++ src/Payments/PaypalSDKHelpers.res | 1 + src/Utilities/PaymentHelpers.res | 28 +++++++++++++++++++++--- src/Utilities/RecoilAtoms.res | 1 + src/Utilities/Utils.res | 5 +++++ src/orca-loader/Elements.res | 7 ++++++ src/orca-loader/LoaderPaymentElement.res | 7 ++++++ src/orca-loader/Types.res | 13 ++++++++++- 9 files changed, 67 insertions(+), 4 deletions(-) diff --git a/src/LoaderController.res b/src/LoaderController.res index d81b6457b..31fa6e4a6 100644 --- a/src/LoaderController.res +++ b/src/LoaderController.res @@ -35,6 +35,9 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime let setUserAddressState = Recoil.useLoggedSetRecoilState(userAddressState, "state", logger) let setUserAddressCountry = Recoil.useLoggedSetRecoilState(userAddressCountry, "country", logger) let (_country, setCountry) = Recoil.useRecoilState(userCountry) + let (isCompleteCallbackUsed, setIsCompleteCallbackUsed) = Recoil.useRecoilState( + isCompleteCallbackUsed, + ) let optionsCallback = (optionsPayment: PaymentType.options) => { [ @@ -245,6 +248,10 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime let metadata = dict->getJsonObjectFromDict("analyticsMetadata") logger.setMetadata(metadata) } + if dict->getDictIsSome("onCompleteDoThisUsed") { + let isCallbackUsedVal = dict->Utils.getBool("onCompleteDoThisUsed", false) + setIsCompleteCallbackUsed(_ => isCallbackUsedVal) + } if dict->getDictIsSome("paymentOptions") { let paymentOptions = dict->getDictFromObj("paymentOptions") diff --git a/src/Payments/PaypalSDK.res b/src/Payments/PaypalSDK.res index 7763a6fd7..f92957c67 100644 --- a/src/Payments/PaypalSDK.res +++ b/src/Payments/PaypalSDK.res @@ -9,6 +9,7 @@ let make = (~sessionObj: SessionsType.token, ~paymentType: CardThemeType.mode) = let areOneClickWalletsRendered = Recoil.useSetRecoilState(RecoilAtoms.areOneClickWalletsRendered) let paymentMethodListValue = Recoil.useRecoilValueFromAtom(PaymentUtils.paymentMethodListValue) let (isCompleted, setIsCompleted) = React.useState(_ => false) + let isCallbackUsedVal = Recoil.useRecoilValueFromAtom(RecoilAtoms.isCompleteCallbackUsed) let token = sessionObj.token let orderDetails = sessionObj.orderDetails->getOrderDetails(paymentType) @@ -90,6 +91,7 @@ let make = (~sessionObj: SessionsType.token, ~paymentType: CardThemeType.mode) = ~handleCloseLoader, ~areOneClickWalletsRendered, ~setIsCompleted, + ~isCallbackUsedVal, ) }) Window.body->Window.appendChild(paypalScript) diff --git a/src/Payments/PaypalSDKHelpers.res b/src/Payments/PaypalSDKHelpers.res index 71c08e1e5..c9287ff57 100644 --- a/src/Payments/PaypalSDKHelpers.res +++ b/src/Payments/PaypalSDKHelpers.res @@ -20,6 +20,7 @@ let loadPaypalSDK = ( RecoilAtoms.areOneClickWalletsRendered => RecoilAtoms.areOneClickWalletsRendered ) => unit, ~setIsCompleted, + ~isCallbackUsedVal: bool, ) => { loggerState.setLogInfo( ~value="Paypal SDK Button Clicked", diff --git a/src/Utilities/PaymentHelpers.res b/src/Utilities/PaymentHelpers.res index af404ea10..981517c51 100644 --- a/src/Utilities/PaymentHelpers.res +++ b/src/Utilities/PaymentHelpers.res @@ -315,9 +315,11 @@ let rec intentCall = ( ~sdkHandleOneClickConfirmPayment, ~counter, ~isPaymentSession=false, + ~isCallbackUsedVal=?, ) => { open Promise let isConfirm = uri->String.includes("/confirm") + let isCompleteAuthorize = uri->String.includes("/complete_authorize") let (eventName: OrcaLogger.eventName, initEventName: OrcaLogger.eventName) = switch ( isConfirm, @@ -506,14 +508,28 @@ let rec intentCall = ( | (Applepay, false) | (Paypal, false) => if !isPaymentSession { - closePaymentLoaderIfAny() + if isCallbackUsedVal->Option.getOr(false) { + Utils.handleOnCompleteDoThisMessage() + } else { + closePaymentLoaderIfAny() + } + postSubmitResponse(~jsonData=data, ~url=url.href) } else if confirmParam.redirect === Some("always") { - handleOpenUrl(url.href) + if isCallbackUsedVal->Option.getOr(false) { + Utils.handleOnCompleteDoThisMessage() + } else { + handleOpenUrl(url.href) + } } else { resolve(data) } - | _ => handleOpenUrl(url.href) + | _ => + if isCallbackUsedVal->Option.getOr(false) { + Utils.handleOnCompleteDoThisMessage() + } else { + handleOpenUrl(url.href) + } } } @@ -890,6 +906,7 @@ let usePaymentSync = (optLogger: option, paymentType: pay open RecoilAtoms let paymentMethodList = Recoil.useRecoilValueFromAtom(paymentMethodList) let keys = Recoil.useRecoilValueFromAtom(keys) + let isCallbackUsedVal = Recoil.useRecoilValueFromAtom(RecoilAtoms.isCompleteCallbackUsed) let customPodUri = Recoil.useRecoilValueFromAtom(customPodUri) let setIsManualRetryEnabled = Recoil.useSetRecoilState(isManualRetryEnabled) (~handleUserError=false, ~confirmParam: ConfirmType.confirmParams, ~iframeId="") => { @@ -917,6 +934,7 @@ let usePaymentSync = (optLogger: option, paymentType: pay ~customPodUri, ~sdkHandleOneClickConfirmPayment=keys.sdkHandleOneClickConfirmPayment, ~counter=0, + ~isCallbackUsedVal, )->ignore } switch paymentMethodList { @@ -963,6 +981,7 @@ let usePaymentIntent = (optLogger, paymentType) => { let customPodUri = Recoil.useRecoilValueFromAtom(customPodUri) let paymentMethodList = Recoil.useRecoilValueFromAtom(paymentMethodList) let keys = Recoil.useRecoilValueFromAtom(keys) + let isCallbackUsedVal = Recoil.useRecoilValueFromAtom(RecoilAtoms.isCompleteCallbackUsed) let setIsManualRetryEnabled = Recoil.useSetRecoilState(isManualRetryEnabled) ( @@ -1056,6 +1075,7 @@ let usePaymentIntent = (optLogger, paymentType) => { ~customPodUri, ~sdkHandleOneClickConfirmPayment=keys.sdkHandleOneClickConfirmPayment, ~counter=0, + ~isCallbackUsedVal, ) ->then(val => { intentCallback(val) @@ -1140,6 +1160,7 @@ let useCompleteAuthorize = (optLogger: option, paymentTyp let customPodUri = Recoil.useRecoilValueFromAtom(customPodUri) let setIsManualRetryEnabled = Recoil.useSetRecoilState(isManualRetryEnabled) let url = RescriptReactRouter.useUrl() + let isCallbackUsedVal = Recoil.useRecoilValueFromAtom(RecoilAtoms.isCompleteCallbackUsed) let paymentTypeFromUrl = CardUtils.getQueryParamsDictforKey(url.search, "componentName")->CardThemeType.getPaymentMode ( @@ -1183,6 +1204,7 @@ let useCompleteAuthorize = (optLogger: option, paymentTyp ~customPodUri, ~sdkHandleOneClickConfirmPayment=keys.sdkHandleOneClickConfirmPayment, ~counter=0, + ~isCallbackUsedVal, )->ignore } switch paymentMethodList { diff --git a/src/Utilities/RecoilAtoms.res b/src/Utilities/RecoilAtoms.res index 26752e0f4..6c2da891b 100644 --- a/src/Utilities/RecoilAtoms.res +++ b/src/Utilities/RecoilAtoms.res @@ -73,6 +73,7 @@ let userVpaId = Recoil.atom("userVpaId", defaultFieldValues) let userPixKey = Recoil.atom("userPixKey", defaultFieldValues) let userPixCPF = Recoil.atom("userPixCPF", defaultFieldValues) let userPixCNPJ = Recoil.atom("userPixCNPJ", defaultFieldValues) +let isCompleteCallbackUsed = Recoil.atom("isCompleteCallbackUsed", false) type areOneClickWalletsRendered = { isGooglePay: bool, diff --git a/src/Utilities/Utils.res b/src/Utilities/Utils.res index a571fd0fb..5c35b3524 100644 --- a/src/Utilities/Utils.res +++ b/src/Utilities/Utils.res @@ -28,6 +28,10 @@ let handleOnFocusPostMessage = (~targetOrigin="*") => { messageParentWindow([("focus", true->JSON.Encode.bool)], ~targetOrigin) } +let handleOnCompleteDoThisMessage = (~targetOrigin="*") => { + messageParentWindow([("completeDoThis", true->JSON.Encode.bool)], ~targetOrigin) +} + let handleOnBlurPostMessage = (~targetOrigin="*") => { messageParentWindow([("blur", true->JSON.Encode.bool)], ~targetOrigin) } @@ -1148,6 +1152,7 @@ let eventHandlerFunc = ( | Click | Ready | Focus + | CompleteDoThis | ConfirmPayment | OneClickConfirmPayment | Blur => diff --git a/src/orca-loader/Elements.res b/src/orca-loader/Elements.res index a493e6ed7..58828faf2 100644 --- a/src/orca-loader/Elements.res +++ b/src/orca-loader/Elements.res @@ -317,6 +317,13 @@ let make = ( ("analyticsMetadata", analyticsMetadata), ("launchTime", launchTime->JSON.Encode.float), ("customBackendUrl", customBackendUrl->JSON.Encode.string), + ( + "onCompleteDoThisUsed", + EventListenerManager.eventListenerMap + ->Dict.get("onCompleteDoThis") + ->Option.isSome + ->JSON.Encode.bool, + ), ]->Dict.fromArray let wallets = PaymentType.getWallets(newOptions->getDictFromJson, "wallets", logger) diff --git a/src/orca-loader/LoaderPaymentElement.res b/src/orca-loader/LoaderPaymentElement.res index 028e50132..a80176a48 100644 --- a/src/orca-loader/LoaderPaymentElement.res +++ b/src/orca-loader/LoaderPaymentElement.res @@ -47,6 +47,13 @@ let make = ( }, "onEscape", ) + | CompleteDoThis => + eventHandlerFunc( + ev => ev.data.completeDoThis, + eventHandler, + CompleteDoThis, + "onCompleteDoThis", + ) | Change => eventHandlerFunc( ev => ev.data.elementType === componentType, diff --git a/src/orca-loader/Types.res b/src/orca-loader/Types.res index 5186769da..74e8eb07e 100644 --- a/src/orca-loader/Types.res +++ b/src/orca-loader/Types.res @@ -4,6 +4,7 @@ type eventData = { blur: bool, ready: bool, clickTriggered: bool, + completeDoThis: bool, elementType: string, classChange: bool, newClassType: string, @@ -184,7 +185,16 @@ let defaultHyperInstance = { } type eventType = - Escape | Change | Click | Ready | Focus | Blur | ConfirmPayment | OneClickConfirmPayment | None + | Escape + | Change + | Click + | Ready + | Focus + | Blur + | CompleteDoThis + | ConfirmPayment + | OneClickConfirmPayment + | None let eventTypeMapper = event => { switch event { @@ -192,6 +202,7 @@ let eventTypeMapper = event => { | "change" => Change | "clickTriggered" => Click | "ready" => Ready + | "completeDoThis" => CompleteDoThis | "focus" => Focus | "blur" => Blur | "confirmTriggered" => ConfirmPayment From 5c08f6689a8a8277f7da20f329d5a7d5d8d783a3 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 15 Oct 2024 11:24:09 +0000 Subject: [PATCH 08/35] chore(release): 0.93.0 [skip ci] # [0.93.0](https://github.com/juspay/hyperswitch-web/compare/v0.92.1...v0.93.0) (2024-10-15) ### Features * added confirm handler ([#731](https://github.com/juspay/hyperswitch-web/issues/731)) ([4f65ecb](https://github.com/juspay/hyperswitch-web/commit/4f65ecbeb48022dbe9da507d98344e43c308b691)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 627e0d630..bae625bf4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# [0.93.0](https://github.com/juspay/hyperswitch-web/compare/v0.92.1...v0.93.0) (2024-10-15) + + +### Features + +* added confirm handler ([#731](https://github.com/juspay/hyperswitch-web/issues/731)) ([4f65ecb](https://github.com/juspay/hyperswitch-web/commit/4f65ecbeb48022dbe9da507d98344e43c308b691)) + ## [0.92.1](https://github.com/juspay/hyperswitch-web/compare/v0.92.0...v0.92.1) (2024-10-10) diff --git a/package-lock.json b/package-lock.json index 2d1564c42..9ce2d5343 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.92.1", + "version": "0.93.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.92.1", + "version": "0.93.0", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index 7780a714e..6c4849a45 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.92.1", + "version": "0.93.0", "main": "index.js", "private": true, "dependencies": { From 9c09ff2d90ece78583c897c9cb29f2f45f346f90 Mon Sep 17 00:00:00 2001 From: sakksham7 <130480324+sakksham7@users.noreply.github.com> Date: Tue, 15 Oct 2024 18:52:49 +0530 Subject: [PATCH 09/35] feat: added click handler (#732) --- CHANGELOG.md | 2 +- src/LoaderController.res | 8 ++++ src/Payments/ApplePay.res | 13 +++-- src/Payments/GPay.res | 5 +- src/Payments/KlarnaSDK.res | 11 +++-- src/Payments/PayPal.res | 5 +- src/Payments/PaypalSDK.res | 4 ++ src/Payments/PaypalSDKHelpers.res | 3 +- src/Utilities/RecoilAtoms.res | 1 + src/Utilities/Utils.res | 16 +++---- src/orca-loader/Elements.res | 61 +++++++++++++----------- src/orca-loader/LoaderPaymentElement.res | 45 +++++++++++++++++ src/orca-loader/Types.res | 4 ++ 13 files changed, 126 insertions(+), 52 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bae625bf4..3e913f58a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2370,4 +2370,4 @@ ### Features -* updated Readme ([427f8fd](https://github.com/juspay/hyperswitch-web/commit/427f8fd91be58fc63b0fa4ab326d562a4caaabab)) +* updated Readme ([427f8fd](https://github.com/juspay/hyperswitch-web/commit/427f8fd91be58fc63b0fa4ab326d562a4caaabab)) \ No newline at end of file diff --git a/src/LoaderController.res b/src/LoaderController.res index 31fa6e4a6..838cedee2 100644 --- a/src/LoaderController.res +++ b/src/LoaderController.res @@ -38,6 +38,9 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime let (isCompleteCallbackUsed, setIsCompleteCallbackUsed) = Recoil.useRecoilState( isCompleteCallbackUsed, ) + let (isPaymentButtonHandlerProvided, setIsPaymentButtonHandlerProvided) = Recoil.useRecoilState( + isPaymentButtonHandlerProvidedAtom, + ) let optionsCallback = (optionsPayment: PaymentType.options) => { [ @@ -248,10 +251,15 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime let metadata = dict->getJsonObjectFromDict("analyticsMetadata") logger.setMetadata(metadata) } + if dict->getDictIsSome("onCompleteDoThisUsed") { let isCallbackUsedVal = dict->Utils.getBool("onCompleteDoThisUsed", false) setIsCompleteCallbackUsed(_ => isCallbackUsedVal) } + if dict->getDictIsSome("isPaymentButtonHandlerProvided") { + let isSDKClick = dict->Utils.getBool("isPaymentButtonHandlerProvided", false) + setIsPaymentButtonHandlerProvided(_ => isSDKClick) + } if dict->getDictIsSome("paymentOptions") { let paymentOptions = dict->getDictFromObj("paymentOptions") diff --git a/src/Payments/ApplePay.res b/src/Payments/ApplePay.res index afbc951e0..0152259eb 100644 --- a/src/Payments/ApplePay.res +++ b/src/Payments/ApplePay.res @@ -5,9 +5,10 @@ let make = (~sessionObj: option, ~walletOptions, ~paymentType: CardTheme let url = RescriptReactRouter.useUrl() let componentName = CardUtils.getQueryParamsDictforKey(url.search, "componentName") let loggerState = Recoil.useRecoilValueFromAtom(RecoilAtoms.loggerAtom) - let {publishableKey, sdkHandleOneClickConfirmPayment} = Recoil.useRecoilValueFromAtom( - RecoilAtoms.keys, + let sdkHandleIsThere = Recoil.useRecoilValueFromAtom( + RecoilAtoms.isPaymentButtonHandlerProvidedAtom, ) + let {publishableKey} = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys) let isApplePayReady = Recoil.useRecoilValueFromAtom(RecoilAtoms.isApplePayReady) let setIsShowOrPayUsing = Recoil.useSetRecoilState(RecoilAtoms.isShowOrPayUsing) let (showApplePay, setShowApplePay) = React.useState(() => false) @@ -212,7 +213,7 @@ let make = (~sessionObj: option, ~walletOptions, ~paymentType: CardTheme ~paymentMethod="APPLE_PAY", ) setApplePayClicked(_ => true) - makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment) + makeOneClickHandlerPromise(sdkHandleIsThere) ->then(result => { let result = result->JSON.Decode.bool->Option.getOr(false) if result { @@ -241,7 +242,11 @@ let make = (~sessionObj: option, ~walletOptions, ~paymentType: CardTheme ~isManualRetryEnabled, ) } else { - ApplePayHelpers.handleApplePayButtonClicked(~sessionObj, ~componentName, ~paymentMethodListValue) + ApplePayHelpers.handleApplePayButtonClicked( + ~sessionObj, + ~componentName, + ~paymentMethodListValue, + ) } } else { let bodyDict = PaymentBody.applePayRedirectBody(~connectors) diff --git a/src/Payments/GPay.res b/src/Payments/GPay.res index 92e008ec9..d9e0c69d1 100644 --- a/src/Payments/GPay.res +++ b/src/Payments/GPay.res @@ -15,7 +15,8 @@ let make = ( let componentName = CardUtils.getQueryParamsDictforKey(url.search, "componentName") let loggerState = Recoil.useRecoilValueFromAtom(loggerAtom) let {iframeId} = Recoil.useRecoilValueFromAtom(keys) - let {publishableKey, sdkHandleOneClickConfirmPayment} = Recoil.useRecoilValueFromAtom(keys) + let isSDKHandleClick = Recoil.useRecoilValueFromAtom(isPaymentButtonHandlerProvidedAtom) + let {publishableKey} = Recoil.useRecoilValueFromAtom(keys) let options = Recoil.useRecoilValueFromAtom(optionAtom) let intent = PaymentHelpers.usePaymentIntent(Some(loggerState), Gpay) let isManualRetryEnabled = Recoil.useRecoilValueFromAtom(RecoilAtoms.isManualRetryEnabled) @@ -103,7 +104,7 @@ let make = ( ~eventName=GOOGLE_PAY_FLOW, ~paymentMethod="GOOGLE_PAY", ) - makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment)->then(result => { + makeOneClickHandlerPromise(isSDKHandleClick)->then(result => { let result = result->JSON.Decode.bool->Option.getOr(false) if result { if isInvokeSDKFlow { diff --git a/src/Payments/KlarnaSDK.res b/src/Payments/KlarnaSDK.res index b5b80397d..a53771a7b 100644 --- a/src/Payments/KlarnaSDK.res +++ b/src/Payments/KlarnaSDK.res @@ -9,11 +9,12 @@ open KlarnaSDKTypes let make = (~sessionObj: SessionsType.token) => { let url = RescriptReactRouter.useUrl() let componentName = CardUtils.getQueryParamsDictforKey(url.search, "componentName") - let loggerState = Recoil.useRecoilValueFromAtom(RecoilAtoms.loggerAtom) - let setIsShowOrPayUsing = Recoil.useSetRecoilState(RecoilAtoms.isShowOrPayUsing) - let {publishableKey, sdkHandleOneClickConfirmPayment} = Recoil.useRecoilValueFromAtom(keys) + let loggerState = Recoil.useRecoilValueFromAtom(loggerAtom) + let setIsShowOrPayUsing = Recoil.useSetRecoilState(isShowOrPayUsing) + let sdkHandleIsThere = Recoil.useRecoilValueFromAtom(isPaymentButtonHandlerProvidedAtom) + let {publishableKey} = Recoil.useRecoilValueFromAtom(keys) let options = Recoil.useRecoilValueFromAtom(optionAtom) - let isManualRetryEnabled = Recoil.useRecoilValueFromAtom(RecoilAtoms.isManualRetryEnabled) + let isManualRetryEnabled = Recoil.useRecoilValueFromAtom(isManualRetryEnabled) let intent = PaymentHelpers.usePaymentIntent(Some(loggerState), Other) let {iframeId} = Recoil.useRecoilValueFromAtom(keys) let status = CommonHooks.useScript("https://x.klarnacdn.net/kp/lib/v1/api.js") // Klarna SDK script @@ -65,7 +66,7 @@ let make = (~sessionObj: SessionsType.token) => { theme: options.wallets.style.theme == Dark ? "default" : "outlined", shape: "default", on_click: authorize => { - makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment)->then( + makeOneClickHandlerPromise(sdkHandleIsThere)->then( result => { let result = result->JSON.Decode.bool->Option.getOr(false) if result { diff --git a/src/Payments/PayPal.res b/src/Payments/PayPal.res index acc65239b..f7edbb5ff 100644 --- a/src/Payments/PayPal.res +++ b/src/Payments/PayPal.res @@ -14,7 +14,8 @@ let payPalIcon = let make = () => { let loggerState = Recoil.useRecoilValueFromAtom(loggerAtom) let (paypalClicked, setPaypalClicked) = React.useState(_ => false) - let {publishableKey, sdkHandleOneClickConfirmPayment} = Recoil.useRecoilValueFromAtom(keys) + let sdkHandleIsThere = Recoil.useRecoilValueFromAtom(isPaymentButtonHandlerProvidedAtom) + let {publishableKey} = Recoil.useRecoilValueFromAtom(keys) let options = Recoil.useRecoilValueFromAtom(optionAtom) let areOneClickWalletsRendered = Recoil.useSetRecoilState(areOneClickWalletsRendered) let paymentMethodListValue = Recoil.useRecoilValueFromAtom(PaymentUtils.paymentMethodListValue) @@ -48,7 +49,7 @@ let make = () => { ) setPaypalClicked(_ => true) open Promise - Utils.makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment) + Utils.makeOneClickHandlerPromise(sdkHandleIsThere) ->then(result => { let result = result->JSON.Decode.bool->Option.getOr(false) if result { diff --git a/src/Payments/PaypalSDK.res b/src/Payments/PaypalSDK.res index f92957c67..1abbc2886 100644 --- a/src/Payments/PaypalSDK.res +++ b/src/Payments/PaypalSDK.res @@ -5,6 +5,9 @@ let make = (~sessionObj: SessionsType.token, ~paymentType: CardThemeType.mode) = let {iframeId, publishableKey, sdkHandleOneClickConfirmPayment} = Recoil.useRecoilValueFromAtom( RecoilAtoms.keys, ) + let sdkHandleIsThere = Recoil.useRecoilValueFromAtom( + RecoilAtoms.isPaymentButtonHandlerProvidedAtom, + ) let (loggerState, _setLoggerState) = Recoil.useRecoilState(RecoilAtoms.loggerAtom) let areOneClickWalletsRendered = Recoil.useSetRecoilState(RecoilAtoms.areOneClickWalletsRendered) let paymentMethodListValue = Recoil.useRecoilValueFromAtom(PaymentUtils.paymentMethodListValue) @@ -92,6 +95,7 @@ let make = (~sessionObj: SessionsType.token, ~paymentType: CardThemeType.mode) = ~areOneClickWalletsRendered, ~setIsCompleted, ~isCallbackUsedVal, + ~sdkHandleIsThere, ) }) Window.body->Window.appendChild(paypalScript) diff --git a/src/Payments/PaypalSDKHelpers.res b/src/Payments/PaypalSDKHelpers.res index c9287ff57..e05a477b7 100644 --- a/src/Payments/PaypalSDKHelpers.res +++ b/src/Payments/PaypalSDKHelpers.res @@ -21,6 +21,7 @@ let loadPaypalSDK = ( ) => unit, ~setIsCompleted, ~isCallbackUsedVal: bool, + ~sdkHandleIsThere: bool, ) => { loggerState.setLogInfo( ~value="Paypal SDK Button Clicked", @@ -34,7 +35,7 @@ let loadPaypalSDK = ( style: buttonStyle, fundingSource: paypal["FUNDING"]["PAYPAL"], createOrder: () => { - Utils.makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment)->then(result => { + Utils.makeOneClickHandlerPromise(sdkHandleIsThere)->then(result => { let result = result->JSON.Decode.bool->Option.getOr(false) if result { Utils.messageParentWindow([ diff --git a/src/Utilities/RecoilAtoms.res b/src/Utilities/RecoilAtoms.res index 6c2da891b..d1207655f 100644 --- a/src/Utilities/RecoilAtoms.res +++ b/src/Utilities/RecoilAtoms.res @@ -74,6 +74,7 @@ let userPixKey = Recoil.atom("userPixKey", defaultFieldValues) let userPixCPF = Recoil.atom("userPixCPF", defaultFieldValues) let userPixCNPJ = Recoil.atom("userPixCNPJ", defaultFieldValues) let isCompleteCallbackUsed = Recoil.atom("isCompleteCallbackUsed", false) +let isPaymentButtonHandlerProvidedAtom = Recoil.atom("isPaymentButtonHandlerProvidedAtom", false) type areOneClickWalletsRendered = { isGooglePay: bool, diff --git a/src/Utilities/Utils.res b/src/Utilities/Utils.res index 5c35b3524..5a3b518f9 100644 --- a/src/Utilities/Utils.res +++ b/src/Utilities/Utils.res @@ -1212,25 +1212,25 @@ let getThemePromise = dict => { } } -let makeOneClickHandlerPromise = sdkHandleOneClickConfirmPayment => { - open EventListenerManager +let makeOneClickHandlerPromise = sdkHandleIsThere => { Promise.make((resolve, _) => { - if sdkHandleOneClickConfirmPayment { + if !sdkHandleIsThere { resolve(JSON.Encode.bool(true)) } else { - let handleMessage = (event: Types.event) => { + let handleMessage = (event: Window.event) => { let json = try { - event.data->anyTypeToJson + event.data->safeParse } catch { | _ => JSON.Encode.null } let dict = json->getDictFromJson - if dict->Dict.get("oneClickDoSubmit")->Option.isSome { - resolve(dict->Dict.get("oneClickDoSubmit")->Option.getOr(true->JSON.Encode.bool)) + + if dict->Dict.get("walletClickEvent")->Option.isSome { + resolve(dict->Dict.get("walletClickEvent")->Option.getOr(true->JSON.Encode.bool)) } } - addSmartEventListener("message", handleMessage, "onOneClickHandlerPaymentConfirm") + Window.addEventListener("message", handleMessage) handleOnConfirmPostMessage(~targetOrigin="*", ~isOneClick=true) } }) diff --git a/src/orca-loader/Elements.res b/src/orca-loader/Elements.res index 58828faf2..110353b7c 100644 --- a/src/orca-loader/Elements.res +++ b/src/orca-loader/Elements.res @@ -296,35 +296,38 @@ let make = ( ("loader", loader), ("fonts", fonts), ]->getJsonFromArrayOfJson - let message = - [ - ( - "paymentElementCreate", - componentType->getIsComponentTypeForPaymentElementCreate->JSON.Encode.bool, - ), - ("otherElements", otherElements->JSON.Encode.bool), - ("options", newOptions), - ("componentType", componentType->JSON.Encode.string), - ("paymentOptions", widgetOptions), - ("iframeId", selectorString->JSON.Encode.string), - ("publishableKey", publishableKey->JSON.Encode.string), - ("endpoint", endpoint->JSON.Encode.string), - ("sdkSessionId", sdkSessionId->JSON.Encode.string), - ("blockConfirm", blockConfirm->JSON.Encode.bool), - ("customPodUri", customPodUri->JSON.Encode.string), - ("sdkHandleOneClickConfirmPayment", sdkHandleOneClickConfirmPayment->JSON.Encode.bool), - ("parentURL", "*"->JSON.Encode.string), - ("analyticsMetadata", analyticsMetadata), - ("launchTime", launchTime->JSON.Encode.float), - ("customBackendUrl", customBackendUrl->JSON.Encode.string), - ( - "onCompleteDoThisUsed", - EventListenerManager.eventListenerMap - ->Dict.get("onCompleteDoThis") - ->Option.isSome - ->JSON.Encode.bool, - ), - ]->Dict.fromArray + let message = [ + ( + "paymentElementCreate", + componentType->getIsComponentTypeForPaymentElementCreate->JSON.Encode.bool, + ), + ("otherElements", otherElements->JSON.Encode.bool), + ("options", newOptions), + ("componentType", componentType->JSON.Encode.string), + ("paymentOptions", widgetOptions), + ("iframeId", selectorString->JSON.Encode.string), + ("publishableKey", publishableKey->JSON.Encode.string), + ("endpoint", endpoint->JSON.Encode.string), + ("sdkSessionId", sdkSessionId->JSON.Encode.string), + ("blockConfirm", blockConfirm->JSON.Encode.bool), + ("customPodUri", customPodUri->JSON.Encode.string), + ("sdkHandleOneClickConfirmPayment", sdkHandleOneClickConfirmPayment->JSON.Encode.bool), + ("parentURL", "*"->JSON.Encode.string), + ("analyticsMetadata", analyticsMetadata), + ("launchTime", launchTime->JSON.Encode.float), + ("customBackendUrl", customBackendUrl->JSON.Encode.string), + ( + "isPaymentButtonHandlerProvided", + LoaderPaymentElement.isPaymentButtonHandlerProvided.contents->JSON.Encode.bool, + ), + ( + "onCompleteDoThisUsed", + EventListenerManager.eventListenerMap + ->Dict.get("onCompleteDoThis") + ->Option.isSome + ->JSON.Encode.bool, + ), + ]->Dict.fromArray let wallets = PaymentType.getWallets(newOptions->getDictFromJson, "wallets", logger) diff --git a/src/orca-loader/LoaderPaymentElement.res b/src/orca-loader/LoaderPaymentElement.res index a80176a48..a09d0e8d8 100644 --- a/src/orca-loader/LoaderPaymentElement.res +++ b/src/orca-loader/LoaderPaymentElement.res @@ -6,6 +6,8 @@ open Identity @val @scope(("navigator", "clipboard")) external writeText: string => promise<'a> = "writeText" +let onCompleteDoThisUsed = ref(false) +let isPaymentButtonHandlerProvided = ref(false) let make = ( componentType, options, @@ -32,6 +34,48 @@ let make = ( true, ) + let asyncWrapper = async fn => { + try { + await fn() + } catch { + | err => Console.log2("Async function call failure", err) + } + } + + let currEventHandler = ref(Some(() => Promise.make((_, _) => {()}))) + let walletOneClickEventHandler = (event: Types.event) => { + let json = try { + event.data->anyTypeToJson + } catch { + | _ => JSON.Encode.null + } + + let dict = json->getDictFromJson + if dict->Dict.get("oneClickConfirmTriggered")->Option.isSome { + switch currEventHandler.contents { + | Some(eH) => + asyncWrapper(eH) + ->Promise.then(() => { + let msg = [("walletClickEvent", true->JSON.Encode.bool)]->Dict.fromArray + event.source->Window.sendPostMessage(msg) + Promise.resolve() + }) + ->ignore + + | None => () + } + } + } + + Window.addEventListener("message", walletOneClickEventHandler) + + let onSDKHandleClick = (eventHandler: option RescriptCore.Promise.t<'a>>) => { + currEventHandler := eventHandler + if eventHandler->Option.isSome { + isPaymentButtonHandlerProvided := true + } + } + let on = (eventType, eventHandler) => { switch eventType->eventTypeMapper { | Escape => @@ -368,6 +412,7 @@ let make = ( destroy, update, mount, + onSDKHandleClick, } } catch { | e => { diff --git a/src/orca-loader/Types.res b/src/orca-loader/Types.res index 74e8eb07e..932612800 100644 --- a/src/orca-loader/Types.res +++ b/src/orca-loader/Types.res @@ -31,6 +31,7 @@ type paymentElement = { mount: string => unit, focus: unit => unit, clear: unit => unit, + onSDKHandleClick: option Promise.t> => unit, } type element = { @@ -107,6 +108,8 @@ let fetchUpdates = () => { setTimeout(() => resolve(Dict.make()->JSON.Encode.object), 1000)->ignore }) } + +let fnArgument = Some(() => Promise.make((_, _) => {()})) let defaultPaymentElement = { on: (_str, _func) => (), collapse: () => (), @@ -117,6 +120,7 @@ let defaultPaymentElement = { mount: _string => (), focus: () => (), clear: () => (), + onSDKHandleClick: fnArgument => (), } let create = (_componentType, _options) => { From f1f8d3287fb523e1214688a5e81314811dd14eda Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 15 Oct 2024 13:24:57 +0000 Subject: [PATCH 10/35] chore(release): 0.94.0 [skip ci] # [0.94.0](https://github.com/juspay/hyperswitch-web/compare/v0.93.0...v0.94.0) (2024-10-15) ### Features * added click handler ([#732](https://github.com/juspay/hyperswitch-web/issues/732)) ([9c09ff2](https://github.com/juspay/hyperswitch-web/commit/9c09ff2d90ece78583c897c9cb29f2f45f346f90)) --- CHANGELOG.md | 9 ++++++++- package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e913f58a..f54bbf42e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# [0.94.0](https://github.com/juspay/hyperswitch-web/compare/v0.93.0...v0.94.0) (2024-10-15) + + +### Features + +* added click handler ([#732](https://github.com/juspay/hyperswitch-web/issues/732)) ([9c09ff2](https://github.com/juspay/hyperswitch-web/commit/9c09ff2d90ece78583c897c9cb29f2f45f346f90)) + # [0.93.0](https://github.com/juspay/hyperswitch-web/compare/v0.92.1...v0.93.0) (2024-10-15) @@ -2370,4 +2377,4 @@ ### Features -* updated Readme ([427f8fd](https://github.com/juspay/hyperswitch-web/commit/427f8fd91be58fc63b0fa4ab326d562a4caaabab)) \ No newline at end of file +* updated Readme ([427f8fd](https://github.com/juspay/hyperswitch-web/commit/427f8fd91be58fc63b0fa4ab326d562a4caaabab)) diff --git a/package-lock.json b/package-lock.json index 9ce2d5343..3d4424941 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.93.0", + "version": "0.94.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.93.0", + "version": "0.94.0", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index 6c4849a45..7bdfebcc0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.93.0", + "version": "0.94.0", "main": "index.js", "private": true, "dependencies": { From 5b7e78b49fe4ce7e05fafb4e259dfa6a3f71919e Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja Date: Tue, 15 Oct 2024 19:00:37 +0530 Subject: [PATCH 11/35] fix: callback fix --- src/orca-loader/LoaderPaymentElement.res | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/orca-loader/LoaderPaymentElement.res b/src/orca-loader/LoaderPaymentElement.res index a09d0e8d8..add7383b7 100644 --- a/src/orca-loader/LoaderPaymentElement.res +++ b/src/orca-loader/LoaderPaymentElement.res @@ -92,12 +92,14 @@ let make = ( "onEscape", ) | CompleteDoThis => - eventHandlerFunc( - ev => ev.data.completeDoThis, - eventHandler, - CompleteDoThis, - "onCompleteDoThis", - ) + if eventHandler->Option.isSome { + eventHandlerFunc( + ev => ev.data.completeDoThis, + eventHandler, + CompleteDoThis, + "onCompleteDoThis", + ) + } | Change => eventHandlerFunc( ev => ev.data.elementType === componentType, From ba47f2f662c962a3ff7c4a8aa664939bfcadd6ab Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 15 Oct 2024 13:32:57 +0000 Subject: [PATCH 12/35] chore(release): 0.94.1 [skip ci] ## [0.94.1](https://github.com/juspay/hyperswitch-web/compare/v0.94.0...v0.94.1) (2024-10-15) ### Bug Fixes * callback fix ([5b7e78b](https://github.com/juspay/hyperswitch-web/commit/5b7e78b49fe4ce7e05fafb4e259dfa6a3f71919e)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f54bbf42e..87f958649 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [0.94.1](https://github.com/juspay/hyperswitch-web/compare/v0.94.0...v0.94.1) (2024-10-15) + + +### Bug Fixes + +* callback fix ([5b7e78b](https://github.com/juspay/hyperswitch-web/commit/5b7e78b49fe4ce7e05fafb4e259dfa6a3f71919e)) + # [0.94.0](https://github.com/juspay/hyperswitch-web/compare/v0.93.0...v0.94.0) (2024-10-15) diff --git a/package-lock.json b/package-lock.json index 3d4424941..4e5fc3453 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.94.0", + "version": "0.94.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.94.0", + "version": "0.94.1", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index 7bdfebcc0..ddf8ff3eb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.94.0", + "version": "0.94.1", "main": "index.js", "private": true, "dependencies": { From 07c96127d60c0f598cb1ae6aadd95c9ce887d350 Mon Sep 17 00:00:00 2001 From: Sagnik Mitra <83326850+ImSagnik007@users.noreply.github.com> Date: Tue, 15 Oct 2024 20:38:16 +0530 Subject: [PATCH 13/35] refactor: Paypal Flow Refactor (#736) Co-authored-by: Pritish Budhiraja --- src/Components/SavedPaymentManagement.res | 2 +- src/Payments/PaypalSDK.res | 10 +- src/Payments/PaypalSDKHelpers.res | 111 +++++++++--- src/Utilities/PaymentHelpers.res | 198 +++++++++++++++++++++- src/Utilities/PaymentUtils.res | 2 +- src/orca-log-catcher/OrcaLogger.res | 4 + 6 files changed, 296 insertions(+), 31 deletions(-) diff --git a/src/Components/SavedPaymentManagement.res b/src/Components/SavedPaymentManagement.res index f492b4b24..f213bef33 100644 --- a/src/Components/SavedPaymentManagement.res +++ b/src/Components/SavedPaymentManagement.res @@ -9,7 +9,7 @@ let make = (~savedMethods: array, ~setSavedMethods) let logger = Recoil.useRecoilValueFromAtom(RecoilAtoms.loggerAtom) let removeSavedMethod = ( - savedMethods: array, + savedMethods: array, paymentMethodId, ) => { savedMethods->Array.filter(savedMethod => { diff --git a/src/Payments/PaypalSDK.res b/src/Payments/PaypalSDK.res index 1abbc2886..952c304b9 100644 --- a/src/Payments/PaypalSDK.res +++ b/src/Payments/PaypalSDK.res @@ -16,9 +16,11 @@ let make = (~sessionObj: SessionsType.token, ~paymentType: CardThemeType.mode) = let token = sessionObj.token let orderDetails = sessionObj.orderDetails->getOrderDetails(paymentType) - let intent = PaymentHelpers.usePaymentIntent(Some(loggerState), Paypal) - let isManualRetryEnabled = Recoil.useRecoilValueFromAtom(RecoilAtoms.isManualRetryEnabled) + let intent = PaymentHelpers.usePostSessionTokens(Some(loggerState), Paypal, Wallet) + let confirm = PaymentHelpers.usePaymentIntent(Some(loggerState), Paypal) + let sessions = Recoil.useRecoilValueFromAtom(RecoilAtoms.sessions) let completeAuthorize = PaymentHelpers.useCompleteAuthorize(Some(loggerState), Paypal) + let isManualRetryEnabled = Recoil.useRecoilValueFromAtom(RecoilAtoms.isManualRetryEnabled) let checkoutScript = Window.document(Window.window)->Window.getElementById("braintree-checkout")->Nullable.toOption let clientScript = @@ -84,18 +86,20 @@ let make = (~sessionObj: SessionsType.token, ~paymentType: CardThemeType.mode) = ~iframeId, ~paymentMethodListValue, ~isGuestCustomer, - ~intent, + ~postSessionTokens=intent, ~isManualRetryEnabled, ~options, ~publishableKey, ~paymentMethodTypes, ~stateJson, + ~confirm, ~completeAuthorize, ~handleCloseLoader, ~areOneClickWalletsRendered, ~setIsCompleted, ~isCallbackUsedVal, ~sdkHandleIsThere, + ~sessions, ) }) Window.body->Window.appendChild(paypalScript) diff --git a/src/Payments/PaypalSDKHelpers.res b/src/Payments/PaypalSDKHelpers.res index e05a477b7..0b4bc071b 100644 --- a/src/Payments/PaypalSDKHelpers.res +++ b/src/Payments/PaypalSDKHelpers.res @@ -1,27 +1,30 @@ open PaypalSDKTypes open Promise +open Utils let loadPaypalSDK = ( ~loggerState: OrcaLogger.loggerMake, - ~sdkHandleOneClickConfirmPayment, + ~sdkHandleOneClickConfirmPayment as _, ~buttonStyle, ~iframeId, ~isManualRetryEnabled, ~paymentMethodListValue, ~isGuestCustomer, - ~intent: PaymentHelpers.paymentIntent, + ~postSessionTokens: PaymentHelpers.paymentIntent, ~options: PaymentType.options, ~publishableKey, ~paymentMethodTypes, ~stateJson, + ~confirm: PaymentHelpers.paymentIntent, ~completeAuthorize: PaymentHelpers.completeAuthorize, ~handleCloseLoader, ~areOneClickWalletsRendered: ( RecoilAtoms.areOneClickWalletsRendered => RecoilAtoms.areOneClickWalletsRendered ) => unit, ~setIsCompleted, - ~isCallbackUsedVal: bool, + ~isCallbackUsedVal as _: bool, ~sdkHandleIsThere: bool, + ~sessions: PaymentType.loadType, ) => { loggerState.setLogInfo( ~value="Paypal SDK Button Clicked", @@ -31,6 +34,23 @@ let loadPaypalSDK = ( let paypalWrapper = GooglePayType.getElementById(Utils.document, "paypal-button") paypalWrapper.innerHTML = "" setIsCompleted(_ => true) + let paypalNextAction = switch sessions { + | Loaded(data) => + data + ->getDictFromJson + ->getOptionalArrayFromDict("session_token") + ->Option.flatMap(arr => { + arr->Array.find(ele => ele->getDictFromJson->getString("connector", "") == "paypal") + }) + ->Option.flatMap(ele => { + ele + ->getDictFromJson + ->getDictFromDict("sdk_next_action") + ->getOptionString("next_action") + }) + ->Option.getOr("") + | _ => "" + } paypal["Buttons"]({ style: buttonStyle, fundingSource: paypal["FUNDING"]["PAYPAL"], @@ -52,17 +72,36 @@ let loadPaypalSDK = ( ~body, ) Promise.make((resolve, _) => { - intent( - ~bodyArr=modifiedPaymentBody, - ~confirmParam={ - return_url: options.wallets.walletReturnUrl, - publishableKey, - }, - ~handleUserError=true, - ~intentCallback=val => - val->Utils.getDictFromJson->Utils.getString("orderId", "")->resolve, - ~manualRetry=isManualRetryEnabled, - ) + if paypalNextAction == "post_session_tokens" { + postSessionTokens( + ~bodyArr=modifiedPaymentBody, + ~confirmParam={ + return_url: options.wallets.walletReturnUrl, + publishableKey, + }, + ~handleUserError=true, + ~intentCallback=val => { + val + ->Utils.getDictFromJson + ->Utils.getDictFromDict("nextActionData") + ->Utils.getString("order_id", "") + ->resolve + }, + ~manualRetry=isManualRetryEnabled, + ) + } else { + confirm( + ~bodyArr=modifiedPaymentBody, + ~confirmParam={ + return_url: options.wallets.walletReturnUrl, + publishableKey, + }, + ~handleUserError=true, + ~intentCallback=val => + val->Utils.getDictFromJson->Utils.getString("orderId", "")->resolve, + ~manualRetry=isManualRetryEnabled, + ) + } }) } else { loggerState.setLogInfo( @@ -100,22 +139,46 @@ let loadPaypalSDK = ( ~statesList=stateJson, ) + let (connectors, _) = + paymentMethodListValue->PaymentUtils.getConnectors(Wallets(Paypal(SDK))) + + let orderId = val->Utils.getDictFromJson->Utils.getString("id", "") + let body = PaymentBody.paypalSdkBody(~token=orderId, ~connectors) + let modifiedPaymentBody = PaymentUtils.appendedCustomerAcceptance( + ~isGuestCustomer, + ~paymentType=paymentMethodListValue.payment_type, + ~body, + ) + let bodyArr = requiredFieldsBody ->JSON.Encode.object ->Utils.unflattenObject ->Utils.getArrayOfTupleFromDict - completeAuthorize( - ~bodyArr, - ~confirmParam={ - return_url: options.wallets.walletReturnUrl, - publishableKey, - }, - ~handleUserError=true, - ) - - resolve() + let confirmBody = bodyArr->Array.concatMany([modifiedPaymentBody]) + Promise.make((_resolve, _) => { + if paypalNextAction == "post_session_tokens" { + confirm( + ~bodyArr=confirmBody, + ~confirmParam={ + return_url: options.wallets.walletReturnUrl, + publishableKey, + }, + ~handleUserError=true, + ~manualRetry=true, + ) + } else { + completeAuthorize( + ~bodyArr, + ~confirmParam={ + return_url: options.wallets.walletReturnUrl, + publishableKey, + }, + ~handleUserError=true, + ) + } + }) }) ->ignore } diff --git a/src/Utilities/PaymentHelpers.res b/src/Utilities/PaymentHelpers.res index 981517c51..0fa7d7b5e 100644 --- a/src/Utilities/PaymentHelpers.res +++ b/src/Utilities/PaymentHelpers.res @@ -321,12 +321,15 @@ let rec intentCall = ( let isConfirm = uri->String.includes("/confirm") let isCompleteAuthorize = uri->String.includes("/complete_authorize") + let isPostSessionTokens = uri->String.includes("/post_session_tokens") let (eventName: OrcaLogger.eventName, initEventName: OrcaLogger.eventName) = switch ( isConfirm, isCompleteAuthorize, + isPostSessionTokens, ) { - | (true, _) => (CONFIRM_CALL, CONFIRM_CALL_INIT) - | (_, true) => (COMPLETE_AUTHORIZE_CALL, COMPLETE_AUTHORIZE_CALL_INIT) + | (true, _, _) => (CONFIRM_CALL, CONFIRM_CALL_INIT) + | (_, true, _) => (COMPLETE_AUTHORIZE_CALL, COMPLETE_AUTHORIZE_CALL_INIT) + | (_, _, true) => (POST_SESSION_TOKENS_CALL, POST_SESSION_TOKENS_CALL_INIT) | _ => (RETRIEVE_CALL, RETRIEVE_CALL_INIT) } logApi( @@ -763,6 +766,17 @@ let rec intentCall = ( resolve(failedSubmitResponse) } } + } else if intent.status == "requires_payment_method" { + if intent.nextAction.type_ === "invoke_sdk_client" { + let nextActionData = + intent.nextAction.next_action_data->Option.getOr(JSON.Encode.null) + let response = + [ + ("orderId", intent.connectorTransactionId->JSON.Encode.string), + ("nextActionData", nextActionData), + ]->getJsonFromArrayOfJson + resolve(response) + } } else if intent.status == "processing" { if intent.nextAction.type_ == "third_party_sdk_session_token" { let session_token = switch intent.nextAction.session_token { @@ -2072,3 +2086,183 @@ let calculateTax = ( JSON.Encode.null->resolve }) } + +let usePostSessionTokens = ( + optLogger, + paymentType: payment, + paymentMethod: PaymentMethodCollectTypes.paymentMethod, +) => { + open RecoilAtoms + open Promise + let url = RescriptReactRouter.useUrl() + let paymentTypeFromUrl = + CardUtils.getQueryParamsDictforKey(url.search, "componentName")->CardThemeType.getPaymentMode + let customPodUri = Recoil.useRecoilValueFromAtom(customPodUri) + let paymentMethodList = Recoil.useRecoilValueFromAtom(paymentMethodList) + let keys = Recoil.useRecoilValueFromAtom(keys) + + let setIsManualRetryEnabled = Recoil.useSetRecoilState(isManualRetryEnabled) + ( + ~handleUserError=false, + ~bodyArr: array<(string, JSON.t)>, + ~confirmParam: ConfirmType.confirmParams, + ~iframeId=keys.iframeId, + ~isThirdPartyFlow=false, + ~intentCallback=_ => (), + ~manualRetry as _=false, + ) => { + switch keys.clientSecret { + | Some(clientSecret) => + let paymentIntentID = clientSecret->getPaymentId + let headers = [ + ("Content-Type", "application/json"), + ("api-key", confirmParam.publishableKey), + ("X-Client-Source", paymentTypeFromUrl->CardThemeType.getPaymentModeToStrMapper), + ] + let body = [ + ("client_secret", clientSecret->JSON.Encode.string), + ("payment_id", paymentIntentID->JSON.Encode.string), + ("payment_method_type", (paymentType :> string)->JSON.Encode.string), + ("payment_method", (paymentMethod :> string)->JSON.Encode.string), + ] + + let endpoint = ApiEndpoint.getApiEndPoint( + ~publishableKey=confirmParam.publishableKey, + ~isConfirmCall=isThirdPartyFlow, + ) + let uri = `${endpoint}/payments/${paymentIntentID}/post_session_tokens` + + let callIntent = body => { + let contentLength = body->String.length->Int.toString + let maskedPayload = + body->safeParseOpt->Option.getOr(JSON.Encode.null)->maskPayload->JSON.stringify + let loggerPayload = + [ + ("payload", maskedPayload->JSON.Encode.string), + ( + "headers", + headers + ->Array.map(header => { + let (key, value) = header + (key, value->JSON.Encode.string) + }) + ->Utils.getJsonFromArrayOfJson, + ), + ] + ->Utils.getJsonFromArrayOfJson + ->JSON.stringify + switch paymentType { + | Card => + handleLogging( + ~optLogger, + ~internalMetadata=loggerPayload, + ~value=contentLength, + ~eventName=PAYMENT_ATTEMPT, + ~paymentMethod="CARD", + ) + | _ => + bodyArr->Array.forEach(((str, json)) => { + if str === "payment_method_type" { + handleLogging( + ~optLogger, + ~value=contentLength, + ~internalMetadata=loggerPayload, + ~eventName=PAYMENT_ATTEMPT, + ~paymentMethod=json->getStringFromJson(""), + ) + } + () + }) + } + + intentCall( + ~fetchApi, + ~uri, + ~headers, + ~bodyStr=body, + ~confirmParam: ConfirmType.confirmParams, + ~clientSecret, + ~optLogger, + ~handleUserError, + ~paymentType, + ~iframeId, + ~fetchMethod=#POST, + ~setIsManualRetryEnabled, + ~customPodUri, + ~sdkHandleOneClickConfirmPayment=keys.sdkHandleOneClickConfirmPayment, + ~counter=0, + ) + ->then(val => { + intentCallback(val) + resolve() + }) + ->ignore + } + + let broswerInfo = BrowserSpec.broswerInfo + let intentWithoutMandate = mandatePaymentType => { + let bodyStr = + body + ->Array.concatMany([ + bodyArr->Array.concat(broswerInfo()), + mandatePaymentType->PaymentBody.paymentTypeBody, + ]) + ->Utils.getJsonFromArrayOfJson + ->JSON.stringify + callIntent(bodyStr) + } + + let intentWithMandate = mandatePaymentType => { + let bodyStr = + body + ->Array.concat( + bodyArr->Array.concatMany([PaymentBody.mandateBody(mandatePaymentType), broswerInfo()]), + ) + ->Utils.getJsonFromArrayOfJson + ->JSON.stringify + callIntent(bodyStr) + } + + switch paymentMethodList { + | LoadError(data) + | Loaded(data) => + let paymentList = data->getDictFromJson->PaymentMethodsRecord.itemToObjMapper + let mandatePaymentType = + paymentList.payment_type->PaymentMethodsRecord.paymentTypeToStringMapper + if paymentList.payment_methods->Array.length > 0 { + switch paymentList.mandate_payment { + | Some(_) => + switch paymentType { + | Card + | Gpay + | Applepay + | KlarnaRedirect + | Paypal + | BankDebits => + intentWithMandate(mandatePaymentType) + | _ => intentWithoutMandate(mandatePaymentType) + } + | None => intentWithoutMandate(mandatePaymentType) + } + } else { + postFailedSubmitResponse( + ~errortype="payment_methods_empty", + ~message="Payment Failed. Try again!", + ) + Console.warn("Please enable atleast one Payment method.") + } + | SemiLoaded => intentWithoutMandate("") + | _ => + postFailedSubmitResponse( + ~errortype="payment_methods_loading", + ~message="Please wait. Try again!", + ) + } + | None => + postFailedSubmitResponse( + ~errortype="post_session_tokens_failed", + ~message="Post Session Tokens failed. Try again!", + ) + } + } +} diff --git a/src/Utilities/PaymentUtils.res b/src/Utilities/PaymentUtils.res index 6422fb090..150978000 100644 --- a/src/Utilities/PaymentUtils.res +++ b/src/Utilities/PaymentUtils.res @@ -478,7 +478,7 @@ let sortCustomerMethodsBasedOnPriority = ( } let getSupportedCardBrands = ( - paymentMethodListValue: OrcaPaymentPage.PaymentMethodsRecord.paymentMethodList, + paymentMethodListValue: PaymentMethodsRecord.paymentMethodList, ) => { let cardPaymentMethod = paymentMethodListValue.payment_methods->Array.find(ele => ele.payment_method === "card") diff --git a/src/orca-log-catcher/OrcaLogger.res b/src/orca-log-catcher/OrcaLogger.res index bdcc4e4cb..82ab3933c 100644 --- a/src/orca-log-catcher/OrcaLogger.res +++ b/src/orca-log-catcher/OrcaLogger.res @@ -84,6 +84,8 @@ type eventName = | DELETE_PAYMENT_METHODS_CALL_INIT | DELETE_PAYMENT_METHODS_CALL | EXTERNAL_TAX_CALCULATION + | POST_SESSION_TOKENS_CALL + | POST_SESSION_TOKENS_CALL_INIT let eventNameToStrMapper = eventName => { switch eventName { @@ -168,6 +170,8 @@ let eventNameToStrMapper = eventName => { | DELETE_PAYMENT_METHODS_CALL_INIT => "DELETE_PAYMENT_METHODS_CALL_INIT" | DELETE_PAYMENT_METHODS_CALL => "DELETE_PAYMENT_METHODS_CALL" | EXTERNAL_TAX_CALCULATION => "EXTERNAL_TAX_CALCULATION" + | POST_SESSION_TOKENS_CALL => "POST_SESSION_TOKENS_CALL" + | POST_SESSION_TOKENS_CALL_INIT => "POST_SESSION_TOKENS_CALL_INIT" } } From 85bc6df60547ddb3d609f95a342f33c220962314 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 15 Oct 2024 15:10:26 +0000 Subject: [PATCH 14/35] chore(release): 0.94.2 [skip ci] ## [0.94.2](https://github.com/juspay/hyperswitch-web/compare/v0.94.1...v0.94.2) (2024-10-15) --- CHANGELOG.md | 2 ++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 87f958649..7e8266a17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +## [0.94.2](https://github.com/juspay/hyperswitch-web/compare/v0.94.1...v0.94.2) (2024-10-15) + ## [0.94.1](https://github.com/juspay/hyperswitch-web/compare/v0.94.0...v0.94.1) (2024-10-15) diff --git a/package-lock.json b/package-lock.json index 4e5fc3453..57b209369 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.94.1", + "version": "0.94.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.94.1", + "version": "0.94.2", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index ddf8ff3eb..d7e353a44 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.94.1", + "version": "0.94.2", "main": "index.js", "private": true, "dependencies": { From 9a5b87d2f0f60c152a861d1f6e9837e49ef6a0ba Mon Sep 17 00:00:00 2001 From: Sagnik Mitra <83326850+ImSagnik007@users.noreply.github.com> Date: Wed, 16 Oct 2024 19:01:59 +0530 Subject: [PATCH 15/35] feat: dynamic tax calculation in paypal (#739) --- src/Payments/PaypalSDK.res | 10 ++++++--- src/Payments/PaypalSDKHelpers.res | 34 +++++++++++++++++++++++++++++-- src/Types/ApplePayTypes.res | 6 +++--- src/Types/PaypalSDKTypes.res | 12 +++++++++++ src/Utilities/ApplePayHelpers.res | 33 ++++++++++++++++++++++-------- src/Utilities/PaymentHelpers.res | 3 +++ src/Utilities/TaxCalculation.res | 2 ++ 7 files changed, 83 insertions(+), 17 deletions(-) diff --git a/src/Payments/PaypalSDK.res b/src/Payments/PaypalSDK.res index 952c304b9..5825e5fd6 100644 --- a/src/Payments/PaypalSDK.res +++ b/src/Payments/PaypalSDK.res @@ -2,9 +2,12 @@ open PaypalSDKTypes @react.component let make = (~sessionObj: SessionsType.token, ~paymentType: CardThemeType.mode) => { - let {iframeId, publishableKey, sdkHandleOneClickConfirmPayment} = Recoil.useRecoilValueFromAtom( - RecoilAtoms.keys, - ) + let { + iframeId, + publishableKey, + sdkHandleOneClickConfirmPayment, + clientSecret, + } = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys) let sdkHandleIsThere = Recoil.useRecoilValueFromAtom( RecoilAtoms.isPaymentButtonHandlerProvidedAtom, ) @@ -100,6 +103,7 @@ let make = (~sessionObj: SessionsType.token, ~paymentType: CardThemeType.mode) = ~isCallbackUsedVal, ~sdkHandleIsThere, ~sessions, + ~clientSecret, ) }) Window.body->Window.appendChild(paypalScript) diff --git a/src/Payments/PaypalSDKHelpers.res b/src/Payments/PaypalSDKHelpers.res index 0b4bc071b..ffdd80024 100644 --- a/src/Payments/PaypalSDKHelpers.res +++ b/src/Payments/PaypalSDKHelpers.res @@ -1,6 +1,7 @@ open PaypalSDKTypes open Promise open Utils +open TaxCalculation let loadPaypalSDK = ( ~loggerState: OrcaLogger.loggerMake, @@ -25,6 +26,7 @@ let loadPaypalSDK = ( ~isCallbackUsedVal as _: bool, ~sdkHandleIsThere: bool, ~sessions: PaymentType.loadType, + ~clientSecret, ) => { loggerState.setLogInfo( ~value="Paypal SDK Button Clicked", @@ -113,6 +115,35 @@ let loadPaypalSDK = ( } }) }, + onShippingAddressChange: data => { + let isTaxCalculationEnabled = paymentMethodListValue.is_tax_calculation_enabled + if isTaxCalculationEnabled { + let newShippingAddressObj = + data + ->getDictFromJson + ->getDictFromObj("shippingAddress") + ->shippingAddressItemToObjMapper + let newShippingAddress = + [ + ("state", newShippingAddressObj.state->Option.getOr("")->JSON.Encode.string), + ("country", newShippingAddressObj.countryCode->Option.getOr("")->JSON.Encode.string), + ("zip", newShippingAddressObj.postalCode->Option.getOr("")->JSON.Encode.string), + ]->getJsonFromArrayOfJson + + let paymentMethodType = "paypal"->JSON.Encode.string + + calculateTax( + ~shippingAddress=[("address", newShippingAddress)]->getJsonFromArrayOfJson, + ~logger=loggerState, + ~publishableKey, + ~clientSecret=clientSecret->Option.getOr(""), + ~paymentMethodType, + ~sessionId=data->getDictFromJson->Dict.get("orderID"), + ) + } else { + Js.Json.null->Js.Promise.resolve + } + }, onApprove: (_data, actions) => { if !options.readOnly { actions.order.get() @@ -141,8 +172,7 @@ let loadPaypalSDK = ( let (connectors, _) = paymentMethodListValue->PaymentUtils.getConnectors(Wallets(Paypal(SDK))) - - let orderId = val->Utils.getDictFromJson->Utils.getString("id", "") + let orderId = val->getDictFromJson->Utils.getString("id", "") let body = PaymentBody.paypalSdkBody(~token=orderId, ~connectors) let modifiedPaymentBody = PaymentUtils.appendedCustomerAcceptance( ~isGuestCustomer, diff --git a/src/Types/ApplePayTypes.res b/src/Types/ApplePayTypes.res index 998f42fcf..f644e938f 100644 --- a/src/Types/ApplePayTypes.res +++ b/src/Types/ApplePayTypes.res @@ -31,7 +31,7 @@ type lineItem = { \"type": string, } type shippingAddressChangeEvent = {shippingContact: JSON.t} -type updatedOrderDetails = {newTotal: lineItem, newLineItems: array} +type orderDetails = {newTotal: lineItem, newLineItems: array} type innerSession type session = { begin: unit => unit, @@ -41,8 +41,8 @@ type session = { mutable onvalidatemerchant: event => unit, completeMerchantValidation: JSON.t => unit, mutable onpaymentauthorized: event => unit, - mutable onshippingcontactselected: shippingAddressChangeEvent => unit, - completeShippingContactSelection: updatedOrderDetails => unit, + mutable onshippingcontactselected: shippingAddressChangeEvent => promise, + completeShippingContactSelection: orderDetails => unit, completePayment: JSON.t => unit, \"STATUS_SUCCESS": string, \"STATUS_FAILURE": string, diff --git a/src/Types/PaypalSDKTypes.res b/src/Types/PaypalSDKTypes.res index 48c01ac9c..6404cf731 100644 --- a/src/Types/PaypalSDKTypes.res +++ b/src/Types/PaypalSDKTypes.res @@ -79,6 +79,7 @@ type buttons = { onApprove: (data, actions) => unit, onCancel: data => unit, onError?: err => unit, + onShippingAddressChange?: JSON.t => promise, } let getLabel = (var: PaymentType.paypalStyleType) => { switch var { @@ -177,3 +178,14 @@ let getOrderDetails = (orderDetails, paymentType) => { shippingAddressOverride, } } + +let shippingAddressItemToObjMapper=dict=>{ + recipientName: dict->Utils.getOptionString("recipientName"), + line1: dict->Utils.getOptionString("line1"), + line2: dict->Utils.getOptionString("line2"), + city: dict->Utils.getOptionString("city"), + countryCode: dict->Utils.getOptionString("countryCode"), + postalCode: dict->Utils.getOptionString("postalCode"), + state: dict->Utils.getOptionString("state"), + phone: dict->Utils.getOptionString("phone"), +} \ No newline at end of file diff --git a/src/Utilities/ApplePayHelpers.res b/src/Utilities/ApplePayHelpers.res index 107ee1a26..688b9d647 100644 --- a/src/Utilities/ApplePayHelpers.res +++ b/src/Utilities/ApplePayHelpers.res @@ -106,6 +106,20 @@ let startApplePaySession = ( } ssn.onshippingcontactselected = shippingAddressChangeEvent => { + let currentTotal = paymentRequest->getDictFromJson->getDictFromDict("total") + let label = currentTotal->getString("label", "apple") + let currentAmount = currentTotal->getString("amount", "0.00") + let \"type" = currentTotal->getString("type", "final") + + let oldTotal: lineItem = { + label, + amount: currentAmount, + \"type", + } + let currentOrderDetails: orderDetails = { + newTotal: oldTotal, + newLineItems: [oldTotal], + } if isTaxCalculationEnabled { let newShippingContact = shippingAddressChangeEvent.shippingContact @@ -113,7 +127,7 @@ let startApplePaySession = ( ->shippingContactItemToObjMapper let newShippingAddress = [ - ("state", newShippingContact.locality->JSON.Encode.string), + ("state", newShippingContact.administrativeArea->JSON.Encode.string), ("country", newShippingContact.countryCode->JSON.Encode.string), ("zip", newShippingContact.postalCode->JSON.Encode.string), ]->getJsonFromArrayOfJson @@ -126,8 +140,7 @@ let startApplePaySession = ( ~publishableKey, ~clientSecret, ~paymentMethodType, - ) - ->thenResolve(response => { + )->thenResolve(response => { switch response->taxResponseToObjMapper { | Some(taxCalculationResponse) => { let (netAmount, ordertaxAmount, shippingCost) = ( @@ -136,13 +149,13 @@ let startApplePaySession = ( taxCalculationResponse.shipping_cost, ) let newTotal: lineItem = { - label: "Net Amount", + label, amount: netAmount->minorUnitToString, - \"type": "final", + \"type", } let newLineItems: array = [ { - label: "Bag Subtotal", + label: "Subtotal", amount: (netAmount - ordertaxAmount - shippingCost)->minorUnitToString, \"type": "final", }, @@ -157,16 +170,18 @@ let startApplePaySession = ( \"type": "final", }, ] - let updatedOrderDetails: updatedOrderDetails = { + let updatedOrderDetails: orderDetails = { newTotal, newLineItems, } ssn.completeShippingContactSelection(updatedOrderDetails) } - | None => ssn.abort() + | None => ssn.completeShippingContactSelection(currentOrderDetails) } }) - ->ignore + } else { + ssn.completeShippingContactSelection(currentOrderDetails) + resolve() } } diff --git a/src/Utilities/PaymentHelpers.res b/src/Utilities/PaymentHelpers.res index 0fa7d7b5e..ed4da5979 100644 --- a/src/Utilities/PaymentHelpers.res +++ b/src/Utilities/PaymentHelpers.res @@ -2017,6 +2017,7 @@ let calculateTax = ( ~shippingAddress, ~logger, ~customPodUri, + ~sessionId, ) => { open Promise let endpoint = ApiEndpoint.getApiEndPoint() @@ -2027,6 +2028,8 @@ let calculateTax = ( ("shipping", shippingAddress), ("payment_method_type", paymentMethodType), ] + sessionId->Option.mapOr((), id => body->Array.push(("session_id", id))->ignore) + logApi( ~optLogger=Some(logger), ~url=uri, diff --git a/src/Utilities/TaxCalculation.res b/src/Utilities/TaxCalculation.res index 0d9d0c33c..5f70f50c1 100644 --- a/src/Utilities/TaxCalculation.res +++ b/src/Utilities/TaxCalculation.res @@ -24,6 +24,7 @@ let calculateTax = ( ~clientSecret, ~publishableKey, ~paymentMethodType, + ~sessionId=None, ) => { PaymentHelpers.calculateTax( ~clientSecret=clientSecret->JSON.Encode.string, @@ -33,5 +34,6 @@ let calculateTax = ( ~shippingAddress, ~logger, ~customPodUri="", + ~sessionId, ) } From 3bdda4de1a49b189c806ff7c64e31958194a7c1b Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Wed, 16 Oct 2024 13:36:28 +0000 Subject: [PATCH 16/35] chore(release): 0.95.0 [skip ci] # [0.95.0](https://github.com/juspay/hyperswitch-web/compare/v0.94.2...v0.95.0) (2024-10-16) ### Features * dynamic tax calculation in paypal ([#739](https://github.com/juspay/hyperswitch-web/issues/739)) ([9a5b87d](https://github.com/juspay/hyperswitch-web/commit/9a5b87d2f0f60c152a861d1f6e9837e49ef6a0ba)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e8266a17..ce259d9cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# [0.95.0](https://github.com/juspay/hyperswitch-web/compare/v0.94.2...v0.95.0) (2024-10-16) + + +### Features + +* dynamic tax calculation in paypal ([#739](https://github.com/juspay/hyperswitch-web/issues/739)) ([9a5b87d](https://github.com/juspay/hyperswitch-web/commit/9a5b87d2f0f60c152a861d1f6e9837e49ef6a0ba)) + ## [0.94.2](https://github.com/juspay/hyperswitch-web/compare/v0.94.1...v0.94.2) (2024-10-15) ## [0.94.1](https://github.com/juspay/hyperswitch-web/compare/v0.94.0...v0.94.1) (2024-10-15) diff --git a/package-lock.json b/package-lock.json index 57b209369..35679a450 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.94.2", + "version": "0.95.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.94.2", + "version": "0.95.0", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index d7e353a44..dbb085acc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.94.2", + "version": "0.95.0", "main": "index.js", "private": true, "dependencies": { From c0d4e157e133d6c1f0a867ef2b9a8480eb314488 Mon Sep 17 00:00:00 2001 From: sakksham7 <130480324+sakksham7@users.noreply.github.com> Date: Wed, 16 Oct 2024 19:05:28 +0530 Subject: [PATCH 17/35] fix: closed loader before calling merchant callback (#741) --- src/Utilities/PaymentHelpers.res | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Utilities/PaymentHelpers.res b/src/Utilities/PaymentHelpers.res index ed4da5979..08179118e 100644 --- a/src/Utilities/PaymentHelpers.res +++ b/src/Utilities/PaymentHelpers.res @@ -529,6 +529,7 @@ let rec intentCall = ( } | _ => if isCallbackUsedVal->Option.getOr(false) { + closePaymentLoaderIfAny() Utils.handleOnCompleteDoThisMessage() } else { handleOpenUrl(url.href) From 6056997a133b0290460b1b34ed95e65c22c1cce8 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Wed, 16 Oct 2024 13:41:33 +0000 Subject: [PATCH 18/35] chore(release): 0.95.1 [skip ci] ## [0.95.1](https://github.com/juspay/hyperswitch-web/compare/v0.95.0...v0.95.1) (2024-10-16) ### Bug Fixes * closed loader before calling merchant callback ([#741](https://github.com/juspay/hyperswitch-web/issues/741)) ([c0d4e15](https://github.com/juspay/hyperswitch-web/commit/c0d4e157e133d6c1f0a867ef2b9a8480eb314488)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce259d9cd..5649fefd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [0.95.1](https://github.com/juspay/hyperswitch-web/compare/v0.95.0...v0.95.1) (2024-10-16) + + +### Bug Fixes + +* closed loader before calling merchant callback ([#741](https://github.com/juspay/hyperswitch-web/issues/741)) ([c0d4e15](https://github.com/juspay/hyperswitch-web/commit/c0d4e157e133d6c1f0a867ef2b9a8480eb314488)) + # [0.95.0](https://github.com/juspay/hyperswitch-web/compare/v0.94.2...v0.95.0) (2024-10-16) diff --git a/package-lock.json b/package-lock.json index 35679a450..9904961dd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.95.0", + "version": "0.95.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.95.0", + "version": "0.95.1", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index dbb085acc..1b03ff58e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.95.0", + "version": "0.95.1", "main": "index.js", "private": true, "dependencies": { From 52544466899116be2222c5a4db1da16241f4fa4b Mon Sep 17 00:00:00 2001 From: sakksham7 <130480324+sakksham7@users.noreply.github.com> Date: Mon, 21 Oct 2024 16:31:27 +0530 Subject: [PATCH 19/35] fix: extra scroll in safari (#744) --- src/Components/DynamicFields.res | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Components/DynamicFields.res b/src/Components/DynamicFields.res index 54158558f..973f2b3ec 100644 --- a/src/Components/DynamicFields.res +++ b/src/Components/DynamicFields.res @@ -524,7 +524,7 @@ let make = ( | Email => | PhoneNumber => | StateAndCity => -
+
Date: Mon, 21 Oct 2024 11:06:24 +0000 Subject: [PATCH 20/35] chore(release): 0.95.2 [skip ci] ## [0.95.2](https://github.com/juspay/hyperswitch-web/compare/v0.95.1...v0.95.2) (2024-10-21) ### Bug Fixes * extra scroll in safari ([#744](https://github.com/juspay/hyperswitch-web/issues/744)) ([5254446](https://github.com/juspay/hyperswitch-web/commit/52544466899116be2222c5a4db1da16241f4fa4b)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5649fefd6..9d09cae4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [0.95.2](https://github.com/juspay/hyperswitch-web/compare/v0.95.1...v0.95.2) (2024-10-21) + + +### Bug Fixes + +* extra scroll in safari ([#744](https://github.com/juspay/hyperswitch-web/issues/744)) ([5254446](https://github.com/juspay/hyperswitch-web/commit/52544466899116be2222c5a4db1da16241f4fa4b)) + ## [0.95.1](https://github.com/juspay/hyperswitch-web/compare/v0.95.0...v0.95.1) (2024-10-16) diff --git a/package-lock.json b/package-lock.json index 9904961dd..73b5fdfa3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.95.1", + "version": "0.95.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.95.1", + "version": "0.95.2", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index 1b03ff58e..097c5ff54 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.95.1", + "version": "0.95.2", "main": "index.js", "private": true, "dependencies": { From 90613062e9bcc1f19e538117d7aebddd3bd5fb76 Mon Sep 17 00:00:00 2001 From: aritro2002 Date: Mon, 21 Oct 2024 17:19:32 +0530 Subject: [PATCH 21/35] fix: add text overflow with ellipsis in dropdown (#745) Co-authored-by: Pritish Budhiraja --- src/Components/DropdownField.res | 3 ++- src/Components/PaymentDropDownField.res | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Components/DropdownField.res b/src/Components/DropdownField.res index d34f3411c..3c9f5ef0b 100644 --- a/src/Components/DropdownField.res +++ b/src/Components/DropdownField.res @@ -119,6 +119,7 @@ let make = ( background: disabled ? disbaledBG : themeObj.colorBackground, opacity: disabled ? "35%" : "", padding: themeObj.spacingUnit, + paddingRight: "22px", width: "100%", } name="" @@ -126,7 +127,7 @@ let make = ( disabled={readOnly || disabled} onChange=handleChange onFocus=handleFocus - className={`${inputClassStyles} ${className} w-full appearance-none outline-none ${cursorClass}`}> + className={`${inputClassStyles} ${className} w-full appearance-none outline-none overflow-hidden whitespace-nowrap text-ellipsis ${cursorClass}`}> {options ->Array.mapWithIndex((item, index) => { From 7796e996dfd32abc59306ab832ebf709d5ee1f19 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Mon, 21 Oct 2024 11:51:31 +0000 Subject: [PATCH 22/35] chore(release): 0.95.3 [skip ci] ## [0.95.3](https://github.com/juspay/hyperswitch-web/compare/v0.95.2...v0.95.3) (2024-10-21) ### Bug Fixes * add text overflow with ellipsis in dropdown ([#745](https://github.com/juspay/hyperswitch-web/issues/745)) ([9061306](https://github.com/juspay/hyperswitch-web/commit/90613062e9bcc1f19e538117d7aebddd3bd5fb76)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d09cae4c..ba0fefc95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [0.95.3](https://github.com/juspay/hyperswitch-web/compare/v0.95.2...v0.95.3) (2024-10-21) + + +### Bug Fixes + +* add text overflow with ellipsis in dropdown ([#745](https://github.com/juspay/hyperswitch-web/issues/745)) ([9061306](https://github.com/juspay/hyperswitch-web/commit/90613062e9bcc1f19e538117d7aebddd3bd5fb76)) + ## [0.95.2](https://github.com/juspay/hyperswitch-web/compare/v0.95.1...v0.95.2) (2024-10-21) diff --git a/package-lock.json b/package-lock.json index 73b5fdfa3..ac674f2f0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.95.2", + "version": "0.95.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.95.2", + "version": "0.95.3", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index 097c5ff54..d72e1f99a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.95.2", + "version": "0.95.3", "main": "index.js", "private": true, "dependencies": { From 44ed3a83b9686b140470575f7aa15c516cac1cc8 Mon Sep 17 00:00:00 2001 From: ArushKapoorJuspay <121166031+ArushKapoorJuspay@users.noreply.github.com> Date: Wed, 23 Oct 2024 15:59:53 +0530 Subject: [PATCH 23/35] feat: added apple pay support inside an iframe (#743) Co-authored-by: Shiva Nandan --- src/LoaderController.res | 7 +- src/Types/ApplePayTypes.res | 18 +++++ src/Utilities/ApplePayHelpers.res | 24 ++---- src/Utilities/PaymentHelpers.res | 9 ++- src/Utilities/Utils.res | 14 +++- src/Window.res | 6 ++ src/orca-loader/Elements.res | 91 ++++++++++++++++------- src/orca-loader/Hyper.res | 74 ++++++++++++++++++ src/orca-loader/PaymentSessionMethods.res | 1 + 9 files changed, 197 insertions(+), 47 deletions(-) diff --git a/src/LoaderController.res b/src/LoaderController.res index 838cedee2..9343459f3 100644 --- a/src/LoaderController.res +++ b/src/LoaderController.res @@ -18,6 +18,8 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime let (launchTime, setLaunchTime) = React.useState(_ => 0.0) let {showCardFormByDefault, paymentMethodOrder} = optionsPayment let (_, setPaymentMethodCollectOptions) = Recoil.useRecoilState(paymentMethodCollectOptionAtom) + let url = RescriptReactRouter.useUrl() + let componentName = CardUtils.getQueryParamsDictforKey(url.search, "componentName") let divRef = React.useRef(Nullable.null) @@ -148,7 +150,10 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime React.useEffect0(() => { messageParentWindow([("iframeMounted", true->JSON.Encode.bool)]) - messageParentWindow([("applePayMounted", true->JSON.Encode.bool)]) + messageParentWindow([ + ("applePayMounted", true->JSON.Encode.bool), + ("componentName", componentName->JSON.Encode.string), + ]) logger.setLogInitiated() let updatedState: PaymentType.loadType = switch paymentMethodList { | Loading => diff --git a/src/Types/ApplePayTypes.res b/src/Types/ApplePayTypes.res index f644e938f..983f4962c 100644 --- a/src/Types/ApplePayTypes.res +++ b/src/Types/ApplePayTypes.res @@ -185,3 +185,21 @@ let getPaymentRequestFromSession = (~sessionObj, ~componentName) => { paymentRequest } + +let handleApplePayIframePostMessage = (msg, componentName, mountedIframeRef) => { + let isApplePayMessageSent = ref(false) + + let iframes = Window.querySelectorAll("iframe") + + iframes->Array.forEach(iframe => { + let iframeSrc = iframe->Window.getAttribute("src")->Option.getOr("") + if iframeSrc->String.includes(`componentName=${componentName}`) { + iframe->Js.Nullable.return->Window.iframePostMessage(msg) + isApplePayMessageSent := true + } + }) + + if !isApplePayMessageSent.contents { + mountedIframeRef->Window.iframePostMessage(msg) + } +} diff --git a/src/Utilities/ApplePayHelpers.res b/src/Utilities/ApplePayHelpers.res index 688b9d647..5c33cca71 100644 --- a/src/Utilities/ApplePayHelpers.res +++ b/src/Utilities/ApplePayHelpers.res @@ -73,9 +73,8 @@ let startApplePaySession = ( ~applePaySessionRef, ~applePayPresent, ~logger: OrcaLogger.loggerMake, - ~applePayEvent: option=None, ~callBackFunc, - ~resolvePromise: option unit>=None, + ~resolvePromise, ~clientSecret, ~publishableKey, ~isTaxCalculationEnabled=false, @@ -202,18 +201,10 @@ let startApplePaySession = ( ~eventName=APPLE_PAY_FLOW, ~paymentMethod="APPLE_PAY", ) - switch (applePayEvent, resolvePromise) { - | (Some(applePayEvent), _) => { - let msg = [("showApplePayButton", true->JSON.Encode.bool)]->Dict.fromArray - applePayEvent.source->Window.sendPostMessage(msg) - } - | (_, Some(resolvePromise)) => - handleFailureResponse( - ~message="ApplePay Session Cancelled", - ~errorType="apple_pay", - )->resolvePromise - | _ => () - } + handleFailureResponse( + ~message="ApplePay Session Cancelled", + ~errorType="apple_pay", + )->resolvePromise } ssn.begin() } @@ -250,9 +241,9 @@ let useHandleApplePayResponse = ( let json = ev.data->safeParse try { let dict = json->getDictFromJson - if dict->Dict.get("applePayProcessPayment")->Option.isSome { + if dict->Dict.get("applePayPaymentToken")->Option.isSome { let token = - dict->Dict.get("applePayProcessPayment")->Option.getOr(Dict.make()->JSON.Encode.object) + dict->Dict.get("applePayPaymentToken")->Option.getOr(Dict.make()->JSON.Encode.object) let billingContactDict = dict->getDictFromDict("applePayBillingContact") let shippingContactDict = dict->getDictFromDict("applePayShippingContact") @@ -329,6 +320,7 @@ let handleApplePayButtonClicked = ( "isTaxCalculationEnabled", paymentMethodListValue.is_tax_calculation_enabled->JSON.Encode.bool, ), + ("componentName", componentName->JSON.Encode.string), ] messageParentWindow(message) } diff --git a/src/Utilities/PaymentHelpers.res b/src/Utilities/PaymentHelpers.res index 08179118e..ef3e67fbd 100644 --- a/src/Utilities/PaymentHelpers.res +++ b/src/Utilities/PaymentHelpers.res @@ -316,6 +316,7 @@ let rec intentCall = ( ~counter, ~isPaymentSession=false, ~isCallbackUsedVal=?, + ~componentName="payment", ) => { open Promise let isConfirm = uri->String.includes("/confirm") @@ -468,6 +469,7 @@ let rec intentCall = ( ~customPodUri, ~sdkHandleOneClickConfirmPayment, ~counter=counter + 1, + ~componentName, ) ->then( res => { @@ -704,6 +706,7 @@ let rec intentCall = ( | "apple_pay" => [ ("applePayButtonClicked", true->JSON.Encode.bool), ("applePayPresent", session_token->anyTypeToJson), + ("componentName", componentName->JSON.Encode.string), ] | "google_pay" => [("googlePayThirdPartyFlow", session_token->anyTypeToJson)] | "open_banking" => { @@ -893,6 +896,7 @@ let rec intentCall = ( ~sdkHandleOneClickConfirmPayment, ~counter=counter + 1, ~isPaymentSession, + ~componentName, ) ->then( res => { @@ -990,8 +994,8 @@ let usePaymentIntent = (optLogger, paymentType) => { open RecoilAtoms open Promise let url = RescriptReactRouter.useUrl() - let paymentTypeFromUrl = - CardUtils.getQueryParamsDictforKey(url.search, "componentName")->CardThemeType.getPaymentMode + let componentName = CardUtils.getQueryParamsDictforKey(url.search, "componentName") + let paymentTypeFromUrl = componentName->CardThemeType.getPaymentMode let blockConfirm = Recoil.useRecoilValueFromAtom(isConfirmBlocked) let customPodUri = Recoil.useRecoilValueFromAtom(customPodUri) let paymentMethodList = Recoil.useRecoilValueFromAtom(paymentMethodList) @@ -1091,6 +1095,7 @@ let usePaymentIntent = (optLogger, paymentType) => { ~sdkHandleOneClickConfirmPayment=keys.sdkHandleOneClickConfirmPayment, ~counter=0, ~isCallbackUsedVal, + ~componentName, ) ->then(val => { intentCallback(val) diff --git a/src/Utilities/Utils.res b/src/Utilities/Utils.res index 5a3b518f9..07e923f70 100644 --- a/src/Utilities/Utils.res +++ b/src/Utilities/Utils.res @@ -1,6 +1,7 @@ @val external document: 'a = "document" @val external window: Dom.element = "window" @val @scope("window") external iframeParent: Dom.element = "parent" +@val @scope("window") external topParent: Dom.element = "top" type event = {data: string} external dictToObj: Dict.t<'a> => {..} = "%identity" @@ -16,12 +17,21 @@ type dateTimeFormat = {resolvedOptions: unit => options} @send external postMessage: (Dom.element, JSON.t, string) => unit = "postMessage" open ErrorUtils + +let messageWindow = (window, ~targetOrigin="*", messageArr) => { + window->postMessage(messageArr->Dict.fromArray->JSON.Encode.object, targetOrigin) +} + +let messageTopWindow = (~targetOrigin="*", messageArr) => { + topParent->messageWindow(~targetOrigin, messageArr) +} + let messageParentWindow = (~targetOrigin="*", messageArr) => { - iframeParent->postMessage(messageArr->Dict.fromArray->JSON.Encode.object, targetOrigin) + iframeParent->messageWindow(~targetOrigin, messageArr) } let messageCurrentWindow = (~targetOrigin="*", messageArr) => { - window->postMessage(messageArr->Dict.fromArray->JSON.Encode.object, targetOrigin) + window->messageWindow(~targetOrigin, messageArr) } let handleOnFocusPostMessage = (~targetOrigin="*") => { diff --git a/src/Window.res b/src/Window.res index 231606624..ebb0570d6 100644 --- a/src/Window.res +++ b/src/Window.res @@ -26,6 +26,7 @@ type style external querySelector: string => Nullable.t = "querySelector" @val @scope("document") external querySelectorAll: string => array = "querySelectorAll" +@send external getAttribute: (Dom.element, string) => option = "getAttribute" type eventData = { elementType: string, @@ -44,6 +45,7 @@ external addEventListener: (string, _ => unit) => unit = "addEventListener" @val @scope("window") external removeEventListener: (string, 'ev => unit) => unit = "removeEventListener" @send external postMessage: (Dom.element, string, string) => unit = "postMessage" +@send external postMessageJSON: (Dom.element, JSON.t, string) => unit = "postMessage" @send external getElementById: (document, string) => Nullable.t = "getElementById" @get @@ -62,6 +64,10 @@ let sendPostMessage = (element, message) => { element->postMessage(message->JSON.Encode.object->JSON.stringify, GlobalVars.targetOrigin) } +let sendPostMessageJSON = (element, message) => { + element->postMessageJSON(message, GlobalVars.targetOrigin) +} + let iframePostMessage = (iframeRef: nullable, message) => { switch iframeRef->Nullable.toOption { | Some(ref) => diff --git a/src/orca-loader/Elements.res b/src/orca-loader/Elements.res index 110353b7c..a664a8750 100644 --- a/src/orca-loader/Elements.res +++ b/src/orca-loader/Elements.res @@ -21,7 +21,6 @@ let make = ( ~analyticsMetadata, ~customBackendUrl, ) => { - let applePaySessionRef = ref(Nullable.null) try { let iframeRef = [] let logger = logger->Option.getOr(OrcaLogger.defaultLoggerConfig) @@ -334,6 +333,7 @@ let make = ( let handleApplePayMounted = (event: Types.event) => { let json = event.data->anyTypeToJson let dict = json->getDictFromJson + let componentName = getString(dict, "componentName", "payment") if dict->Dict.get("applePayMounted")->Option.isSome { if wallets.applePay === Auto { @@ -341,8 +341,11 @@ let make = ( | Some(session) => try { if session.canMakePayments() { - let msg = [("applePayCanMakePayments", true->JSON.Encode.bool)]->Dict.fromArray - event.source->Window.sendPostMessage(msg) + let msg = [ + ("hyperApplePayCanMakePayments", true->JSON.Encode.bool), + ("componentName", componentName->JSON.Encode.string), + ] + messageTopWindow(msg) } else { Console.log("CANNOT MAKE PAYMENT USING APPLE PAY") logger.setLogInfo( @@ -374,6 +377,28 @@ let make = ( ~logType=INFO, ) } + } else if dict->Dict.get("applePayCanMakePayments")->Option.isSome { + let applePayCanMakePayments = getBool(dict, "applePayCanMakePayments", false) + + if applePayCanMakePayments { + try { + let msg = [("applePayCanMakePayments", true->JSON.Encode.bool)]->Dict.fromArray + + handleApplePayIframePostMessage(msg, componentName, mountedIframeRef) + } catch { + | exn => { + let exnString = exn->anyTypeToJson->JSON.stringify + + Console.log("CANNOT MAKE PAYMENT USING APPLE PAY: " ++ exnString) + logger.setLogInfo( + ~value=exnString, + ~eventName=APPLE_PAY_FLOW, + ~paymentMethod="APPLE_PAY", + ~logType=ERROR, + ) + } + } + } } } @@ -792,6 +817,8 @@ let make = ( let handleApplePayMessages = (applePayEvent: Types.event) => { let json = applePayEvent.data->Identity.anyTypeToJson let dict = json->getDictFromJson + let componentName = dict->getString("componentName", "payment") + switch ( dict->Dict.get("applePayButtonClicked"), dict->Dict.get("applePayPaymentRequest"), @@ -817,33 +844,45 @@ let make = ( ~paymentMethod="APPLE_PAY", ) - let callBackFunc = payment => { - let msg = - [ - ("applePayProcessPayment", payment.token), - ("applePayBillingContact", payment.billingContact), - ("applePayShippingContact", payment.shippingContact), - ]->Dict.fromArray - applePayEvent.source->Window.sendPostMessage(msg) - } - - ApplePayHelpers.startApplePaySession( - ~paymentRequest, - ~applePaySessionRef, - ~applePayPresent, - ~logger, - ~applePayEvent=Some(applePayEvent), - ~callBackFunc, - ~clientSecret, - ~publishableKey, - ~isTaxCalculationEnabled, - ) + let msg = [ + ("hyperApplePayButtonClicked", true->JSON.Encode.bool), + ("paymentRequest", paymentRequest), + ("applePayPresent", applePayPresent->Option.getOr(JSON.Encode.null)), + ("clientSecret", clientSecret->JSON.Encode.string), + ("publishableKey", publishableKey->JSON.Encode.string), + ("isTaxCalculationEnabled", isTaxCalculationEnabled->JSON.Encode.bool), + ("sdkSessionId", sdkSessionId->JSON.Encode.string), + ("analyticsMetadata", analyticsMetadata), + ("componentName", componentName->JSON.Encode.string), + ] + messageTopWindow(msg) } - } else { - () } | _ => () } + + if dict->Dict.get("applePayPaymentToken")->Option.isSome { + let token = dict->getJsonFromDict("applePayPaymentToken", JSON.Encode.null) + let billingContact = + dict->getJsonFromDict("applePayBillingContact", JSON.Encode.null) + let shippingContact = + dict->getJsonFromDict("applePayShippingContact", JSON.Encode.null) + + let msg = + [ + ("applePayPaymentToken", token), + ("applePayBillingContact", billingContact), + ("applePayShippingContact", shippingContact), + ]->Dict.fromArray + + handleApplePayIframePostMessage(msg, componentName, mountedIframeRef) + } + + if dict->Dict.get("showApplePayButton")->Option.isSome { + let msg = [("showApplePayButton", true->JSON.Encode.bool)]->Dict.fromArray + + handleApplePayIframePostMessage(msg, componentName, mountedIframeRef) + } } addSmartEventListener("message", handleApplePayMessages, "onApplePayMessages") diff --git a/src/orca-loader/Hyper.res b/src/orca-loader/Hyper.res index 6941d62a7..eb3d6e29e 100644 --- a/src/orca-loader/Hyper.res +++ b/src/orca-loader/Hyper.res @@ -60,6 +60,80 @@ let preloader = () => { preloadFile(~type_="script", ~href="https://js.braintreegateway.com/web/3.88.4/js/client.min.js") } +let handleHyperApplePayMounted = (event: Types.event) => { + open ApplePayTypes + let json = event.data->anyTypeToJson + let dict = json->getDictFromJson + let applePaySessionRef = ref(Nullable.null) + + let componentName = dict->getString("componentName", "payment") + + if dict->Dict.get("hyperApplePayCanMakePayments")->Option.isSome { + let msg = + [ + ("applePayCanMakePayments", true->JSON.Encode.bool), + ("componentName", componentName->JSON.Encode.string), + ] + ->Dict.fromArray + ->JSON.Encode.object + event.source->Window.sendPostMessageJSON(msg) + } else if dict->Dict.get("hyperApplePayButtonClicked")->Option.isSome { + let paymentRequest = dict->Dict.get("paymentRequest")->Option.getOr(JSON.Encode.null) + let applePayPresent = dict->Dict.get("applePayPresent") + let clientSecret = dict->getString("clientSecret", "") + let publishableKey = dict->getString("publishableKey", "") + let isTaxCalculationEnabled = dict->getBool("isTaxCalculationEnabled", false) + let sdkSessionId = dict->getString("sdkSessionId", "") + let analyticsMetadata = dict->getJsonFromDict("analyticsMetadata", JSON.Encode.null) + + let logger = OrcaLogger.make( + ~sessionId=sdkSessionId, + ~source=Loader, + ~merchantId=publishableKey, + ~metadata=analyticsMetadata, + ~clientSecret, + ) + + let callBackFunc = payment => { + let msg = + [ + ("applePayPaymentToken", payment.token), + ("applePayBillingContact", payment.billingContact), + ("applePayShippingContact", payment.shippingContact), + ("componentName", componentName->JSON.Encode.string), + ] + ->Dict.fromArray + ->JSON.Encode.object + event.source->Window.sendPostMessageJSON(msg) + } + + let resolvePromise = _ => { + let msg = + [ + ("showApplePayButton", true->JSON.Encode.bool), + ("componentName", componentName->JSON.Encode.string), + ] + ->Dict.fromArray + ->JSON.Encode.object + event.source->Window.sendPostMessageJSON(msg) + } + + ApplePayHelpers.startApplePaySession( + ~paymentRequest, + ~applePaySessionRef, + ~applePayPresent, + ~logger, + ~callBackFunc, + ~clientSecret, + ~publishableKey, + ~isTaxCalculationEnabled, + ~resolvePromise, + ) + } +} + +addSmartEventListener("message", handleHyperApplePayMounted, "onHyperApplePayMount") + let make = (publishableKey, options: option, analyticsInfo: option) => { try { let isPreloadEnabled = diff --git a/src/orca-loader/PaymentSessionMethods.res b/src/orca-loader/PaymentSessionMethods.res index 60e54b844..fb80a5614 100644 --- a/src/orca-loader/PaymentSessionMethods.res +++ b/src/orca-loader/PaymentSessionMethods.res @@ -194,6 +194,7 @@ let getCustomerSavedPaymentMethods = ( ~callBackFunc=processPayment, ~clientSecret, ~publishableKey, + ~resolvePromise, ) } From f53537abbe79d28e43805224e88dbef81a2ee2fe Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Wed, 23 Oct 2024 10:31:51 +0000 Subject: [PATCH 24/35] chore(release): 0.96.0 [skip ci] # [0.96.0](https://github.com/juspay/hyperswitch-web/compare/v0.95.3...v0.96.0) (2024-10-23) ### Features * added apple pay support inside an iframe ([#743](https://github.com/juspay/hyperswitch-web/issues/743)) ([44ed3a8](https://github.com/juspay/hyperswitch-web/commit/44ed3a83b9686b140470575f7aa15c516cac1cc8)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ba0fefc95..4e7bf7ee4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# [0.96.0](https://github.com/juspay/hyperswitch-web/compare/v0.95.3...v0.96.0) (2024-10-23) + + +### Features + +* added apple pay support inside an iframe ([#743](https://github.com/juspay/hyperswitch-web/issues/743)) ([44ed3a8](https://github.com/juspay/hyperswitch-web/commit/44ed3a83b9686b140470575f7aa15c516cac1cc8)) + ## [0.95.3](https://github.com/juspay/hyperswitch-web/compare/v0.95.2...v0.95.3) (2024-10-21) diff --git a/package-lock.json b/package-lock.json index ac674f2f0..7b8ec0ad0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.95.3", + "version": "0.96.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.95.3", + "version": "0.96.0", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index d72e1f99a..cd23cd0c7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.95.3", + "version": "0.96.0", "main": "index.js", "private": true, "dependencies": { From 6122d9d200b934969ee8643e598754d724a786a4 Mon Sep 17 00:00:00 2001 From: Sanskar Atrey Date: Fri, 25 Oct 2024 12:56:20 +0530 Subject: [PATCH 25/35] fix: card cvc bug fix (#748) --- .../cypress/e2e/cvc-checks-e2e-test.cy.ts | 84 +++++++++++++++++++ cypress-tests/cypress/support/utils.ts | 2 + src/CardUtils.res | 4 + src/Payment.res | 3 +- 4 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 cypress-tests/cypress/e2e/cvc-checks-e2e-test.cy.ts diff --git a/cypress-tests/cypress/e2e/cvc-checks-e2e-test.cy.ts b/cypress-tests/cypress/e2e/cvc-checks-e2e-test.cy.ts new file mode 100644 index 000000000..883aaa5bf --- /dev/null +++ b/cypress-tests/cypress/e2e/cvc-checks-e2e-test.cy.ts @@ -0,0 +1,84 @@ +import * as testIds from "../../../src/Utilities/TestUtils.bs"; +import { getClientURL, amexTestCard, visaTestCard, createPaymentBody } from "../support/utils"; + +describe("Card CVC Checks", () => { + let getIframeBody: () => Cypress.Chainable>; + const publishableKey = Cypress.env('HYPERSWITCH_PUBLISHABLE_KEY') + const secretKey = Cypress.env('HYPERSWITCH_SECRET_KEY') + let iframeSelector = + "#orca-payment-element-iframeRef-orca-elements-payment-element-payment-element"; + + + beforeEach(() => { + getIframeBody = () => cy.iframe(iframeSelector); + cy.createPaymentIntent(secretKey, createPaymentBody).then(() => { + cy.getGlobalState("clientSecret").then((clientSecret) => { + + cy.visit(getClientURL(clientSecret, publishableKey)); + }); + + }) + }); + + + + + it("title rendered correctly", () => { + cy.contains("Hyperswitch Unified Checkout").should("be.visible"); + }); + + it("orca-payment-element iframe loaded", () => { + cy.get( + "#orca-payment-element-iframeRef-orca-elements-payment-element-payment-element" + ) + .should("be.visible") + .its("0.contentDocument") + .its("body"); + }); + + + it('user can enter 4 digit cvc in card form', () => { + getIframeBody().find(`[data-testid=${testIds.addNewCardIcon}]`).click() + getIframeBody().find(`[data-testid=${testIds.cardNoInputTestId}]`).type(amexTestCard) + getIframeBody().find(`[data-testid=${testIds.expiryInputTestId}]`).type("0444") + getIframeBody().find(`[data-testid=${testIds.cardCVVInputTestId}]`).type("1234").then(() => { + getIframeBody().find(`[data-testid=${testIds.cardCVVInputTestId}]`).should('have.value', '1234'); + }) + + + }) + it('user can enter 3 digit cvc on saved payment methods screen', () => { + getIframeBody().find(`[data-testid=${testIds.cardCVVInputTestId}]`).type('123').then(() => { + getIframeBody().find(`[data-testid=${testIds.cardCVVInputTestId}]`).should('have.value', '123'); + }) + + }) + + it('user can enter 3 digit cvc in card form', () => { + getIframeBody().find(`[data-testid=${testIds.addNewCardIcon}]`).click() + getIframeBody().find(`[data-testid=${testIds.cardNoInputTestId}]`).type(visaTestCard) + getIframeBody().find(`[data-testid=${testIds.expiryInputTestId}]`).type("0444") + getIframeBody().find(`[data-testid=${testIds.cardCVVInputTestId}]`).type("123").then(() => { + getIframeBody().find(`[data-testid=${testIds.cardCVVInputTestId}]`).should('have.value', '123'); + }) + }) + + it('user can enter 4 digit cvc on saved payment methods screen', () => { + cy.wait(2000) + getIframeBody() + .contains('div', '4 digit cvc test card') + .should('exist') + .trigger('click') + cy.wait(1000) + + getIframeBody().find(`[data-testid=${testIds.cardCVVInputTestId}]`).type("1234").then(() => { + getIframeBody().find(`[data-testid=${testIds.cardCVVInputTestId}]`).should('have.value', '1234'); + }) + + }) + +}) + + + + diff --git a/cypress-tests/cypress/support/utils.ts b/cypress-tests/cypress/support/utils.ts index 08a516365..4d6ca4c02 100644 --- a/cypress-tests/cypress/support/utils.ts +++ b/cypress-tests/cypress/support/utils.ts @@ -116,3 +116,5 @@ export const confirmBody = { export const stripeTestCard = "4000000000003220"; export const adyenTestCard = "4917610000000000"; export const bluesnapTestCard = "4000000000001091"; +export const amexTestCard = "378282246310005" +export const visaTestCard = "4242424242424242"; diff --git a/src/CardUtils.res b/src/CardUtils.res index 02a4bd55f..9341d889d 100644 --- a/src/CardUtils.res +++ b/src/CardUtils.res @@ -671,3 +671,7 @@ let getEligibleCoBadgedCardSchemes = (~matchedCardSchemes, ~enabledCardSchemes) enabledCardSchemes->Array.includes(ele->String.toLowerCase) }) } + +let getCardBrandFromStates = (cardBrand, cardScheme, showFields) => { + !showFields ? cardScheme : cardBrand +} diff --git a/src/Payment.res b/src/Payment.res index 9aa7ba63b..f549921df 100644 --- a/src/Payment.res +++ b/src/Payment.res @@ -18,7 +18,6 @@ let make = (~paymentMode, ~integrateError, ~logger) => { let isManualRetryEnabled = Recoil.useRecoilValueFromAtom(isManualRetryEnabled) let paymentToken = Recoil.useRecoilValueFromAtom(paymentTokenAtom) let paymentMethodListValue = Recoil.useRecoilValueFromAtom(PaymentUtils.paymentMethodListValue) - let {iframeId} = keys let (cardNumber, setCardNumber) = React.useState(_ => "") @@ -56,6 +55,8 @@ let make = (~paymentMode, ~integrateError, ~logger) => { let (cardBrand, setCardBrand) = React.useState(_ => !showFields && isNotBancontact ? cardScheme : cardBrand ) + + let cardBrand = CardUtils.getCardBrandFromStates(cardBrand, cardScheme, showFields) let supportedCardBrands = React.useMemo(() => { paymentMethodListValue->PaymentUtils.getSupportedCardBrands }, [paymentMethodListValue]) From 627980d55a18a8ebe15ba65cc7cb2a1ccde068d0 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 25 Oct 2024 07:28:14 +0000 Subject: [PATCH 26/35] chore(release): 0.96.1 [skip ci] ## [0.96.1](https://github.com/juspay/hyperswitch-web/compare/v0.96.0...v0.96.1) (2024-10-25) ### Bug Fixes * card cvc bug fix ([#748](https://github.com/juspay/hyperswitch-web/issues/748)) ([6122d9d](https://github.com/juspay/hyperswitch-web/commit/6122d9d200b934969ee8643e598754d724a786a4)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e7bf7ee4..1519bc3d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [0.96.1](https://github.com/juspay/hyperswitch-web/compare/v0.96.0...v0.96.1) (2024-10-25) + + +### Bug Fixes + +* card cvc bug fix ([#748](https://github.com/juspay/hyperswitch-web/issues/748)) ([6122d9d](https://github.com/juspay/hyperswitch-web/commit/6122d9d200b934969ee8643e598754d724a786a4)) + # [0.96.0](https://github.com/juspay/hyperswitch-web/compare/v0.95.3...v0.96.0) (2024-10-23) diff --git a/package-lock.json b/package-lock.json index 7b8ec0ad0..b2ec9bb59 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.96.0", + "version": "0.96.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.96.0", + "version": "0.96.1", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index cd23cd0c7..4ceafaf2a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.96.0", + "version": "0.96.1", "main": "index.js", "private": true, "dependencies": { From 6059f13fa147d4087872576fe05852b939323f33 Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja Date: Mon, 28 Oct 2024 13:10:25 +0530 Subject: [PATCH 27/35] refactor: disable logging in integration environment (#753) --- package.json | 25 ++++++++++++------------- webpack.common.js | 4 ++-- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/package.json b/package.json index 4ceafaf2a..57ab68d49 100644 --- a/package.json +++ b/package.json @@ -16,23 +16,22 @@ "webpack-merge": "^5.9.0" }, "scripts": { - "build:dev": "cross-env sdkEnv=sandbox webpack --config webpack.dev.js", - "build:dev-integ": "cross-env sdkEnv=integ webpack --config webpack.dev.js", - "start": "cross-env sdkEnv=local webpack serve --config webpack.dev.js", - "build:prod": "cross-env sdkEnv=prod webpack --config webpack.common.js", "build": "webpack --config webpack.common.js", - "build:sandbox": "cross-env sdkEnv=sandbox webpack --config webpack.common.js", - "build:integ": "cross-env sdkEnv=integ webpack --config webpack.common.js", - "test": "cd cypress-tests && npm run cypress:run", + "build:integ": "cross-env sdkEnv=integ enableLogging=false webpack --config webpack.common.js", + "build:playground": "npm run setup:playground && npm run build", + "build:prod": "cross-env sdkEnv=prod enableLogging=true webpack --config webpack.common.js", + "build:sandbox": "cross-env sdkEnv=sandbox enableLogging=true webpack --config webpack.common.js", + "deploy-to-s3": "node ./scripts/pushToS3.js", + "postinstall": "cd Hyperswitch-React-Demo-App && npm i", + "prepare": "husky install", "re:build": "rescript", "re:clean": "rescript clean", - "re:start": "rescript -w", "re:format": "rescript format -all", - "start:playground": "npm run postinstall && cd Hyperswitch-React-Demo-App && node promptScript.js && npm run start", - "build:playground": "npm run postinstall && cd Hyperswitch-React-Demo-App && node promptScript.js && npm run build", - "prepare": "husky install", - "deploy-to-s3": "node ./scripts/pushToS3.js", - "postinstall": "cd Hyperswitch-React-Demo-App && npm i", + "re:start": "rescript -w", + "setup:playground": "npm run postinstall && cd Hyperswitch-React-Demo-App && node promptScript.js", + "start": "cross-env sdkEnv=local enableLogging=false webpack serve --config webpack.dev.js", + "start:playground": "npm run setup:playground && npm run start", + "test": "cd cypress-tests && npm run cypress:run", "test:hooks": "npx eslint src/" }, "eslintConfig": { diff --git a/webpack.common.js b/webpack.common.js index 981f2a979..4357ab075 100644 --- a/webpack.common.js +++ b/webpack.common.js @@ -14,6 +14,7 @@ const getEnvVariable = (variable, defaultValue) => process.env[variable] ?? defaultValue; const sdkEnv = getEnvVariable("sdkEnv", "local"); +const enableLogging = getEnvVariable("enableLogging", "false") === "true"; const envSdkUrl = getEnvVariable("ENV_SDK_URL", ""); const envBackendUrl = getEnvVariable("ENV_BACKEND_URL", ""); const envLoggingUrl = getEnvVariable("ENV_LOGGING_URL", ""); @@ -60,7 +61,6 @@ const confirmEndPoint = const logEndpoint = envLoggingUrl || `https://${logDomain}.hyperswitch.io/logs/sdk`; -const enableLogging = true; const loggingLevel = "DEBUG"; const maxLogsPushedPerEventName = 100; @@ -84,7 +84,7 @@ module.exports = (publicPath = "auto") => { logEndpoint: JSON.stringify(logEndpoint), sentryDSN: JSON.stringify(process.env.SENTRY_DSN), sentryScriptUrl: JSON.stringify(process.env.SENTRY_SCRIPT_URL), - enableLogging: JSON.stringify(enableLogging), + enableLogging: enableLogging, loggingLevel: JSON.stringify(loggingLevel), maxLogsPushedPerEventName: JSON.stringify(maxLogsPushedPerEventName), }), From bc4e296bae2e3d7c94bb4c47c0a779cd510aa6b0 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Mon, 28 Oct 2024 07:42:15 +0000 Subject: [PATCH 28/35] chore(release): 0.96.2 [skip ci] ## [0.96.2](https://github.com/juspay/hyperswitch-web/compare/v0.96.1...v0.96.2) (2024-10-28) --- CHANGELOG.md | 2 ++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1519bc3d9..c66c3a707 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +## [0.96.2](https://github.com/juspay/hyperswitch-web/compare/v0.96.1...v0.96.2) (2024-10-28) + ## [0.96.1](https://github.com/juspay/hyperswitch-web/compare/v0.96.0...v0.96.1) (2024-10-25) diff --git a/package-lock.json b/package-lock.json index b2ec9bb59..cfcead004 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.96.1", + "version": "0.96.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.96.1", + "version": "0.96.2", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index 57ab68d49..6615f765d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.96.1", + "version": "0.96.2", "main": "index.js", "private": true, "dependencies": { From 40ef7a5578b3a687c9b596a27818f4533758f136 Mon Sep 17 00:00:00 2001 From: aritro2002 Date: Tue, 29 Oct 2024 12:30:32 +0530 Subject: [PATCH 29/35] fix: remove blue border in firefox (#746) Co-authored-by: Pritish Budhiraja --- src/Index.res | 1 + src/index.css | 23 ++++++++--------------- 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/src/Index.res b/src/Index.res index 34fb585d3..52691270d 100644 --- a/src/Index.res +++ b/src/Index.res @@ -1,4 +1,5 @@ %%raw(`require("tailwindcss/tailwind.css")`) +%%raw("import './index.css'") Sentry.initiateSentry(~dsn=GlobalVars.sentryDSN) diff --git a/src/index.css b/src/index.css index 651ed53e7..a6f7ec31d 100644 --- a/src/index.css +++ b/src/index.css @@ -1,16 +1,9 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; -body { - margin: 0; - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', - 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', - sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -code { - font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', - monospace; +/* Remove focus outline in Firefox */ +@-moz-document url-prefix() { + *:focus, + *:focus-visible, + *:focus-within, + *:active { + outline: transparent !important; + } } From 7c1584b06bdcfc7ece35d11ab0f1249109852635 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 29 Oct 2024 07:02:19 +0000 Subject: [PATCH 30/35] chore(release): 0.96.3 [skip ci] ## [0.96.3](https://github.com/juspay/hyperswitch-web/compare/v0.96.2...v0.96.3) (2024-10-29) ### Bug Fixes * remove blue border in firefox ([#746](https://github.com/juspay/hyperswitch-web/issues/746)) ([40ef7a5](https://github.com/juspay/hyperswitch-web/commit/40ef7a5578b3a687c9b596a27818f4533758f136)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c66c3a707..6598502e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [0.96.3](https://github.com/juspay/hyperswitch-web/compare/v0.96.2...v0.96.3) (2024-10-29) + + +### Bug Fixes + +* remove blue border in firefox ([#746](https://github.com/juspay/hyperswitch-web/issues/746)) ([40ef7a5](https://github.com/juspay/hyperswitch-web/commit/40ef7a5578b3a687c9b596a27818f4533758f136)) + ## [0.96.2](https://github.com/juspay/hyperswitch-web/compare/v0.96.1...v0.96.2) (2024-10-28) ## [0.96.1](https://github.com/juspay/hyperswitch-web/compare/v0.96.0...v0.96.1) (2024-10-25) diff --git a/package-lock.json b/package-lock.json index cfcead004..fe440a524 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.96.2", + "version": "0.96.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.96.2", + "version": "0.96.3", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index 6615f765d..ae6bb03ba 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.96.2", + "version": "0.96.3", "main": "index.js", "private": true, "dependencies": { From 0039fbe65ec7ff958d637d00c58aed710fed5b1f Mon Sep 17 00:00:00 2001 From: Sagnik Mitra <83326850+ImSagnik007@users.noreply.github.com> Date: Tue, 29 Oct 2024 12:43:43 +0530 Subject: [PATCH 31/35] feat: tax calculation in google pay (#750) Co-authored-by: Pritish Budhiraja Co-authored-by: Shiva Nandan --- src/Components/SavedMethods.res | 1 + src/Payments/GPay.res | 1 + src/Types/GooglePayType.res | 2 + src/Utilities/GooglePayHelpers.res | 21 ++++- src/orca-loader/Elements.res | 123 +++++++++++++++++++++++------ 5 files changed, 120 insertions(+), 28 deletions(-) diff --git a/src/Components/SavedMethods.res b/src/Components/SavedMethods.res index ae2dbdf1f..2516e9ca5 100644 --- a/src/Components/SavedMethods.res +++ b/src/Components/SavedMethods.res @@ -141,6 +141,7 @@ let make = ( GooglePayHelpers.handleGooglePayClicked( ~sessionObj=optToken, ~componentName, + ~paymentMethodListValue, ~iframeId, ~readOnly, ) diff --git a/src/Payments/GPay.res b/src/Payments/GPay.res index d9e0c69d1..26ba4e176 100644 --- a/src/Payments/GPay.res +++ b/src/Payments/GPay.res @@ -127,6 +127,7 @@ let make = ( GooglePayHelpers.handleGooglePayClicked( ~sessionObj, ~componentName, + ~paymentMethodListValue, ~iframeId, ~readOnly=options.readOnly, ) diff --git a/src/Types/GooglePayType.res b/src/Types/GooglePayType.res index a2d99aaf6..acbbf276e 100644 --- a/src/Types/GooglePayType.res +++ b/src/Types/GooglePayType.res @@ -14,6 +14,7 @@ type paymentDataRequest = { mutable shippingAddressRequired: bool, mutable emailRequired: bool, mutable shippingAddressParameters: JSON.t, + mutable callbackIntents: array, } @val @scope("Object") external assign2: (JSON.t, JSON.t) => paymentDataRequest = "assign" type element = { @@ -180,6 +181,7 @@ let getPaymentDataFromSession = (~sessionObj, ~componentName) => { paymentDataRequest.shippingAddressRequired = gpayobj.shippingAddressRequired paymentDataRequest.shippingAddressParameters = gpayobj.shippingAddressParameters->transformKeys(CamelCase) + paymentDataRequest.callbackIntents = ["SHIPPING_ADDRESS"->JSON.Encode.string] } paymentDataRequest diff --git a/src/Utilities/GooglePayHelpers.res b/src/Utilities/GooglePayHelpers.res index 04b9c9ef6..a8007b69a 100644 --- a/src/Utilities/GooglePayHelpers.res +++ b/src/Utilities/GooglePayHelpers.res @@ -151,7 +151,13 @@ let useHandleGooglePayResponse = ( }, (paymentMethodTypes, stateJson, isManualRetryEnabled, requiredFieldsBody, isWallet)) } -let handleGooglePayClicked = (~sessionObj, ~componentName, ~iframeId, ~readOnly) => { +let handleGooglePayClicked = ( + ~sessionObj, + ~componentName, + ~iframeId, + ~readOnly, + ~paymentMethodListValue: PaymentMethodsRecord.paymentMethodList, +) => { let paymentDataRequest = GooglePayType.getPaymentDataFromSession(~sessionObj, ~componentName) messageParentWindow([ ("fullscreen", true->JSON.Encode.bool), @@ -162,6 +168,10 @@ let handleGooglePayClicked = (~sessionObj, ~componentName, ~iframeId, ~readOnly) messageParentWindow([ ("GpayClicked", true->JSON.Encode.bool), ("GpayPaymentDataRequest", paymentDataRequest->Identity.anyTypeToJson), + ( + "IsTaxCalculationEnabled", + paymentMethodListValue.is_tax_calculation_enabled->JSON.Encode.bool, + ), ]) } } @@ -169,6 +179,7 @@ let handleGooglePayClicked = (~sessionObj, ~componentName, ~iframeId, ~readOnly) let useSubmitCallback = (~isWallet, ~sessionObj, ~componentName) => { let areRequiredFieldsValid = Recoil.useRecoilValueFromAtom(RecoilAtoms.areRequiredFieldsValid) let areRequiredFieldsEmpty = Recoil.useRecoilValueFromAtom(RecoilAtoms.areRequiredFieldsEmpty) + let paymentMethodListValue = Recoil.useRecoilValueFromAtom(PaymentUtils.paymentMethodListValue) let options = Recoil.useRecoilValueFromAtom(RecoilAtoms.optionAtom) let {localeString} = Recoil.useRecoilValueFromAtom(RecoilAtoms.configAtom) let {iframeId} = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys) @@ -178,7 +189,13 @@ let useSubmitCallback = (~isWallet, ~sessionObj, ~componentName) => { let json = ev.data->safeParse let confirm = json->getDictFromJson->ConfirmType.itemToObjMapper if confirm.doSubmit && areRequiredFieldsValid && !areRequiredFieldsEmpty { - handleGooglePayClicked(~sessionObj, ~componentName, ~iframeId, ~readOnly=options.readOnly) + handleGooglePayClicked( + ~sessionObj, + ~componentName, + ~paymentMethodListValue, + ~iframeId, + ~readOnly=options.readOnly, + ) } else if areRequiredFieldsEmpty { postFailedSubmitResponse( ~errortype="validation_error", diff --git a/src/orca-loader/Elements.res b/src/orca-loader/Elements.res index a664a8750..d6aa0b596 100644 --- a/src/orca-loader/Elements.res +++ b/src/orca-loader/Elements.res @@ -915,35 +915,106 @@ let make = ( ) try { - let gPayClient = GooglePayType.google( - { - "environment": publishableKey->String.startsWith("pk_prd_") - ? "PRODUCTION" - : "TEST", - }->Identity.anyTypeToJson, - ) - - gPayClient.isReadyToPay(payRequest) - ->then(res => { - let dict = res->getDictFromJson - let isReadyToPay = getBool(dict, "result", false) - let msg = [("isReadyToPay", isReadyToPay->JSON.Encode.bool)]->Dict.fromArray - mountedIframeRef->Window.iframePostMessage(msg) - resolve() - }) - ->catch(err => { - logger.setLogInfo( - ~value=err->Identity.anyTypeToJson->JSON.stringify, - ~eventName=GOOGLE_PAY_FLOW, - ~paymentMethod="GOOGLE_PAY", - ~logType=DEBUG, - ) - resolve() - }) - ->ignore + let transactionInfo = gpayobj.transaction_info->getDictFromJson let handleGooglePayMessages = (event: Types.event) => { let evJson = event.data->anyTypeToJson + let isTaxCalculationEnabled = + evJson + ->getOptionalJsonFromJson("IsTaxCalculationEnabled") + ->Option.flatMap(JSON.Decode.bool) + ->Option.getOr(false) + + let onPaymentDataChanged = intermediatePaymentData => { + let shippingAddress = + intermediatePaymentData + ->getDictFromJson + ->getDictFromDict("shippingAddress") + ->billingContactItemToObjMapper + let newShippingAddress = + [ + ("state", shippingAddress.administrativeArea->JSON.Encode.string), + ("country", shippingAddress.countryCode->JSON.Encode.string), + ("zip", shippingAddress.postalCode->JSON.Encode.string), + ]->getJsonFromArrayOfJson + + let paymentMethodType = "google_pay"->JSON.Encode.string + + if isTaxCalculationEnabled { + TaxCalculation.calculateTax( + ~shippingAddress=[ + ("address", newShippingAddress), + ]->getJsonFromArrayOfJson, + ~logger, + ~publishableKey, + ~clientSecret, + ~paymentMethodType, + )->then(resp => { + switch resp->TaxCalculation.taxResponseToObjMapper { + | Some(taxCalculationResponse) => { + let updatePaymentRequest = + [ + ( + "newTransactionInfo", + [ + ( + "countryCode", + shippingAddress.countryCode->JSON.Encode.string, + ), + ( + "currencyCode", + transactionInfo + ->getString("currency_code", "") + ->JSON.Encode.string, + ), + ("totalPriceStatus", "FINAL"->JSON.Encode.string), + ( + "totalPrice", + taxCalculationResponse.net_amount + ->minorUnitToString + ->JSON.Encode.string, + ), + ]->getJsonFromArrayOfJson, + ), + ]->getJsonFromArrayOfJson + updatePaymentRequest->resolve + } + | None => JSON.Encode.null->resolve + } + }) + } else { + JSON.Encode.null->resolve + } + } + let gPayClient = GooglePayType.google( + { + "environment": publishableKey->String.startsWith("pk_prd_") + ? "PRODUCTION" + : "TEST", + "paymentDataCallbacks": { + "onPaymentDataChanged": onPaymentDataChanged, + }, + }->Identity.anyTypeToJson, + ) + + gPayClient.isReadyToPay(payRequest) + ->then(res => { + let dict = res->getDictFromJson + let isReadyToPay = getBool(dict, "result", false) + let msg = [("isReadyToPay", isReadyToPay->JSON.Encode.bool)]->Dict.fromArray + mountedIframeRef->Window.iframePostMessage(msg) + resolve() + }) + ->catch(err => { + logger.setLogInfo( + ~value=err->Identity.anyTypeToJson->JSON.stringify, + ~eventName=GOOGLE_PAY_FLOW, + ~paymentMethod="GOOGLE_PAY", + ~logType=DEBUG, + ) + resolve() + }) + ->ignore let gpayClicked = evJson ->getOptionalJsonFromJson("GpayClicked") From dd789930210966e0828a40c5b0f745a7dbfa1049 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 29 Oct 2024 07:15:44 +0000 Subject: [PATCH 32/35] chore(release): 0.97.0 [skip ci] # [0.97.0](https://github.com/juspay/hyperswitch-web/compare/v0.96.3...v0.97.0) (2024-10-29) ### Features * tax calculation in google pay ([#750](https://github.com/juspay/hyperswitch-web/issues/750)) ([0039fbe](https://github.com/juspay/hyperswitch-web/commit/0039fbe65ec7ff958d637d00c58aed710fed5b1f)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6598502e7..962929a15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# [0.97.0](https://github.com/juspay/hyperswitch-web/compare/v0.96.3...v0.97.0) (2024-10-29) + + +### Features + +* tax calculation in google pay ([#750](https://github.com/juspay/hyperswitch-web/issues/750)) ([0039fbe](https://github.com/juspay/hyperswitch-web/commit/0039fbe65ec7ff958d637d00c58aed710fed5b1f)) + ## [0.96.3](https://github.com/juspay/hyperswitch-web/compare/v0.96.2...v0.96.3) (2024-10-29) diff --git a/package-lock.json b/package-lock.json index fe440a524..ff68b0145 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "orca-payment-page", - "version": "0.96.3", + "version": "0.97.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "orca-payment-page", - "version": "0.96.3", + "version": "0.97.0", "hasInstallScript": true, "dependencies": { "@glennsl/rescript-fetch": "^0.2.0", diff --git a/package.json b/package.json index ae6bb03ba..b65050649 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.96.3", + "version": "0.97.0", "main": "index.js", "private": true, "dependencies": { From 63f536ef22dc0304b01d703a232ce99819743608 Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja Date: Tue, 29 Oct 2024 13:58:14 +0530 Subject: [PATCH 33/35] feat: added dynamic fields for SEPA (#624) --- src/App.res | 32 ++ src/CardTheme.res | 4 +- src/CardUtils.res | 2 +- src/Components/AddBankAccount.res | 7 +- src/Components/DynamicFields.res | 37 +++ src/Components/PayNowButton.res | 17 +- src/LoaderController.res | 10 +- src/LocaleStrings/ArabicLocale.res | 1 + src/LocaleStrings/CatalanLocale.res | 1 + src/LocaleStrings/ChineseLocale.res | 1 + src/LocaleStrings/DeutschLocale.res | 1 + src/LocaleStrings/DutchLocale.res | 1 + src/LocaleStrings/EnglishGBLocale.res | 1 + src/LocaleStrings/EnglishLocale.res | 1 + src/LocaleStrings/FrenchBelgiumLocale.res | 1 + src/LocaleStrings/FrenchLocale.res | 1 + src/LocaleStrings/HebrewLocale.res | 1 + src/LocaleStrings/ItalianLocale.res | 1 + src/LocaleStrings/JapaneseLocale.res | 1 + src/LocaleStrings/LocaleStringTypes.res | 1 + src/LocaleStrings/PolishLocale.res | 1 + src/LocaleStrings/PortugueseLocale.res | 1 + src/LocaleStrings/RussianLocale.res | 1 + src/LocaleStrings/SpanishLocale.res | 1 + src/LocaleStrings/SwedishLocale.res | 1 + src/Payments/ACHBankDebit.res | 2 +- src/Payments/BankDebitModal.res | 344 ++++++++++++---------- src/Payments/BecsBankDebit.res | 2 +- src/Payments/PaymentMethodsRecord.res | 5 + src/Payments/PaymentMethodsWrapper.res | 9 +- src/Payments/SepaBankDebit.res | 93 +++--- src/Types/ACHTypes.res | 1 + src/Utilities/DynamicFieldsUtils.res | 74 +++-- src/Utilities/PaymentBody.res | 45 +-- src/Utilities/RecoilAtoms.res | 1 + src/Utilities/Utils.res | 2 + src/orca-loader/LoaderPaymentElement.res | 4 + 37 files changed, 415 insertions(+), 294 deletions(-) diff --git a/src/App.res b/src/App.res index 020d9cd9a..eec095614 100644 --- a/src/App.res +++ b/src/App.res @@ -16,6 +16,38 @@ let make = () => { None }, [logger]) + React.useEffect0(() => { + let handleMetaDataPostMessage = (ev: Window.event) => { + let json = ev.data->Utils.safeParse + let dict = json->Utils.getDictFromJson + + if dict->Dict.get("metadata")->Option.isSome { + let metadata = dict->Utils.getJsonObjectFromDict("metadata") + let config = metadata->Utils.getDictFromJson->Dict.get("config") + + switch config { + | Some(config) => { + let config = CardTheme.itemToObjMapper( + config->Utils.getDictFromJson, + DefaultTheme.default, + DefaultTheme.defaultRules, + logger, + ) + + CardUtils.generateFontsLink(config.fonts) + let dict = config.appearance.rules->Utils.getDictFromJson + if dict->Dict.toArray->Array.length > 0 { + Utils.generateStyleSheet("", dict, "mystyle") + } + } + | None => () + } + } + } + Window.addEventListener("message", handleMetaDataPostMessage) + Some(() => Window.removeEventListener("message", handleMetaDataPostMessage)) + }) + let renderFullscreen = switch paymentMode { | "paymentMethodCollect" => diff --git a/src/CardTheme.res b/src/CardTheme.res index 28aa2a226..c5cd8eb1d 100644 --- a/src/CardTheme.res +++ b/src/CardTheme.res @@ -3,7 +3,7 @@ open Utils open ErrorUtils let getTheme = (val, logger) => { - switch val { + switch val->String.toLowerCase { | "default" => Default | "brutal" => Brutal | "midnight" => Midnight @@ -360,7 +360,7 @@ let getAppearance = ( variables: getVariables("variables", json, default, logger), rules: mergeJsons(rulesJson, getJsonObjectFromDict(json, "rules")), innerLayout: getWarningString(json, "innerLayout", "spaced", ~logger)->getInnerLayout, - labels: switch getWarningString(json, "labels", "above", ~logger) { + labels: switch getWarningString(json, "labels", "above", ~logger)->String.toLowerCase { | "above" => Above | "floating" => Floating | "none" => Never diff --git a/src/CardUtils.res b/src/CardUtils.res index 9341d889d..e917851b9 100644 --- a/src/CardUtils.res +++ b/src/CardUtils.res @@ -424,7 +424,7 @@ let cvcNumberInRange = (val, cardBrand) => { }) cvcLengthInRange } -let genreateFontsLink = (fonts: array) => { +let generateFontsLink = (fonts: array) => { if fonts->Array.length > 0 { fonts ->Array.map(item => diff --git a/src/Components/AddBankAccount.res b/src/Components/AddBankAccount.res index b89e379a2..d49f5787e 100644 --- a/src/Components/AddBankAccount.res +++ b/src/Components/AddBankAccount.res @@ -6,7 +6,7 @@ module ToolTip = { let {themeObj} = Recoil.useRecoilValueFromAtom(configAtom)
diff --git a/src/Payments/BankDebitModal.res b/src/Payments/BankDebitModal.res index 2476e3f40..86e9a6d88 100644 --- a/src/Payments/BankDebitModal.res +++ b/src/Payments/BankDebitModal.res @@ -106,7 +106,7 @@ module AccountNumberCard = { let clearSpaces = str => str->String.replaceRegExp(%re("/\D+/g"), "") @react.component -let make = (~setModalData) => { +let make = (~setModalData, ~paymentType: CardThemeType.mode) => { let selectedOption = Recoil.useRecoilValueFromAtom(RecoilAtoms.selectedOptionAtom) let (routingNumber, setRoutingNumber) = React.useState(_ => "") let (iban, setIban) = React.useState(_ => "") @@ -116,6 +116,8 @@ let make = (~setModalData) => { let {themeObj, config, localeString} = Recoil.useRecoilValueFromAtom(RecoilAtoms.configAtom) let (accountType, setAccountType) = React.useState(() => "Savings") + let (requiredFieldsBody, setRequiredFieldsBody) = React.useState(_ => Dict.make()) + let (openModal, setOpenModal) = React.useState(_ => false) let (accountNum, setAccountNum) = React.useState(_ => "") @@ -183,25 +185,66 @@ let make = (~setModalData) => { iban !== "" || (accountNum->String.length > 0 && sortCode->String.length > 0) - -
-
-
- {React.string(localeString.billingDetailsText)} -
-
- -
-
- {React.string("Bank Details")} -
+ let onClickHandler = () => { + setModalData(_ => Some({ + routingNumber, + accountNumber: accountNum, + accountHolderName, + accountType: accountType->String.toLowerCase, + iban, + sortCode, + requiredFieldsBody, + })) + Modal.close(setOpenModal) + } + + let dynamicFieldsModalBody = + <> + + + + + let nonDynamicFieldsModalBody = + <> +
+ {React.string(localeString.billingDetailsText)} +
+
+ +
+
+ {React.string("Bank Details")} +
+
+ {React.string("Account Holder Name")} +
+ setInputFocus(_ => NONE)} + /> +
{ color: themeObj.colorText, marginBottom: "5px", }> - {React.string("Account Holder Name")} + {React.string("IBAN")}
setInputFocus(_ => NONE)} + value=iban + onChange=changeIBAN + type_="text" + maxLength=42 + inputRef=ibanRef + placeholder="eg: DE00 0000 0000 0000 0000 00" /> - -
- {React.string("IBAN")} + +
+ +
+
+ {React.string("Routing number")} +
+ setInputFocus(_ => Routing)} + />
-
-
- -
-
- {React.string("Routing number")} -
- setInputFocus(_ => Routing)} - /> + +
+
+ {React.string("Account number")}
- - -
-
- {React.string("Account number")} -
- setInputFocus(_ => Account)} - onBlur={_ => setInputFocus(_ => NONE)} - /> -
-
-
- -
- setInputFocus(_ => Account)} + onBlur={_ => setInputFocus(_ => NONE)} />
- -
- {React.string("BSB")} -
- + +
+ - -
+
+ +
+ {React.string("BSB")} +
+ +
+