repo
stringclasses
4 values
file_path
stringlengths
6
193
extension
stringclasses
23 values
content
stringlengths
0
1.73M
token_count
int64
0
724k
__index_level_0__
int64
0
10.8k
hyperswitch-client-core
src/hooks/AlertHook.res
.res
open ReactNative @val external alert: string => unit = "alert" let useAlerts = () => { let handleSuccessFailure = AllPaymentHooks.useHandleSuccessFailure() ( // let exitRN = HyperModule.useExitRN() ~errorType: string, ~message, ) => { let apiResStatus: PaymentConfirmTypes.error = { type_: "", status: "failed", code: "", message, } switch (errorType, Platform.os) { | ("error", _) => handleSuccessFailure(~apiResStatus, ()) | ("warning", #android) => ToastAndroid.show(message, ToastAndroid.long) | ("warning", #ios) => Alert.alert(~title="Warning", ~message, ()) | ("warning", #web) => alert(message) | _ => Console.error(message) } } }
188
10,731
hyperswitch-client-core
src/hooks/WebKit.res
.res
type platformType = [#ios | #iosWebView | #android | #androidWebView | #web | #next] let (platform, platformString) = if Next.getNextEnv == "next" { (#next, "next") } else if ReactNative.Platform.os === #android { (#android, "android") } else if ReactNative.Platform.os === #ios { (#ios, "ios") } else if Window.webKit->Nullable.toOption->Option.isSome { (#iosWebView, "iosWebView") } else if Window.androidInterface->Nullable.toOption->Option.isSome { (#androidWebView, "androidWebView") } else { (#web, "web") } type useWebKit = { exitPaymentSheet: string => unit, sdkInitialised: string => unit, launchApplePay: string => unit, launchGPay: string => unit, } let useWebKit = () => { let messageHandlers = switch Window.webKit->Nullable.toOption { | Some(webKit) => webKit.messageHandlers | None => None } let exitPaymentSheet = str => { switch platform { | #iosWebView => switch messageHandlers { | Some(messageHandlers) => switch messageHandlers.exitPaymentSheet { | Some(exitPaymentSheet) => exitPaymentSheet.postMessage(str) | None => () } | None => () } | #androidWebView => switch Window.androidInterface->Nullable.toOption { | Some(interface) => interface.exitPaymentSheet(str) | None => () } | _ => Window.postMessageToParent(str, "*") } } let sdkInitialised = str => { switch platform { | #iosWebView => switch messageHandlers { | Some(messageHandlers) => switch messageHandlers.sdkInitialised { | Some(sdkInitialised) => sdkInitialised.postMessage(str) | None => () } | None => () } | #androidWebView => switch Window.androidInterface->Nullable.toOption { | Some(interface) => interface.sdkInitialised(str) | None => () } | _ => Window.postMessageToParent(str, "*") } } let launchApplePay = str => { switch platform { | #iosWebView => switch messageHandlers { | Some(messageHandlers) => switch messageHandlers.launchApplePay { | Some(launchApplePay) => launchApplePay.postMessage(str) | None => () } | None => Window.postMessageToParent(str, "*") } | _ => () } } let launchGPay = str => { switch platform { | #androidWebView => switch Window.androidInterface->Nullable.toOption { | Some(interface) => interface.launchGPay(str) | None => () } | _ => Window.postMessageToParent(str, "*") } } {exitPaymentSheet, sdkInitialised, launchApplePay, launchGPay} }
630
10,732
hyperswitch-client-core
src/hooks/AllPaymentHooks.res
.res
open PaymentConfirmTypes type apiLogType = Request | Response | NoResponse | Err let useApiLogWrapper = () => { let logger = LoggerHook.useLoggerHook() ( ~logType, ~eventName, ~url, ~statusCode, ~apiLogType, ~data, ~paymentMethod=?, ~paymentExperience=?, (), ) => { let (_value, internalMetadata) = switch apiLogType { | Request => ([("url", url->JSON.Encode.string)], []) | Response => ( [("url", url->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string)], [("response", data)], ) | NoResponse => ( [ ("url", url->JSON.Encode.string), ("statusCode", "504"->JSON.Encode.string), ("response", data), ], [("response", data)], ) | Err => ( [ ("url", url->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string), ("response", data), ], [("response", data)], ) } logger( ~logType, ~value=apiLogType->JSON.stringifyAny->Option.getOr(""), ~internalMetadata=internalMetadata->Dict.fromArray->JSON.Encode.object->JSON.stringify, ~category=API, ~eventName, ~paymentMethod?, ~paymentExperience?, (), ) } } let useHandleSuccessFailure = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let {exit} = HyperModule.useExitPaymentsheet() let exitCard = HyperModule.useExitCard() let exitWidget = HyperModule.useExitWidget() (~apiResStatus: error, ~closeSDK=true, ~reset=true, ()) => { switch nativeProp.sdkState { | PaymentSheet | HostedCheckout | PaymentMethodsManagement => if closeSDK { exit(apiResStatus, reset) } | CardWidget => exitCard(apiResStatus) | WidgetPaymentSheet => if closeSDK { exit(apiResStatus, reset) } | CustomWidget(str) => exitWidget(apiResStatus, str->SdkTypes.widgetToStrMapper->String.toLowerCase) | ExpressCheckoutWidget => exitWidget(apiResStatus, "expressCheckout") | _ => () } } } let useSessionToken = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let baseUrl = GlobalHooks.useGetBaseUrl()() let apiLogWrapper = LoggerHook.useApiLogWrapper() (~wallet=[], ()) => { switch WebKit.platform { | #next => Promise.resolve(Next.sessionsRes) | _ => let headers = Utils.getHeader(nativeProp.publishableKey, nativeProp.hyperParams.appId) let uri = `${baseUrl}/payments/session_tokens` let body = [ ( "payment_id", String.split(nativeProp.clientSecret, "_secret_") ->Array.get(0) ->Option.getOr("") ->JSON.Encode.string, ), ("client_secret", nativeProp.clientSecret->JSON.Encode.string), ("wallets", wallet->JSON.Encode.array), ] ->Dict.fromArray ->JSON.Encode.object ->JSON.stringify apiLogWrapper( ~logType=INFO, ~eventName=SESSIONS_CALL_INIT, ~url=uri, ~statusCode="", ~apiLogType=Request, ~data=JSON.Encode.null, (), ) CommonHooks.fetchApi(~uri, ~method_=Post, ~headers, ~bodyStr=body, ()) ->Promise.then(data => { let statusCode = data->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) === "2" { apiLogWrapper( ~logType=INFO, ~eventName=SESSIONS_CALL, ~url=uri, ~statusCode, ~apiLogType=Response, ~data=JSON.Encode.null, (), ) data->Fetch.Response.json } else { data ->Fetch.Response.json ->Promise.then(error => { let value = [ ("url", uri->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string), ("response", error), ] ->Dict.fromArray ->JSON.Encode.object apiLogWrapper( ~logType=ERROR, ~eventName=SESSIONS_CALL, ~url=uri, ~statusCode, ~apiLogType=Err, ~data=value, (), ) Promise.resolve(error) }) } }) ->Promise.catch(err => { apiLogWrapper( ~logType=ERROR, ~eventName=SESSIONS_CALL, ~url=uri, ~statusCode="504", ~apiLogType=NoResponse, ~data=err->Utils.getError(`API call failed: ${uri}`), (), ) Promise.resolve(JSON.Encode.null) }) } } } let useRetrieveHook = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let apiLogWrapper = LoggerHook.useApiLogWrapper() let baseUrl = GlobalHooks.useGetBaseUrl()() (type_, clientSecret, publishableKey, ~isForceSync=false) => { switch (WebKit.platform, type_) { | (#next, Types.List) => Promise.resolve(Next.listRes) | (_, type_) => let headers = Utils.getHeader(publishableKey, nativeProp.hyperParams.appId) let ( uri, eventName: LoggerTypes.eventName, initEventName: LoggerTypes.eventName, ) = switch type_ { | Payment => ( `${baseUrl}/payments/${String.split(clientSecret, "_secret_") ->Array.get(0) ->Option.getOr("")}?force_sync=${isForceSync ? "true" : "false"}&client_secret=${clientSecret}`, RETRIEVE_CALL, RETRIEVE_CALL_INIT, ) | List => ( `${baseUrl}/account/payment_methods?client_secret=${clientSecret}`, PAYMENT_METHODS_CALL, PAYMENT_METHODS_CALL_INIT, ) } apiLogWrapper( ~logType=INFO, ~eventName=initEventName, ~url=uri, ~statusCode="", ~apiLogType=Request, ~data=JSON.Encode.null, (), ) CommonHooks.fetchApi(~uri, ~method_=Get, ~headers, ()) ->Promise.then(data => { let statusCode = data->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) === "2" { apiLogWrapper( ~logType=INFO, ~eventName, ~url=uri, ~statusCode, ~apiLogType=Response, ~data=JSON.Encode.null, (), ) data->Fetch.Response.json } else { data ->Fetch.Response.json ->Promise.then(error => { let value = [ ("url", uri->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string), ("response", error), ] ->Dict.fromArray ->JSON.Encode.object apiLogWrapper( ~logType=ERROR, ~eventName, ~url=uri, ~statusCode, ~apiLogType=Err, ~data=value, (), ) Promise.resolve(error) }) } }) ->Promise.catch(err => { apiLogWrapper( ~logType=ERROR, ~eventName, ~url=uri, ~statusCode="504", ~apiLogType=NoResponse, ~data=err->Utils.getError(`API call failed: ${uri}`), (), ) Promise.resolve(JSON.Encode.null) }) } } } let useBrowserHook = () => { let retrievePayment = useRetrieveHook() let (allApiData, setAllApiData) = React.useContext(AllApiDataContext.allApiDataContext) let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let intervalId = React.useRef(Nullable.null) ( ~clientSecret, ~publishableKey, ~openUrl, ~responseCallback, ~errorCallback, ~processor, ~useEphemeralWebSession=false, ) => { BrowserHook.openUrl( openUrl, Utils.getReturnUrl(~appId=nativeProp.hyperParams.appId, ~appURL=None), intervalId, ~useEphemeralWebSession, ~appearance=nativeProp.configuration.appearance ) ->Promise.then(res => { if res.status === Success { retrievePayment(Payment, clientSecret, publishableKey) ->Promise.then(s => { if s == JSON.Encode.null { setAllApiData({ ...allApiData, additionalPMLData: {...allApiData.additionalPMLData, retryEnabled: None}, }) errorCallback(~errorMessage=defaultConfirmError, ~closeSDK=true, ()) } else { let status = s ->Utils.getDictFromJson ->Dict.get("status") ->Option.flatMap(JSON.Decode.string) ->Option.getOr("") switch status { | "succeeded" => setAllApiData({ ...allApiData, additionalPMLData: {...allApiData.additionalPMLData, retryEnabled: None}, }) responseCallback( ~paymentStatus=LoadingContext.PaymentSuccess, ~status={status, message: "", code: "", type_: ""}, ) | "processing" | "requires_capture" | "requires_confirmation" | "cancelled" | "requires_merchant_action" => responseCallback( ~paymentStatus=LoadingContext.ProcessingPayments(None), ~status={status, message: "", code: "", type_: ""}, ) | _ => setAllApiData({ ...allApiData, additionalPMLData: {...allApiData.additionalPMLData, retryEnabled: None}, }) errorCallback( ~errorMessage={status, message: "", type_: "", code: ""}, ~closeSDK={true}, (), ) } } Promise.resolve() }) ->ignore } else if res.status == Cancel { setAllApiData({ ...allApiData, additionalPMLData: { ...allApiData.additionalPMLData, retryEnabled: Some({ processor, redirectUrl: openUrl, }), }, }) errorCallback( ~errorMessage={status: "cancelled", message: "", type_: "", code: ""}, ~closeSDK={false}, (), ) } else if res.status === Failed { setAllApiData({ ...allApiData, additionalPMLData: {...allApiData.additionalPMLData, retryEnabled: None}, }) errorCallback( ~errorMessage={status: "failed", message: "", type_: "", code: ""}, ~closeSDK={true}, (), ) } else { errorCallback( ~errorMessage={ status: res->JSON.stringifyAny->Option.getOr(""), message: "", type_: "", code: "", }, ~closeSDK={false}, (), ) } Promise.resolve() }) ->ignore } } let useRedirectHook = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let (allApiData, setAllApiData) = React.useContext(AllApiDataContext.allApiDataContext) let redirectToBrowserHook = useBrowserHook() let retrievePayment = useRetrieveHook() let apiLogWrapper = LoggerHook.useApiLogWrapper() let logger = LoggerHook.useLoggerHook() let baseUrl = GlobalHooks.useGetBaseUrl()() let handleNativeThreeDS = NetceteraThreeDsHooks.useExternalThreeDs() let getOpenProps = PlaidHelperHook.usePlaidProps() ( ~body: string, ~publishableKey: string, ~clientSecret: string, ~errorCallback: (~errorMessage: error, ~closeSDK: bool, unit) => unit, ~paymentMethod, ~paymentExperience: option<string>=?, ~responseCallback: (~paymentStatus: LoadingContext.sdkPaymentState, ~status: error) => unit, ~isCardPayment=false, (), ) => { let uriPram = String.split(clientSecret, "_secret_")->Array.get(0)->Option.getOr("") let uri = `${baseUrl}/payments/${uriPram}/confirm` let headers = Utils.getHeader(publishableKey, nativeProp.hyperParams.appId) let handleApiRes = (~status, ~reUri, ~error: error, ~nextAction: option<nextAction>=?) => { switch nextAction->PaymentUtils.getActionType { | "three_ds_invoke" => { let netceteraSDKApiKey = nativeProp.configuration.netceteraSDKApiKey->Option.getOr("") handleNativeThreeDS( ~baseUrl, ~appId=nativeProp.hyperParams.appId, ~netceteraSDKApiKey, ~clientSecret, ~publishableKey, ~nextAction, ~retrievePayment, ~sdkEnvironment=nativeProp.env, ~onSuccess=message => { responseCallback( ~paymentStatus=PaymentSuccess, ~status={status: "succeeded", message, code: "", type_: ""}, ) }, ~onFailure=message => { errorCallback( ~errorMessage={status: "failed", message, type_: "", code: ""}, ~closeSDK={true}, (), ) }, ) } | "third_party_sdk_session_token" => { // TODO: add event loggers for analytics let session_token = Option.getOr(nextAction, defaultNextAction).session_token let openProps = getOpenProps(retrievePayment, responseCallback, errorCallback) switch session_token { | Some(token) => Plaid.create({token: token.open_banking_session_token}) Plaid.open_(openProps)->ignore | None => () } } | _ => switch status { | "succeeded" => logger( ~logType=INFO, ~value="", ~category=USER_EVENT, ~eventName=PAYMENT_SUCCESS, ~paymentMethod={paymentMethod}, ~paymentExperience?, (), ) setAllApiData({ ...allApiData, additionalPMLData: {...allApiData.additionalPMLData, retryEnabled: None}, }) responseCallback( ~paymentStatus=PaymentSuccess, ~status={status, message: "", code: "", type_: ""}, ) | "requires_capture" | "processing" | "requires_confirmation" | "requires_merchant_action" => { setAllApiData({ ...allApiData, additionalPMLData: {...allApiData.additionalPMLData, retryEnabled: None}, }) responseCallback( ~paymentStatus=ProcessingPayments(None), ~status={status, message: "", code: "", type_: ""}, ) } | "requires_customer_action" => { setAllApiData({ ...allApiData, additionalPMLData: {...allApiData.additionalPMLData, retryEnabled: None}, }) logger( ~logType=INFO, ~category=USER_EVENT, ~value="", ~internalMetadata=reUri, ~eventName=REDIRECTING_USER, ~paymentMethod, (), ) redirectToBrowserHook( ~clientSecret, ~publishableKey, ~openUrl=reUri, ~responseCallback, ~errorCallback, ~processor=body, ~useEphemeralWebSession=isCardPayment, ) } | statusVal => logger( ~logType=ERROR, ~value={statusVal ++ error.message->Option.getOr("")}, ~category=USER_EVENT, ~eventName=PAYMENT_FAILED, ~paymentMethod={paymentMethod}, ~paymentExperience?, (), ) setAllApiData({ ...allApiData, additionalPMLData: {...allApiData.additionalPMLData, retryEnabled: None}, }) errorCallback( ~errorMessage=error, //~closeSDK={error.code == "IR_16" || error.code == "HE_00"}, ~closeSDK=true, (), ) } } } switch allApiData.additionalPMLData.retryEnabled { | Some({redirectUrl, processor}) => processor == body ? retrievePayment(Payment, clientSecret, publishableKey) ->Promise.then(res => { if res == JSON.Encode.null { errorCallback(~errorMessage={defaultConfirmError}, ~closeSDK=false, ()) } else { let status = res->Utils.getDictFromJson->Utils.getString("status", "") handleApiRes( ~status, ~reUri=redirectUrl, ~error={ code: "", message: "hardcoded retrieve payment error", type_: "", status: "failed", }, ) } Promise.resolve() }) ->ignore : { apiLogWrapper( ~logType=INFO, ~eventName=CONFIRM_CALL_INIT, ~url=uri, ~statusCode="", ~apiLogType=Request, ~data=JSON.Encode.null, (), ) CommonHooks.fetchApi(~uri, ~method_=Post, ~headers, ~bodyStr=body, ()) ->Promise.then(data => { let statusCode = data->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) === "2" { apiLogWrapper( ~logType=INFO, ~eventName=CONFIRM_CALL, ~url=uri, ~statusCode, ~apiLogType=Response, ~data=JSON.Encode.null, (), ) data->Fetch.Response.json } else { data ->Fetch.Response.json ->Promise.then(error => { let value = [ ("url", uri->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string), ("response", error), ] ->Dict.fromArray ->JSON.Encode.object apiLogWrapper( ~logType=ERROR, ~eventName=CONFIRM_CALL, ~url=uri, ~statusCode, ~apiLogType=Response, ~data=value, (), ) Promise.resolve(error) }) } }) ->Promise.then(jsonResponse => { let {nextAction, status, error} = itemToObjMapper(jsonResponse->Utils.getDictFromJson) handleApiRes(~status, ~reUri=nextAction.redirectToUrl, ~error) Promise.resolve() }) ->Promise.catch(err => { apiLogWrapper( ~logType=ERROR, ~eventName=CONFIRM_CALL, ~url=uri, ~statusCode="504", ~apiLogType=NoResponse, ~data=err->Utils.getError(`API call failed: ${uri}`), (), ) errorCallback(~errorMessage=defaultConfirmError, ~closeSDK=false, ()) Promise.resolve() }) ->ignore } | _ => { apiLogWrapper( ~logType=INFO, ~eventName=CONFIRM_CALL_INIT, ~url=uri, ~statusCode="", ~apiLogType=Request, ~data=JSON.Encode.null, (), ) CommonHooks.fetchApi(~uri, ~method_=Post, ~headers, ~bodyStr=body, ()) ->Promise.then(data => { let statusCode = data->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) === "2" { apiLogWrapper( ~logType=INFO, ~eventName=CONFIRM_CALL, ~url=uri, ~statusCode, ~apiLogType=Response, ~data=JSON.Encode.null, (), ) data->Fetch.Response.json } else { data ->Fetch.Response.json ->Promise.then(error => { let value = [ ("url", uri->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string), ("response", error), ] ->Dict.fromArray ->JSON.Encode.object apiLogWrapper( ~logType=ERROR, ~eventName=CONFIRM_CALL, ~url=uri, ~statusCode, ~apiLogType=Err, ~data=value, (), ) Promise.resolve(error) }) } }) ->Promise.then(jsonResponse => { let confirmResponse = jsonResponse->Utils.getDictFromJson let {nextAction, status, error} = itemToObjMapper(confirmResponse) handleApiRes(~status, ~reUri=nextAction.redirectToUrl, ~error, ~nextAction) Promise.resolve() }) ->Promise.catch(err => { apiLogWrapper( ~logType=ERROR, ~eventName=CONFIRM_CALL, ~url=uri, ~statusCode="504", ~apiLogType=NoResponse, ~data=err->Utils.getError(`API call failed: ${uri}`), (), ) errorCallback(~errorMessage=defaultConfirmError, ~closeSDK=false, ()) Promise.resolve() }) ->ignore } } } } let useGetSavedPMHook = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let apiLogWrapper = LoggerHook.useApiLogWrapper() let baseUrl = GlobalHooks.useGetBaseUrl()() let uri = switch nativeProp.sdkState { | PaymentMethodsManagement => `${baseUrl}/customers/payment_methods` | _ => `${baseUrl}/customers/payment_methods?client_secret=${nativeProp.clientSecret}` } let apiKey = switch nativeProp.sdkState { | PaymentMethodsManagement => nativeProp.ephemeralKey->Option.getOr("") | _ => nativeProp.publishableKey } () => { switch WebKit.platform { | #next => Promise.resolve(Next.clistRes->Some) | _ => apiLogWrapper( ~logType=INFO, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL_INIT, ~url=uri, ~statusCode="", ~apiLogType=Request, ~data=JSON.Encode.null, (), ) CommonHooks.fetchApi( ~uri, ~method_=Get, ~headers=Utils.getHeader(apiKey, nativeProp.hyperParams.appId), (), ) ->Promise.then(data => { let statusCode = data->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) === "2" { data ->Fetch.Response.json ->Promise.then(data => { apiLogWrapper( ~logType=INFO, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~url=uri, ~statusCode, ~apiLogType=Response, ~data=JSON.Encode.null, (), ) Some(data)->Promise.resolve }) } else { data ->Fetch.Response.json ->Promise.then(error => { let value = [ ("url", uri->JSON.Encode.string), ("statusCode", statusCode->JSON.Encode.string), ("response", error), ] ->Dict.fromArray ->JSON.Encode.object apiLogWrapper( ~logType=ERROR, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~url=uri, ~statusCode, ~apiLogType=Err, ~data=value, (), ) None->Promise.resolve }) } }) ->Promise.catch(err => { apiLogWrapper( ~logType=ERROR, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~url=uri, ~statusCode="504", ~apiLogType=NoResponse, ~data=err->Utils.getError(`API call failed: ${uri}`), (), ) None->Promise.resolve }) } } } let useDeleteSavedPaymentMethod = () => { let baseUrl = GlobalHooks.useGetBaseUrl()() let apiLogWrapper = LoggerHook.useApiLogWrapper() let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) (~paymentMethodId: string) => { let uri = `${baseUrl}/payment_methods/${paymentMethodId}` apiLogWrapper( ~logType=INFO, ~eventName=DELETE_PAYMENT_METHODS_CALL_INIT, ~url=uri, ~statusCode="", ~apiLogType=Request, ~data=JSON.Encode.null, (), ) if nativeProp.ephemeralKey->Option.isSome { CommonHooks.fetchApi( ~uri, ~method_=Delete, ~headers=Utils.getHeader( nativeProp.ephemeralKey->Option.getOr(""), nativeProp.hyperParams.appId, ), (), ) ->Promise.then(resp => { let statusCode = resp->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) !== "2" { resp ->Fetch.Response.json ->Promise.then(data => { apiLogWrapper( ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=DELETE_PAYMENT_METHODS_CALL, ~logType=ERROR, (), ) None->Promise.resolve }) } else { resp ->Fetch.Response.json ->Promise.then(data => { apiLogWrapper( ~url=uri, ~data, ~statusCode, ~apiLogType=Response, ~eventName=DELETE_PAYMENT_METHODS_CALL, ~logType=INFO, (), ) Some(data)->Promise.resolve }) } }) ->Promise.catch(err => { apiLogWrapper( ~logType=ERROR, ~eventName=DELETE_PAYMENT_METHODS_CALL, ~url=uri, ~statusCode="504", ~apiLogType=NoResponse, ~data=err->Utils.getError(`API call failed: ${uri}`), (), ) None->Promise.resolve }) } else { apiLogWrapper( ~logType=ERROR, ~eventName=DELETE_PAYMENT_METHODS_CALL, ~url=uri, ~statusCode="", ~apiLogType=NoResponse, ~data="Ephemeral key not found."->JSON.Encode.string, (), ) None->Promise.resolve } } } let useSavePaymentMethod = () => { let baseUrl = GlobalHooks.useGetBaseUrl()() let apiLogWrapper = LoggerHook.useApiLogWrapper() let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) (~body: PaymentMethodListType.redirectType) => { let uriParam = nativeProp.paymentMethodId let uri = `${baseUrl}/payment_methods/${uriParam}/save` apiLogWrapper( ~logType=INFO, ~eventName=ADD_PAYMENT_METHOD_CALL_INIT, ~url=uri, ~statusCode="", ~apiLogType=Request, ~data=JSON.Encode.null, (), ) CommonHooks.fetchApi( ~uri, ~method_=Post, ~headers=Utils.getHeader(nativeProp.publishableKey, nativeProp.hyperParams.appId), ~bodyStr=body->JSON.stringifyAny->Option.getOr(""), (), ) ->Promise.then(resp => { let statusCode = resp->Fetch.Response.status->string_of_int if statusCode->String.charAt(0) !== "2" { resp ->Fetch.Response.json ->Promise.then(error => { apiLogWrapper( ~url=uri, ~data=error, ~statusCode, ~apiLogType=Err, ~eventName=ADD_PAYMENT_METHOD_CALL, ~logType=ERROR, (), ) error->Promise.resolve }) } else { resp ->Fetch.Response.json ->Promise.then(data => { apiLogWrapper( ~url=uri, ~data, ~statusCode, ~apiLogType=Response, ~eventName=ADD_PAYMENT_METHOD_CALL, ~logType=INFO, (), ) data->Promise.resolve }) } }) ->Promise.catch(err => { apiLogWrapper( ~logType=ERROR, ~eventName=ADD_PAYMENT_METHOD_CALL, ~url=uri, ~statusCode="504", ~apiLogType=NoResponse, ~data=err->Utils.getError(`API call failed: ${uri}`), (), ) err->Utils.getError(`API call failed: ${uri}`)->Promise.resolve }) } }
6,268
10,733
hyperswitch-client-core
src/hooks/PlaidHelperHook.res
.res
open PaymentConfirmTypes open LoadingContext let usePlaidProps = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let getOpenProps = ( retrievePayment: (Types.retrieve, string, string, ~isForceSync: bool=?) => promise<Js.Json.t>, responseCallback: (~paymentStatus: sdkPaymentState, ~status: error) => unit, errorCallback: (~errorMessage: error, ~closeSDK: bool, unit) => unit, ) => { let openProps: PlaidTypes.linkOpenProps = { onSuccess: success => { retrievePayment( Types.Payment, nativeProp.clientSecret, nativeProp.publishableKey, ~isForceSync=true, ) ->Promise.then(res => { if res == JSON.Encode.null { errorCallback(~errorMessage=defaultConfirmError, ~closeSDK=true, ()) } else { let status = res ->Utils.getDictFromJson ->Dict.get("status") ->Option.flatMap(JSON.Decode.string) ->Option.getOr("") switch status { | "succeeded" | "requires_customer_action" | "processing" => responseCallback( ~paymentStatus=PaymentSuccess, ~status={ status: success.metadata.status->Option.getOr(""), message: success.metadata.metadataJson->Option.getOr("success message"), code: "", type_: "", }, ) | "requires_capture" | "requires_confirmation" | "cancelled" | "requires_merchant_action" => () responseCallback( ~paymentStatus=ProcessingPayments(None), ~status={status, message: "", code: "", type_: ""}, ) | _ => errorCallback( ~errorMessage={ status, message: "Payment is processing. Try again later!", type_: "sync_payment_failed", code: "", }, ~closeSDK={true}, (), ) } } Promise.resolve() }) ->ignore }, onExit: linkExit => { Plaid.dismissLink() let error: error = { message: switch linkExit.error { | Some(err) => err.errorMessage | None => "unknown error" }, } errorCallback(~errorMessage=error, ~closeSDK={true}, ()) }, } openProps } getOpenProps }
516
10,734
hyperswitch-client-core
src/hooks/AnimatedValue.res
.res
open ReactNative let useAnimatedValue = (initialValue: float) => { let lazyRef = React.useRef(None) if lazyRef.current === None { lazyRef.current = Some(Animated.Value.create(initialValue)) } switch lazyRef.current { | Some(val) => val | None => Animated.Value.create(initialValue) } }
77
10,735
hyperswitch-client-core
src/hooks/ShadowHook/ShadowHookImpl.web.res
.res
let useGetShadowStyle = (~shadowIntensity, ~shadowColor="black", ()) => { let shadowOffsetHeight = shadowIntensity->Float.toString let shadowOpacity = 0.2->Float.toString let shadowOffsetWidth = 0.->Float.toString let processedColor = ReactNative.Color.processColor(shadowColor)->Int.fromString->Option.getOr(0) let r = processedColor->lsr(16)->land(255)->Int.toString let g = processedColor->lsr(8)->land(255)->Int.toString let b = processedColor->land(255)->Int.toString let a: JsxDOMStyle.t = { boxShadow: `${shadowOffsetWidth} ${shadowOffsetWidth} ${shadowOffsetHeight}px rgba(${r}, ${g}, ${b}, ${shadowOpacity})`, } a }
189
10,736
hyperswitch-client-core
src/hooks/ShadowHook/ShadowHookImpl.ios.res
.res
let useGetShadowStyle = (~shadowIntensity, ~shadowColor="black", ()) => { let shadowOffsetHeight = shadowIntensity let shadowRadius = shadowIntensity let shadowOpacity = 0.2 let shadowOffsetWidth = 0. ReactNative.Style.viewStyle( ~shadowRadius, ~shadowOpacity, ~shadowOffset={ ReactNative.Style.offset(~width=shadowOffsetWidth, ~height=shadowOffsetHeight /. 2.) }, ~shadowColor, (), ) }
111
10,737
hyperswitch-client-core
src/hooks/ShadowHook/ShadowHookImpl.android.res
.res
let useGetShadowStyle = (~shadowIntensity, ()) => { ReactNative.Style.viewStyle(~elevation=shadowIntensity, ()) }
28
10,738
hyperswitch-client-core
src/hooks/ShadowHook/ShadowHook.res
.res
@module("./ShadowHookImpl") external useGetShadowStyle: ( ~shadowIntensity: float, ~shadowColor: ReactNative.Color.t=?, unit, ) => ReactNative.Style.t = "useGetShadowStyle"
48
10,739
hyperswitch-client-core
src/hooks/BackHandlerHook/BackHandlerHookImpl.web.res
.res
let useBackHandler = () => ()
8
10,740
hyperswitch-client-core
src/hooks/BackHandlerHook/BackHandlerHookImpl.native.res
.res
let useBackHandler = (~loading: LoadingContext.sdkPaymentState, ~sdkState: SdkTypes.sdkState) => { let handleSuccessFailure = AllPaymentHooks.useHandleSuccessFailure() React.useEffect2(() => { let backHandler = ReactNative.BackHandler.addEventListener(#hardwareBackPress, () => { switch loading { | ProcessingPayments(_) => () | _ => if [SdkTypes.PaymentSheet, SdkTypes.HostedCheckout]->Array.includes(sdkState) { handleSuccessFailure( ~apiResStatus=PaymentConfirmTypes.defaultCancelError, ~closeSDK=true, ~reset=false, (), ) } } true }) Some(() => backHandler["remove"]()) }, (loading, sdkState)) }
164
10,741
hyperswitch-client-core
src/hooks/BackHandlerHook/BackHandlerHook.res
.res
@module("./BackHandlerHookImpl") external useBackHandler: ( ~loading: LoadingContext.sdkPaymentState, ~sdkState: SdkTypes.sdkState, ) => unit = "useBackHandler"
44
10,742
hyperswitch-client-core
src/pages/hostedCheckout/HostedCheckoutSdk.res
.res
open ReactNative open Style @react.component let make = () => { let (confirmButtonDataRef, setConfirmButtonDataRef) = React.useState(_ => React.null) let setConfirmButtonDataRef = React.useCallback1(confirmButtonDataRef => { setConfirmButtonDataRef(_ => confirmButtonDataRef) }, [setConfirmButtonDataRef]) let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let {tabArr, elementArr} = PMListModifier.useListModifier() <View style={viewStyle(~maxWidth=450.->dp, ~alignSelf=#center, ~width=100.->pct, ())}> <Space height=20. /> <WalletView elementArr /> <CustomTabView hocComponentArr=tabArr loading={allApiData.sessions == Loading} setConfirmButtonDataRef /> <Space /> {confirmButtonDataRef} </View> }
215
10,743
hyperswitch-client-core
src/pages/hostedCheckout/HostedCheckout.res
.res
open ReactNative open Style @react.component let make = () => { let {bgColor} = ThemebasedStyle.useThemeBasedStyle() let useMediaView = WindowDimension.useMediaView() let isMobileView = WindowDimension.useIsMobileView() let parentViewStyle = switch useMediaView() { | Mobile => viewStyle() | _ => viewStyle(~flexDirection=#row, ()) } let sdkViewStyle = switch useMediaView() { | Mobile => viewStyle() | _ => viewStyle( ~flex=1., ~alignItems=#center, ~justifyContent=#center, ~shadowOffset=offset(~width=-7.5, ~height=0.), ~shadowRadius=20., ~shadowColor="rgba(1,1,1,0.027)", ~padding=32.->dp, (), ) } let checkoutViewStyle = switch useMediaView() { | Mobile => viewStyle() | _ => viewStyle( ~flex=1., ~marginHorizontal=80.->dp, ~alignItems=#center, ~justifyContent=#"space-around", ~paddingVertical=30.->dp, (), ) } <View style={array([viewStyle(~flex=1., ()), bgColor])}> <ScrollView keyboardShouldPersistTaps={#handled} showsHorizontalScrollIndicator={false} contentContainerStyle={viewStyle(~flexGrow=1., ~paddingBottom=40.->dp, ())}> <View style={array([parentViewStyle, viewStyle(~flex=1., ~marginHorizontal=15.->dp, ())])}> <View style={checkoutViewStyle}> <CheckoutView /> {isMobileView ? React.null : <CheckoutView.TermsView />} </View> <View style={array([bgColor, sdkViewStyle])}> <HostedCheckoutSdk /> </View> </View> </ScrollView> </View> }
448
10,744
hyperswitch-client-core
src/pages/hostedCheckout/CheckoutView.res
.res
open ReactNative open Style module TermsView = { @react.component let make = () => { <View style={viewStyle(~flexDirection=#row, ~width=100.->pct, ())}> <TextWrapper text="Powerd by Hyperswitch" textType={ModalText} /> <Space /> <TextWrapper text="|" textType={ModalText} /> <Space /> <TextWrapper text="Terms" textType={ModalText} /> <Space /> <TextWrapper text="Privacy" textType={ModalText} /> </View> } } module CheckoutHeader = { @react.component let make = (~toggleModal) => { let {bgColor} = ThemebasedStyle.useThemeBasedStyle() let useMediaView = WindowDimension.useMediaView()() <View style={array([ viewStyle( ~flexDirection=#row, ~alignItems=#center, ~padding=16.->dp, ~justifyContent=#"space-between", (), ), bgColor, ])}> <View style={viewStyle(~flexDirection=#row, ~alignItems=#center, ())}> // <CustomTouchableOpacity style={viewStyle(~padding=16.->dp, ())}> // <Icon name="back" height=24. width=20. fill="black" /> // </CustomTouchableOpacity> <ReImage uri="https://stripe-camo.global.ssl.fastly.net/63f4ec8cbe3d41be42a10161d3a86d3a3bda2d541052dc077e4d5e164c3386e1/68747470733a2f2f66696c65732e7374726970652e636f6d2f66696c65732f4d44423859574e6a64463878534559775a317044536c4978626d7470597a4a5866475a666447567a6446394263456c304f453952576e5a7652454a555330566f4d47564d62464e34546b38303063713345486f6c71" /> <Space width=10. /> <TextWrapper text="Powdur" textType={CardText} /> <Space width=10. /> <View style={viewStyle( ~backgroundColor="#ffdd93", ~paddingHorizontal=5.->dp, ~paddingVertical=2.->dp, ~borderRadius=3., (), )}> <TextWrapper textType={ModalTextBold}> {"TEST MODE"->React.string} </TextWrapper> </View> </View> {useMediaView == Mobile ? <View style={viewStyle(~flexDirection=#row, ~alignItems=#center, ())}> <CustomTouchableOpacity onPress={_ => toggleModal()} style={viewStyle(~flexDirection=#row, ~alignItems=#center, ())}> <TextWrapper text="Details" textType={ModalText} /> <Space width=10. /> <ChevronIcon width=15. height=15. fill="hsla(0,0%, 10% , 0.5 )" /> </CustomTouchableOpacity> </View> : React.null} </View> } } module Cart = { @react.component let make = () => { <View style={viewStyle( ~flexDirection=#row, ~paddingHorizontal=18.->dp, ~justifyContent=#"space-between", (), )}> <View style={viewStyle(~flexDirection=#row, ())}> <ReImage style={viewStyle(~width=50.->dp, ~height=50.->dp, ~borderRadius=8., ())} uri="https://stripe-camo.global.ssl.fastly.net/c25a949b6f1ffabee9af1a5696d7f152325bdce2d1b926456d42994c3d91ad78/68747470733a2f2f66696c65732e7374726970652e636f6d2f6c696e6b732f666c5f746573745f67625631776635726a4c64725a635858647032346d643649" /> <Space /> <View> <TextWrapper text="The Pure Set" textType={ModalText} /> <TextWrapper text="Qty 1" textType={ModalText} /> </View> </View> <TextWrapper text="US$65.00" textType={CardText} /> </View> } } module CartView = { @react.component let make = (~slideAnimation) => { let isMobileView = WindowDimension.useIsMobileView() let style = isMobileView ? viewStyle(~transform=Animated.ValueXY.getTranslateTransform(slideAnimation), ()) : viewStyle() let {bgColor} = ThemebasedStyle.useThemeBasedStyle() <Animated.View style={array([style, bgColor, viewStyle(~elevation=10., ())])}> <Space /> <Cart /> <Space /> <Cart /> <Space /> <View style={viewStyle( ~flexDirection=#row, ~justifyContent=#"space-between", ~paddingHorizontal=20.->dp, (), )}> <TextWrapper text="Total" textType={ModalText} /> <TextWrapper text="US$129.00" textType={CardText} /> </View> <Space height=20. /> </Animated.View> } } @react.component let make = () => { let (modalKey, setModalKey) = React.useState(_ => false) let (slideAnimation, _) = React.useState(_ => Animated.ValueXY.create({"x": 0., "y": -200.})) let isMobileView = WindowDimension.useIsMobileView() let toggleModal = () => { if modalKey { Animated.timing( slideAnimation["y"], { toValue: -200.->Animated.Value.Timing.fromRawValue, duration: 300., useNativeDriver: false, }, ) ->Animated.start(~endCallback=_ => setModalKey(_ => false), ()) ->ignore } else { setModalKey(_ => true) Animated.timing( slideAnimation["y"], { toValue: 1.->Animated.Value.Timing.fromRawValue, duration: 300., useNativeDriver: false, }, ) ->Animated.start() ->ignore } } <View style={viewStyle(~width=100.->pct, ())}> <CheckoutHeader toggleModal /> <Space height=30. /> <View style={isMobileView ? viewStyle() : viewStyle()}> <CheckoutDetails toggleModal /> {isMobileView ? <Modal visible=modalKey animationType={#none} presentationStyle={#overFullScreen} transparent=true supportedOrientations=[#"portrait-upside-down"]> <View style={viewStyle(~backgroundColor="rgba(0,0,0,0.2)", ~flex=1., ())}> <CartView slideAnimation /> <CustomTouchableOpacity style={viewStyle(~flex=1., ())} onPress={_ => toggleModal()} /> </View> </Modal> : <CartView slideAnimation />} </View> </View> }
1,912
10,745
hyperswitch-client-core
src/pages/hostedCheckout/CheckoutDetails.res
.res
open ReactNative open Style @react.component let make = (~toggleModal) => { let isMobileView = WindowDimension.useIsMobileView() <View style={viewStyle(~alignItems={isMobileView ? #center : #"flex-start"}, ())}> {isMobileView ? <ReImage style={viewStyle(~width=120.->dp, ~height=120.->dp, ~borderRadius=8., ())} uri="" /> : <Space height=25. />} <Space /> <TextWrapper text="Pay Powdur" textType=TextWrapper.ModalTextBold /> <Space /> <TextWrapper text="US$129.00" textType=TextWrapper.SubheadingBold /> <Space /> {isMobileView ? <CustomTouchableOpacity onPress={_ => {toggleModal()}} style={viewStyle( ~backgroundColor="hsla(0,0%, 10% , 0.05 )", ~padding=13.->dp, ~flexDirection=#row, ~alignItems=#center, ~justifyContent=#center, ~borderRadius=5., (), )}> <TextWrapper text="View Details" textType={LinkText} /> <Space width=8. /> <ChevronIcon width=14. height=14. fill="black" /> </CustomTouchableOpacity> : React.null} </View> }
325
10,746
hyperswitch-client-core
src/pages/paymentMethodsManagement/PaymentMethodListItem.res
.res
open ReactNative open Style module AddPaymentMethodButton = { @react.component let make = () => { let {component} = ThemebasedStyle.useThemeBasedStyle() let localeObject = GetLocale.useGetLocalObj() <CustomTouchableOpacity onPress={_ => ( HyperModule.hyperModule.onAddPaymentMethod("") )} style={viewStyle( ~paddingVertical=16.->dp, ~paddingHorizontal=24.->dp, ~borderBottomWidth=0.8, ~borderBottomColor=component.borderColor, ~flexDirection=#row, ~flexWrap=#nowrap, (), )}> <View style={viewStyle( ~flexDirection=#row, ~flexWrap=#nowrap, ~alignItems=#center, ~flex=1., (), )}> <Icon name={"addwithcircle"} height=16. width=16. style={viewStyle(~marginEnd=20.->dp, ~marginStart=5.->dp, ~marginVertical=10.->dp, ())} /> <Space /> <TextWrapper text={localeObject.addPaymentMethodLabel} textType=LinkText /> </View> </CustomTouchableOpacity> } } module PaymentMethodTitle = { @react.component let make = (~pmDetails: SdkTypes.savedDataType) => { let nickName = switch pmDetails { | SAVEDLISTCARD(obj) => obj.nick_name | _ => None } <View style={viewStyle(~flex=1., ())}> {switch nickName { | Some(val) => val != "" ? <> <TextWrapper text={val} textType={CardTextBold} ellipsizeMode=#tail numberOfLines={1} /> <Space height=5. /> </> : React.null | None => React.null }} <TextWrapper text={switch pmDetails { | SAVEDLISTWALLET(obj) => obj.walletType | SAVEDLISTCARD(obj) => obj.cardNumber | NONE => None } ->Option.getOr("") ->String.replaceAll("*", "●")} textType={switch pmDetails { | SAVEDLISTWALLET(_) => CardTextBold | _ => CardText }} /> </View> } } @react.component let make = (~pmDetails: SdkTypes.savedDataType, ~handleDelete) => { let {component} = ThemebasedStyle.useThemeBasedStyle() let localeObject = GetLocale.useGetLocalObj() let paymentMethodId = switch pmDetails { | SAVEDLISTCARD(cardData) => cardData.paymentMethodId | SAVEDLISTWALLET(walletData) => walletData.paymentMethodId | NONE => None } <CustomTouchableOpacity onPress={_ => handleDelete(paymentMethodId->Option.getOr(""))} style={viewStyle( ~padding=16.->dp, ~borderBottomWidth=0.8, ~borderBottomColor=component.borderColor, ~flexDirection=#row, ~flexWrap=#nowrap, ~alignItems=#center, ~justifyContent=#"space-between", ~flex=1., (), )}> <View style={viewStyle(~flexDirection=#row, ~flexWrap=#nowrap, ~alignItems=#center, ~flex=4., ())}> <Icon name={switch pmDetails { | SAVEDLISTCARD(obj) => obj.cardScheme | SAVEDLISTWALLET(obj) => obj.walletType | NONE => None }->Option.getOr("")} height=36. width=36. style={viewStyle(~marginEnd=5.->dp, ())} /> <Space /> <PaymentMethodTitle pmDetails /> </View> <View style={viewStyle( ~flexDirection=#"row-reverse", ~flexWrap=#nowrap, ~alignItems=#center, ~flex=1., (), )}> <TextWrapper text={localeObject.deletePaymentMethod->Option.getOr("Delete")} textType=LinkText /> </View> </CustomTouchableOpacity> }
943
10,747
hyperswitch-client-core
src/pages/paymentMethodsManagement/PaymentMethodsManagement.res
.res
open ReactNative open Style @react.component let make = () => { let {component} = ThemebasedStyle.useThemeBasedStyle() let deletePaymentMethod = AllPaymentHooks.useDeleteSavedPaymentMethod() let showAlert = AlertHook.useAlerts() let logger = LoggerHook.useLoggerHook() let (allApiData, setAllApiData) = React.useContext(AllApiDataContext.allApiDataContext) let (isLoading, setIsLoading) = React.useState(_ => true) let (savedMethods, setSavedMethods) = React.useState(_ => []) React.useEffect(() => { switch allApiData.savedPaymentMethods { | Loading => setIsLoading(_ => true) | Some(data) => setSavedMethods(_ => data.pmList->Option.getOr([])) setIsLoading(_ => false) | None => setIsLoading(_ => false) } None }, [allApiData.savedPaymentMethods]) let filterPaymentMethod = (savedMethods: array<SdkTypes.savedDataType>, paymentMethodId) => { savedMethods->Array.filter(pm => { let savedPaymentMethodId = switch pm { | SdkTypes.SAVEDLISTCARD(cardData) => cardData.paymentMethodId->Option.getOr("") | SdkTypes.SAVEDLISTWALLET(walletData) => walletData.paymentMethodId->Option.getOr("") | NONE => "" } savedPaymentMethodId != paymentMethodId }) } let handleDeletePaymentMethods = paymentMethodId => { let savedPaymentMethodContextObj = switch allApiData.savedPaymentMethods { | Some(data) => data | _ => AllApiDataContext.dafaultsavePMObj } deletePaymentMethod(~paymentMethodId) ->Promise.then(res => { switch res { | Some(data) => { let dict = data->Utils.getDictFromJson let paymentMethodId = dict->Utils.getString("payment_method_id", "") let isDeleted = dict->Utils.getBool("deleted", false) if isDeleted { logger( ~logType=INFO, ~value="Successfully Deleted Saved Payment Method", ~category=API, ~eventName=DELETE_SAVED_PAYMENT_METHOD, (), ) setAllApiData({ ...allApiData, savedPaymentMethods: Some({ ...savedPaymentMethodContextObj, pmList: Some(savedMethods->filterPaymentMethod(paymentMethodId)), }), }) setSavedMethods(prev => prev->filterPaymentMethod(paymentMethodId)) Promise.resolve() } else { logger( ~logType=ERROR, ~value=data->JSON.stringify, ~category=API, ~eventName=DELETE_SAVED_PAYMENT_METHOD, (), ) showAlert(~errorType="warning", ~message="Unable to delete payment method") Promise.resolve() } } | None => showAlert(~errorType="warning", ~message="Unable to delete payment method") Promise.resolve() } }) ->ignore } isLoading ? <View style={viewStyle( ~backgroundColor=component.background, ~width=100.->pct, ~flex=1., ~justifyContent=#center, ~alignItems=#center, (), )}> <TextWrapper text={"Loading ..."} textType={CardText} /> </View> : savedMethods->Array.length > 0 ? <View style={viewStyle(~backgroundColor=component.background, ~height=100.->pct, ())}> <ScrollView keyboardShouldPersistTaps=#handled> {savedMethods ->Array.mapWithIndex((item, i) => { <PaymentMethodListItem key={i->Int.toString} pmDetails={item} handleDelete=handleDeletePaymentMethods /> }) ->React.array} <PaymentMethodListItem.AddPaymentMethodButton /> <Space height=200. /> </ScrollView> </View> : <> <View style={viewStyle( ~width=100.->pct, ~paddingVertical=24.->dp, ~paddingHorizontal=24.->dp, ~borderBottomWidth=0.8, ~borderBottomColor=component.borderColor, ~backgroundColor=component.background, ~alignItems=#center, (), )}> <TextWrapper text={"No saved payment methods available."} textType={ModalTextLight} /> </View> <PaymentMethodListItem.AddPaymentMethodButton /> </> }
978
10,748
hyperswitch-client-core
src/pages/payment/SavedPaymentScreenChild.res
.res
open ReactNative open ReactNative.Style @react.component let make = ( ~savedPaymentMethodsData, ~isSaveCardCheckboxSelected, ~setSaveCardChecboxSelected, ~showSavePMCheckbox, ~merchantName, ~savedCardCvv, ~setSavedCardCvv, ~setIsCvcValid, ) => { let {borderRadius, component, shadowColor, shadowIntensity} = ThemebasedStyle.useThemeBasedStyle() let (selected, isSelected) = React.useState(_ => true) let getShadowStyle = ShadowHook.useGetShadowStyle(~shadowIntensity, ~shadowColor, ()) let localeObj = GetLocale.useGetLocalObj() <> <Space /> <View style={array([ getShadowStyle, viewStyle( ~paddingHorizontal=24.->dp, ~paddingVertical=5.->dp, ~borderRadius, ~borderWidth=0.0, ~borderColor=component.borderColor, ~backgroundColor=component.background, (), ), ])}> <SavedPMListWithLoader listArr={savedPaymentMethodsData} savedCardCvv setSavedCardCvv setIsCvcValid /> </View> <Space height=20. /> <ClickableTextElement initialIconName="addwithcircle" text={localeObj.addPaymentMethodLabel} isSelected=selected setIsSelected=isSelected textType={TextWrapper.LinkTextBold} fillIcon=false /> {showSavePMCheckbox ? <> <Space /> <ClickableTextElement disabled={false} initialIconName="checkboxClicked" updateIconName=Some("checkboxNotClicked") text={localeObj.cardTermsPart1 ++ merchantName ++ localeObj.cardTermsPart2} isSelected={isSaveCardCheckboxSelected} setIsSelected={setSaveCardChecboxSelected} textType={TextWrapper.ModalText} disableScreenSwitch=true /> </> : React.null} <Space height=12. /> </> }
454
10,749
hyperswitch-client-core
src/pages/payment/WalletView.res
.res
open ReactNative open Style module WalletDisclaimer = { @react.component let make = () => { let localeObject = GetLocale.useGetLocalObj() <> <Space height=10. /> <View style={viewStyle( ~display=#flex, ~justifyContent=#center, ~alignContent=#center, ~flexDirection=#row, ~alignItems=#center, (), )}> <Icon name="lock" fill="#767676" style={viewStyle(~marginEnd=5.->dp, ())} /> <TextWrapper text={localeObject.walletDisclaimer} textType={ModalText} /> </View> </> } } @react.component let make = (~loading=true, ~elementArr, ~showDisclaimer=false) => { let localeObject = GetLocale.useGetLocalObj() <> {switch elementArr->Array.length { | 0 => loading ? <> <Space /> <CustomLoader /> <Space height=15. /> <TextWithLine text=localeObject.orPayUsing /> </> : React.null | _ => <> <Space /> {elementArr->React.array} {showDisclaimer ? <WalletDisclaimer /> : React.null} <Space height=15. /> <TextWithLine text=localeObject.orPayUsing /> </> }} </> }
309
10,750
hyperswitch-client-core
src/pages/payment/CardParent.res
.res
@react.component let make = ( ~cardVal: PaymentMethodListType.payment_method_types_card, ~isScreenFocus, ~setConfirmButtonDataRef, ) => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) <ErrorBoundary level={FallBackScreen.Screen} rootTag=nativeProp.rootTag> <Card cardVal isScreenFocus setConfirmButtonDataRef /> </ErrorBoundary> }
97
10,751
hyperswitch-client-core
src/pages/payment/Card.res
.res
open ReactNative open PaymentMethodListType @react.component let make = ( ~cardVal: PaymentMethodListType.payment_method_types_card, ~isScreenFocus, ~setConfirmButtonDataRef: React.element => unit, ) => { // Custom Hooks let localeObject = GetLocale.useGetLocalObj() let handleSuccessFailure = AllPaymentHooks.useHandleSuccessFailure() let fetchAndRedirect = AllPaymentHooks.useRedirectHook() // Custom context let (_, setLoading) = React.useContext(LoadingContext.loadingContext) let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let (isNicknameSelected, setIsNicknameSelected) = React.useState(_ => false) let (keyToTrigerButtonClickError, setKeyToTrigerButtonClickError) = React.useState(_ => 0) let savedPaymentMethodsData = switch allApiData.savedPaymentMethods { | Some(data) => data | _ => AllApiDataContext.dafaultsavePMObj } let isSaveCardCheckboxVisible = nativeProp.configuration.displaySavedPaymentMethodsCheckbox // Fields Hooks let (cardData, _) = React.useContext(CardDataContext.cardDataContext) let (nickname, setNickname) = React.useState(_ => None) // Validity Hooks let (isAllCardValuesValid, setIsAllCardValuesValid) = React.useState(_ => false) let (isAllDynamicFieldValid, setIsAllDynamicFieldValid) = React.useState(_ => true) let (isNicknameValid, setIsNicknameValid) = React.useState(_ => true) let requiredFields = cardVal.required_field->Array.filter(val => { switch val.field_type { | RequiredFieldsTypes.UnKnownField(_) => false | _ => true } }) let (dynamicFieldsJson, setDynamicFieldsJson) = React.useState((_): dict<( JSON.t, option<string>, )> => Dict.make()) let (error, setError) = React.useState(_ => None) let isConfirmButtonValid = isAllCardValuesValid && isAllDynamicFieldValid && isNicknameValid let initialiseNetcetera = NetceteraThreeDsHooks.useInitNetcetera() let (isInitialised, setIsInitialised) = React.useState(_ => false) React.useEffect1(() => { if ( WebKit.platform === #android && !isInitialised && allApiData.additionalPMLData.requestExternalThreeDsAuthentication->Option.getOr(false) && cardData.cardNumber->String.length > 0 ) { setIsInitialised(_ => true) initialiseNetcetera( ~netceteraSDKApiKey=nativeProp.configuration.netceteraSDKApiKey->Option.getOr(""), ~sdkEnvironment=nativeProp.env, ) } None }, [cardData.cardNumber]) React.useEffect(() => { if isNicknameSelected == false { setNickname(_ => None) setIsNicknameValid(_ => true) } None }, [isNicknameSelected]) let processRequest = (prop: PaymentMethodListType.payment_method_types_card) => { let errorCallback = (~errorMessage: PaymentConfirmTypes.error, ~closeSDK, ()) => { if !closeSDK { setLoading(FillingDetails) switch errorMessage.message { | Some(message) => setError(_ => Some(message)) | None => () } } handleSuccessFailure(~apiResStatus=errorMessage, ~closeSDK, ()) } let responseCallback = (~paymentStatus: LoadingContext.sdkPaymentState, ~status) => { switch paymentStatus { | PaymentSuccess => { setLoading(PaymentSuccess) setTimeout(() => { handleSuccessFailure(~apiResStatus=status, ()) }, 300)->ignore } | _ => handleSuccessFailure(~apiResStatus=status, ()) } } let payment_method_data = PaymentUtils.generatePaymentMethodData( ~prop, ~cardData, ~cardHolderName=None, ~nickname, ) let body = PaymentUtils.generateCardConfirmBody( ~nativeProp, ~prop, ~payment_method_data=payment_method_data->Option.getOr(JSON.Encode.null), ~allApiData, ~isNicknameSelected, ~isSaveCardCheckboxVisible, ~isGuestCustomer=savedPaymentMethodsData.isGuestCustomer, (), ) let paymentBodyWithDynamicFields = PaymentMethodListType.getPaymentBody( body, dynamicFieldsJson->Dict.toArray->Array.map(((key, (value, error))) => (key, value, error)), ) fetchAndRedirect( ~body=paymentBodyWithDynamicFields->JSON.stringifyAny->Option.getOr(""), ~publishableKey=nativeProp.publishableKey, ~clientSecret=nativeProp.clientSecret, ~errorCallback, ~responseCallback, ~paymentMethod=prop.payment_method_type, ~isCardPayment=true, (), ) } let handlePress = _ => { isConfirmButtonValid ? { setLoading(ProcessingPayments(None)) processRequest(cardVal) } : setKeyToTrigerButtonClickError(prev => prev + 1) } React.useEffect7(() => { if isScreenFocus { setConfirmButtonDataRef( <ConfirmButton loading=false isAllValuesValid=true handlePress paymentMethod="CARD" errorText=error />, ) } None }, ( isConfirmButtonValid, isScreenFocus, error, isNicknameSelected, nickname, dynamicFieldsJson, cardData, )) <> <View> <TextWrapper text=localeObject.cardDetailsLabel textType={ModalText} /> <Space height=8. /> <CardElement setIsAllValid=setIsAllCardValuesValid reset=false keyToTrigerButtonClickError cardNetworks=cardVal.card_networks /> {cardVal.required_field->Array.length != 0 ? <> <DynamicFields setIsAllDynamicFieldValid setDynamicFieldsJson requiredFields isSaveCardsFlow={false} savedCardsData=None keyToTrigerButtonClickError /> <Space height=8. /> </> : React.null} {switch ( nativeProp.configuration.displaySavedPaymentMethodsCheckbox, savedPaymentMethodsData.isGuestCustomer, allApiData.additionalPMLData.mandateType, ) { | (true, false, NEW_MANDATE | NORMAL) => <> <Space height=8. /> <ClickableTextElement disabled={false} initialIconName="checkboxClicked" updateIconName=Some("checkboxNotClicked") text=localeObject.saveCardDetails isSelected=isNicknameSelected setIsSelected=setIsNicknameSelected textType={ModalText} disableScreenSwitch=true /> </> | _ => React.null }} {switch ( savedPaymentMethodsData.isGuestCustomer, isNicknameSelected, nativeProp.configuration.displaySavedPaymentMethodsCheckbox, allApiData.additionalPMLData.mandateType, ) { | (false, _, true, NEW_MANDATE | NORMAL) => isNicknameSelected ? <NickNameElement nickname setNickname setIsNicknameValid /> : React.null | (false, _, false, NEW_MANDATE) | (false, _, _, SETUP_MANDATE) => <NickNameElement nickname setNickname setIsNicknameValid /> | _ => React.null }} </View> </> }
1,663
10,752
hyperswitch-client-core
src/pages/payment/ClickableTextElement.res
.res
open ReactNative open Style @react.component let make = ( ~initialIconName, ~updateIconName=None, ~text, ~isSelected, ~setIsSelected, ~textType, ~fillIcon=true, ~disabled=false, ~disableScreenSwitch=false, ) => { let (isSavedCardScreen, setSaveCardScreen) = React.useContext( PaymentScreenContext.paymentScreenTypeContext, ) <CustomTouchableOpacity disabled activeOpacity=1. style={viewStyle(~flexDirection=#row, ~alignItems=#center, ~alignSelf=#"flex-start", ())} onPress={_ => { !disableScreenSwitch ? { let newSheetType = switch isSavedCardScreen { | PAYMENTSHEET => PaymentScreenContext.SAVEDCARDSCREEN | SAVEDCARDSCREEN => PaymentScreenContext.PAYMENTSHEET } setSaveCardScreen(newSheetType) } : setIsSelected(_ => !isSelected) }}> <CustomSelectBox initialIconName updateIconName isSelected fillIcon /> <TextWrapper text textType overrideStyle=Some(viewStyle(~paddingHorizontal=6.->dp, ())) /> </CustomTouchableOpacity> }
264
10,753
hyperswitch-client-core
src/pages/payment/ConfirmButtonAnimation.res
.res
open ReactNative open Style @react.component let make = ( ~isAllValuesValid, ~handlePress, ~hasSomeFields=true, ~paymentMethod, ~paymentExperience=?, ~displayText="Pay Now", (), ) => { let localeObject = GetLocale.useGetLocalObj() let (loading, _) = React.useContext(LoadingContext.loadingContext) let { payNowButtonColor, payNowButtonBorderColor, buttonBorderRadius, buttonBorderWidth, } = ThemebasedStyle.useThemeBasedStyle() let logger = LoggerHook.useLoggerHook() React.useEffect2(() => { if isAllValuesValid && hasSomeFields { logger( ~logType=INFO, ~value="", ~category=USER_EVENT, ~eventName=PAYMENT_DATA_FILLED, ~paymentMethod, ~paymentExperience?, (), ) } None }, (isAllValuesValid, hasSomeFields)) <View style={viewStyle(~alignItems=#center, ())}> <Space height=10. /> <CustomButton borderWidth=buttonBorderWidth borderRadius=buttonBorderRadius borderColor=payNowButtonBorderColor buttonState={switch loading { | ProcessingPayments(_) => LoadingButton | PaymentSuccess => Completed | _ => isAllValuesValid ? Normal : Disabled }} loadingText="Processing..." linearGradientColorTuple=Some(isAllValuesValid ? payNowButtonColor : ("#CCCCCC", "#CCCCCC")) text={displayText == "Pay Now" ? localeObject.payNowButton : displayText} name="Pay" testID={TestUtils.payButtonTestId} onPress={ev => { if !(isAllValuesValid && hasSomeFields) { logger( ~logType=INFO, ~value="", ~category=USER_EVENT, ~eventName=PAYMENT_DATA_FILLED, ~paymentMethod, ~paymentExperience?, (), ) } logger( ~logType=INFO, ~value="", ~category=USER_EVENT, ~eventName=PAYMENT_ATTEMPT, ~paymentMethod, ~paymentExperience?, (), ) handlePress(ev) }} /> <HyperSwitchBranding /> </View> }
501
10,754
hyperswitch-client-core
src/pages/payment/NickNameElement.res
.res
@react.component let make = (~nickname, ~setNickname, ~setIsNicknameValid) => { let {component, borderWidth, borderRadius, dangerColor} = ThemebasedStyle.useThemeBasedStyle() let localeObject = GetLocale.useGetLocalObj() let (isFocus, setisFocus) = React.useState(_ => false) let (errorMessage, setErrorMesage) = React.useState(_ => None) let onChange = text => { setNickname(_ => text == "" || String.trim(text) == "" ? None : Some(text)) switch text->Validation.containsMoreThanTwoDigits { | true => { setErrorMesage(_ => Some(localeObject.invalidDigitsNickNameError)) setIsNicknameValid(_ => false) } | false => { setErrorMesage(_ => None) setIsNicknameValid(_ => true) } } } <> <Space /> // <TextWrapper text={localeObject.cardNickname} textType=SubheadingBold /> // <Space height=5. /> <CustomInput state={nickname->Option.getOr("")} setState={str => onChange(str)} placeholder={`${localeObject.cardNickname}${" (Optional)"}`} keyboardType=#default isValid={isFocus || errorMessage->Option.isNone} onFocus={_ => { setNickname(nickname => String.trim(nickname->Option.getOr(""))->Some) setisFocus(_ => true) }} onBlur={_ => { setNickname(nickname => String.trim(nickname->Option.getOr(""))->Some) setisFocus(_ => false) }} textColor={isFocus || errorMessage->Option.isNone ? component.color : dangerColor} borderBottomLeftRadius=borderRadius borderBottomRightRadius=borderRadius borderTopLeftRadius=borderRadius borderTopRightRadius=borderRadius borderTopWidth=borderWidth borderBottomWidth=borderWidth borderLeftWidth=borderWidth borderRightWidth=borderWidth animateLabel=localeObject.cardNickname maxLength=Some(12) /> {switch errorMessage { | Some(text) => !isFocus ? <ErrorText text=Some(text) /> : React.null | None => React.null }} <Space height=5. /> </> }
487
10,755
hyperswitch-client-core
src/pages/payment/PaymentSheet.res
.res
@react.component let make = (~setConfirmButtonDataRef) => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let (_, setPaymentScreenType) = React.useContext(PaymentScreenContext.paymentScreenTypeContext) //getting payment list data here let {tabArr, elementArr} = PMListModifier.useListModifier() let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let savedPaymentMethodsData = switch allApiData.savedPaymentMethods { | Some(data) => data | _ => AllApiDataContext.dafaultsavePMObj } let localeObject = GetLocale.useGetLocalObj() React.useEffect0(() => { setPaymentScreenType(PAYMENTSHEET) None }) let (localeStrings, _) = React.useContext(LocaleStringDataContext.localeDataContext) <> <WalletView loading={nativeProp.sdkState !== CardWidget && allApiData.sessions == Loading && localeStrings == Loading} elementArr showDisclaimer={allApiData.additionalPMLData.mandateType->PaymentUtils.checkIfMandate} /> <CustomTabView hocComponentArr=tabArr loading={allApiData.sessions == Loading && localeStrings == Loading} setConfirmButtonDataRef /> {PaymentUtils.showUseExisitingSavedCardsBtn( ~isGuestCustomer=savedPaymentMethodsData.isGuestCustomer, ~pmList=savedPaymentMethodsData.pmList, ~mandateType=allApiData.additionalPMLData.mandateType, ~displaySavedPaymentMethods=nativeProp.configuration.displaySavedPaymentMethods, ) ? <> <Space height=10. /> <ClickableTextElement initialIconName="cardv1" text=localeObject.useExisitingSavedCards isSelected=true setIsSelected={_ => ()} textType={TextWrapper.LinkTextBold} fillIcon=true /> <Space height=12. /> </> : React.null} </> }
452
10,756
hyperswitch-client-core
src/pages/payment/SavedPMListWithLoader.res
.res
open ReactNative open Style module LoadingListItem = { @react.component let make = () => { <View style={viewStyle(~display=#flex, ~flexDirection=#row, ~alignItems=#center, ())}> <View style={viewStyle(~marginRight=10.->dp, ())}> <CustomLoader width="30" height="25" /> </View> // <View style={viewStyle(~marginLeft=30.->dp,~backgroundColor="green", ())}> <CustomLoader height="30" /> // </View> </View> } } module LoadingPmList = { @react.component let make = () => { <> <LoadingListItem /> <Space height=15. /> <LoadingListItem /> <Space height=15. /> <LoadingListItem /> </> } } let placeDefaultPMAtTopOfArr = (listArr: array<SdkTypes.savedDataType>) => { let defaultPm = listArr->Array.find(obj => { switch obj { | SAVEDLISTCARD(obj) => obj.isDefaultPaymentMethod | SAVEDLISTWALLET(obj) => obj.isDefaultPaymentMethod | NONE => Some(false) }->Option.getOr(false) }) let listArr = listArr->Array.filter(obj => { !( switch obj { | SAVEDLISTCARD(obj) => obj.isDefaultPaymentMethod | SAVEDLISTWALLET(obj) => obj.isDefaultPaymentMethod | NONE => Some(false) }->Option.getOr(false) ) }) defaultPm->Option.isSome ? [defaultPm->Option.getOr(NONE)]->Array.concat(listArr) : listArr } @react.component let make = ( ~listArr: array<SdkTypes.savedDataType>, ~savedCardCvv, ~setSavedCardCvv, ~setIsCvcValid, ) => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let (allApiData, setAllApiData) = React.useContext(AllApiDataContext.allApiDataContext) let savedPaymentMethodContextObj = switch allApiData.savedPaymentMethods { | Some(data) => data | _ => AllApiDataContext.dafaultsavePMObj } let listArr = nativeProp.configuration.displayDefaultSavedPaymentIcon ? listArr->placeDefaultPMAtTopOfArr : listArr React.useEffect0(_ => { switch listArr->Array.get(0) { | Some(obj) => switch obj { | SdkTypes.SAVEDLISTCARD(obj) => setAllApiData({ ...allApiData, savedPaymentMethods: Some({ ...savedPaymentMethodContextObj, selectedPaymentMethod: Some({ walletName: NONE, token: obj.payment_token, }), }), }) | SAVEDLISTWALLET(obj) => let walletType = obj.walletType->Option.getOr("")->SdkTypes.walletNameToTypeMapper setAllApiData({ ...allApiData, savedPaymentMethods: Some({ ...savedPaymentMethodContextObj, selectedPaymentMethod: Some({ walletName: walletType, token: obj.payment_token, }), }), }) | _ => () } | None => () } None }) allApiData.savedPaymentMethods == Loading ? <LoadingPmList /> : <ScrollView keyboardShouldPersistTaps=#handled> {listArr ->Array.mapWithIndex((item, i) => { <SaveCardsList.PaymentMethodListView key={i->Int.toString} pmObject={item} isButtomBorder={Some(listArr)->Option.getOr([])->Array.length - 1 === i ? false : true} savedCardCvv setSavedCardCvv setIsCvcValid /> }) ->React.array} </ScrollView> }
876
10,757
hyperswitch-client-core
src/pages/payment/SaveCardsList.res
.res
open ReactNative open Style module CVVComponent = { @react.component let make = (~savedCardCvv, ~setSavedCardCvv, ~isPaymentMethodSelected, ~cardScheme) => { let {component, dangerColor} = ThemebasedStyle.useThemeBasedStyle() React.useEffect1(() => { setSavedCardCvv(_ => None) None }, [isPaymentMethodSelected]) let (isCvcFocus, setIsCvcFocus) = React.useState(_ => false) let isCvcValid = isCvcFocus || savedCardCvv->Option.isNone ? true : savedCardCvv->Option.getOr("")->String.length > 0 && Validation.cvcNumberInRange(savedCardCvv->Option.getOr(""), cardScheme) let localeObject = GetLocale.useGetLocalObj() let errorMsgText = !isCvcValid ? Some(localeObject.inCompleteCVCErrorText) : None let onCvvChange = cvv => setSavedCardCvv(_ => Some(Validation.formatCVCNumber(cvv, cardScheme))) { isPaymentMethodSelected ? <> <View style={viewStyle( ~display=#flex, ~flexDirection=#row, ~alignItems=#center, ~paddingHorizontal=40.->dp, ~marginTop=10.->dp, (), )}> <View style={viewStyle(~width={50.->dp}, ())}> <TextWrapper text="CVC:" textType={ModalText} /> </View> <CustomInput state={isPaymentMethodSelected ? savedCardCvv->Option.getOr("") : ""} setState={isPaymentMethodSelected ? onCvvChange : _ => ()} placeholder="123" animateLabel="CVC" fontSize=12. keyboardType=#"number-pad" enableCrossIcon=false width={100.->dp} height=40. isValid={isPaymentMethodSelected ? isCvcValid : true} onFocus={() => { setIsCvcFocus(_ => true) }} onBlur={() => { setIsCvcFocus(_ => false) }} secureTextEntry=true textColor={isCvcValid ? component.color : dangerColor} iconRight=CustomIcon({ Validation.checkCardCVC(savedCardCvv->Option.getOr(""), cardScheme) ? <Icon name="cvvfilled" height=35. width=35. fill="black" /> : <Icon name="cvvempty" height=35. width=35. fill="black" /> }) /> </View> {errorMsgText->Option.isSome && isPaymentMethodSelected ? <ErrorText text=errorMsgText /> : React.null} </> : React.null } } } module PMWithNickNameComponent = { @react.component let make = (~pmDetails: SdkTypes.savedDataType) => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let nickName = switch pmDetails { | SAVEDLISTCARD(obj) => obj.nick_name | _ => None } let isDefaultPm = switch pmDetails { | SAVEDLISTCARD(obj) => obj.isDefaultPaymentMethod | SAVEDLISTWALLET(obj) => obj.isDefaultPaymentMethod | NONE => Some(false) }->Option.getOr(false) <View style={viewStyle(~display=#flex, ~flexDirection=#column, ())}> {switch nickName { | Some(val) => val != "" ? <View style={viewStyle(~display=#flex, ~flexDirection=#row, ~alignItems=#center, ())}> <TextWrapper text={val->String.length > 15 ? val->String.slice(~start=0, ~end=13)->String.concat("..") : val} textType={CardTextBold} /> <Space height=5. /> {nativeProp.configuration.displayDefaultSavedPaymentIcon && isDefaultPm ? <Icon name="defaultTick" height=14. width=14. fill="black" /> : React.null} </View> : React.null | None => React.null }} <View style={viewStyle(~display=#flex, ~flexDirection=#row, ~alignItems=#center, ())}> <Icon name={switch pmDetails { | SAVEDLISTCARD(obj) => obj.cardScheme | SAVEDLISTWALLET(obj) => obj.walletType | NONE => None }->Option.getOr("")} height=25. width=24. style={viewStyle(~marginEnd=5.->dp, ())} /> <TextWrapper text={switch pmDetails { | SAVEDLISTWALLET(obj) => obj.walletType | SAVEDLISTCARD(obj) => obj.cardNumber | NONE => None } ->Option.getOr("") ->String.replaceAll("*", "●")} textType={switch pmDetails { | SAVEDLISTWALLET(_) => CardTextBold | _ => CardText }} /> </View> </View> } } module PaymentMethodListView = { @react.component let make = ( ~pmObject: SdkTypes.savedDataType, ~isButtomBorder=true, ~savedCardCvv, ~setSavedCardCvv, ~setIsCvcValid, ) => { //~hashedCardNumber, ~expDate, ~selectedx let localeObj = GetLocale.useGetLocalObj() let (allApiData, setAllApiData) = React.useContext(AllApiDataContext.allApiDataContext) let savedPaymentMethordContextObj = switch allApiData.savedPaymentMethods { | Some(data) => data | _ => AllApiDataContext.dafaultsavePMObj } let checkAndProcessIfWallet = (~newToken) => { switch newToken { | None => setAllApiData({ ...allApiData, savedPaymentMethods: Some({ ...savedPaymentMethordContextObj, selectedPaymentMethod: None, }), }) | Some(_) => switch pmObject { | SdkTypes.SAVEDLISTCARD(_) => setAllApiData({ ...allApiData, savedPaymentMethods: Some({ ...savedPaymentMethordContextObj, selectedPaymentMethod: Some({ walletName: NONE, token: newToken, }), }), }) | SdkTypes.SAVEDLISTWALLET(obj) => { let walletType = obj.walletType->Option.getOr("")->SdkTypes.walletNameToTypeMapper setAllApiData({ ...allApiData, savedPaymentMethods: Some({ ...savedPaymentMethordContextObj, selectedPaymentMethod: Some({ walletName: walletType, token: newToken, }), }), }) } | _ => () } } } let {primaryColor, component} = ThemebasedStyle.useThemeBasedStyle() let pmToken = switch pmObject { | SdkTypes.SAVEDLISTCARD(obj) => obj.mandate_id->Option.isSome ? obj.mandate_id->Option.getOr("") : obj.payment_token->Option.getOr("") | SdkTypes.SAVEDLISTWALLET(obj) => obj.payment_token->Option.getOr("") | NONE => "" } let onPress = () => { checkAndProcessIfWallet(~newToken={Some(pmToken)}) } let preSelectedObj = savedPaymentMethordContextObj.selectedPaymentMethod->Option.getOr({ walletName: NONE, token: None, }) let isPaymentMethodSelected = switch preSelectedObj.token { | Some(val) => val == pmToken | None => false } let cardScheme = switch pmObject { | SdkTypes.SAVEDLISTCARD(card) => card.cardScheme->Option.getOr("") | _ => "NotCard" } React.useEffect2(() => { if isPaymentMethodSelected { setIsCvcValid(_ => switch cardScheme { | "NotCard" => true | _ => switch savedCardCvv { | Some(cvv) => cvv->String.length > 0 && Validation.cvcNumberInRange(cvv, cardScheme) | None => !(pmObject->PaymentUtils.checkIsCVCRequired) } } ) } None }, (isPaymentMethodSelected, savedCardCvv)) <CustomTouchableOpacity onPress={_ => { onPress() }} style={viewStyle( ~minHeight=60.->dp, ~paddingVertical=16.->dp, ~borderBottomWidth={isButtomBorder ? 1.0 : 0.}, ~borderBottomColor=component.borderColor, ~justifyContent=#center, (), )} activeOpacity=1.> <View style={viewStyle( ~flexDirection=#row, ~flexWrap=#wrap, ~alignItems=#center, ~justifyContent=#"space-between", (), )}> <View style={viewStyle(~flexDirection=#row, ~alignItems=#center, ~maxWidth=60.->pct, ())}> <CustomRadioButton size=20.5 selected=isPaymentMethodSelected color=primaryColor // selected={selectedToken->Option.isSome // ? selectedToken->Option.getOr("") == cardToken // : false} /> <Space /> <PMWithNickNameComponent pmDetails=pmObject /> </View> {switch pmObject { | SAVEDLISTCARD(obj) => <TextWrapper text={localeObj.cardExpiresText ++ " " ++ obj.expiry_date->Option.getOr("")} textType={ModalTextLight} /> | SAVEDLISTWALLET(_) | NONE => React.null }} </View> {pmObject->PaymentUtils.checkIsCVCRequired ? <CVVComponent savedCardCvv setSavedCardCvv isPaymentMethodSelected cardScheme /> : React.null} </CustomTouchableOpacity> } }
2,276
10,758
hyperswitch-client-core
src/pages/payment/SavedPaymentScreen.res
.res
open ReactNative @react.component let make = ( ~setConfirmButtonDataRef, ~savedPaymentMethordContextObj: AllApiDataContext.savedPaymentMethodDataObj, ) => { let (_, setPaymentScreenType) = React.useContext(PaymentScreenContext.paymentScreenTypeContext) let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let (_, setLoading) = React.useContext(LoadingContext.loadingContext) let (error, setError) = React.useState(_ => None) let handleSuccessFailure = AllPaymentHooks.useHandleSuccessFailure() let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let fetchAndRedirect = AllPaymentHooks.useRedirectHook() let {launchApplePay, launchGPay} = WebKit.useWebKit() // let (isAllDynamicFieldValid, setIsAllDynamicFieldValid) = React.useState(_ => true) // let (dynamicFieldsJson, setDynamicFieldsJson) = React.useState((_): array<( // RescriptCoreFuture.Dict.key, // JSON.t, // option<string>, // )> => []) let isCVVRequiredByAnyPm = (pmList: option<array<SdkTypes.savedDataType>>) => { pmList ->Option.getOr([]) ->Array.reduce(false, (accumulator, item) => accumulator || switch item { | SAVEDLISTCARD(obj) => obj.requiresCVV == true | _ => false } ) } let (isSaveCardCheckboxSelected, setSaveCardChecboxSelected) = React.useState(_ => false) let (showSavePMCheckbox, setShowSavePMCheckbox) = React.useState(_ => allApiData.additionalPMLData.mandateType == NEW_MANDATE && nativeProp.configuration.displaySavedPaymentMethodsCheckbox && isCVVRequiredByAnyPm(savedPaymentMethordContextObj.pmList) ) let (savedCardCvv, setSavedCardCvv) = React.useState(_ => None) let (isCvcValid, setIsCvcValid) = React.useState(_ => false) let logger = LoggerHook.useLoggerHook() let showAlert = AlertHook.useAlerts() let (buttomFlex, _) = React.useState(_ => Animated.Value.create(1.)) let savedPaymentMethodsData = switch allApiData.savedPaymentMethods { | Some(data) => data | _ => AllApiDataContext.dafaultsavePMObj } let animateFlex = (~flexval, ~value, ~endCallback=() => (), ()) => { Animated.timing( flexval, { toValue: {value->Animated.Value.Timing.fromRawValue}, isInteraction: true, useNativeDriver: false, delay: 0., }, )->Animated.start(~endCallback=_ => {endCallback()}, ()) } let (countryStateData, _) = React.useContext(CountryStateDataContext.countryStateDataContext) React.useEffect0(() => { setPaymentScreenType(SAVEDCARDSCREEN) None }) let processRequest = ( ~payment_method, ~payment_method_data, ~payment_method_type, ~email=?, (), ) => { let errorCallback = (~errorMessage, ~closeSDK, ()) => { logger( ~logType=INFO, ~value="", ~category=USER_EVENT, ~eventName=PAYMENT_FAILED, ~paymentMethod=payment_method_type, (), ) if !closeSDK { setLoading(FillingDetails) } handleSuccessFailure(~apiResStatus=errorMessage, ~closeSDK, ()) } let responseCallback = (~paymentStatus: LoadingContext.sdkPaymentState, ~status) => { logger( ~logType=INFO, ~value="", ~category=USER_EVENT, ~eventName=PAYMENT_DATA_FILLED, ~paymentMethod=payment_method_type, (), ) logger( ~logType=INFO, ~value="", ~category=USER_EVENT, ~eventName=PAYMENT_ATTEMPT, ~paymentMethod=payment_method_type, (), ) switch paymentStatus { | PaymentSuccess => { logger( ~logType=INFO, ~value="", ~category=USER_EVENT, ~eventName=PAYMENT_SUCCESS, ~paymentMethod=payment_method_type, (), ) setLoading(PaymentSuccess) animateFlex( ~flexval=buttomFlex, ~value=0.01, ~endCallback=() => { setTimeout(() => { handleSuccessFailure(~apiResStatus=status, ()) }, 600)->ignore }, (), ) } | _ => handleSuccessFailure(~apiResStatus=status, ()) } } let body: PaymentMethodListType.redirectType = { client_secret: nativeProp.clientSecret, return_url: ?Utils.getReturnUrl(~appId=nativeProp.hyperParams.appId, ~appURL=allApiData.additionalPMLData.redirect_url), ?email, payment_method, payment_method_type, payment_method_data, billing: ?nativeProp.configuration.defaultBillingDetails, shipping: ?nativeProp.configuration.shippingDetails, payment_type: ?allApiData.additionalPMLData.paymentType, customer_acceptance: ?( if ( allApiData.additionalPMLData.mandateType->PaymentUtils.checkIfMandate && !savedPaymentMethodsData.isGuestCustomer ) { Some({ acceptance_type: "online", accepted_at: Date.now()->Date.fromTime->Date.toISOString, online: { user_agent: ?nativeProp.hyperParams.userAgent, }, }) } else { None } ), browser_info: { user_agent: ?nativeProp.hyperParams.userAgent, device_model: ?nativeProp.hyperParams.device_model, os_type: ?nativeProp.hyperParams.os_type, os_version: ?nativeProp.hyperParams.os_version, }, } fetchAndRedirect( ~body=body->JSON.stringifyAny->Option.getOr(""), ~publishableKey=nativeProp.publishableKey, ~clientSecret=nativeProp.clientSecret, ~errorCallback, ~responseCallback, ~paymentMethod=payment_method_type, (), ) } let selectedObj = savedPaymentMethordContextObj.selectedPaymentMethod->Option.getOr({ walletName: NONE, token: Some(""), }) let confirmGPay = var => { let paymentData = var->PaymentConfirmTypes.itemToObjMapperJava switch paymentData.error { | "" => let json = paymentData.paymentMethodData->JSON.parseExn let obj = json ->Utils.getDictFromJson ->GooglePayTypeNew.itemToObjMapper( switch countryStateData { | FetchData(data) | Localdata(data) => data.states | _ => Dict.make() }, ) let payment_method_data = [ ( "wallet", [ ( selectedObj.walletName->SdkTypes.walletTypeToStrMapper, obj.paymentMethodData->Utils.getJsonObjectFromRecord, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ( "billing", switch obj.paymentMethodData.info { | Some(info) => switch info.billing_address { | Some(address) => address->Utils.getJsonObjectFromRecord | None => JSON.Encode.null } | None => JSON.Encode.null }, ), ] ->Dict.fromArray ->JSON.Encode.object processRequest( ~payment_method="wallet", ~payment_method_data, ~payment_method_type=selectedObj.walletName->SdkTypes.walletTypeToStrMapper, ~email=?obj.email, (), ) | "Cancel" => setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Payment was Cancelled") | err => setLoading(FillingDetails) showAlert(~errorType="error", ~message=err) } } let confirmApplePay = var => { switch var ->Dict.get("status") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.string ->Option.getOr("") { | "Cancelled" => setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Cancelled") | "Failed" => setLoading(FillingDetails) showAlert(~errorType="error", ~message="Failed") | "Error" => setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Error") | _ => let payment_data = var->Dict.get("payment_data")->Option.getOr(JSON.Encode.null) let payment_method = var->Dict.get("payment_method")->Option.getOr(JSON.Encode.null) let transaction_identifier = var->Dict.get("transaction_identifier")->Option.getOr(JSON.Encode.null) if ( transaction_identifier->Utils.getStringFromJson( "Simulated Identifier", ) == "Simulated Identifier" ) { setTimeout(() => { setLoading(FillingDetails) showAlert( ~errorType="warning", ~message="Apple Pay is not supported in Simulated Environment", ) }, 2000)->ignore } else { let paymentData = [ ("payment_data", payment_data), ("payment_method", payment_method), ("transaction_identifier", transaction_identifier), ] ->Dict.fromArray ->JSON.Encode.object let payment_method_data = [ ( "wallet", [(selectedObj.walletName->SdkTypes.walletTypeToStrMapper, paymentData)] ->Dict.fromArray ->JSON.Encode.object, ), ( "billing", switch var->GooglePayTypeNew.getBillingContact( "billing_contact", switch countryStateData { | FetchData(data) | Localdata(data) => data.states | _ => Dict.make() }, ) { | Some(billing) => billing->Utils.getJsonObjectFromRecord | None => JSON.Encode.null }, ), ] ->Dict.fromArray ->JSON.Encode.object processRequest( ~payment_method="wallet", ~payment_method_data, ~payment_method_type=selectedObj.walletName->SdkTypes.walletTypeToStrMapper, ~email=?switch var->GooglePayTypeNew.getBillingContact( "billing_contact", switch countryStateData { | FetchData(data) | Localdata(data) => data.states | _ => Dict.make() }, ) { | Some(billing) => billing.email | None => None }, (), ) } } } let confirmSamsungPay = ( status, billingDetails: option<SamsungPayType.addressCollectedFromSpay>, ) => { if status->ThreeDsUtils.isStatusSuccess { let response = status.message ->JSON.parseExn ->JSON.Decode.object ->Option.getOr(Dict.make()) let billingAddress = billingDetails->SamsungPayType.getAddressObj(BILLING_ADDRESS) let obj = SamsungPayType.itemToObjMapper(response) let payment_method_data = [ ( "wallet", [ ( selectedObj.walletName->SdkTypes.walletTypeToStrMapper, obj->Utils.getJsonObjectFromRecord, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ( "billing", switch billingAddress { | Some(address) => address->Utils.getJsonObjectFromRecord | None => JSON.Encode.null }, ), ] ->Dict.fromArray ->JSON.Encode.object processRequest( ~payment_method="wallet", ~payment_method_data, ~payment_method_type=selectedObj.walletName->SdkTypes.walletTypeToStrMapper, ~email=?switch billingAddress { | Some(address) => address.email | None => None }, (), ) } else { setLoading(FillingDetails) showAlert( ~errorType="warning", ~message=`Samsung Pay Error, Please try again ${status.message}`, ) } logger( ~logType=INFO, ~value=`SPAY result from native ${status.status->JSON.stringifyAny->Option.getOr("")}`, ~category=USER_EVENT, ~eventName=SAMSUNG_PAY, (), ) } React.useEffect1(() => { switch selectedObj.walletName { | APPLE_PAY => Window.registerEventListener("applePayData", confirmApplePay) | GOOGLE_PAY => Window.registerEventListener("googlePayData", confirmGPay) | _ => () } None }, [selectedObj.walletName]) let processSavedPMRequest = () => { let errorCallback = (~errorMessage: PaymentConfirmTypes.error, ~closeSDK, ()) => { if !closeSDK { setLoading(FillingDetails) switch errorMessage.message { | Some(message) => setError(_ => Some(message)) | None => () } } handleSuccessFailure(~apiResStatus=errorMessage, ~closeSDK, ()) } let responseCallback = (~paymentStatus: LoadingContext.sdkPaymentState, ~status) => { switch paymentStatus { | PaymentSuccess => { setLoading(PaymentSuccess) setTimeout(() => { handleSuccessFailure(~apiResStatus=status, ()) }, 300)->ignore } | _ => handleSuccessFailure(~apiResStatus=status, ()) } } let sessionObject = switch allApiData.sessions { | Some(sessionData) => sessionData ->Array.find(item => item.wallet_name == selectedObj.walletName) ->Option.getOr(SessionsType.defaultToken) | _ => SessionsType.defaultToken } switch selectedObj.walletName { | GOOGLE_PAY => if WebKit.platform === #android { HyperModule.launchGPay( GooglePayTypeNew.getGpayTokenStringified(~obj=sessionObject, ~appEnv=nativeProp.env), confirmGPay, ) } else { launchGPay( GooglePayTypeNew.getGpayTokenStringified(~obj=sessionObject, ~appEnv=nativeProp.env), ) } | APPLE_PAY => if WebKit.platform === #ios { let timerId = setTimeout(() => { setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Apple Pay Error, Please try again") logger( ~logType=DEBUG, ~value="apple_pay", ~category=USER_EVENT, ~paymentMethod="apple_pay", ~eventName=APPLE_PAY_PRESENT_FAIL_FROM_NATIVE, (), ) }, 5000) HyperModule.launchApplePay( [ ("session_token_data", sessionObject.session_token_data), ("payment_request_data", sessionObject.payment_request_data), ] ->Dict.fromArray ->JSON.Encode.object ->JSON.stringify, confirmApplePay, _ => { logger( ~logType=DEBUG, ~value="apple_pay", ~category=USER_EVENT, ~paymentMethod="apple_pay", ~eventName=APPLE_PAY_BRIDGE_SUCCESS, (), ) }, _ => { clearTimeout(timerId) }, ) } else { launchApplePay( [ ("session_token_data", sessionObject.session_token_data), ("payment_request_data", sessionObject.payment_request_data), ] ->Dict.fromArray ->JSON.Encode.object ->JSON.stringify, ) } | SAMSUNG_PAY => { logger( ~logType=INFO, ~value="Samsung Pay Button Clicked", ~category=USER_EVENT, ~eventName=SAMSUNG_PAY, (), ) SamsungPayModule.presentSamsungPayPaymentSheet(confirmSamsungPay) } | NONE => let (body, paymentMethodType) = ( PaymentUtils.generateSavedCardConfirmBody( ~nativeProp, ~payment_token=selectedObj.token->Option.getOr(""), ~savedCardCvv, ), "card", ) // let paymentBodyWithDynamicFields = PaymentMethodListType.getPaymentBody( // body, // dynamicFieldsJson, // ) let paymentBodyWithDynamicFields = body fetchAndRedirect( ~body=paymentBodyWithDynamicFields->JSON.stringifyAny->Option.getOr(""), ~publishableKey=nativeProp.publishableKey, ~clientSecret=nativeProp.clientSecret, ~errorCallback, ~responseCallback, ~paymentMethod=paymentMethodType, (), ) | _ => let (body, paymentMethodType) = ( PaymentUtils.generateWalletConfirmBody( ~nativeProp, ~payment_method_type=selectedObj.walletName->SdkTypes.walletTypeToStrMapper, ~payment_token=selectedObj.token->Option.getOr(""), ), "wallet", ) // let paymentBodyWithDynamicFields = PaymentMethodListType.getPaymentBody( // body, // dynamicFieldsJson, // ) let paymentBodyWithDynamicFields = body fetchAndRedirect( ~body=paymentBodyWithDynamicFields->JSON.stringifyAny->Option.getOr(""), ~publishableKey=nativeProp.publishableKey, ~clientSecret=nativeProp.clientSecret, ~errorCallback, ~responseCallback, ~paymentMethod=paymentMethodType, (), ) } } let handlePress = _ => { setLoading(ProcessingPayments(None)) processSavedPMRequest() } React.useEffect5(() => { setShowSavePMCheckbox(_ => allApiData.additionalPMLData.mandateType == NEW_MANDATE && nativeProp.configuration.displaySavedPaymentMethodsCheckbox && isCVVRequiredByAnyPm(savedPaymentMethordContextObj.pmList) ) let selectedObj = savedPaymentMethordContextObj.selectedPaymentMethod->Option.getOr({ walletName: NONE, token: Some(""), }) let paymentMethod = switch selectedObj.walletName { | NONE => "card" | wallet => wallet->SdkTypes.walletTypeToStrMapper } setConfirmButtonDataRef( <ConfirmButton loading=false isAllValuesValid={savedPaymentMethordContextObj.selectedPaymentMethod->Option.isSome && allApiData.additionalPMLData.paymentType->Option.isSome && isCvcValid} handlePress hasSomeFields=false paymentMethod errorText=error />, ) None }, ( savedPaymentMethordContextObj.selectedPaymentMethod, allApiData, isSaveCardCheckboxSelected, error, isCvcValid, )) <SavedPaymentScreenChild savedPaymentMethodsData={savedPaymentMethordContextObj.pmList->Option.getOr([])} isSaveCardCheckboxSelected setSaveCardChecboxSelected showSavePMCheckbox merchantName={nativeProp.configuration.merchantDisplayName == "" ? allApiData.additionalPMLData.merchantName->Option.getOr("") : nativeProp.configuration.merchantDisplayName} savedCardCvv setSavedCardCvv setIsCvcValid /> }
4,170
10,759
hyperswitch-client-core
src/pages/payment/Redirect.res
.res
open ReactNative open PaymentMethodListType open CustomPicker open RequiredFieldsTypes type klarnaSessionCheck = { isKlarna: bool, session_token: string, } @react.component let make = ( ~redirectProp: payment_method, ~fields: Types.redirectTypeJson, ~isScreenFocus, ~isDynamicFields: bool=false, ~dynamicFields: required_fields=[], ~setConfirmButtonDataRef: React.element => unit, ~sessionObject: SessionsType.sessions=SessionsType.defaultToken, ) => { let walletType: PaymentMethodListType.payment_method_types_wallet = switch redirectProp { | WALLET(walletVal) => walletVal | _ => { payment_method: "", payment_method_type: "", payment_method_type_wallet: NONE, payment_experience: [], required_field: [], } } let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let (launchKlarna, setLaunchKlarna) = React.useState(_ => None) let (email, setEmail) = React.useState(_ => None) let (isEmailValid, setIsEmailValid) = React.useState(_ => None) let (emailIsFocus, setEmailIsFocus) = React.useState(_ => false) let (name, setName) = React.useState(_ => None) let (isNameValid, setIsNameValid) = React.useState(_ => None) let (nameIsFocus, setNameIsFocus) = React.useState(_ => false) let (isAllDynamicFieldValid, setIsAllDynamicFieldValid) = React.useState(_ => false) let (dynamicFieldsJson, setDynamicFieldsJson) = React.useState((_): dict<( JSON.t, option<string>, )> => Dict.make()) let (keyToTrigerButtonClickError, setKeyToTrigerButtonClickError) = React.useState(_ => 0) let (country, setCountry) = React.useState(_ => Some(nativeProp.hyperParams.country)) let (blikCode, setBlikCode) = React.useState(_ => None) let showAlert = AlertHook.useAlerts() let bankName = switch redirectProp { | BANK_REDIRECT(prop) => prop.bank_names | _ => [] } let getBankNames = bankNames => { bankNames ->Array.map(x => { x.bank_name }) ->Array.reduce([], (acc, item) => { acc->Array.concat(item) }) ->Array.map(x => { x->JSON.parseExn->JSON.Decode.string->Option.getOr("") }) } let paymentMethod = switch redirectProp { | CARD(prop) => prop.payment_method_type | WALLET(prop) => prop.payment_method_type | PAY_LATER(prop) => prop.payment_method_type | BANK_REDIRECT(prop) => prop.payment_method_type | CRYPTO(prop) => prop.payment_method_type | OPEN_BANKING(prop) => prop.payment_method_type | BANK_DEBIT(prop) => prop.payment_method_type } let bankDebitPMType = switch redirectProp { | BANK_DEBIT(prop) => prop.payment_method_type_var | _ => Other } let paymentExperience = switch redirectProp { | CARD(_) | BANK_REDIRECT(_) => None | WALLET(prop) => prop.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.payment_experience_type_decode) | PAY_LATER(prop) => prop.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.payment_experience_type_decode) | OPEN_BANKING(prop) => prop.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.payment_experience_type_decode) | CRYPTO(prop) => prop.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.payment_experience_type_decode) | BANK_DEBIT(prop) => prop.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.payment_experience_type_decode) } let paymentMethodType = switch redirectProp { | BANK_REDIRECT(prop) => prop.payment_method_type | _ => "" } let bankList = switch paymentMethodType { | "ideal" => getBankNames(bankName)->Js.Array.sortInPlace | "eps" => getBankNames(bankName)->Js.Array.sortInPlace | _ => [] } let bankItems = Bank.bankNameConverter(bankList) let bankData: array<customPickerType> = bankItems->Array.map(item => { { label: item.displayName, value: item.hyperSwitch, } }) let (statesAndCountry, _) = React.useContext(CountryStateDataContext.countryStateDataContext) let countryData: array<customPickerType> = switch statesAndCountry { | Localdata(data) | FetchData(data) => data.countries->Array.map(item => { { label: item.label != "" ? item.label ++ " - " ++ item.value : item.value, value: item.isoAlpha2, icon: Utils.getCountryFlags(item.isoAlpha2), } }) | _ => [] } let (selectedBank, setSelectedBank) = React.useState(_ => Some( switch bankItems->Array.get(0) { | Some(x) => x.hyperSwitch | _ => "" }, )) let logger = LoggerHook.useLoggerHook() let onChangeCountry = val => { setCountry(val) logger( ~logType=INFO, ~value=country->Option.getOr(""), ~category=USER_EVENT, ~eventName=COUNTRY_CHANGED, ~paymentMethod, ~paymentExperience=getPaymentExperienceType(paymentExperience->Option.getOr(NONE)), (), ) } let onChangeBank = val => { setSelectedBank(val) } let onChangeBlikCode = (val: string) => { let onlyNumerics = val->String.replaceRegExp(%re("/\D+/g"), "") let firstPart = onlyNumerics->String.slice(~start=0, ~end=3) let secondPart = onlyNumerics->String.slice(~start=3, ~end=6) let finalVal = if onlyNumerics->String.length <= 3 { firstPart } else if onlyNumerics->String.length > 3 && onlyNumerics->String.length <= 6 { `${firstPart}-${secondPart}` } else { onlyNumerics } setBlikCode(_ => Some(finalVal)) } let (error, setError) = React.useState(_ => None) let handleSuccessFailure = AllPaymentHooks.useHandleSuccessFailure() let fetchAndRedirect = AllPaymentHooks.useRedirectHook() let localeObject = GetLocale.useGetLocalObj() let {component, borderWidth, borderRadius} = ThemebasedStyle.useThemeBasedStyle() let (_, setLoading) = React.useContext(LoadingContext.loadingContext) let {isKlarna, session_token} = React.useMemo1(() => { switch allApiData.sessions { | Some(sessionData) => switch sessionData->Array.find(item => item.wallet_name == KLARNA) { | Some(tok) => {isKlarna: tok.wallet_name === KLARNA, session_token: tok.session_token} | None => {isKlarna: false, session_token: ""} } | _ => {isKlarna: false, session_token: ""} } }, [allApiData.sessions]) let errorCallback = (~errorMessage: PaymentConfirmTypes.error, ~closeSDK, ()) => { if !closeSDK { setLoading(FillingDetails) switch errorMessage.message { | Some(message) => setError(_ => Some(message)) | None => () } } handleSuccessFailure(~apiResStatus=errorMessage, ~closeSDK, ()) } let responseCallback = (~paymentStatus: LoadingContext.sdkPaymentState, ~status) => { switch paymentStatus { | PaymentSuccess => { setLoading(PaymentSuccess) setTimeout(() => { handleSuccessFailure(~apiResStatus=status, ()) }, 300)->ignore } | _ => handleSuccessFailure(~apiResStatus=status, ()) } /* setLoading(PaymentSuccess) animateFlex( ~flexval=buttomFlex, ~value=0.01, ~endCallback=() => { setTimeout(() => { handleSuccessFailure(~apiResStatus=status, ()) }, 300)->ignore }, (), ) */ } let processRequest = ( ~payment_method_data, ~payment_method, ~payment_method_type, ~payment_experience_type="redirect_to_url", ~eligible_connectors=?, ~shipping=?, (), ) => { let body: redirectType = { client_secret: nativeProp.clientSecret, return_url: ?Utils.getReturnUrl(~appId=nativeProp.hyperParams.appId, ~appURL=allApiData.additionalPMLData.redirect_url), payment_method, payment_method_type, payment_experience: payment_experience_type, connector: ?eligible_connectors, payment_method_data, billing: ?nativeProp.configuration.defaultBillingDetails, shipping: shipping->Option.getOr( nativeProp.configuration.shippingDetails->Option.getOr({ phone: None, address: None, email: None, }), ), setup_future_usage: ?( allApiData.additionalPMLData.mandateType != NORMAL ? Some("off_session") : None ), payment_type: ?allApiData.additionalPMLData.paymentType, // mandate_data: ?( // allApiData.additionalPMLData.mandateType != NORMAL // ? Some({ // customer_acceptance: { // acceptance_type: "offline", // accepted_at: Date.now()->Date.fromTime->Date.toISOString, // online: { // ip_address: ?nativeProp.hyperParams.ip, // user_agent: ?nativeProp.hyperParams.userAgent, // }, // }, // }) // : None // ), customer_acceptance: ?( allApiData.additionalPMLData.mandateType->PaymentUtils.checkIfMandate ? Some({ acceptance_type: "online", accepted_at: Date.now()->Date.fromTime->Date.toISOString, online: { user_agent: ?nativeProp.hyperParams.userAgent, }, }) : None ), browser_info: { user_agent: ?nativeProp.hyperParams.userAgent, language: ?nativeProp.configuration.appearance.locale, device_model: ?nativeProp.hyperParams.device_model, os_type: ?nativeProp.hyperParams.os_type, os_version: ?nativeProp.hyperParams.os_version, // TODO: Remove these hardcoded values and get actual values from web-view (iOS and android) // accept_header: "", // color_depth: 0, // java_enabled: true, // java_script_enabled: true, // screen_height: 932, // screen_width: 430, // time_zone: -330, }, } fetchAndRedirect( ~body=body->JSON.stringifyAny->Option.getOr(""), ~publishableKey=nativeProp.publishableKey, ~clientSecret=nativeProp.clientSecret, ~errorCallback, ~responseCallback, ~paymentMethod, ~paymentExperience=getPaymentExperienceType(paymentExperience->Option.getOr(NONE)), (), ) } let processRequestPayLater = (prop: payment_method_types_pay_later, authToken) => { let payment_experience_type_decode = authToken == "redirect" ? REDIRECT_TO_URL : INVOKE_SDK_CLIENT switch prop.payment_experience->Array.find(exp => exp.payment_experience_type_decode === payment_experience_type_decode ) { | Some(exp) => let dynamicFieldsArray = dynamicFieldsJson->Dict.toArray let dynamicFieldsJsonDict = dynamicFieldsArray->Array.reduce(Dict.make(), ( acc, (key, (val, _)), ) => { acc->Dict.set(key, val) acc }) let redirectData = if isDynamicFields { [ ( "billing_email", dynamicFieldsArray ->Array.find(((key, _)) => key->String.includes("email") == true) ->Option.map(((_, (value, _))) => value) ->Option.getOr(""->JSON.Encode.string), ), ( "billing_name", dynamicFieldsArray ->Array.find(((key, _)) => key->String.includes("first_name") == true) ->Option.map(((_, (value, _))) => value->JSON.Decode.string->Option.getOr("")) ->Option.getOr("") ->String.concat(" ") ->String.concat( dynamicFieldsArray ->Array.find(((key, _)) => key->String.includes("last_name") == true) ->Option.map(((_, (value, _))) => value->JSON.Decode.string->Option.getOr("")) ->Option.getOr(""), ) ->JSON.Encode.string, ), ( "billing_country", dynamicFieldsArray ->Array.find(((key, _)) => key->String.includes("country") == true) ->Option.map(((_, (value, _))) => value) ->Option.getOr(""->JSON.Encode.string), ), ] ->Dict.fromArray ->JSON.Encode.object } else { [ ("billing_email", email->Option.getOr("")->JSON.Encode.string), ("billing_name", name->Option.getOr("")->JSON.Encode.string), ("billing_country", country->Option.getOr("")->JSON.Encode.string), ] ->Dict.fromArray ->JSON.Encode.object } let sdkData = [("token", authToken->JSON.Encode.string)]->Dict.fromArray->JSON.Encode.object // let payment_method_data = // [ // ( // prop.payment_method, // [ // ( // prop.payment_method_type ++ (authToken == "redirect" ? "_redirect" : "_sdk"), // authToken == "redirect" ? redirectData : sdkData, // ), // ] // ->Dict.fromArray // ->JSON.Encode.object, // ), // ] // ->Dict.fromArray // ->JSON.Encode.object let payment_method_data = Dict.make() let innerData = Dict.make() innerData->Dict.set( prop.payment_method_type ++ (authToken == "redirect" ? "_redirect" : "_sdk"), authToken == "redirect" ? redirectData : sdkData, ) let middleData = Dict.make() middleData->Dict.set(prop.payment_method, innerData->JSON.Encode.object) payment_method_data->Dict.set("payment_method_data", middleData->JSON.Encode.object) let dynamic_pmd = payment_method_data->mergeTwoFlattenedJsonDicts(dynamicFieldsJsonDict) processRequest( ~payment_method_data=dynamic_pmd ->Utils.getJsonObjectFromDict("payment_method_data") ->JSON.stringifyAny ->Option.getOr("{}") ->JSON.parseExn, ~payment_method=prop.payment_method, ~payment_method_type=prop.payment_method_type, ~payment_experience_type=exp.payment_experience_type, (), ) | None => logger( ~logType=DEBUG, ~value=walletType.payment_method_type, ~category=USER_EVENT, ~paymentMethod=walletType.payment_method_type, ~eventName=NO_WALLET_ERROR, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Payment Method Unavailable") } } let processRequestBankRedirect = (prop: payment_method_types_bank_redirect) => { let payment_method_data = [ ( prop.payment_method, [ ( prop.payment_method_type, [ ( "country", switch country { | Some(country) => country != "" ? country->JSON.Encode.string : JSON.Encode.null | _ => JSON.Encode.null }, ), ("bank_name", selectedBank->Option.getOr("")->JSON.Encode.string), ( "blik_code", blikCode->Option.getOr("")->String.replace("-", "")->JSON.Encode.string, ), ("preferred_language", "en"->JSON.Encode.string), ( "billing_details", [("billing_name", name->Option.getOr("")->JSON.Encode.string)] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object processRequest( ~payment_method_data, ~payment_method=prop.payment_method, ~payment_method_type=prop.payment_method_type, (), ) } let processRequestCrypto = (prop: payment_method_types_pay_later) => { let payment_method_data = [(prop.payment_method, []->Dict.fromArray->JSON.Encode.object)] ->Dict.fromArray ->JSON.Encode.object processRequest( ~payment_method_data, ~payment_method=prop.payment_method, ~payment_method_type=prop.payment_method_type, ~eligible_connectors=?prop.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.eligible_connectors), (), ) } let confirmPayPal = var => { let paymentData = var->PaymentConfirmTypes.itemToObjMapperJava switch paymentData.error { | "" => let json = paymentData.paymentMethodData->JSON.Encode.string let paymentData = [("token", json)]->Dict.fromArray->JSON.Encode.object let payment_method_data = [ ( walletType.payment_method, [(walletType.payment_method_type ++ "_sdk", paymentData)] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object processRequest( ~payment_method=walletType.payment_method, ~payment_method_data, ~payment_method_type=paymentMethod, ~payment_experience_type=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.payment_experience_type), ~eligible_connectors=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.eligible_connectors), (), ) | "User has canceled" => setLoading(FillingDetails) setError(_ => Some("Payment was Cancelled")) | err => setError(_ => Some(err)) } } let (countryStateData, _) = React.useContext(CountryStateDataContext.countryStateDataContext) let confirmGPay = var => { let paymentData = var->PaymentConfirmTypes.itemToObjMapperJava switch paymentData.error { | "" => let json = paymentData.paymentMethodData->JSON.parseExn let obj = json ->Utils.getDictFromJson ->GooglePayTypeNew.itemToObjMapper( switch countryStateData { | FetchData(data) | Localdata(data) => data.states | _ => Dict.make() }, ) let payment_method_data = [ ( walletType.payment_method, [(walletType.payment_method_type, obj.paymentMethodData->Utils.getJsonObjectFromRecord)] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object processRequest( ~payment_method=walletType.payment_method, ~payment_method_data, ~payment_method_type=paymentMethod, ~payment_experience_type=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.payment_experience_type), ~eligible_connectors=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.eligible_connectors), (), ) | "Cancel" => setLoading(FillingDetails) setError(_ => Some("Payment was Cancelled")) | err => setLoading(FillingDetails) setError(_ => Some(err)) } } let confirmApplePay = var => { switch var ->Dict.get("status") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.string ->Option.getOr("") { | "Cancelled" => setLoading(FillingDetails) setError(_ => Some("Cancelled")) | "Failed" => setLoading(FillingDetails) setError(_ => Some("Failed")) | "Error" => setLoading(FillingDetails) setError(_ => Some("Error")) | _ => let transaction_identifier = var->Dict.get("transaction_identifier")->Option.getOr(JSON.Encode.null) if transaction_identifier->JSON.stringify == "Simulated Identifier" { setLoading(FillingDetails) setError(_ => Some("Apple Pay is not supported in Simulated Environment")) } else { let payment_data = var->Dict.get("payment_data")->Option.getOr(JSON.Encode.null) let payment_method = var->Dict.get("payment_method")->Option.getOr(JSON.Encode.null) let billingAddress = var->GooglePayTypeNew.getBillingContact( "billing_contact", switch countryStateData { | FetchData(data) | Localdata(data) => data.states | _ => Dict.make() }, ) let shippingAddress = var->GooglePayTypeNew.getBillingContact( "shipping_contact", switch countryStateData { | FetchData(data) | Localdata(data) => data.states | _ => Dict.make() }, ) let paymentData = [ ("payment_data", payment_data), ("payment_method", payment_method), ("transaction_identifier", transaction_identifier), ] ->Dict.fromArray ->JSON.Encode.object let payment_method_data = walletType.required_field ->GooglePayTypeNew.getFlattenData(~shippingAddress, ~billingAddress) ->JSON.Encode.object ->RequiredFieldsTypes.unflattenObject ->Dict.get("payment_method_data") ->Option.getOr(JSON.Encode.null) ->Utils.getDictFromJson payment_method_data->Dict.set( walletType.payment_method, [(walletType.payment_method_type, paymentData)] ->Dict.fromArray ->JSON.Encode.object, ) processRequest( ~payment_method=walletType.payment_method, ~payment_method_data=payment_method_data->JSON.Encode.object, ~payment_method_type=paymentMethod, ~payment_experience_type=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.payment_experience_type), ~eligible_connectors=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.eligible_connectors), (), ) } } } let processRequestWallet = (walletType: payment_method_types_wallet) => { // let payment_method_data = // [ // ( // prop.payment_method, // [ // ( // prop.payment_method_type ++ "_redirect", // [ // //Telephone number is for MB Way // // ( // // "telephone_number", // // phoneNumber // // ->Option.getOr("") // // ->String.replaceString(" ", "") // // ->JSON.Encode.string, // // ), // ] // ->Dict.fromArray // ->JSON.Encode.object, // ), // ] // ->Dict.fromArray // ->JSON.Encode.object, // ), // ] // ->Dict.fromArray // ->JSON.Encode.object // processRequest( // ~payment_method_data, // ~payment_method=prop.payment_method, // ~payment_method_type=prop.payment_method_type, // // connector: prop.bank_namesArray.get(0).eligible_connectors, // // setup_future_usage:"off_session", // (), // ) setLoading(ProcessingPayments(None)) logger( ~logType=INFO, ~value=walletType.payment_method_type, ~category=USER_EVENT, ~paymentMethod=walletType.payment_method_type, ~eventName=PAYMENT_METHOD_CHANGED, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) if ( walletType.payment_experience ->Array.find(exp => exp.payment_experience_type_decode == INVOKE_SDK_CLIENT) ->Option.isSome ) { switch walletType.payment_method_type_wallet { | GOOGLE_PAY => HyperModule.launchGPay( GooglePayTypeNew.getGpayTokenStringified(~obj=sessionObject, ~appEnv=nativeProp.env), confirmGPay, ) | PAYPAL => if ( sessionObject.session_token !== "" && WebKit.platform == #android && PaypalModule.payPalModule->Option.isSome ) { PaypalModule.launchPayPal(sessionObject.session_token, confirmPayPal) } else if ( walletType.payment_experience ->Array.find(exp => exp.payment_experience_type_decode == REDIRECT_TO_URL) ->Option.isSome ) { let redirectData = []->Dict.fromArray->JSON.Encode.object let payment_method_data = [ ( walletType.payment_method, [(walletType.payment_method_type ++ "_redirect", redirectData)] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object let altPaymentExperience = walletType.payment_experience->Array.find(x => x.payment_experience_type_decode === REDIRECT_TO_URL ) let walletTypeAlt = { ...walletType, payment_experience: [ altPaymentExperience->Option.getOr({ payment_experience_type: "", payment_experience_type_decode: NONE, eligible_connectors: [], }), ], } // when session token for paypal is absent, switch to redirect flow processRequest( ~payment_method=walletType.payment_method, ~payment_method_data, ~payment_method_type=paymentMethod, ~payment_experience_type=?walletTypeAlt.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.payment_experience_type), ~eligible_connectors=?walletTypeAlt.payment_experience ->Array.get(0) ->Option.map(paymentExperience => paymentExperience.eligible_connectors), (), ) } | APPLE_PAY => if ( sessionObject.session_token_data == JSON.Encode.null || sessionObject.payment_request_data == JSON.Encode.null ) { setLoading(FillingDetails) setError(_ => Some("Waiting for Sessions API")) } else { let timerId = setTimeout(() => { setLoading(FillingDetails) setError(_ => Some("Apple Pay Error, Please try again")) logger( ~logType=DEBUG, ~value="apple_pay", ~category=USER_EVENT, ~paymentMethod="apple_pay", ~eventName=APPLE_PAY_PRESENT_FAIL_FROM_NATIVE, (), ) }, 5000) HyperModule.launchApplePay( [ ("session_token_data", sessionObject.session_token_data), ("payment_request_data", sessionObject.payment_request_data), ] ->Dict.fromArray ->JSON.Encode.object ->JSON.stringify, confirmApplePay, _ => { logger( ~logType=DEBUG, ~value="apple_pay", ~category=USER_EVENT, ~paymentMethod="apple_pay", ~eventName=APPLE_PAY_BRIDGE_SUCCESS, (), ) }, _ => { clearTimeout(timerId) }, ) } | _ => setLoading(FillingDetails) } } else if ( walletType.payment_experience ->Array.find(exp => exp.payment_experience_type_decode == REDIRECT_TO_URL) ->Option.isSome ) { let redirectData = []->Dict.fromArray->JSON.Encode.object let payment_method_data = [ ( walletType.payment_method, [(walletType.payment_method_type ++ "_redirect", redirectData)] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object processRequest( ~payment_method=walletType.payment_method, ~payment_method_data, ~payment_method_type=paymentMethod, (), ) } else { logger( ~logType=DEBUG, ~value=walletType.payment_method_type, ~category=USER_EVENT, ~paymentMethod=walletType.payment_method_type, ~eventName=NO_WALLET_ERROR, ~paymentExperience=?walletType.payment_experience ->Array.get(0) ->Option.map(paymentExperience => getPaymentExperienceType(paymentExperience.payment_experience_type_decode) ), (), ) setLoading(FillingDetails) showAlert(~errorType="warning", ~message="Payment Method Unavailable") } } let processRequestOpenBanking = (prop: payment_method_types_open_banking) => { let payment_method_data = [ ( prop.payment_method, [ ( prop.payment_method_type, [] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object processRequest( ~payment_method_data, ~payment_method=prop.payment_method, ~payment_method_type=prop.payment_method_type, (), ) } let processRequestBankDebit = (prop: payment_method_types_bank_debit) => { let dynamicFieldsArray = dynamicFieldsJson->Dict.toArray let dynamicFieldsJsonDict = dynamicFieldsArray->Array.reduce(Dict.make(), ( acc, (key, (val, _)), ) => { acc->Dict.set(key, val) acc }) let payment_method_data = dynamicFieldsJsonDict->JSON.Encode.object->unflattenObject processRequest( ~payment_method_data=payment_method_data ->Utils.getJsonObjectFromDict("payment_method_data") ->JSON.stringifyAny ->Option.getOr("{}") ->JSON.parseExn, ~payment_method=prop.payment_method, ~payment_method_type=prop.payment_method_type, (), ) } //need refactoring let handlePressEmail = text => { setIsEmailValid(_ => text->EmailValidation.isEmailValid) setEmail(_ => Some(text)) } let handlePressName = text => { let y = if text->String.length >= 3 { Some(true) } else { None } setIsNameValid(_ => y) setName(_ => Some(text)) } let isEmailValidForFocus = { emailIsFocus ? true : isEmailValid->Option.getOr(true) } let isNameValidForFocus = { nameIsFocus ? true : isNameValid->Option.getOr(true) } let hasSomeFields = fields.fields->Array.length > 0 let isAllValuesValid = React.useMemo(() => // need dynamic fields isDynamicFields ? isAllDynamicFieldValid : ((fields.fields->Array.includes("email") ? isEmailValid->Option.getOr(false) : true) && ( fields.fields->Array.includes("name") ? isNameValid->Option.getOr(false) : true )) || (fields.name == "klarna" && isKlarna) , ( isEmailValid, isNameValid, allApiData.sessions, isDynamicFields, isAllDynamicFieldValid, dynamicFieldsJson, )) let handlePress = _ => { if isAllValuesValid { setLoading(ProcessingPayments(None)) setKeyToTrigerButtonClickError(prev => prev + 1) switch redirectProp { | PAY_LATER(prop) => fields.name == "klarna" && isKlarna ? setLaunchKlarna(_ => Some(prop)) : processRequestPayLater(prop, "redirect") | BANK_REDIRECT(prop) => processRequestBankRedirect(prop) | CRYPTO(prop) => processRequestCrypto(prop) | WALLET(prop) => processRequestWallet(prop) | OPEN_BANKING(prop) => processRequestOpenBanking(prop) | BANK_DEBIT(prop) => processRequestBankDebit(prop) | _ => () } } else { setKeyToTrigerButtonClickError(prev => prev + 1) } } React.useEffect(() => { if isScreenFocus { setConfirmButtonDataRef( <ConfirmButton loading=false isAllValuesValid=true handlePress hasSomeFields paymentMethod paymentExperience={getPaymentExperienceType(paymentExperience->Option.getOr(NONE))} errorText=error />, ) } None }, ( isAllValuesValid, hasSomeFields, paymentMethod, paymentExperience, isScreenFocus, error, blikCode, name, email, country, selectedBank, )) <> <ErrorBoundary level={FallBackScreen.Screen} rootTag=nativeProp.rootTag> <UIUtils.RenderIf condition={fields.header->String.length > 0}> <TextWrapper text={fields.header} textType=Subheading /> </UIUtils.RenderIf> {KlarnaModule.klarnaReactPaymentView->Option.isSome && fields.name == "klarna" && isKlarna ? <> <Space /> <Klarna launchKlarna processRequest=processRequestPayLater return_url=Utils.getReturnUrl(~appId=nativeProp.hyperParams.appId, ~appURL=allApiData.additionalPMLData.redirect_url) klarnaSessionTokens=session_token /> <ErrorText text=error /> </> : <> {if isDynamicFields { <DynamicFields requiredFields=dynamicFields setIsAllDynamicFieldValid setDynamicFieldsJson keyToTrigerButtonClickError savedCardsData=None paymentMethodType={bankDebitPMType} /> } else { fields.fields ->Array.mapWithIndex((field, index) => <View key={`field-${fields.text}${index->Int.toString}`}> <Space /> {switch field { | "email" => <CustomInput state={email->Option.getOr("")} setState={handlePressEmail} placeholder=localeObject.emailLabel keyboardType=#"email-address" borderBottomLeftRadius=borderRadius borderBottomRightRadius=borderRadius borderTopLeftRadius=borderRadius borderTopRightRadius=borderRadius borderTopWidth=borderWidth borderBottomWidth=borderWidth borderLeftWidth=borderWidth borderRightWidth=borderWidth isValid=isEmailValidForFocus onFocus={_ => { setEmailIsFocus(_ => true) }} onBlur={_ => { setEmailIsFocus(_ => false) }} textColor=component.color /> | "name" => <CustomInput state={name->Option.getOr("")} setState={handlePressName} placeholder=localeObject.fullNameLabel keyboardType=#default isValid=isNameValidForFocus onFocus={_ => { setNameIsFocus(_ => true) }} onBlur={_ => { setNameIsFocus(_ => false) }} textColor=component.color borderBottomLeftRadius=borderRadius borderBottomRightRadius=borderRadius borderTopLeftRadius=borderRadius borderTopRightRadius=borderRadius borderTopWidth=borderWidth borderBottomWidth=borderWidth borderLeftWidth=borderWidth borderRightWidth=borderWidth /> | "country" => <CustomPicker value=country isCountryStateFields=true setValue=onChangeCountry borderBottomLeftRadius=borderRadius borderBottomRightRadius=borderRadius borderBottomWidth=borderWidth items=countryData placeholderText=localeObject.countryLabel /> | "bank" => <CustomPicker value=selectedBank setValue=onChangeBank borderBottomLeftRadius=borderRadius borderBottomRightRadius=borderRadius borderBottomWidth=borderWidth items=bankData placeholderText=localeObject.bankLabel /> | "blik_code" => <CustomInput state={blikCode->Option.getOr("")} setState={onChangeBlikCode} borderBottomLeftRadius=borderRadius borderBottomRightRadius=borderRadius borderBottomWidth=borderWidth placeholder="000-000" keyboardType=#numeric maxLength=Some(7) /> | _ => React.null }} </View> ) ->React.array }} <Space /> <RedirectionText /> </>} </ErrorBoundary> <Space height=5. /> </> }
8,171
10,760
hyperswitch-client-core
src/pages/widgets/ExpressCheckoutWidget.res
.res
open ReactNative open Style @react.component let make = () => { let handleSuccessFailure = AllPaymentHooks.useHandleSuccessFailure() React.useEffect0(() => { let nee = NativeEventEmitter.make( Dict.get(ReactNative.NativeModules.nativeModules, "HyperModule"), ) let event = NativeEventEmitter.addListener(nee, "confirmEC", var => { let _responseFromJava = var->PaymentConfirmTypes.itemToObjMapperJava handleSuccessFailure( ~apiResStatus={ message: "", code: "", type_: "", status: "succeeded", }, ~closeSDK=false, (), ) }) HyperModule.sendMessageToNative(`{"isReady": "true", "paymentMethodType": "expressCheckout"}`) Some( () => { event->EventSubscription.remove }, ) }) <View style={viewStyle( ~flex=1., ~backgroundColor="white", ~flexDirection=#row, ~justifyContent=#"space-between", ~alignItems=#center, ~borderRadius=5., ~paddingHorizontal=5.->dp, (), )}> <View style={viewStyle(~alignItems=#center, ~flexDirection=#row, ())}> <Icon name="visa" height=32. width=32. /> <Space /> <TextWrapper textType={PlaceholderText}> {"**** 4242"->React.string} </TextWrapper> </View> <CustomTouchableOpacity onPress={_ => HyperModule.launchWidgetPaymentSheet("", _ => {()})}> <TextWrapper textType={LinkText}> {"Change"->React.string} </TextWrapper> </CustomTouchableOpacity> </View> }
382
10,761
hyperswitch-client-core
src/pages/widgets/CustomWidget.res
.res
open ReactNative open Style module WidgetError = { @react.component let make = () => { Exn.raiseError("Payment Method not available")->ignore React.null } } @react.component let make = (~walletType) => { let (nativeProp, setNativeProp) = React.useContext(NativePropContext.nativePropContext) let (_, setLoading) = React.useContext(LoadingContext.loadingContext) let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let (button, setButton) = React.useState(_ => None) React.useEffect1(() => { if nativeProp.publishableKey == "" { setLoading(ProcessingPayments(None)) } else { setButton(_ => PMListModifier.widgetModifier( allApiData.paymentList, allApiData.sessions, walletType, nativeProp.hyperParams.confirm, ) ) } let nee = NativeEventEmitter.make( Dict.get(ReactNative.NativeModules.nativeModules, "HyperModule"), ) let event = NativeEventEmitter.addListener(nee, "widget", var => { let responseFromJava = var->PaymentConfirmTypes.itemToObjMapperJava if ( walletType == switch responseFromJava.paymentMethodType { | "google_pay" => GOOGLE_PAY | "paypal" => PAYPAL | _ => NONE } ) { setNativeProp({ ...nativeProp, publishableKey: responseFromJava.publishableKey, clientSecret: responseFromJava.clientSecret, hyperParams: { ...nativeProp.hyperParams, confirm: responseFromJava.confirm, }, configuration: { ...nativeProp.configuration, appearance: { ...nativeProp.configuration.appearance, googlePay: { buttonType: PLAIN, buttonStyle: None, }, }, }, }) } }) HyperModule.sendMessageToNative( `{"isReady": "true", "paymentMethodType": "${walletType ->SdkTypes.widgetToStrMapper ->String.toLowerCase}"}`, ) Some( () => { event->EventSubscription.remove }, ) }, [allApiData.sessions]) <ErrorBoundary level={FallBackScreen.Widget} rootTag=nativeProp.rootTag> <View style={viewStyle( ~flex=1., ~width=100.->pct, ~maxHeight=45.->dp, ~backgroundColor="transparent", (), )}> {switch button { | Some(component) => component === React.null ? <WidgetError /> : component | None => <LoadingOverlay /> }} </View> </ErrorBoundary> }
594
10,762
hyperswitch-client-core
src/pages/widgets/CardWidget.res
.res
open ReactNative open Style @react.component let make = () => { let (cardData, _) = React.useContext(CardDataContext.cardDataContext) let {cardNumber, expireDate, cvv, zip} = cardData let (_, setLoading) = React.useContext(LoadingContext.loadingContext) let (reset, setReset) = React.useState(_ => false) let (isCardValuesValid, setIsCardValuesValid) = React.useState(_ => false) let fetchAndRedirect = AllPaymentHooks.useRedirectHook() let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let handleSuccessFailure = AllPaymentHooks.useHandleSuccessFailure() let retrievePayment = AllPaymentHooks.useRetrieveHook() let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let processRequest = ( prop: PaymentMethodListType.payment_method_types_card, clientSecret, publishableKey, ) => { let errorCallback = (~errorMessage, ~closeSDK, ()) => { if !closeSDK { setLoading(FillingDetails) } handleSuccessFailure(~apiResStatus=errorMessage, ~closeSDK, ()) } let responseCallback = ( ~paymentStatus: LoadingContext.sdkPaymentState, ~status: PaymentConfirmTypes.error, ) => { setReset(_ => true) switch paymentStatus { | PaymentSuccess => { setLoading(PaymentSuccess) setTimeout(() => { setLoading(FillingDetails) handleSuccessFailure(~apiResStatus=status, ()) }, 800)->ignore } | _ => handleSuccessFailure(~apiResStatus=status, ()) } } let (month, year) = Validation.getExpiryDates(expireDate) let cardBrand = Validation.getCardBrand(cardNumber) let payment_method_data = [ ( prop.payment_method, [ ("card_number", cardNumber->Validation.clearSpaces->JSON.Encode.string), ("card_exp_month", month->JSON.Encode.string), ("card_exp_year", year->JSON.Encode.string), ("card_holder_name", ""->JSON.Encode.string), ("card_cvc", cvv->JSON.Encode.string), ( "card_network", switch cardBrand { | "" => JSON.Encode.null | cardBrand => cardBrand->JSON.Encode.string }, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object let body: PaymentMethodListType.redirectType = { client_secret: clientSecret, return_url: ?Utils.getReturnUrl( ~appId=nativeProp.hyperParams.appId, ~appURL=allApiData.additionalPMLData.redirect_url, ), payment_method: prop.payment_method, payment_method_type: prop.payment_method_type, connector: switch prop.card_networks { | Some(cardNetworks) => cardNetworks ->Array.get(0) ->Option.mapOr([], card_network => card_network.eligible_connectors) | None => [] }, payment_method_data, billing: ?nativeProp.configuration.defaultBillingDetails, shipping: ?nativeProp.configuration.shippingDetails, } fetchAndRedirect( ~body=body->JSON.stringifyAny->Option.getOr(""), ~publishableKey, ~clientSecret, ~errorCallback, ~responseCallback, ~paymentMethod=prop.payment_method_type, (), ) } let showAlert = AlertHook.useAlerts() let handlePress = (clientSecret, publishableKey) => { setLoading(ProcessingPayments(None)) retrievePayment(List, clientSecret, publishableKey) ->Promise.then(res => { let paymentList = res ->PaymentMethodListType.jsonTopaymentMethodListType ->Array.find(item => { switch item { | CARD(_) => true | _ => false } }) switch paymentList { | Some(val) => switch val { | CARD(prop) => processRequest(prop, clientSecret, publishableKey) | _ => () }->ignore | None => showAlert(~errorType="warning", ~message="Card Payment is not enabled") } Promise.resolve(res) }) ->ignore } React.useEffect5(() => { let nee = NativeEventEmitter.make( Dict.get(ReactNative.NativeModules.nativeModules, "HyperModule"), ) let event = NativeEventEmitter.addListener(nee, "confirm", var => { let responseFromJava = var->PaymentConfirmTypes.itemToObjMapperJava handlePress(responseFromJava.clientSecret, responseFromJava.publishableKey) }) HyperModule.sendMessageToNative(`{"isReady": "true", "paymentMethodType": "card"}`) Some( () => { event->EventSubscription.remove }, ) }, (cardNumber, cvv, expireDate, zip, isCardValuesValid)) <View style={array([ viewStyle( ~flex=1., ~justifyContent=#center, ~alignItems=#center, ~backgroundColor="transparent", (), ), ])}> <CardElement setIsAllValid=setIsCardValuesValid viewType=CardElement.CardForm({isZipAvailable: true}) reset /> </View> }
1,158
10,763
hyperswitch-client-core
reactNativeWeb/tsconfig.json
.json
{ "compilerOptions": { "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "strict": false, "noEmit": true, "incremental": true, "module": "esnext", "esModuleInterop": true, "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve" }, "include": [ "next-env.d.ts", "**/*.ts", "**/*.tsx" ], "exclude": [ "node_modules" ] }
150
10,764
hyperswitch-client-core
reactNativeWeb/version.json
.json
{ "version": "1.0.7" }
13
10,765
hyperswitch-client-core
reactNativeWeb/WebApp.res
.res
@react.component let app = (~props) => { let (propFromEvent, setPropFromEvent) = React.useState(() => None) let {sdkInitialised} = WebKit.useWebKit() Window.useEventListener() React.useEffect0(() => { let handleMessage = jsonData => { try { switch jsonData->Dict.get("props") { | Some(json) => setPropFromEvent(_ => Some(json)) | None => () } } catch { | _ => () } } Window.registerEventListener("initialProps", handleMessage) let sdkInitialisedProp = JSON.stringifyAny({ "sdkLoaded": true, })->Option.getOr("") sdkInitialised(sdkInitialisedProp) None }) switch (propFromEvent, props->Utils.getDictFromJson->Utils.getBool("local", false)) { | (Some(props), _) => <App props rootTag=1 /> | (None, true) => <App props rootTag=0 /> | _ => React.null } }
229
10,766
hyperswitch-client-core
reactNativeWeb/webpack.config.js
.js
const path = require('path'); const TerserPlugin = require('terser-webpack-plugin'); require('dotenv').config({path: './.env'}); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin'); const appDirectory = path.resolve(__dirname); const {presets, plugins} = require(`${appDirectory}/babel.config.js`); const isDevelopment = process.env.NODE_ENV == 'development'; const repoVersion = require('./version.json').version; const majorVersion = 'v' + repoVersion.split('.')[0]; const repoPublicPath = isDevelopment ? `` : `/mobile/${repoVersion}/mobile/${majorVersion}`; const compileNodeModules = [ // Add every react-native package that needs compiling // 'react-native-gesture-handler', // 'react-native-linear-gradient', // 'react-native-klarna-inapp-sdk', 'react-native-inappbrowser-reborn', '@react-native-picker/picker', '@react-navigation/material-top-tabs', '@react-navigation/stack', '@rescript/react', 'react-native', 'react-native-gesture-handler', 'react-native-safe-area-context', 'react-native-screens', 'react-native-svg', 'react-native-tab-view', 'react-content-loader', 'react-native-hyperswitch-netcetera-3ds', 'react-native-scan-card', ].map(moduleName => path.resolve(appDirectory, `../node_modules/${moduleName}`), ); const babelLoaderConfiguration = { test: /\.js$|tsx?$/, // Add every directory that needs to be compiled by Babel during the build. include: [ path.resolve(__dirname, 'index.web.js'), // Entry to your application path.resolve(__dirname, '../App.js'), // Change this to your main App file path.resolve(__dirname, '../src'), ...compileNodeModules, ], use: { loader: 'babel-loader', options: { cacheDirectory: true, presets, plugins: [ ...plugins, isDevelopment && require.resolve('react-refresh/babel'), ].filter(Boolean), }, }, }; const svgLoaderConfiguration = { test: /\.svg$/, use: [ { loader: '@svgr/webpack', }, ], }; const imageLoaderConfiguration = { test: /\.(gif|jpe?g|png)$/, use: { loader: 'url-loader', options: { name: '[name].[ext]', }, }, }; module.exports = { entry: { app: path.join(__dirname, 'index.web.js'), }, output: { path: path.resolve(appDirectory, 'dist'), filename: 'index.bundle.js', publicPath: `${repoPublicPath}/`, }, devtool: 'source-map', devServer: { hot: true, port: 8081, }, resolve: { extensions: [ '.web.tsx', '.web.ts', '.tsx', '.ts', '.web.bs.js', '.bs.js', '.web.js', '.js', ], alias: { 'react-native$': 'react-native-web', 'react-native-linear-gradient': 'react-native-web-linear-gradient', 'react-native-klarna-inapp-sdk/index': 'react-native-web', '@sentry/react-native': '@sentry/react', 'react-native-hyperswitch-paypal': 'react-native-web', 'react-native-hyperswitch-kount': 'react-native-web', 'react-native-hyperswitch-netcetera-3ds': 'react-native-web', 'react-native-plaid-link-sdk': 'react-native-web', }, }, optimization: { minimize: !isDevelopment, minimizer: [!isDevelopment && new TerserPlugin()].filter(Boolean), }, module: { rules: [ babelLoaderConfiguration, imageLoaderConfiguration, svgLoaderConfiguration, ], }, plugins: [ new HtmlWebpackPlugin({ template: path.join(__dirname, 'index.html'), }), new webpack.HotModuleReplacementPlugin(), isDevelopment && new ReactRefreshWebpackPlugin(), new webpack.DefinePlugin({ // See: https://github.com/necolas/react-native-web/issues/349 __DEV__: JSON.stringify(false), }), ].filter(Boolean), };
958
10,767
hyperswitch-client-core
reactNativeWeb/index.web.js
.js
import {AppRegistry} from 'react-native'; import {name as appName} from '../app.json'; import {app} from './WebApp.bs.js'; AppRegistry.registerComponent(appName, () => app); const initReactNativeWeb = async () => { AppRegistry.runApplication(appName, { initialProps: {}, rootTag: document.getElementById('app-root'), }); }; initReactNativeWeb();
85
10,768
hyperswitch-client-core
reactNativeWeb/next.config.js
.js
/** @type {import('next').NextConfig} */ const bsconfig = require('../rescript.json'); let transpileModules = [ // Add every react-native package that needs compiling // 'react-native-linear-gradient', 'react-native-klarna-inapp-sdk', 'react-native-inappbrowser-reborn', // 'react-native-hyperswitch-paypal', // 'react-native-hyperswitch-kount', 'react-native-plaid-link-sdk', '@sentry/react-native', 'react-native', 'react-native-web', 'react-native-svg', 'react-content-loader/native', 'rescript' ].concat(bsconfig["bs-dependencies"]); module.exports = { env: { environment: 'next', }, output: 'export', typescript: { // !! WARN !! // Dangerously allow production builds to successfully complete even if // your project has type errors. // !! WARN !! ignoreBuildErrors: true, }, transpilePackages: transpileModules, experimental: { esmExternals: "loose", forceSwcTransforms: true, turbo: { resolveAlias: { "react-native": "react-native-web", 'react-native-klarna-inapp-sdk/index': 'react-native-web', '@sentry/react-native': '@sentry/nextjs', 'react-native-hyperswitch-paypal': 'react-native-web', 'react-native-hyperswitch-kount': 'react-native-web', 'react-native-plaid-link-sdk': 'react-native-web', 'react-native-inappbrowser-reborn': 'react-native-web', 'react-content-loader/native': 'react-content-loader', }, resolveExtensions: [ ".web.bs.js", ".web.js", ".web.jsx", ".web.ts", ".web.tsx", ".mdx", ".tsx", ".ts", ".jsx", ".js", ".mjs", ".json", ], }, }, webpack: (config) => { config.resolve.alias = { ...(config.resolve.alias || {}), // Transform all direct `react-native` imports to `react-native-web` "react-native$": "react-native-web", 'react-native-klarna-inapp-sdk/index': 'react-native-web', '@sentry/react-native': '@sentry/nextjs', 'react-native-hyperswitch-paypal': 'react-native-web', 'react-native-hyperswitch-kount': 'react-native-web', 'react-native-plaid-link-sdk': 'react-native-web', 'react-native-inappbrowser-reborn': 'react-native-web', 'react-content-loader/native': 'react-content-loader', }; config.resolve.extensions = [ ".web.js", ".web.jsx", ".web.ts", ".web.tsx", ".web.bs.js", ...config.resolve.extensions, ]; return config; }, };
642
10,769
hyperswitch-client-core
reactNativeWeb/index.html
.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>HyperSwitch Web</title> <style> #app-root { display: flex; flex: 1 1 100%; height: 100vh; } textarea:focus, input:focus { outline: none; } </style> </head> <body> <div id="app-root"></div> </body> </html>
162
10,770
hyperswitch-client-core
reactNativeWeb/babel.config.js
.js
module.exports = { presets: [ [ 'module:@react-native/babel-preset', { useTransformReactJSXExperimental: true }, ], "next/babel" ], plugins: [ ['react-native-web'], ['@babel/plugin-transform-flow-strip-types'], ['module:react-native-dotenv'], ['@babel/plugin-transform-react-jsx', { runtime: 'automatic' }], ['@babel/plugin-proposal-decorators', { legacy: true }], ['@babel/plugin-proposal-class-properties', { loose: true }], ['@babel/plugin-proposal-private-methods', { loose: true }], ['@babel/plugin-proposal-private-property-in-object', { loose: true }], '@babel/plugin-transform-runtime', // 'react-native-reanimated/plugin', // <--- Only add this plugin if "react-native-reanimated" is installed in your project. ], };
191
10,771
hyperswitch-client-core
reactNativeWeb/DemoApp/DemoAppIndex.html
.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>HyperSwitch Web</title> <style> body { margin: 0; } #app-root { display: flex; flex: 1 1 100%; height: 100vh; } iframe { width: 100%; border: 0; } </style> </head> <body> <div id="app-root" style="justify-content: center"> <div id="status" style="align-self: center"></div> <iframe src="http://localhost:8081"></iframe> </div> </body> </html>
218
10,772
hyperswitch-client-core
reactNativeWeb/DemoApp/webpack.config.js
.js
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const appDirectory = path.resolve(__dirname); module.exports = { entry: { app: path.join(__dirname, 'DemoAppIndex.js'), }, output: { path: path.resolve(appDirectory, 'dist'), publicPath: '/', filename: 'index.bundle.js', }, devtool: 'source-map', devServer: { open: true, port: 8082, // Specify the port here }, resolve: { extensions: [ '.web.tsx', '.web.ts', '.tsx', '.ts', '.web.bs.js', '.bs.js', '.web.js', '.js', ], }, plugins: [ new HtmlWebpackPlugin({ template : path.join(__dirname, "DemoAppIndex.html") }), ] };
199
10,773
hyperswitch-client-core
reactNativeWeb/DemoApp/DemoAppIndex.js
.js
let defaultProps = { local: false, configuration: { paymentSheetHeaderLabel: 'Add a payment method', savedPaymentSheetHeaderLabel: 'Saved payment method', allowsDelayedPaymentMethods: true, merchantDisplayName: 'Example, Inc.', // disableSavedCardScreen: true, // paymentSheetHeaderText: 'Hello world', // savedPaymentScreenHeaderText: 'Testing....', allowsPaymentMethodsRequiringShippingAddress: false, googlePay: { environment: 'Test', countryCode: 'US', currencyCode: 'US', }, // displaySavedPaymentMethodsCheckbox: false, // shippingDetails: { // address: { // city: 'city', // country: 'US', // line1: 'US', // line2: 'line2', // postalCode: '560060', // state: 'California', // }, // name: 'Shipping INC', // }, // displaySavedPaymentMethods: false, appearance: { theme: 'Light', // componentBackground:"black", // colors:{ // background:"#F5F8F9", // primary:"#8DBD00" // }, // primaryButton:{ // shapes:{ // borderRadius:20.0 // }} // locale: "en" typography: { fontResId: 'montserrat', }, }, }, hyperParams: { ip: '13.232.74.226', 'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.', launchTime: Date.now(), // country: 'AT', country: 'US', }, country: 'US', type: 'payment', };const TRUSTED_ORIGINS = ['http://localhost:8081', 'https://your-production-url.com']; // Add trusted origins const initReactNativeWeb = async () => { const createProps = async () => { try { let response = await fetch('http://localhost:5252/create-payment-intent'); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const data = await response.json(); defaultProps.publishableKey = data.publishableKey; defaultProps.clientSecret = data.clientSecret; defaultProps.local = true; const iframe = document.querySelector('iframe'); if (iframe && iframe.contentWindow) { iframe.contentWindow.postMessage( JSON.stringify({ initialProps: { props: defaultProps } }), TRUSTED_ORIGINS[0] ); } else { console.error('Iframe not found or inaccessible.'); } } catch (error) { console.error('Error fetching payment intent:', error); } }; const handleMessage = (event) => { if (!TRUSTED_ORIGINS.includes(event.origin)) { console.warn(`Blocked message from untrusted origin: ${event.origin}`); return; } try { let data = JSON.parse(event.data); if (data.sdkLoaded) { createProps(); } if (data.status) { const iframe = document.querySelector('iframe'); if (iframe) iframe.style.display = 'none'; const statusElement = document.getElementById('status'); if (statusElement) { statusElement.textContent = `Status: ${data.status} ${data.message ? 'Message: ' + data.message : ''}`; } else { console.error('Status element not found.'); } } } catch (error) { console.error('Error processing message:', error); } }; window.addEventListener('message', handleMessage); }; initReactNativeWeb();
839
10,774
hyperswitch-client-core
reactNativeWeb/pages/index.tsx
.tsx
import { useEffect, useState } from 'react'; import Head from 'next/head' import App from '../../App' export default function Home() { const [initialProps, setProps] = useState({ clientSecret: '' }); let fetchProps = async () => { let props = { local: true, configuration: { allowsDelayedPaymentMethods: true, merchantDisplayName: 'Example, Inc.', allowsPaymentMethodsRequiringShippingAddress: false, googlePay: { environment: 'Test', countryCode: 'US', currencyCode: 'US', }, }, country: 'US', type: 'hostedCheckout', publishableKey: 'pk_snd_dummy', clientSecret: 'pay_dummy_secret_dummy', }; setProps(props) } useEffect(() => { fetchProps() }, []) return ( <> <Head> <title>React Native Next</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.ico" /> <style> {` textarea:focus, input:focus { outline: none; } `} </style> </Head> <main style={{ display: 'flex', minHeight: '100vh', width: '100%', overflowX: 'hidden', position: 'relative' }}> {initialProps.clientSecret !== '' && <App props={initialProps} />} </main> </> ) }
344
10,775