From 092a1ee226508bd112987cb3aeb202bcdd92648e Mon Sep 17 00:00:00 2001 From: Arun Mishra <68141066+arun-mi@users.noreply.github.com> Date: Mon, 13 Nov 2023 21:27:34 +0530 Subject: [PATCH] Revert to older flow (#22) Co-authored-by: arun.mishra --- src/Payments/ApplePay.res | 15 +- src/Payments/PreMountLoader.res | 150 +++--- src/Payments/QRCodeDisplay.res | 8 +- src/Utilities/PaymentHelpers.res | 112 ++-- src/orca-loader/Elements.res | 895 ++++++++++++++----------------- 5 files changed, 527 insertions(+), 653 deletions(-) diff --git a/src/Payments/ApplePay.res b/src/Payments/ApplePay.res index e75cb6cae..cc47a215c 100644 --- a/src/Payments/ApplePay.res +++ b/src/Payments/ApplePay.res @@ -1,8 +1,9 @@ type props = {sessionObj: option, list: PaymentMethodsRecord.list} let default = (props: props) => { - let {publishableKey} = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys) + let loggerState = Recoil.useRecoilValueFromAtom(RecoilAtoms.loggerAtom) let setIsShowOrPayUsing = Recoil.useSetRecoilState(RecoilAtoms.isShowOrPayUsing) + let {publishableKey} = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys) let (showApplePay, setShowApplePay) = React.useState(() => false) let (showApplePayLoader, setShowApplePayLoader) = React.useState(() => false) let intent = PaymentHelpers.usePaymentIntent(None, Applepay) @@ -195,6 +196,12 @@ let default = (props: props) => { }` let onApplePayButtonClicked = () => { + loggerState.setLogInfo( + ~value="Apple Pay Button Clicked", + ~eventName=APPLE_PAY_FLOW, + ~paymentMethod="APPLE_PAY", + (), + ) setApplePayClicked(_ => true) if isInvokeSDKFlow { @@ -220,6 +227,12 @@ let default = (props: props) => { let bodyDict = PaymentBody.applePayRedirectBody(~connectors) processPayment(bodyDict) } + loggerState.setLogInfo( + ~value="", + ~eventName=PAYMENT_DATA_FILLED, + ~paymentMethod="APPLE_PAY", + (), + ) } React.useEffect0(() => { diff --git a/src/Payments/PreMountLoader.res b/src/Payments/PreMountLoader.res index de4c0328a..c93f38d4a 100644 --- a/src/Payments/PreMountLoader.res +++ b/src/Payments/PreMountLoader.res @@ -1,83 +1,83 @@ @react.component let make = (~sessionId, ~publishableKey, ~clientSecret, ~endpoint) => { - open Utils - let logger = OrcaLogger.make( - ~sessionId, - ~source=Loader, - ~merchantId=publishableKey, - ~clientSecret, - (), - ) + // open Utils + // let logger = OrcaLogger.make( + // ~sessionId, + // ~source=Loader, + // ~merchantId=publishableKey, + // ~clientSecret, + // (), + // ) - let ( - paymentMethodsResponse, - customerPaymentMethodsResponse, - sessionTokensResponse, - ) = React.useMemo0(() => { - ( - PaymentHelpers.usePaymentMethodList( - ~clientSecret, - ~publishableKey, - ~logger, - ~switchToCustomPod=false, - ~endpoint, - ), - PaymentHelpers.useCustomerDetails( - ~clientSecret, - ~publishableKey, - ~optLogger=Some(logger), - ~switchToCustomPod=false, - ~endpoint, - ), - PaymentHelpers.useSessions( - ~clientSecret, - ~publishableKey, - ~optLogger=Some(logger), - ~switchToCustomPod=false, - ~endpoint, - (), - ), - ) - }) + // // let ( + // // paymentMethodsResponse, + // // customerPaymentMethodsResponse, + // // sessionTokensResponse, + // // ) = React.useMemo0(() => { + // // ( + // // PaymentHelpers.usePaymentMethodList( + // // ~clientSecret, + // // ~publishableKey, + // // ~logger, + // // ~switchToCustomPod=false, + // // ~endpoint, + // // ), + // // PaymentHelpers.useCustomerDetails( + // // ~clientSecret, + // // ~publishableKey, + // // ~optLogger=Some(logger), + // // ~switchToCustomPod=false, + // // ~endpoint, + // // ), + // // PaymentHelpers.useSessions( + // // ~clientSecret, + // // ~publishableKey, + // // ~optLogger=Some(logger), + // // ~switchToCustomPod=false, + // // ~endpoint, + // // (), + // // ), + // // ) + // // }) - let sendPromiseData = (promise, key) => { - open Promise - promise - ->then(res => { - handlePostMessage([("response", res), ("data", key->Js.Json.string)]) - resolve() - }) - ->catch(_err => { - handlePostMessage([("response", Js.Json.null), ("data", key->Js.Json.string)]) - resolve() - }) - ->ignore - } + // // let sendPromiseData = (promise, key) => { + // // open Promise + // // promise + // // ->then(res => { + // // handlePostMessage([("response", res), ("data", key->Js.Json.string)]) + // // resolve() + // // }) + // // ->catch(_err => { + // // handlePostMessage([("response", Js.Json.null), ("data", key->Js.Json.string)]) + // // resolve() + // // }) + // // ->ignore + // // } - React.useEffect0(() => { - let handle = (ev: Window.event) => { - let json = try { - ev.data->Js.Json.parseExn - } catch { - | _ => Js.Json.null - } - let dict = json->Utils.getDictFromJson - if dict->Js.Dict.get("sendPaymentMethodsResponse")->Belt.Option.isSome { - paymentMethodsResponse->sendPromiseData("payment_methods") - } else if dict->Js.Dict.get("sendCustomerPaymentMethodsResponse")->Belt.Option.isSome { - customerPaymentMethodsResponse->sendPromiseData("customer_payment_methods") - } else if dict->Js.Dict.get("sendSessionTokensResponse")->Belt.Option.isSome { - sessionTokensResponse->sendPromiseData("session_tokens") - } - } - Window.addEventListener("message", handle) - handlePostMessage([("preMountLoaderInitCallback", true->Js.Json.boolean)]) - Some( - () => { - Window.removeEventListener("message", handle) - }, - ) - }) + // // React.useEffect0(() => { + // // let handle = (ev: Window.event) => { + // // let json = try { + // // ev.data->Js.Json.parseExn + // // } catch { + // // | _ => Js.Json.null + // // } + // // let dict = json->Utils.getDictFromJson + // // if dict->Js.Dict.get("sendPaymentMethodsResponse")->Belt.Option.isSome { + // // paymentMethodsResponse->sendPromiseData("payment_methods") + // // } else if dict->Js.Dict.get("sendCustomerPaymentMethodsResponse")->Belt.Option.isSome { + // // customerPaymentMethodsResponse->sendPromiseData("customer_payment_methods") + // // } else if dict->Js.Dict.get("sendSessionTokensResponse")->Belt.Option.isSome { + // // sessionTokensResponse->sendPromiseData("session_tokens") + // // } + // // } + // // Window.addEventListener("message", handle) + // // handlePostMessage([("preMountLoaderInitCallback", true->Js.Json.boolean)]) + // // Some( + // // () => { + // // Window.removeEventListener("message", handle) + // // }, + // // ) + // // }) React.null } diff --git a/src/Payments/QRCodeDisplay.res b/src/Payments/QRCodeDisplay.res index 73aa916e3..6cd83e990 100644 --- a/src/Payments/QRCodeDisplay.res +++ b/src/Payments/QRCodeDisplay.res @@ -51,7 +51,6 @@ let make = () => { paymentIntentId, headers->Js.Dict.entries, ~optLogger=Some(logger), - ~switchToCustomPod, ) ->then(res => { Modal.close(setOpenModal) @@ -80,12 +79,7 @@ let make = () => { let closeModal = () => { open Promise - PaymentHelpers.retrievePaymentIntent( - clientSecret, - headers, - ~optLogger=Some(logger), - ~switchToCustomPod, - ) + PaymentHelpers.retrievePaymentIntent(clientSecret, headers, ~optLogger=Some(logger)) ->then(json => { let dict = json->Js.Json.decodeObject->Belt.Option.getWithDefault(Js.Dict.empty()) let status = dict->getString("status", "") diff --git a/src/Utilities/PaymentHelpers.res b/src/Utilities/PaymentHelpers.res index a4100a505..e5ba00964 100644 --- a/src/Utilities/PaymentHelpers.res +++ b/src/Utilities/PaymentHelpers.res @@ -7,12 +7,13 @@ type url = {searchParams: searchParams, href: string} @new external urlSearch: string => url = "URL" open LoggerUtils +open ApiEndpoint type payment = Card | BankTransfer | BankDebits | KlarnaRedirect | Gpay | Applepay | Paypal | Other let closePaymentLoaderIfAny = () => Utils.handlePostMessage([("fullscreen", false->Js.Json.boolean)]) -let retrievePaymentIntent = (clientSecret, headers, ~optLogger, ~switchToCustomPod) => { +let retrievePaymentIntent = (clientSecret, headers, ~optLogger) => { open Promise let paymentIntentID = Js.String2.split(clientSecret, "_secret_")[0] let endpoint = ApiEndpoint.getApiEndPoint() @@ -27,12 +28,7 @@ let retrievePaymentIntent = (clientSecret, headers, ~optLogger, ~switchToCustomP ~logCategory=API, (), ) - fetchApi( - uri, - ~method_=Fetch.Get, - ~headers=headers->ApiEndpoint.addCustomPodHeader(~switchToCustomPod, ()), - (), - ) + fetchApi(uri, ~method_=Fetch.Get, ~headers=headers->ApiEndpoint.addCustomPodHeader(), ()) ->then(res => { let statusCode = res->Fetch.Response.status->string_of_int if statusCode->Js.String2.charAt(0) !== "2" { @@ -72,9 +68,9 @@ let retrievePaymentIntent = (clientSecret, headers, ~optLogger, ~switchToCustomP }) } -let rec pollRetrievePaymentIntent = (clientSecret, headers, ~optLogger, ~switchToCustomPod) => { +let rec pollRetrievePaymentIntent = (clientSecret, headers, ~optLogger) => { open Promise - retrievePaymentIntent(clientSecret, headers, ~optLogger, ~switchToCustomPod) + retrievePaymentIntent(clientSecret, headers, ~optLogger) ->then(json => { let dict = json->Js.Json.decodeObject->Belt.Option.getWithDefault(Js.Dict.empty()) let status = dict->getString("status", "") @@ -83,13 +79,13 @@ let rec pollRetrievePaymentIntent = (clientSecret, headers, ~optLogger, ~switchT resolve(json) } else { delay(2000)->then(_val => { - pollRetrievePaymentIntent(clientSecret, headers, ~optLogger, ~switchToCustomPod) + pollRetrievePaymentIntent(clientSecret, headers, ~optLogger) }) } }) ->catch(e => { Js.log2("Unable to retrieve payment due to following error", e) - pollRetrievePaymentIntent(clientSecret, headers, ~optLogger, ~switchToCustomPod) + pollRetrievePaymentIntent(clientSecret, headers, ~optLogger) }) } @@ -112,7 +108,6 @@ let intentCall = ( ~iframeId, ~fetchMethod, ~setIsManualRetryEnabled, - ~switchToCustomPod, ) => { open Promise let isConfirm = uri->Js.String2.includes("/confirm") @@ -131,7 +126,7 @@ let intentCall = ( fetchApi( uri, ~method_=fetchMethod, - ~headers=headers->ApiEndpoint.addCustomPodHeader(~switchToCustomPod, ()), + ~headers=headers->ApiEndpoint.addCustomPodHeader(), ~bodyStr, (), ) @@ -302,15 +297,6 @@ let intentCall = ( ~message="Payment failed. Try again!", ) if uri->Js.String2.includes("force_sync=true") { - handleLogging( - ~optLogger, - ~value=intent.nextAction.type_, - ~internalMetadata=intent.nextAction.type_, - ~eventName=REDIRECTING_USER, - ~paymentMethod, - ~logType=ERROR, - (), - ) openUrl(url.href) } } @@ -402,7 +388,6 @@ let intentCall = ( let usePaymentSync = (optLogger: option, paymentType: payment) => { let list = Recoil.useRecoilValueFromAtom(RecoilAtoms.list) let keys = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys) - let switchToCustomPod = Recoil.useRecoilValueFromAtom(RecoilAtoms.switchToCustomPod) let setIsManualRetryEnabled = Recoil.useSetRecoilState(RecoilAtoms.isManualRetryEnabled) (~handleUserError=false, ~confirmParam: ConfirmType.confirmParams, ~iframeId="", ()) => { switch keys.clientSecret { @@ -426,7 +411,6 @@ let usePaymentSync = (optLogger: option, paymentType: pay ~iframeId, ~fetchMethod=Fetch.Get, ~setIsManualRetryEnabled, - ~switchToCustomPod, ) } switch list { @@ -469,8 +453,6 @@ let rec maskPayload = payloadDict => { } let usePaymentIntent = (optLogger: option, paymentType: payment) => { - let blockConfirm = Recoil.useRecoilValueFromAtom(RecoilAtoms.isConfirmBlocked) - let switchToCustomPod = Recoil.useRecoilValueFromAtom(RecoilAtoms.switchToCustomPod) let list = Recoil.useRecoilValueFromAtom(RecoilAtoms.list) let keys = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys) let (isManualRetryEnabled, setIsManualRetryEnabled) = Recoil.useRecoilState( @@ -516,6 +498,15 @@ let usePaymentIntent = (optLogger: option, paymentType: p ~paymentMethod="CARD", (), ) + | Applepay => + handleLogging( + ~optLogger, + ~value="", + ~internalMetadata=loggerPayload, + ~eventName=PAYMENT_ATTEMPT, + ~paymentMethod="APPLE_PAY", + (), + ) | _ => let _ = bodyArr->Js.Array2.map(((str, json)) => { if str === "payment_method_type" { @@ -531,27 +522,23 @@ let usePaymentIntent = (optLogger: option, paymentType: p () }) } - if blockConfirm && Window.isInteg { - Js.log3("CONFIRM IS BLOCKED", body->Js.Json.parseExn, headers) - } else { - intentCall( - ~fetchApi, - ~uri, - ~headers, - ~bodyStr=body, - ~confirmParam: ConfirmType.confirmParams, - ~clientSecret, - ~optLogger, - ~handleUserError, - ~paymentType, - ~iframeId, - ~fetchMethod, - ~setIsManualRetryEnabled, - ~switchToCustomPod, - ) - } + intentCall( + ~fetchApi, + ~uri, + ~headers, + ~bodyStr=body, + ~confirmParam: ConfirmType.confirmParams, + ~clientSecret, + ~optLogger, + ~handleUserError, + ~paymentType, + ~iframeId, + ~fetchMethod, + ~setIsManualRetryEnabled, + ) } + // open Promise let broswerInfo = BrowserSpec.broswerInfo let intentWithoutMandate = () => { let bodyStr = @@ -607,11 +594,10 @@ let usePaymentIntent = (optLogger: option, paymentType: p let useSessions = ( ~clientSecret, ~publishableKey, + ~endpoint, ~wallets=[], ~isDelayedSessionToken=false, ~optLogger, - ~switchToCustomPod, - ~endpoint, (), ) => { open Promise @@ -641,7 +627,7 @@ let useSessions = ( uri, ~method_=Fetch.Post, ~bodyStr=body->Js.Json.stringify, - ~headers=headers->ApiEndpoint.addCustomPodHeader(~switchToCustomPod, ()), + ~headers=headers->addCustomPodHeader(), (), ) ->then(resp => { @@ -693,13 +679,7 @@ let useSessions = ( }) } -let usePaymentMethodList = ( - ~clientSecret, - ~publishableKey, - ~logger, - ~switchToCustomPod, - ~endpoint, -) => { +let usePaymentMethodList = (~clientSecret, ~publishableKey, ~endpoint, ~logger) => { open Promise let headers = [("Content-Type", "application/json"), ("api-key", publishableKey)] let uri = `${endpoint}/account/payment_methods?client_secret=${clientSecret}` @@ -712,12 +692,7 @@ let usePaymentMethodList = ( ~logCategory=API, (), ) - fetchApi( - uri, - ~method_=Fetch.Get, - ~headers=headers->ApiEndpoint.addCustomPodHeader(~switchToCustomPod, ()), - (), - ) + fetchApi(uri, ~method_=Fetch.Get, ~headers=headers->addCustomPodHeader(), ()) ->then(resp => { let statusCode = resp->Fetch.Response.status->string_of_int if statusCode->Js.String2.charAt(0) !== "2" { @@ -767,13 +742,7 @@ let usePaymentMethodList = ( }) } -let useCustomerDetails = ( - ~clientSecret, - ~publishableKey, - ~endpoint, - ~optLogger, - ~switchToCustomPod, -) => { +let useCustomerDetails = (~clientSecret, ~publishableKey, ~endpoint, ~optLogger) => { open Promise let headers = [("Content-Type", "application/json"), ("api-key", publishableKey)] let uri = `${endpoint}/customers/payment_methods?client_secret=${clientSecret}` @@ -786,12 +755,7 @@ let useCustomerDetails = ( ~logCategory=API, (), ) - fetchApi( - uri, - ~method_=Fetch.Get, - ~headers=headers->ApiEndpoint.addCustomPodHeader(~switchToCustomPod, ()), - (), - ) + fetchApi(uri, ~method_=Fetch.Get, ~headers=headers->ApiEndpoint.addCustomPodHeader(), ()) ->then(res => { let statusCode = res->Fetch.Response.status->string_of_int if statusCode->Js.String2.charAt(0) !== "2" { diff --git a/src/orca-loader/Elements.res b/src/orca-loader/Elements.res index 34d183cb8..08d803f41 100644 --- a/src/orca-loader/Elements.res +++ b/src/orca-loader/Elements.res @@ -30,7 +30,9 @@ let make = ( let logger = logger->Belt.Option.getWithDefault(OrcaLogger.defaultLoggerConfig) let savedPaymentElement = Js.Dict.empty() let localOptions = options->Js.Json.decodeObject->Belt.Option.getWithDefault(Js.Dict.empty()) - let clientSecret = localOptions->getRequiredString("clientSecret", "", ~logger) + let clientSecretId = localOptions->getRequiredString("clientSecret", "", ~logger) + let testMode = publishableKey->Js.String2.startsWith("pk_snd_") + let endpoint = testMode ? "https://sandbox.hyperswitch.io" : "https://api.hyperswitch.io" let appearance = localOptions ->Js.Dict.get("appearance") @@ -43,162 +45,92 @@ let make = ( ->Belt.Option.getWithDefault([]) ->Js.Json.array - let blockConfirm = GlobalVars.isInteg - ? options - ->Js.Json.decodeObject - ->Belt.Option.flatMap(x => x->Js.Dict.get("orcaBlockConfirmABP")) - ->Belt.Option.flatMap(Js.Json.decodeBoolean) - ->Belt.Option.getWithDefault(false) - : false - let switchToCustomPod = GlobalVars.isInteg - ? options - ->Js.Json.decodeObject - ->Belt.Option.flatMap(x => x->Js.Dict.get("switchToCustomPodABP")) - ->Belt.Option.flatMap(Js.Json.decodeBoolean) - ->Belt.Option.getWithDefault(false) - : false - let endpoint = ApiEndpoint.getApiEndPoint(~publishableKey, ())->Js.Global.encodeURIComponent - - let localSelectorString = "hyper-preMountLoader-iframe" - let mountPreMountLoaderIframe = () => { - let elemAlreadyExists = Window.querySelector( - `#orca-payment-element-iframeRef-${localSelectorString}-parent`, - ) - - switch elemAlreadyExists->Js.Nullable.toOption { - | Some(dom) => dom->Window.remove - | None => () - } - - let componentType = "preMountLoader" - let iframeDivHtml = `` - - let iframeDiv = Window.createElement("div") - iframeDiv->Window.setAttribute( - "id", - `orca-payment-element-iframeRef-${localSelectorString}-parent`, - ) - iframeDiv->Window.innerHTML(iframeDivHtml) - Window.body->Window.appendChild(iframeDiv) - - let elem = Window.querySelector(`#orca-payment-element-iframeRef-${localSelectorString}`) - elem - } + let paymentMethodListPromise = PaymentHelpers.usePaymentMethodList( + ~clientSecret=clientSecretId, + ~publishableKey, + ~endpoint, + ~logger, + ) + + let sessionsPromise = PaymentHelpers.useSessions( + ~clientSecret=clientSecretId, + ~publishableKey, + ~endpoint, + ~optLogger=Some(logger), + (), + ) let locale = localOptions->getJsonStringFromDict("locale", "") let loader = localOptions->getJsonStringFromDict("loader", "") + let clientSecret = localOptions->getRequiredString("clientSecret", "", ~logger) let clientSecretReMatch = Js.Re.test_(`.+_secret_[A-Za-z0-9]+`->Js.Re.fromString, clientSecret) - let iframeIsReadyPromise = { - Js.Promise.make((~resolve, ~reject as _) => { - let handleIframeIsReadyHandler = (event: Types.event) => { - let json = event.data->eventToJson - let dict = json->getDictFromJson - if dict->Js.Dict.get("preMountLoaderInitCallback")->Belt.Option.isSome { - resolve(. Js.Dict.empty()) - } - } - addSmartEventListener( - "message", - handleIframeIsReadyHandler, - "handlePreMountIframeIsReadyHandler", - ) - }) - } - let preMountLoaderIframeDiv = mountPreMountLoaderIframe() - let fetchPaymentsList = mountedIframeRef => { - let handlePaymentMethodsLoaded = (event: Types.event) => { - let json = event.data->eventToJson - let dict = json->getDictFromJson - let isPaymentMethodsData = dict->Utils.getString("data", "") === "payment_methods" - if isPaymentMethodsData { - let json = dict->Utils.getJsonFromDict("response", Js.Json.null) - let isApplePayPresent = - PaymentMethodsRecord.getPaymentMethodTypeFromList( - ~list=json->Utils.getDictFromJson->PaymentMethodsRecord.itemToObjMapper, - ~paymentMethod="wallet", - ~paymentMethodType="apple_pay", - )->Belt.Option.isSome - - let isGooglePayPresent = - PaymentMethodsRecord.getPaymentMethodTypeFromList( - ~list=json->Utils.getDictFromJson->PaymentMethodsRecord.itemToObjMapper, - ~paymentMethod="wallet", - ~paymentMethodType="google_pay", - )->Belt.Option.isSome - - if isApplePayPresent || isGooglePayPresent { - if ( - Window.querySelectorAll(`script[src="https://tpgw.trustpay.eu/js/v1.js"]`)->Js.Array2.length === 0 && - Window.querySelectorAll(`script[src="https://test-tpgw.trustpay.eu/js/v1.js"]`)->Js.Array2.length === 0 - ) { - let trustPayScriptURL = - publishableKey->Js.String2.startsWith("pk_prd_") - ? "https://tpgw.trustpay.eu/js/v1.js" - : "https://test-tpgw.trustpay.eu/js/v1.js" - let trustPayScript = Window.createElement("script") - trustPayScript->Window.elementSrc(trustPayScriptURL) - trustPayScript->Window.elementOnerror(err => { - logger.setLogInfo( - ~value="ERROR DURING LOADING TRUSTPAY APPLE PAY: " ++ - err->toJson->Js.Json.stringify, - ~eventName=TRUSTPAY_SCRIPT, - ~logType=ERROR, - (), - ) - Utils.logInfo(Js.log2("ERROR DURING LOADING TRUSTPAY APPLE PAY", err)) - }) - Window.body->Window.appendChild(trustPayScript) - logger.setLogInfo(~value="TrustPay Script Loaded", ~eventName=TRUSTPAY_SCRIPT, ()) - } + open Promise + paymentMethodListPromise + ->then(json => { + let isApplePayPresent = + PaymentMethodsRecord.getPaymentMethodTypeFromList( + ~list=json->Utils.getDictFromJson->PaymentMethodsRecord.itemToObjMapper, + ~paymentMethod="wallet", + ~paymentMethodType="apple_pay", + )->Belt.Option.isSome + + let isGooglePayPresent = + PaymentMethodsRecord.getPaymentMethodTypeFromList( + ~list=json->Utils.getDictFromJson->PaymentMethodsRecord.itemToObjMapper, + ~paymentMethod="wallet", + ~paymentMethodType="google_pay", + )->Belt.Option.isSome + + if isApplePayPresent || isGooglePayPresent { + if ( + Window.querySelectorAll(`script[src="https://tpgw.trustpay.eu/js/v1.js"]`)->Js.Array2.length === 0 && + Window.querySelectorAll(`script[src="https://test-tpgw.trustpay.eu/js/v1.js"]`)->Js.Array2.length === 0 + ) { + let trustPayScriptURL = + publishableKey->Js.String2.startsWith("pk_prd_") + ? "https://tpgw.trustpay.eu/js/v1.js" + : "https://test-tpgw.trustpay.eu/js/v1.js" + let trustPayScript = Window.createElement("script") + trustPayScript->Window.elementSrc(trustPayScriptURL) + trustPayScript->Window.elementOnerror(err => { + Utils.logInfo(Js.log2("ERROR DURING LOADING TRUSTPAY APPLE PAY", err)) + }) + Window.body->Window.appendChild(trustPayScript) + logger.setLogInfo(~value="TrustPay Script Loaded", ~eventName=TRUSTPAY_SCRIPT, ()) } - let msg = [("paymentMethodList", json)]->Js.Dict.fromArray - mountedIframeRef->Window.iframePostMessage(msg) } - } - let msg = [("sendPaymentMethodsResponse", true->Js.Json.boolean)]->Js.Dict.fromArray - addSmartEventListener("message", handlePaymentMethodsLoaded, "onPaymentMethodsLoaded") - open Promise - iframeIsReadyPromise - ->then(_ => { - preMountLoaderIframeDiv->Window.iframePostMessage(msg) - Js.Json.null->resolve + + // Js.Global.setTimeout(() => { + let msg = [("paymentMethodList", json)]->Js.Dict.fromArray + mountedIframeRef->Window.iframePostMessage(msg) + // }, 5000)->ignore + json->resolve }) ->ignore } - - let fetchCustomerPaymentMethods = mountedIframeRef => { - let handleCustomerPaymentMethodsLoaded = (event: Types.event) => { - let json = event.data->eventToJson - let dict = json->getDictFromJson - let isCustomerPaymentMethodsData = - dict->Utils.getString("data", "") === "customer_payment_methods" - if isCustomerPaymentMethodsData { - let json = dict->Utils.getJsonFromDict("response", Js.Json.null) - let msg = [("customerPaymentMethods", json)]->Js.Dict.fromArray - mountedIframeRef->Window.iframePostMessage(msg) - } - } - let msg = [("sendCustomerPaymentMethodsResponse", true->Js.Json.boolean)]->Js.Dict.fromArray - addSmartEventListener( - "message", - handleCustomerPaymentMethodsLoaded, - "onCustomerPaymentMethodsLoaded", + let fetchCustomerDetails = mountedIframeRef => { + let customerDetailsPromise = PaymentHelpers.useCustomerDetails( + ~clientSecret=clientSecretId, + ~publishableKey, + ~endpoint, + ~optLogger=Some(logger), ) open Promise - iframeIsReadyPromise - ->then(_ => { - preMountLoaderIframeDiv->Window.iframePostMessage(msg) - Js.Json.null->resolve + customerDetailsPromise + ->then(json => { + // Js.Global.setTimeout(() => { + let msg = [("customerPaymentMethods", json)]->Js.Dict.fromArray + mountedIframeRef->Window.iframePostMessage(msg) + // }, 5000)->ignore + json->resolve + }) + ->catch(_err => { + let dict = + [("customer_payment_methods", []->Js.Json.array)]->Js.Dict.fromArray->Js.Json.object_ + let msg = [("customerPaymentMethods", dict)]->Js.Dict.fromArray + mountedIframeRef->Window.iframePostMessage(msg) + resolve(msg->Js.Json.object_) }) ->ignore } @@ -281,7 +213,6 @@ let make = ( ] ->Js.Dict.fromArray ->Js.Json.object_ - let endpoint = ApiEndpoint.getApiEndPoint(~publishableKey, ()) let message = [ ("paymentElementCreate", (componentType == "payment")->Js.Json.boolean), @@ -293,9 +224,6 @@ let make = ( ("publishableKey", publishableKey->Js.Json.string), ("sdkSessionId", sdkSessionId->Js.Json.string), ("sdkHandleConfirmPayment", sdkHandleConfirmPayment->Js.Json.boolean), - ("AOrcaBBlockPConfirm", blockConfirm->Js.Json.boolean), - ("switchToCustomPodABP", switchToCustomPod->Js.Json.boolean), - ("endpoint", endpoint->Js.Json.string), ("parentURL", "*"->Js.Json.string), ]->Js.Dict.fromArray @@ -310,13 +238,7 @@ let make = ( let msg = [("applePayCanMakePayments", true->Js.Json.boolean)]->Js.Dict.fromArray mountedIframeRef->Window.iframePostMessage(msg) } else { - logger.setLogInfo( - ~value="CANNOT MAKE PAYMENT USING APPLE PAY", - ~eventName=APPLE_PAY_FLOW, - ~paymentMethod="APPLE_PAY", - ~logType=ERROR, - (), - ) + Utils.logInfo(Js.log("CANNOT MAKE PAYMENT USING APPLE PAY")) } | None => () @@ -406,369 +328,350 @@ let make = ( addSmartEventListener("message", handleApplePayMounted, "onApplePayMount") addSmartEventListener("message", handleGooglePayThirdPartyFlow, "onGooglePayThirdParty") + Window.removeEventListener("message", handleApplePayMessages.contents) + sessionsPromise + ->then(json => { + let sessionsArr = + json + ->Js.Json.decodeObject + ->Belt.Option.getWithDefault(Js.Dict.empty()) + ->SessionsType.getSessionsTokenJson("session_token") + + let applePayPresent = sessionsArr->Js.Array2.find(item => { + let x = + item + ->Js.Json.decodeObject + ->Belt.Option.flatMap(x => { + x->Js.Dict.get("wallet_name") + }) + ->Belt.Option.flatMap(Js.Json.decodeString) + ->Belt.Option.getWithDefault("") + x === "apple_pay" || x === "applepay" + }) + let googlePayPresent = sessionsArr->Js.Array2.find(item => { + let x = + item + ->Js.Json.decodeObject + ->Belt.Option.flatMap(x => { + x->Js.Dict.get("wallet_name") + }) + ->Belt.Option.flatMap(Js.Json.decodeString) + ->Belt.Option.getWithDefault("") + x === "google_pay" || x === "googlepay" + }) - let fetchSessionTokens = mountedIframeRef => { - let handleSessionTokensLoaded = (event: Types.event) => { - let json = event.data->eventToJson - let dict = json->getDictFromJson - let sessionTokensData = dict->Utils.getString("data", "") === "session_tokens" - if sessionTokensData { - let json = dict->Utils.getJsonFromDict("response", Js.Json.null) + (json, applePayPresent, googlePayPresent)->resolve + }) + ->then(res => { + let (json, applePayPresent, googlePayPresent) = res + if componentType === "payment" && applePayPresent->Belt.Option.isSome { + //do operations here + + let processPayment = (token: Js.Json.t) => { + //let body = PaymentBody.applePayBody(~token) + let msg = [("applePayProcessPayment", token)]->Js.Dict.fromArray + mountedIframeRef->Window.iframePostMessage(msg) + } - { - let sessionsArr = - json - ->Js.Json.decodeObject - ->Belt.Option.getWithDefault(Js.Dict.empty()) - ->SessionsType.getSessionsTokenJson("session_token") - - let applePayPresent = sessionsArr->Js.Array2.find(item => { - let x = - item - ->Js.Json.decodeObject - ->Belt.Option.flatMap(x => { - x->Js.Dict.get("wallet_name") - }) - ->Belt.Option.flatMap(Js.Json.decodeString) - ->Belt.Option.getWithDefault("") - x === "apple_pay" || x === "applepay" - }) - let googlePayPresent = sessionsArr->Js.Array2.find(item => { - let x = - item - ->Js.Json.decodeObject - ->Belt.Option.flatMap(x => { - x->Js.Dict.get("wallet_name") - }) - ->Belt.Option.flatMap(Js.Json.decodeString) - ->Belt.Option.getWithDefault("") - x === "google_pay" || x === "googlepay" - }) + handleApplePayMessages := + ( + (event: Types.event) => { + let json = event.data->eventToJson + let dict = json->getDictFromJson - (json, applePayPresent, googlePayPresent)->resolve - } - ->then(res => { - let (json, applePayPresent, googlePayPresent) = res - if componentType === "payment" && applePayPresent->Belt.Option.isSome { - let processPayment = (token: Js.Json.t) => { - let msg = [("applePayProcessPayment", token)]->Js.Dict.fromArray - mountedIframeRef->Window.iframePostMessage(msg) - } + switch dict->Js.Dict.get("applePayButtonClicked") { + | Some(val) => + if val->Js.Json.decodeBoolean->Belt.Option.getWithDefault(false) { + let isDelayedSessionToken = + applePayPresent + ->Belt.Option.flatMap(Js.Json.decodeObject) + ->Belt.Option.getWithDefault(Js.Dict.empty()) + ->Js.Dict.get("delayed_session_token") + ->Belt.Option.getWithDefault(Js.Json.null) + ->Js.Json.decodeBoolean + ->Belt.Option.getWithDefault(false) + + if isDelayedSessionToken { + logger.setLogInfo( + ~value="Delayed Session Token Flow", + ~eventName=APPLE_PAY_FLOW, + ~paymentMethod="APPLE_PAY", + (), + ) - handleApplePayMessages := - ( - (event: Types.event) => { - let json = event.data->eventToJson - let dict = json->getDictFromJson - - switch dict->Js.Dict.get("applePayButtonClicked") { - | Some(val) => - if val->Js.Json.decodeBoolean->Belt.Option.getWithDefault(false) { - let isDelayedSessionToken = - applePayPresent - ->Belt.Option.flatMap(Js.Json.decodeObject) - ->Belt.Option.getWithDefault(Js.Dict.empty()) - ->Js.Dict.get("delayed_session_token") - ->Belt.Option.getWithDefault(Js.Json.null) - ->Js.Json.decodeBoolean - ->Belt.Option.getWithDefault(false) - - if isDelayedSessionToken { - let applePayPresent = - dict - ->Js.Dict.get("applePayPresent") - ->Belt.Option.flatMap(Js.Json.decodeObject) - ->Belt.Option.getWithDefault(Js.Dict.empty()) - - let connector = - applePayPresent - ->Js.Dict.get("connector") - ->Belt.Option.getWithDefault(Js.Json.null) - ->Js.Json.decodeString - ->Belt.Option.getWithDefault("") - - switch connector { - | "trustpay" => - let secrets = - applePayPresent - ->Js.Dict.get("session_token_data") - ->Belt.Option.getWithDefault(Js.Json.null) - ->Js.Json.decodeObject - ->Belt.Option.getWithDefault(Js.Dict.empty()) - ->Js.Dict.get("secrets") - ->Belt.Option.getWithDefault(Js.Json.null) - - let paymentRequest = - applePayPresent - ->Js.Dict.get("payment_request_data") - ->Belt.Option.flatMap(Js.Json.decodeObject) - ->Belt.Option.getWithDefault(Js.Dict.empty()) - ->ApplePayTypes.jsonToPaymentRequestDataType - - let payment = - secrets - ->Js.Json.decodeObject - ->Belt.Option.getWithDefault(Js.Dict.empty()) - ->Js.Dict.get("payment") - ->Belt.Option.getWithDefault(Js.Json.null) - ->Js.Json.decodeString - ->Belt.Option.getWithDefault("") - - try { - let trustpay = trustPayApi(secrets) - trustpay.finishApplePaymentV2(. payment, paymentRequest) - ->then(res => { - logger.setLogInfo( - ~value="TrustPay ApplePay Success Response", - ~internalMetadata=res->Js.Json.stringify, - ~eventName=APPLE_PAY_FLOW, - ~paymentMethod="APPLE_PAY", - ~logType=DEBUG, - (), - ) - let msg = - [ - ("applePaySyncPayment", true->Js.Json.boolean), - ]->Js.Dict.fromArray - mountedIframeRef->Window.iframePostMessage(msg) - resolve() - }) - ->catch(err => { - let exceptionMessage = - err->Utils.formatException->Js.Json.stringify - logger.setLogInfo( - ~eventName=APPLE_PAY_FLOW, - ~paymentMethod="APPLE_PAY", - ~value=exceptionMessage, - ~logType=ERROR, - ~internalMetadata="finishApplePaymentV2 catch", - (), - ) - let msg = - [ - ("applePaySyncPayment", true->Js.Json.boolean), - ]->Js.Dict.fromArray - mountedIframeRef->Window.iframePostMessage(msg) - resolve() - }) - ->ignore - } catch { - | exn => { - logger.setLogInfo( - ~value=exn->Utils.formatException->Js.Json.stringify, - ~eventName=APPLE_PAY_FLOW, - ~paymentMethod="APPLE_PAY", - ~logType=ERROR, - ~internalMetadata="outer catch", - (), - ) - let msg = - [ - ("applePaySyncPayment", true->Js.Json.boolean), - ]->Js.Dict.fromArray - mountedIframeRef->Window.iframePostMessage(msg) - } - } - | _ => () - } - } else { - let paymentRequest = - applePayPresent - ->Belt.Option.flatMap(Js.Json.decodeObject) - ->Belt.Option.getWithDefault(Js.Dict.empty()) - ->Js.Dict.get("payment_request_data") - ->Belt.Option.getWithDefault(Js.Dict.empty()->Js.Json.object_) - ->Utils.transformKeys(Utils.CamelCase) - - let ssn = applePaySession(3, paymentRequest) - switch applePaySessionRef.contents->Js.Nullable.toOption { - | Some(session) => - try { - session.abort(.) - } catch { - | error => Js.log2("Abort fail", error) - } - | None => () - } - - ssn.begin(.) - applePaySessionRef := ssn->Js.Nullable.return - - ssn.onvalidatemerchant = _event => { - let merchantSession = - applePayPresent - ->Belt.Option.flatMap(Js.Json.decodeObject) - ->Belt.Option.getWithDefault(Js.Dict.empty()) - ->Js.Dict.get("session_token_data") - ->Belt.Option.getWithDefault(Js.Dict.empty()->Js.Json.object_) - ->Utils.transformKeys(Utils.CamelCase) - ssn.completeMerchantValidation(. merchantSession) - } - - ssn.onpaymentauthorized = event => { - ssn.completePayment(. {"status": ssn.\"STATUS_SUCCESS"}->objToJson) - applePaySessionRef := Js.Nullable.null - processPayment(event.payment.token) - } - ssn.oncancel = _ev => { - let msg = - [("showApplePayButton", true->Js.Json.boolean)]->Js.Dict.fromArray - mountedIframeRef->Window.iframePostMessage(msg) - applePaySessionRef := Js.Nullable.null - Utils.logInfo(Js.log("Apple Pay payment cancelled")) - } + let applePayPresent = + dict + ->Js.Dict.get("applePayPresent") + ->Belt.Option.flatMap(Js.Json.decodeObject) + ->Belt.Option.getWithDefault(Js.Dict.empty()) + + let connector = + applePayPresent + ->Js.Dict.get("connector") + ->Belt.Option.getWithDefault(Js.Json.null) + ->Js.Json.decodeString + ->Belt.Option.getWithDefault("") + + switch connector { + | "trustpay" => + logger.setLogInfo( + ~value="TrustPay Connector Flow", + ~eventName=APPLE_PAY_FLOW, + ~paymentMethod="APPLE_PAY", + (), + ) + let secrets = + applePayPresent + ->Js.Dict.get("session_token_data") + ->Belt.Option.getWithDefault(Js.Json.null) + ->Js.Json.decodeObject + ->Belt.Option.getWithDefault(Js.Dict.empty()) + ->Js.Dict.get("secrets") + ->Belt.Option.getWithDefault(Js.Json.null) + + let paymentRequest = + applePayPresent + ->Js.Dict.get("payment_request_data") + ->Belt.Option.flatMap(Js.Json.decodeObject) + ->Belt.Option.getWithDefault(Js.Dict.empty()) + ->ApplePayTypes.jsonToPaymentRequestDataType + + let payment = + secrets + ->Js.Json.decodeObject + ->Belt.Option.getWithDefault(Js.Dict.empty()) + ->Js.Dict.get("payment") + ->Belt.Option.getWithDefault(Js.Json.null) + ->Js.Json.decodeString + ->Belt.Option.getWithDefault("") + + try { + let trustpay = trustPayApi(secrets) + trustpay.finishApplePaymentV2(. payment, paymentRequest) + ->then(res => { + logger.setLogInfo( + ~value="TrustPay ApplePay Success Response", + ~internalMetadata=res->Js.Json.stringify, + ~eventName=APPLE_PAY_FLOW, + ~paymentMethod="APPLE_PAY", + (), + ) + let msg = + [("applePaySyncPayment", true->Js.Json.boolean)]->Js.Dict.fromArray + mountedIframeRef->Window.iframePostMessage(msg) + logger.setLogInfo( + ~value="", + ~eventName=PAYMENT_DATA_FILLED, + ~paymentMethod="APPLE_PAY", + (), + ) + resolve() + }) + ->catch(err => { + let exceptionMessage = err->Utils.formatException->Js.Json.stringify + logger.setLogInfo( + ~eventName=APPLE_PAY_FLOW, + ~paymentMethod="APPLE_PAY", + ~value=exceptionMessage, + (), + ) + let msg = + [("applePaySyncPayment", true->Js.Json.boolean)]->Js.Dict.fromArray + mountedIframeRef->Window.iframePostMessage(msg) + resolve() + }) + ->ignore + } catch { + | exn => { + logger.setLogInfo( + ~value=exn->Utils.formatException->Js.Json.stringify, + ~eventName=APPLE_PAY_FLOW, + ~paymentMethod="APPLE_PAY", + (), + ) + let msg = + [("applePaySyncPayment", true->Js.Json.boolean)]->Js.Dict.fromArray + mountedIframeRef->Window.iframePostMessage(msg) } - } else { - () + } + | _ => () + } + } else { + let paymentRequest = + applePayPresent + ->Belt.Option.flatMap(Js.Json.decodeObject) + ->Belt.Option.getWithDefault(Js.Dict.empty()) + ->Js.Dict.get("payment_request_data") + ->Belt.Option.getWithDefault(Js.Dict.empty()->Js.Json.object_) + ->Utils.transformKeys(Utils.CamelCase) + + let ssn = applePaySession(3, paymentRequest) + switch applePaySessionRef.contents->Js.Nullable.toOption { + | Some(session) => + try { + session.abort(.) + } catch { + | error => Js.log2("Abort fail", error) } | None => () } - } - ) - addSmartEventListener( - "message", - handleApplePayMessages.contents, - "onApplePayMessages", - ) - } - if componentType === "payment" && googlePayPresent->Belt.Option.isSome { - let dict = json->getDictFromJson - let sessionObj = SessionsType.itemToObjMapper(dict, Others) - let gPayToken = SessionsType.getPaymentSessionObj(sessionObj.sessionsToken, Gpay) + ssn.begin(.) + applePaySessionRef := ssn->Js.Nullable.return + + ssn.onvalidatemerchant = _event => { + let merchantSession = + applePayPresent + ->Belt.Option.flatMap(Js.Json.decodeObject) + ->Belt.Option.getWithDefault(Js.Dict.empty()) + ->Js.Dict.get("session_token_data") + ->Belt.Option.getWithDefault(Js.Dict.empty()->Js.Json.object_) + ->Utils.transformKeys(Utils.CamelCase) + ssn.completeMerchantValidation(. merchantSession) + } - let tokenObj = switch gPayToken { - | OtherTokenOptional(optToken) => optToken - | _ => Some(SessionsType.defaultToken) + ssn.onpaymentauthorized = event => { + ssn.completePayment(. {"status": ssn.\"STATUS_SUCCESS"}->objToJson) + applePaySessionRef := Js.Nullable.null + processPayment(event.payment.token) + } + ssn.oncancel = _ev => { + let msg = + [("showApplePayButton", true->Js.Json.boolean)]->Js.Dict.fromArray + mountedIframeRef->Window.iframePostMessage(msg) + applePaySessionRef := Js.Nullable.null + Utils.logInfo(Js.log("Apple Pay payment cancelled")) + } + } + } else { + () + } + | None => () } + } + ) - let gpayobj = switch tokenObj { - | Some(val) => val - | _ => SessionsType.defaultToken - } + addSmartEventListener("message", handleApplePayMessages.contents, "onApplePayMessages") + } + if componentType === "payment" && googlePayPresent->Belt.Option.isSome { + let dict = json->getDictFromJson + let sessionObj = SessionsType.itemToObjMapper(dict, Others) + let gPayToken = SessionsType.getPaymentSessionObj(sessionObj.sessionsToken, Gpay) - let baseRequest = { - "apiVersion": 2, - "apiVersionMinor": 0, - } - let paymentDataRequest = GooglePayType.assign2( - Js.Dict.empty()->Js.Json.object_, - baseRequest->toJson, - ) + let tokenObj = switch gPayToken { + | OtherTokenOptional(optToken) => optToken + | _ => Some(SessionsType.defaultToken) + } - let payRequest = GooglePayType.assign( - Js.Dict.empty()->Js.Json.object_, - baseRequest->toJson, - { - "allowedPaymentMethods": gpayobj.allowed_payment_methods->arrayJsonToCamelCase, - }->toJson, - ) - paymentDataRequest.allowedPaymentMethods = - gpayobj.allowed_payment_methods->arrayJsonToCamelCase - paymentDataRequest.transactionInfo = - gpayobj.transaction_info->transformKeys(CamelCase) - paymentDataRequest.merchantInfo = gpayobj.merchant_info->transformKeys(CamelCase) - try { - let gPayClient = GooglePayType.google( - { - "environment": publishableKey->Js.String2.startsWith("pk_prd_") - ? "PRODUCTION" - : "TEST", - }->toJson, - ) - - if gpayobj.allowed_payment_methods->Belt.Array.length !== 0 { - gPayClient.isReadyToPay(. payRequest) - ->then(res => { - let dict = res->getDictFromJson - let isReadyToPay = getBool(dict, "result", false) - let msg = - [("isReadyToPay", isReadyToPay->Js.Json.boolean)]->Js.Dict.fromArray - mountedIframeRef->Window.iframePostMessage(msg) - resolve() - }) - ->catch(err => { - logger.setLogInfo( - ~value=err->toJson->Js.Json.stringify, - ~eventName=GOOGLE_PAY_FLOW, - ~paymentMethod="GOOGLE_PAY", - ~logType=DEBUG, - (), - ) - resolve() - }) - ->ignore - } + let gpayobj = switch tokenObj { + | Some(val) => val + | _ => SessionsType.defaultToken + } - let handleGooglePayMessages = (event: Types.event) => { - let evJson = event.data->eventToJson - let gpayClicked = - evJson - ->OrcaUtils.getOptionalJsonFromJson("GpayClicked") - ->OrcaUtils.getBoolfromjson(false) - - if gpayClicked { - Js.Global.setTimeout(() => { - gPayClient.loadPaymentData(. paymentDataRequest->toJson) - ->then(json => { - logger.setLogInfo( - ~value=json->toJson->Js.Json.stringify, - ~eventName=GOOGLE_PAY_FLOW, - ~paymentMethod="GOOGLE_PAY", - ~logType=DEBUG, - (), - ) - let msg = [("gpayResponse", json->toJson)]->Js.Dict.fromArray - mountedIframeRef->Window.iframePostMessage(msg) - resolve() - }) - ->catch(err => { - logger.setLogInfo( - ~value=err->toJson->Js.Json.stringify, - ~eventName=GOOGLE_PAY_FLOW, - ~paymentMethod="GOOGLE_PAY", - ~logType=DEBUG, - (), - ) - - let msg = [("gpayError", err->toJson)]->Js.Dict.fromArray - mountedIframeRef->Window.iframePostMessage(msg) - resolve() - }) - ->ignore - }, 0)->ignore - } - } - addSmartEventListener("message", handleGooglePayMessages, "onGooglePayMessages") - } catch { - | _ => Js.log("Error loading Gpay") - } - } + let baseRequest = { + "apiVersion": 2, + "apiVersionMinor": 0, + } + let paymentDataRequest = GooglePayType.assign2( + Js.Dict.empty()->Js.Json.object_, + baseRequest->toJson, + ) + + let payRequest = GooglePayType.assign( + Js.Dict.empty()->Js.Json.object_, + baseRequest->toJson, + { + "allowedPaymentMethods": gpayobj.allowed_payment_methods->arrayJsonToCamelCase, + }->toJson, + ) + paymentDataRequest.allowedPaymentMethods = + gpayobj.allowed_payment_methods->arrayJsonToCamelCase + paymentDataRequest.transactionInfo = gpayobj.transaction_info->transformKeys(CamelCase) + paymentDataRequest.merchantInfo = gpayobj.merchant_info->transformKeys(CamelCase) + try { + let gPayClient = GooglePayType.google( + { + "environment": publishableKey->Js.String2.startsWith("pk_prd_") + ? "PRODUCTION" + : "TEST", + }->toJson, + ) - json->resolve - }) - ->then(json => { - let msg = [("sessions", json)]->Js.Dict.fromArray + gPayClient.isReadyToPay(. payRequest) + ->then(res => { + let dict = res->getDictFromJson + let isReadyToPay = getBool(dict, "result", false) + let msg = [("isReadyToPay", isReadyToPay->Js.Json.boolean)]->Js.Dict.fromArray mountedIframeRef->Window.iframePostMessage(msg) - json->resolve + resolve() + }) + ->catch(err => { + logger.setLogInfo( + ~value=err->toJson->Js.Json.stringify, + ~eventName=GOOGLE_PAY_FLOW, + ~paymentMethod="GOOGLE_PAY", + ~logType=DEBUG, + (), + ) + resolve() }) ->ignore + + let handleGooglePayMessages = (event: Types.event) => { + let evJson = event.data->eventToJson + let gpayClicked = + evJson + ->OrcaUtils.getOptionalJsonFromJson("GpayClicked") + ->OrcaUtils.getBoolfromjson(false) + + if gpayClicked { + Js.Global.setTimeout(() => { + gPayClient.loadPaymentData(. paymentDataRequest->toJson) + ->then(json => { + logger.setLogInfo( + ~value=json->toJson->Js.Json.stringify, + ~eventName=GOOGLE_PAY_FLOW, + ~paymentMethod="GOOGLE_PAY", + ~logType=DEBUG, + (), + ) + let msg = [("gpayResponse", json->toJson)]->Js.Dict.fromArray + mountedIframeRef->Window.iframePostMessage(msg) + resolve() + }) + ->catch(err => { + logger.setLogInfo( + ~value=err->toJson->Js.Json.stringify, + ~eventName=GOOGLE_PAY_FLOW, + ~paymentMethod="GOOGLE_PAY", + ~logType=DEBUG, + (), + ) + + let msg = [("gpayError", err->toJson)]->Js.Dict.fromArray + mountedIframeRef->Window.iframePostMessage(msg) + resolve() + }) + ->ignore + }, 0)->ignore + } + } + addSmartEventListener("message", handleGooglePayMessages, "onGooglePayMessages") + } catch { + | _ => Js.log("Error loading Gpay") } } - let msg = [("sendSessionTokensResponse", true->Js.Json.boolean)]->Js.Dict.fromArray - addSmartEventListener("message", handleSessionTokensLoaded, "onSessionTokensLoaded") - - iframeIsReadyPromise - ->then(_ => { - preMountLoaderIframeDiv->Window.iframePostMessage(msg) - Js.Json.null->resolve - }) - ->ignore - } + json->resolve + }) + ->then(json => { + let msg = [("sessions", json)]->Js.Dict.fromArray + mountedIframeRef->Window.iframePostMessage(msg) + json->resolve + }) + ->ignore fetchPaymentsList(mountedIframeRef) - disableSaveCards ? () : fetchCustomerPaymentMethods(mountedIframeRef) - fetchSessionTokens(mountedIframeRef) + disableSaveCards ? () : fetchCustomerDetails(mountedIframeRef) mountedIframeRef->Window.iframePostMessage(message) }