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-web
src/Utilities/PaymentHelpers.res
.res
open Utils open Identity open PaymentHelpersTypes open LoggerUtils open URLModule let getPaymentType = paymentMethodType => switch paymentMethodType { | "apple_pay" => Applepay | "samsung_pay" => Samsungpay | "google_pay" => Gpay | "paze" => Paze | "debit" | "credit" | "" => Card | _ => Other } let closePaymentLoaderIfAny = () => messageParentWindow([("fullscreen", false->JSON.Encode.bool)]) let retrievePaymentIntent = ( clientSecret, headers, ~optLogger, ~customPodUri, ~isForceSync=false, ) => { open Promise let paymentIntentID = clientSecret->getPaymentId let endpoint = ApiEndpoint.getApiEndPoint() let forceSync = isForceSync ? "&force_sync=true" : "" let uri = `${endpoint}/payments/${paymentIntentID}?client_secret=${clientSecret}${forceSync}` logApi( ~optLogger, ~url=uri, ~apiLogType=Request, ~eventName=RETRIEVE_CALL_INIT, ~logType=INFO, ~logCategory=API, ) fetchApi(uri, ~method=#GET, ~headers=headers->ApiEndpoint.addCustomPodHeader(~customPodUri)) ->then(res => { let statusCode = res->Fetch.Response.status->Int.toString if statusCode->String.charAt(0) !== "2" { res ->Fetch.Response.json ->then(data => { logApi( ~optLogger, ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=RETRIEVE_CALL, ~logType=ERROR, ~logCategory=API, ) JSON.Encode.null->resolve }) } else { logApi( ~optLogger, ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName=RETRIEVE_CALL, ~logType=INFO, ~logCategory=API, ) res->Fetch.Response.json } }) ->catch(e => { Console.error2("Unable to retrieve payment details because of ", e) JSON.Encode.null->resolve }) } let threeDsAuth = (~clientSecret, ~optLogger, ~threeDsMethodComp, ~headers) => { let endpoint = ApiEndpoint.getApiEndPoint() let paymentIntentID = String.split(clientSecret, "_secret_")[0]->Option.getOr("") let url = `${endpoint}/payments/${paymentIntentID}/3ds/authentication` let broswerInfo = BrowserSpec.broswerInfo let body = [ ("client_secret", clientSecret->JSON.Encode.string), ("device_channel", "BRW"->JSON.Encode.string), ("threeds_method_comp_ind", threeDsMethodComp->JSON.Encode.string), ] ->Array.concat(broswerInfo()) ->getJsonFromArrayOfJson open Promise logApi( ~optLogger, ~url, ~apiLogType=Request, ~eventName=AUTHENTICATION_CALL_INIT, ~logType=INFO, ~logCategory=API, ) fetchApi(url, ~method=#POST, ~bodyStr=body->JSON.stringify, ~headers=headers->Dict.fromArray) ->then(res => { let statusCode = res->Fetch.Response.status->Int.toString if statusCode->String.charAt(0) !== "2" { res ->Fetch.Response.json ->then(data => { logApi( ~optLogger, ~url, ~data, ~statusCode, ~apiLogType=Err, ~eventName=AUTHENTICATION_CALL, ~logType=ERROR, ~logCategory=API, ) let dict = data->getDictFromJson let errorObj = PaymentError.itemToObjMapper(dict) closePaymentLoaderIfAny() postFailedSubmitResponse(~errortype=errorObj.error.type_, ~message=errorObj.error.message) JSON.Encode.null->resolve }) } else { logApi(~optLogger, ~url, ~statusCode, ~apiLogType=Response, ~eventName=AUTHENTICATION_CALL) res->Fetch.Response.json } }) ->catch(err => { let exceptionMessage = err->formatException Console.error2("Unable to call 3ds auth ", exceptionMessage) logApi( ~optLogger, ~url, ~eventName=AUTHENTICATION_CALL, ~apiLogType=NoResponse, ~data=exceptionMessage, ~logType=ERROR, ~logCategory=API, ) reject(err) }) } let rec pollRetrievePaymentIntent = ( clientSecret, headers, ~optLogger, ~customPodUri, ~isForceSync=false, ) => { open Promise retrievePaymentIntent(clientSecret, headers, ~optLogger, ~customPodUri, ~isForceSync) ->then(json => { let dict = json->getDictFromJson let status = dict->getString("status", "") if status === "succeeded" || status === "failed" { resolve(json) } else { delay(2000) ->then(_val => { pollRetrievePaymentIntent(clientSecret, headers, ~optLogger, ~customPodUri, ~isForceSync) }) ->catch(_ => Promise.resolve(JSON.Encode.null)) } }) ->catch(e => { Console.error2("Unable to retrieve payment due to following error", e) pollRetrievePaymentIntent(clientSecret, headers, ~optLogger, ~customPodUri, ~isForceSync) }) } let retrieveStatus = (~headers, ~customPodUri, pollID, logger) => { open Promise let endpoint = ApiEndpoint.getApiEndPoint() let uri = `${endpoint}/poll/status/${pollID}` logApi( ~optLogger=Some(logger), ~url=uri, ~apiLogType=Request, ~eventName=POLL_STATUS_CALL_INIT, ~logType=INFO, ~logCategory=API, ) fetchApi(uri, ~method=#GET, ~headers=headers->ApiEndpoint.addCustomPodHeader(~customPodUri)) ->then(res => { let statusCode = res->Fetch.Response.status->Int.toString if statusCode->String.charAt(0) !== "2" { res ->Fetch.Response.json ->then(data => { logApi( ~optLogger=Some(logger), ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=POLL_STATUS_CALL, ~logType=ERROR, ~logCategory=API, ) JSON.Encode.null->resolve }) } else { logApi( ~optLogger=Some(logger), ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName=POLL_STATUS_CALL, ~logType=INFO, ~logCategory=API, ) res->Fetch.Response.json } }) ->catch(e => { Console.error2("Unable to Poll status details because of ", e) JSON.Encode.null->resolve }) } let rec pollStatus = (~headers, ~customPodUri, ~pollId, ~interval, ~count, ~returnUrl, ~logger) => { open Promise retrieveStatus(~headers, ~customPodUri, pollId, logger) ->then(json => { let dict = json->getDictFromJson let status = dict->getString("status", "") Promise.make((resolve, _) => { if status === "completed" { resolve(json) } else if count === 0 { messageParentWindow([("fullscreen", false->JSON.Encode.bool)]) openUrl(returnUrl) } else { delay(interval) ->then( _ => { pollStatus( ~headers, ~customPodUri, ~pollId, ~interval, ~count=count - 1, ~returnUrl, ~logger, )->then( res => { resolve(res) Promise.resolve() }, ) }, ) ->catch(_ => Promise.resolve()) ->ignore } }) }) ->catch(e => { Console.error2("Unable to retrieve payment due to following error", e) pollStatus( ~headers, ~customPodUri, ~pollId, ~interval, ~count=count - 1, ~returnUrl, ~logger, )->then(res => resolve(res)) }) } let rec intentCall = ( ~fetchApi: ( string, ~bodyStr: string=?, ~headers: Dict.t<string>=?, ~method: Fetch.method, ) => promise<Fetch.Response.t>, ~uri, ~headers, ~bodyStr, ~confirmParam: ConfirmType.confirmParams, ~clientSecret, ~optLogger, ~handleUserError, ~paymentType, ~iframeId, ~fetchMethod, ~setIsManualRetryEnabled, ~customPodUri, ~sdkHandleOneClickConfirmPayment, ~counter, ~isPaymentSession=false, ~isCallbackUsedVal=?, ~componentName="payment", ~redirectionFlags, ) => { open Promise let isConfirm = uri->String.includes("/confirm") let isCompleteAuthorize = uri->String.includes("/complete_authorize") let isPostSessionTokens = uri->String.includes("/post_session_tokens") let (eventName: HyperLogger.eventName, initEventName: HyperLogger.eventName) = switch ( isConfirm, isCompleteAuthorize, isPostSessionTokens, ) { | (true, _, _) => (CONFIRM_CALL, CONFIRM_CALL_INIT) | (_, true, _) => (COMPLETE_AUTHORIZE_CALL, COMPLETE_AUTHORIZE_CALL_INIT) | (_, _, true) => (POST_SESSION_TOKENS_CALL, POST_SESSION_TOKENS_CALL_INIT) | _ => (RETRIEVE_CALL, RETRIEVE_CALL_INIT) } logApi( ~optLogger, ~url=uri, ~apiLogType=Request, ~eventName=initEventName, ~logType=INFO, ~logCategory=API, ~isPaymentSession, ) let handleOpenUrl = url => { if isPaymentSession { Utils.replaceRootHref(url, redirectionFlags) } else { openUrl(url) } } fetchApi( uri, ~method=fetchMethod, ~headers=headers->ApiEndpoint.addCustomPodHeader(~customPodUri), ~bodyStr, ) ->then(res => { let statusCode = res->Fetch.Response.status->Int.toString let url = makeUrl(confirmParam.return_url) url.searchParams.set("payment_intent_client_secret", clientSecret) url.searchParams.set("status", "failed") url.searchParams.set("payment_id", clientSecret->getPaymentId) messageParentWindow([("confirmParams", confirmParam->anyTypeToJson)]) if statusCode->String.charAt(0) !== "2" { res ->Fetch.Response.json ->then(data => { Promise.make( (resolve, _) => { if isConfirm { let paymentMethod = switch paymentType { | Card => "CARD" | _ => bodyStr ->safeParse ->getDictFromJson ->getString("payment_method_type", "") } handleLogging( ~optLogger, ~value=data->JSON.stringify, ~eventName=PAYMENT_FAILED, ~paymentMethod, ) } logApi( ~optLogger, ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName, ~logType=ERROR, ~logCategory=API, ~isPaymentSession, ) let dict = data->getDictFromJson let errorObj = PaymentError.itemToObjMapper(dict) if !isPaymentSession { closePaymentLoaderIfAny() postFailedSubmitResponse( ~errortype=errorObj.error.type_, ~message=errorObj.error.message, ) } if handleUserError { handleOpenUrl(url.href) } else { let failedSubmitResponse = getFailedSubmitResponse( ~errorType=errorObj.error.type_, ~message=errorObj.error.message, ) resolve(failedSubmitResponse) } }, )->then(resolve) }) ->catch(err => { Promise.make( (resolve, _) => { let exceptionMessage = err->formatException logApi( ~optLogger, ~url=uri, ~statusCode, ~apiLogType=NoResponse, ~data=exceptionMessage, ~eventName, ~logType=ERROR, ~logCategory=API, ~isPaymentSession, ) if counter >= 5 { if !isPaymentSession { closePaymentLoaderIfAny() postFailedSubmitResponse(~errortype="server_error", ~message="Something went wrong") } if handleUserError { handleOpenUrl(url.href) } else { let failedSubmitResponse = getFailedSubmitResponse( ~errorType="server_error", ~message="Something went wrong", ) resolve(failedSubmitResponse) } } else { let paymentIntentID = clientSecret->getPaymentId let endpoint = ApiEndpoint.getApiEndPoint( ~publishableKey=confirmParam.publishableKey, ~isConfirmCall=isConfirm, ) let retrieveUri = `${endpoint}/payments/${paymentIntentID}?client_secret=${clientSecret}` intentCall( ~fetchApi, ~uri=retrieveUri, ~headers, ~bodyStr, ~confirmParam: ConfirmType.confirmParams, ~clientSecret, ~optLogger, ~handleUserError, ~paymentType, ~iframeId, ~fetchMethod=#GET, ~setIsManualRetryEnabled, ~customPodUri, ~sdkHandleOneClickConfirmPayment, ~counter=counter + 1, ~componentName, ~redirectionFlags, ) ->then( res => { resolve(res) Promise.resolve() }, ) ->catch(_ => Promise.resolve()) ->ignore } }, )->then(resolve) }) } else { res ->Fetch.Response.json ->then(data => { Promise.make( (resolve, _) => { logApi( ~optLogger, ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName, ~isPaymentSession, ) let intent = PaymentConfirmTypes.itemToObjMapper(data->getDictFromJson) let paymentMethod = switch paymentType { | Card => "CARD" | _ => intent.payment_method_type } let url = makeUrl(confirmParam.return_url) url.searchParams.set("payment_intent_client_secret", clientSecret) url.searchParams.set("payment_id", clientSecret->getPaymentId) url.searchParams.set("status", intent.status) let handleProcessingStatus = (paymentType, sdkHandleOneClickConfirmPayment) => { switch (paymentType, sdkHandleOneClickConfirmPayment) { | (Card, _) | (Gpay, false) | (Applepay, false) | (Paypal, false) => if !isPaymentSession { if isCallbackUsedVal->Option.getOr(false) { handleOnCompleteDoThisMessage() } else { closePaymentLoaderIfAny() } postSubmitResponse(~jsonData=data, ~url=url.href) } else if confirmParam.redirect === Some("always") { if isCallbackUsedVal->Option.getOr(false) { handleOnCompleteDoThisMessage() } else { handleOpenUrl(url.href) } } else { resolve(data) } | _ => if isCallbackUsedVal->Option.getOr(false) { closePaymentLoaderIfAny() handleOnCompleteDoThisMessage() } else { handleOpenUrl(url.href) } } } if intent.status == "requires_customer_action" { if intent.nextAction.type_ == "redirect_to_url" { handleLogging( ~optLogger, ~value="", ~internalMetadata=intent.nextAction.redirectToUrl, ~eventName=REDIRECTING_USER, ~paymentMethod, ) handleOpenUrl(intent.nextAction.redirectToUrl) } else if intent.nextAction.type_ == "display_bank_transfer_information" { let metadata = switch intent.nextAction.bank_transfer_steps_and_charges_details { | Some(obj) => obj->getDictFromJson | None => Dict.make() } let dict = deepCopyDict(metadata) dict->Dict.set("data", data) dict->Dict.set("url", url.href->JSON.Encode.string) handleLogging( ~optLogger, ~value="", ~internalMetadata=dict->JSON.Encode.object->JSON.stringify, ~eventName=DISPLAY_BANK_TRANSFER_INFO_PAGE, ~paymentMethod, ) if !isPaymentSession { messageParentWindow([ ("fullscreen", true->JSON.Encode.bool), ("param", `${intent.payment_method_type}BankTransfer`->JSON.Encode.string), ("iframeId", iframeId->JSON.Encode.string), ("metadata", dict->JSON.Encode.object), ]) } resolve(data) } else if intent.nextAction.type_ === "qr_code_information" { let qrData = intent.nextAction.image_data_url->Option.getOr("") let displayText = intent.nextAction.display_text->Option.getOr("") let borderColor = intent.nextAction.border_color->Option.getOr("") let expiryTime = intent.nextAction.display_to_timestamp->Option.getOr(0.0) let headerObj = Dict.make() mergeHeadersIntoDict(~dict=headerObj, ~headers) let metaData = [ ("qrData", qrData->JSON.Encode.string), ("paymentIntentId", clientSecret->JSON.Encode.string), ("publishableKey", confirmParam.publishableKey->JSON.Encode.string), ("headers", headerObj->JSON.Encode.object), ("expiryTime", expiryTime->Float.toString->JSON.Encode.string), ("url", url.href->JSON.Encode.string), ("paymentMethod", paymentMethod->JSON.Encode.string), ("display_text", displayText->JSON.Encode.string), ("border_color", borderColor->JSON.Encode.string), ]->getJsonFromArrayOfJson handleLogging( ~optLogger, ~value="", ~internalMetadata=metaData->JSON.stringify, ~eventName=DISPLAY_QR_CODE_INFO_PAGE, ~paymentMethod, ) if !isPaymentSession { messageParentWindow([ ("fullscreen", true->JSON.Encode.bool), ("param", `qrData`->JSON.Encode.string), ("iframeId", iframeId->JSON.Encode.string), ("metadata", metaData), ]) } resolve(data) } else if intent.nextAction.type_ === "three_ds_invoke" { let threeDsData = intent.nextAction.three_ds_data ->Option.flatMap(JSON.Decode.object) ->Option.getOr(Dict.make()) let do3dsMethodCall = threeDsData ->Dict.get("three_ds_method_details") ->Option.flatMap(JSON.Decode.object) ->Option.flatMap(x => x->Dict.get("three_ds_method_data_submission")) ->Option.getOr(Dict.make()->JSON.Encode.object) ->JSON.Decode.bool ->getBoolValue let headerObj = Dict.make() mergeHeadersIntoDict(~dict=headerObj, ~headers) let metaData = [ ("threeDSData", threeDsData->JSON.Encode.object), ("paymentIntentId", clientSecret->JSON.Encode.string), ("publishableKey", confirmParam.publishableKey->JSON.Encode.string), ("headers", headerObj->JSON.Encode.object), ("url", url.href->JSON.Encode.string), ("iframeId", iframeId->JSON.Encode.string), ]->Dict.fromArray handleLogging( ~optLogger, ~value=do3dsMethodCall ? "Y" : "N", ~eventName=THREE_DS_METHOD, ~paymentMethod, ) if do3dsMethodCall { messageParentWindow([ ("fullscreen", true->JSON.Encode.bool), ("param", `3ds`->JSON.Encode.string), ("iframeId", iframeId->JSON.Encode.string), ("metadata", metaData->JSON.Encode.object), ]) } else { metaData->Dict.set("3dsMethodComp", "U"->JSON.Encode.string) messageParentWindow([ ("fullscreen", true->JSON.Encode.bool), ("param", `3dsAuth`->JSON.Encode.string), ("iframeId", iframeId->JSON.Encode.string), ("metadata", metaData->JSON.Encode.object), ]) } } else if intent.nextAction.type_ === "invoke_hidden_iframe" { let iframeData = intent.nextAction.iframe_data ->Option.flatMap(JSON.Decode.object) ->Option.getOr(Dict.make()) let headerObj = Dict.make() mergeHeadersIntoDict(~dict=headerObj, ~headers) let metaData = [ ("iframeData", iframeData->JSON.Encode.object), ("paymentIntentId", clientSecret->JSON.Encode.string), ("publishableKey", confirmParam.publishableKey->JSON.Encode.string), ("headers", headerObj->JSON.Encode.object), ("url", url.href->JSON.Encode.string), ("iframeId", iframeId->JSON.Encode.string), ("confirmParams", confirmParam->anyTypeToJson), ]->Dict.fromArray messageParentWindow([ ("fullscreen", true->JSON.Encode.bool), ("param", `redsys3ds`->JSON.Encode.string), ("iframeId", iframeId->JSON.Encode.string), ("metadata", metaData->JSON.Encode.object), ]) } else if intent.nextAction.type_ === "display_voucher_information" { let voucherData = intent.nextAction.voucher_details->Option.getOr({ download_url: "", reference: "", }) let headerObj = Dict.make() mergeHeadersIntoDict(~dict=headerObj, ~headers) let metaData = [ ("voucherUrl", voucherData.download_url->JSON.Encode.string), ("reference", voucherData.reference->JSON.Encode.string), ("returnUrl", url.href->JSON.Encode.string), ("paymentMethod", paymentMethod->JSON.Encode.string), ("payment_intent_data", data), ]->Dict.fromArray handleLogging( ~optLogger, ~value="", ~internalMetadata=metaData->JSON.Encode.object->JSON.stringify, ~eventName=DISPLAY_VOUCHER, ~paymentMethod, ) messageParentWindow([ ("fullscreen", true->JSON.Encode.bool), ("param", `voucherData`->JSON.Encode.string), ("iframeId", iframeId->JSON.Encode.string), ("metadata", metaData->JSON.Encode.object), ]) } else if intent.nextAction.type_ == "third_party_sdk_session_token" { let session_token = switch intent.nextAction.session_token { | Some(token) => token->getDictFromJson | None => Dict.make() } let walletName = session_token->getString("wallet_name", "") let message = switch walletName { | "apple_pay" => [ ("applePayButtonClicked", true->JSON.Encode.bool), ("applePayPresent", session_token->anyTypeToJson), ("componentName", componentName->JSON.Encode.string), ] | "google_pay" => [("googlePayThirdPartyFlow", session_token->anyTypeToJson)] | "open_banking" => { let metaData = [ ( "linkToken", session_token ->getString("open_banking_session_token", "") ->JSON.Encode.string, ), ("pmAuthConnectorArray", ["plaid"]->anyTypeToJson), ("publishableKey", confirmParam.publishableKey->JSON.Encode.string), ("clientSecret", clientSecret->JSON.Encode.string), ("isForceSync", true->JSON.Encode.bool), ]->getJsonFromArrayOfJson [ ("fullscreen", true->JSON.Encode.bool), ("param", "plaidSDK"->JSON.Encode.string), ("iframeId", iframeId->JSON.Encode.string), ("metadata", metaData), ] } | _ => [] } if !isPaymentSession { messageParentWindow(message) } resolve(data) } else if intent.nextAction.type_ === "invoke_sdk_client" { let nextActionData = intent.nextAction.next_action_data->Option.getOr(JSON.Encode.null) let response = [ ("orderId", intent.connectorTransactionId->JSON.Encode.string), ("nextActionData", nextActionData), ]->getJsonFromArrayOfJson resolve(response) } else { if !isPaymentSession { postFailedSubmitResponse( ~errortype="confirm_payment_failed", ~message="Payment failed. Try again!", ) } if uri->String.includes("force_sync=true") { handleLogging( ~optLogger, ~value=intent.nextAction.type_, ~internalMetadata=intent.nextAction.type_, ~eventName=REDIRECTING_USER, ~paymentMethod, ~logType=ERROR, ) handleOpenUrl(url.href) } else { let failedSubmitResponse = getFailedSubmitResponse( ~errorType="confirm_payment_failed", ~message="Payment failed. Try again!", ) resolve(failedSubmitResponse) } } } else if intent.status == "requires_payment_method" { if intent.nextAction.type_ === "invoke_sdk_client" { let nextActionData = intent.nextAction.next_action_data->Option.getOr(JSON.Encode.null) let response = [ ("orderId", intent.connectorTransactionId->JSON.Encode.string), ("nextActionData", nextActionData), ]->getJsonFromArrayOfJson resolve(response) } } else if intent.status == "processing" { if intent.nextAction.type_ == "third_party_sdk_session_token" { let session_token = switch intent.nextAction.session_token { | Some(token) => token->getDictFromJson | None => Dict.make() } let walletName = session_token->getString("wallet_name", "") let message = switch walletName { | "apple_pay" => [ ("applePayButtonClicked", true->JSON.Encode.bool), ("applePayPresent", session_token->anyTypeToJson), ] | "google_pay" => [("googlePayThirdPartyFlow", session_token->anyTypeToJson)] | _ => [] } if !isPaymentSession { messageParentWindow(message) } } else { handleProcessingStatus(paymentType, sdkHandleOneClickConfirmPayment) } resolve(data) } else if intent.status != "" { if intent.status === "succeeded" { handleLogging( ~optLogger, ~value=intent.status, ~eventName=PAYMENT_SUCCESS, ~paymentMethod, ) } else if intent.status === "failed" { handleLogging( ~optLogger, ~value=intent.status, ~eventName=PAYMENT_FAILED, ~paymentMethod, ) } if intent.status === "failed" { setIsManualRetryEnabled(_ => intent.manualRetryAllowed) } handleProcessingStatus(paymentType, sdkHandleOneClickConfirmPayment) } else if !isPaymentSession { postFailedSubmitResponse( ~errortype="confirm_payment_failed", ~message="Payment failed. Try again!", ) } else { let failedSubmitResponse = getFailedSubmitResponse( ~errorType="confirm_payment_failed", ~message="Payment failed. Try again!", ) resolve(failedSubmitResponse) } }, )->then(resolve) }) } }) ->catch(err => { Promise.make((resolve, _) => { try { let url = makeUrl(confirmParam.return_url) url.searchParams.set("payment_intent_client_secret", clientSecret) url.searchParams.set("payment_id", clientSecret->getPaymentId) url.searchParams.set("status", "failed") let exceptionMessage = err->formatException logApi( ~optLogger, ~url=uri, ~eventName, ~apiLogType=NoResponse, ~data=exceptionMessage, ~logType=ERROR, ~logCategory=API, ~isPaymentSession, ) if counter >= 5 { if !isPaymentSession { closePaymentLoaderIfAny() postFailedSubmitResponse(~errortype="server_error", ~message="Something went wrong") } if handleUserError { handleOpenUrl(url.href) } else { let failedSubmitResponse = getFailedSubmitResponse( ~errorType="server_error", ~message="Something went wrong", ) resolve(failedSubmitResponse) } } else { let paymentIntentID = clientSecret->getPaymentId let endpoint = ApiEndpoint.getApiEndPoint( ~publishableKey=confirmParam.publishableKey, ~isConfirmCall=isConfirm, ) let retrieveUri = `${endpoint}/payments/${paymentIntentID}?client_secret=${clientSecret}` intentCall( ~fetchApi, ~uri=retrieveUri, ~headers, ~bodyStr, ~confirmParam: ConfirmType.confirmParams, ~clientSecret, ~optLogger, ~handleUserError, ~paymentType, ~iframeId, ~fetchMethod=#GET, ~setIsManualRetryEnabled, ~customPodUri, ~sdkHandleOneClickConfirmPayment, ~counter=counter + 1, ~isPaymentSession, ~componentName, ~redirectionFlags, ) ->then( res => { resolve(res) Promise.resolve() }, ) ->catch(_ => Promise.resolve()) ->ignore } } catch { | _ => if !isPaymentSession { postFailedSubmitResponse(~errortype="error", ~message="Something went wrong") } let failedSubmitResponse = getFailedSubmitResponse( ~errorType="server_error", ~message="Something went wrong", ) resolve(failedSubmitResponse) } })->then(resolve) }) } let usePaymentSync = (optLogger: option<HyperLogger.loggerMake>, paymentType: payment) => { open RecoilAtoms let paymentMethodList = Recoil.useRecoilValueFromAtom(paymentMethodList) let keys = Recoil.useRecoilValueFromAtom(keys) let isCallbackUsedVal = Recoil.useRecoilValueFromAtom(RecoilAtoms.isCompleteCallbackUsed) let customPodUri = Recoil.useRecoilValueFromAtom(customPodUri) let redirectionFlags = Recoil.useRecoilValueFromAtom(redirectionFlagsAtom) let setIsManualRetryEnabled = Recoil.useSetRecoilState(isManualRetryEnabled) (~handleUserError=false, ~confirmParam: ConfirmType.confirmParams, ~iframeId="") => { switch keys.clientSecret { | Some(clientSecret) => let paymentIntentID = clientSecret->getPaymentId let headers = [("Content-Type", "application/json"), ("api-key", confirmParam.publishableKey)] let endpoint = ApiEndpoint.getApiEndPoint(~publishableKey=confirmParam.publishableKey) let uri = `${endpoint}/payments/${paymentIntentID}?force_sync=true&client_secret=${clientSecret}` let paymentSync = () => { intentCall( ~fetchApi, ~uri, ~headers, ~bodyStr="", ~confirmParam: ConfirmType.confirmParams, ~clientSecret, ~optLogger, ~handleUserError, ~paymentType, ~iframeId, ~fetchMethod=#GET, ~setIsManualRetryEnabled, ~customPodUri, ~sdkHandleOneClickConfirmPayment=keys.sdkHandleOneClickConfirmPayment, ~counter=0, ~isCallbackUsedVal, ~redirectionFlags, )->ignore } switch paymentMethodList { | Loaded(_) => paymentSync() | _ => () } | None => postFailedSubmitResponse( ~errortype="sync_payment_failed", ~message="Sync Payment Failed. Try Again!", ) } } } let maskStr = str => str->Js.String2.replaceByRe(%re(`/\S/g`), "x") let rec maskPayload = payloadJson => { switch payloadJson->JSON.Classify.classify { | Object(valueDict) => valueDict ->Dict.toArray ->Array.map(entry => { let (key, value) = entry (key, maskPayload(value)) }) ->getJsonFromArrayOfJson | Array(arr) => arr->Array.map(maskPayload)->JSON.Encode.array | String(valueStr) => valueStr->maskStr->JSON.Encode.string | Number(float) => Float.toString(float)->maskStr->JSON.Encode.string | Bool(bool) => (bool ? "true" : "false")->JSON.Encode.string | Null => JSON.Encode.string("null") } } let useCompleteAuthorizeHandler = () => { open RecoilAtoms let customPodUri = Recoil.useRecoilValueFromAtom(customPodUri) let setIsManualRetryEnabled = Recoil.useSetRecoilState(isManualRetryEnabled) let isCallbackUsedVal = Recoil.useRecoilValueFromAtom(isCompleteCallbackUsed) let redirectionFlags = Recoil.useRecoilValueFromAtom(redirectionFlagsAtom) ( ~clientSecret: option<string>, ~bodyArr, ~confirmParam: ConfirmType.confirmParams, ~iframeId, ~optLogger, ~handleUserError, ~paymentType, ~sdkHandleOneClickConfirmPayment, ~headers: option<array<(string, string)>>=?, ~paymentMode: option<string>=?, ) => switch clientSecret { | Some(cs) => let endpoint = ApiEndpoint.getApiEndPoint(~publishableKey=confirmParam.publishableKey) let uri = `${endpoint}/payments/${cs->getPaymentId}/complete_authorize` let finalHeaders = switch headers { | Some(h) => h | None => [ ("Content-Type", "application/json"), ("api-key", confirmParam.publishableKey), ("X-Client-Source", paymentMode->Option.getOr("")), ] } let bodyStr = [("client_secret", cs->JSON.Encode.string)] ->Array.concatMany([bodyArr, BrowserSpec.broswerInfo()]) ->getJsonFromArrayOfJson ->JSON.stringify intentCall( ~fetchApi, ~uri, ~headers=finalHeaders, ~bodyStr, ~confirmParam, ~clientSecret=cs, ~optLogger, ~handleUserError, ~paymentType, ~iframeId, ~fetchMethod=#POST, ~setIsManualRetryEnabled, ~customPodUri, ~sdkHandleOneClickConfirmPayment, ~counter=0, ~isCallbackUsedVal, ~redirectionFlags, )->ignore | None => postFailedSubmitResponse( ~errortype="complete_authorize_failed", ~message="Complete Authorize Failed. Try Again!", ) } } let useCompleteAuthorize = (optLogger, paymentType) => { let completeAuthorizeHandler = useCompleteAuthorizeHandler() let keys = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys) let paymentMethodList = Recoil.useRecoilValueFromAtom(RecoilAtoms.paymentMethodList) let url = RescriptReactRouter.useUrl() let mode = CardUtils.getQueryParamsDictforKey(url.search, "componentName") ->CardThemeType.getPaymentMode ->CardThemeType.getPaymentModeToStrMapper (~handleUserError=false, ~bodyArr, ~confirmParam, ~iframeId=keys.iframeId) => switch paymentMethodList { | Loaded(_) => completeAuthorizeHandler( ~clientSecret=keys.clientSecret, ~bodyArr, ~confirmParam, ~iframeId, ~optLogger, ~handleUserError, ~paymentType, ~sdkHandleOneClickConfirmPayment=keys.sdkHandleOneClickConfirmPayment, ~paymentMode=mode, ) | _ => () } } let useRedsysCompleteAuthorize = optLogger => { let completeAuthorizeHandler = useCompleteAuthorizeHandler() ( ~handleUserError=false, ~bodyArr, ~confirmParam, ~iframeId="redsys3ds", ~clientSecret, ~headers, ) => completeAuthorizeHandler( ~clientSecret, ~bodyArr, ~confirmParam, ~iframeId, ~optLogger, ~handleUserError, ~paymentType=Card, ~sdkHandleOneClickConfirmPayment=false, ~headers, ) } let usePaymentIntent = (optLogger, paymentType) => { open RecoilAtoms open Promise let url = RescriptReactRouter.useUrl() let componentName = CardUtils.getQueryParamsDictforKey(url.search, "componentName") let paymentTypeFromUrl = componentName->CardThemeType.getPaymentMode let blockConfirm = Recoil.useRecoilValueFromAtom(isConfirmBlocked) let customPodUri = Recoil.useRecoilValueFromAtom(customPodUri) let paymentMethodList = Recoil.useRecoilValueFromAtom(paymentMethodList) let keys = Recoil.useRecoilValueFromAtom(keys) let isCallbackUsedVal = Recoil.useRecoilValueFromAtom(RecoilAtoms.isCompleteCallbackUsed) let redirectionFlags = Recoil.useRecoilValueFromAtom(redirectionFlagsAtom) let setIsManualRetryEnabled = Recoil.useSetRecoilState(isManualRetryEnabled) ( ~handleUserError=false, ~bodyArr: array<(string, JSON.t)>, ~confirmParam: ConfirmType.confirmParams, ~iframeId=keys.iframeId, ~isThirdPartyFlow=false, ~intentCallback=_ => (), ~manualRetry=false, ) => { switch keys.clientSecret { | Some(clientSecret) => let paymentIntentID = clientSecret->getPaymentId let headers = [ ("Content-Type", "application/json"), ("api-key", confirmParam.publishableKey), ("X-Client-Source", paymentTypeFromUrl->CardThemeType.getPaymentModeToStrMapper), ] let returnUrlArr = [("return_url", confirmParam.return_url->JSON.Encode.string)] let manual_retry = manualRetry ? [("retry_action", "manual_retry"->JSON.Encode.string)] : [] let body = [("client_secret", clientSecret->JSON.Encode.string)]->Array.concatMany([ returnUrlArr, manual_retry, ]) let endpoint = ApiEndpoint.getApiEndPoint( ~publishableKey=confirmParam.publishableKey, ~isConfirmCall=isThirdPartyFlow, ) let uri = `${endpoint}/payments/${paymentIntentID}/confirm` let callIntent = body => { let contentLength = body->String.length->Int.toString let maskedPayload = body->safeParseOpt->Option.getOr(JSON.Encode.null)->maskPayload->JSON.stringify let loggerPayload = [ ("payload", maskedPayload->JSON.Encode.string), ( "headers", headers ->Array.map(header => { let (key, value) = header (key, value->JSON.Encode.string) }) ->getJsonFromArrayOfJson, ), ] ->getJsonFromArrayOfJson ->JSON.stringify switch paymentType { | Card => handleLogging( ~optLogger, ~internalMetadata=loggerPayload, ~value=contentLength, ~eventName=PAYMENT_ATTEMPT, ~paymentMethod="CARD", ) | _ => bodyArr->Array.forEach(((str, json)) => { if str === "payment_method_type" { handleLogging( ~optLogger, ~value=contentLength, ~internalMetadata=loggerPayload, ~eventName=PAYMENT_ATTEMPT, ~paymentMethod=json->getStringFromJson(""), ) } () }) } if blockConfirm && GlobalVars.isInteg { Console.warn2("CONFIRM IS BLOCKED - Body", body) Console.warn2( "CONFIRM IS BLOCKED - Headers", headers->Dict.fromArray->Identity.anyTypeToJson->JSON.stringify, ) } else { intentCall( ~fetchApi, ~uri, ~headers, ~bodyStr=body, ~confirmParam: ConfirmType.confirmParams, ~clientSecret, ~optLogger, ~handleUserError, ~paymentType, ~iframeId, ~fetchMethod=#POST, ~setIsManualRetryEnabled, ~customPodUri, ~sdkHandleOneClickConfirmPayment=keys.sdkHandleOneClickConfirmPayment, ~counter=0, ~isCallbackUsedVal, ~componentName, ~redirectionFlags, ) ->then(val => { intentCallback(val) resolve() }) ->catch(_ => resolve()) ->ignore } } let broswerInfo = BrowserSpec.broswerInfo let intentWithoutMandate = mandatePaymentType => { let bodyStr = body ->Array.concatMany([ bodyArr->Array.concat(broswerInfo()), mandatePaymentType->PaymentBody.paymentTypeBody, ]) ->getJsonFromArrayOfJson ->JSON.stringify callIntent(bodyStr) } let intentWithMandate = mandatePaymentType => { let bodyStr = body ->Array.concat( bodyArr->Array.concatMany([PaymentBody.mandateBody(mandatePaymentType), broswerInfo()]), ) ->getJsonFromArrayOfJson ->JSON.stringify callIntent(bodyStr) } switch paymentMethodList { | LoadError(data) | Loaded(data) => let paymentList = data->getDictFromJson->PaymentMethodsRecord.itemToObjMapper let mandatePaymentType = paymentList.payment_type->PaymentMethodsRecord.paymentTypeToStringMapper if paymentList.payment_methods->Array.length > 0 { switch paymentList.mandate_payment { | Some(_) => switch paymentType { | Card | Gpay | Applepay | KlarnaRedirect | Paypal | BankDebits => intentWithMandate(mandatePaymentType) | _ => intentWithoutMandate(mandatePaymentType) } | None => intentWithoutMandate(mandatePaymentType) } } else { postFailedSubmitResponse( ~errortype="payment_methods_empty", ~message="Payment Failed. Try again!", ) Console.warn("Please enable atleast one Payment method.") } | SemiLoaded => intentWithoutMandate("") | _ => postFailedSubmitResponse( ~errortype="payment_methods_loading", ~message="Please wait. Try again!", ) } | None => postFailedSubmitResponse( ~errortype="confirm_payment_failed", ~message="Payment failed. Try again!", ) } } } let fetchSessions = ( ~clientSecret, ~publishableKey, ~wallets=[], ~isDelayedSessionToken=false, ~optLogger, ~customPodUri, ~endpoint, ~isPaymentSession=false, ~merchantHostname=Window.Location.hostname, ) => { open Promise let headers = [ ("Content-Type", "application/json"), ("api-key", publishableKey), ("X-Merchant-Domain", merchantHostname), ] let paymentIntentID = clientSecret->getPaymentId let body = [ ("payment_id", paymentIntentID->JSON.Encode.string), ("client_secret", clientSecret->JSON.Encode.string), ("wallets", wallets->JSON.Encode.array), ("delayed_session_token", isDelayedSessionToken->JSON.Encode.bool), ]->getJsonFromArrayOfJson let uri = `${endpoint}/payments/session_tokens` logApi( ~optLogger, ~url=uri, ~apiLogType=Request, ~eventName=SESSIONS_CALL_INIT, ~logType=INFO, ~logCategory=API, ~isPaymentSession, ) fetchApi( uri, ~method=#POST, ~bodyStr=body->JSON.stringify, ~headers=headers->ApiEndpoint.addCustomPodHeader(~customPodUri), ) ->then(resp => { let statusCode = resp->Fetch.Response.status->Int.toString if statusCode->String.charAt(0) !== "2" { resp ->Fetch.Response.json ->then(data => { logApi( ~optLogger, ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=SESSIONS_CALL, ~logType=ERROR, ~logCategory=API, ~isPaymentSession, ) JSON.Encode.null->resolve }) } else { logApi( ~optLogger, ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName=SESSIONS_CALL, ~logType=INFO, ~logCategory=API, ~isPaymentSession, ) Fetch.Response.json(resp) } }) ->catch(err => { let exceptionMessage = err->formatException logApi( ~optLogger, ~url=uri, ~apiLogType=NoResponse, ~eventName=SESSIONS_CALL, ~logType=ERROR, ~logCategory=API, ~data=exceptionMessage, ~isPaymentSession, ) JSON.Encode.null->resolve }) } let confirmPayout = (~clientSecret, ~publishableKey, ~logger, ~customPodUri, ~uri, ~body) => { open Promise let headers = [("Content-Type", "application/json"), ("api-key", publishableKey)] logApi( ~optLogger=Some(logger), ~url=uri, ~apiLogType=Request, ~eventName=CONFIRM_PAYOUT_CALL_INIT, ~logType=INFO, ~logCategory=API, ) let body = body ->Array.concat([("client_secret", clientSecret->JSON.Encode.string)]) ->getJsonFromArrayOfJson fetchApi( uri, ~method=#POST, ~bodyStr=body->JSON.stringify, ~headers=headers->ApiEndpoint.addCustomPodHeader(~customPodUri), ) ->then(resp => { let statusCode = resp->Fetch.Response.status->Int.toString resp ->Fetch.Response.json ->then(data => { if statusCode->String.charAt(0) !== "2" { logApi( ~optLogger=Some(logger), ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=CONFIRM_PAYOUT_CALL, ~logType=ERROR, ~logCategory=API, ) } else { logApi( ~optLogger=Some(logger), ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName=CONFIRM_PAYOUT_CALL, ~logType=INFO, ~logCategory=API, ) } resolve(data) }) }) ->catch(err => { let exceptionMessage = err->formatException logApi( ~optLogger=Some(logger), ~url=uri, ~apiLogType=NoResponse, ~eventName=CONFIRM_PAYOUT_CALL, ~logType=ERROR, ~logCategory=API, ~data=exceptionMessage, ) JSON.Encode.null->resolve }) } let createPaymentMethod = ( ~clientSecret, ~publishableKey, ~logger, ~customPodUri, ~endpoint, ~body, ) => { open Promise let headers = [("Content-Type", "application/json"), ("api-key", publishableKey)] let uri = `${endpoint}/payment_methods` logApi( ~optLogger=Some(logger), ~url=uri, ~apiLogType=Request, ~eventName=CREATE_CUSTOMER_PAYMENT_METHODS_CALL_INIT, ~logType=INFO, ~logCategory=API, ) let body = body ->Array.concat([("client_secret", clientSecret->JSON.Encode.string)]) ->getJsonFromArrayOfJson fetchApi( uri, ~method=#POST, ~bodyStr=body->JSON.stringify, ~headers=headers->ApiEndpoint.addCustomPodHeader(~customPodUri), ) ->then(resp => { let statusCode = resp->Fetch.Response.status->Int.toString if statusCode->String.charAt(0) !== "2" { resp ->Fetch.Response.json ->then(data => { logApi( ~optLogger=Some(logger), ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=CREATE_CUSTOMER_PAYMENT_METHODS_CALL, ~logType=ERROR, ~logCategory=API, ) JSON.Encode.null->resolve }) } else { logApi( ~optLogger=Some(logger), ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName=CREATE_CUSTOMER_PAYMENT_METHODS_CALL, ~logType=INFO, ~logCategory=API, ) Fetch.Response.json(resp) } }) ->catch(err => { let exceptionMessage = err->formatException logApi( ~optLogger=Some(logger), ~url=uri, ~apiLogType=NoResponse, ~eventName=CREATE_CUSTOMER_PAYMENT_METHODS_CALL, ~logType=ERROR, ~logCategory=API, ~data=exceptionMessage, ) JSON.Encode.null->resolve }) } let fetchPaymentMethodList = ( ~clientSecret, ~publishableKey, ~logger, ~customPodUri, ~endpoint, ) => { open Promise let headers = [("Content-Type", "application/json"), ("api-key", publishableKey)] let uri = `${endpoint}/account/payment_methods?client_secret=${clientSecret}` logApi( ~optLogger=Some(logger), ~url=uri, ~apiLogType=Request, ~eventName=PAYMENT_METHODS_CALL_INIT, ~logType=INFO, ~logCategory=API, ) fetchApi(uri, ~method=#GET, ~headers=headers->ApiEndpoint.addCustomPodHeader(~customPodUri)) ->then(resp => { let statusCode = resp->Fetch.Response.status->Int.toString if statusCode->String.charAt(0) !== "2" { resp ->Fetch.Response.json ->then(data => { logApi( ~optLogger=Some(logger), ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=PAYMENT_METHODS_CALL, ~logType=ERROR, ~logCategory=API, ) JSON.Encode.null->resolve }) } else { logApi( ~optLogger=Some(logger), ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName=PAYMENT_METHODS_CALL, ~logType=INFO, ~logCategory=API, ) Fetch.Response.json(resp) } }) ->catch(err => { let exceptionMessage = err->formatException logApi( ~optLogger=Some(logger), ~url=uri, ~apiLogType=NoResponse, ~eventName=PAYMENT_METHODS_CALL, ~logType=ERROR, ~logCategory=API, ~data=exceptionMessage, ) JSON.Encode.null->resolve }) } let fetchCustomerPaymentMethodList = ( ~clientSecret, ~publishableKey, ~endpoint, ~optLogger, ~customPodUri, ~isPaymentSession=false, ) => { open Promise let headers = [("Content-Type", "application/json"), ("api-key", publishableKey)] let uri = `${endpoint}/customers/payment_methods?client_secret=${clientSecret}` logApi( ~optLogger, ~url=uri, ~apiLogType=Request, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL_INIT, ~logType=INFO, ~logCategory=API, ~isPaymentSession, ) fetchApi(uri, ~method=#GET, ~headers=headers->ApiEndpoint.addCustomPodHeader(~customPodUri)) ->then(res => { let statusCode = res->Fetch.Response.status->Int.toString if statusCode->String.charAt(0) !== "2" { res ->Fetch.Response.json ->then(data => { logApi( ~optLogger, ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~logType=ERROR, ~logCategory=API, ~isPaymentSession, ) JSON.Encode.null->resolve }) } else { logApi( ~optLogger, ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~logType=INFO, ~logCategory=API, ~isPaymentSession, ) res->Fetch.Response.json } }) ->catch(err => { let exceptionMessage = err->formatException logApi( ~optLogger, ~url=uri, ~apiLogType=NoResponse, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~logType=ERROR, ~logCategory=API, ~data=exceptionMessage, ~isPaymentSession, ) JSON.Encode.null->resolve }) } let paymentIntentForPaymentSession = ( ~body, ~paymentType, ~payload, ~publishableKey, ~clientSecret, ~logger, ~customPodUri, ~redirectionFlags, ) => { let confirmParams = payload ->getDictFromJson ->getDictFromDict("confirmParams") let redirect = confirmParams->getString("redirect", "if_required") let returnUrl = confirmParams->getString("return_url", "") let confirmParam: ConfirmType.confirmParams = { return_url: returnUrl, publishableKey, redirect, } let paymentIntentID = String.split(clientSecret, "_secret_")[0]->Option.getOr("") let endpoint = ApiEndpoint.getApiEndPoint( ~publishableKey=confirmParam.publishableKey, ~isConfirmCall=true, ) let uri = `${endpoint}/payments/${paymentIntentID}/confirm` let headers = [("Content-Type", "application/json"), ("api-key", confirmParam.publishableKey)] let broswerInfo = BrowserSpec.broswerInfo() let returnUrlArr = [("return_url", confirmParam.return_url->JSON.Encode.string)] let bodyStr = body ->Array.concatMany([ broswerInfo, [("client_secret", clientSecret->JSON.Encode.string)], returnUrlArr, ]) ->getJsonFromArrayOfJson ->JSON.stringify intentCall( ~fetchApi, ~uri, ~headers, ~bodyStr, ~confirmParam: ConfirmType.confirmParams, ~clientSecret, ~optLogger=Some(logger), ~handleUserError=false, ~paymentType, ~iframeId="", ~fetchMethod=#POST, ~setIsManualRetryEnabled={_ => ()}, ~customPodUri, ~sdkHandleOneClickConfirmPayment=false, ~counter=0, ~isPaymentSession=true, ~redirectionFlags, ) } let callAuthLink = ( ~publishableKey, ~clientSecret, ~paymentMethodType, ~pmAuthConnectorsArr, ~iframeId, ~optLogger, ) => { open Promise let endpoint = ApiEndpoint.getApiEndPoint() let uri = `${endpoint}/payment_methods/auth/link` let headers = [("Content-Type", "application/json"), ("api-key", publishableKey)]->Dict.fromArray logApi( ~optLogger, ~url=uri, ~apiLogType=Request, ~eventName=PAYMENT_METHODS_AUTH_LINK_CALL_INIT, ~logType=INFO, ~logCategory=API, ) fetchApi( uri, ~method=#POST, ~bodyStr=[ ("client_secret", clientSecret->Option.getOr("")->JSON.Encode.string), ("payment_id", clientSecret->Option.getOr("")->getPaymentId->JSON.Encode.string), ("payment_method", "bank_debit"->JSON.Encode.string), ("payment_method_type", paymentMethodType->JSON.Encode.string), ] ->getJsonFromArrayOfJson ->JSON.stringify, ~headers, ) ->then(res => { let statusCode = res->Fetch.Response.status->Int.toString if statusCode->String.charAt(0) !== "2" { res ->Fetch.Response.json ->then(data => { logApi( ~optLogger, ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=PAYMENT_METHODS_AUTH_LINK_CALL, ~logType=ERROR, ~logCategory=API, ) JSON.Encode.null->resolve }) } else { res ->Fetch.Response.json ->then(data => { let metaData = [ ("linkToken", data->getDictFromJson->getString("link_token", "")->JSON.Encode.string), ("pmAuthConnectorArray", pmAuthConnectorsArr->anyTypeToJson), ("publishableKey", publishableKey->JSON.Encode.string), ("clientSecret", clientSecret->Option.getOr("")->JSON.Encode.string), ("isForceSync", false->JSON.Encode.bool), ]->getJsonFromArrayOfJson messageParentWindow([ ("fullscreen", true->JSON.Encode.bool), ("param", "plaidSDK"->JSON.Encode.string), ("iframeId", iframeId->JSON.Encode.string), ("metadata", metaData), ]) logApi( ~optLogger, ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName=PAYMENT_METHODS_AUTH_LINK_CALL, ~logType=INFO, ~logCategory=API, ) JSON.Encode.null->resolve }) } }) ->catch(e => { logApi( ~optLogger, ~url=uri, ~apiLogType=NoResponse, ~eventName=PAYMENT_METHODS_AUTH_LINK_CALL, ~logType=ERROR, ~logCategory=API, ~data={e->formatException}, ) Console.error2("Unable to retrieve payment_methods auth/link because of ", e) JSON.Encode.null->resolve }) } let callAuthExchange = ( ~publicToken, ~clientSecret, ~paymentMethodType, ~publishableKey, ~setOptionValue: (PaymentType.options => PaymentType.options) => unit, ~optLogger, ) => { open Promise open PaymentType let endpoint = ApiEndpoint.getApiEndPoint() let logger = HyperLogger.make(~source=Elements(Payment)) let uri = `${endpoint}/payment_methods/auth/exchange` let updatedBody = [ ("client_secret", clientSecret->Option.getOr("")->JSON.Encode.string), ("payment_id", clientSecret->Option.getOr("")->getPaymentId->JSON.Encode.string), ("payment_method", "bank_debit"->JSON.Encode.string), ("payment_method_type", paymentMethodType->JSON.Encode.string), ("public_token", publicToken->JSON.Encode.string), ] let headers = [("Content-Type", "application/json"), ("api-key", publishableKey)]->Dict.fromArray logApi( ~optLogger, ~url=uri, ~apiLogType=Request, ~eventName=PAYMENT_METHODS_AUTH_EXCHANGE_CALL_INIT, ~logType=INFO, ~logCategory=API, ) fetchApi( uri, ~method=#POST, ~bodyStr=updatedBody->getJsonFromArrayOfJson->JSON.stringify, ~headers, ) ->then(res => { let statusCode = res->Fetch.Response.status->Int.toString if statusCode->String.charAt(0) !== "2" { res ->Fetch.Response.json ->then(data => { logApi( ~optLogger, ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=PAYMENT_METHODS_AUTH_EXCHANGE_CALL, ~logType=ERROR, ~logCategory=API, ) JSON.Encode.null->resolve }) } else { logApi( ~optLogger, ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName=PAYMENT_METHODS_AUTH_EXCHANGE_CALL, ~logType=INFO, ~logCategory=API, ) fetchCustomerPaymentMethodList( ~clientSecret=clientSecret->Option.getOr(""), ~publishableKey, ~optLogger=Some(logger), ~customPodUri="", ~endpoint, ) ->then(customerListResponse => { let customerListResponse = [("customerPaymentMethods", customerListResponse)]->Dict.fromArray setOptionValue( prev => { ...prev, customerPaymentMethods: customerListResponse->createCustomerObjArr( "customerPaymentMethods", ), }, ) JSON.Encode.null->resolve }) ->catch(e => { Console.error2( "Unable to retrieve customer/payment_methods after auth/exchange because of ", e, ) JSON.Encode.null->resolve }) } }) ->catch(e => { logApi( ~optLogger, ~url=uri, ~apiLogType=NoResponse, ~eventName=PAYMENT_METHODS_AUTH_EXCHANGE_CALL, ~logType=ERROR, ~logCategory=API, ~data={e->formatException}, ) Console.error2("Unable to retrieve payment_methods auth/exchange because of ", e) JSON.Encode.null->resolve }) } let fetchSavedPaymentMethodList = ( ~ephemeralKey, ~endpoint, ~optLogger, ~customPodUri, ~isPaymentSession=false, ) => { open Promise let headers = [("Content-Type", "application/json"), ("api-key", ephemeralKey)] let uri = `${endpoint}/customers/payment_methods` logApi( ~optLogger, ~url=uri, ~apiLogType=Request, ~eventName=SAVED_PAYMENT_METHODS_CALL_INIT, ~logType=INFO, ~logCategory=API, ~isPaymentSession, ) fetchApi(uri, ~method=#GET, ~headers=headers->ApiEndpoint.addCustomPodHeader(~customPodUri)) ->then(res => { let statusCode = res->Fetch.Response.status->Int.toString if statusCode->String.charAt(0) !== "2" { res ->Fetch.Response.json ->then(data => { logApi( ~optLogger, ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~logType=ERROR, ~logCategory=API, ~isPaymentSession, ) JSON.Encode.null->resolve }) } else { logApi( ~optLogger, ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~logType=INFO, ~logCategory=API, ~isPaymentSession, ) res->Fetch.Response.json } }) ->catch(err => { let exceptionMessage = err->formatException logApi( ~optLogger, ~url=uri, ~apiLogType=NoResponse, ~eventName=CUSTOMER_PAYMENT_METHODS_CALL, ~logType=ERROR, ~logCategory=API, ~data=exceptionMessage, ~isPaymentSession, ) JSON.Encode.null->resolve }) } let deletePaymentMethod = (~ephemeralKey, ~paymentMethodId, ~logger, ~customPodUri) => { open Promise let endpoint = ApiEndpoint.getApiEndPoint() let headers = [("Content-Type", "application/json"), ("api-key", ephemeralKey)] let uri = `${endpoint}/payment_methods/${paymentMethodId}` logApi( ~optLogger=Some(logger), ~url=uri, ~apiLogType=Request, ~eventName=DELETE_PAYMENT_METHODS_CALL_INIT, ~logType=INFO, ~logCategory=API, ) fetchApi(uri, ~method=#DELETE, ~headers=headers->ApiEndpoint.addCustomPodHeader(~customPodUri)) ->then(resp => { let statusCode = resp->Fetch.Response.status->Int.toString if statusCode->String.charAt(0) !== "2" { resp ->Fetch.Response.json ->then(data => { logApi( ~optLogger=Some(logger), ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=DELETE_PAYMENT_METHODS_CALL, ~logType=ERROR, ~logCategory=API, ) JSON.Encode.null->resolve }) } else { logApi( ~optLogger=Some(logger), ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName=DELETE_PAYMENT_METHODS_CALL, ~logType=INFO, ~logCategory=API, ) Fetch.Response.json(resp) } }) ->catch(err => { let exceptionMessage = err->formatException logApi( ~optLogger=Some(logger), ~url=uri, ~apiLogType=NoResponse, ~eventName=DELETE_PAYMENT_METHODS_CALL, ~logType=ERROR, ~logCategory=API, ~data=exceptionMessage, ) JSON.Encode.null->resolve }) } let calculateTax = ( ~apiKey, ~paymentId, ~clientSecret, ~paymentMethodType, ~shippingAddress, ~logger, ~customPodUri, ~sessionId, ) => { open Promise let endpoint = ApiEndpoint.getApiEndPoint() let headers = [("Content-Type", "application/json"), ("api-key", apiKey)] let uri = `${endpoint}/payments/${paymentId}/calculate_tax` let body = [ ("client_secret", clientSecret), ("shipping", shippingAddress), ("payment_method_type", paymentMethodType), ] sessionId->Option.mapOr((), id => body->Array.push(("session_id", id))->ignore) logApi( ~optLogger=Some(logger), ~url=uri, ~apiLogType=Request, ~eventName=EXTERNAL_TAX_CALCULATION, ~logType=INFO, ~logCategory=API, ) fetchApi( uri, ~method=#POST, ~headers=headers->ApiEndpoint.addCustomPodHeader(~customPodUri), ~bodyStr=body->getJsonFromArrayOfJson->JSON.stringify, ) ->then(resp => { let statusCode = resp->Fetch.Response.status->Int.toString if statusCode->String.charAt(0) !== "2" { resp ->Fetch.Response.json ->then(data => { logApi( ~optLogger=Some(logger), ~url=uri, ~data, ~statusCode, ~apiLogType=Err, ~eventName=EXTERNAL_TAX_CALCULATION, ~logType=ERROR, ~logCategory=API, ) JSON.Encode.null->resolve }) } else { logApi( ~optLogger=Some(logger), ~url=uri, ~statusCode, ~apiLogType=Response, ~eventName=EXTERNAL_TAX_CALCULATION, ~logType=INFO, ~logCategory=API, ) resp->Fetch.Response.json } }) ->catch(err => { let exceptionMessage = err->formatException logApi( ~optLogger=Some(logger), ~url=uri, ~apiLogType=NoResponse, ~eventName=EXTERNAL_TAX_CALCULATION, ~logType=ERROR, ~logCategory=API, ~data=exceptionMessage, ) JSON.Encode.null->resolve }) } let usePostSessionTokens = ( optLogger, paymentType: payment, paymentMethod: PaymentMethodCollectTypes.paymentMethod, ) => { open RecoilAtoms open Promise let url = RescriptReactRouter.useUrl() let paymentTypeFromUrl = CardUtils.getQueryParamsDictforKey(url.search, "componentName")->CardThemeType.getPaymentMode let customPodUri = Recoil.useRecoilValueFromAtom(customPodUri) let paymentMethodList = Recoil.useRecoilValueFromAtom(paymentMethodList) let keys = Recoil.useRecoilValueFromAtom(keys) let redirectionFlags = Recoil.useRecoilValueFromAtom(RecoilAtoms.redirectionFlagsAtom) let setIsManualRetryEnabled = Recoil.useSetRecoilState(isManualRetryEnabled) ( ~handleUserError=false, ~bodyArr: array<(string, JSON.t)>, ~confirmParam: ConfirmType.confirmParams, ~iframeId=keys.iframeId, ~isThirdPartyFlow=false, ~intentCallback=_ => (), ~manualRetry as _=false, ) => { switch keys.clientSecret { | Some(clientSecret) => let paymentIntentID = clientSecret->getPaymentId let headers = [ ("Content-Type", "application/json"), ("api-key", confirmParam.publishableKey), ("X-Client-Source", paymentTypeFromUrl->CardThemeType.getPaymentModeToStrMapper), ] let body = [ ("client_secret", clientSecret->JSON.Encode.string), ("payment_id", paymentIntentID->JSON.Encode.string), ("payment_method_type", (paymentType :> string)->JSON.Encode.string), ("payment_method", (paymentMethod :> string)->JSON.Encode.string), ] let endpoint = ApiEndpoint.getApiEndPoint( ~publishableKey=confirmParam.publishableKey, ~isConfirmCall=isThirdPartyFlow, ) let uri = `${endpoint}/payments/${paymentIntentID}/post_session_tokens` let callIntent = body => { let contentLength = body->String.length->Int.toString let maskedPayload = body->safeParseOpt->Option.getOr(JSON.Encode.null)->maskPayload->JSON.stringify let loggerPayload = [ ("payload", maskedPayload->JSON.Encode.string), ( "headers", headers ->Array.map(header => { let (key, value) = header (key, value->JSON.Encode.string) }) ->getJsonFromArrayOfJson, ), ] ->getJsonFromArrayOfJson ->JSON.stringify switch paymentType { | Card => handleLogging( ~optLogger, ~internalMetadata=loggerPayload, ~value=contentLength, ~eventName=PAYMENT_ATTEMPT, ~paymentMethod="CARD", ) | _ => bodyArr->Array.forEach(((str, json)) => { if str === "payment_method_type" { handleLogging( ~optLogger, ~value=contentLength, ~internalMetadata=loggerPayload, ~eventName=PAYMENT_ATTEMPT, ~paymentMethod=json->getStringFromJson(""), ) } () }) } intentCall( ~fetchApi, ~uri, ~headers, ~bodyStr=body, ~confirmParam: ConfirmType.confirmParams, ~clientSecret, ~optLogger, ~handleUserError, ~paymentType, ~iframeId, ~fetchMethod=#POST, ~setIsManualRetryEnabled, ~customPodUri, ~sdkHandleOneClickConfirmPayment=keys.sdkHandleOneClickConfirmPayment, ~counter=0, ~redirectionFlags, ) ->then(val => { intentCallback(val) resolve() }) ->catch(_ => Promise.resolve()) ->ignore } let broswerInfo = BrowserSpec.broswerInfo let intentWithoutMandate = mandatePaymentType => { let bodyStr = body ->Array.concatMany([ bodyArr->Array.concat(broswerInfo()), mandatePaymentType->PaymentBody.paymentTypeBody, ]) ->getJsonFromArrayOfJson ->JSON.stringify callIntent(bodyStr) } let intentWithMandate = mandatePaymentType => { let bodyStr = body ->Array.concat( bodyArr->Array.concatMany([PaymentBody.mandateBody(mandatePaymentType), broswerInfo()]), ) ->getJsonFromArrayOfJson ->JSON.stringify callIntent(bodyStr) } switch paymentMethodList { | LoadError(data) | Loaded(data) => let paymentList = data->getDictFromJson->PaymentMethodsRecord.itemToObjMapper let mandatePaymentType = paymentList.payment_type->PaymentMethodsRecord.paymentTypeToStringMapper if paymentList.payment_methods->Array.length > 0 { switch paymentList.mandate_payment { | Some(_) => switch paymentType { | Card | Gpay | Applepay | KlarnaRedirect | Paypal | BankDebits => intentWithMandate(mandatePaymentType) | _ => intentWithoutMandate(mandatePaymentType) } | None => intentWithoutMandate(mandatePaymentType) } } else { postFailedSubmitResponse( ~errortype="payment_methods_empty", ~message="Payment Failed. Try again!", ) Console.warn("Please enable atleast one Payment method.") } | SemiLoaded => intentWithoutMandate("") | _ => postFailedSubmitResponse( ~errortype="payment_methods_loading", ~message="Please wait. Try again!", ) } | None => postFailedSubmitResponse( ~errortype="post_session_tokens_failed", ~message="Post Session Tokens failed. Try again!", ) } } }
16,397
10,530
hyperswitch-web
src/Utilities/RecoilAtoms.res
.res
open RecoilAtomTypes let keys = Recoil.atom("keys", CommonHooks.defaultkeys) let configAtom = Recoil.atom("defaultRecoilConfig", CardTheme.defaultRecoilConfig) let portalNodes = Recoil.atom("portalNodes", PortalState.defaultDict) let elementOptions = Recoil.atom("elementOptions", ElementType.defaultOptions) let optionAtom = Recoil.atom("options", PaymentType.defaultOptions) let sessions = Recoil.atom("sessions", PaymentType.Loading) let paymentMethodList = Recoil.atom("paymentMethodList", PaymentType.Loading) let loggerAtom = Recoil.atom("component", HyperLogger.defaultLoggerConfig) let sessionId = Recoil.atom("sessionId", "") let isConfirmBlocked = Recoil.atom("isConfirmBlocked", false) let customPodUri = Recoil.atom("customPodUri", "") let selectedOptionAtom = Recoil.atom("selectedOption", "") let paymentTokenAtom = Recoil.atom( "paymentToken", { paymentToken: "", customerId: "", }, ) let showCardFieldsAtom = Recoil.atom("showCardFields", false) let phoneJson = Recoil.atom("phoneJson", Loading) let cardBrand = Recoil.atom("cardBrand", "") let paymentMethodCollectOptionAtom = Recoil.atom( "paymentMethodCollectOptions", PaymentMethodCollectUtils.defaultPaymentMethodCollectOptions, ) let payoutDynamicFieldsAtom = Recoil.atom( "payoutDynamicFields", PaymentMethodCollectUtils.defaultPayoutDynamicFields(), ) let paymentMethodTypeAtom = Recoil.atom("paymentMethodType", PaymentMethodCollectUtils.defaultPmt()) let formDataAtom = Recoil.atom("formData", PaymentMethodCollectUtils.defaultFormDataDict) let validityDictAtom = Recoil.atom("validityDict", PaymentMethodCollectUtils.defaultValidityDict) let defaultFieldValues = { value: "", isValid: None, errorString: "", } let userFullName = Recoil.atom("userFullName", defaultFieldValues) let userEmailAddress = Recoil.atom("userEmailAddress", defaultFieldValues) let userPhoneNumber = Recoil.atom( "userPhoneNumber", { ...defaultFieldValues, countryCode: "", }, ) let userCardNickName = Recoil.atom("userCardNickName", defaultFieldValues) let isGooglePayReady = Recoil.atom("isGooglePayReady", false) let isApplePayReady = Recoil.atom("isApplePayReady", false) let isSamsungPayReady = Recoil.atom("isSamsungPayReady", false) let userCountry = Recoil.atom("userCountry", "") let userBank = Recoil.atom("userBank", "") let userAddressline1 = Recoil.atom("userAddressline1", defaultFieldValues) let userAddressline2 = Recoil.atom("userAddressline2", defaultFieldValues) let userAddressCity = Recoil.atom("userAddressCity", defaultFieldValues) let userAddressPincode = Recoil.atom("userAddressPincode", defaultFieldValues) let userAddressState = Recoil.atom("userAddressState", defaultFieldValues) let userAddressCountry = Recoil.atom("userAddressCountry", defaultFieldValues) let userBlikCode = Recoil.atom("userBlikCode", defaultFieldValues) let fieldsComplete = Recoil.atom("fieldsComplete", false) let isManualRetryEnabled = Recoil.atom("isManualRetryEnabled", false) let userCurrency = Recoil.atom("userCurrency", "") let cryptoCurrencyNetworks = Recoil.atom("cryptoCurrencyNetworks", "") let isShowOrPayUsing = Recoil.atom("isShowOrPayUsing", false) let areRequiredFieldsValid = Recoil.atom("areRequiredFieldsValid", true) let areRequiredFieldsEmpty = Recoil.atom("areRequiredFieldsEmpty", false) let dateOfBirth = Recoil.atom("dateOfBirth", Nullable.null) let userBillingName = Recoil.atom("userBillingName", defaultFieldValues) let userVpaId = Recoil.atom("userVpaId", defaultFieldValues) let userPixKey = Recoil.atom("userPixKey", defaultFieldValues) let userPixCPF = Recoil.atom("userPixCPF", defaultFieldValues) let userPixCNPJ = Recoil.atom("userPixCNPJ", defaultFieldValues) let isCompleteCallbackUsed = Recoil.atom("isCompleteCallbackUsed", false) let isPaymentButtonHandlerProvidedAtom = Recoil.atom("isPaymentButtonHandlerProvidedAtom", false) let userBankAccountNumber = Recoil.atom("userBankAccountNumber", defaultFieldValues) type areOneClickWalletsRendered = { isGooglePay: bool, isApplePay: bool, isPaypal: bool, isKlarna: bool, isSamsungPay: bool, } let defaultAreOneClickWalletsRendered = { isGooglePay: false, isApplePay: false, isPaypal: false, isKlarna: false, isSamsungPay: false, } let areOneClickWalletsRendered = Recoil.atom( "areOneClickWalletsBtnRendered", defaultAreOneClickWalletsRendered, ) type clickToPayConfig = { isReady: option<bool>, availableCardBrands: array<string>, email: string, clickToPayCards: option<array<ClickToPayHelpers.clickToPayCard>>, dpaName: string, } let defaultClickToPayConfig = { isReady: None, availableCardBrands: [], email: "", clickToPayCards: None, dpaName: "", } let clickToPayConfig = Recoil.atom("clickToPayConfig", defaultClickToPayConfig) let defaultRedirectionFlags: redirectionFlags = { shouldUseTopRedirection: false, shouldRemoveBeforeUnloadEvents: false, } let redirectionFlagsAtom = Recoil.atom("redirectionFlags", defaultRedirectionFlags)
1,243
10,531
hyperswitch-web
src/Utilities/PmAuthConnectorUtils.res
.res
type pmAuthConnector = PLAID | NONE type isPmAuthConnectorReady = {plaid: bool} let pmAuthNameToTypeMapper = authConnectorName => { switch authConnectorName { | "plaid" => PLAID | _ => NONE } } let pmAuthConnectorToScriptUrlMapper = authConnector => { switch authConnector { | PLAID => "https://cdn.plaid.com/link/v2/stable/link-initialize.js" | NONE => "" } } let mountAuthConnectorScript = ( ~authConnector, ~onScriptLoaded, ~logger: HyperLogger.loggerMake, ) => { let authConnector = authConnector->Option.getOr("") let pmAuthConnectorScriptUrl = authConnector->pmAuthNameToTypeMapper->pmAuthConnectorToScriptUrlMapper let pmAuthConnectorScript = Window.createElement("script") logger.setLogInfo( ~value=`Pm Auth Connector ${authConnector} Script Loading`, ~eventName=PM_AUTH_CONNECTOR_SCRIPT, ) pmAuthConnectorScript->Window.elementSrc(pmAuthConnectorScriptUrl) pmAuthConnectorScript->Window.elementOnerror(_ => { logger.setLogInfo( ~value=`Pm Auth Connector ${authConnector} Script Load Failure`, ~eventName=PM_AUTH_CONNECTOR_SCRIPT, ) }) pmAuthConnectorScript->Window.elementOnload(_ => { onScriptLoaded(authConnector) logger.setLogInfo( ~value=`Pm Auth Connector ${authConnector} Script Loaded`, ~eventName=PM_AUTH_CONNECTOR_SCRIPT, ) }) Window.body->Window.appendChild(pmAuthConnectorScript) } let mountAllRequriedAuthConnectorScripts = ( ~pmAuthConnectorsArr, ~onScriptLoaded, ~logger: HyperLogger.loggerMake, ) => { pmAuthConnectorsArr->Array.forEach(item => { mountAuthConnectorScript(~authConnector=item, ~onScriptLoaded, ~logger) }) } let findPmAuthAllPMAuthConnectors = ( paymentMethodListValue: array<PaymentMethodsRecord.methods>, ) => { let bankDebitPaymentMethodsArr = paymentMethodListValue->Array.filter(item => item.payment_method == "bank_debit") let pmAuthConnectorDict = Dict.make() bankDebitPaymentMethodsArr->Array.forEach(item => { item.payment_method_types->Array.forEach(item => { if item.pm_auth_connector->Option.isSome { pmAuthConnectorDict->Dict.set(item.payment_method_type, item.pm_auth_connector) } }) }) pmAuthConnectorDict } let getAllRequiredPmAuthConnectors = pmAuthConnectorsDict => { let requiredPmAuthConnectorsArr = pmAuthConnectorsDict->Dict.valuesToArray requiredPmAuthConnectorsArr->Array.filterWithIndex((item, idx) => idx == requiredPmAuthConnectorsArr->Array.indexOf(item) ) }
631
10,532
hyperswitch-web
src/Utilities/Phone_number.json
.json
{ "countries": [ { "country_code": "AF", "country_name": "Afghanistan", "country_flag": "🇦🇫", "phone_number_code": "+93", "validation_regex": "^(\\+?93)?\\d{9}$", "format_example": "0701234567", "format_regex": "^\\d{10}$" }, { "country_code": "AL", "country_name": "Albania", "country_flag": "🇦🇱", "phone_number_code": "+355", "validation_regex": "^(\\+?355|0)6[789]\\d{7}$", "format_example": "0671234567", "format_regex": "^\\d{10}$" }, { "country_code": "DZ", "country_name": "Algeria", "country_flag": "🇩🇿", "phone_number_code": "+213", "validation_regex": "^(\\+?213|0)(5|6|7)\\d{8}$", "format_example": "0551234567", "format_regex": "^\\d{10}$" }, { "country_code": "AD", "country_name": "Andorra", "country_flag": "🇦🇩", "phone_number_code": "+376", "validation_regex": "^(\\+?376)?\\d{6}$", "format_example": "612345", "format_regex": "^\\d{6}$" }, { "country_code": "AO", "country_name": "Angola", "country_flag": "🇦🇴", "phone_number_code": "+244", "validation_regex": "^(\\+?244)\\d{9}$", "format_example": "923123456", "format_regex": "^\\d{9}$" }, { "country_code": "AG", "country_name": "Antigua and Barbuda", "country_flag": "🇦🇬", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?268\\d{7}$", "format_example": "(268) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "AR", "country_name": "Argentina", "country_flag": "🇦🇷", "phone_number_code": "+54", "validation_regex": "^(\\+?54)?9?(11|2\\d|3[0-9])\\d{8}$", "format_example": "91123456789", "format_regex": "^(\\d{2})?(\\d{4})(\\d{4})$" }, { "country_code": "AM", "country_name": "Armenia", "country_flag": "🇦🇲", "phone_number_code": "+374", "validation_regex": "^(\\+?374)?(10|55|77|93)\\d{6}$", "format_example": "091123456", "format_regex": "^(\\d{3})(\\d{6})$" }, { "country_code": "AU", "country_name": "Australia", "country_flag": "🇦🇺", "phone_number_code": "+61", "validation_regex": "^(\\+?61|0)[2-478](?!11)\\d{8}$", "format_example": "0412345678", "format_regex": "^(\\d{4})(\\d{3})(\\d{3})$" }, { "country_code": "AT", "country_name": "Austria", "country_flag": "🇦🇹", "phone_number_code": "+43", "validation_regex": "^(\\+?43|0)\\d{4,5}\\d{4,}$", "format_example": "06641234567", "format_regex": "^(\\d{4,5})(\\d{4,})$" }, { "country_code": "AZ", "country_name": "Azerbaijan", "country_flag": "🇦🇿", "phone_number_code": "+994", "validation_regex": "^(\\+?994|0)5\\d{8}$", "format_example": "0501234567", "format_regex": "^\\d{10}$" }, { "country_code": "BS", "country_name": "Bahamas", "country_flag": "🇧🇸", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?242\\d{7}$", "format_example": "(242) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "BH", "country_name": "Bahrain", "country_flag": "🇧🇭", "phone_number_code": "+973", "validation_regex": "^(\\+?973)?\\d{8}$", "format_example": "34567890", "format_regex": "^\\d{8}$" }, { "country_code": "BD", "country_name": "Bangladesh", "country_flag": "🇧🇩", "phone_number_code": "+880", "validation_regex": "^(\\+?880|0)1[13456789][0-9]{8}$", "format_example": "01712345678", "format_regex": "^(\\d{3})(\\d{3})(\\d{4})$" }, { "country_code": "BB", "country_name": "Barbados", "country_flag": "🇧🇧", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?246\\d{7}$", "format_example": "(246) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "BY", "country_name": "Belarus", "country_flag": "🇧🇾", "phone_number_code": "+375", "validation_regex": "^(\\+?375)(24|25|29|33|44)\\d{7}$", "format_example": "291234567", "format_regex": "^(\\d{2})(\\d{3})(\\d{2})(\\d{2})$" }, { "country_code": "BE", "country_name": "Belgium", "country_flag": "🇧🇪", "phone_number_code": "+32", "validation_regex": "^(\\+?32|0)\\d{8,9}$", "format_example": "0470123456", "format_regex": "^(\\d{3})(\\d{2})(\\d{2})(\\d{2})$" }, { "country_code": "BZ", "country_name": "Belize", "country_flag": "🇧🇿", "phone_number_code": "+501", "validation_regex": "^(\\+?501)?\\d{7}$", "format_example": "6101234", "format_regex": "^\\d{7}$" }, { "country_code": "BJ", "country_name": "Benin", "country_flag": "🇧🇯", "phone_number_code": "+229", "validation_regex": "^(\\+?229)?\\d{8}$", "format_example": "90123456", "format_regex": "^\\d{8}$" }, { "country_code": "BT", "country_name": "Bhutan", "country_flag": "🇧🇹", "phone_number_code": "+975", "validation_regex": "^(\\+?975)?\\d{7}$", "format_example": "17123456", "format_regex": "^\\d{7}$" }, { "country_code": "BO", "country_name": "Bolivia", "country_flag": "🇧🇴", "phone_number_code": "+591", "validation_regex": "^(\\+?591)?([2679]\\d{7,8}|[1-5]\\d{1,7})$", "format_example": "71234567", "format_regex": "^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{1})$" }, { "country_code": "BA", "country_name": "Bosnia and Herzegovina", "country_flag": "🇧🇦", "phone_number_code": "+387", "validation_regex": "^(\\+?387|0)6[0-6]\\d{6}$", "format_example": "061234567", "format_regex": "^\\d{9}$" }, { "country_code": "BW", "country_name": "Botswana", "country_flag": "🇧🇼", "phone_number_code": "+267", "validation_regex": "^(\\+?267)?\\d{7}$", "format_example": "71123456", "format_regex": "^\\d{8}$" }, { "country_code": "BR", "country_name": "Brazil", "country_flag": "🇧🇷", "phone_number_code": "+55", "validation_regex": "^(\\+?55|0[1-9]{2})[2-9]\\d{7,8}$", "format_example": "01123456789", "format_regex": "^(\\d{2})(\\d{5})(\\d{4})$" }, { "country_code": "BN", "country_name": "Brunei", "country_flag": "🇧🇳", "phone_number_code": "+673", "validation_regex": "^(\\+?673)?\\d{7}$", "format_example": "7123456", "format_regex": "^\\d{7}$" }, { "country_code": "BG", "country_name": "Bulgaria", "country_flag": "🇧🇬", "phone_number_code": "+359", "validation_regex": "^(\\+?359|0)8[789]\\d{7}$", "format_example": "0888123456", "format_regex": "^\\d{10}$" }, { "country_code": "BF", "country_name": "Burkina Faso", "country_flag": "🇧🇫", "phone_number_code": "+226", "validation_regex": "^(\\+?226)?\\d{8}$", "format_example": "70123456", "format_regex": "^\\d{8}$" }, { "country_code": "BI", "country_name": "Burundi", "country_flag": "🇧🇮", "phone_number_code": "+257", "validation_regex": "^(\\+?257)?\\d{8}$", "format_example": "79123456", "format_regex": "^\\d{8}$" }, { "country_code": "KH", "country_name": "Cambodia", "country_flag": "🇰🇭", "phone_number_code": "+855", "validation_regex": "^(\\+?855|0)1\\d{8}$", "format_example": "091234567", "format_regex": "^\\d{9}$" }, { "country_code": "CM", "country_name": "Cameroon", "country_flag": "🇨🇲", "phone_number_code": "+237", "validation_regex": "^(\\+?237)?[2368]\\d{7,8}$", "format_example": "671234567", "format_regex": "^\\d{9}$" }, { "country_code": "CA", "country_name": "Canada", "country_flag": "🇨🇦", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?[2-9]\\d{2}[2-9](?!11)\\d{6}$", "format_example": "(123) 456-7890", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "CV", "country_name": "Cape Verde", "country_flag": "🇨🇻", "phone_number_code": "+238", "validation_regex": "^(\\+?238)?\\d{7}$", "format_example": "9912345", "format_regex": "^\\d{7}$" }, { "country_code": "CF", "country_name": "Central African Republic", "country_flag": "🇨🇫", "phone_number_code": "+236", "validation_regex": "^(\\+?236)?\\d{8}$", "format_example": "70123456", "format_regex": "^\\d{8}$" }, { "country_code": "TD", "country_name": "Chad", "country_flag": "🇹🇩", "phone_number_code": "+235", "validation_regex": "^(\\+?235)?\\d{6}$", "format_example": "66123456", "format_regex": "^\\d{8}$" }, { "country_code": "CL", "country_name": "Chile", "country_flag": "🇨🇱", "phone_number_code": "+56", "validation_regex": "^(\\+?56|0)[2-9]\\d{1}\\d{7}$", "format_example": "091234567", "format_regex": "^(\\d{2})(\\d{7})$" }, { "country_code": "CN", "country_name": "China", "country_flag": "🇨🇳", "phone_number_code": "+86", "validation_regex": "^(\\+?86)?1[345789]\\d{9}$", "format_example": "13812345678", "format_regex": "^(\\d{3})(\\d{4})(\\d{4})$" }, { "country_code": "CO", "country_name": "Colombia", "country_flag": "🇨🇴", "phone_number_code": "+57", "validation_regex": "^(\\+?57)?[1-8]\\d{7,10}$", "format_example": "3212345678", "format_regex": "^(\\d{3})(\\d{7,10})$" }, { "country_code": "KM", "country_name": "Comoros", "country_flag": "🇰🇲", "phone_number_code": "+269", "validation_regex": "^(\\+?269|0)3\\d{6}$", "format_example": "3212345", "format_regex": "^\\d{7}$" }, { "country_code": "CG", "country_name": "Congo - Brazzaville", "country_flag": "🇨🇬", "phone_number_code": "+242", "validation_regex": "^(\\+?242)?\\d{6}$", "format_example": "06123456", "format_regex": "^\\d{8}$" }, { "country_code": "CD", "country_name": "Congo - Kinshasa", "country_flag": "🇨🇩", "phone_number_code": "+243", "validation_regex": "^(\\+?243)?\\d{9}$", "format_example": "081234567", "format_regex": "^\\d{9}$" }, { "country_code": "CR", "country_name": "Costa Rica", "country_flag": "🇨🇷", "phone_number_code": "+506", "validation_regex": "^(\\+?506)?[24578]\\d{7}$", "format_example": "83123456", "format_regex": "^\\d{8}$" }, { "country_code": "HR", "country_name": "Croatia", "country_flag": "🇭🇷", "phone_number_code": "+385", "validation_regex": "^(\\+?385|0)9\\d{8}$", "format_example": "0912345678", "format_regex": "^\\d{10}$" }, { "country_code": "CU", "country_name": "Cuba", "country_flag": "🇨🇺", "phone_number_code": "+53", "validation_regex": "^(\\+?53)?5[2-9]\\d{7}$", "format_example": "5281234567", "format_regex": "^\\d{10}$" }, { "country_code": "CY", "country_name": "Cyprus", "country_flag": "🇨🇾", "phone_number_code": "+357", "validation_regex": "^(\\+?357|0)9\\d{7}$", "format_example": "96123456", "format_regex": "^\\d{8}$" }, { "country_code": "CZ", "country_name": "Czech Republic", "country_flag": "🇨🇿", "phone_number_code": "+420", "validation_regex": "^(\\+?420)?[26789]\\d{8}$", "format_example": "601123456", "format_regex": "^(\\d{3})(\\d{3})(\\d{3})$" }, { "country_code": "CI", "country_name": "Côte d'Ivoire", "country_flag": "🇨🇮", "phone_number_code": "+225", "validation_regex": "^(\\+?225)?\\d{8}$", "format_example": "01234567", "format_regex": "^\\d{8}$" }, { "country_code": "DK", "country_name": "Denmark", "country_flag": "🇩🇰", "phone_number_code": "+45", "validation_regex": "^(\\+?45)?\\d{8}$", "format_example": "12345678", "format_regex": "^\\d{8}$" }, { "country_code": "DJ", "country_name": "Djibouti", "country_flag": "🇩🇯", "phone_number_code": "+253", "validation_regex": "^(\\+?253)?\\d{6}$", "format_example": "77123456", "format_regex": "^\\d{8}$" }, { "country_code": "DM", "country_name": "Dominica", "country_flag": "🇩🇲", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?767\\d{7}$", "format_example": "(767) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "DO", "country_name": "Dominican Republic", "country_flag": "🇩🇴", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?809\\d{7}$", "format_example": "(809) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "TL", "country_name": "East Timor", "country_flag": "🇹🇱", "phone_number_code": "+670", "validation_regex": "^(\\+?670)?\\d{7}$", "format_example": "7721234", "format_regex": "^\\d{7}$" }, { "country_code": "EC", "country_name": "Ecuador", "country_flag": "🇪🇨", "phone_number_code": "+593", "validation_regex": "^(\\+?593|0)([2-7]|9[2-9])\\d{7}$", "format_example": "091234567", "format_regex": "^(\\d{2})(\\d{7})$" }, { "country_code": "EG", "country_name": "Egypt", "country_flag": "🇪🇬", "phone_number_code": "+20", "validation_regex": "^(\\+?20|0)1[0-2]\\d{8}$", "format_example": "01012345678", "format_regex": "^(\\d{4})(\\d{2})(\\d{2})(\\d{2})$" }, { "country_code": "SV", "country_name": "El Salvador", "country_flag": "🇸🇻", "phone_number_code": "+503", "validation_regex": "^(\\+?503)?[67]\\d{7}$", "format_example": "70123456", "format_regex": "^\\d{8}$" }, { "country_code": "GQ", "country_name": "Equatorial Guinea", "country_flag": "🇬🇶", "phone_number_code": "+240", "validation_regex": "^(\\+?240)?\\d{6}$", "format_example": "222123456", "format_regex": "^\\d{9}$" }, { "country_code": "ER", "country_name": "Eritrea", "country_flag": "🇪🇷", "phone_number_code": "+291", "validation_regex": "^(\\+?291)?\\d{7}$", "format_example": "07123456", "format_regex": "^\\d{8}$" }, { "country_code": "EE", "country_name": "Estonia", "country_flag": "🇪🇪", "phone_number_code": "+372", "validation_regex": "^(\\+?372)?\\d{7}$", "format_example": "51234567", "format_regex": "^\\d{8}$" }, { "country_code": "ET", "country_name": "Ethiopia", "country_flag": "🇪🇹", "phone_number_code": "+251", "validation_regex": "^(\\+?251|0)9\\d{8}$", "format_example": "0911234567", "format_regex": "^\\d{10}$" }, { "country_code": "FK", "country_name": "Falkland Islands", "country_flag": "🇫🇰", "phone_number_code": "+500", "validation_regex": "^(\\+?500)?\\d{5}$", "format_example": "51234", "format_regex": "^\\d{5}$" }, { "country_code": "FO", "country_name": "Faroe Islands", "country_flag": "🇫🇴", "phone_number_code": "+298", "validation_regex": "^(\\+?298)?\\d{6}$", "format_example": "211234", "format_regex": "^\\d{6}$" }, { "country_code": "FJ", "country_name": "Fiji", "country_flag": "🇫🇯", "phone_number_code": "+679", "validation_regex": "^(\\+?679)?\\d{7}$", "format_example": "7012345", "format_regex": "^\\d{7}$" }, { "country_code": "FI", "country_name": "Finland", "country_flag": "🇫🇮", "phone_number_code": "+358", "validation_regex": "^(\\+?358|0)4\\d{8}$", "format_example": "0412345678", "format_regex": "^\\d{10}$" }, { "country_code": "FR", "country_name": "France", "country_flag": "🇫🇷", "phone_number_code": "+33", "validation_regex": "^(\\+?33|0)[67]\\d{8}$", "format_example": "0612345678", "format_regex": "^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})$" }, { "country_code": "GF", "country_name": "French Guiana", "country_flag": "🇬🇫", "phone_number_code": "+594", "validation_regex": "^(\\+?594|0)6\\d{8}$", "format_example": "0691234567", "format_regex": "^\\d{10}$" }, { "country_code": "PF", "country_name": "French Polynesia", "country_flag": "🇵🇫", "phone_number_code": "+689", "validation_regex": "^(\\+?689)\\d{6}$", "format_example": "401234", "format_regex": "^\\d{6}$" }, { "country_code": "GA", "country_name": "Gabon", "country_flag": "🇬🇦", "phone_number_code": "+241", "validation_regex": "^(\\+?241)?\\d{6}$", "format_example": "06123456", "format_regex": "^\\d{8}$" }, { "country_code": "GM", "country_name": "Gambia", "country_flag": "🇬🇲", "phone_number_code": "+220", "validation_regex": "^(\\+?220)?\\d{7}$", "format_example": "3012345", "format_regex": "^\\d{7}$" }, { "country_code": "GE", "country_name": "Georgia", "country_flag": "🇬🇪", "phone_number_code": "+995", "validation_regex": "^(\\+?995|0)5\\d{8}$", "format_example": "599123456", "format_regex": "^\\d{9}$" }, { "country_code": "DE", "country_name": "Germany", "country_flag": "🇩🇪", "phone_number_code": "+49", "validation_regex": "^(\\+?49|0)(\\d{2,4}-?\\d{2,12})$", "format_example": "030 12345678", "format_regex": "^\\d{3} \\d{8,12}$" }, { "country_code": "GH", "country_name": "Ghana", "country_flag": "🇬🇭", "phone_number_code": "+233", "validation_regex": "^(\\+?233|0)([236]-?\\d{7,9}|[45]\\d{8})$", "format_example": "0241234567", "format_regex": "^(\\d{3})(\\d{7})$" }, { "country_code": "GI", "country_name": "Gibraltar", "country_flag": "🇬🇮", "phone_number_code": "+350", "validation_regex": "^(\\+?350)?\\d{8}$", "format_example": "57123456", "format_regex": "^\\d{8}$" }, { "country_code": "GR", "country_name": "Greece", "country_flag": "🇬🇷", "phone_number_code": "+30", "validation_regex": "^(\\+?30|0)6\\d{9}$", "format_example": "6912345678", "format_regex": "^\\d{10}$" }, { "country_code": "GL", "country_name": "Greenland", "country_flag": "🇬🇱", "phone_number_code": "+299", "validation_regex": "^(\\+?299)?\\d{6}$", "format_example": "221234", "format_regex": "^\\d{6}$" }, { "country_code": "GD", "country_name": "Grenada", "country_flag": "🇬🇩", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?473\\d{7}$", "format_example": "(473) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "GP", "country_name": "Guadeloupe", "country_flag": "🇬🇵", "phone_number_code": "+590", "validation_regex": "^(\\+?590|0)690\\d{6}$", "format_example": "0690123456", "format_regex": "^\\d{10}$" }, { "country_code": "GT", "country_name": "Guatemala", "country_flag": "🇬🇹", "phone_number_code": "+502", "validation_regex": "^(\\+?502)?[24568]\\d{7}$", "format_example": "50123456", "format_regex": "^\\d{8}$" }, { "country_code": "GG", "country_name": "Guernsey", "country_flag": "🇬🇬", "phone_number_code": "+44", "validation_regex": "^(\\+?44|0)1481\\d{6}$", "format_example": "01481123456", "format_regex": "^\\d{11}$" }, { "country_code": "GN", "country_name": "Guinea", "country_flag": "🇬🇳", "phone_number_code": "+224", "validation_regex": "^(\\+?224)\\d{8}$", "format_example": "601123456", "format_regex": "^\\d{9}$" }, { "country_code": "GW", "country_name": "Guinea-Bissau", "country_flag": "🇬🇼", "phone_number_code": "+245", "validation_regex": "^(\\+?245)\\d{7}$", "format_example": "5512345", "format_regex": "^\\d{7}$" }, { "country_code": "GY", "country_name": "Guyana", "country_flag": "🇬🇾", "phone_number_code": "+592", "validation_regex": "^(\\+?592)\\d{6}$", "format_example": "6123456", "format_regex": "^\\d{7}$" }, { "country_code": "HT", "country_name": "Haiti", "country_flag": "🇭🇹", "phone_number_code": "+509", "validation_regex": "^(\\+?509)?[2-9]\\d{7}$", "format_example": "34123456", "format_regex": "^\\d{8}$" }, { "country_code": "HN", "country_name": "Honduras", "country_flag": "🇭🇳", "phone_number_code": "+504", "validation_regex": "^(\\+?504)?[78]\\d{7}$", "format_example": "97123456", "format_regex": "^\\d{8}$" }, { "country_code": "HK", "country_name": "Hong Kong SAR China", "country_flag": "🇭🇰", "phone_number_code": "+852", "validation_regex": "^(\\+?852)?[569]\\d{3}\\d{4}$", "format_example": "9123 4567", "format_regex": "^(\\d{4})(\\d{4})$" }, { "country_code": "HU", "country_name": "Hungary", "country_flag": "🇭🇺", "phone_number_code": "+36", "validation_regex": "^(\\+?36)(20|30|70)\\d{7}$", "format_example": "201234567", "format_regex": "^(\\d{3})(\\d{6})$" }, { "country_code": "IS", "country_name": "Iceland", "country_flag": "🇮🇸", "phone_number_code": "+354", "validation_regex": "^(\\+?354)?\\d{7}$", "format_example": "6112345", "format_regex": "^\\d{7}$" }, { "country_code": "IN", "country_name": "India", "country_flag": "🇮🇳", "phone_number_code": "+91", "validation_regex": "^(\\+?91|0)?[6789]\\d{9}$", "format_example": "9123456789", "format_regex": "^(\\d{3})(\\d{4})(\\d{4})$" }, { "country_code": "ID", "country_name": "Indonesia", "country_flag": "🇮🇩", "phone_number_code": "+62", "validation_regex": "^(\\+?62|0)[2-9]\\d{7,11}$", "format_example": "08123456789", "format_regex": "^(\\d{4})(\\d{4,7})$" }, { "country_code": "IR", "country_name": "Iran", "country_flag": "🇮🇷", "phone_number_code": "+98", "validation_regex": "^(\\+?98|0)9\\d{9}$", "format_example": "09123456789", "format_regex": "^(\\d{4})(\\d{3})(\\d{4})$" }, { "country_code": "IQ", "country_name": "Iraq", "country_flag": "🇮🇶", "phone_number_code": "+964", "validation_regex": "^(\\+?964|0)7[0-9]\\d{8}$", "format_example": "07912345678", "format_regex": "^\\d{11}$" }, { "country_code": "IE", "country_name": "Ireland", "country_flag": "🇮🇪", "phone_number_code": "+353", "validation_regex": "^(\\+?353|0)\\d{8,9}$", "format_example": "0871234567", "format_regex": "^\\d{10}$" }, { "country_code": "IM", "country_name": "Isle of Man", "country_flag": "🇮🇲", "phone_number_code": "+44", "validation_regex": "^(\\+?44|0)1624\\d{6}$", "format_example": "01624 123456", "format_regex": "^(\\d{5})(\\d{6})$" }, { "country_code": "IL", "country_name": "Israel", "country_flag": "🇮🇱", "phone_number_code": "+972", "validation_regex": "^(\\+?972|0)([23489]|5[0248]|77)[1-9]\\d{6}$", "format_example": "0501234567", "format_regex": "^(\\d{3})(\\d{4})(\\d{3})$" }, { "country_code": "IT", "country_name": "Italy", "country_flag": "🇮🇹", "phone_number_code": "+39", "validation_regex": "^(\\+?39)?\\d{10}$", "format_example": "3123456789", "format_regex": "^\\d{10}$" }, { "country_code": "JM", "country_name": "Jamaica", "country_flag": "🇯🇲", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?876\\d{7}$", "format_example": "(876) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "JP", "country_name": "Japan", "country_flag": "🇯🇵", "phone_number_code": "+81", "validation_regex": "^(\\+?81|0)\\d{1,4}-?\\d{1,4}-?\\d{4}$", "format_example": "090-1234-5678", "format_regex": "^(\\d{1,4})(\\d{1,4})(\\d{4})$" }, { "country_code": "JE", "country_name": "Jersey", "country_flag": "🇯🇪", "phone_number_code": "+44", "validation_regex": "^(\\+?44|0)1534\\d{6}$", "format_example": "01534 123456", "format_regex": "^(\\d{5})(\\d{6})$" }, { "country_code": "JO", "country_name": "Jordan", "country_flag": "🇯🇴", "phone_number_code": "+962", "validation_regex": "^(\\+?962|0)7[789]\\d{7}$", "format_example": "0791234567", "format_regex": "^\\d{10}$" }, { "country_code": "KZ", "country_name": "Kazakhstan", "country_flag": "🇰🇿", "phone_number_code": "+7", "validation_regex": "^(\\+?7|8)7\\d{9}$", "format_example": "87771234567", "format_regex": "^\\d{11}$" }, { "country_code": "KE", "country_name": "Kenya", "country_flag": "🇰🇪", "phone_number_code": "+254", "validation_regex": "^(\\+?254|0)7\\d{8}$", "format_example": "0712345678", "format_regex": "^\\d{10}$" }, { "country_code": "KI", "country_name": "Kiribati", "country_flag": "🇰🇮", "phone_number_code": "+686", "validation_regex": "^(\\+?686)?\\d{5}$", "format_example": "90123", "format_regex": "^\\d{5}$" }, { "country_code": "KW", "country_name": "Kuwait", "country_flag": "🇰🇼", "phone_number_code": "+965", "validation_regex": "^(\\+?965)?\\d{8}$", "format_example": "51234567", "format_regex": "^\\d{8}$" }, { "country_code": "KG", "country_name": "Kyrgyzstan", "country_flag": "🇰🇬", "phone_number_code": "+996", "validation_regex": "^(\\+?996)?\\d{9}$", "format_example": "0700123456", "format_regex": "^\\d{10}$" }, { "country_code": "LA", "country_name": "Laos", "country_flag": "🇱🇦", "phone_number_code": "+856", "validation_regex": "^(\\+?856|0)20\\d{8}$", "format_example": "020 12345678", "format_regex": "^\\d{11}$" }, { "country_code": "LV", "country_name": "Latvia", "country_flag": "🇱🇻", "phone_number_code": "+371", "validation_regex": "^(\\+?371)2\\d{7}$", "format_example": "21234567", "format_regex": "^\\d{8}$" }, { "country_code": "LB", "country_name": "Lebanon", "country_flag": "🇱🇧", "phone_number_code": "+961", "validation_regex": "^(\\+?961|0)3\\d{7}$", "format_example": "03123456", "format_regex": "^\\d{8}$" }, { "country_code": "LS", "country_name": "Lesotho", "country_flag": "🇱🇸", "phone_number_code": "+266", "validation_regex": "^(\\+?266)?\\d{8}$", "format_example": "50123456", "format_regex": "^\\d{8}$" }, { "country_code": "LR", "country_name": "Liberia", "country_flag": "🇱🇷", "phone_number_code": "+231", "validation_regex": "^(\\+?231)[56]\\d{7}$", "format_example": "65123456", "format_regex": "^\\d{8}$" }, { "country_code": "LY", "country_name": "Libya", "country_flag": "🇱🇾", "phone_number_code": "+218", "validation_regex": "^(\\+?218|0)9\\d{8}$", "format_example": "0912345678", "format_regex": "^(\\d{3})(\\d{3})(\\d{4})$" }, { "country_code": "LI", "country_name": "Liechtenstein", "country_flag": "🇱🇮", "phone_number_code": "+423", "validation_regex": "^(\\+?423)?\\d{7}$", "format_example": "6612345", "format_regex": "^\\d{7}$" }, { "country_code": "LT", "country_name": "Lithuania", "country_flag": "🇱🇹", "phone_number_code": "+370", "validation_regex": "^(\\+?370)\\d{8}$", "format_example": "61234567", "format_regex": "^\\d{8}$" }, { "country_code": "LU", "country_name": "Luxembourg", "country_flag": "🇱🇺", "phone_number_code": "+352", "validation_regex": "^(\\+?352)\\d{6}$", "format_example": "621123456", "format_regex": "^\\d{9}$" }, { "country_code": "MO", "country_name": "Macau SAR China", "country_flag": "🇲🇴", "phone_number_code": "+853", "validation_regex": "^(\\+?853)?6\\d{7}$", "format_example": "66123456", "format_regex": "^\\d{8}$" }, { "country_code": "MK", "country_name": "Macedonia", "country_flag": "🇲🇰", "phone_number_code": "+389", "validation_regex": "^(\\+?389)7\\d{8}$", "format_example": "071234567", "format_regex": "^\\d{9}$" }, { "country_code": "MG", "country_name": "Madagascar", "country_flag": "🇲🇬", "phone_number_code": "+261", "validation_regex": "^(\\+?261)?3[2-9]\\d{7}$", "format_example": "0321234567", "format_regex": "^\\d{10}$" }, { "country_code": "MW", "country_name": "Malawi", "country_flag": "🇲🇼", "phone_number_code": "+265", "validation_regex": "^(\\+?265)\\d{8}$", "format_example": "991234567", "format_regex": "^\\d{9}$" }, { "country_code": "MY", "country_name": "Malaysia", "country_flag": "🇲🇾", "phone_number_code": "+60", "validation_regex": "^(\\+?60|0)([3467-9]|1[2-5789])\\d{7,9}$", "format_example": "012-3456789", "format_regex": "^(\\d{3})(\\d{7,9})$" }, { "country_code": "MV", "country_name": "Maldives", "country_flag": "🇲🇻", "phone_number_code": "+960", "validation_regex": "^(\\+?960)?\\d{7}$", "format_example": "7712345", "format_regex": "^\\d{7}$" }, { "country_code": "ML", "country_name": "Mali", "country_flag": "🇲🇱", "phone_number_code": "+223", "validation_regex": "^(\\+?223)[67]\\d{7}$", "format_example": "65123456", "format_regex": "^\\d{8}$" }, { "country_code": "MT", "country_name": "Malta", "country_flag": "🇲🇹", "phone_number_code": "+356", "validation_regex": "^(\\+?356)?[79]\\d{7}$", "format_example": "79012345", "format_regex": "^\\d{8}$" }, { "country_code": "MH", "country_name": "Marshall Islands", "country_flag": "🇲🇭", "phone_number_code": "+692", "validation_regex": "^(\\+?692)?\\d{7}$", "format_example": "2351234", "format_regex": "^\\d{7}$" }, { "country_code": "MQ", "country_name": "Martinique", "country_flag": "🇲🇶", "phone_number_code": "+596", "validation_regex": "^(\\+?596|0)696\\d{6}$", "format_example": "0696123456", "format_regex": "^\\d{10}$" }, { "country_code": "MR", "country_name": "Mauritania", "country_flag": "🇲🇷", "phone_number_code": "+222", "validation_regex": "^(\\+?222)?\\d{6}$", "format_example": "22123456", "format_regex": "^\\d{8}$" }, { "country_code": "MU", "country_name": "Mauritius", "country_flag": "🇲🇺", "phone_number_code": "+230", "validation_regex": "^(\\+?230)?\\d{7}$", "format_example": "51234567", "format_regex": "^\\d{8}$" }, { "country_code": "YT", "country_name": "Mayotte", "country_flag": "🇾🇹", "phone_number_code": "+262", "validation_regex": "^(\\+?262|0)639\\d{6}$", "format_example": "0639123456", "format_regex": "^\\d{10}$" }, { "country_code": "MX", "country_name": "Mexico", "country_flag": "🇲🇽", "phone_number_code": "+52", "validation_regex": "^(\\+?52|01)?[1-9]\\d{9}$", "format_example": "5512345678", "format_regex": "^(\\d{3})(\\d{3})(\\d{4})$" }, { "country_code": "MD", "country_name": "Moldova", "country_flag": "🇲🇩", "phone_number_code": "+373", "validation_regex": "^(\\+?373|0)(6[369]|\\d{2})\\d{6}$", "format_example": "062123456", "format_regex": "^(\\d{3})(\\d{6})$" }, { "country_code": "MC", "country_name": "Monaco", "country_flag": "🇲🇨", "phone_number_code": "+377", "validation_regex": "^(\\+?377)\\d{8}$", "format_example": "61234567", "format_regex": "^\\d{8}$" }, { "country_code": "MN", "country_name": "Mongolia", "country_flag": "🇲🇳", "phone_number_code": "+976", "validation_regex": "^(\\+?976)?\\d{8}$", "format_example": "88123456", "format_regex": "^\\d{8}$" }, { "country_code": "ME", "country_name": "Montenegro", "country_flag": "🇲🇪", "phone_number_code": "+382", "validation_regex": "^(\\+?382|0)6[0-6]\\d{6}$", "format_example": "067123456", "format_regex": "^\\d{9}$" }, { "country_code": "MS", "country_name": "Montserrat", "country_flag": "🇲🇸", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?664\\d{7}$", "format_example": "(664) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "MA", "country_name": "Morocco", "country_flag": "🇲🇦", "phone_number_code": "+212", "validation_regex": "^(\\+?212|0)\\d{9}$", "format_example": "0612345678", "format_regex": "^(\\d{2})(\\d{3})(\\d{2})(\\d{2})(\\d{2})$" }, { "country_code": "MZ", "country_name": "Mozambique", "country_flag": "🇲🇿", "phone_number_code": "+258", "validation_regex": "^(\\+?258)?[28]\\d{7,8}$", "format_example": "821234567", "format_regex": "^\\d{9}$" }, { "country_code": "MM", "country_name": "Myanmar (Burma)", "country_flag": "🇲🇲", "phone_number_code": "+95", "validation_regex": "^(\\+?95|0)\\d{9}$", "format_example": "0912345678", "format_regex": "^(\\d{2})(\\d{3})(\\d{2})(\\d{2})(\\d{2})$" }, { "country_code": "NA", "country_name": "Namibia", "country_flag": "🇳🇦", "phone_number_code": "+264", "validation_regex": "^(\\+?264|0)\\d{8,9}$", "format_example": "0811234567", "format_regex": "^\\d{10}$" }, { "country_code": "NR", "country_name": "Nauru", "country_flag": "🇳🇷", "phone_number_code": "+674", "validation_regex": "^(\\+?674)\\d{5}$", "format_example": "5551234", "format_regex": "^\\d{7}$" }, { "country_code": "NP", "country_name": "Nepal", "country_flag": "🇳🇵", "phone_number_code": "+977", "validation_regex": "^(\\+?977)?9[78]\\d{8}$", "format_example": "9812345678", "format_regex": "^(\\d{4})(\\d{6})$" }, { "country_code": "NL", "country_name": "Netherlands", "country_flag": "🇳🇱", "phone_number_code": "+31", "validation_regex": "^(\\+?31|0)6\\d{8}$", "format_example": "0612345678", "format_regex": "^(\\d{2})(\\d{8})$" }, { "country_code": "NC", "country_name": "New Caledonia", "country_flag": "🇳🇨", "phone_number_code": "+687", "validation_regex": "^(\\+?687)\\d{6}$", "format_example": "751234", "format_regex": "^\\d{6}$" }, { "country_code": "NZ", "country_name": "New Zealand", "country_flag": "🇳🇿", "phone_number_code": "+64", "validation_regex": "^(\\+?64|0)2\\d{7,9}$", "format_example": "021123456", "format_regex": "^(\\d{3})(\\d{7,9})$" }, { "country_code": "NI", "country_name": "Nicaragua", "country_flag": "🇳🇮", "phone_number_code": "+505", "validation_regex": "^(\\+?505)\\d{8}$", "format_example": "81234567", "format_regex": "^\\d{8}$" }, { "country_code": "NE", "country_name": "Niger", "country_flag": "🇳🇪", "phone_number_code": "+227", "validation_regex": "^(\\+?227)[25-7]\\d{7}$", "format_example": "92123456", "format_regex": "^\\d{8}$" }, { "country_code": "NG", "country_name": "Nigeria", "country_flag": "🇳🇬", "phone_number_code": "+234", "validation_regex": "^(\\+?234)[7-9]\\d{9}$", "format_example": "08123456789", "format_regex": "^(\\d{3})(\\d{4})(\\d{4})$" }, { "country_code": "NU", "country_name": "Niue", "country_flag": "🇳🇺", "phone_number_code": "+683", "validation_regex": "^(\\+?683)\\d{4}$", "format_example": "4012", "format_regex": "^\\d{4}$" }, { "country_code": "NF", "country_name": "Norfolk Island", "country_flag": "🇳🇫", "phone_number_code": "+672", "validation_regex": "^(\\+?672)3\\d{3}$", "format_example": "3123", "format_regex": "^\\d{4}$" }, { "country_code": "KP", "country_name": "North Korea", "country_flag": "🇰🇵", "phone_number_code": "+850", "validation_regex": "^(\\+?850)?\\d{8}$", "format_example": "1921234567", "format_regex": "^\\d{10}$" }, { "country_code": "MP", "country_name": "Northern Mariana Islands", "country_flag": "🇲🇵", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?670\\d{7}$", "format_example": "(670) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "NO", "country_name": "Norway", "country_flag": "🇳🇴", "phone_number_code": "+47", "validation_regex": "^(\\+?47)?[29]\\d{7}$", "format_example": "912 34 567", "format_regex": "^(\\d{3}) \\d{2} \\d{3}$" }, { "country_code": "OM", "country_name": "Oman", "country_flag": "🇴🇲", "phone_number_code": "+968", "validation_regex": "^(\\+?968)?9\\d{7}$", "format_example": "91234567", "format_regex": "^\\d{8}$" }, { "country_code": "PK", "country_name": "Pakistan", "country_flag": "🇵🇰", "phone_number_code": "+92", "validation_regex": "^(\\+?92|0)3\\d{9}$", "format_example": "03123456789", "format_regex": "^(\\d{4})(\\d{3})(\\d{4})$" }, { "country_code": "PW", "country_name": "Palau", "country_flag": "🇵🇼", "phone_number_code": "+680", "validation_regex": "^(\\+?680)?\\d{7}$", "format_example": "6201234", "format_regex": "^\\d{7}$" }, { "country_code": "PS", "country_name": "Palestinian Territories", "country_flag": "🇵🇸", "phone_number_code": "+970", "validation_regex": "^(\\+?970)5[02-9]\\d{7}$", "format_example": "0599123456", "format_regex": "^(\\d{4})(\\d{3})(\\d{3})$" }, { "country_code": "PA", "country_name": "Panama", "country_flag": "🇵🇦", "phone_number_code": "+507", "validation_regex": "^(\\+?507)\\d{7,8}$", "format_example": "61234567", "format_regex": "^\\d{8}$" }, { "country_code": "PG", "country_name": "Papua New Guinea", "country_flag": "🇵🇬", "phone_number_code": "+675", "validation_regex": "^(\\+?675)\\d{7}$", "format_example": "70123456", "format_regex": "^\\d{8}$" }, { "country_code": "PY", "country_name": "Paraguay", "country_flag": "🇵🇾", "phone_number_code": "+595", "validation_regex": "^(\\+?595|0)9[678]\\d{7}$", "format_example": "0986123456", "format_regex": "^(\\d{3})(\\d{7})$" }, { "country_code": "PE", "country_name": "Peru", "country_flag": "🇵🇪", "phone_number_code": "+51", "validation_regex": "^(\\+?51|0)9\\d{8}$", "format_example": "912345678", "format_regex": "^(\\d{3})(\\d{6})$" }, { "country_code": "PH", "country_name": "Philippines", "country_flag": "🇵🇭", "phone_number_code": "+63", "validation_regex": "^(\\+?63|0)\\d{10}$", "format_example": "09123456789", "format_regex": "^(\\d{4})(\\d{6})$" }, { "country_code": "PN", "country_name": "Pitcairn Islands", "country_flag": "🇵🇳", "phone_number_code": "+870", "validation_regex": "^(\\+?870)\\d{8}$", "format_example": "51234567", "format_regex": "^\\d{8}$" }, { "country_code": "PL", "country_name": "Poland", "country_flag": "🇵🇱", "phone_number_code": "+48", "validation_regex": "^(\\+?48)?[5-8]\\d{8}$", "format_example": "512345678", "format_regex": "^\\d{9}$" }, { "country_code": "PT", "country_name": "Portugal", "country_flag": "🇵🇹", "phone_number_code": "+351", "validation_regex": "^(\\+?351)?9[1236]\\d{7}$", "format_example": "912345678", "format_regex": "^(\\d{3})(\\d{3})(\\d{3})$" }, { "country_code": "PR", "country_name": "Puerto Rico", "country_flag": "🇵🇷", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?787\\d{7}$", "format_example": "(787) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "QA", "country_name": "Qatar", "country_flag": "🇶🇦", "phone_number_code": "+974", "validation_regex": "^(\\+?974)?\\d{8}$", "format_example": "33123456", "format_regex": "^\\d{8}$" }, { "country_code": "RE", "country_name": "Réunion", "country_flag": "🇷🇪", "phone_number_code": "+262", "validation_regex": "^(\\+?262|0)6\\d{8}$", "format_example": "0692123456", "format_regex": "^\\d{10}$" }, { "country_code": "RO", "country_name": "Romania", "country_flag": "🇷🇴", "phone_number_code": "+40", "validation_regex": "^(\\+?40|0)7[2-8]\\d{7}$", "format_example": "0712345678", "format_regex": "^\\d{10}$" }, { "country_code": "RU", "country_name": "Russia", "country_flag": "🇷🇺", "phone_number_code": "+7", "validation_regex": "^(\\+?7|8)9\\d{9}$", "format_example": "9123456789", "format_regex": "^\\d{10}$" }, { "country_code": "RW", "country_name": "Rwanda", "country_flag": "🇷🇼", "phone_number_code": "+250", "validation_regex": "^(\\+?250)\\d{9}$", "format_example": "0781234567", "format_regex": "^(\\d{3})(\\d{3})(\\d{4})$" }, { "country_code": "BL", "country_name": "Saint Barthélemy", "country_flag": "🇧🇱", "phone_number_code": "+590", "validation_regex": "^(\\+?590|0)690\\d{6}$", "format_example": "0690123456", "format_regex": "^\\d{10}$" }, { "country_code": "SH", "country_name": "Saint Helena", "country_flag": "🇸🇭", "phone_number_code": "+290", "validation_regex": "^(\\+?290)\\d{4}$", "format_example": "5123", "format_regex": "^\\d{4}$" }, { "country_code": "KN", "country_name": "Saint Kitts and Nevis", "country_flag": "🇰🇳", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?869\\d{7}$", "format_example": "(869) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "LC", "country_name": "Saint Lucia", "country_flag": "🇱🇨", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?758\\d{7}$", "format_example": "(758) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "MF", "country_name": "Saint Martin", "country_flag": "🇲🇫", "phone_number_code": "+590", "validation_regex": "^(\\+?590|0)696\\d{6}$", "format_example": "0696123456", "format_regex": "^\\d{10}$" }, { "country_code": "PM", "country_name": "Saint Pierre and Miquelon", "country_flag": "🇵🇲", "phone_number_code": "+508", "validation_regex": "^(\\+?508)\\d{6}$", "format_example": "551234", "format_regex": "^\\d{6}$" }, { "country_code": "VC", "country_name": "Saint Vincent and the Grenadines", "country_flag": "🇻🇨", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?784\\d{7}$", "format_example": "(784) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "WS", "country_name": "Samoa", "country_flag": "🇼🇸", "phone_number_code": "+685", "validation_regex": "^(\\+?685)\\d{6}$", "format_example": "601234", "format_regex": "^\\d{6}$" }, { "country_code": "SM", "country_name": "San Marino", "country_flag": "🇸🇲", "phone_number_code": "+378", "validation_regex": "^(\\+?378)\\d{5,11}$", "format_example": "666123456", "format_regex": "^\\d{9}$" }, { "country_code": "ST", "country_name": "São Tomé and Príncipe", "country_flag": "🇸🇹", "phone_number_code": "+239", "validation_regex": "^(\\+?239)\\d{7}$", "format_example": "9812345", "format_regex": "^\\d{7}$" }, { "country_code": "SA", "country_name": "Saudi Arabia", "country_flag": "🇸🇦", "phone_number_code": "+966", "validation_regex": "^(\\+?966|0)(5(0|[5-9])|[67]\\d)\\d{7}$", "format_example": "0501234567", "format_regex": "^(\\d{3})(\\d{3})(\\d{4})$" }, { "country_code": "SN", "country_name": "Senegal", "country_flag": "🇸🇳", "phone_number_code": "+221", "validation_regex": "^(\\+?221)[4679]\\d{7}$", "format_example": "701234567", "format_regex": "^\\d{9}$" }, { "country_code": "RS", "country_name": "Serbia", "country_flag": "🇷🇸", "phone_number_code": "+381", "validation_regex": "^(\\+?3816|0)\\d{7,9}$", "format_example": "601234567", "format_regex": "^(\\d{3})(\\d{6,8})$" }, { "country_code": "SC", "country_name": "Seychelles", "country_flag": "🇸🇨", "phone_number_code": "+248", "validation_regex": "^(\\+?248)\\d{6}$", "format_example": "2512345", "format_regex": "^\\d{7}$" }, { "country_code": "SL", "country_name": "Sierra Leone", "country_flag": "🇸🇱", "phone_number_code": "+232", "validation_regex": "^(\\+?232)\\d{8}$", "format_example": "076123456", "format_regex": "^\\d{9}$" }, { "country_code": "SG", "country_name": "Singapore", "country_flag": "🇸🇬", "phone_number_code": "+65", "validation_regex": "^(\\+?65)?[689]\\d{7}$", "format_example": "91234567", "format_regex": "^(\\d{4})(\\d{4})$" }, { "country_code": "SX", "country_name": "Sint Maarten", "country_flag": "🇸🇽", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?721\\d{7}$", "format_example": "(721) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "SK", "country_name": "Slovakia", "country_flag": "🇸🇰", "phone_number_code": "+421", "validation_regex": "^(\\+?421)?9\\d{8}$", "format_example": "0912345678", "format_regex": "^(\\d{3})(\\d{3})(\\d{3})$" }, { "country_code": "SI", "country_name": "Slovenia", "country_flag": "🇸🇮", "phone_number_code": "+386", "validation_regex": "^(\\+?386)\\d{8}$", "format_example": "03123456", "format_regex": "^\\d{8}$" }, { "country_code": "SB", "country_name": "Solomon Islands", "country_flag": "🇸🇧", "phone_number_code": "+677", "validation_regex": "^(\\+?677)\\d{5}$", "format_example": "50123", "format_regex": "^\\d{5}$" }, { "country_code": "SO", "country_name": "Somalia", "country_flag": "🇸🇴", "phone_number_code": "+252", "validation_regex": "^(\\+?252)\\d{7,8}$", "format_example": "71234567", "format_regex": "^\\d{8}$" }, { "country_code": "ZA", "country_name": "South Africa", "country_flag": "🇿🇦", "phone_number_code": "+27", "validation_regex": "^(\\+?27|0)\\d{9}$", "format_example": "0712345678", "format_regex": "^(\\d{2})(\\d{3})(\\d{4})$" }, { "country_code": "GS", "country_name": "South Georgia & South Sandwich Islands", "country_flag": "🇬🇸", "phone_number_code": "+500", "validation_regex": "^(\\+?500)\\d{4}$", "format_example": "51234", "format_regex": "^\\d{5}$" }, { "country_code": "KR", "country_name": "South Korea", "country_flag": "🇰🇷", "phone_number_code": "+82", "validation_regex": "^(\\+?82|0)1\\d{9}$", "format_example": "01012345678", "format_regex": "^(\\d{3})(\\d{4})(\\d{4})$" }, { "country_code": "SS", "country_name": "South Sudan", "country_flag": "🇸🇸", "phone_number_code": "+211", "validation_regex": "^(\\+?211)?\\d{9}$", "format_example": "977123456", "format_regex": "^\\d{9}$" }, { "country_code": "ES", "country_name": "Spain", "country_flag": "🇪🇸", "phone_number_code": "+34", "validation_regex": "^(\\+?34)?[6789]\\d{8}$", "format_example": "612345678", "format_regex": "^(\\d{3})(\\d{3})(\\d{3})$" }, { "country_code": "LK", "country_name": "Sri Lanka", "country_flag": "🇱🇰", "phone_number_code": "+94", "validation_regex": "^(\\+?94|0)[1-9]\\d{8}$", "format_example": "0712345678", "format_regex": "^(\\d{2})(\\d{3})(\\d{4})$" }, { "country_code": "SD", "country_name": "Sudan", "country_flag": "🇸🇩", "phone_number_code": "+249", "validation_regex": "^(\\+?249)\\d{9}$", "format_example": "0912345678", "format_regex": "^(\\d{2})(\\d{3})(\\d{4})$" }, { "country_code": "SR", "country_name": "Suriname", "country_flag": "🇸🇷", "phone_number_code": "+597", "validation_regex": "^(\\+?597)\\d{6}$", "format_example": "8512345", "format_regex": "^\\d{7}$" }, { "country_code": "SJ", "country_name": "Svalbard and Jan Mayen", "country_flag": "🇸🇯", "phone_number_code": "+47", "validation_regex": "^(\\+?47)?[2489]\\d{7}$", "format_example": "91234567", "format_regex": "^(\\d{2})(\\d{2})(\\d{2})(\\d{2})$" }, { "country_code": "SZ", "country_name": "Swaziland", "country_flag": "🇸🇿", "phone_number_code": "+268", "validation_regex": "^(\\+?268)\\d{7}$", "format_example": "76123456", "format_regex": "^\\d{8}$" }, { "country_code": "SE", "country_name": "Sweden", "country_flag": "🇸🇪", "phone_number_code": "+46", "validation_regex": "^(\\+?46|0)7[02369]\\d{7}$", "format_example": "0701234567", "format_regex": "^(\\d{3})(\\d{3})(\\d{2})(\\d{2})$" }, { "country_code": "CH", "country_name": "Switzerland", "country_flag": "🇨🇭", "phone_number_code": "+41", "validation_regex": "^(\\+?41|0)7[56789]\\d{7}$", "format_example": "0781234567", "format_regex": "^(\\d{3})(\\d{3})(\\d{2})(\\d{2})$" }, { "country_code": "SY", "country_name": "Syria", "country_flag": "🇸🇾", "phone_number_code": "+963", "validation_regex": "^(\\+?963|0)9\\d{8}$", "format_example": "0912345678", "format_regex": "^\\d{10}$" }, { "country_code": "TW", "country_name": "Taiwan", "country_flag": "🇹🇼", "phone_number_code": "+886", "validation_regex": "^(\\+?886\\-?|0)?9\\d{8}$", "format_example": "0912345678", "format_regex": "^(\\d{4})(\\d{6})$" }, { "country_code": "TJ", "country_name": "Tajikistan", "country_flag": "🇹🇯", "phone_number_code": "+992", "validation_regex": "^(\\+?992\\-?)?[5-9]\\d{8}$", "format_example": "901234567", "format_regex": "^(\\d{3})(\\d{6})$" }, { "country_code": "TZ", "country_name": "Tanzania", "country_flag": "🇹🇿", "phone_number_code": "+255", "validation_regex": "^(\\+?255)\\d{9}$", "format_example": "0712345678", "format_regex": "^(\\d{2})(\\d{3})(\\d{4})$" }, { "country_code": "TH", "country_name": "Thailand", "country_flag": "🇹🇭", "phone_number_code": "+66", "validation_regex": "^(\\+?66|0)\\d{8,9}$", "format_example": "0812345678", "format_regex": "^(\\d{2})(\\d{3})(\\d{4})$" }, { "country_code": "TG", "country_name": "Togo", "country_flag": "🇹🇬", "phone_number_code": "+228", "validation_regex": "^(\\+?228)\\d{8}$", "format_example": "90123456", "format_regex": "^\\d{8}$" }, { "country_code": "TK", "country_name": "Tokelau", "country_flag": "🇹🇰", "phone_number_code": "+690", "validation_regex": "^(\\+?690)\\d{4}$", "format_example": "3123", "format_regex": "^\\d{4}$" }, { "country_code": "TO", "country_name": "Tonga", "country_flag": "🇹🇴", "phone_number_code": "+676", "validation_regex": "^(\\+?676)\\d{5}$", "format_example": "20123", "format_regex": "^\\d{5}$" }, { "country_code": "TT", "country_name": "Trinidad and Tobago", "country_flag": "🇹🇹", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?868\\d{7}$", "format_example": "(868) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "TN", "country_name": "Tunisia", "country_flag": "🇹🇳", "phone_number_code": "+216", "validation_regex": "^(\\+?216)?[2459]\\d{7}$", "format_example": "20123456", "format_regex": "^(\\d{2})(\\d{6})$" }, { "country_code": "TR", "country_name": "Turkey", "country_flag": "🇹🇷", "phone_number_code": "+90", "validation_regex": "^(\\+?90|0)?5\\d{9}$", "format_example": "05321234567", "format_regex": "^(\\d{4})(\\d{3})(\\d{2})(\\d{2})$" }, { "country_code": "TM", "country_name": "Turkmenistan", "country_flag": "🇹🇲", "phone_number_code": "+993", "validation_regex": "^(\\+?993\\-?)?\\d{7}$", "format_example": "6612345", "format_regex": "^\\d{7}$" }, { "country_code": "TC", "country_name": "Turks and Caicos Islands", "country_flag": "🇹🇨", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?649\\d{7}$", "format_example": "(649) 123-4567", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "TV", "country_name": "Tuvalu", "country_flag": "🇹🇻", "phone_number_code": "+688", "validation_regex": "^(\\+?688)\\d{5}$", "format_example": "90123", "format_regex": "^\\d{5}$" }, { "country_code": "UG", "country_name": "Uganda", "country_flag": "🇺🇬", "phone_number_code": "+256", "validation_regex": "^(\\+?256)\\d{9}$", "format_example": "0712345678", "format_regex": "^(\\d{2})(\\d{3})(\\d{4})$" }, { "country_code": "UA", "country_name": "Ukraine", "country_flag": "🇺🇦", "phone_number_code": "+380", "validation_regex": "^(\\+?380)\\d{9}$", "format_example": "0661234567", "format_regex": "^(\\d{3})(\\d{2})(\\d{2})(\\d{2})$" }, { "country_code": "AE", "country_name": "United Arab Emirates", "country_flag": "🇦🇪", "phone_number_code": "+971", "validation_regex": "^(\\+?971|0)5[056-9]\\d{7}$", "format_example": "0501234567", "format_regex": "^(\\d{3})(\\d{4})(\\d{2})(\\d{2})$" }, { "country_code": "GB", "country_name": "United Kingdom", "country_flag": "🇬🇧", "phone_number_code": "+44", "validation_regex": "^(\\+?44|0)7\\d{9}$", "format_example": "07123456789", "format_regex": "^(\\d{4})(\\d{3})(\\d{4})$" }, { "country_code": "US", "country_name": "United States", "country_flag": "🇺🇸", "phone_number_code": "+1", "validation_regex": "^(\\+?1)?[2-9]\\d{2}[2-9](?!11)\\d{6}$", "format_example": "(123) 456-7890", "format_regex": "^\\(\\d{3}\\) \\d{3}-\\d{4}$" }, { "country_code": "UY", "country_name": "Uruguay", "country_flag": "🇺🇾", "phone_number_code": "+598", "validation_regex": "^(\\+?598|0)9\\d{7}$", "format_example": "091234567", "format_regex": "^(\\d{2})(\\d{3})(\\d{4})$" }, { "country_code": "UZ", "country_name": "Uzbekistan", "country_flag": "🇺🇿", "phone_number_code": "+998", "validation_regex": "^(\\+?998\\-?)[13-79]\\d{7}$", "format_example": "901234567", "format_regex": "^(\\d{3})(\\d{6})$" }, { "country_code": "VU", "country_name": "Vanuatu", "country_flag": "🇻🇺", "phone_number_code": "+678", "validation_regex": "^(\\+?678)\\d{5}$", "format_example": "59123", "format_regex": "^\\d{5}$" }, { "country_code": "VE", "country_name": "Venezuela", "country_flag": "🇻🇪", "phone_number_code": "+58", "validation_regex": "^(\\+?58)?[41269]\\d{7}$", "format_example": "04121234567", "format_regex": "^(\\d{4})(\\d{7})$" }, { "country_code": "VN", "country_name": "Vietnam", "country_flag": "🇻🇳", "phone_number_code": "+84", "validation_regex": "^(\\+?84|0)1\\d{9}$", "format_example": "0912345678", "format_regex": "^(\\d{3})(\\d{3})(\\d{4})$" }, { "country_code": "WF", "country_name": "Wallis and Futuna", "country_flag": "🇼🇫", "phone_number_code": "+681", "validation_regex": "^(\\+?681)\\d{6}$", "format_example": "501234", "format_regex": "^\\d{6}$" }, { "country_code": "EH", "country_name": "Western Sahara", "country_flag": "🇪🇭", "phone_number_code": "+212", "validation_regex": "^(\\+?212)\\d{9}$", "format_example": "0651234567", "format_regex": "^(\\d{2})(\\d{3})(\\d{2})(\\d{2})$" }, { "country_code": "YE", "country_name": "Yemen", "country_flag": "🇾🇪", "phone_number_code": "+967", "validation_regex": "^(\\+?967)?[12569]\\d{7}$", "format_example": "712345678", "format_regex": "^(\\d{3})(\\d{6})$" }, { "country_code": "ZM", "country_name": "Zambia", "country_flag": "🇿🇲", "phone_number_code": "+260", "validation_regex": "^(\\+?260)\\d{9}$", "format_example": "0951234567", "format_regex": "^(\\d{2})(\\d{3})(\\d{4})$" }, { "country_code": "ZW", "country_name": "Zimbabwe", "country_flag": "🇿🇼", "phone_number_code": "+263", "validation_regex": "^(\\+?263)\\d{9}$", "format_example": "0712345678", "format_regex": "^(\\d{2})(\\d{3})(\\d{4})$" } ] }
22,179
10,533
hyperswitch-web
src/Utilities/SamsungPayHelpers.res
.res
open SamsungPayType open Utils let getTransactionDetail = dict => { let amountDict = dict->getDictFromDict("amount") let merchantDict = dict->getDictFromDict("merchant") { orderNumber: dict->getString("order_number", ""), amount: { option: amountDict->getString("option", ""), currency: amountDict->getString("currency_code", ""), total: amountDict->getString("total", ""), }, merchant: { name: merchantDict->getString("name", ""), countryCode: merchantDict->getString("country_code", ""), url: merchantDict->getString("url", ""), }, } } let handleSamsungPayClicked = (~sessionObj, ~componentName, ~iframeId, ~readOnly) => { messageParentWindow([ ("fullscreen", true->JSON.Encode.bool), ("param", "paymentloader"->JSON.Encode.string), ("iframeId", iframeId->JSON.Encode.string), ("componentName", componentName->JSON.Encode.string), ]) if !readOnly { messageParentWindow([ ("SamsungPayClicked", true->JSON.Encode.bool), ("SPayPaymentDataRequest", getTransactionDetail(sessionObj)->Identity.anyTypeToJson), ]) } } let getPaymentMethodData = dict => { let threeDSDict = dict->getDictFromDict("3DS") { method: dict->getString("method", ""), recurring_payment: dict->getBool("recurring_payment", false), card_brand: dict->getString("card_brand", ""), card_last4digits: dict->getString("card_last4digits", ""), threeDS: { \"type": threeDSDict->getString("type", ""), version: threeDSDict->getString("version", ""), data: threeDSDict->getString("data", ""), }, } } let itemToObjMapper = dict => { paymentMethodData: getPaymentMethodData(dict), } let getSamsungPayBodyFromResponse = (~sPayResponse) => { sPayResponse->getDictFromJson->itemToObjMapper } let useHandleSamsungPayResponse = ( ~intent: PaymentHelpersTypes.paymentIntent, ~isSavedMethodsFlow=false, ~isWallet=true, ) => { let options = Recoil.useRecoilValueFromAtom(RecoilAtoms.optionAtom) let {publishableKey} = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys) let isManualRetryEnabled = Recoil.useRecoilValueFromAtom(RecoilAtoms.isManualRetryEnabled) let paymentMethodListValue = Recoil.useRecoilValueFromAtom(PaymentUtils.paymentMethodListValue) let isGuestCustomer = UtilityHooks.useIsGuestCustomer() React.useEffect0(() => { let handleSamsung = (ev: Window.event) => { let json = ev.data->safeParse let dict = json->getDictFromJson if dict->Dict.get("samsungPayResponse")->Option.isSome { let metadata = dict->getJsonObjectFromDict("samsungPayResponse") let getBody = getSamsungPayBodyFromResponse(~sPayResponse=metadata) let body = PaymentBody.samsungPayBody( ~metadata=getBody.paymentMethodData->Identity.anyTypeToJson, ) let finalBody = PaymentUtils.appendedCustomerAcceptance( ~isGuestCustomer, ~paymentType=paymentMethodListValue.payment_type, ~body, ) intent( ~bodyArr=finalBody, ~confirmParam={ return_url: options.wallets.walletReturnUrl, publishableKey, }, ~handleUserError=false, ~manualRetry=isManualRetryEnabled, ) } if dict->Dict.get("samsungPayError")->Option.isSome { messageParentWindow([("fullscreen", false->JSON.Encode.bool)]) if isSavedMethodsFlow || !isWallet { postFailedSubmitResponse(~errortype="server_error", ~message="Something went wrong") } } } Window.addEventListener("message", handleSamsung) Some(() => {Window.removeEventListener("message", handleSamsung)}) }) }
884
10,534
hyperswitch-web
src/Utilities/Identity.res
.res
external anyTypeToJson: 'a => JSON.t = "%identity" external unsafeToJsExn: exn => Exn.t = "%identity" external jsonToNullableJson: JSON.t => Nullable.t<JSON.t> = "%identity"
50
10,535
hyperswitch-web
src/Utilities/ApiEndpoint.res
.res
let switchToInteg = false let isLocal = false let sdkDomainUrl = `${GlobalVars.sdkUrl}${GlobalVars.repoPublicPath}` let apiEndPoint: ref<option<string>> = ref(None) let setApiEndPoint = str => { apiEndPoint := Some(str) } let getApiEndPoint = (~publishableKey="", ~isConfirmCall=false) => { let testMode = publishableKey->String.startsWith("pk_snd_") switch apiEndPoint.contents { | Some(str) => str | None => let backendEndPoint = isConfirmCall ? GlobalVars.confirmEndPoint : GlobalVars.backendEndPoint GlobalVars.isProd && testMode ? "https://beta.hyperswitch.io/api" : backendEndPoint } } let addCustomPodHeader = (arr: array<(string, string)>, ~customPodUri=?) => { switch customPodUri { | Some("") | None => () | Some(customPodVal) => arr->Array.push(("x-feature", customPodVal)) } arr->Dict.fromArray }
226
10,536
hyperswitch-web
src/Utilities/ErrorUtils.res
.res
type type_ = Error | Warning type stringType = Dynamic(string => string) | Static(string) type error = array<(HyperLogger.eventName, type_, string)> open HyperLogger let errorWarning = [ ( INVALID_PK, Error, Static( "INTEGRATION ERROR: Invalid Publishable key, starts with pk_dev_(development), pk_snd_(sandbox/test) or pk_prd_(production/live)", ), ), ( DEPRECATED_LOADSTRIPE, Warning, Static("loadStripe is deprecated. Please use loadHyper instead."), ), ( REQUIRED_PARAMETER, Error, Dynamic( str => {`INTEGRATION ERROR: ${str} is a required field/parameter or ${str} cannot be empty`}, ), ), ( UNKNOWN_KEY, Warning, Dynamic( str => { `Unknown Key: ${str} is a unknown/invalid key, please provide a correct key. This might cause issue in the future` }, ), ), ( TYPE_BOOL_ERROR, Error, Dynamic( str => { `Type Error: '${str}' Expected boolean` }, ), ), ( TYPE_STRING_ERROR, Error, Dynamic( str => { `Type Error: '${str}' Expected string` }, ), ), ( TYPE_INT_ERROR, Error, Dynamic( str => { `Type Error: '${str}' Expected int` }, ), ), ( VALUE_OUT_OF_RANGE, Warning, Dynamic( str => { `Value out of range: '${str}'. Please provide a value inside the range` }, ), ), ( UNKNOWN_VALUE, Warning, Dynamic( str => { `Unknown Value: ${str}. Please provide a correct value. This might cause issue in the future` }, ), ), ( SDK_CONNECTOR_WARNING, Warning, Dynamic( str => { `INTEGRATION ERROR: ${str}` }, ), ), (INVALID_FORMAT, Error, Dynamic(str => {str})), ( HTTP_NOT_ALLOWED, Error, Dynamic( str => `INTEGRATION ERROR: ${str} Serve your application over HTTPS. This is a requirement both in development and in production. One way to get up and running is to use a service like ngrok.`, ), ), ( INTERNAL_API_DOWN, Warning, Static( "LOAD ERROR: Something went wrong! Please try again or contact out dev support https://hyperswitch.io/docs/support", ), ), ] let manageErrorWarning = ( key: HyperLogger.eventName, ~dynamicStr="", ~logger: HyperLogger.loggerMake, ) => { let entry = errorWarning->Array.find(((value, _, _)) => value == key) switch entry { | Some(value) => { let (eventName, type_, str) = value let value = switch str { | Static(string) => string | Dynamic(fn) => fn(dynamicStr) } let logType: HyperLogger.logType = switch type_ { | Warning => WARNING | Error => ERROR } logger.setLogError(~value, ~eventName, ~logType, ~logCategory=USER_ERROR) switch type_ { | Warning => Console.warn(value) | Error => Console.error(value) Exn.raiseError(value) } } | None => () } } let unknownKeysWarning = (validKeysArr, dict: Dict.t<JSON.t>, dictType: string, ~logger) => { dict ->Dict.toArray ->Array.forEach(((key, _)) => { if validKeysArr->Array.includes(key) { () } else { manageErrorWarning(UNKNOWN_KEY, ~dynamicStr=`'${key}' key in ${dictType}`, ~logger) } }) } let unknownPropValueWarning = ( inValidValue, validValueArr, dictType, ~logger: HyperLogger.loggerMake, ) => { let expectedValues = validValueArr ->Array.map(item => { `'${item}'` }) ->Array.joinWith(", ") manageErrorWarning( UNKNOWN_VALUE, ~dynamicStr=`'${inValidValue}' value in ${dictType}, Expected ${expectedValues}`, ~logger, ) } let valueOutRangeWarning = (num: int, dictType, range, ~logger: HyperLogger.loggerMake) => { manageErrorWarning( VALUE_OUT_OF_RANGE, ~dynamicStr=`${num->Int.toString} value in ${dictType} Expected value between ${range}`, ~logger: HyperLogger.loggerMake, ) }
1,023
10,537
hyperswitch-web
src/Utilities/PaymentUtils.res
.res
let paymentMethodListValue = Recoil.atom("paymentMethodListValue", PaymentMethodsRecord.defaultList) let paymentListLookupNew = ( list: PaymentMethodsRecord.paymentMethodList, ~order, ~isShowPaypal, ~isShowKlarnaOneClick, ~isKlarnaSDKFlow, ~paymentMethodListValue: PaymentMethodsRecord.paymentMethodList, ~areAllGooglePayRequiredFieldsPrefilled, ~isGooglePayReady, ~shouldDisplayApplePayInTabs, ~shouldDisplayPayPalInTabs, ) => { let pmList = list->PaymentMethodsRecord.buildFromPaymentList let walletsList = [] let walletToBeDisplayedInTabs = [ "mb_way", "ali_pay", "ali_pay_hk", "mobile_pay", "we_chat_pay", "vipps", "twint", "dana", "go_pay", "kakao_pay", "gcash", "momo", "touch_n_go", "mifinity", ] let otherPaymentList = [] if shouldDisplayApplePayInTabs { walletToBeDisplayedInTabs->Array.push("apple_pay") } if shouldDisplayPayPalInTabs { walletToBeDisplayedInTabs->Array.push("paypal") } if ( !paymentMethodListValue.collect_billing_details_from_wallets && !areAllGooglePayRequiredFieldsPrefilled && isGooglePayReady ) { walletToBeDisplayedInTabs->Array.push("google_pay") } pmList->Array.forEach(item => { if walletToBeDisplayedInTabs->Array.includes(item.paymentMethodName) { otherPaymentList->Array.push(item.paymentMethodName)->ignore } else if item.methodType == "wallet" { if item.paymentMethodName !== "paypal" || isShowPaypal { walletsList->Array.push(item.paymentMethodName)->ignore } } else if item.methodType == "bank_debit" { otherPaymentList->Array.push(item.paymentMethodName ++ "_debit")->ignore } else if ( item.methodType == "bank_transfer" && (item.paymentMethodName !== "sepa_bank_transfer" && item.paymentMethodName !== "instant_bank_transfer") ) { otherPaymentList->Array.push(item.paymentMethodName ++ "_transfer")->ignore } else if item.methodType == "card" { otherPaymentList->Array.push("card")->ignore } else if item.methodType == "reward" { otherPaymentList->Array.push(item.paymentMethodName)->ignore } else if item.methodType == "pay_later" { if item.paymentMethodName === "klarna" { let klarnaPaymentMethodExperience = PaymentMethodsRecord.getPaymentExperienceTypeFromPML( ~paymentMethodList=paymentMethodListValue, ~paymentMethodName=item.methodType, ~paymentMethodType=item.paymentMethodName, ) let isInvokeSDKExperience = klarnaPaymentMethodExperience->Array.includes(InvokeSDK) let isRedirectExperience = klarnaPaymentMethodExperience->Array.includes(RedirectToURL) // To be fixed for Klarna Checkout - PR - https://github.com/juspay/hyperswitch-web/pull/851 if isKlarnaSDKFlow && isShowKlarnaOneClick && isInvokeSDKExperience { walletsList->Array.push(item.paymentMethodName)->ignore } else if isRedirectExperience { otherPaymentList->Array.push(item.paymentMethodName)->ignore } } else { otherPaymentList->Array.push(item.paymentMethodName)->ignore } } else { otherPaymentList->Array.push(item.paymentMethodName)->ignore } }) ( walletsList->Utils.removeDuplicate->Utils.sortBasedOnPriority(order), otherPaymentList->Utils.removeDuplicate->Utils.sortBasedOnPriority(order), ) } type exp = Redirect | SDK type paylater = Klarna(exp) | AfterPay(exp) | Affirm(exp) type wallet = Gpay(exp) | ApplePay(exp) | Paypal(exp) type card = Credit(exp) | Debit(exp) type banks = Sofort | Eps | GiroPay | Ideal | EFT type transfer = ACH | Sepa | Bacs | Instant type connectorType = | PayLater(paylater) | Wallets(wallet) | Cards(card) | Banks(banks) | BankTransfer(transfer) | BankDebit(transfer) | Crypto let getMethod = method => { switch method { | PayLater(_) => "pay_later" | Wallets(_) => "wallet" | Cards(_) => "card" | Banks(_) => "bank_redirect" | BankTransfer(_) => "bank_transfer" | BankDebit(_) => "bank_debit" | Crypto => "crypto" } } let getMethodType = method => { switch method { | PayLater(val) => switch val { | Klarna(_) => "klarna" | AfterPay(_) => "afterpay_clearpay" | Affirm(_) => "affirm" } | Wallets(val) => switch val { | Gpay(_) => "google_pay" | ApplePay(_) => "apple_pay" | Paypal(_) => "paypal" } | Cards(_) => "card" | Banks(val) => switch val { | Sofort => "sofort" | Eps => "eps" | GiroPay => "giropay" | Ideal => "ideal" | EFT => "eft" } | BankDebit(val) | BankTransfer(val) => switch val { | ACH => "ach" | Bacs => "bacs" | Sepa => "sepa" | Instant => "instant" } | Crypto => "crypto_currency" } } let getExperience = (val: exp) => { switch val { | Redirect => "redirect_to_url" | SDK => "invoke_sdk_client" } } let getPaymentExperienceType = (val: PaymentMethodsRecord.paymentFlow) => { switch val { | RedirectToURL => "redirect_to_url" | InvokeSDK => "invoke_sdk_client" | QrFlow => "display_qr_code" } } let getExperienceType = method => { switch method { | PayLater(val) => switch val { | Klarna(val) => val->getExperience | AfterPay(val) => val->getExperience | Affirm(val) => val->getExperience } | Wallets(val) => switch val { | Gpay(val) => val->getExperience | ApplePay(val) => val->getExperience | Paypal(val) => val->getExperience } | Cards(_) => "card" | Crypto => "redirect_to_url" | _ => "" } } let getConnectors = (list: PaymentMethodsRecord.paymentMethodList, method: connectorType) => { let paymentMethod = list.payment_methods->Array.find(item => item.payment_method == method->getMethod) switch paymentMethod { | Some(val) => let paymentMethodType = val.payment_method_types->Array.find(item => item.payment_method_type == method->getMethodType ) switch paymentMethodType { | Some(val) => let experienceType = val.payment_experience->Array.find(item => { item.payment_experience_type->getPaymentExperienceType == method->getExperienceType }) let eligibleConnectors = switch experienceType { | Some(val) => val.eligible_connectors | None => [] } switch method { | Banks(_) => ([], val.bank_names) | BankTransfer(_) => (val.bank_transfers_connectors, []) | BankDebit(_) => (val.bank_debits_connectors, []) | _ => (eligibleConnectors, []) } | None => ([], []) } | None => ([], []) } } let getDisplayNameAndIcon = ( customNames: PaymentType.customMethodNames, paymentMethodName, defaultName, defaultIcon, ) => { let customNameObj = customNames ->Array.filter((item: PaymentType.alias) => { item.paymentMethodName === paymentMethodName }) ->Array.get(0) switch customNameObj { | Some(val) => val.paymentMethodName === "classic" || val.paymentMethodName === "evoucher" ? { switch val.aliasName { | "" => (defaultName, defaultIcon) | aliasName => let id = aliasName->String.split(" ") ( aliasName, Some(PaymentMethodsRecord.icon(id->Array.get(0)->Option.getOr(""), ~size=19)), ) } } : (defaultName, defaultIcon) | None => (defaultName, defaultIcon) } } let getPaymentMethodName = (~paymentMethodType, ~paymentMethodName) => { if paymentMethodType == "bank_debit" { paymentMethodName->String.replace("_debit", "") } else if ( paymentMethodType == "bank_transfer" && (paymentMethodName !== "sepa_bank_transfer" && paymentMethodName !== "instant_bank_transfer") ) { paymentMethodName->String.replace("_transfer", "") } else { paymentMethodName } } let isAppendingCustomerAcceptance = ( ~isGuestCustomer, ~paymentType: PaymentMethodsRecord.payment_type, ) => { !isGuestCustomer && (paymentType === NEW_MANDATE || paymentType === SETUP_MANDATE) } let appendedCustomerAcceptance = (~isGuestCustomer, ~paymentType, ~body) => { isAppendingCustomerAcceptance(~isGuestCustomer, ~paymentType) ? body->Array.concat([("customer_acceptance", PaymentBody.customerAcceptanceBody)]) : body } let usePaymentMethodTypeFromList = ( ~paymentMethodListValue, ~paymentMethod, ~paymentMethodType, ) => { React.useMemo(() => { PaymentMethodsRecord.getPaymentMethodTypeFromList( ~paymentMethodListValue, ~paymentMethod, ~paymentMethodType=getPaymentMethodName( ~paymentMethodType=paymentMethod, ~paymentMethodName=paymentMethodType, ), )->Option.getOr(PaymentMethodsRecord.defaultPaymentMethodType) }, (paymentMethodListValue, paymentMethod, paymentMethodType)) } let useAreAllRequiredFieldsPrefilled = ( ~paymentMethodListValue, ~paymentMethod, ~paymentMethodType, ) => { let paymentMethodTypes = usePaymentMethodTypeFromList( ~paymentMethodListValue, ~paymentMethod, ~paymentMethodType, ) paymentMethodTypes.required_fields->Array.reduce(true, (acc, requiredField) => { acc && requiredField.value != "" }) } let getIsKlarnaSDKFlow = sessions => { let dict = sessions->Utils.getDictFromJson let sessionObj = SessionsType.itemToObjMapper(dict, Others) let klarnaTokenObj = SessionsType.getPaymentSessionObj(sessionObj.sessionsToken, Klarna) switch klarnaTokenObj { | OtherTokenOptional(optToken) => optToken->Option.isSome | _ => false } } let usePaypalFlowStatus = (~sessions, ~paymentMethodListValue) => { open Utils let sessionObj = sessions ->getDictFromJson ->SessionsType.itemToObjMapper(Others) let { paypalToken, isPaypalSDKFlow, isPaypalRedirectFlow, } = PayPalHelpers.usePaymentMethodExperience(~paymentMethodListValue, ~sessionObj) let isPaypalTokenExist = switch paypalToken { | OtherTokenOptional(optToken) => switch optToken { | Some(_) => true | _ => false } | _ => false } (isPaypalSDKFlow, isPaypalRedirectFlow, isPaypalTokenExist) } let useGetPaymentMethodList = (~paymentOptions, ~paymentType, ~sessions) => { open Utils let methodslist = Recoil.useRecoilValueFromAtom(RecoilAtoms.paymentMethodList) let {showCardFormByDefault, paymentMethodOrder} = Recoil.useRecoilValueFromAtom( RecoilAtoms.optionAtom, ) let optionAtomValue = Recoil.useRecoilValueFromAtom(RecoilAtoms.optionAtom) let paymentOrder = paymentMethodOrder->getOptionalArr->removeDuplicate let isKlarnaSDKFlow = getIsKlarnaSDKFlow(sessions) let paymentMethodListValue = Recoil.useRecoilValueFromAtom(paymentMethodListValue) let areAllApplePayRequiredFieldsPrefilled = useAreAllRequiredFieldsPrefilled( ~paymentMethodListValue, ~paymentMethod="wallet", ~paymentMethodType="apple_pay", ) let areAllGooglePayRequiredFieldsPrefilled = useAreAllRequiredFieldsPrefilled( ~paymentMethodListValue, ~paymentMethod="wallet", ~paymentMethodType="google_pay", ) let areAllPaypalRequiredFieldsPreFilled = useAreAllRequiredFieldsPrefilled( ~paymentMethodListValue, ~paymentMethod="wallet", ~paymentMethodType="paypal", ) let isApplePayReady = Recoil.useRecoilValueFromAtom(RecoilAtoms.isApplePayReady) let isGooglePayReady = Recoil.useRecoilValueFromAtom(RecoilAtoms.isGooglePayReady) let (isPaypalSDKFlow, isPaypalRedirectFlow, isPaypalTokenExist) = usePaypalFlowStatus( ~sessions, ~paymentMethodListValue, ) React.useMemo(() => { switch methodslist { | Loaded(paymentlist) => let paymentOrder = paymentOrder->Array.length > 0 ? paymentOrder : PaymentModeType.defaultOrder let plist = paymentlist->getDictFromJson->PaymentMethodsRecord.itemToObjMapper let shouldDisplayApplePayInTabs = !paymentMethodListValue.collect_billing_details_from_wallets && !areAllApplePayRequiredFieldsPrefilled && isApplePayReady let isShowPaypal = optionAtomValue.wallets.payPal === Auto let shouldDisplayPayPalInTabs = isShowPaypal && !paymentMethodListValue.collect_billing_details_from_wallets && !areAllPaypalRequiredFieldsPreFilled && isPaypalRedirectFlow && (!isPaypalSDKFlow || !isPaypalTokenExist) let (wallets, otherOptions) = plist->paymentListLookupNew( ~order=paymentOrder, ~isShowPaypal, ~isShowKlarnaOneClick=optionAtomValue.wallets.klarna === Auto, ~isKlarnaSDKFlow, ~paymentMethodListValue=plist, ~areAllGooglePayRequiredFieldsPrefilled, ~isGooglePayReady, ~shouldDisplayApplePayInTabs, ~shouldDisplayPayPalInTabs, ) let klarnaPaymentMethodExperience = PaymentMethodsRecord.getPaymentExperienceTypeFromPML( ~paymentMethodList=plist, ~paymentMethodName="pay_later", ~paymentMethodType="klarna", ) let isKlarnaInvokeSDKExperience = klarnaPaymentMethodExperience->Array.includes(InvokeSDK) let filterPaymentMethods = (paymentOptionsList: array<string>) => { paymentOptionsList->Array.filter(paymentOptionsName => { switch paymentOptionsName { | "klarna" => !(isKlarnaSDKFlow && isKlarnaInvokeSDKExperience) | "apple_pay" => shouldDisplayApplePayInTabs | _ => true } }) } ( wallets->removeDuplicate->Utils.getWalletPaymentMethod(paymentType), paymentOptions ->Array.concat(otherOptions) ->removeDuplicate ->filterPaymentMethods, otherOptions, ) | SemiLoaded => showCardFormByDefault && checkPriorityList(paymentMethodOrder) ? ([], ["card"], []) : ([], [], []) | _ => ([], [], []) } }, ( methodslist, paymentMethodOrder, optionAtomValue.wallets.payPal, optionAtomValue.wallets.klarna, paymentType, isKlarnaSDKFlow, areAllApplePayRequiredFieldsPrefilled, areAllGooglePayRequiredFieldsPrefilled, isApplePayReady, isGooglePayReady, showCardFormByDefault, )) } let useStatesJson = setStatesJson => { React.useEffect0(_ => { let fetchStates = async () => { try { let res = await AddressPaymentInput.importStates("./../States.json") setStatesJson(_ => res.states) } catch { | err => Console.error2("Error importing states:", err) } } fetchStates()->ignore None }) } let getStateJson = async _ => { try { let res = await AddressPaymentInput.importStates("./../States.json") res.states } catch { | err => Console.error2("Error importing states:", err) JSON.Encode.null } } let sortCustomerMethodsBasedOnPriority = ( sortArr: array<PaymentType.customerMethods>, priorityArr: array<string>, ~displayDefaultSavedPaymentIcon=true, ) => { if priorityArr->Array.length === 0 { sortArr } else { // * Need to discuss why this is used. // let priorityArr = priorityArr->Array.length > 0 ? priorityArr : PaymentModeType.defaultOrder let getPaymentMethod = (customerMethod: PaymentType.customerMethods) => { if customerMethod.paymentMethod === "card" { customerMethod.paymentMethod } else { switch customerMethod.paymentMethodType { | Some(paymentMethodType) => paymentMethodType | _ => customerMethod.paymentMethod } } } let getCustomerMethodPriority = (paymentMethod: string) => { let priorityArrLength = priorityArr->Array.length let index = priorityArr->Array.indexOf(paymentMethod) index === -1 ? priorityArrLength : index } let handleCustomerMethodsSort = ( firstCustomerMethod: PaymentType.customerMethods, secondCustomerMethod: PaymentType.customerMethods, ) => { let firstPaymentMethod = firstCustomerMethod->getPaymentMethod let secondPaymentMethod = secondCustomerMethod->getPaymentMethod if ( displayDefaultSavedPaymentIcon && (firstCustomerMethod.defaultPaymentMethodSet || secondCustomerMethod.defaultPaymentMethodSet) ) { firstCustomerMethod.defaultPaymentMethodSet ? -1 : 1 } else { firstPaymentMethod->getCustomerMethodPriority - secondPaymentMethod->getCustomerMethodPriority } } sortArr->Belt.SortArray.stableSortBy(handleCustomerMethodsSort) } } let getSupportedCardBrands = (paymentMethodListValue: PaymentMethodsRecord.paymentMethodList) => { let cardPaymentMethod = paymentMethodListValue.payment_methods->Array.find(ele => ele.payment_method === "card") switch cardPaymentMethod { | Some(cardPaymentMethod) => let cardNetworks = cardPaymentMethod.payment_method_types->Array.map(ele => ele.card_networks) let cardNetworkNames = cardNetworks->Array.map(ele => ele->Array.map(val => val.card_network->CardUtils.getCardStringFromType->String.toLowerCase) ) Some( cardNetworkNames ->Array.reduce([], (acc, ele) => acc->Array.concat(ele)) ->Utils.getUniqueArray, ) | None => None } } let checkIsCardSupported = (cardNumber, supportedCardBrands) => { let cardBrand = cardNumber->CardUtils.getCardBrand let clearValue = cardNumber->CardUtils.clearSpaces if cardBrand == "" { Some(CardUtils.cardValid(clearValue, cardBrand)) } else if CardUtils.cardValid(clearValue, cardBrand) { switch supportedCardBrands { | Some(brands) => Some(brands->Array.includes(cardBrand->String.toLowerCase)) | None => Some(true) } } else { None } } let emitMessage = paymentMethodInfo => Utils.messageParentWindow([("paymentMethodInfo", paymentMethodInfo->JSON.Encode.object)]) let emitPaymentMethodInfo = (~paymentMethod, ~paymentMethodType, ~cardBrand=CardUtils.NOTFOUND) => { if cardBrand === CardUtils.NOTFOUND { emitMessage( [ ("paymentMethod", paymentMethod->JSON.Encode.string), ("paymentMethodType", paymentMethodType->JSON.Encode.string), ]->Dict.fromArray, ) } else { emitMessage( [ ("paymentMethod", paymentMethod->JSON.Encode.string), ("paymentMethodType", paymentMethodType->JSON.Encode.string), ("cardBrand", cardBrand->CardUtils.getCardStringFromType->JSON.Encode.string), ]->Dict.fromArray, ) } } let useEmitPaymentMethodInfo = ( ~paymentMethodName, ~paymentMethods: array<PaymentMethodsRecord.methods>, ~cardBrand, ) => { let loggerState = Recoil.useRecoilValueFromAtom(RecoilAtoms.loggerAtom) React.useEffect(() => { if paymentMethodName->String.includes("_debit") { emitPaymentMethodInfo(~paymentMethod="bank_debit", ~paymentMethodType=paymentMethodName) } else if paymentMethodName->String.includes("_transfer") { emitPaymentMethodInfo(~paymentMethod="bank_transfer", ~paymentMethodType=paymentMethodName) } else if paymentMethodName === "card" { emitPaymentMethodInfo( ~paymentMethod="card", ~paymentMethodType="debit", ~cardBrand=cardBrand->CardUtils.getCardType, ) } else { let finalOptionalPaymentMethodTypeValue = paymentMethods ->Array.filter(paymentMethodData => paymentMethodData.payment_method_types ->Array.filter( paymentMethodType => paymentMethodType.payment_method_type === paymentMethodName, ) ->Array.length > 0 ) ->Array.get(0) switch finalOptionalPaymentMethodTypeValue { | Some(finalPaymentMethodType) => emitPaymentMethodInfo( ~paymentMethod=finalPaymentMethodType.payment_method, ~paymentMethodType=paymentMethodName, ) | None => loggerState.setLogError( ~value="Payment method type not found", ~eventName=PAYMENT_METHOD_TYPE_DETECTION_FAILED, ) } } None }, (paymentMethodName, cardBrand, paymentMethods)) }
4,903
10,538
hyperswitch-web
src/Utilities/PaymentHelpersTypes.res
.res
type payment = | Card | BankTransfer | BankDebits | KlarnaRedirect | Gpay | Applepay | Paypal | Samsungpay | Paze | Other type paymentIntent = ( ~handleUserError: bool=?, ~bodyArr: array<(string, JSON.t)>, ~confirmParam: ConfirmType.confirmParams, ~iframeId: string=?, ~isThirdPartyFlow: bool=?, ~intentCallback: Core__JSON.t => unit=?, ~manualRetry: bool=?, ) => unit type completeAuthorize = ( ~handleUserError: bool=?, ~bodyArr: array<(string, JSON.t)>, ~confirmParam: ConfirmType.confirmParams, ~iframeId: string=?, ) => unit
181
10,539
hyperswitch-web
src/Utilities/EventListenerManager.res
.res
type sessionStorage @val external sessionStorage: sessionStorage = "sessionStorage" @send external setItem: (sessionStorage, string, 'a => unit) => unit = "setItem" let eventListenerMap: Dict.t<Types.event => unit> = Dict.make() let addSmartEventListener = (type_, handlerMethod: Types.event => unit, activity) => { switch eventListenerMap->Dict.get(activity) { | Some(value) => Window.removeEventListener(type_, value) | None => () } eventListenerMap->Dict.set(activity, handlerMethod) Window.addEventListener(type_, handlerMethod) }
125
10,540
hyperswitch-web
src/Utilities/Utils.res
.res
@val external document: 'a = "document" @val external window: Dom.element = "window" @val @scope("window") external iframeParent: Dom.element = "parent" @send external body: ('a, Dom.element) => Dom.element = "body" @val @scope("window") external topParent: Dom.element = "top" type event = {data: string} external dictToObj: Dict.t<'a> => {..} = "%identity" @module("./Phone_number.json") external phoneNumberJson: JSON.t = "default" type options = {timeZone: string} type dateTimeFormat = {resolvedOptions: unit => options} @val @scope("Intl") external dateTimeFormat: unit => dateTimeFormat = "DateTimeFormat" @send external remove: Dom.element => unit = "remove" @send external postMessage: (Dom.element, JSON.t, string) => unit = "postMessage" open ErrorUtils let getJsonFromArrayOfJson = arr => arr->Dict.fromArray->JSON.Encode.object let messageWindow = (window, ~targetOrigin="*", messageArr) => { window->postMessage(messageArr->getJsonFromArrayOfJson, targetOrigin) } let messageTopWindow = (~targetOrigin="*", messageArr) => { topParent->messageWindow(~targetOrigin, messageArr) } let messageParentWindow = (~targetOrigin="*", messageArr) => { iframeParent->messageWindow(~targetOrigin, messageArr) } let messageCurrentWindow = (~targetOrigin="*", messageArr) => { window->messageWindow(~targetOrigin, messageArr) } let handleOnFocusPostMessage = (~targetOrigin="*") => { messageParentWindow([("focus", true->JSON.Encode.bool)], ~targetOrigin) } let handleOnCompleteDoThisMessage = (~targetOrigin="*") => { messageParentWindow([("completeDoThis", true->JSON.Encode.bool)], ~targetOrigin) } let handleOnBlurPostMessage = (~targetOrigin="*") => { messageParentWindow([("blur", true->JSON.Encode.bool)], ~targetOrigin) } let handleOnClickPostMessage = (~targetOrigin="*", ev) => { messageParentWindow( [("clickTriggered", true->JSON.Encode.bool), ("event", ev->JSON.stringify->JSON.Encode.string)], ~targetOrigin, ) } let handleOnConfirmPostMessage = (~targetOrigin="*", ~isOneClick=false) => { let message = isOneClick ? "oneClickConfirmTriggered" : "confirmTriggered" messageParentWindow([(message, true->JSON.Encode.bool)], ~targetOrigin) } let handleBeforeRedirectPostMessage = (~targetOrigin="*") => { messageTopWindow([("disableBeforeUnloadEventListener", true->JSON.Encode.bool)], ~targetOrigin) } let getOptionString = (dict, key) => { dict->Dict.get(key)->Option.flatMap(JSON.Decode.string) } let getString = (dict, key, default) => { getOptionString(dict, key)->Option.getOr(default) } let getStringFromJson = (json, default) => { json->JSON.Decode.string->Option.getOr(default) } let convertDictToArrayOfKeyStringTuples = dict => { dict ->Dict.toArray ->Array.map(entries => { let (x, val) = entries (x, val->JSON.Decode.string->Option.getOr("")) }) } let mergeHeadersIntoDict = (~dict, ~headers) => { headers->Array.forEach(entries => { let (x, val) = entries Dict.set(dict, x, val->JSON.Encode.string) }) } let getInt = (dict, key, default: int) => { dict ->Dict.get(key) ->Option.flatMap(JSON.Decode.float) ->Option.getOr(default->Int.toFloat) ->Float.toInt } let getFloatFromString = (str, default) => str->Float.fromString->Option.getOr(default) let getFloatFromJson = (json, default) => { switch json->JSON.Classify.classify { | String(str) => getFloatFromString(str, default) | Number(floatValue) => floatValue | _ => default } } let getFloat = (dict, key, default) => { dict->Dict.get(key)->Option.map(json => getFloatFromJson(json, default))->Option.getOr(default) } let getJsonBoolValue = (dict, key, default) => { dict->Dict.get(key)->Option.getOr(default->JSON.Encode.bool) } let getJsonStringFromDict = (dict, key, default) => { dict->Dict.get(key)->Option.getOr(default->JSON.Encode.string) } let getJsonArrayFromDict = (dict, key, default) => { dict->Dict.get(key)->Option.getOr(default->JSON.Encode.array) } let getJsonFromDict = (dict, key, default) => { dict->Dict.get(key)->Option.getOr(default) } let getJsonObjFromDict = (dict, key, default) => { dict->Dict.get(key)->Option.flatMap(JSON.Decode.object)->Option.getOr(default) } let getDecodedStringFromJson = (json, callbackFunc, defaultValue) => { json ->JSON.Decode.object ->Option.flatMap(callbackFunc) ->Option.flatMap(JSON.Decode.string) ->Option.getOr(defaultValue) } let getDecodedBoolFromJson = (json, callbackFunc, defaultValue) => { json ->JSON.Decode.object ->Option.flatMap(callbackFunc) ->Option.flatMap(JSON.Decode.bool) ->Option.getOr(defaultValue) } let getRequiredString = (dict, key, default, ~logger) => { let optionalStr = getOptionString(dict, key) switch optionalStr { | Some(val) => { val == "" ? manageErrorWarning(REQUIRED_PARAMETER, ~dynamicStr=key, ~logger) : () val } | None => { manageErrorWarning(REQUIRED_PARAMETER, ~dynamicStr=key, ~logger) optionalStr->Option.getOr(default) } } } let getWarningString = (dict, key, default, ~logger) => { switch dict->Dict.get(key) { | Some(val) => switch val->JSON.Decode.string { | Some(val) => val | None => manageErrorWarning(TYPE_STRING_ERROR, ~dynamicStr=key, ~logger) default } | None => default } } let getDictFromObj = (dict, key) => { dict->Dict.get(key)->Option.flatMap(JSON.Decode.object)->Option.getOr(Dict.make()) } let getJsonObjectFromDict = (dict, key) => { dict->Dict.get(key)->Option.getOr(JSON.Encode.object(Dict.make())) } let getOptionBool = (dict, key) => { dict->Dict.get(key)->Option.flatMap(JSON.Decode.bool) } let getDictFromJson = (json: JSON.t) => { json->JSON.Decode.object->Option.getOr(Dict.make()) } let getDictFromDict = (dict, key) => { dict->getJsonObjectFromDict(key)->getDictFromJson } let getBool = (dict, key, default) => { getOptionBool(dict, key)->Option.getOr(default) } let getBoolWithWarning = (dict, key, default, ~logger) => { switch dict->Dict.get(key) { | Some(val) => switch val->JSON.Decode.bool { | Some(val) => val | None => manageErrorWarning(TYPE_BOOL_ERROR, ~dynamicStr=key, ~logger) default } | None => default } } let getNumberWithWarning = (dict, key, ~logger, default) => { switch dict->Dict.get(key) { | Some(val) => switch val->JSON.Decode.float { | Some(val) => val->Float.toInt | None => manageErrorWarning(TYPE_INT_ERROR, ~dynamicStr=key, ~logger) default } | None => default } } let getOptionalArrayFromDict = (dict, key) => { dict->Dict.get(key)->Option.flatMap(JSON.Decode.array) } let getArray = (dict, key) => { dict->getOptionalArrayFromDict(key)->Option.getOr([]) } let getStrArray = (dict, key) => { dict ->getOptionalArrayFromDict(key) ->Option.getOr([]) ->Array.map(json => json->getStringFromJson("")) } let getOptionalStrArray: (Dict.t<JSON.t>, string) => option<array<string>> = (dict, key) => { switch dict->getOptionalArrayFromDict(key) { | Some(val) => val->Array.length === 0 ? None : Some(val->Array.map(json => json->getStringFromJson(""))) | None => None } } let getBoolValue = val => val->Option.getOr(false) let toKebabCase = str => { str ->String.split("") ->Array.mapWithIndex((item, i) => { if item->String.toUpperCase === item { `${i != 0 ? "-" : ""}${item->String.toLowerCase}` } else { item } }) ->Array.joinWith("") } let handleMessage = (fun, _errorMessage) => { let handle = (ev: Window.event) => { try { fun(ev) } catch { | _err => () } } Window.addEventListener("message", handle) Some(() => Window.removeEventListener("message", handle)) } let useSubmitPaymentData = callback => { React.useEffect(() => {handleMessage(callback, "")}, [callback]) } let useWindowSize = () => { let (size, setSize) = React.useState(_ => (0, 0)) React.useLayoutEffect1(() => { let updateSize = () => { setSize(_ => (Window.innerWidth, Window.innerHeight)) } Window.addEventListener("resize", updateSize) updateSize() Some(_ => Window.removeEventListener("resize", updateSize)) }, []) size } let mergeJsons = (json1, json2) => { let obj1 = json1->getDictFromJson let obj2 = json2->getDictFromJson let rec merge = (obj1, obj2) => { if obj1 != obj2 { obj2 ->Dict.keysToArray ->Array.map(key => { let overrideProp = obj2->getJsonObjectFromDict(key) let defaultProp = obj1->getJsonObjectFromDict(key) if defaultProp->getDictFromJson->Dict.keysToArray->Array.length == 0 { obj1->Dict.set(key, overrideProp) } else if ( overrideProp->JSON.Decode.object->Option.isSome && defaultProp->JSON.Decode.object->Option.isSome ) { merge(defaultProp->getDictFromJson, overrideProp->getDictFromJson) } else if overrideProp !== defaultProp { obj1->Dict.set(key, overrideProp) } }) ->ignore obj1 } else { obj1 }->ignore } merge(obj1, obj2)->ignore obj1->JSON.Encode.object } let postFailedSubmitResponse = (~errortype, ~message) => { let errorDict = [ ("type", errortype->JSON.Encode.string), ("message", message->JSON.Encode.string), ]->Dict.fromArray messageParentWindow([ ("submitSuccessful", false->JSON.Encode.bool), ("error", errorDict->JSON.Encode.object), ]) } let postSubmitResponse = (~jsonData, ~url) => { messageParentWindow([ ("submitSuccessful", true->JSON.Encode.bool), ("data", jsonData), ("url", url->JSON.Encode.string), ]) } let getFailedSubmitResponse = (~errorType, ~message) => { [ ( "error", [ ("type", errorType->JSON.Encode.string), ("message", message->JSON.Encode.string), ]->getJsonFromArrayOfJson, ), ]->getJsonFromArrayOfJson } let toCamelCase = str => { if str->String.includes(":") { str } else { str ->String.toLowerCase ->Js.String2.unsafeReplaceBy0(%re(`/([-_][a-z])/g`), (letter, _, _) => { letter->String.toUpperCase }) ->String.replaceRegExp(%re(`/[^a-zA-Z]/g`), "") } } let toSnakeCase = str => { str->Js.String2.unsafeReplaceBy0(%re("/[A-Z]/g"), (letter, _, _) => `_${letter->String.toLowerCase}` ) } type case = CamelCase | SnakeCase | KebabCase let rec transformKeys = (json: JSON.t, to: case) => { let toCase = switch to { | CamelCase => toCamelCase | SnakeCase => toSnakeCase | KebabCase => toKebabCase } let dict = json->getDictFromJson dict ->Dict.toArray ->Array.map(((key, value)) => { let x = switch JSON.Classify.classify(value) { | Object(obj) => (key->toCase, obj->JSON.Encode.object->transformKeys(to)) | Array(arr) => ( key->toCase, { arr ->Array.map(item => if item->JSON.Decode.object->Option.isSome { item->transformKeys(to) } else { item } ) ->JSON.Encode.array }, ) | String(str) => { let val = if str == "Final" { "FINAL" } else if str == "example" || str == "Adyen" { "adyen" } else { str } (key->toCase, val->JSON.Encode.string) } | Number(val) => (key->toCase, val->Float.toString->JSON.Encode.string) | _ => (key->toCase, value) } x }) ->getJsonFromArrayOfJson } let getClientCountry = clientTimeZone => { Country.country ->Array.find(item => item.timeZones->Array.find(i => i == clientTimeZone)->Option.isSome) ->Option.getOr(Country.defaultTimeZone) } let removeDuplicate = arr => { arr->Array.filterWithIndex((item, i) => { arr->Array.indexOf(item) === i }) } let isEmailValid = email => { switch email->String.match( %re( "/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/" ), ) { | Some(_match) => Some(true) | None => email->String.length > 0 ? Some(false) : None } } let isVpaIdValid = vpaId => { switch vpaId->String.match( %re("/^[a-zA-Z0-9]([a-zA-Z0-9.-]{1,50})[a-zA-Z0-9]@[a-zA-Z0-9]{2,}$/"), ) { | Some(_match) => Some(true) | None => vpaId->String.length > 0 ? Some(false) : None } } let checkEmailValid = ( email: RecoilAtomTypes.field, fn: (RecoilAtomTypes.field => RecoilAtomTypes.field) => unit, ) => { switch email.value->String.match( %re( "/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/" ), ) { | Some(_match) => fn(prev => { ...prev, isValid: Some(true), }) | None => email.value->String.length > 0 ? fn(prev => { ...prev, isValid: Some(false), }) : fn(prev => { ...prev, isValid: None, }) } } let validatePhoneNumber = (countryCode, number) => { let phoneNumberDict = phoneNumberJson->JSON.Decode.object->Option.getOr(Dict.make()) let countriesArr = phoneNumberDict ->Dict.get("countries") ->Option.flatMap(JSON.Decode.array) ->Option.getOr([]) ->Belt.Array.keepMap(JSON.Decode.object) let filteredArr = countriesArr->Array.filter(countryObj => { countryObj ->Dict.get("phone_number_code") ->Option.flatMap(JSON.Decode.string) ->Option.getOr("") == countryCode }) switch filteredArr[0] { | Some(obj) => let regex = obj->Dict.get("validation_regex")->Option.flatMap(JSON.Decode.string)->Option.getOr("") RegExp.test(regex->RegExp.fromString, number) | None => false } } let sortBasedOnPriority = (sortArr: array<string>, priorityArr: array<string>) => { let finalPriorityArr = priorityArr->Array.filter(val => sortArr->Array.includes(val)) sortArr ->Array.map(item => { if finalPriorityArr->Array.includes(item) { () } else { finalPriorityArr->Array.push(item)->ignore } }) ->ignore finalPriorityArr } let isAllValid = ( card: option<bool>, cardSupported: option<bool>, cvc: option<bool>, expiry: option<bool>, zip: bool, paymentMode: string, ) => { card->getBoolValue && cardSupported->getBoolValue && cvc->getBoolValue && expiry->getBoolValue && (paymentMode == "payment" || zip) } let getCountryPostal = (countryCode, postalCodes: array<PostalCodeType.postalCodes>) => { postalCodes ->Array.find(item => item.iso == countryCode) ->Option.getOr(PostalCodeType.defaultPostalCode) } let getCountryNames = (list: array<Country.timezoneType>) => { list->Array.reduce([], (arr, item) => { arr->Array.push(item.countryName)->ignore arr }) } let getBankNames = (list: Bank.bankList, allBanks: array<string>) => { list->Array.reduce([], (arr, item) => { if allBanks->Array.includes(item.hyperSwitch) { arr->Array.push(item.displayName)->ignore } arr }) } let getBankKeys = (str, banks: Bank.bankList, default) => { let bank = banks->Array.find(item => item.displayName == str)->Option.getOr(default) bank.hyperSwitch } let constructClass = (~classname, ~dict) => { let puseduoArr = [] let modifiedArr = [] dict ->Dict.toArray ->Array.map(entry => { let (key, value) = entry let class = if !(key->String.startsWith(":")) && !(key->String.startsWith(".")) { switch value->JSON.Decode.string { | Some(str) => `${key->toKebabCase}:${str}` | None => "" } } else if key->String.startsWith(":") { switch value->JSON.Decode.object { | Some(obj) => let style = obj ->Dict.toArray ->Array.map(entry => { let (key, value) = entry switch value->JSON.Decode.string { | Some(str) => `${key->toKebabCase}:${str}` | None => "" } }) `.${classname}${key} {${style->Array.joinWith(";")}}` | None => "" } } else if key->String.startsWith(".") { switch value->JSON.Decode.object { | Some(obj) => let style = obj ->Dict.toArray ->Array.map(entry => { let (key, value) = entry switch value->JSON.Decode.string { | Some(str) => `${key->toKebabCase}:${str}` | None => "" } }) `${key} {${style->Array.joinWith(";")}} ` | None => "" } } else { "" } if !(key->String.startsWith(":")) && !(key->String.startsWith(".")) { modifiedArr->Array.push(class)->ignore } else if key->String.startsWith(":") || key->String.startsWith(".") { puseduoArr->Array.push(class)->ignore } }) ->ignore if classname->String.length == 0 { `${modifiedArr->Array.joinWith(";")} ${puseduoArr->Array.joinWith(" ")}` } else { `.${classname} {${modifiedArr->Array.joinWith(";")}} ${puseduoArr->Array.joinWith(" ")}` } } let generateStyleSheet = (classname, dict, id) => { let createStyle = () => { let style = document["createElement"]("style") style["type"] = "text/css" style["id"] = id style["appendChild"](document["createTextNode"](constructClass(~classname, ~dict)))->ignore document["body"]["appendChild"](style)->ignore } switch Window.window->Window.document->Window.getElementById(id)->Nullable.toOption { | Some(val) => { val->remove createStyle() } | None => createStyle() } } let openUrl = url => { messageParentWindow([("openurl", url->JSON.Encode.string)]) } let getArrofJsonString = (arr: array<string>) => { arr->Array.map(item => item->JSON.Encode.string) } let getPaymentDetails = (arr: array<string>) => { let finalArr = [] arr ->Array.map(item => { let optionalVal = PaymentDetails.details->Array.find(i => i.type_ == item) switch optionalVal { | Some(val) => finalArr->Array.push(val)->ignore | None => () } }) ->ignore finalArr } let getOptionalArr = arr => { switch arr { | Some(val) => val | None => [] } } let checkPriorityList = paymentMethodOrder => { paymentMethodOrder->getOptionalArr->Array.get(0)->Option.getOr("") == "card" || paymentMethodOrder->Option.isNone } type sizeunit = Pixel | Rem | Em let addSize = (str: string, value: float, unit: sizeunit) => { let getUnit = unit => { switch unit { | Pixel => "px" | Rem => "rem" | Em => "em" } } let unitInString = getUnit(unit) if str->String.endsWith(unitInString) { let arr = str->String.split("") let val = arr ->Array.slice(~start=0, ~end={arr->Array.length - unitInString->String.length}) ->Array.joinWith("") ->Float.fromString ->Option.getOr(0.0) (val +. value)->Float.toString ++ unitInString } else { str } } let toInt = val => val->Int.fromString->Option.getOr(0) let validateRountingNumber = str => { if str->String.length != 9 { false } else { let firstWeight = 3 let weights = [firstWeight, 7, 1, 3, 7, 1, 3, 7, 1] let sum = str ->String.split("") ->Array.mapWithIndex((item, i) => item->toInt * weights[i]->Option.getOr(firstWeight)) ->Array.reduce(0, (acc, val) => { acc + val }) mod(sum, 10) == 0 } } let handlePostMessageEvents = ( ~complete, ~empty, ~paymentType, ~loggerState: HyperLogger.loggerMake, ~savedMethod=false, ) => { if complete && paymentType !== "" { let value = "Payment Data Filled" ++ (savedMethod ? ": Saved Payment Method" : ": New Payment Method") loggerState.setLogInfo(~value, ~eventName=PAYMENT_DATA_FILLED, ~paymentMethod=paymentType) } messageParentWindow([ ("elementType", "payment"->JSON.Encode.string), ("complete", complete->JSON.Encode.bool), ("empty", empty->JSON.Encode.bool), ("value", [("type", paymentType->JSON.Encode.string)]->getJsonFromArrayOfJson), ]) } let onlyDigits = str => str->String.replaceRegExp(%re(`/\D/g`), "") let getCountryCode = country => { Country.country ->Array.find(item => item.countryName == country) ->Option.getOr(Country.defaultTimeZone) } let getStateNames = (list: JSON.t, country: RecoilAtomTypes.field) => { let options = list ->getDictFromJson ->getOptionalArrayFromDict(getCountryCode(country.value).isoAlpha2) ->Option.getOr([]) options->Array.reduce([], (arr, item) => { arr ->Array.push( item->getDictFromJson->Dict.get("name")->Option.flatMap(JSON.Decode.string)->Option.getOr(""), ) ->ignore arr }) } let isAddressComplete = ( line1: RecoilAtomTypes.field, city: RecoilAtomTypes.field, postalCode: RecoilAtomTypes.field, country: RecoilAtomTypes.field, state: RecoilAtomTypes.field, ) => line1.value != "" && city.value != "" && postalCode.value != "" && country.value != "" && state.value != "" let deepCopyDict = dict => { let emptyDict = Dict.make() dict ->Dict.toArray ->Array.map(item => { let (key, value) = item emptyDict->Dict.set(key, value) }) ->ignore emptyDict } let snakeToTitleCase = str => { let words = str->String.split("_") words ->Array.map(item => { item->String.charAt(0)->String.toUpperCase ++ item->String.sliceToEnd(~start=1) }) ->Array.joinWith(" ") } let formatIBAN = iban => { let formatted = iban->String.replaceRegExp(%re(`/[^a-zA-Z0-9]/g`), "") let countryCode = formatted->String.substring(~start=0, ~end=2)->String.toUpperCase let codeLastTwo = formatted->String.substring(~start=2, ~end=4) let remaining = formatted->String.substringToEnd(~start=4) let chunks = switch remaining->String.match(%re(`/(.{1,4})/g`)) { | Some(matches) => matches | None => [] } `${countryCode}${codeLastTwo} ${chunks->Array.joinWith(" ")}`->String.trim } let formatBSB = bsb => { let formatted = bsb->String.replaceRegExp(%re("/\D+/g"), "") let firstPart = formatted->String.substring(~start=0, ~end=3) let secondPart = formatted->String.substring(~start=3, ~end=6) if formatted->String.length <= 3 { firstPart } else if formatted->String.length > 3 && formatted->String.length <= 6 { `${firstPart}-${secondPart}` } else { formatted } } let getDictIsSome = (dict, key) => { dict->Dict.get(key)->Option.isSome } let rgbaTorgb = bgColor => { let cleanBgColor = bgColor->String.trim if cleanBgColor->String.startsWith("rgba") || cleanBgColor->String.startsWith("rgb") { let start = cleanBgColor->String.indexOf("(") let end = cleanBgColor->String.indexOf(")") let colorArr = cleanBgColor->String.substring(~start=start + 1, ~end)->String.split(",") if colorArr->Array.length === 3 { cleanBgColor } else { let red = colorArr->Array.get(0)->Option.getOr("0") let green = colorArr->Array.get(1)->Option.getOr("0") let blue = colorArr->Array.get(2)->Option.getOr("0") `rgba(${red}, ${green}, ${blue})` } } else { cleanBgColor } } let delay = timeOut => { Promise.make((resolve, _reject) => { setTimeout(() => { resolve(Dict.make()) }, timeOut)->ignore }) } let getHeaders = (~uri=?, ~token=?, ~headers=Dict.make()) => { let headerObj = [ ("Content-Type", "application/json"), ("X-Client-Version", Window.version), ("X-Payment-Confirm-Source", "sdk"), ("X-Browser-Name", HyperLogger.arrayOfNameAndVersion->Array.get(0)->Option.getOr("Others")), ("X-Browser-Version", HyperLogger.arrayOfNameAndVersion->Array.get(1)->Option.getOr("0")), ("X-Client-Platform", "web"), ]->Dict.fromArray switch (token, uri) { | (Some(tok), Some(_uriVal)) => headerObj->Dict.set("Authorization", tok) | _ => () } Dict.toArray(headers)->Array.forEach(entries => { let (x, val) = entries Dict.set(headerObj, x, val) }) Fetch.Headers.fromObject(headerObj->dictToObj) } let formatException = exc => switch exc { | Exn.Error(obj) => let message = Exn.message(obj) let name = Exn.name(obj) let stack = Exn.stack(obj) let fileName = Exn.fileName(obj) if ( message->Option.isSome || name->Option.isSome || stack->Option.isSome || fileName->Option.isSome ) { [ ("message", message->Option.getOr("Unknown Error")->JSON.Encode.string), ("type", name->Option.getOr("Unknown")->JSON.Encode.string), ("stack", stack->Option.getOr("Unknown")->JSON.Encode.string), ("fileName", fileName->Option.getOr("Unknown")->JSON.Encode.string), ]->getJsonFromArrayOfJson } else { exc->Identity.anyTypeToJson } | _ => exc->Identity.anyTypeToJson } let fetchApi = (uri, ~bodyStr: string="", ~headers=Dict.make(), ~method: Fetch.method) => { open Promise let body = switch method { | #GET => resolve(None) | _ => resolve(Some(Fetch.Body.string(bodyStr))) } body->then(body => { Fetch.fetch( uri, { method, ?body, headers: getHeaders(~headers, ~uri), }, ) ->catch(err => { reject(err) }) ->then(resp => { resolve(resp) }) }) } let arrayJsonToCamelCase = arr => { arr->Array.map(item => { item->transformKeys(CamelCase) }) } let getArrayValFromJsonDict = (dict, key, arrayKey) => { dict ->Dict.get(key) ->Option.flatMap(JSON.Decode.object) ->Option.getOr(Dict.make()) ->Dict.get(arrayKey) ->Option.flatMap(JSON.Decode.array) ->Option.getOr([]) ->Belt.Array.keepMap(JSON.Decode.string) } let isOtherElements = componentType => { componentType == "card" || componentType == "cardNumber" || componentType == "cardExpiry" || componentType == "cardCvc" } let nbsp = `\u00A0` let callbackFuncForExtractingValFromDict = key => { x => x->Dict.get(key) } let brandIconSize = 28 let getClasses = (options, key) => { let classes = options->getDictFromObj("classes") classes->getString(key, "") } let safeParseOpt = st => { try { JSON.parseExn(st)->Some } catch { | _ => None } } let safeParse = st => { safeParseOpt(st)->Option.getOr(JSON.Encode.null) } let getArrayOfTupleFromDict = dict => { dict ->Dict.keysToArray ->Array.map(key => (key, Dict.get(dict, key)->Option.getOr(JSON.Encode.null))) } let getOptionalJsonFromJson = (json, str) => { json->JSON.Decode.object->Option.getOr(Dict.make())->Dict.get(str) } let getStringFromOptionalJson = (json, default) => { json->Option.flatMap(JSON.Decode.string)->Option.getOr(default) } let getBoolFromOptionalJson = (json, default) => { json->Option.flatMap(JSON.Decode.bool)->Option.getOr(default) } let getBoolFromJson = (json, default) => { json->JSON.Decode.bool->Option.getOr(default) } let getOptionalJson = (json, str) => { json ->JSON.Decode.object ->Option.flatMap(x => x->Dict.get("data")) ->Option.getOr(Dict.make()->JSON.Encode.object) ->JSON.Decode.object ->Option.getOr(Dict.make()) ->Dict.get(str) } let rec setNested = (dict, keys, value) => { switch keys[0] { | Some(firstKey) => if keys->Array.length === 1 { Dict.set(dict, firstKey, value) } else { let subDict = switch Dict.get(dict, firstKey) { | Some(json) => switch json->JSON.Decode.object { | Some(obj) => obj | None => dict } | None => let subDict = Dict.make() dict->Dict.set(firstKey, subDict->JSON.Encode.object) subDict } let remainingKeys = keys->Array.sliceToEnd(~start=1) setNested(subDict, remainingKeys, value) } | None => () } } let unflattenObject = obj => { let newDict = Dict.make() switch obj->JSON.Decode.object { | Some(dict) => dict ->Dict.toArray ->Array.forEach(entry => { let (key, value) = entry setNested(newDict, key->String.split("."), value) }) | None => () } newDict } let mergeTwoFlattenedJsonDicts = (dict1, dict2) => [...dict1->Dict.toArray, ...dict2->Dict.toArray]->getJsonFromArrayOfJson->unflattenObject open Identity let rec flattenObject = (obj, addIndicatorForObject) => { let newDict = Dict.make() switch obj->JSON.Decode.object { | Some(obj) => obj ->Dict.toArray ->Array.forEach(entry => { let (key, value) = entry if value->jsonToNullableJson->Js.Nullable.isNullable { Dict.set(newDict, key, value) } else { switch value->JSON.Decode.object { | Some(_valueObj) => { if addIndicatorForObject { Dict.set(newDict, key, JSON.Encode.object(Dict.make())) } let flattenedSubObj = flattenObject(value, addIndicatorForObject) flattenedSubObj ->Dict.toArray ->Array.forEach(subEntry => { let (subKey, subValue) = subEntry Dict.set(newDict, `${key}.${subKey}`, subValue) }) } | None => Dict.set(newDict, key, value) } } }) | _ => () } newDict } let rec flattenObjectWithStringifiedJson = (obj, addIndicatorForObject, keepParent) => { let newDict = Dict.make() switch obj->JSON.Decode.object { | Some(obj) => obj ->Dict.toArray ->Array.forEach(entry => { let (key, value) = entry if value->jsonToNullableJson->Js.Nullable.isNullable { Dict.set(newDict, key, value) } else { switch value->getStringFromJson("")->safeParse->JSON.Decode.object { | Some(_valueObj) => { if addIndicatorForObject { Dict.set(newDict, key, JSON.Encode.object(Dict.make())) } let flattenedSubObj = flattenObjectWithStringifiedJson( value->getStringFromJson("")->safeParse, addIndicatorForObject, keepParent, ) flattenedSubObj ->Dict.toArray ->Array.forEach(subEntry => { let (subKey, subValue) = subEntry let keyN = keepParent ? `${key}.${subKey}` : subKey Dict.set(newDict, keyN, subValue) }) } | None => Dict.set(newDict, key, value) } } }) | _ => () } newDict } let rec flatten = (obj, addIndicatorForObject) => { let newDict = Dict.make() switch obj->JSON.Classify.classify { | Object(obj) => obj ->Dict.toArray ->Array.forEach(entry => { let (key, value) = entry if value->jsonToNullableJson->Js.Nullable.isNullable { Dict.set(newDict, key, value) } else { switch value->JSON.Classify.classify { | Object(_valueObjDict) => { if addIndicatorForObject { Dict.set(newDict, key, JSON.Encode.object(Dict.make())) } let flattenedSubObj = flatten(value, addIndicatorForObject) flattenedSubObj ->Dict.toArray ->Array.forEach(subEntry => { let (subKey, subValue) = subEntry Dict.set(newDict, `${key}.${subKey}`, subValue) }) } | Array(dictArray) => { let stringArray = [] let arrayArray = [] dictArray->Array.forEachWithIndex((item, index) => { switch item->JSON.Classify.classify { | String(_str) => stringArray->Array.push(item) | Object(_obj) => { let flattenedSubObj = flatten(item, addIndicatorForObject) flattenedSubObj ->Dict.toArray ->Array.forEach( subEntry => { let (subKey, subValue) = subEntry Dict.set(newDict, `${key}[${index->Int.toString}].${subKey}`, subValue) }, ) } | _ => arrayArray->Array.push(item) } }) if stringArray->Array.length > 0 { Dict.set(newDict, key, stringArray->JSON.Encode.array) } if arrayArray->Array.length > 0 { Dict.set(newDict, key, arrayArray->JSON.Encode.array) } } | _ => Dict.set(newDict, key, value) } } }) | _ => () } newDict } let eventHandlerFunc = ( condition: Types.event => bool, eventHandler, evType: Types.eventType, activity, ) => { let changeHandler = ev => { if ev->condition { switch evType { | Change | Click | Ready | Focus | CompleteDoThis | ConfirmPayment | OneClickConfirmPayment | Blur => switch eventHandler { | Some(eH) => eH(Some(ev.data)) | None => () } | _ => () } } } EventListenerManager.addSmartEventListener("message", changeHandler, activity) } let makeIframe = (element, url) => { open Types Promise.make((resolve, _) => { let iframe = createElement("iframe") iframe.id = "orca-fullscreen" iframe.src = url iframe.name = "fullscreen" iframe.style = "position: fixed; inset: 0; width: 100vw; height: 100vh; border: 0; z-index: 422222133323; " iframe.onload = () => { resolve(Dict.make()) } element->appendChild(iframe) }) } let makeForm = (element, url, id) => { open Types let form = createElement("form") form.id = id form.name = id form.action = url form.method = "POST" form.enctype = "application/x-www-form-urlencoded;charset=UTF-8" form.style = "display: hidden;" element->appendChild(form) form } let getThemePromise = dict => { let theme = dict ->getJsonObjectFromDict("appearance") ->getDictFromJson ->getString("theme", "default") switch theme { | "default" => None | "brutal" => Some(ThemeImporter.importTheme("../BrutalTheme.bs.js")) | "midnight" => Some(ThemeImporter.importTheme("../MidnightTheme.bs.js")) | "charcoal" => Some(ThemeImporter.importTheme("../CharcoalTheme.bs.js")) | "soft" => Some(ThemeImporter.importTheme("../SoftTheme.bs.js")) | "none" => Some(ThemeImporter.importTheme("../NoTheme.bs.js")) | _ => None } } let makeOneClickHandlerPromise = sdkHandleIsThere => { Promise.make((resolve, _) => { if !sdkHandleIsThere { resolve(JSON.Encode.bool(true)) } else { let handleMessage = (event: Window.event) => { let json = try { event.data->safeParse } catch { | _ => JSON.Encode.null } let dict = json->getDictFromJson if dict->Dict.get("walletClickEvent")->Option.isSome { resolve(dict->Dict.get("walletClickEvent")->Option.getOr(true->JSON.Encode.bool)) } } Window.addEventListener("message", handleMessage) handleOnConfirmPostMessage(~targetOrigin="*", ~isOneClick=true) } }) } let generateRandomString = length => { let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let result = ref("") let charactersLength = characters->String.length Int.range(0, length)->Array.forEach(_ => { let charIndex = mod((Math.random() *. 100.0)->Float.toInt, charactersLength) result := result.contents ++ characters->String.charAt(charIndex) }) result.contents } let getWalletPaymentMethod = (wallets, paymentType: CardThemeType.mode) => { switch paymentType { | GooglePayElement => wallets->Array.filter(item => item === "google_pay") | PayPalElement => wallets->Array.filter(item => item === "paypal") | ApplePayElement => wallets->Array.filter(item => item === "apple_pay") | KlarnaElement => wallets->Array.filter(item => item === "klarna") | PazeElement => wallets->Array.filter(item => item === "paze") | SamsungPayElement => wallets->Array.filter(item => item === "samsung_pay") | _ => wallets } } let expressCheckoutComponents = [ "googlePay", "payPal", "applePay", "klarna", "paze", "samsungPay", "expressCheckout", ] let spmComponents = ["paymentMethodCollect"]->Array.concat(expressCheckoutComponents) let componentsForPaymentElementCreate = ["payment", "paymentMethodCollect", "paymentMethodsManagement"]->Array.concat( expressCheckoutComponents, ) let getIsExpressCheckoutComponent = componentType => { expressCheckoutComponents->Array.includes(componentType) } let getIsComponentTypeForPaymentElementCreate = componentType => { componentsForPaymentElementCreate->Array.includes(componentType) } let walletElementPaymentType: array<CardThemeType.mode> = [ GooglePayElement, PayPalElement, ApplePayElement, SamsungPayElement, KlarnaElement, PazeElement, ExpressCheckoutElement, ] let getIsWalletElementPaymentType = (paymentType: CardThemeType.mode) => { walletElementPaymentType->Array.includes(paymentType) } let getUniqueArray = arr => arr->Array.map(item => (item, ""))->Dict.fromArray->Dict.keysToArray let getStateNameFromStateCodeAndCountry = (list: JSON.t, stateCode: string, country: string) => { let options = list ->getDictFromJson ->getOptionalArrayFromDict(country) options ->Option.flatMap( Array.find(_, item => item ->getDictFromJson ->getString("code", "") === stateCode ), ) ->Option.flatMap(stateObj => stateObj ->getDictFromJson ->getOptionString("name") ) ->Option.getOr(stateCode) } let removeHyphen = str => str->String.replaceRegExp(%re("/-/g"), "") let compareLogic = (a, b) => { if a == b { 0. } else if a > b { -1. } else { 1. } } let currencyNetworksDict = [ ("BTC", ["bitcoin", "bnb_smart_chain"]), ("LTC", ["litecoin", "bnb_smart_chain"]), ("ETH", ["ethereum", "bnb_smart_chain"]), ("XRP", ["ripple", "bnb_smart_chain"]), ("XLM", ["stellar", "bnb_smart_chain"]), ("BCH", ["bitcoin_cash", "bnb_smart_chain"]), ("ADA", ["cardano", "bnb_smart_chain"]), ("SOL", ["solana", "bnb_smart_chain"]), ("SHIB", ["ethereum", "bnb_smart_chain"]), ("TRX", ["tron", "bnb_smart_chain"]), ("DOGE", ["dogecoin", "bnb_smart_chain"]), ("BNB", ["bnb_smart_chain"]), ("USDT", ["ethereum", "tron", "bnb_smart_chain"]), ("USDC", ["ethereum", "tron", "bnb_smart_chain"]), ("DAI", ["ethereum", "bnb_smart_chain"]), ]->Dict.fromArray let toSpacedUpperCase = (~str, ~delimiter) => str ->String.toUpperCase ->String.split(delimiter) ->Array.joinWith(" ") let handleFailureResponse = (~message, ~errorType) => [ ( "error", [ ("type", errorType->JSON.Encode.string), ("message", message->JSON.Encode.string), ]->getJsonFromArrayOfJson, ), ]->getJsonFromArrayOfJson let getPaymentId = clientSecret => String.split(clientSecret, "_secret_")->Array.get(0)->Option.getOr("") let checkIs18OrAbove = dateOfBirth => { let currentDate = Date.make() let year = currentDate->Date.getFullYear - 18 let month = currentDate->Date.getMonth let date = currentDate->Date.getDate let compareDate = Date.makeWithYMD(~year, ~month, ~date) dateOfBirth <= compareDate } let getFirstAndLastNameFromFullName = fullName => { let nameStrings = fullName->String.split(" ") let firstName = nameStrings ->Array.get(0) ->Option.flatMap(x => Some(x->JSON.Encode.string)) ->Option.getOr(JSON.Encode.null) let lastNameStr = nameStrings->Array.sliceToEnd(~start=1)->Array.joinWith(" ")->String.trim let lastNameJson = lastNameStr === "" ? JSON.Encode.null : lastNameStr->JSON.Encode.string (firstName, lastNameJson) } let isKeyPresentInDict = (dict, key) => dict->Dict.get(key)->Option.isSome let minorUnitToString = val => (val->Int.toFloat /. 100.)->Float.toString let mergeAndFlattenToTuples = (body, requiredFieldsBody) => body ->getJsonFromArrayOfJson ->flattenObject(true) ->mergeTwoFlattenedJsonDicts(requiredFieldsBody) ->getArrayOfTupleFromDict let handleIframePostMessageForWallets = (msg, componentName, mountedIframeRef) => { let isMessageSent = ref(false) let iframes = Window.querySelectorAll("iframe") iframes->Array.forEach(iframe => { let iframeSrc = iframe->Window.getAttribute("src")->Nullable.toOption->Option.getOr("") if iframeSrc->String.includes(`componentName=${componentName}`) { iframe->Js.Nullable.return->Window.iframePostMessage(msg) isMessageSent := true } }) if !isMessageSent.contents { mountedIframeRef->Window.iframePostMessage(msg) } } let isDigitLimitExceeded = (val, ~digit) => { switch val->String.match(%re("/\d/g")) { | Some(matches) => matches->Array.length > digit | None => false } } /* Redirect Handling */ let replaceRootHref = (href: string, redirectionFlags: RecoilAtomTypes.redirectionFlags) => { if redirectionFlags.shouldRemoveBeforeUnloadEvents { handleBeforeRedirectPostMessage() } switch redirectionFlags.shouldUseTopRedirection { | true => try { setTimeout(() => { Window.Top.Location.replace(href) }, 100)->ignore } catch { | e => { Console.error3( "Failed to redirect root document", e, `Using [window.location.replace] for redirection`, ) Window.Location.replace(href) } } | false => Window.Location.replace(href) } } let isValidHexColor = (color: string): bool => { let hexRegex = %re("/^#([0-9a-f]{6}|[0-9a-f]{3})$/i") Js.Re.test_(hexRegex, color) }
11,031
10,541
hyperswitch-web
src/Utilities/DynamicFieldsUtils.res
.res
open RecoilAtoms let dynamicFieldsEnabledPaymentMethods = [ "crypto_currency", "debit", "credit", "blik", "google_pay", "apple_pay", "bancontact_card", "open_banking_uk", "eps", "ideal", "sofort", "pix_transfer", "giropay", "local_bank_transfer_transfer", "afterpay_clearpay", "mifinity", "upi_collect", "sepa", "sepa_bank_transfer", "instant_bank_transfer", "affirm", "walley", "ach", "bacs", "pay_bright", "multibanco_transfer", "paypal", ] let getName = (item: PaymentMethodsRecord.required_fields, field: RecoilAtomTypes.field) => { let fieldNameArr = field.value->String.split(" ") let requiredFieldsArr = item.required_field->String.split(".") switch requiredFieldsArr->Array.get(requiredFieldsArr->Array.length - 1)->Option.getOr("") { | "first_name" => fieldNameArr->Array.get(0)->Option.getOr(field.value) | "last_name" => fieldNameArr ->Array.sliceToEnd(~start=1) ->Array.reduce("", (acc, item) => acc === "" ? item : `${acc} ${item}`) | _ => field.value } } let countryNames = Utils.getCountryNames(Country.country) let billingAddressFields: array<PaymentMethodsRecord.paymentMethodsFields> = [ BillingName, AddressLine1, AddressLine2, AddressCity, AddressState, AddressCountry(countryNames), AddressPincode, ] let isBillingAddressFieldType = (fieldType: PaymentMethodsRecord.paymentMethodsFields) => { switch fieldType { | BillingName | AddressLine1 | AddressLine2 | AddressCity | AddressState | AddressCountry(_) | AddressPincode => true | _ => false } } let getBillingAddressPathFromFieldType = (fieldType: PaymentMethodsRecord.paymentMethodsFields) => { switch fieldType { | AddressLine1 => "payment_method_data.billing.address.line1" | AddressLine2 => "payment_method_data.billing.address.line2" | AddressCity => "payment_method_data.billing.address.city" | AddressState => "payment_method_data.billing.address.state" | AddressCountry(_) => "payment_method_data.billing.address.country" | AddressPincode => "payment_method_data.billing.address.zip" | _ => "" } } let removeBillingDetailsIfUseBillingAddress = ( requiredFields: array<PaymentMethodsRecord.required_fields>, billingAddress: PaymentType.billingAddress, ) => { if billingAddress.isUseBillingAddress { requiredFields->Array.filter(requiredField => { !(requiredField.field_type->isBillingAddressFieldType) }) } else { requiredFields } } let addBillingAddressIfUseBillingAddress = ( fieldsArr, billingAddress: PaymentType.billingAddress, ) => { if billingAddress.isUseBillingAddress { fieldsArr->Array.concat(billingAddressFields) } else { fieldsArr } } let clickToPayFields: array<PaymentMethodsRecord.paymentMethodsFields> = [Email, PhoneNumber] let isClickToPayFieldType = (fieldType: PaymentMethodsRecord.paymentMethodsFields) => { switch fieldType { | Email | PhoneNumber => true | _ => false } } let removeClickToPayFieldsIfSaveDetailsWithClickToPay = ( requiredFields: array<PaymentMethodsRecord.required_fields>, isSaveDetailsWithClickToPay, ) => { if isSaveDetailsWithClickToPay { requiredFields->Array.filter(requiredField => { !(requiredField.field_type->isClickToPayFieldType) }) } else { requiredFields } } let addClickToPayFieldsIfSaveDetailsWithClickToPay = (fieldsArr, isSaveDetailsWithClickToPay) => { if isSaveDetailsWithClickToPay { [...fieldsArr, ...clickToPayFields] } else { fieldsArr } } let checkIfNameIsValid = ( requiredFieldsType: array<PaymentMethodsRecord.required_fields>, paymentMethodFields, field: RecoilAtomTypes.field, ) => { requiredFieldsType ->Array.filter(required_field => required_field.field_type === paymentMethodFields) ->Array.reduce(true, (acc, item) => { let fieldNameArr = field.value->String.split(" ") let requiredFieldsArr = item.required_field->String.split(".") let fieldValue = switch requiredFieldsArr ->Array.get(requiredFieldsArr->Array.length - 1) ->Option.getOr("") { | "first_name" => fieldNameArr->Array.get(0)->Option.getOr("") | "last_name" => fieldNameArr->Array.get(1)->Option.getOr("") | _ => field.value } acc && fieldValue !== "" }) } let useRequiredFieldsEmptyAndValid = ( ~requiredFields, ~fieldsArr: array<PaymentMethodsRecord.paymentMethodsFields>, ~countryNames, ~bankNames, ~isCardValid, ~isExpiryValid, ~isCVCValid, ~cardNumber, ~cardExpiry, ~cvcNumber, ~isSavedCardFlow, ) => { let email = Recoil.useRecoilValueFromAtom(userEmailAddress) let vpaId = Recoil.useRecoilValueFromAtom(userVpaId) let pixCNPJ = Recoil.useRecoilValueFromAtom(userPixCNPJ) let pixCPF = Recoil.useRecoilValueFromAtom(userPixCPF) let pixKey = Recoil.useRecoilValueFromAtom(userPixKey) let fullName = Recoil.useRecoilValueFromAtom(userFullName) let billingName = Recoil.useRecoilValueFromAtom(userBillingName) let line1 = Recoil.useRecoilValueFromAtom(userAddressline1) let line2 = Recoil.useRecoilValueFromAtom(userAddressline2) let phone = Recoil.useRecoilValueFromAtom(userPhoneNumber) let state = Recoil.useRecoilValueFromAtom(userAddressState) let city = Recoil.useRecoilValueFromAtom(userAddressCity) let postalCode = Recoil.useRecoilValueFromAtom(userAddressPincode) let blikCode = Recoil.useRecoilValueFromAtom(userBlikCode) let country = Recoil.useRecoilValueFromAtom(userCountry) let selectedBank = Recoil.useRecoilValueFromAtom(userBank) let currency = Recoil.useRecoilValueFromAtom(userCurrency) let (areRequiredFieldsValid, setAreRequiredFieldsValid) = Recoil.useRecoilState( areRequiredFieldsValid, ) let setAreRequiredFieldsEmpty = Recoil.useSetRecoilState(areRequiredFieldsEmpty) let {billingAddress} = Recoil.useRecoilValueFromAtom(optionAtom) let cryptoCurrencyNetworks = Recoil.useRecoilValueFromAtom(cryptoCurrencyNetworks) let dateOfBirth = Recoil.useRecoilValueFromAtom(dateOfBirth) let bankAccountNumber = Recoil.useRecoilValueFromAtom(userBankAccountNumber) let fieldsArrWithBillingAddress = fieldsArr->addBillingAddressIfUseBillingAddress(billingAddress) React.useEffect(() => { let areRequiredFieldsValid = fieldsArr->Array.reduce(true, (acc, paymentMethodFields) => { acc && switch paymentMethodFields { | Email => email.isValid->Option.getOr(false) | FullName => checkIfNameIsValid(requiredFields, paymentMethodFields, fullName) && fullName.isValid->Option.getOr(false) | Country => country !== "" || countryNames->Array.length === 0 | AddressCountry(countryArr) => country !== "" || countryArr->Array.length === 0 | BillingName => checkIfNameIsValid(requiredFields, paymentMethodFields, billingName) | AddressLine1 => line1.value !== "" | AddressLine2 => billingAddress.isUseBillingAddress || line2.value !== "" | Bank => selectedBank !== "" || bankNames->Array.length === 0 | PhoneNumber => phone.value !== "" | StateAndCity => state.value !== "" && city.value !== "" | CountryAndPincode(countryArr) => (country !== "" || countryArr->Array.length === 0) && postalCode.value !== "" | AddressCity => city.value !== "" | AddressPincode => postalCode.value !== "" | AddressState => state.value !== "" | BlikCode => blikCode.value !== "" | CryptoCurrencyNetworks => cryptoCurrencyNetworks !== "" | Currency(currencyArr) => currency !== "" || currencyArr->Array.length === 0 | CardNumber => isCardValid->Option.getOr(false) | CardExpiryMonth | CardExpiryYear | CardExpiryMonthAndYear => isExpiryValid->Option.getOr(false) | CardCvc => isCVCValid->Option.getOr(false) | CardExpiryAndCvc => isExpiryValid->Option.getOr(false) && isCVCValid->Option.getOr(false) | DateOfBirth => switch dateOfBirth->Nullable.toOption { | Some(val) => val->Utils.checkIs18OrAbove | None => false } | VpaId => vpaId.isValid->Option.getOr(false) | PixCNPJ => pixCNPJ.isValid->Option.getOr(false) | PixCPF => pixCPF.isValid->Option.getOr(false) | PixKey => pixKey.isValid->Option.getOr(false) | BankAccountNumber | IBAN => bankAccountNumber.value !== "" | _ => true } }) setAreRequiredFieldsValid(_ => isSavedCardFlow || areRequiredFieldsValid) let areRequiredFieldsEmpty = fieldsArrWithBillingAddress->Array.reduce(false, ( acc, paymentMethodFields: PaymentMethodsRecord.paymentMethodsFields, ) => { open CardUtils acc || switch paymentMethodFields { | Email => email.value === "" | FullName => fullName.value === "" | Country => country === "" && countryNames->Array.length > 0 | AddressCountry(countryArr) => country === "" && countryArr->Array.length > 0 | BillingName => billingName.value === "" | AddressLine1 => line1.value === "" | AddressLine2 => !billingAddress.isUseBillingAddress && line2.value === "" | Bank => selectedBank === "" && bankNames->Array.length > 0 | StateAndCity => city.value === "" || state.value === "" | CountryAndPincode(countryArr) => (country === "" && countryArr->Array.length > 0) || postalCode.value === "" | PhoneNumber => phone.value === "" | AddressCity => city.value === "" | AddressPincode => postalCode.value === "" | AddressState => state.value === "" | BlikCode => blikCode.value === "" | PixCNPJ => pixCNPJ.value === "" | PixCPF => pixCPF.value === "" | PixKey => pixKey.value === "" | CryptoCurrencyNetworks => cryptoCurrencyNetworks === "" | Currency(currencyArr) => currency === "" && currencyArr->Array.length > 0 | CardNumber => cardNumber === "" | CardExpiryMonth => let (month, _) = getExpiryDates(cardExpiry) month === "" | CardExpiryYear => let (_, year) = getExpiryDates(cardExpiry) year === "" | CardExpiryMonthAndYear => let (month, year) = getExpiryDates(cardExpiry) month === "" || year === "" | CardCvc => cvcNumber === "" | CardExpiryAndCvc => let (month, year) = getExpiryDates(cardExpiry) month === "" || year === "" || cvcNumber === "" | DateOfBirth => dateOfBirth->Js.Nullable.isNullable | BankAccountNumber | IBAN => bankAccountNumber.value === "" | _ => false } }) setAreRequiredFieldsEmpty(_ => areRequiredFieldsEmpty) None }, ( fieldsArr, currency, fullName.value, country, billingName.value, line1.value, dateOfBirth, email, vpaId, line2.value, selectedBank, phone.value, city.value, postalCode, state.value, blikCode.value, pixCNPJ.value, pixKey.value, pixCPF.value, isCardValid, isExpiryValid, isCVCValid, cardNumber, cardExpiry, cvcNumber, bankAccountNumber, cryptoCurrencyNetworks, )) React.useEffect(() => { switch (isCardValid, isExpiryValid, isCVCValid) { | (Some(cardValid), Some(expiryValid), Some(cvcValid)) => CardUtils.emitIsFormReadyForSubmission( cardValid && expiryValid && cvcValid && areRequiredFieldsValid, ) | _ => () } None }, (isCardValid, isExpiryValid, isCVCValid, areRequiredFieldsValid)) } let useSetInitialRequiredFields = ( ~requiredFields: array<PaymentMethodsRecord.required_fields>, ~paymentMethodType, ) => { let logger = Recoil.useRecoilValueFromAtom(loggerAtom) let (email, setEmail) = Recoil.useLoggedRecoilState(userEmailAddress, "email", logger) let (fullName, setFullName) = Recoil.useLoggedRecoilState(userFullName, "fullName", logger) let (billingName, setBillingName) = Recoil.useLoggedRecoilState( userBillingName, "billingName", logger, ) let (line1, setLine1) = Recoil.useLoggedRecoilState(userAddressline1, "line1", logger) let (line2, setLine2) = Recoil.useLoggedRecoilState(userAddressline2, "line2", logger) let (phone, setPhone) = Recoil.useLoggedRecoilState(userPhoneNumber, "phone", logger) let (state, setState) = Recoil.useLoggedRecoilState(userAddressState, "state", logger) let (city, setCity) = Recoil.useLoggedRecoilState(userAddressCity, "city", logger) let (postalCode, setPostalCode) = Recoil.useLoggedRecoilState( userAddressPincode, "postal_code", logger, ) let (blikCode, setBlikCode) = Recoil.useLoggedRecoilState(userBlikCode, "blikCode", logger) let (pixCNPJ, setPixCNPJ) = Recoil.useLoggedRecoilState(userPixCNPJ, "pixCNPJ", logger) let (pixCPF, setPixCPF) = Recoil.useLoggedRecoilState(userPixCPF, "pixCPF", logger) let (pixKey, setPixKey) = Recoil.useLoggedRecoilState(userPixKey, "pixKey", logger) let (country, setCountry) = Recoil.useLoggedRecoilState(userCountry, "country", logger) let (selectedBank, setSelectedBank) = Recoil.useLoggedRecoilState( userBank, "selectedBank", logger, ) let (currency, setCurrency) = Recoil.useLoggedRecoilState(userCurrency, "currency", logger) let (cryptoCurrencyNetworks, setCryptoCurrencyNetworks) = Recoil.useRecoilState( cryptoCurrencyNetworks, ) let (dateOfBirth, setDateOfBirth) = Recoil.useLoggedRecoilState( dateOfBirth, "dateOfBirth", logger, ) let (bankAccountNumber, setBankAccountNumber) = Recoil.useLoggedRecoilState( userBankAccountNumber, "bankAccountNumber", logger, ) React.useEffect(() => { let getNameValue = (item: PaymentMethodsRecord.required_fields) => { requiredFields ->Array.filter(requiredFields => requiredFields.field_type === item.field_type) ->Array.reduce("", (acc, item) => { let requiredFieldsArr = item.required_field->String.split(".") switch requiredFieldsArr->Array.get(requiredFieldsArr->Array.length - 1)->Option.getOr("") { | "first_name" => item.value->String.concat(acc) | "last_name" => acc->String.concatMany([" ", item.value]) | _ => acc } }) ->String.trim } let setFields = ( setMethod: (RecoilAtomTypes.field => RecoilAtomTypes.field) => unit, field: RecoilAtomTypes.field, item: PaymentMethodsRecord.required_fields, isNameField, ~isCountryCodeAvailable=?, ) => { if isNameField && field.value === "" { if isCountryCodeAvailable->Option.isSome { setMethod(prev => { ...prev, countryCode: getNameValue(item), }) } else { setMethod(prev => { ...prev, value: getNameValue(item), }) } } else if field.value === "" { if isCountryCodeAvailable->Option.isSome { setMethod(prev => { ...prev, countryCode: item.value, }) } else { setMethod(prev => { ...prev, value: item.value, }) } } } requiredFields->Array.forEach(requiredField => { let value = requiredField.value switch requiredField.field_type { | Email => { let emailValue = email.value setFields(setEmail, email, requiredField, false) if emailValue === "" { let newEmail: RecoilAtomTypes.field = { value, isValid: None, errorString: "", } Utils.checkEmailValid(newEmail, setEmail) } } | FullName => setFields(setFullName, fullName, requiredField, true) | AddressLine1 => setFields(setLine1, line1, requiredField, false) | AddressLine2 => setFields(setLine2, line2, requiredField, false) | StateAndCity => { setFields(setState, state, requiredField, false) setFields(setCity, city, requiredField, false) } | CountryAndPincode(_) => { setFields(setPostalCode, postalCode, requiredField, false) if value !== "" && country === "" { let countryCode = Country.getCountry(paymentMethodType) ->Array.filter(item => item.isoAlpha2 === value) ->Array.get(0) ->Option.getOr(Country.defaultTimeZone) setCountry(_ => countryCode.countryName) } } | AddressState => setFields(setState, state, requiredField, false) | AddressCity => setFields(setCity, city, requiredField, false) | PhoneCountryCode => setFields(setPhone, phone, requiredField, false, ~isCountryCodeAvailable=true) | AddressPincode => setFields(setPostalCode, postalCode, requiredField, false) | PhoneNumber => setFields(setPhone, phone, requiredField, false) | BlikCode => setFields(setBlikCode, blikCode, requiredField, false) | PixKey => setFields(setPixKey, pixKey, requiredField, false) | PixCNPJ => setFields(setPixCNPJ, pixCNPJ, requiredField, false) | PixCPF => setFields(setPixCPF, pixCPF, requiredField, false) | BillingName => setFields(setBillingName, billingName, requiredField, true) | Country | AddressCountry(_) => if value !== "" { let defaultCountry = Country.getCountry(paymentMethodType) ->Array.filter(item => item.isoAlpha2 === value) ->Array.get(0) ->Option.getOr(Country.defaultTimeZone) setCountry(_ => defaultCountry.countryName) } | Currency(_) => if value !== "" && currency === "" { setCurrency(_ => value) } | Bank => if value !== "" && selectedBank === "" { setSelectedBank(_ => value) } | CryptoCurrencyNetworks => if value !== "" && cryptoCurrencyNetworks === "" { setCryptoCurrencyNetworks(_ => value) } | DateOfBirth => switch dateOfBirth->Nullable.toOption { | Some(x) => if value !== "" && x->Date.toDateString === "" { setDateOfBirth(_ => Nullable.make(x)) } | None => () } | IBAN | BankAccountNumber => setFields(setBankAccountNumber, bankAccountNumber, requiredField, false) | LanguagePreference(_) | SpecialField(_) | InfoElement | CardNumber | CardExpiryMonth | CardExpiryYear | CardExpiryMonthAndYear | CardCvc | CardExpiryAndCvc | ShippingName // Shipping Details are currently supported by only one click widgets | ShippingAddressLine1 | ShippingAddressLine2 | ShippingAddressCity | ShippingAddressPincode | ShippingAddressState | ShippingAddressCountry(_) | VpaId | None => () } }) None }, [requiredFields]) } let useRequiredFieldsBody = ( ~requiredFields: array<PaymentMethodsRecord.required_fields>, ~paymentMethodType, ~cardNumber, ~cardExpiry, ~cvcNumber, ~isSavedCardFlow, ~isAllStoredCardsHaveName, ~setRequiredFieldsBody, ) => { let configValue = Recoil.useRecoilValueFromAtom(configAtom) let email = Recoil.useRecoilValueFromAtom(userEmailAddress) let vpaId = Recoil.useRecoilValueFromAtom(userVpaId) let pixCNPJ = Recoil.useRecoilValueFromAtom(userPixCNPJ) let pixCPF = Recoil.useRecoilValueFromAtom(userPixCPF) let pixKey = Recoil.useRecoilValueFromAtom(userPixKey) let fullName = Recoil.useRecoilValueFromAtom(userFullName) let billingName = Recoil.useRecoilValueFromAtom(userBillingName) let line1 = Recoil.useRecoilValueFromAtom(userAddressline1) let line2 = Recoil.useRecoilValueFromAtom(userAddressline2) let phone = Recoil.useRecoilValueFromAtom(userPhoneNumber) let state = Recoil.useRecoilValueFromAtom(userAddressState) let city = Recoil.useRecoilValueFromAtom(userAddressCity) let postalCode = Recoil.useRecoilValueFromAtom(userAddressPincode) let blikCode = Recoil.useRecoilValueFromAtom(userBlikCode) let country = Recoil.useRecoilValueFromAtom(userCountry) let selectedBank = Recoil.useRecoilValueFromAtom(userBank) let currency = Recoil.useRecoilValueFromAtom(userCurrency) let {billingAddress} = Recoil.useRecoilValueFromAtom(optionAtom) let cryptoCurrencyNetworks = Recoil.useRecoilValueFromAtom(cryptoCurrencyNetworks) let dateOfBirth = Recoil.useRecoilValueFromAtom(dateOfBirth) let bankAccountNumber = Recoil.useRecoilValueFromAtom(userBankAccountNumber) let getFieldValueFromFieldType = (fieldType: PaymentMethodsRecord.paymentMethodsFields) => { switch fieldType { | Email => email.value | AddressLine1 => line1.value | AddressLine2 => line2.value | AddressCity => city.value | AddressPincode => postalCode.value | AddressState => state.value | BlikCode => blikCode.value->Utils.removeHyphen | PhoneNumber => phone.value | PhoneCountryCode => phone.countryCode->Option.getOr("") | Currency(_) => currency | Country => country | LanguagePreference(languageOptions) => languageOptions->Array.includes( configValue.config.locale->String.toUpperCase->String.split("-")->Array.joinWith("_"), ) ? configValue.config.locale : "en" | Bank => ( Bank.getBanks(paymentMethodType) ->Array.find(item => item.displayName == selectedBank) ->Option.getOr(Bank.defaultBank) ).hyperSwitch | AddressCountry(_) => { let countryCode = Country.getCountry(paymentMethodType) ->Array.filter(item => item.countryName === country) ->Array.get(0) ->Option.getOr(Country.defaultTimeZone) countryCode.isoAlpha2 } | BillingName => billingName.value | CardNumber => cardNumber->CardUtils.clearSpaces | CardExpiryMonth => let (month, _) = CardUtils.getExpiryDates(cardExpiry) month | CardExpiryYear => let (_, year) = CardUtils.getExpiryDates(cardExpiry) year | CryptoCurrencyNetworks => cryptoCurrencyNetworks | DateOfBirth => switch dateOfBirth->Nullable.toOption { | Some(x) => x->Date.toISOString->String.slice(~start=0, ~end=10) | None => "" } | CardCvc => cvcNumber | VpaId => vpaId.value | PixCNPJ => pixCNPJ.value | PixCPF => pixCPF.value | PixKey => pixKey.value | IBAN | BankAccountNumber => bankAccountNumber.value | StateAndCity | CountryAndPincode(_) | SpecialField(_) | InfoElement | CardExpiryMonthAndYear | CardExpiryAndCvc | FullName | ShippingName // Shipping Details are currently supported by only one click widgets | ShippingAddressLine1 | ShippingAddressLine2 | ShippingAddressCity | ShippingAddressPincode | ShippingAddressState | ShippingAddressCountry(_) | None => "" } } let addBillingDetailsIfUseBillingAddress = requiredFieldsBody => { if billingAddress.isUseBillingAddress { billingAddressFields->Array.reduce(requiredFieldsBody, (acc, item) => { let value = item->getFieldValueFromFieldType if item === BillingName { let arr = value->String.split(" ") acc->Dict.set( "payment_method_data.billing.address.first_name", arr->Array.get(0)->Option.getOr("")->JSON.Encode.string, ) acc->Dict.set( "payment_method_data.billing.address.last_name", arr->Array.get(1)->Option.getOr("")->JSON.Encode.string, ) } else { let path = item->getBillingAddressPathFromFieldType acc->Dict.set(path, value->JSON.Encode.string) } acc }) } else { requiredFieldsBody } } React.useEffect(() => { let requiredFieldsBody = requiredFields ->Array.filter(item => item.field_type !== None) ->Array.reduce(Dict.make(), (acc, item) => { let value = switch item.field_type { | BillingName => getName(item, billingName) | FullName => getName(item, fullName) | _ => item.field_type->getFieldValueFromFieldType } if value != "" { if ( isSavedCardFlow && (item.field_type === BillingName || item.field_type === FullName) && item.display_name === "card_holder_name" && item.required_field === "payment_method_data.card.card_holder_name" ) { if !isAllStoredCardsHaveName { acc->Dict.set( "payment_method_data.card_token.card_holder_name", value->JSON.Encode.string, ) } } else { acc->Dict.set(item.required_field, value->JSON.Encode.string) } } acc }) ->addBillingDetailsIfUseBillingAddress setRequiredFieldsBody(_ => requiredFieldsBody) None }, ( fullName.value, email.value, vpaId.value, line1.value, line2.value, pixCNPJ.value, pixCPF.value, pixKey.value, city.value, postalCode.value, state.value, blikCode.value, phone.value, phone.countryCode, currency, billingName.value, country, cardNumber, cardExpiry, cvcNumber, selectedBank, cryptoCurrencyNetworks, dateOfBirth, bankAccountNumber, )) } let isFieldTypeToRenderOutsideBilling = (fieldType: PaymentMethodsRecord.paymentMethodsFields) => { switch fieldType { | FullName | CardNumber | CardExpiryMonth | CardExpiryYear | CardExpiryMonthAndYear | CardCvc | CardExpiryAndCvc | CryptoCurrencyNetworks | PixKey | PixCPF | PixCNPJ | DateOfBirth | Currency(_) | VpaId | IBAN | BankAccountNumber => true | _ => false } } let combineStateAndCity = arr => { open PaymentMethodsRecord let hasStateAndCity = arr->Array.includes(AddressState) && arr->Array.includes(AddressCity) if hasStateAndCity { arr->Array.push(StateAndCity)->ignore arr->Array.filter(item => switch item { | AddressCity | AddressState => false | _ => true } ) } else { arr } } let combineCountryAndPostal = arr => { open PaymentMethodsRecord let hasCountryAndPostal = arr ->Array.filter(item => switch item { | AddressCountry(_) => true | AddressPincode => true | _ => false } ) ->Array.length == 2 let options = arr->Array.reduce([], (acc, item) => { acc->Array.concat( switch item { | AddressCountry(val) => val | _ => [] }, ) }) if hasCountryAndPostal { arr->Array.push(CountryAndPincode(options))->ignore arr->Array.filter(item => switch item { | AddressPincode | AddressCountry(_) => false | _ => true } ) } else { arr } } let combineCardExpiryMonthAndYear = arr => { open PaymentMethodsRecord let hasCardExpiryMonthAndYear = arr->Array.includes(CardExpiryMonth) && arr->Array.includes(CardExpiryYear) if hasCardExpiryMonthAndYear { arr->Array.push(CardExpiryMonthAndYear)->ignore arr->Array.filter(item => switch item { | CardExpiryMonth | CardExpiryYear => false | _ => true } ) } else { arr } } let combineCardExpiryAndCvc = arr => { open PaymentMethodsRecord let hasCardExpiryAndCvc = arr->Array.includes(CardExpiryMonthAndYear) && arr->Array.includes(CardCvc) if hasCardExpiryAndCvc { arr->Array.push(CardExpiryAndCvc)->ignore arr->Array.filter(item => switch item { | CardExpiryMonthAndYear | CardCvc => false | _ => true } ) } else { arr } } let updateDynamicFields = ( arr: array<PaymentMethodsRecord.paymentMethodsFields>, billingAddress, isSaveDetailsWithClickToPay, ) => { arr ->Utils.removeDuplicate ->Array.filter(item => item !== None) ->addBillingAddressIfUseBillingAddress(billingAddress) ->addClickToPayFieldsIfSaveDetailsWithClickToPay(isSaveDetailsWithClickToPay) ->combineStateAndCity ->combineCountryAndPostal ->combineCardExpiryMonthAndYear ->combineCardExpiryAndCvc } let useSubmitCallback = () => { let logger = Recoil.useRecoilValueFromAtom(loggerAtom) let (line1, setLine1) = Recoil.useLoggedRecoilState(userAddressline1, "line1", logger) let (line2, setLine2) = Recoil.useLoggedRecoilState(userAddressline2, "line2", logger) let (state, setState) = Recoil.useLoggedRecoilState(userAddressState, "state", logger) let (postalCode, setPostalCode) = Recoil.useLoggedRecoilState( userAddressPincode, "postal_code", logger, ) let (city, setCity) = Recoil.useLoggedRecoilState(userAddressCity, "city", logger) let {billingAddress} = Recoil.useRecoilValueFromAtom(optionAtom) let {localeString} = Recoil.useRecoilValueFromAtom(configAtom) React.useCallback((ev: Window.event) => { let json = ev.data->Utils.safeParse let confirm = json->Utils.getDictFromJson->ConfirmType.itemToObjMapper if confirm.doSubmit { if line1.value == "" { setLine1(prev => { ...prev, errorString: localeString.line1EmptyText, }) } if line2.value == "" { setLine2(prev => { ...prev, errorString: billingAddress.isUseBillingAddress ? "" : localeString.line2EmptyText, }) } if state.value == "" { setState(prev => { ...prev, errorString: localeString.stateEmptyText, }) } if postalCode.value == "" { setPostalCode(prev => { ...prev, errorString: localeString.postalCodeEmptyText, }) } if city.value == "" { setCity(prev => { ...prev, errorString: localeString.cityEmptyText, }) } } }, (line1, line2, state, city, postalCode)) } let usePaymentMethodTypeFromList = ( ~paymentMethodListValue, ~paymentMethod, ~paymentMethodType, ) => { React.useMemo(() => { PaymentMethodsRecord.getPaymentMethodTypeFromList( ~paymentMethodListValue, ~paymentMethod, ~paymentMethodType=PaymentUtils.getPaymentMethodName( ~paymentMethodType=paymentMethod, ~paymentMethodName=paymentMethodType, ), )->Option.getOr(PaymentMethodsRecord.defaultPaymentMethodType) }, (paymentMethodListValue, paymentMethod, paymentMethodType)) } let removeRequiredFieldsDuplicates = ( requiredFields: array<PaymentMethodsRecord.required_fields>, ) => { let (_, requiredFields) = requiredFields->Array.reduce(([], []), ( (requiredFieldKeys, uniqueRequiredFields), item, ) => { let requiredField = item.required_field if requiredFieldKeys->Array.includes(requiredField)->not { requiredFieldKeys->Array.push(requiredField) uniqueRequiredFields->Array.push(item) } (requiredFieldKeys, uniqueRequiredFields) }) requiredFields } let getNameFromString = (name, requiredFieldsArr) => { let nameArr = name->String.split(" ") let nameArrLength = nameArr->Array.length switch requiredFieldsArr->Array.get(requiredFieldsArr->Array.length - 1)->Option.getOr("") { | "first_name" => { let end = nameArrLength === 1 ? nameArrLength : nameArrLength - 1 nameArr ->Array.slice(~start=0, ~end) ->Array.reduce("", (acc, item) => { acc ++ " " ++ item }) } | "last_name" => if nameArrLength === 1 { "" } else { nameArr->Array.get(nameArrLength - 1)->Option.getOr(name) } | _ => name }->String.trim } let getNameFromFirstAndLastName = (~firstName, ~lastName, ~requiredFieldsArr) => { switch requiredFieldsArr->Array.get(requiredFieldsArr->Array.length - 1)->Option.getOr("") { | "first_name" => firstName | "last_name" => lastName | _ => firstName->String.concatMany([" ", lastName]) }->String.trim } let defaultRequiredFieldsArray: array<PaymentMethodsRecord.required_fields> = [ { required_field: "email", display_name: "email", field_type: Email, value: "", }, { required_field: "payment_method_data.billing.address.state", display_name: "state", field_type: AddressState, value: "", }, { required_field: "payment_method_data.billing.address.first_name", display_name: "billing_first_name", field_type: BillingName, value: "", }, { required_field: "payment_method_data.billing.address.city", display_name: "city", field_type: AddressCity, value: "", }, { required_field: "payment_method_data.billing.address.country", display_name: "country", field_type: AddressCountry(["ALL"]), value: "", }, { required_field: "payment_method_data.billing.address.line1", display_name: "line", field_type: AddressLine1, value: "", }, { required_field: "payment_method_data.billing.address.zip", display_name: "zip", field_type: AddressPincode, value: "", }, { required_field: "payment_method_data.billing.address.last_name", display_name: "billing_last_name", field_type: BillingName, value: "", }, ] let getApplePayRequiredFields = ( ~billingContact: ApplePayTypes.billingContact, ~shippingContact: ApplePayTypes.shippingContact, ~requiredFields=defaultRequiredFieldsArray, ~statesList, ) => { requiredFields->Array.reduce(Dict.make(), (acc, item) => { let requiredFieldsArr = item.required_field->String.split(".") let getName = (firstName, lastName) => { switch requiredFieldsArr->Array.get(requiredFieldsArr->Array.length - 1)->Option.getOr("") { | "first_name" => firstName | "last_name" => lastName | _ => firstName->String.concatMany([" ", lastName]) }->String.trim } let getAddressLine = (addressLines, index) => { addressLines->Array.get(index)->Option.getOr("") } let billingCountryCode = billingContact.countryCode->String.toUpperCase let shippingCountryCode = shippingContact.countryCode->String.toUpperCase let fieldVal = switch item.field_type { | FullName | BillingName => getNameFromFirstAndLastName( ~firstName=billingContact.givenName, ~lastName=billingContact.familyName, ~requiredFieldsArr, ) | AddressLine1 => billingContact.addressLines->getAddressLine(0) | AddressLine2 => billingContact.addressLines->getAddressLine(1) | AddressCity => billingContact.locality | AddressState => Utils.getStateNameFromStateCodeAndCountry( statesList, billingContact.administrativeArea, billingCountryCode, ) | Country | AddressCountry(_) => billingCountryCode | AddressPincode => billingContact.postalCode | Email => shippingContact.emailAddress | PhoneNumber => shippingContact.phoneNumber | ShippingName => getName(shippingContact.givenName, shippingContact.familyName) | ShippingAddressLine1 => shippingContact.addressLines->getAddressLine(0) | ShippingAddressLine2 => shippingContact.addressLines->getAddressLine(1) | ShippingAddressCity => shippingContact.locality | ShippingAddressState => Utils.getStateNameFromStateCodeAndCountry( statesList, shippingContact.administrativeArea, shippingCountryCode, ) | ShippingAddressCountry(_) => shippingCountryCode | ShippingAddressPincode => shippingContact.postalCode | _ => "" } if fieldVal !== "" { acc->Dict.set(item.required_field, fieldVal->JSON.Encode.string) } acc }) } let getGooglePayRequiredFields = ( ~billingContact: GooglePayType.billingContact, ~shippingContact: GooglePayType.billingContact, ~requiredFields=defaultRequiredFieldsArray, ~statesList, ~email, ) => { requiredFields->Array.reduce(Dict.make(), (acc, item) => { let requiredFieldsArr = item.required_field->String.split(".") let fieldVal = switch item.field_type { | FullName => billingContact.name->getNameFromString(requiredFieldsArr) | BillingName => billingContact.name->getNameFromString(requiredFieldsArr) | AddressLine1 => billingContact.address1 | AddressLine2 => billingContact.address2 | AddressCity => billingContact.locality | AddressState => Utils.getStateNameFromStateCodeAndCountry( statesList, billingContact.administrativeArea, billingContact.countryCode, ) | Country | AddressCountry(_) => billingContact.countryCode | AddressPincode => billingContact.postalCode | Email => email | PhoneNumber => shippingContact.phoneNumber->String.replaceAll(" ", "")->String.replaceAll("-", "") | ShippingName => shippingContact.name->getNameFromString(requiredFieldsArr) | ShippingAddressLine1 => shippingContact.address1 | ShippingAddressLine2 => shippingContact.address2 | ShippingAddressCity => shippingContact.locality | ShippingAddressState => Utils.getStateNameFromStateCodeAndCountry( statesList, shippingContact.administrativeArea, shippingContact.countryCode, ) | ShippingAddressCountry(_) => shippingContact.countryCode | ShippingAddressPincode => shippingContact.postalCode | _ => "" } if fieldVal !== "" { acc->Dict.set(item.required_field, fieldVal->JSON.Encode.string) } acc }) } let getPaypalRequiredFields = ( ~details: PaypalSDKTypes.details, ~paymentMethodTypes: PaymentMethodsRecord.paymentMethodTypes, ~statesList, ) => { paymentMethodTypes.required_fields->Array.reduce(Dict.make(), (acc, item) => { let requiredFieldsArr = item.required_field->String.split(".") let fieldVal = switch item.field_type { | ShippingName => { let name = details.shippingAddress.recipientName name->Option.map(getNameFromString(_, requiredFieldsArr)) } | ShippingAddressLine1 => details.shippingAddress.line1 | ShippingAddressLine2 => details.shippingAddress.line2 | ShippingAddressCity => details.shippingAddress.city | ShippingAddressState => { let administrativeArea = details.shippingAddress.state->Option.getOr("") let countryCode = details.shippingAddress.countryCode->Option.getOr("") Utils.getStateNameFromStateCodeAndCountry(statesList, administrativeArea, countryCode)->Some } | ShippingAddressCountry(_) => details.shippingAddress.countryCode | ShippingAddressPincode => details.shippingAddress.postalCode | Email => details.email->Some | PhoneNumber => details.phone | _ => None } fieldVal->Option.mapOr((), fieldVal => acc->Dict.set(item.required_field, fieldVal->JSON.Encode.string) ) acc }) } let getKlarnaRequiredFields = ( ~shippingContact: KlarnaSDKTypes.collected_shipping_address, ~paymentMethodTypes: PaymentMethodsRecord.paymentMethodTypes, ~statesList, ) => { paymentMethodTypes.required_fields->Array.reduce(Dict.make(), (acc, item) => { let requiredFieldsArr = item.required_field->String.split(".") let fieldVal = switch item.field_type { | ShippingName => getNameFromFirstAndLastName( ~firstName=shippingContact.given_name, ~lastName=shippingContact.family_name, ~requiredFieldsArr, ) | ShippingAddressLine1 => shippingContact.street_address | ShippingAddressCity => shippingContact.city | ShippingAddressState => { let administrativeArea = shippingContact.region let countryCode = shippingContact.country Utils.getStateNameFromStateCodeAndCountry(statesList, administrativeArea, countryCode) } | ShippingAddressCountry(_) => shippingContact.country | ShippingAddressPincode => shippingContact.postal_code | Email => shippingContact.email | PhoneNumber => shippingContact.phone | _ => "" } if fieldVal !== "" { acc->Dict.set(item.required_field, fieldVal->JSON.Encode.string) } acc }) }
9,811
10,542
hyperswitch-web
src/Utilities/GooglePayHelpers.res
.res
open Utils let getGooglePayBodyFromResponse = ( ~gPayResponse, ~isGuestCustomer, ~paymentMethodListValue=PaymentMethodsRecord.defaultList, ~connectors, ~requiredFields=[], ~stateJson, ~isPaymentSession=false, ~isSavedMethodsFlow=false, ) => { let obj = gPayResponse->getDictFromJson->GooglePayType.itemToObjMapper let gPayBody = PaymentUtils.appendedCustomerAcceptance( ~isGuestCustomer, ~paymentType=paymentMethodListValue.payment_type, ~body=PaymentBody.gpayBody(~payObj=obj, ~connectors), ) let billingContact = obj.paymentMethodData.info ->getDictFromJson ->getJsonObjectFromDict("billingAddress") ->getDictFromJson ->GooglePayType.billingContactItemToObjMapper let shippingContact = gPayResponse ->getDictFromJson ->getJsonObjectFromDict("shippingAddress") ->getDictFromJson ->GooglePayType.billingContactItemToObjMapper let email = gPayResponse ->getDictFromJson ->getString("email", "") let requiredFieldsBody = if isPaymentSession || isSavedMethodsFlow { DynamicFieldsUtils.getGooglePayRequiredFields( ~billingContact, ~shippingContact, ~statesList=stateJson, ~email, ) } else { DynamicFieldsUtils.getGooglePayRequiredFields( ~billingContact, ~shippingContact, ~requiredFields, ~statesList=stateJson, ~email, ) } gPayBody->mergeAndFlattenToTuples(requiredFieldsBody) } let processPayment = ( ~body: array<(string, JSON.t)>, ~isThirdPartyFlow=false, ~intent: PaymentHelpersTypes.paymentIntent, ~options: PaymentType.options, ~publishableKey, ~isManualRetryEnabled, ) => { intent( ~bodyArr=body, ~confirmParam={ return_url: options.wallets.walletReturnUrl, publishableKey, }, ~handleUserError=true, ~isThirdPartyFlow, ~manualRetry=isManualRetryEnabled, ) } let useHandleGooglePayResponse = ( ~connectors, ~intent, ~isSavedMethodsFlow=false, ~isWallet=true, ~requiredFieldsBody=Dict.make(), ) => { let options = Recoil.useRecoilValueFromAtom(RecoilAtoms.optionAtom) let {publishableKey} = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys) let isManualRetryEnabled = Recoil.useRecoilValueFromAtom(RecoilAtoms.isManualRetryEnabled) let paymentMethodListValue = Recoil.useRecoilValueFromAtom(PaymentUtils.paymentMethodListValue) let isGuestCustomer = UtilityHooks.useIsGuestCustomer() let (stateJson, setStatesJson) = React.useState(_ => JSON.Encode.null) PaymentUtils.useStatesJson(setStatesJson) let paymentMethodTypes = DynamicFieldsUtils.usePaymentMethodTypeFromList( ~paymentMethodListValue, ~paymentMethod="wallet", ~paymentMethodType="google_pay", ) React.useEffect(() => { let handle = (ev: Window.event) => { let json = ev.data->safeParse let dict = json->getDictFromJson if dict->Dict.get("gpayResponse")->Option.isSome { let metadata = dict->getJsonObjectFromDict("gpayResponse") let body = getGooglePayBodyFromResponse( ~gPayResponse=metadata, ~isGuestCustomer, ~paymentMethodListValue, ~connectors, ~requiredFields=paymentMethodTypes.required_fields, ~stateJson, ~isSavedMethodsFlow, ) let googlePayBody = if isWallet { body } else { body->mergeAndFlattenToTuples(requiredFieldsBody) } processPayment( ~body=googlePayBody, ~isThirdPartyFlow=false, ~intent, ~options: PaymentType.options, ~publishableKey, ~isManualRetryEnabled, ) } if dict->Dict.get("gpayError")->Option.isSome { messageParentWindow([("fullscreen", false->JSON.Encode.bool)]) if isSavedMethodsFlow || !isWallet { postFailedSubmitResponse(~errortype="server_error", ~message="Something went wrong") } } } Window.addEventListener("message", handle) Some(() => {Window.removeEventListener("message", handle)}) }, (paymentMethodTypes, stateJson, isManualRetryEnabled, requiredFieldsBody, isWallet)) } let handleGooglePayClicked = (~sessionObj, ~componentName, ~iframeId, ~readOnly) => { let paymentDataRequest = GooglePayType.getPaymentDataFromSession(~sessionObj, ~componentName) messageParentWindow([ ("fullscreen", true->JSON.Encode.bool), ("param", "paymentloader"->JSON.Encode.string), ("iframeId", iframeId->JSON.Encode.string), ]) if !readOnly { messageParentWindow([ ("GpayClicked", true->JSON.Encode.bool), ("GpayPaymentDataRequest", paymentDataRequest->Identity.anyTypeToJson), ]) } } let useSubmitCallback = (~isWallet, ~sessionObj, ~componentName) => { let areRequiredFieldsValid = Recoil.useRecoilValueFromAtom(RecoilAtoms.areRequiredFieldsValid) let areRequiredFieldsEmpty = Recoil.useRecoilValueFromAtom(RecoilAtoms.areRequiredFieldsEmpty) let options = Recoil.useRecoilValueFromAtom(RecoilAtoms.optionAtom) let {localeString} = Recoil.useRecoilValueFromAtom(RecoilAtoms.configAtom) let {iframeId} = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys) React.useCallback((ev: Window.event) => { if !isWallet { let json = ev.data->safeParse let confirm = json->getDictFromJson->ConfirmType.itemToObjMapper if confirm.doSubmit && areRequiredFieldsValid && !areRequiredFieldsEmpty { handleGooglePayClicked(~sessionObj, ~componentName, ~iframeId, ~readOnly=options.readOnly) } else if areRequiredFieldsEmpty { postFailedSubmitResponse( ~errortype="validation_error", ~message=localeString.enterFieldsText, ) } else if !areRequiredFieldsValid { postFailedSubmitResponse( ~errortype="validation_error", ~message=localeString.enterValidDetailsText, ) } } }, ( areRequiredFieldsValid, areRequiredFieldsEmpty, isWallet, sessionObj, componentName, iframeId, )) }
1,487
10,543
hyperswitch-web
src/Utilities/LoggerUtils.res
.res
let logApi = ( ~eventName, ~statusCode="", ~data: JSON.t=Dict.make()->JSON.Encode.object, ~apiLogType: HyperLogger.apiLogType, ~url="", ~paymentMethod="", ~result: JSON.t=Dict.make()->JSON.Encode.object, ~optLogger: option<HyperLogger.loggerMake>, ~logType: HyperLogger.logType=INFO, ~logCategory: HyperLogger.logCategory=API, ~isPaymentSession: bool=false, ) => { 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)], ) | Method => ([("method", paymentMethod->JSON.Encode.string)], [("result", result)]) } switch optLogger { | Some(logger) => logger.setLogApi( ~eventName, ~value=ArrayType(value), ~internalMetadata=ArrayType(internalMetadata), ~logType, ~logCategory, ~apiLogType, ~isPaymentSession, ) | None => () } } let logInputChangeInfo = (text, logger: HyperLogger.loggerMake) => { logger.setLogInfo(~value=text, ~eventName=INPUT_FIELD_CHANGED) } let handleLogging = ( ~optLogger: option<HyperLogger.loggerMake>, ~value, ~internalMetadata="", ~eventName, ~paymentMethod, ~logType: HyperLogger.logType=INFO, ) => { switch optLogger { | Some(logger) => logger.setLogInfo(~value, ~internalMetadata, ~eventName, ~paymentMethod, ~logType) | _ => () } }
483
10,544
hyperswitch-web
src/Utilities/TaxCalculation.res
.res
open Utils type calculateTaxResponse = { payment_id: string, net_amount: int, order_tax_amount: int, shipping_cost: int, } let taxResponseToObjMapper = resp => { resp ->JSON.Decode.object ->Option.map(dict => { payment_id: dict->getString("payment_id", ""), net_amount: dict->getInt("net_amount", 0), order_tax_amount: dict->getInt("order_tax_amount", 0), shipping_cost: dict->getInt("shipping_cost", 0), }) } let calculateTax = ( ~shippingAddress, ~logger, ~clientSecret, ~publishableKey, ~paymentMethodType, ~sessionId=None, ) => { PaymentHelpers.calculateTax( ~clientSecret=clientSecret->JSON.Encode.string, ~apiKey=publishableKey, ~paymentId=clientSecret->getPaymentId, ~paymentMethodType, ~shippingAddress, ~logger, ~customPodUri="", ~sessionId, ) }
226
10,545
hyperswitch-web
src/Utilities/URLModule.res
.res
type match type pathname = {match: match} type searchParams = {set: (string, string) => unit} type url = {searchParams: searchParams, href: string, pathname: pathname} @new external makeUrl: string => url = "URL"
57
10,546
hyperswitch-web
src/Utilities/PaymentBody.res
.res
let billingDetailsTuple = ( ~fullName, ~email, ~line1, ~line2, ~city, ~state, ~postalCode, ~country, ) => { let (firstName, lastName) = fullName->Utils.getFirstAndLastNameFromFullName ( "billing", [ ("email", email->JSON.Encode.string), ( "address", [ ("first_name", firstName), ("last_name", lastName), ("line1", line1->JSON.Encode.string), ("line2", line2->JSON.Encode.string), ("city", city->JSON.Encode.string), ("state", state->JSON.Encode.string), ("zip", postalCode->JSON.Encode.string), ("country", country->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ) } let cardPaymentBody = ( ~cardNumber, ~month, ~year, ~cardHolderName=None, ~cvcNumber, ~cardBrand, ~nickname="", ) => { let cardBody = [ ("card_number", cardNumber->CardUtils.clearSpaces->JSON.Encode.string), ("card_exp_month", month->JSON.Encode.string), ("card_exp_year", year->JSON.Encode.string), ("card_cvc", cvcNumber->JSON.Encode.string), ("card_issuer", ""->JSON.Encode.string), ] cardHolderName ->Option.map(name => cardBody->Array.push(("card_holder_name", name->JSON.Encode.string))->ignore) ->ignore if nickname != "" { cardBody->Array.push(("nick_name", nickname->JSON.Encode.string))->ignore } [ ("payment_method", "card"->JSON.Encode.string), ( "payment_method_data", [ ("card", cardBody->Array.concat(cardBrand)->Utils.getJsonFromArrayOfJson), ]->Utils.getJsonFromArrayOfJson, ), ] } let bancontactBody = () => { let bancontactField = [("bancontact_card", []->Utils.getJsonFromArrayOfJson)]->Utils.getJsonFromArrayOfJson let bankRedirectField = [("bank_redirect", bancontactField)]->Utils.getJsonFromArrayOfJson [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "bancontact_card"->JSON.Encode.string), ("payment_method_data", bankRedirectField), ] } let boletoBody = (~socialSecurityNumber) => [ ("payment_method", "voucher"->JSON.Encode.string), ("payment_method_type", "boleto"->JSON.Encode.string), ( "payment_method_data", [ ( "voucher", [ ( "boleto", [ ("social_security_number", socialSecurityNumber->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let customerAcceptanceBody = [ ("acceptance_type", "online"->JSON.Encode.string), ("accepted_at", Date.now()->Js.Date.fromFloat->Date.toISOString->JSON.Encode.string), ( "online", [ ("user_agent", BrowserSpec.navigator.userAgent->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson let savedCardBody = ( ~paymentToken, ~customerId, ~cvcNumber, ~requiresCvv, ~isCustomerAcceptanceRequired, ) => { let savedCardBody = [ ("payment_method", "card"->JSON.Encode.string), ("payment_token", paymentToken->JSON.Encode.string), ("customer_id", customerId->JSON.Encode.string), ] if requiresCvv { savedCardBody->Array.push(("card_cvc", cvcNumber->JSON.Encode.string))->ignore } if isCustomerAcceptanceRequired { savedCardBody->Array.push(("customer_acceptance", customerAcceptanceBody))->ignore } savedCardBody } let clickToPayBody = (~merchantTransactionId, ~correlationId, ~xSrcFlowId) => { let clickToPayServiceDetails = [ ("merchant_transaction_id", merchantTransactionId->JSON.Encode.string), ("correlation_id", correlationId->JSON.Encode.string), ("x_src_flow_id", xSrcFlowId->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson [ ("payment_method", "card"->JSON.Encode.string), ("ctp_service_details", clickToPayServiceDetails), ] } let savedPaymentMethodBody = ( ~paymentToken, ~customerId, ~paymentMethod, ~paymentMethodType, ~isCustomerAcceptanceRequired, ) => { let savedPaymentMethodBody = [ ("payment_method", paymentMethod->JSON.Encode.string), ("payment_token", paymentToken->JSON.Encode.string), ("customer_id", customerId->JSON.Encode.string), ("payment_method_type", paymentMethodType), ] if isCustomerAcceptanceRequired { savedPaymentMethodBody->Array.push(("customer_acceptance", customerAcceptanceBody))->ignore } savedPaymentMethodBody } let mandateBody = paymentType => [ ("mandate_data", [("customer_acceptance", customerAcceptanceBody)]->Utils.getJsonFromArrayOfJson), ("customer_acceptance", customerAcceptanceBody), ("setup_future_usage", "off_session"->JSON.Encode.string), ("payment_type", {paymentType === "" ? JSON.Encode.null : paymentType->JSON.Encode.string}), ] let paymentTypeBody = paymentType => if paymentType != "" { [("payment_type", paymentType->JSON.Encode.string)] } else { [] } let confirmPayloadForSDKButton = (sdkHandleConfirmPayment: PaymentType.sdkHandleConfirmPayment) => [ ( "confirmParams", [ ("return_url", sdkHandleConfirmPayment.confirmParams.return_url->JSON.Encode.string), ("redirect", "always"->JSON.Encode.string), // *As in the case of SDK Button we are not returning the promise back so it will always redirect ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson let bankDebitsCommonBody = paymentMethodType => { [ ("payment_method", "bank_debit"->JSON.Encode.string), ("setup_future_usage", "off_session"->JSON.Encode.string), ("payment_method_type", paymentMethodType->JSON.Encode.string), ("customer_acceptance", customerAcceptanceBody), ] } let achBankDebitBody = ( ~email, ~bank: ACHTypes.data, ~cardHolderName, ~line1, ~line2, ~country, ~city, ~postalCode, ~state, ) => bankDebitsCommonBody("ach")->Array.concat([ ( "payment_method_data", [ billingDetailsTuple( ~fullName=cardHolderName, ~email, ~line1, ~line2, ~city, ~state, ~postalCode, ~country, ), ( "bank_debit", [ ( "ach_bank_debit", [ ("account_number", bank.accountNumber->JSON.Encode.string), ("bank_account_holder_name", bank.accountHolderName->JSON.Encode.string), ("routing_number", bank.routingNumber->JSON.Encode.string), ("bank_type", bank.accountType->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]) let bacsBankDebitBody = ( ~email, ~accNum, ~sortCode, ~line1, ~line2, ~city, ~zip, ~state, ~country, ~bankAccountHolderName, ) => bankDebitsCommonBody("bacs")->Array.concat([ ( "payment_method_data", [ billingDetailsTuple( ~fullName=bankAccountHolderName, ~email, ~line1, ~line2, ~city, ~state, ~postalCode=zip, ~country, ), ( "bank_debit", [ ( "bacs_bank_debit", [ ("bank_account_holder_name", bankAccountHolderName->JSON.Encode.string), ("sort_code", sortCode->JSON.Encode.string), ("account_number", accNum->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]) let becsBankDebitBody = ( ~fullName, ~email, ~data: ACHTypes.data, ~line1, ~line2, ~country, ~city, ~postalCode, ~state, ) => bankDebitsCommonBody("becs")->Array.concat([ ( "payment_method_data", [ billingDetailsTuple( ~fullName, ~email, ~line1, ~line2, ~city, ~state, ~postalCode, ~country, ), ( "bank_debit", [ ( "becs_bank_debit", [ ("bsb_number", data.sortCode->JSON.Encode.string), ("account_number", data.accountNumber->JSON.Encode.string), ("bank_account_holder_name", data.accountHolderName->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]) let klarnaRedirectionBody = (~fullName, ~email, ~country, ~connectors) => [ ("payment_method", "pay_later"->JSON.Encode.string), ("payment_method_type", "klarna"->JSON.Encode.string), ("payment_experience", "redirect_to_url"->JSON.Encode.string), ("connector", connectors->Utils.getArrofJsonString->JSON.Encode.array), ("name", fullName->JSON.Encode.string), ( "payment_method_data", [ ( "pay_later", [ ( "klarna_redirect", [ ("billing_email", email->JSON.Encode.string), ("billing_country", country->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let klarnaSDKbody = (~token, ~connectors) => [ ("payment_method", "pay_later"->JSON.Encode.string), ("payment_method_type", "klarna"->JSON.Encode.string), ("payment_experience", "invoke_sdk_client"->JSON.Encode.string), ("connector", connectors->Utils.getArrofJsonString->JSON.Encode.array), ( "payment_method_data", [ ( "pay_later", [ ("klarna_sdk", [("token", token->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let klarnaCheckoutBody = (~connectors) => { open Utils let checkoutBody = []->Utils.getJsonFromArrayOfJson let payLaterBody = [("klarna_checkout", checkoutBody)]->getJsonFromArrayOfJson let paymentMethodData = [("pay_later", payLaterBody)]->getJsonFromArrayOfJson [ ("payment_method", "pay_later"->JSON.Encode.string), ("payment_method_type", "klarna"->JSON.Encode.string), ("payment_experience", "redirect_to_url"->JSON.Encode.string), ("connector", connectors->getArrofJsonString->JSON.Encode.array), ("payment_method_data", paymentMethodData), ] } let paypalRedirectionBody = (~connectors) => [ ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", "paypal"->JSON.Encode.string), ("payment_experience", "redirect_to_url"->JSON.Encode.string), ("connector", connectors->Utils.getArrofJsonString->JSON.Encode.array), ( "payment_method_data", [ ( "wallet", [("paypal_redirect", []->Utils.getJsonFromArrayOfJson)]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let paypalSdkBody = (~token, ~connectors) => [ ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", "paypal"->JSON.Encode.string), ("payment_experience", "invoke_sdk_client"->JSON.Encode.string), ("connector", connectors->Utils.getArrofJsonString->JSON.Encode.array), ( "payment_method_data", [ ( "wallet", [ ("paypal_sdk", [("token", token->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let samsungPayBody = (~metadata) => { let paymentCredential = [("payment_credential", metadata)]->Utils.getJsonFromArrayOfJson let spayBody = [("samsung_pay", paymentCredential)]->Utils.getJsonFromArrayOfJson let paymentMethodData = [("wallet", spayBody)]->Utils.getJsonFromArrayOfJson [ ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", "samsung_pay"->JSON.Encode.string), ("payment_method_data", paymentMethodData), ] } let gpayBody = (~payObj: GooglePayType.paymentData, ~connectors: array<string>) => { let gPayBody = [ ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", "google_pay"->JSON.Encode.string), ( "payment_method_data", [ ( "wallet", [ ( "google_pay", [ ("type", payObj.paymentMethodData.\"type"->JSON.Encode.string), ("description", payObj.paymentMethodData.description->JSON.Encode.string), ("info", payObj.paymentMethodData.info->Utils.transformKeys(Utils.SnakeCase)), ( "tokenization_data", payObj.paymentMethodData.tokenizationData->Utils.transformKeys(Utils.SnakeCase), ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] if connectors->Array.length > 0 { gPayBody ->Array.push(("connector", connectors->Utils.getArrofJsonString->JSON.Encode.array)) ->ignore } gPayBody } let gpayRedirectBody = (~connectors: array<string>) => [ ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", "google_pay"->JSON.Encode.string), ("connector", connectors->Utils.getArrofJsonString->JSON.Encode.array), ( "payment_method_data", [ ( "wallet", [("google_pay_redirect", Dict.make()->JSON.Encode.object)]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let gPayThirdPartySdkBody = (~connectors) => [ ("connector", connectors->Utils.getArrofJsonString->JSON.Encode.array), ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", "google_pay"->JSON.Encode.string), ( "payment_method_data", [ ( "wallet", [ ("google_pay_third_party_sdk", Dict.make()->JSON.Encode.object), ]->Utils.getJsonFromArrayOfJson, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ] let applePayBody = (~token, ~connectors) => { let dict = token->JSON.Decode.object->Option.getOr(Dict.make()) let paymentDataString = dict ->Dict.get("paymentData") ->Option.getOr(Dict.make()->JSON.Encode.object) ->JSON.stringify ->Window.btoa dict->Dict.set("paymentData", paymentDataString->JSON.Encode.string) let applePayBody = [ ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", "apple_pay"->JSON.Encode.string), ( "payment_method_data", [ ( "wallet", [ ("apple_pay", dict->JSON.Encode.object->Utils.transformKeys(SnakeCase)), ]->Utils.getJsonFromArrayOfJson, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ] if connectors->Array.length > 0 { applePayBody ->Array.push(("connector", connectors->Utils.getArrofJsonString->JSON.Encode.array)) ->ignore } applePayBody } let applePayRedirectBody = (~connectors) => [ ("connector", connectors->Utils.getArrofJsonString->JSON.Encode.array), ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", "apple_pay"->JSON.Encode.string), ( "payment_method_data", [ ( "wallet", [("apple_pay_redirect", Dict.make()->JSON.Encode.object)]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let applePayThirdPartySdkBody = (~connectors) => [ ("connector", connectors->Utils.getArrofJsonString->JSON.Encode.array), ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", "apple_pay"->JSON.Encode.string), ( "payment_method_data", [ ( "wallet", [ ("apple_pay_third_party_sdk", Dict.make()->JSON.Encode.object), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let cryptoBody = () => [ ("payment_method", "crypto"->JSON.Encode.string), ("payment_method_type", "crypto_currency"->JSON.Encode.string), ("payment_experience", "redirect_to_url"->JSON.Encode.string), ( "payment_method_data", [("crypto", []->Utils.getJsonFromArrayOfJson)]->Utils.getJsonFromArrayOfJson, ), ] let afterpayRedirectionBody = () => [ ("payment_method", "pay_later"->JSON.Encode.string), ("payment_method_type", "afterpay_clearpay"->JSON.Encode.string), ("payment_experience", "redirect_to_url"->JSON.Encode.string), ( "payment_method_data", [ ( "pay_later", [ ("afterpay_clearpay_redirect", []->Utils.getJsonFromArrayOfJson), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let giroPayBody = (~name, ~iban="") => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "giropay"->JSON.Encode.string), ( "payment_method_data", [ ( "bank_redirect", [ ( "giropay", [ ( "billing_details", [("billing_name", name->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson, ), ("bank_account_iban", iban->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let sofortBody = (~country, ~name, ~email) => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "sofort"->JSON.Encode.string), ( "payment_method_data", [ ( "bank_redirect", [ ( "sofort", [ ("country", (country == "" ? "US" : country)->JSON.Encode.string), ("preferred_language", "en"->JSON.Encode.string), ( "billing_details", [ ("billing_name", name->JSON.Encode.string), ("email", (email == "" ? "[email protected]" : email)->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let iDealBody = (~name, ~bankName) => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "ideal"->JSON.Encode.string), ( "payment_method_data", [ ( "bank_redirect", [ ( "ideal", [ ( "billing_details", [("billing_name", name->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson, ), ("bank_name", (bankName == "" ? "american_express" : bankName)->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let epsBody = (~name, ~bankName) => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "eps"->JSON.Encode.string), ( "payment_method_data", [ ( "bank_redirect", [ ( "eps", [ ( "billing_details", [("billing_name", name->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson, ), ("bank_name", (bankName === "" ? "american_express" : bankName)->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let blikBody = (~blikCode) => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "blik"->JSON.Encode.string), ( "payment_method_data", [ ( "bank_redirect", [ ("blik", [("blik_code", blikCode->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let p24Body = (~email) => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "przelewy24"->JSON.Encode.string), ( "payment_method_data", [ ("billing", [("email", email->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson), ( "bank_redirect", [("przelewy24", Dict.make()->JSON.Encode.object)]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let interacBody = (~email, ~country) => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "interac"->JSON.Encode.string), ( "payment_method_data", [ ( "bank_redirect", [ ( "interac", [ ("email", email->JSON.Encode.string), ("country", country->JSON.Encode.string), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let trustlyBody = (~country) => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "trustly"->JSON.Encode.string), ( "payment_method_data", [ ( "bank_redirect", [ ("trustly", [("country", country->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let polandOB = (~bank) => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "online_banking_poland"->JSON.Encode.string), ( "payment_method_data", [ ( "bank_redirect", [ ( "online_banking_poland", [("issuer", bank->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let czechOB = (~bank) => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "online_banking_czech_republic"->JSON.Encode.string), ( "payment_method_data", [ ( "bank_redirect", [ ( "online_banking_czech_republic", [("issuer", bank->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let slovakiaOB = (~bank) => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "online_banking_slovakia"->JSON.Encode.string), ( "payment_method_data", [ ( "bank_redirect", [ ( "online_banking_slovakia", [("issuer", bank->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let mbWayBody = (~phoneNumber) => [ ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", "mb_way"->JSON.Encode.string), ( "payment_method_data", [ ( "wallet", [ ( "mb_way_redirect", [("telephone_number", phoneNumber->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let rewardBody = (~paymentMethodType) => [ ("payment_method", "reward"->JSON.Encode.string), ("payment_method_type", paymentMethodType->JSON.Encode.string), ("payment_method_data", "reward"->JSON.Encode.string), ] let fpxOBBody = (~bank) => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "online_banking_fpx"->JSON.Encode.string), ( "payment_method_data", [ ( "bank_redirect", [ ( "online_banking_fpx", [("issuer", bank->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let thailandOBBody = (~bank) => [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "online_banking_thailand"->JSON.Encode.string), ( "payment_method_data", [ ( "bank_redirect", [ ( "online_banking_thailand", [("issuer", bank->JSON.Encode.string)]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ] let pazeBody = (~completeResponse) => { open Utils let pazeCompleteResponse = [("complete_response", completeResponse->JSON.Encode.string)]->getJsonFromArrayOfJson let pazeWalletData = [("paze", pazeCompleteResponse)]->getJsonFromArrayOfJson let paymentMethodData = [("wallet", pazeWalletData)]->getJsonFromArrayOfJson [ ("payment_method", "wallet"->JSON.Encode.string), ("payment_method_type", "paze"->JSON.Encode.string), ("payment_method_data", paymentMethodData), ] } let eftBody = () => { open Utils let eftProviderName = [("provider", "ozow"->JSON.Encode.string)]->getJsonFromArrayOfJson let eftBankRedirectData = [("eft", eftProviderName)]->getJsonFromArrayOfJson let paymentMethodData = [("bank_redirect", eftBankRedirectData)]->getJsonFromArrayOfJson [ ("payment_method", "bank_redirect"->JSON.Encode.string), ("payment_method_type", "eft"->JSON.Encode.string), ("payment_method_data", paymentMethodData), ] } let getPaymentMethodType = (paymentMethod, paymentMethodType) => switch paymentMethod { | "bank_debit" => paymentMethodType->String.replace("_debit", "") | "bank_transfer" => if paymentMethodType != "sepa_bank_transfer" && paymentMethodType != "instant_bank_transfer" { paymentMethodType->String.replace("_transfer", "") } else { paymentMethodType } | _ => paymentMethodType } let appendRedirectPaymentMethods = [ "touch_n_go", "momo", "gcash", "kakao_pay", "go_pay", "dana", "vipps", "twint", "atome", "pay_bright", "walley", "affirm", "we_chat_pay", "ali_pay", "ali_pay_hk", ] let appendBankeDebitMethods = ["sepa"] let appendBankTransferMethods = ["ach", "bacs", "multibanco"] let getPaymentMethodSuffix = (~paymentMethodType, ~paymentMethod, ~isQrPaymentMethod) => { if isQrPaymentMethod { Some("qr") } else if appendRedirectPaymentMethods->Array.includes(paymentMethodType) { Some("redirect") } else if ( appendBankeDebitMethods->Array.includes(paymentMethodType) && paymentMethod == "bank_debit" ) { Some("bank_debit") } else if ( appendBankTransferMethods->Array.includes(paymentMethodType) && paymentMethod == "bank_transfer" ) { Some("bank_transfer") } else { None } } let appendPaymentMethodExperience = (~paymentMethod, ~paymentMethodType, ~isQrPaymentMethod) => switch getPaymentMethodSuffix(~paymentMethodType, ~paymentMethod, ~isQrPaymentMethod) { | Some(suffix) => `${paymentMethodType}_${suffix}` | None => paymentMethodType } let paymentExperiencePaymentMethods = ["affirm"] let appendPaymentExperience = (paymentBodyArr, paymentMethodType) => if paymentExperiencePaymentMethods->Array.includes(paymentMethodType) { paymentBodyArr->Array.concat([("payment_experience", "redirect_to_url"->JSON.Encode.string)]) } else { paymentBodyArr } let dynamicPaymentBody = (paymentMethod, paymentMethodType, ~isQrPaymentMethod=false) => { let paymentMethodType = paymentMethod->getPaymentMethodType(paymentMethodType) [ ("payment_method", paymentMethod->JSON.Encode.string), ("payment_method_type", paymentMethodType->JSON.Encode.string), ( "payment_method_data", [ ( paymentMethod, [ ( appendPaymentMethodExperience(~paymentMethod, ~paymentMethodType, ~isQrPaymentMethod), Dict.make()->JSON.Encode.object, ), ]->Utils.getJsonFromArrayOfJson, ), ]->Utils.getJsonFromArrayOfJson, ), ]->appendPaymentExperience(paymentMethodType) } let getPaymentBody = ( ~paymentMethod, ~paymentMethodType, ~fullName, ~email, ~country, ~bank, ~blikCode, ~paymentExperience: PaymentMethodsRecord.paymentFlow=RedirectToURL, ~phoneNumber, ) => switch paymentMethodType { | "afterpay_clearpay" => afterpayRedirectionBody() | "crypto_currency" => cryptoBody() | "sofort" => sofortBody(~country, ~name=fullName, ~email) | "ideal" => iDealBody(~name=fullName, ~bankName=bank) | "eps" => epsBody(~name=fullName, ~bankName=bank) | "blik" => blikBody(~blikCode) | "ali_pay" | "ali_pay_hk" => switch paymentExperience { | QrFlow => dynamicPaymentBody(paymentMethod, paymentMethodType, ~isQrPaymentMethod=true) | RedirectToURL | _ => dynamicPaymentBody(paymentMethod, paymentMethodType) } | "we_chat_pay" => switch paymentExperience { | QrFlow => dynamicPaymentBody(paymentMethod, paymentMethodType, ~isQrPaymentMethod=true) | RedirectToURL | _ => dynamicPaymentBody(paymentMethod, paymentMethodType) } | "duit_now" => switch paymentExperience { | QrFlow => dynamicPaymentBody(paymentMethod, paymentMethodType, ~isQrPaymentMethod=true) | RedirectToURL | _ => dynamicPaymentBody(paymentMethod, paymentMethodType) } | "giropay" => giroPayBody(~name=fullName) | "trustly" => trustlyBody(~country) | "online_banking_poland" => polandOB(~bank) | "online_banking_czech_republic" => czechOB(~bank) | "online_banking_slovakia" => slovakiaOB(~bank) | "mb_way" => mbWayBody(~phoneNumber) | "interac" => interacBody(~email, ~country) | "przelewy24" => p24Body(~email) | "online_banking_fpx" => fpxOBBody(~bank) | "online_banking_thailand" => thailandOBBody(~bank) | "classic" | "evoucher" => rewardBody(~paymentMethodType) | "eft" => eftBody() | _ => dynamicPaymentBody(paymentMethod, paymentMethodType) }
7,473
10,547
hyperswitch-web
src/Utilities/ApplePayHelpers.res
.res
open ApplePayTypes open Utils open TaxCalculation let processPayment = ( ~bodyArr, ~isThirdPartyFlow=false, ~isGuestCustomer, ~paymentMethodListValue=PaymentMethodsRecord.defaultList, ~intent: PaymentHelpersTypes.paymentIntent, ~options: PaymentType.options, ~publishableKey, ~isManualRetryEnabled, ) => { let requestBody = PaymentUtils.appendedCustomerAcceptance( ~isGuestCustomer, ~paymentType=paymentMethodListValue.payment_type, ~body=bodyArr, ) intent( ~bodyArr=requestBody, ~confirmParam={ return_url: options.wallets.walletReturnUrl, publishableKey, }, ~handleUserError=true, ~isThirdPartyFlow, ~manualRetry=isManualRetryEnabled, ) } let getApplePayFromResponse = ( ~token, ~billingContactDict, ~shippingContactDict, ~requiredFields=[], ~stateJson, ~connectors, ~isPaymentSession=false, ~isSavedMethodsFlow=false, ) => { let billingContact = billingContactDict->ApplePayTypes.billingContactItemToObjMapper let shippingContact = shippingContactDict->ApplePayTypes.shippingContactItemToObjMapper let requiredFieldsBody = if isPaymentSession || isSavedMethodsFlow { DynamicFieldsUtils.getApplePayRequiredFields( ~billingContact, ~shippingContact, ~statesList=stateJson, ) } else { DynamicFieldsUtils.getApplePayRequiredFields( ~billingContact, ~shippingContact, ~requiredFields, ~statesList=stateJson, ) } let bodyDict = PaymentBody.applePayBody(~token, ~connectors) bodyDict->mergeAndFlattenToTuples(requiredFieldsBody) } let startApplePaySession = ( ~paymentRequest, ~applePaySessionRef, ~applePayPresent, ~logger: HyperLogger.loggerMake, ~callBackFunc, ~resolvePromise, ~clientSecret, ~publishableKey, ~isTaxCalculationEnabled=false, ) => { open Promise let ssn = applePaySession(3, paymentRequest) switch applePaySessionRef.contents->Nullable.toOption { | Some(session) => try { session.abort() } catch { | error => Console.error2("Abort fail", error) } | None => () } applePaySessionRef := ssn->Js.Nullable.return ssn.onvalidatemerchant = _event => { let merchantSession = applePayPresent ->Belt.Option.flatMap(JSON.Decode.object) ->Option.getOr(Dict.make()) ->Dict.get("session_token_data") ->Option.getOr(Dict.make()->JSON.Encode.object) ->transformKeys(CamelCase) ssn.completeMerchantValidation(merchantSession) } ssn.onshippingcontactselected = shippingAddressChangeEvent => { let currentTotal = paymentRequest->getDictFromJson->getDictFromDict("total") let label = currentTotal->getString("label", "apple") let currentAmount = currentTotal->getString("amount", "0.00") let \"type" = currentTotal->getString("type", "final") let oldTotal: lineItem = { label, amount: currentAmount, \"type", } let currentOrderDetails: orderDetails = { newTotal: oldTotal, newLineItems: [oldTotal], } if isTaxCalculationEnabled { let newShippingContact = shippingAddressChangeEvent.shippingContact ->getDictFromJson ->shippingContactItemToObjMapper let newShippingAddress = [ ("state", newShippingContact.administrativeArea->JSON.Encode.string), ("country", newShippingContact.countryCode->JSON.Encode.string), ("zip", newShippingContact.postalCode->JSON.Encode.string), ]->getJsonFromArrayOfJson let paymentMethodType = "apple_pay"->JSON.Encode.string calculateTax( ~shippingAddress=[("address", newShippingAddress)]->getJsonFromArrayOfJson, ~logger, ~publishableKey, ~clientSecret, ~paymentMethodType, )->thenResolve(response => { switch response->taxResponseToObjMapper { | Some(taxCalculationResponse) => { let (netAmount, ordertaxAmount, shippingCost) = ( taxCalculationResponse.net_amount, taxCalculationResponse.order_tax_amount, taxCalculationResponse.shipping_cost, ) let newTotal: lineItem = { label, amount: netAmount->minorUnitToString, \"type", } let newLineItems: array<lineItem> = [ { label: "Subtotal", amount: (netAmount - ordertaxAmount - shippingCost)->minorUnitToString, \"type": "final", }, { label: "Order Tax Amount", amount: ordertaxAmount->minorUnitToString, \"type": "final", }, { label: "Shipping Cost", amount: shippingCost->minorUnitToString, \"type": "final", }, ] let updatedOrderDetails: orderDetails = { newTotal, newLineItems, } ssn.completeShippingContactSelection(updatedOrderDetails) } | None => ssn.completeShippingContactSelection(currentOrderDetails) } }) } else { ssn.completeShippingContactSelection(currentOrderDetails) resolve() } } ssn.onpaymentauthorized = event => { ssn.completePayment({"status": ssn.\"STATUS_SUCCESS"}->Identity.anyTypeToJson) applePaySessionRef := Nullable.null let value = "Payment Data Filled: New Payment Method" logger.setLogInfo(~value, ~eventName=PAYMENT_DATA_FILLED, ~paymentMethod="APPLE_PAY") let payment = event.payment payment->callBackFunc } ssn.oncancel = _ => { applePaySessionRef := Nullable.null logger.setLogError( ~value="Apple Pay Payment Cancelled", ~eventName=APPLE_PAY_FLOW, ~paymentMethod="APPLE_PAY", ) handleFailureResponse( ~message="ApplePay Session Cancelled", ~errorType="apple_pay", )->resolvePromise } ssn.begin() } let useHandleApplePayResponse = ( ~connectors, ~intent, ~setApplePayClicked=_ => (), ~syncPayment=() => (), ~isInvokeSDKFlow=true, ~isSavedMethodsFlow=false, ~isWallet=true, ~requiredFieldsBody=Dict.make(), ) => { let options = Recoil.useRecoilValueFromAtom(RecoilAtoms.optionAtom) let {publishableKey} = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys) let paymentMethodListValue = Recoil.useRecoilValueFromAtom(PaymentUtils.paymentMethodListValue) let logger = Recoil.useRecoilValueFromAtom(RecoilAtoms.loggerAtom) let (stateJson, setStatesJson) = React.useState(_ => JSON.Encode.null) let isGuestCustomer = UtilityHooks.useIsGuestCustomer() PaymentUtils.useStatesJson(setStatesJson) let paymentMethodTypes = DynamicFieldsUtils.usePaymentMethodTypeFromList( ~paymentMethodListValue, ~paymentMethod="wallet", ~paymentMethodType="apple_pay", ) let isManualRetryEnabled = Recoil.useRecoilValueFromAtom(RecoilAtoms.isManualRetryEnabled) React.useEffect(() => { let handleApplePayMessages = (ev: Window.event) => { let json = ev.data->safeParse try { let dict = json->getDictFromJson if dict->Dict.get("applePayPaymentToken")->Option.isSome { let token = dict->Dict.get("applePayPaymentToken")->Option.getOr(Dict.make()->JSON.Encode.object) let billingContactDict = dict->getDictFromDict("applePayBillingContact") let shippingContactDict = dict->getDictFromDict("applePayShippingContact") let applePayBody = getApplePayFromResponse( ~token, ~billingContactDict, ~shippingContactDict, ~requiredFields=paymentMethodTypes.required_fields, ~stateJson, ~connectors, ~isSavedMethodsFlow, ) let bodyArr = if isWallet { applePayBody } else { applePayBody->mergeAndFlattenToTuples(requiredFieldsBody) } processPayment( ~bodyArr, ~isThirdPartyFlow=false, ~isGuestCustomer, ~paymentMethodListValue, ~intent, ~options, ~publishableKey, ~isManualRetryEnabled, ) } else if dict->Dict.get("showApplePayButton")->Option.isSome { setApplePayClicked(_ => false) if isSavedMethodsFlow || !isWallet { postFailedSubmitResponse(~errortype="server_error", ~message="Something went wrong") } } else if dict->Dict.get("applePaySyncPayment")->Option.isSome { syncPayment() } } catch { | err => logger.setLogError( ~value="Error in parsing Apple Pay Data", ~eventName=APPLE_PAY_FLOW, ~paymentMethod="APPLE_PAY", ~internalMetadata=err->formatException->JSON.stringify, ) } } Window.addEventListener("message", handleApplePayMessages) Some( () => { messageParentWindow([("applePaySessionAbort", true->JSON.Encode.bool)]) Window.removeEventListener("message", handleApplePayMessages) }, ) }, ( isInvokeSDKFlow, processPayment, stateJson, isManualRetryEnabled, isWallet, requiredFieldsBody, )) } let handleApplePayButtonClicked = ( ~sessionObj, ~componentName, ~paymentMethodListValue: PaymentMethodsRecord.paymentMethodList, ) => { let paymentRequest = ApplePayTypes.getPaymentRequestFromSession(~sessionObj, ~componentName) let message = [ ("applePayButtonClicked", true->JSON.Encode.bool), ("applePayPaymentRequest", paymentRequest), ( "isTaxCalculationEnabled", paymentMethodListValue.is_tax_calculation_enabled->JSON.Encode.bool, ), ("componentName", componentName->JSON.Encode.string), ] messageParentWindow(message) } let useSubmitCallback = (~isWallet, ~sessionObj, ~componentName) => { let areRequiredFieldsValid = Recoil.useRecoilValueFromAtom(RecoilAtoms.areRequiredFieldsValid) let areRequiredFieldsEmpty = Recoil.useRecoilValueFromAtom(RecoilAtoms.areRequiredFieldsEmpty) let options = Recoil.useRecoilValueFromAtom(RecoilAtoms.optionAtom) let {localeString} = Recoil.useRecoilValueFromAtom(RecoilAtoms.configAtom) let paymentMethodListValue = Recoil.useRecoilValueFromAtom(PaymentUtils.paymentMethodListValue) React.useCallback((ev: Window.event) => { if !isWallet { let json = ev.data->safeParse let confirm = json->getDictFromJson->ConfirmType.itemToObjMapper if confirm.doSubmit && areRequiredFieldsValid && !areRequiredFieldsEmpty { if !options.readOnly { handleApplePayButtonClicked(~sessionObj, ~componentName, ~paymentMethodListValue) } } else if areRequiredFieldsEmpty { postFailedSubmitResponse( ~errortype="validation_error", ~message=localeString.enterFieldsText, ) } else if !areRequiredFieldsValid { postFailedSubmitResponse( ~errortype="validation_error", ~message=localeString.enterValidDetailsText, ) } } }, (areRequiredFieldsValid, areRequiredFieldsEmpty, isWallet, sessionObj, componentName)) }
2,603
10,548
hyperswitch-web
src/Utilities/TestUtils.res
.res
let paymentMethodListTestId = "paymentList" let paymentMethodDropDownTestId = "paymentMethodsSelect" let cardNoInputTestId = "cardNoInput" let expiryInputTestId = "expiryInput" let cardCVVInputTestId = "cvvInput" let cardHolderNameInputTestId = "BillingName" let fullNameInputTestId = "FullName" let emailInputTestId = "email" let addressLine1InputTestId = "line1" let cityInputTestId = "city" let countryDropDownTestId = "Country" let stateDropDownTestId = "State" let postalCodeInputTestId = "postal" let addNewCardIcon = "addNewCard" /* { "cardNo":"4242 4242 4242 4242", "cardExpiry":"04/24", "cardCVV":"424", "billingName":"John Doe", "cardHolderName":"John Doe", "email":"[email protected]", "address":"123 Main Street Apt 4B", "city":"New York", "country":"United States", "state":"New York", "postalCode":"10001", "paymentSuccessfulText":"Payment successful" } */ let fieldTestIdMapping = { "billing.address.city": cityInputTestId, "billing.address.country": countryDropDownTestId, "billing.address.first_name": cardHolderNameInputTestId, "billing.address.last_name": cardHolderNameInputTestId, "billing.address.line1": addressLine1InputTestId, "billing.address.state": stateDropDownTestId, "billing.address.zip": postalCodeInputTestId, "email": emailInputTestId, "payment_method_data.card.card_cvc": cardCVVInputTestId, "payment_method_data.card.card_exp_month": expiryInputTestId, "payment_method_data.card.card_exp_year": expiryInputTestId, "payment_method_data.card.card_holder_name": fullNameInputTestId, "payment_method_data.card.card_number": cardNoInputTestId, }
434
10,549
hyperswitch-web
src/Utilities/PaymentMethodCollectUtils.res
.res
open CardUtils open ErrorUtils open PaymentMethodCollectTypes open Utils type t = Dict.t<JSON.t> // Function to get a nested value let getNestedValue = (dict: t, key: string): option<JSON.t> => { let keys = String.split(key, ".") let length = Array.length(keys) let rec traverse = (currentDict, index): option<JSON.t> => { if index === length - 1 { Dict.get(currentDict, Array.getUnsafe(keys, index)) } else { let keyPart = Array.getUnsafe(keys, index) switch Dict.get(currentDict, keyPart) { | Some(subDict) => switch JSON.Decode.object(subDict) { | Some(innerDict) => traverse(innerDict, index + 1) | None => None } | None => None } } } traverse(dict, 0) } // Helper function to get or create a sub-dictionary let getOrCreateSubDict = (dict: t, key: string): t => { switch Dict.get(dict, key) { | Some(subDict) => switch JSON.Decode.object(subDict) { | Some(innerDict) => innerDict | None => { let newSubDict = Dict.make() Dict.set(dict, key, JSON.Encode.object(newSubDict)) newSubDict } } | None => { let newSubDict = Dict.make() Dict.set(dict, key, JSON.Encode.object(newSubDict)) newSubDict } } } // Function to set a nested value let setNestedValue = (dict: t, key: string, value: JSON.t): unit => { let keys = String.split(key, ".") let rec traverse = (currentDict, index) => { if index === Array.length(keys) - 1 { Dict.set(currentDict, Array.getUnsafe(keys, index), value) } else { let keyPart = Array.getUnsafe(keys, index) let subDict = getOrCreateSubDict(currentDict, keyPart) traverse(subDict, index + 1) } } traverse(dict, 0) } let getPaymentMethodForPmt = (paymentMethodType: paymentMethodType): paymentMethod => { switch paymentMethodType { | Card(_) => Card | BankTransfer(_) => BankTransfer | Wallet(_) => Wallet } } let getPaymentMethod = (paymentMethod: paymentMethod): string => { switch paymentMethod { | Card => "card" | BankTransfer => "bank_transfer" | Wallet => "wallet" } } let getPaymentMethodForPayoutsConfirm = (paymentMethod: paymentMethod): string => { switch paymentMethod { | Card => "card" | BankTransfer => "bank" | Wallet => "wallet" } } let getPaymentMethodType = (paymentMethodType: paymentMethodType): string => { switch paymentMethodType { | Card(cardType) => switch cardType { | Credit => "credit" | Debit => "debit" } | BankTransfer(bankTransferType) => switch bankTransferType { | ACH => "ach" | Bacs => "bacs" | Pix => "pix" | Sepa => "sepa" } | Wallet(walletType) => switch walletType { | Paypal => "paypal" | Venmo => "venmo" } } } let getPaymentMethodLabel = (paymentMethod: paymentMethod): string => { switch paymentMethod { | Card => "Card" | BankTransfer => "Bank" | Wallet => "Wallet" } } let getPaymentMethodTypeLabel = (paymentMethodType: paymentMethodType): string => { switch paymentMethodType { | Card(cardType) => switch cardType { | Credit | Debit => "Card" } | BankTransfer(bankTransferType) => switch bankTransferType { | ACH => "ACH" | Bacs => "BACS" | Pix => "Pix" | Sepa => "SEPA" } | Wallet(walletType) => switch walletType { | Paypal => "PayPal" | Venmo => "Venmo" } } } let getPaymentMethodDataFieldKey = (key): string => switch key { | PayoutMethodData(p) => switch p { | CardNumber => "card.cardNumber" | CardExpDate(_) => "card.cardExp" | CardHolderName => "card.cardHolder" | CardBrand => "card.brand" | ACHRoutingNumber => "ach.routing" | ACHAccountNumber => "ach.account" | ACHBankName => "ach.bankName" | ACHBankCity => "ach.bankCity" | BacsSortCode => "bacs.sort" | BacsAccountNumber => "bacs.account" | BacsBankName => "bacs.bankName" | BacsBankCity => "bacs.bankCity" | SepaIban => "sepa.iban" | SepaBic => "sepa.bic" | SepaBankName => "sepa.bankName" | SepaBankCity => "sepa.bankCity" | SepaCountryCode => "sepa.countryCode" | PaypalMail => "paypal.email" | PaypalMobNumber => "paypal.phoneNumber" | PixKey => "pix.key" | PixBankAccountNumber => "pix.account" | PixBankName => "pix.bankName" | VenmoMobNumber => "venmo.phoneNumber" } | BillingAddress(b) => switch b { | Email => "billing.address.email" | FullName(_) => "billing.address.fullName" | CountryCode => "billing.address.countryCode" | PhoneNumber => "billing.address.phoneNumber" | PhoneCountryCode => "billing.address.phoneCountryCode" | AddressLine1 => "billing.address.addressLine1" | AddressLine2 => "billing.address.addressLine2" | AddressCity => "billing.address.addressCity" | AddressState => "billing.address.addressState" | AddressPincode => "billing.address.addressPincode" | AddressCountry(_) => "billing.address.addressCountry" } } let getPaymentMethodDataFieldLabel = (key, localeString: LocaleStringTypes.localeStrings): string => switch key { | PayoutMethodData(CardNumber) => localeString.cardNumberLabel | PayoutMethodData(CardExpDate(_)) => localeString.validThruText | PayoutMethodData(CardHolderName) => localeString.cardHolderName | PayoutMethodData(ACHRoutingNumber) => localeString.formFieldACHRoutingNumberLabel | PayoutMethodData(ACHAccountNumber) | PayoutMethodData(BacsAccountNumber) => localeString.accountNumberText | PayoutMethodData(BacsSortCode) => localeString.sortCodeText | PayoutMethodData(SepaIban) => localeString.formFieldSepaIbanLabel | PayoutMethodData(SepaBic) => localeString.formFieldSepaBicLabel | PayoutMethodData(PixKey) => localeString.formFieldPixIdLabel | PayoutMethodData(PixBankAccountNumber) => localeString.formFieldBankAccountNumberLabel | PayoutMethodData(PaypalMail) => localeString.emailLabel | PayoutMethodData(PaypalMobNumber) | PayoutMethodData(VenmoMobNumber) => localeString.formFieldPhoneNumberLabel | PayoutMethodData(SepaCountryCode) => localeString.formFieldCountryCodeLabel | PayoutMethodData(ACHBankName) | PayoutMethodData(BacsBankName) | PayoutMethodData(PixBankName) | PayoutMethodData(SepaBankName) => localeString.formFieldBankNameLabel | PayoutMethodData(ACHBankCity) | PayoutMethodData(BacsBankCity) | PayoutMethodData(SepaBankCity) => localeString.formFieldBankCityLabel | PayoutMethodData(CardBrand) => "Misc." // Address details | BillingAddress(Email) => localeString.emailLabel | BillingAddress(FullName(_)) => localeString.fullNameLabel | BillingAddress(CountryCode) => localeString.countryLabel | BillingAddress(PhoneNumber) => localeString.formFieldPhoneNumberLabel | BillingAddress(PhoneCountryCode) => localeString.formFieldCountryCodeLabel | BillingAddress(AddressLine1) => localeString.line1Label | BillingAddress(AddressLine2) => localeString.line2Label | BillingAddress(AddressCity) => localeString.cityLabel | BillingAddress(AddressState) => localeString.stateLabel | BillingAddress(AddressPincode) => localeString.postalCodeLabel | BillingAddress(AddressCountry(_)) => localeString.countryLabel } let getPaymentMethodDataFieldPlaceholder = ( key, locale: LocaleStringTypes.localeStrings, constant: LocaleStringTypes.constantStrings, ): string => { switch key { | PayoutMethodData(CardNumber) => constant.formFieldCardNumberPlaceholder | PayoutMethodData(CardExpDate(_)) => locale.expiryPlaceholder | PayoutMethodData(CardHolderName) => locale.formFieldCardHoldernamePlaceholder | PayoutMethodData(ACHRoutingNumber) => constant.formFieldACHRoutingNumberPlaceholder | PayoutMethodData(ACHAccountNumber) => constant.formFieldAccountNumberPlaceholder | PayoutMethodData(BacsSortCode) => constant.formFieldSortCodePlaceholder | PayoutMethodData(BacsAccountNumber) => constant.formFieldAccountNumberPlaceholder | PayoutMethodData(SepaIban) => constant.formFieldSepaIbanPlaceholder | PayoutMethodData(SepaBic) => constant.formFieldSepaBicPlaceholder | PayoutMethodData(SepaCountryCode) => locale.countryLabel | PayoutMethodData(PixKey) => constant.formFieldPixIdPlaceholder | PayoutMethodData(PixBankAccountNumber) => constant.formFieldBankAccountNumberPlaceholder | PayoutMethodData(ACHBankName) | PayoutMethodData(BacsBankName) | PayoutMethodData(PixBankName) | PayoutMethodData(SepaBankName) => locale.formFieldBankNamePlaceholder | PayoutMethodData(ACHBankCity) | PayoutMethodData(BacsBankCity) | PayoutMethodData(SepaBankCity) => locale.formFieldBankCityPlaceholder | PayoutMethodData(PaypalMail) => locale.formFieldEmailPlaceholder | PayoutMethodData(PaypalMobNumber) | PayoutMethodData(VenmoMobNumber) => locale.formFieldPhoneNumberPlaceholder | PayoutMethodData(CardBrand) => "Misc." // TODO: handle billing address locales this | _ => "" } } let getPaymentMethodDataFieldMaxLength = (key): int => switch key { | PayoutMethodData(CardNumber) => 23 | PayoutMethodData(CardExpDate(_)) => 7 | PayoutMethodData(ACHRoutingNumber) => 9 | PayoutMethodData(ACHAccountNumber) => 12 | PayoutMethodData(BacsSortCode) => 6 | PayoutMethodData(BacsAccountNumber) => 18 | PayoutMethodData(SepaBic) => 8 | PayoutMethodData(SepaIban) => 34 | _ => 32 } let getPaymentMethodDataFieldCharacterPattern = (key): option<Js.Re.t> => switch key { | PayoutMethodData(ACHAccountNumber) => Some(%re("/^\d{1,17}$/")) | PayoutMethodData(ACHRoutingNumber) => Some(%re("/^\d{1,9}$/")) | PayoutMethodData(BacsAccountNumber) => Some(%re("/^\d{1,18}$/")) | PayoutMethodData(BacsSortCode) => Some(%re("/^\d{1,6}$/")) | PayoutMethodData(CardHolderName) => Some(%re("/^([a-zA-Z]| ){1,32}$/")) | PayoutMethodData(CardNumber) => Some(%re("/^\d{1,18}$/")) | PayoutMethodData(PaypalMail) => Some(%re("/^[a-zA-Z0-9._%+-]*[a-zA-Z0-9._%+-]*@[a-zA-Z0-9.-]*$/")) | PayoutMethodData(PaypalMobNumber) => Some(%re("/^[0-9]{1,12}$/")) | PayoutMethodData(SepaBic) => Some(%re("/^([A-Z0-9]| ){1,8}$/")) | PayoutMethodData(SepaIban) => Some(%re("/^([A-Z0-9]| ){1,34}$/")) | BillingAddress(AddressPincode) => Some(%re("/^([0-9A-Z]| ){1,10}$/")) | BillingAddress(PhoneNumber) => Some(%re("/^[0-9]{1,12}$/")) | BillingAddress(PhoneCountryCode) => Some(%re("/^[0-9]{1,2}$/")) | _ => None } let getPaymentMethodDataFieldInputType = (key): string => switch key { | PayoutMethodData(PaypalMail) => "email" | PayoutMethodData(ACHAccountNumber) | PayoutMethodData(ACHRoutingNumber) | PayoutMethodData(BacsAccountNumber) | PayoutMethodData(BacsSortCode) | PayoutMethodData(CardExpDate(_)) | PayoutMethodData(CardNumber) | PayoutMethodData(PaypalMobNumber) | PayoutMethodData(VenmoMobNumber) => "tel" | _ => "text" } let getPayoutImageSource = (payoutStatus: payoutStatus): string => { switch payoutStatus { | Success => "https://live.hyperswitch.io/payment-link-assets/success.png" | Initiated | Pending | RequiresFulfillment => "https://live.hyperswitch.io/payment-link-assets/pending.png" | Cancelled | Failed | Ineligible | Expired | RequiresCreation | Reversed | RequiresConfirmation | RequiresPayoutMethodData | RequiresVendorAccountCreation => "https://live.hyperswitch.io/payment-link-assets/failed.png" } } let getPayoutReadableStatus = ( payoutStatus: payoutStatus, localeString: LocaleStringTypes.localeStrings, ): string => switch payoutStatus { | Success => localeString.payoutStatusSuccessText | Initiated | Pending | RequiresFulfillment => localeString.payoutStatusPendingText | Cancelled | Failed | Ineligible | Expired | RequiresCreation | Reversed | RequiresConfirmation | RequiresPayoutMethodData | RequiresVendorAccountCreation => localeString.payoutStatusFailedText } let getPayoutStatusString = (payoutStatus: payoutStatus): string => switch payoutStatus { | Success => "success" | Initiated => "initiated" | Pending => "pending" | RequiresFulfillment => "requires_fulfillment" | Cancelled => "expired" | Failed => "failed" | Ineligible => "ineligible" | Expired => "cancelled" | RequiresCreation => "requires_creation" | Reversed => "reversed" | RequiresConfirmation => "requires_confirmation" | RequiresPayoutMethodData => "requires_payout_method_data" | RequiresVendorAccountCreation => "requires_vendor_account_creation" } let getPayoutStatusMessage = ( payoutStatus: payoutStatus, localeString: LocaleStringTypes.localeStrings, ): string => switch payoutStatus { | Success => localeString.payoutStatusSuccessMessage | Initiated | Pending | RequiresFulfillment => localeString.payoutStatusPendingMessage | Cancelled | Failed | Ineligible | Expired | RequiresCreation | Reversed | RequiresConfirmation | RequiresPayoutMethodData | RequiresVendorAccountCreation => localeString.payoutStatusFailedMessage } let getPaymentMethodDataErrorString = ( key, value, localeString: LocaleStringTypes.localeStrings, ): string => { let len = value->String.length let notEmptyAndComplete = len >= 0 && len === key->getPaymentMethodDataFieldMaxLength switch (key, notEmptyAndComplete) { | (PayoutMethodData(CardNumber), _) => localeString.inValidCardErrorText | (PayoutMethodData(CardExpDate(_)), false) => localeString.inCompleteExpiryErrorText | (PayoutMethodData(CardExpDate(_)), true) => localeString.pastExpiryErrorText | (PayoutMethodData(ACHRoutingNumber), false) => localeString.formFieldInvalidRoutingNumber | (BillingAddress(AddressState), _) => "Invalid state" | _ => "" } } let getPaymentMethodIcon = (paymentMethod: paymentMethod) => switch paymentMethod { | Card => <Icon name="default-card" size=20 /> | BankTransfer => <Icon name="bank" size=20 /> | Wallet => <Icon name="wallet-generic-line" size=20 /> } let getBankTransferIcon = (bankTransfer: bankTransfer) => switch bankTransfer { | ACH => <Icon name="ach_bank_transfer" size=20 /> | Bacs => <Icon name="bank" size=20 /> | Pix => <Icon name="wallet-pix" size=20 /> | Sepa => <Icon name="bank" size=20 /> } let getWalletIcon = (wallet: wallet) => switch wallet { | Paypal => <Icon name="wallet-paypal" size=20 /> | Venmo => <Icon name="wallet-venmo" size=20 /> } let getPaymentMethodTypeIcon = (paymentMethodType: paymentMethodType) => switch paymentMethodType { | Card(_) => Card->getPaymentMethodIcon | BankTransfer(b) => b->getBankTransferIcon | Wallet(w) => w->getWalletIcon } // Defaults let defaultFormDataDict: Dict.t<string> = Dict.make() let defaultValidityDict: Dict.t<option<bool>> = Dict.make() let defaultOptionsLimitInTabLayout = 2 let defaultAvailablePaymentMethods: array<paymentMethod> = [] let defaultAvailablePaymentMethodTypes: array<paymentMethodType> = [] let defaultPm: paymentMethod = Card let defaultPmt = (~pm=defaultPm): paymentMethodType => { switch pm { | Card => Card(Debit) | BankTransfer => BankTransfer(ACH) | Wallet => Wallet(Paypal) } } let defaultCardFields: array<dynamicFieldForPaymentMethodData> = [ { pmdMap: "payout_method_data.card.card_number", displayName: "user_card_number", fieldType: CardNumber, value: None, }, { pmdMap: "payout_method_data.card.expiry_month", displayName: "user_card_exp_month", fieldType: CardExpDate(CardExpMonth), value: None, }, { pmdMap: "payout_method_data.card.expiry_year", displayName: "user_card_exp_year", fieldType: CardExpDate(CardExpYear), value: None, }, ] let defaultAchFields = [ { pmdMap: "payout_method_data.ach.bank_routing_number", displayName: "user_routing_number", fieldType: ACHRoutingNumber, value: None, }, { pmdMap: "payout_method_data.ach.bank_account_number", displayName: "user_bank_account_number", fieldType: ACHAccountNumber, value: None, }, ] let defaultBacsFields = [ { pmdMap: "payout_method_data.bank.bank_sort_code", displayName: "user_sort_code", fieldType: BacsSortCode, value: None, }, { pmdMap: "payout_method_data.bank.bank_account_number", displayName: "user_bank_account_number", fieldType: BacsAccountNumber, value: None, }, ] let defaultPixTransferFields = [ { pmdMap: "payout_method_data.bank.bank_account_number", displayName: "user_bank_account_number", fieldType: PixBankAccountNumber, value: None, }, { pmdMap: "payout_method_data.bank.pix_key", displayName: "user_pix_key", fieldType: PixKey, value: None, }, ] let defaultSepaFields = [ { pmdMap: "payout_method_data.bank.iban", displayName: "user_iban", fieldType: SepaIban, value: None, }, ] let defaultPaypalFields = [ { pmdMap: "payout_method_data.wallet.telephone_number", displayName: "user_phone_number", fieldType: PaypalMobNumber, value: None, }, ] let defaultDynamicPmdFields = (~pmt: paymentMethodType=defaultPmt()): array< dynamicFieldForPaymentMethodData, > => { switch pmt { | Card(_) => defaultCardFields | BankTransfer(ACH) => defaultAchFields | BankTransfer(Bacs) => defaultBacsFields | BankTransfer(Pix) => defaultPixTransferFields | BankTransfer(Sepa) => defaultSepaFields | Wallet(Paypal) => defaultPaypalFields | Wallet(Venmo) => [] } } let defaultPayoutDynamicFields = (~pmt: paymentMethodType=defaultPmt()): payoutDynamicFields => { { address: None, payoutMethodData: defaultDynamicPmdFields(~pmt), } } let defaultFormLayout: formLayout = Tabs let defaultJourneyView: journeyViews = SelectPM let defaultTabView: tabViews = DetailsForm let defaultView = (layout: formLayout) => { switch layout { | Journey => Journey(SelectPM) | Tabs => Tabs(defaultTabView) } } let defaultPaymentMethodCollectFlow: paymentMethodCollectFlow = PayoutLinkInitiate let defaultAmount = "0.01" let defaultCurrency = "EUR" let defaultEnabledPaymentMethods: array<paymentMethodType> = [ Card(Credit), Card(Debit), BankTransfer(ACH), BankTransfer(Bacs), BankTransfer(Sepa), Wallet(Paypal), ] let defaultEnabledPaymentMethodsWithDynamicFields: array<paymentMethodTypeWithDynamicFields> = [ Card((Credit, defaultPayoutDynamicFields(~pmt=Card(Credit)))), Card((Debit, defaultPayoutDynamicFields(~pmt=Card(Debit)))), BankTransfer((ACH, defaultPayoutDynamicFields(~pmt=BankTransfer(ACH)))), BankTransfer((Bacs, defaultPayoutDynamicFields(~pmt=BankTransfer(Bacs)))), BankTransfer((Sepa, defaultPayoutDynamicFields(~pmt=BankTransfer(Sepa)))), Wallet((Paypal, defaultPayoutDynamicFields(~pmt=Wallet(Paypal)))), ] let defaultPaymentMethodCollectOptions = { enabledPaymentMethods: defaultEnabledPaymentMethods, enabledPaymentMethodsWithDynamicFields: defaultEnabledPaymentMethodsWithDynamicFields, linkId: "", payoutId: "", customerId: "", theme: "#1A1A1A", collectorName: "HyperSwitch", logo: "", returnUrl: None, amount: defaultAmount, currency: defaultCurrency, flow: defaultPaymentMethodCollectFlow, sessionExpiry: "", formLayout: defaultFormLayout, } let defaultStatusInfo = { status: Success, payoutId: "", message: EnglishLocale.localeStrings.payoutStatusSuccessMessage, code: None, errorMessage: None, reason: None, } let itemToObjMapper = (dict, logger) => { unknownKeysWarning( [ "enabledPaymentMethods", "linkId", "payoutId", "customerId", "theme", "collectorName", "logo", "returnUrl", "amount", "currency", "flow", "sessionExpiry", "formLayout", ], dict, "options", ~logger, ) let (enabledPaymentMethods, enabledPaymentMethodsWithDynamicFields) = switch dict->Dict.get( "enabledPaymentMethods", ) { | Some(json) => json->decodePaymentMethodTypeArray(defaultDynamicPmdFields) | None => (defaultEnabledPaymentMethods, defaultEnabledPaymentMethodsWithDynamicFields) } { enabledPaymentMethodsWithDynamicFields, enabledPaymentMethods, linkId: getString(dict, "linkId", ""), payoutId: getString(dict, "payoutId", ""), customerId: getString(dict, "customerId", ""), theme: getString(dict, "theme", ""), collectorName: getString(dict, "collectorName", ""), logo: getString(dict, "logo", ""), returnUrl: dict->Dict.get("returnUrl")->Option.flatMap(JSON.Decode.string), amount: dict->decodeAmount(defaultAmount), currency: getString(dict, "currency", defaultCurrency), flow: dict->decodeFlow(defaultPaymentMethodCollectFlow), sessionExpiry: getString(dict, "sessionExpiry", ""), formLayout: dict->decodeFormLayout(defaultFormLayout), } } let calculateValidity = (key, value, ~default=None) => { switch key { | PayoutMethodData(CardNumber) => if cardNumberInRange(value)->Array.includes(true) && calculateLuhn(value) { Some(true) } else if value->String.length == 0 { default } else { Some(false) } | PayoutMethodData(CardExpDate(_)) => if value->String.length > 0 && getExpiryValidity(value) { Some(true) } else if value->String.length == 0 { default } else { Some(false) } | PayoutMethodData(ACHRoutingNumber) => if value->String.length === 9 { let p1 = switch ( value->String.charAt(0)->Int.fromString, value->String.charAt(3)->Int.fromString, value->String.charAt(6)->Int.fromString, ) { | (Some(a), Some(b), Some(c)) => Some(3 * (a + b + c)) | _ => None } let p2 = switch ( value->String.charAt(1)->Int.fromString, value->String.charAt(4)->Int.fromString, value->String.charAt(7)->Int.fromString, ) { | (Some(a), Some(b), Some(c)) => Some(7 * (a + b + c)) | _ => None } let p3 = switch ( value->String.charAt(2)->Int.fromString, value->String.charAt(5)->Int.fromString, value->String.charAt(8)->Int.fromString, ) { | (Some(a), Some(b), Some(c)) => Some(a + b + c) | _ => None } switch (p1, p2, p3) { | (Some(a), Some(b), Some(c)) => Some(mod(a + b + c, 10) == 0) | _ => Some(false) } } else { Some(false) } | PayoutMethodData(SepaIban) => Some(value->String.length > 13 && value->String.length < 34) // Sepa BIC is optional | PayoutMethodData(SepaBic) => Some(true) // Defaults | PayoutMethodData(_) | BillingAddress(_) => value->String.length > 0 ? Some(true) : Some(false) } } let checkValidity = (keys, fieldValidityDict, ~defaultValidity=true) => { keys->Array.reduce(true, (acc, key) => { switch fieldValidityDict->Dict.get(key) { | Some(validity) => acc && validity->Option.getOr(defaultValidity) | None => defaultValidity } }) } let processPaymentMethodDataFields = ( dynamicFieldsInfo: array<dynamicFieldForPaymentMethodData>, paymentMethodDataDict, fieldValidityDict, ) => { let (dynamicFieldsData, dynamicFieldKeys) = dynamicFieldsInfo->Array.reduce(([], []), ( (dataArr, keys), dynamicFieldInfo, ) => { switch dynamicFieldInfo.fieldType { | CardExpDate(CardExpMonth) => { let key = PayoutMethodData(CardExpDate(CardExpMonth)) let info: dynamicFieldInfo = PayoutMethodData(dynamicFieldInfo) let fieldKey = key->getPaymentMethodDataFieldKey paymentMethodDataDict ->Dict.get(fieldKey) ->Option.map(value => { value ->String.split("/") ->Array.get(0) ->Option.map(month => dataArr->Array.push((info, month->String.trim))) }) ->ignore keys->Array.push(fieldKey) (dataArr, keys) } | CardExpDate(CardExpYear) => { let key = PayoutMethodData(CardExpDate(CardExpMonth)) let info: dynamicFieldInfo = PayoutMethodData(dynamicFieldInfo) let fieldKey = key->getPaymentMethodDataFieldKey paymentMethodDataDict ->Dict.get(fieldKey) ->Option.map(value => { value ->String.split("/") ->Array.get(1) ->Option.map(year => dataArr->Array.push((info, `20${year->String.trim}`))) }) ->ignore keys->Array.push(fieldKey) (dataArr, keys) } | _ => { let key = PayoutMethodData(dynamicFieldInfo.fieldType) let info: dynamicFieldInfo = PayoutMethodData(dynamicFieldInfo) let fieldKey = key->getPaymentMethodDataFieldKey paymentMethodDataDict ->Dict.get(fieldKey) ->Option.map(value => dataArr->Array.push((info, value->String.trim))) ->ignore keys->Array.push(fieldKey) (dataArr, keys) } } }) dynamicFieldKeys->checkValidity(fieldValidityDict, ~defaultValidity=false) ? Some(dynamicFieldsData) : None } let processAddressFields = ( dynamicFieldsInfo: array<dynamicFieldForAddress>, paymentMethodDataDict, fieldValidityDict, ) => { let (dynamicFieldsData, dynamicFieldKeys) = dynamicFieldsInfo->Array.reduce(([], []), ( (dataArr, keys), dynamicFieldInfo, ) => { switch dynamicFieldInfo.fieldType { | FullName(FirstName) => { let key = BillingAddress(FullName(FirstName)) let info: dynamicFieldInfo = BillingAddress(dynamicFieldInfo) let fieldKey = key->getPaymentMethodDataFieldKey paymentMethodDataDict ->Dict.get(fieldKey) ->Option.map(value => { value ->String.split(" ") ->Array.get(0) ->Option.map(firstName => dataArr->Array.push((info, firstName))) }) ->ignore keys->Array.push(fieldKey) (dataArr, keys) } | FullName(LastName) => { let key = BillingAddress(FullName(FirstName)) let info: dynamicFieldInfo = BillingAddress(dynamicFieldInfo) let fieldKey = key->getPaymentMethodDataFieldKey paymentMethodDataDict ->Dict.get(fieldKey) ->Option.map(value => { let nameSplits = value->String.split(" ") let lastName = nameSplits ->Array.slice(~start=1, ~end=nameSplits->Array.length) ->Array.joinWith(" ") if lastName->String.length > 0 { dataArr->Array.push((info, lastName)) // Use first name as last name ? } else { nameSplits ->Array.get(0) ->Option.map( firstName => { dataArr->Array.push((info, firstName)) }, ) ->ignore } }) ->ignore keys->Array.push(fieldKey) (dataArr, keys) } | _ => { let key = BillingAddress(dynamicFieldInfo.fieldType) let info: dynamicFieldInfo = BillingAddress(dynamicFieldInfo) let fieldKey = key->getPaymentMethodDataFieldKey paymentMethodDataDict ->Dict.get(fieldKey) ->Option.map(value => dataArr->Array.push((info, value))) ->ignore keys->Array.push(fieldKey) (dataArr, keys) } } }) dynamicFieldKeys->checkValidity(fieldValidityDict, ~defaultValidity=false) ? Some(dynamicFieldsData) : None } let formPaymentMethodData = (paymentMethodDataDict, fieldValidityDict, requiredFields): option< array<(dynamicFieldInfo, string)>, > => { let collectedFields = { let addressFields = requiredFields.address->Option.flatMap(address => processAddressFields(address, paymentMethodDataDict, fieldValidityDict) ) processPaymentMethodDataFields( requiredFields.payoutMethodData, paymentMethodDataDict, fieldValidityDict, )->Option.flatMap(fields => { addressFields ->Option.map(address => address->Array.concat(fields)) ->Option.orElse(Some(fields)) }) } collectedFields } let formBody = (flow: paymentMethodCollectFlow, paymentMethodData: paymentMethodData) => { let (paymentMethodType, fields) = paymentMethodData // Helper function to create nested structure from pmdMap let createNestedStructure = (dict, key, value) => { let keys = key->String.split(".") let rec addToDict = (dict, keys) => { switch keys { | [] => () | [lastKey] => dict->Dict.set(lastKey, JSON.Encode.string(value)) | _ => { let head = keys->Array.get(0)->Option.getOr("") let nestedDict = dict->Dict.get(head)->Option.getOr(Dict.make()->JSON.Encode.object) let newNestedDict = switch nestedDict { | Object(d) => d | _ => Dict.make() } addToDict(newNestedDict, keys->Array.sliceToEnd(~start=1)) dict->Dict.set(head, newNestedDict->JSON.Encode.object) } } } addToDict(dict, keys) } // Process fields let pmdDict = Dict.make() fields->Array.forEach(((fieldInfo, value)) => { switch fieldInfo { | BillingAddress(addressInfo) => createNestedStructure(pmdDict, addressInfo.pmdMap, value) | PayoutMethodData(paymentMethodInfo) => createNestedStructure(pmdDict, paymentMethodInfo.pmdMap, value) } }) let body: array<(string, JSON.t)> = [] // Required fields pmdDict ->Dict.toArray ->Array.map(((key, val)) => { body->Array.push((key, val)) }) ->ignore let paymentMethod = paymentMethodType->getPaymentMethodForPmt // Flow specific fields switch flow { | PayoutMethodCollect => { body->Array.push(("payment_method", paymentMethod->getPaymentMethod->JSON.Encode.string)) body->Array.push(( "payment_method_type", paymentMethodType->getPaymentMethodType->JSON.Encode.string, )) } | PayoutLinkInitiate => body->Array.push(( "payout_type", paymentMethod->getPaymentMethodForPayoutsConfirm->JSON.Encode.string, )) } body } let getPayoutDynamicFields = ( enabledPaymentMethodsWithDynamicFields: array<paymentMethodTypeWithDynamicFields>, reqPmt, ): option<payoutDynamicFields> => enabledPaymentMethodsWithDynamicFields ->Array.find(pmtr => { switch (pmtr, reqPmt) { | (Card(_), Card(_)) | (BankTransfer(ACH, _), BankTransfer(ACH)) | (BankTransfer(Bacs, _), BankTransfer(Bacs)) | (BankTransfer(Pix, _), BankTransfer(Pix)) | (BankTransfer(Sepa, _), BankTransfer(Sepa)) | (Wallet(Paypal, _), Wallet(Paypal)) | (Wallet(Venmo, _), Wallet(Venmo)) => true | _ => false } }) ->Option.map(pmt => { switch pmt { | Card(_, payoutDynamicFields) | BankTransfer(_, payoutDynamicFields) | Wallet(_, payoutDynamicFields) => payoutDynamicFields } }) let getDefaultsAndValidity = payoutDynamicFields => { payoutDynamicFields.address ->Option.map(address => { address->Array.reduce((Dict.make(), Dict.make()), ((values, validity), field) => { switch (field.fieldType, field.value) { | (AddressCountry(countries), None) => countries->Array.get(0) | _ => field.value } ->Option.map( value => { let key = BillingAddress(field.fieldType) let isValid = calculateValidity(key, value) let keyStr = key->getPaymentMethodDataFieldKey values->Dict.set(keyStr, value) validity->Dict.set(keyStr, isValid) (values, validity) }, ) ->Option.getOr({(values, validity)}) }) }) ->Option.map(((addressValues, addressValidity)) => { payoutDynamicFields.payoutMethodData->Array.reduce((addressValues, addressValidity), ( (values, validity), field, ) => { switch field.value { | Some(value) => { let key = PayoutMethodData(field.fieldType) let isValid = calculateValidity(key, value) let keyStr = key->getPaymentMethodDataFieldKey values->Dict.set(keyStr, value) validity->Dict.set(keyStr, isValid) } | None => () } (values, validity) }) }) }
8,482
10,550
hyperswitch-client-core
metro.config.js
.js
const {getDefaultConfig} = require('@react-native/metro-config'); // const exclusionList = require('metro-config/src/defaults/exclusionList'); /** * Metro configuration * https://facebook.github.io/metro/docs/configuration * * @type {import('@react-native/metro-config').MetroConfig} */ const defaultConfig = getDefaultConfig(__dirname); module.exports = { ...defaultConfig, resolver: { ...defaultConfig.resolver, sourceExts: ['bs.js', ...defaultConfig.resolver.sourceExts], }, };
113
10,551
hyperswitch-client-core
tsconfig.json
.json
{ "extends": "@react-native/typescript-config/tsconfig.json", "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "incremental": true, "jsx": "preserve", "paths": { "@/*": ["./*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "exclude": ["node_modules"] }
172
10,552
hyperswitch-client-core
package.json
.json
{ "name": "hyperswitch", "version": "1.1.3", "private": true, "scripts": { "start": "react-native start --reset-cache", "server": "node server.js", "re:start": "rescript build -w", "re:format": "rescript format -all", "web": "NODE_ENV=development webpack serve --mode=development --config reactNativeWeb/webpack.config.js", "web:demo": "concurrently \"yarn web\" \"yarn server\" \"webpack server --mode=development --config reactNativeWeb/DemoApp/webpack.config.js\" ", "bundle": "bundle install && cd ios && bundle exec pod install", "ios": "react-native run-ios", "run:ios": "bundle && react-native run-ios", "android": "react-native run-android --appIdSuffix demoapp --main-activity .demoapp.MainActivity && yarn run adb", "web:next": "cd reactNativeWeb && next", "bundle:android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/hyperswitch.bundle", "bundle:ios": "react-native bundle --platform ios --dev false --entry-file index.js --bundle-output ios/hyperswitchSDK/Core/Resources/hyperswitch.bundle", "build:web": "rm -rf reactNativeWeb/dist/ && webpack --mode=production --config reactNativeWeb/webpack.config.js", "build:lib": "android/build-lib.sh", "clean": "rm -rf node_modules && rm -rf package-lock.json && rm -rf yarn.lock && yarn run clean:gradle && yarn run clean:pod", "re:build": "rescript", "re:check": "rescript build -warn-error +a-4-9", "re:clean": "rescript clean", "pod": "cd ios && pod install && cd ..", "adb": "adb reverse tcp:8081 tcp:8081", "clean:gradle": "cd android && ./gradlew clean && cd ..", "clean:pod": "cd ios && pod deintegrate && cd ..", "clean:gradle:cache": "rm -rf ~/.gradle", "clean:pod:cache": "pod cache clean --all", "deploy-to-s3": "node ./scripts/pushToS3.js", "lint": "eslint .", "test": "jest", "android:e2e": "npx detox test --configuration android.emu.debug --loglevel trace --record-logs all", "build:android-e2e": "npx detox build --configuration android.emu.debug", "build:ios-e2e": "npx detox build --configuration ios.sim.debug", "ios-e2e": "npx detox test --configuration ios.sim.debug --loglevel trace --record-logs all", "prepare": "husky" }, "dependencies": { "@sentry/react-native": "^5.9.1", "pako": "^2.1.0", "react-native-hyperswitch-netcetera-3ds": "^0.1.3", "react-native-hyperswitch-samsung-pay": "^0.1.3", "react-native-hyperswitch-scancard": "^0.3.1", "react-native-inappbrowser-reborn": "^3.7.0", "react-native-klarna-inapp-sdk": "^2.1.13", "react-native-svg": "^15.6.0" }, "devDependencies": { "@babel/core": "^7.25.2", "@babel/eslint-parser": "^7.24.5", "@babel/plugin-proposal-class-properties": "^7.18.6", "@babel/plugin-proposal-decorators": "^7.20.13", "@babel/plugin-proposal-private-methods": "^7.18.6", "@babel/plugin-proposal-private-property-in-object": "^7.20.5", "@babel/preset-env": "^7.25.3", "@babel/runtime": "^7.25.0", "@commitlint/cli": "^17.0.3", "@commitlint/config-conventional": "^17.0.3", "@pmmmwh/react-refresh-webpack-plugin": "^0.5.15", "@react-native-community/cli": "18.0.0", "@react-native-community/cli-platform-android": "18.0.0", "@react-native-community/cli-platform-ios": "18.0.0", "@react-native/babel-preset": "0.79.1", "@react-native/eslint-config": "0.79.1", "@react-native/metro-config": "0.79.1", "@react-native/typescript-config": "0.79.1", "@rescript/core": "^1.5.2", "@rescript/react": "^0.12.1", "@semantic-release/changelog": "^6.0.1", "@semantic-release/commit-analyzer": "^9.0.2", "@semantic-release/git": "^10.0.1", "@semantic-release/npm": "^11.0.1", "@semantic-release/release-notes-generator": "^10.0.3", "@sentry/nextjs": "^7.73.0", "@svgr/webpack": "^6.5.1", "@swc/core": "^1.7.23", "@tsconfig/react-native": "^3.0.0", "@types/jest": "^29.5.13", "@types/pako": "^2", "@types/react": "^19.0.0", "@types/react-test-renderer": "^19.0.0", "babel-jest": "^29.6.3", "babel-loader": "^9.1.3", "babel-plugin-react-native-web": "^0.20.0", "bufferutil": "^4.0.8", "concurrently": "^9.0.1", "cors": "^2.8.5", "cross-env": "^7.0.3", "cz-conventional-changelog": "^3.3.0", "detox": "^20.28.0", "dotenv": "^10.0.0", "esbuild": "^0.23.1", "eslint": "^8.19.0", "eslint-config-next": "^13.5.5", "express": "^4.18.2", "html-webpack-plugin": "^5.6.0", "husky": "^9.0.11", "jest": "^29.6.3", "next": "^14.2.25", "patch-package": "^6.5.1", "prettier": "2.8.8", "react": "19.0.0", "react-content-loader": "^6.2.1", "react-dom": "19.0.0", "react-native": "^0.79.1", "react-native-bundle-visualizer": "^3.1.3", "react-native-dotenv": "^3.4.11", "react-native-web": "^0.20.0", "react-test-renderer": "19.0.0", "rescript": "11", "rescript-react-native": "^0.73.1", "semantic-release": "^22.0.7", "supports-color": "^9.4.0", "swc-loader": "^0.2.3", "terser-webpack-plugin": "^5.3.9", "ts-loader": "^9.5.1", "typescript": "5.0.4", "url-loader": "^4.1.1", "webpack": "^5.93.0", "webpack-cli": "^5.1.4", "webpack-dev-server": "^5.0.4" }, "jest": { "preset": "react-native" }, "config": { "commitizen": { "path": "./node_modules/cz-conventional-changelog", "types": { "feat": { "description": "A new feature", "title": "Features" }, "fix": { "description": "A bug fix", "title": "Bug Fixes" }, "refactor": { "description": "A code change that neither fixes a bug nor adds a feature", "title": "Code Refactoring" }, "chore": { "description": "Other changes that don't modify src or test files", "title": "Chores" }, "docs": { "description": "Documentation only changes", "title": "Documentation" }, "revert": { "description": "Reverts a previous commit", "title": "Reverts" } } } }, "commitlint": { "extends": [ "@commitlint/config-conventional" ] }, "release": { "branches": [ "main", { "name": "release-[0-9]+", "prerelease": true } ], "repositoryUrl": "https://github.com/juspay/hyperswitch-client-core.git", "plugins": [ [ "@semantic-release/commit-analyzer", { "preset": "angular", "releaseRules": [ { "type": "refactor", "release": false }, { "type": "docs", "release": false }, { "type": "chore", "release": false }, { "type": "fix", "release": "patch" }, { "type": "revert", "release": "patch" }, { "type": "feat", "release": "minor" }, { "type": "BREAKING CHANGE", "release": "major" } ] } ], "@semantic-release/release-notes-generator", "@semantic-release/npm", "@semantic-release/changelog", "@semantic-release/git" ] }, "engines": { "node": ">=18" }, "workspaces": [ "detox-tests" ], "packageManager": "[email protected]+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e" }
2,497
10,553
hyperswitch-client-core
lefthook.yml
.yml
# EXAMPLE USAGE: # # Refer for explanation to following link: # https://github.com/evilmartians/lefthook/blob/master/docs/configuration.md # # pre-push: # commands: # packages-audit: # tags: frontend security # run: yarn audit # gems-audit: # tags: backend security # run: bundle audit # # pre-commit: # parallel: true # commands: # eslint: # glob: "*.{js,ts,jsx,tsx}" # run: yarn eslint {staged_files} # rubocop: # tags: backend style # glob: "*.rb" # exclude: "application.rb|routes.rb" # run: bundle exec rubocop --force-exclusion {all_files} # govet: # tags: backend style # files: git ls-files -m # glob: "*.go" # run: go vet {files} # scripts: # "hello.js": # runner: node # "any.go": # runner: go run
241
10,554
hyperswitch-client-core
CHANGELOG.md
.md
## [1.1.3](https://github.com/juspay/hyperswitch-client-core/compare/v1.1.2...v1.1.3) (2025-04-29) ### Bug Fixes * state field error msg fix ([#269](https://github.com/juspay/hyperswitch-client-core/issues/269)) ([d8f8bd7](https://github.com/juspay/hyperswitch-client-core/commit/d8f8bd70736a159daa42f9fc4a3dc37db4f7c9ac)) ## [1.1.2](https://github.com/juspay/hyperswitch-client-core/compare/v1.1.1...v1.1.2) (2025-04-29) ### Bug Fixes * remove popup / use ephemeral web session for card payments ([#267](https://github.com/juspay/hyperswitch-client-core/issues/267)) ([848f57d](https://github.com/juspay/hyperswitch-client-core/commit/848f57d088abd2f66f71a6dbc32507d9ce14b5ff)) ## [1.1.1](https://github.com/juspay/hyperswitch-client-core/compare/v1.1.0...v1.1.1) (2025-04-28) ### Bug Fixes * active opacity issue for picker component ([#262](https://github.com/juspay/hyperswitch-client-core/issues/262)) ([423a780](https://github.com/juspay/hyperswitch-client-core/commit/423a780826fac4c271bf9af231541923145ebd64)) # [1.1.0](https://github.com/juspay/hyperswitch-client-core/compare/v1.0.10...v1.1.0) (2025-03-26) ### Features * **cobadge card, netecetera, hyperota and other changes:** new features ([284e2a0](https://github.com/juspay/hyperswitch-client-core/commit/284e2a08bb0ea905b008a93d0df05e9670dd4ae2)) ## [1.0.10](https://github.com/juspay/hyperswitch-client-core/compare/v1.0.9...v1.0.10) (2025-03-24) ### Bug Fixes * conditionally overwrite threeDSAppRequestorURL for Android ([#249](https://github.com/juspay/hyperswitch-client-core/issues/249)) ([e79664b](https://github.com/juspay/hyperswitch-client-core/commit/e79664b23b4567108fcd54378ebb56d051344def)) ## [1.0.9](https://github.com/juspay/hyperswitch-client-core/compare/v1.0.8...v1.0.9) (2025-03-21) ### Bug Fixes * blocked logs for on prem merchants ([#204](https://github.com/juspay/hyperswitch-client-core/issues/204)) ([59372db](https://github.com/juspay/hyperswitch-client-core/commit/59372db8e3fc3796c8d21c6fa6daa3006886cfd5)) ## [1.0.8](https://github.com/juspay/hyperswitch-client-core/compare/v1.0.7...v1.0.8) (2025-03-21) ### Bug Fixes * sentry ([#250](https://github.com/juspay/hyperswitch-client-core/issues/250)) ([d6f4ac2](https://github.com/juspay/hyperswitch-client-core/commit/d6f4ac253c23d0bfc63df21ddeca15f04bdf37a5)) ## [1.0.7](https://github.com/juspay/hyperswitch-client-core/compare/v1.0.6...v1.0.7) (2025-03-21) ### Bug Fixes * sentry dsn ([#240](https://github.com/juspay/hyperswitch-client-core/issues/240)) ([62b280a](https://github.com/juspay/hyperswitch-client-core/commit/62b280ab3221cdd00dacb938ab96a1988efbd813)) ## [1.0.6](https://github.com/juspay/hyperswitch-client-core/compare/v1.0.5...v1.0.6) (2025-03-21) ### Bug Fixes * removed samsung pay dependency ([11784d7](https://github.com/juspay/hyperswitch-client-core/commit/11784d728dd10b1a83eea550d0d92d6a5fb8546a)) ## [1.0.5](https://github.com/juspay/hyperswitch-client-core/compare/v1.0.4...v1.0.5) (2025-03-21) ### Bug Fixes * updated the regex for cartes Bancaires ([#241](https://github.com/juspay/hyperswitch-client-core/issues/241)) ([f1d7a5c](https://github.com/juspay/hyperswitch-client-core/commit/f1d7a5c00a33a877a2c32ae7f332fd93c04c3866)) ## [1.0.4](https://github.com/juspay/hyperswitch-client-core/compare/v1.0.3...v1.0.4) (2025-03-21) ### Bug Fixes * oob return url for netcetera android ([#246](https://github.com/juspay/hyperswitch-client-core/issues/246)) ([fef4c8f](https://github.com/juspay/hyperswitch-client-core/commit/fef4c8f5943115488ab70ed6d50c3d16247a0d7f)) ## [1.0.3](https://github.com/juspay/hyperswitch-client-core/compare/v1.0.2...v1.0.3) (2025-03-19) ### Bug Fixes * co-badged card selection when priority scheme disabled ([#237](https://github.com/juspay/hyperswitch-client-core/issues/237)) ([e4bcede](https://github.com/juspay/hyperswitch-client-core/commit/e4bcedef082e890e384ffee887f289a47f0ce35d)) ## [1.0.2](https://github.com/juspay/hyperswitch-client-core/compare/v1.0.1...v1.0.2) (2025-03-17) ### Bug Fixes * fixed card brand validation for mastercard ([#243](https://github.com/juspay/hyperswitch-client-core/issues/243)) ([47cc3ac](https://github.com/juspay/hyperswitch-client-core/commit/47cc3ace5654d89dcf2a0f6aa6195aa6e6ad1ef9)) ## [1.0.1](https://github.com/juspay/hyperswitch-client-core/compare/v1.0.0...v1.0.1) (2025-03-16) ### Bug Fixes * global context hierarchy ([#239](https://github.com/juspay/hyperswitch-client-core/issues/239)) ([a2a80b8](https://github.com/juspay/hyperswitch-client-core/commit/a2a80b82e6c15985be75422e39f79199e361898f)) # 1.0.0 (2025-03-07) ### Bug Fixes * active scrollview height ([d3664ac](https://github.com/juspay/hyperswitch-client-core/commit/d3664ac0ef8d17fcd4135147765797b67bbb4549)) * add spaces to last name ([#169](https://github.com/juspay/hyperswitch-client-core/issues/169)) ([1a669c1](https://github.com/juspay/hyperswitch-client-core/commit/1a669c1a3f17ebd87f12b5be8eaa4f157fc99ec9)) * added checkbox for saved payment method screen with conditions t… ([#16](https://github.com/juspay/hyperswitch-client-core/issues/16)) ([7b201c6](https://github.com/juspay/hyperswitch-client-core/commit/7b201c6c66c19482ae066032081f07471719b45a)) * added client_core_version to LoggerUtils ([c6c795b](https://github.com/juspay/hyperswitch-client-core/commit/c6c795b0cc86094b8fb76aa782503b4b1f749361)) * added defaultTick icon for SavedPM ([#152](https://github.com/juspay/hyperswitch-client-core/issues/152)) ([8967a2a](https://github.com/juspay/hyperswitch-client-core/commit/8967a2a5d5d9d13ffd83cc4cc4e5bab5ade7cdd3)) * added Locale support for error messages ([#15](https://github.com/juspay/hyperswitch-client-core/issues/15)) ([ecef552](https://github.com/juspay/hyperswitch-client-core/commit/ecef552422d2ead7bedb63c1aac53082bd24ebe1)) * added locale support for hardcoded wallet description string ([#57](https://github.com/juspay/hyperswitch-client-core/issues/57)) ([e182df9](https://github.com/juspay/hyperswitch-client-core/commit/e182df9460396247a85ff6a5b450f7999f84010a)) * added locale support for saved payment method screen ([#39](https://github.com/juspay/hyperswitch-client-core/issues/39)) ([132d35e](https://github.com/juspay/hyperswitch-client-core/commit/132d35e37bf3107761dd119e21c4069f1c7b7d0a)) * added max cvv length support ([#154](https://github.com/juspay/hyperswitch-client-core/issues/154)) ([36a6c26](https://github.com/juspay/hyperswitch-client-core/commit/36a6c26f738ef9c43404c7d9377c4642d6e3423a)) * added SafeArea top for iOS & removed unused dependencies ([#2](https://github.com/juspay/hyperswitch-client-core/issues/2)) ([a3d7155](https://github.com/juspay/hyperswitch-client-core/commit/a3d7155b9d788076236abe53dd23cee88e908ad7)) * added Scancard and Netcetera as optional dependecy ([4bd0ea8](https://github.com/juspay/hyperswitch-client-core/commit/4bd0ea8708398d3380985685102f98ae55cad7ab)) * added sdk version to logs ([#37](https://github.com/juspay/hyperswitch-client-core/issues/37)) ([d5e1781](https://github.com/juspay/hyperswitch-client-core/commit/d5e17818bd00f3d5108cc4450fe436f628effe71)) * android launch command added and keyboard hack removed ([c20c098](https://github.com/juspay/hyperswitch-client-core/commit/c20c09814ae6d4d5958d00100b1c0dfabb1789c9)) * animation fix on payment sheet ([#3](https://github.com/juspay/hyperswitch-client-core/issues/3)) ([402a6e6](https://github.com/juspay/hyperswitch-client-core/commit/402a6e6be7d097e064f5ba0001c75bb5517807f0)) * appearance fixes ([e62c919](https://github.com/juspay/hyperswitch-client-core/commit/e62c9193de9c982849a38f350d48870bad31c7c8)) * apple pay data collection fix ([3400854](https://github.com/juspay/hyperswitch-client-core/commit/3400854bd134fabd13ae9b62d549096c23e11980)) * applepay appearance fix ([#62](https://github.com/juspay/hyperswitch-client-core/issues/62)) ([0b54035](https://github.com/juspay/hyperswitch-client-core/commit/0b54035b4760b6153c35a64fcde1b119f9065b8b)) * autoComplete text (keyboard flicker) ([b0553bd](https://github.com/juspay/hyperswitch-client-core/commit/b0553bda6d7ddbb89490492ac5476c2d793de10f)) * border-width and radius value fixed ([#161](https://github.com/juspay/hyperswitch-client-core/issues/161)) ([91a35c9](https://github.com/juspay/hyperswitch-client-core/commit/91a35c94aafe72cd554689c40ac39deffc1bf5b5)) * co-badged scheme selection issue ([#226](https://github.com/juspay/hyperswitch-client-core/issues/226)) ([dc1aa18](https://github.com/juspay/hyperswitch-client-core/commit/dc1aa188bcb42ca9414878372af0b6c198bc068f)) * code-push-patch conflict ([990f272](https://github.com/juspay/hyperswitch-client-core/commit/990f272e7212a5984156ac247270f837e0eefa21)) * customer acceptance and nickname was not being sent in confirm p… ([#8](https://github.com/juspay/hyperswitch-client-core/issues/8)) ([aec578d](https://github.com/juspay/hyperswitch-client-core/commit/aec578df92fe5603e3d3e0302774982a2ded80da)) * customer acceptance logic fixes ([37d3c42](https://github.com/juspay/hyperswitch-client-core/commit/37d3c42bf8eddbf77c76d4331cfcc0836818325d)) * customTab height fix ([#166](https://github.com/juspay/hyperswitch-client-core/issues/166)) ([db1fdff](https://github.com/juspay/hyperswitch-client-core/commit/db1fdfff3519862eb9025c11c1b2ac6a860433b4)) * fix error description on input fields ([#53](https://github.com/juspay/hyperswitch-client-core/issues/53)) ([3f7f512](https://github.com/juspay/hyperswitch-client-core/commit/3f7f512bd977d33530e742b3c6f7c3d37d8a1406)) * fix hooks issues ([#9](https://github.com/juspay/hyperswitch-client-core/issues/9)) ([40013b3](https://github.com/juspay/hyperswitch-client-core/commit/40013b36c1afa72f1625050c119918a2f1f75c8b)) * fix: Headless function error handling ([ec453c4](https://github.com/juspay/hyperswitch-client-core/commit/ec453c436adf8be312d535b82b856eb76508e058)) * fixed CardHolderName value and added lanugage support for error messages ([#11](https://github.com/juspay/hyperswitch-client-core/issues/11)) ([fee919f](https://github.com/juspay/hyperswitch-client-core/commit/fee919f09ad2265da31dbe56341b56b87598ae23)) * fixed First Name and Last Name ([#13](https://github.com/juspay/hyperswitch-client-core/issues/13)) ([c7bafbd](https://github.com/juspay/hyperswitch-client-core/commit/c7bafbd08ae9eaaf1a4dbf31bc0868fa0b52950e)) * fixed name not displaying and custom picker should pick initial value ([#12](https://github.com/juspay/hyperswitch-client-core/issues/12)) ([7b61844](https://github.com/juspay/hyperswitch-client-core/commit/7b6184406967054b129c402e998e355e77324848)) * fixed payment sheet and saved payment screen modal texts ([#20](https://github.com/juspay/hyperswitch-client-core/issues/20)) ([b9d3e39](https://github.com/juspay/hyperswitch-client-core/commit/b9d3e39826a7d0fb5e05ea3743cc4794695b700c)) * fixed wrong validation in country state data s3 api call ([#184](https://github.com/juspay/hyperswitch-client-core/issues/184)) ([2695c7a](https://github.com/juspay/hyperswitch-client-core/commit/2695c7a69ef0ebe84e49f3cb0cecbce7bc440aaa)) * flutter-crash-fix ([8469a8d](https://github.com/juspay/hyperswitch-client-core/commit/8469a8db298e1694f9923e65419fe5075af927e6)) * headless edge case ([0fa4a40](https://github.com/juspay/hyperswitch-client-core/commit/0fa4a40e64afd7844fdc9968da150c52752d0b03)) * headless error message ([64ee0e7](https://github.com/juspay/hyperswitch-client-core/commit/64ee0e7fea52e03a8bdbbec5986a2366c78dacf5)) * height Issue fix ([f829f0e](https://github.com/juspay/hyperswitch-client-core/commit/f829f0e70d7c638e273f2ff3d42cd4fcf858ba86)) * infinite Loading Issue fix in various PM ([9961a31](https://github.com/juspay/hyperswitch-client-core/commit/9961a314f9ebf366dbb167a12f6fcb2114f1a18a)) * keyboard dismiss click on tooltip ([2ddacad](https://github.com/juspay/hyperswitch-client-core/commit/2ddacad2578a8264f8c82bae7c210382c46cb5bd)) * keyboard dismiss on tooltip visibility and common logic for padding ([145ace7](https://github.com/juspay/hyperswitch-client-core/commit/145ace7704e0c99e267b09c6637b7e8c1347eaed)) * loading Overlay to stop interaction ([7fc0ff3](https://github.com/juspay/hyperswitch-client-core/commit/7fc0ff374ec7c2ab847e5a22be663aec8cba04bd)) * migrated e2e pipelines to actions v4 ([#203](https://github.com/juspay/hyperswitch-client-core/issues/203)) ([1783713](https://github.com/juspay/hyperswitch-client-core/commit/1783713c38bfef7d2e66712efe555ca9c4eb8c19)) * minimum height added to handle abruptness ([16c5a48](https://github.com/juspay/hyperswitch-client-core/commit/16c5a4899986fba878d8bb264df2b8d444e36c64)) * modal header UI ([#111](https://github.com/juspay/hyperswitch-client-core/issues/111)) ([0ceeed4](https://github.com/juspay/hyperswitch-client-core/commit/0ceeed4a5e967bb16fb9f31e170bf03c78ab2919)) * Modal Header Webview styling ([edc0de8](https://github.com/juspay/hyperswitch-client-core/commit/edc0de84f27af0c6258aab2f72a61bd1e56ab517)) * moved `defaultView` prop from `hyperParams` to `configuration` object ([#216](https://github.com/juspay/hyperswitch-client-core/issues/216)) ([49df0af](https://github.com/juspay/hyperswitch-client-core/commit/49df0af30ef139bd28fb766d625284371fb1aa3c)) * multiple email fields merged ([#200](https://github.com/juspay/hyperswitch-client-core/issues/200)) ([bb2fe34](https://github.com/juspay/hyperswitch-client-core/commit/bb2fe34fefeee8d0279e7cd200430dd9c472894a)) * name and custom picker ([#14](https://github.com/juspay/hyperswitch-client-core/issues/14)) ([d16a09e](https://github.com/juspay/hyperswitch-client-core/commit/d16a09e5e9d86deab0924289733cd52569bf01bd)) * native navigation overlapping with confirm btn ([#170](https://github.com/juspay/hyperswitch-client-core/issues/170)) ([54f2284](https://github.com/juspay/hyperswitch-client-core/commit/54f2284dafb14584a439795a795f7d292e352df2)) * netcetera fixes ([a402755](https://github.com/juspay/hyperswitch-client-core/commit/a402755ab82af62102613ef2a3ca7c9dcb856ff9)) * netcetera initialisation multiple times ([5dacfeb](https://github.com/juspay/hyperswitch-client-core/commit/5dacfebfe6026c1ff82a04f74a20d92aa089a9b8)) * nickname input field and validation ([#191](https://github.com/juspay/hyperswitch-client-core/issues/191)) ([e1d7256](https://github.com/juspay/hyperswitch-client-core/commit/e1d72566110d8441bd3afb763bcd898ec07477ca)) * no change in nickname if user send empty string in nickname field ([#194](https://github.com/juspay/hyperswitch-client-core/issues/194)) ([f4ee5bd](https://github.com/juspay/hyperswitch-client-core/commit/f4ee5bdd9a39c2c2464823c910d4db14269c6617)) * orientation change field breaking fix ([ad1ae58](https://github.com/juspay/hyperswitch-client-core/commit/ad1ae58e1505e8564261a83720b4ca9ad6b0c304)) * padding in scrollview bottomsheet ([#172](https://github.com/juspay/hyperswitch-client-core/issues/172)) ([9799eba](https://github.com/juspay/hyperswitch-client-core/commit/9799ebadf88c39e810ebf956cfbf7522ba703b77)) * patch flutter 1.3.1-patch1 ([297f60b](https://github.com/juspay/hyperswitch-client-core/commit/297f60b02497fefaf49694156ef8c33e2e5bb186)) * payment session call fix ([8f94380](https://github.com/juspay/hyperswitch-client-core/commit/8f943802da884424e851c3df8e852a3ee0c9bcb2)) * pipeline fix ([#205](https://github.com/juspay/hyperswitch-client-core/issues/205)) ([e757455](https://github.com/juspay/hyperswitch-client-core/commit/e7574557af5bb39db5af192abd3a024f517aa35f)) * primary button color fixes ([514b8ff](https://github.com/juspay/hyperswitch-client-core/commit/514b8ff5e1bf347e37543a7f6e17291cd38b5a8b)) * remove leading spaces on nickname input field ([#198](https://github.com/juspay/hyperswitch-client-core/issues/198)) ([1b6a0a2](https://github.com/juspay/hyperswitch-client-core/commit/1b6a0a206e6b67f76684ae70427a97fc90b1a5ae)) * removed error-msg on initial focus ([#159](https://github.com/juspay/hyperswitch-client-core/issues/159)) ([a26e086](https://github.com/juspay/hyperswitch-client-core/commit/a26e086e8de512f2b8ac6c172d6f67fa985efbba)) * removed the focus on confirm click ([#158](https://github.com/juspay/hyperswitch-client-core/issues/158)) ([6a60516](https://github.com/juspay/hyperswitch-client-core/commit/6a60516b43b097f8499123d2cb52eb23035e46d9)) * removing card_holder_name if present in saved cards flow ([#26](https://github.com/juspay/hyperswitch-client-core/issues/26)) ([bc768ce](https://github.com/juspay/hyperswitch-client-core/commit/bc768ce6791ef0cc828e8dbd858829730c74f82a)) * removing plaid dependency temp ([162cfec](https://github.com/juspay/hyperswitch-client-core/commit/162cfece184267cdb27b4f0a93568a776cf6288c)) * rescript compilation errors ([8845fb6](https://github.com/juspay/hyperswitch-client-core/commit/8845fb68e290ea54c004ca1fc1491a8e7a539785)) * revert PR stop progressbar for frictionless flow ([da7a703](https://github.com/juspay/hyperswitch-client-core/commit/da7a703672e852cf415fba10cb912f467a21d5da)) * rounded corner fix ([68ef192](https://github.com/juspay/hyperswitch-client-core/commit/68ef192b055b29d77e676e19dd6215d4d00d2fab)) * save new payment method flow ([#130](https://github.com/juspay/hyperswitch-client-core/issues/130)) ([d62cab9](https://github.com/juspay/hyperswitch-client-core/commit/d62cab9a9a11c31ca5d9958fae657aa47c4da7a8)) * saved pm sorting logic ([4e01c75](https://github.com/juspay/hyperswitch-client-core/commit/4e01c75666a6ee48224f5bb4392e16a55b77ea7a)) * Scrollview keyboardShouldPersistTaps fix ([68c3ed2](https://github.com/juspay/hyperswitch-client-core/commit/68c3ed2e0b400e225e9fd097ce663c7c6d722760)) * sentry initialization removed for Headless Mode ([b545f92](https://github.com/juspay/hyperswitch-client-core/commit/b545f9219e1dd46458996822d9a159cb8639111e)) * sentry initialization removed for Headless Mode ([#17](https://github.com/juspay/hyperswitch-client-core/issues/17)) ([7a89bc3](https://github.com/juspay/hyperswitch-client-core/commit/7a89bc3952f6bc15ec9ba09c0f53cc3b8e01fc31)) * sheet dismiss timeout fixes ([b1cc6e8](https://github.com/juspay/hyperswitch-client-core/commit/b1cc6e842d50a2ca6c3a99eef3007519d483b221)) * stop progressbar for frictionless flow ([6dda2ee](https://github.com/juspay/hyperswitch-client-core/commit/6dda2ee70fc42f49b982253b20a61bec835561d3)) * theme support for Platform Pay Buttons ([e766bf7](https://github.com/juspay/hyperswitch-client-core/commit/e766bf7e82d912bdcfb9498f59d806a188cea364)) * tooltip position correction ([82f7a73](https://github.com/juspay/hyperswitch-client-core/commit/82f7a730f0e388a8320d66eeaeabde5bdcc31138)) * translation for cardHolderName is fixed ([#180](https://github.com/juspay/hyperswitch-client-core/issues/180)) ([ce63430](https://github.com/juspay/hyperswitch-client-core/commit/ce63430d86f318a413db80a1f6b1afd33b1288d6)) * ui and config for pmm ([#109](https://github.com/juspay/hyperswitch-client-core/issues/109)) ([319a65d](https://github.com/juspay/hyperswitch-client-core/commit/319a65d4e632126eac1ebfd3daed3633a026d0da)) * ui interaction for ClickableTextElement ([#160](https://github.com/juspay/hyperswitch-client-core/issues/160)) ([2fa238a](https://github.com/juspay/hyperswitch-client-core/commit/2fa238a8a7c57b7d71774c2366e7cf7187b2995c)) * validation errors on blur for nickname ([#151](https://github.com/juspay/hyperswitch-client-core/issues/151)) ([8991212](https://github.com/juspay/hyperswitch-client-core/commit/89912122f391eb4a1236a3ed57e01a5ed42b505b)) * validation messages for cvv and expiry-date ([#155](https://github.com/juspay/hyperswitch-client-core/issues/155)) ([ed073e4](https://github.com/juspay/hyperswitch-client-core/commit/ed073e4d3323eee614f4f3aed555fe9f8a14b942)) * validation rules for card holder's name and nickname ([#143](https://github.com/juspay/hyperswitch-client-core/issues/143)) ([5e9a5f4](https://github.com/juspay/hyperswitch-client-core/commit/5e9a5f4e61fdcf00fd1b1467672472150216c9c0)) ### Features * added api in demo server to replicate s2s call for pmm ([#122](https://github.com/juspay/hyperswitch-client-core/issues/122)) ([2fbeaf9](https://github.com/juspay/hyperswitch-client-core/commit/2fbeaf9c9df89a6c46ce1e0bb31a71702eaf88b9)) * added card network supported validation ([#189](https://github.com/juspay/hyperswitch-client-core/issues/189)) ([ee551f4](https://github.com/juspay/hyperswitch-client-core/commit/ee551f4200f18752875f846f908bd4b3e165b35a)) * added conditional S3 api call and used local states and countries for gpay and applepay ([#182](https://github.com/juspay/hyperswitch-client-core/issues/182)) ([3c658a1](https://github.com/juspay/hyperswitch-client-core/commit/3c658a194ff0703945b2f24e7c572859c03e4093)) * added cvv field on saved pm screen ([#18](https://github.com/juspay/hyperswitch-client-core/issues/18)) ([805f970](https://github.com/juspay/hyperswitch-client-core/commit/805f970c2a76cf5ee6592613cefeb3d72c6be668)) * added device check and logs ([#215](https://github.com/juspay/hyperswitch-client-core/issues/215)) ([eae1811](https://github.com/juspay/hyperswitch-client-core/commit/eae181132d19172b7c839450b239ae95e541a93e)) * added external 3ds support using netcetera ([#6](https://github.com/juspay/hyperswitch-client-core/issues/6)) ([4007585](https://github.com/juspay/hyperswitch-client-core/commit/4007585f6d4c56795b78a41433001251c819ba44)) * added payment method - EPS ([#54](https://github.com/juspay/hyperswitch-client-core/issues/54)) ([2fe9ccf](https://github.com/juspay/hyperswitch-client-core/commit/2fe9ccf6952ab8ec7b14864b6bb7c8410fa11d48)) * added payment method - sofort ([#60](https://github.com/juspay/hyperswitch-client-core/issues/60)) ([30611c4](https://github.com/juspay/hyperswitch-client-core/commit/30611c4210db39b832e6000a4d4d32b07a67e673)) * added payment method - trustly ([#64](https://github.com/juspay/hyperswitch-client-core/issues/64)) ([2abedcb](https://github.com/juspay/hyperswitch-client-core/commit/2abedcb27c42778eb38d110b296fcb94a7038617)) * added payment method iDEAL ([#59](https://github.com/juspay/hyperswitch-client-core/issues/59)) ([73d62e4](https://github.com/juspay/hyperswitch-client-core/commit/73d62e4035f88987d2b5cd34ccf08b7c47b81298)) * added portal support ([#210](https://github.com/juspay/hyperswitch-client-core/issues/210)) ([4847701](https://github.com/juspay/hyperswitch-client-core/commit/48477015357ab1a6b91581656a6da956595ab1be)) * added react native detox framework for e2e automation ([#165](https://github.com/juspay/hyperswitch-client-core/issues/165)) ([0145a42](https://github.com/juspay/hyperswitch-client-core/commit/0145a4296c0552a272e3e665b282334af1d90fbe)) * added samsung pay ([#112](https://github.com/juspay/hyperswitch-client-core/issues/112)) ([a5056fd](https://github.com/juspay/hyperswitch-client-core/commit/a5056fd7cb48e3726ba45bc667d7551d44285d15)) * added support to collect billing from spay ([#224](https://github.com/juspay/hyperswitch-client-core/issues/224)) ([44c82f4](https://github.com/juspay/hyperswitch-client-core/commit/44c82f4fd18e954132634c88975530140a8e1519)) * added x-redirect-uri in headers ([#91](https://github.com/juspay/hyperswitch-client-core/issues/91)) ([132c714](https://github.com/juspay/hyperswitch-client-core/commit/132c714ad845af0d6a6e39f0e11a4d82e27aab4e)) * android webview sdk ([e1eb7b1](https://github.com/juspay/hyperswitch-client-core/commit/e1eb7b143ba655c4b8202ed773a2867a7bd13f1e)) * api-handler for saving new payment method ([#118](https://github.com/juspay/hyperswitch-client-core/issues/118)) ([1255653](https://github.com/juspay/hyperswitch-client-core/commit/125565341220b68194b1b861e15207abd99b6666)) * apple pay native view ([#24](https://github.com/juspay/hyperswitch-client-core/issues/24)) ([ce305c2](https://github.com/juspay/hyperswitch-client-core/commit/ce305c2c51aa10ce9b457c818b0f9fea492b8ac8)) * blik payment method ([#49](https://github.com/juspay/hyperswitch-client-core/issues/49)) ([2b345c7](https://github.com/juspay/hyperswitch-client-core/commit/2b345c784a0050c2a6efcbd981a4c7c0e5505e0b)) * displayDefaultSavedPaymentIcon prop added ([#22](https://github.com/juspay/hyperswitch-client-core/issues/22)) ([c283af3](https://github.com/juspay/hyperswitch-client-core/commit/c283af385b3e0b6765f7876fa64f9c1b5afb9894)) * googlePay button view ([5e10a05](https://github.com/juspay/hyperswitch-client-core/commit/5e10a05236fdbc75cb6111af3a3bc277f0e39055)) * header for platform added ([95134c3](https://github.com/juspay/hyperswitch-client-core/commit/95134c31ede8dd28c0b6d3377c3abf430b89def0)) * hot reloading for web ([#103](https://github.com/juspay/hyperswitch-client-core/issues/103)) ([09bca1e](https://github.com/juspay/hyperswitch-client-core/commit/09bca1e3734fed30c1a821a4aa1f9178b88d0519)) * moved countries and states to S3 ([#173](https://github.com/juspay/hyperswitch-client-core/issues/173)) ([8c8159f](https://github.com/juspay/hyperswitch-client-core/commit/8c8159f70e87874076895a97365a84c7ae63c838)) * new text wrapper and props for different text types are added ([#19](https://github.com/juspay/hyperswitch-client-core/issues/19)) ([25a457f](https://github.com/juspay/hyperswitch-client-core/commit/25a457f07dbd5567378b0b731e022de12878a4b3)) * plaid sdk pis flow ([#76](https://github.com/juspay/hyperswitch-client-core/issues/76)) ([39665f2](https://github.com/juspay/hyperswitch-client-core/commit/39665f20779944ac17491207bc51b17a8446cd45)) * platformButtons added ([#69](https://github.com/juspay/hyperswitch-client-core/issues/69)) ([3119d79](https://github.com/juspay/hyperswitch-client-core/commit/3119d79121318a286b3c19e2f3f64478646c8501)) * pmm add pm button ([#119](https://github.com/juspay/hyperswitch-client-core/issues/119)) ([db9a2b7](https://github.com/juspay/hyperswitch-client-core/commit/db9a2b73f38ee6b6e5792a0954476d71a32e594d)) * publish automation for android ([#140](https://github.com/juspay/hyperswitch-client-core/issues/140)) ([1820cbb](https://github.com/juspay/hyperswitch-client-core/commit/1820cbb44e681980fca609565df0662ad0f11849)) * router for payment method management ([#93](https://github.com/juspay/hyperswitch-client-core/issues/93)) ([149bd42](https://github.com/juspay/hyperswitch-client-core/commit/149bd42d4260966844ae81894fe53d5741ff6fd8)) ### Reverts * applepay-appearance-fix revert ([#66](https://github.com/juspay/hyperswitch-client-core/issues/66)) ([b0c1200](https://github.com/juspay/hyperswitch-client-core/commit/b0c1200349be35dc6e5e666e32807ca82d3611c9)) ## 1.0.0 2024-04-26 - Initial release
11,400
10,555
hyperswitch-client-core
SECURITY.md
.md
# Security Policy ## Reporting a security issue The hyperswitch project team welcomes security reports and is committed to providing prompt attention to security issues. Security issues should be reported privately via the [advisories page on GitHub][report-vulnerability] or by email at [[email protected]](mailto:[email protected]). Security issues should not be reported via the public GitHub Issue tracker. [report-vulnerability]: https://github.com/juspay/hyperswitch-client-core/security/advisories/
117
10,556
hyperswitch-client-core
LICENSE
none
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
2,252
10,557
hyperswitch-client-core
server.js
.js
const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); app.use(express.static('./dist')); app.use(express.json()); require('dotenv').config({path: './.env'}); const PORT = 5252; async function createPaymentIntent(request) { try { const url = process.env.HYPERSWITCH_SERVER_URL || 'https://sandbox.hyperswitch.io'; const apiResponse = await fetch(`${url}/payments`, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'api-key': process.env.HYPERSWITCH_SECRET_KEY, }, body: JSON.stringify(request), }); const paymentIntent = await apiResponse.json(); if (paymentIntent.error) { console.error('Error - ', paymentIntent.error); throw new Error(paymentIntent.error.message ?? 'Something went wrong.'); } return paymentIntent; } catch (error) { console.error('Failed to create payment intent:', error); throw new Error( error.message || 'Unexpected error occurred while creating payment intent.', ); } } app.get('/create-payment-intent', async (req, res) => { try { const createPaymentBody = { amount: 2999, currency: 'USD', authentication_type: 'no_three_ds', customer_id: 'hyperswitch_demo_id', capture_method: 'automatic', email: '[email protected]', billing: { address: { line1: '1467', line2: 'Harrison Street', line3: 'Harrison Street', city: 'San Fransico', state: 'California', zip: '94122', country: 'US', first_name: 'joseph', last_name: 'Doe', }, }, shipping: { address: { line1: '1467', line2: 'Harrison Street', line3: 'Harrison Street', city: 'San Fransico', state: 'California', zip: '94122', country: 'US', first_name: 'joseph', last_name: 'Doe', }, }, }; const profileId = process.env.PROFILE_ID; if (profileId) { createPaymentBody.profile_id = profileId; } var paymentIntent = await createPaymentIntent(createPaymentBody); // Send publishable key and PaymentIntent details to client res.send({ publishableKey: process.env.HYPERSWITCH_PUBLISHABLE_KEY, clientSecret: paymentIntent.client_secret, }); } catch (err) { console.error(err); return res.status(400).send({ error: { message: err.message, }, }); } }); app.get('/create-ephemeral-key', async (req, res) => { try { const response = await fetch( `https://sandbox.hyperswitch.io/ephemeral_keys`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'api-key': process.env.HYPERSWITCH_SECRET_KEY, }, body: JSON.stringify({customer_id: 'hyperswitch_sdk_demo_id'}), }, ); const ephemeralKey = await response.json(); res.send({ ephemeralKey: ephemeralKey.secret, }); } catch (err) { return res.status(400).send({ error: { message: err.message, }, }); } }); app.get('/payment_methods', async (req, res) => { try { const response = await fetch( `https://sandbox.hyperswitch.io/payment_methods`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'api-key': process.env.HYPERSWITCH_SECRET_KEY, }, body: JSON.stringify({customer_id: 'hyperswitch_sdk_demo_id'}), }, ); const json = await response.json(); res.send({ customerId: json.customer_id, paymentMethodId: json.payment_method_id, clientSecret: json.client_secret, publishableKey: process.env.HYPERSWITCH_PUBLISHABLE_KEY, }); } catch (err) { return res.status(400).send({ error: { message: err.message, }, }); } }); app.get('/netcetera-sdk-api-key', (req, res) => { const apiKey = process.env.NETCETERA_SDK_API_KEY; if (apiKey) { res.status(200).send({netceteraApiKey: apiKey}); } else { res.status(500).send({error: 'Netcetera SDK API key is missing'}); } }); app.listen(PORT, () => console.info(`Node server listening at http://localhost:${PORT}`), );
1,092
10,558
hyperswitch-client-core
rescript.json
.json
{ "name": "hyperswitch", "jsx": {"version": 4}, "package-specs": { "module": "esmodule", "in-source": true }, "bsc-flags": ["-bs-super-errors","-open RescriptCore"], "suffix": ".bs.js", "sources": [ { "dir": "src", "subdirs": true }, { "dir": "reactNativeWeb", "subdirs": true }, { "dir": "./shared-code/sdk-utils", "subdirs": true } ], "bs-dependencies": [ "@rescript/react", "rescript-react-native", "@rescript/core" ] }
167
10,559
hyperswitch-client-core
react-native.config.js
.js
module.exports = { assets: ['./assets/fonts/'], project: { android: { appName: 'demo-app', }, }, };
32
10,560
hyperswitch-client-core
Gemfile
none
source 'https://rubygems.org' # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version ruby ">= 2.6.10" # Exclude problematic versions of cocoapods and activesupport that causes build failures. gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1' gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0' gem 'xcodeproj', '< 1.26.0' gem 'concurrent-ruby', '< 1.3.4' # Ruby 3.4.0 has removed some libraries from the standard library. gem 'bigdecimal' gem 'logger' gem 'benchmark' gem 'mutex_m'
186
10,561
hyperswitch-client-core
app.json
.json
{ "name": "hyperSwitch", "displayName": "hyperswitch", "headless": "HyperHeadless" }
29
10,562
hyperswitch-client-core
README.md
.md
# Hyperswitch Client Core This repository hosts the essential components of the Hyperswitch SDK, which supports various platforms. Directly cloning this repository allows immediate access to a web-compatible version of the SDK. > **Important:** The official Hyperswitch Web SDK is maintained separately. Visit [this link](https://github.com/juspay/hyperswitch-web) for details. The `hyperswitch-client-core` is designed to function within a git submodule framework, facilitating integration with iOS, Android, React Native, Flutter, and Web platforms. ### Setting up the SDK For Android or iOS integration, initialize the necessary submodules using: ```sh git submodule update --init --recursive ``` ### Installing Dependencies To install required dependencies: ```sh yarn install ``` ### Set Environment Variables Rename .en file to .env and input your Hyperswitch API and Publishable Key. Get your Hyperswitch keys from [Hyperswitch dashboard](https://app.hyperswitch.io/dashboard/register) ### Start the server Launch two terminal instances to start the servers: ```sh yarn run server # This starts the mock server yarn run re:start # This initiates the Rescript compiler ``` ### Starting the Metro Server To begin the metro server for native app development: ```sh yarn run start ``` ### Launching the Playground To run the playground, use the following commands based on the target platform: | Platform | Command | | -------- | ------------------ | | Web | `yarn run web` | | Android | `yarn run android` | | iOS | `yarn run ios` | Upon successful setup, your application should be operational on your Android Emulator or iOS Simulator, assuming the emulator or simulator is configured properly. Additionally, the application can be executed directly from Android Studio or Xcode. ### Setup iOS local development The following table outlines the available configuration variables, their values, and descriptions: | Key | Value | Description | | :------------------ | :------------ | :----------------------------------------------- | | `HyperswitchSource` | `LocalHosted` | Load the bundle from the Metro server | | `HyperswitchSource` | `LocalBundle` | Load the bundle from a pre-compiled local bundle | `HyperswitchSource` defaults to `LocalHosted`. ### How to set variables During local development, you may need to set specific variables to configure the SDK's behavior. You can set these variables using Xcode, command line interface (CLI), or any text editor. All changes will be made inside ios folder(submodule). ### Xcode Project > Targets > Info Custom iOS Target Properties ### CLI Alternatively, you can leverage the plutil command to modify the Info.plist file directly from the terminal. For example, to set the HyperswitchSource variable, execute the following command: ```shell plutil -replace HyperswitchSource -string "LocalBundle" Info.plist ``` Info.plist is present in hyperswitch directory. ### Text Editor If you prefer a more manual approach, you can open the Info.plist file in a text editor and add or modify the required keys and their corresponding values. For instance: ``` <key>HyperswitchSource</key> <string>LocalHosted</string> ``` ## Integration Get started with our [📚 integration guides](https://docs.hyperswitch.io/hyperswitch-cloud/integration-guide) ## Licenses - [Hyperswitch Client Core License](LICENSE)
745
10,563
hyperswitch-client-core
index.js
.js
import {AppRegistry} from 'react-native'; import NewApp from './src/routes/Update'; import {name as appName, headless} from './app.json'; import {registerHeadless} from './src/headless/Headless.bs'; AppRegistry.registerComponent(appName, () => NewApp); registerHeadless(headless);
68
10,564
hyperswitch-client-core
App.js
.js
export {make as default} from './src/routes/App.bs.js'; // import {ActivityIndicator, View} from 'react-native'; // export default App = props => { // return ( // <View // style={{ // backgroundColor: // props.props.type == 'card' ? 'transparent' : '#00000070', // flex: 1, // justifyContent: 'center', // }}> // <ActivityIndicator size="large" /> // </View> // ); // };
111
10,565
hyperswitch-client-core
babel.config.js
.js
module.exports = { presets: ['module:@react-native/babel-preset'], plugins: ['module:react-native-dotenv'], };
29
10,566
hyperswitch-client-core
__tests__/App-test.tsx
.tsx
/** * @format */ import 'react-native'; import React from 'react'; import App from '../App'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { renderer.create(<App />); });
59
10,567
hyperswitch-client-core
ota/ios.config.json
.json
{ "config": { "target_platform": "ios", "target_version": "0.2.4", "release_tag_version": "v1.0.6", "release_env": "prod" } }
51
10,568
hyperswitch-client-core
ota/Readme.md
.md
# OTA Configuration Guide Explanation of Configuration Keys - `enable_ota_updates` → Enables or disables OTA updates. When `false`, only Release Config (RC) is updated. `(Optional)` `(default - true)` - `target_platform` → Specifies the platform for the update (`android` or `ios`). - `target_version` → Defines the `platform version`. - `release_tag_version` → Specifies the `Git tag version` used for the build and deployment process. - `enable_rollback` → If `true`, allows rolling back to the previous version in case of failure.`(Optional)` `(default - false)` - `release_config_timeout_ms` → Timeout (in `milliseconds`) for retrieving the release configuration. `(Optional)` `(default - from Config.json)` - `package_timeout_ms` → Timeout (in `milliseconds`) for downloading and applying the application package update. `(Optional)` `(default - from Config.json)` - `release_env` → Specify the release environment [`sandbox` , `prod`] `(Optional)` `(default - sandbox)` - `test` → Enables or disables Test updates for local mobile testing.
238
10,569
hyperswitch-client-core
ota/android.config.json
.json
{ "config": { "target_platform": "android", "target_version": "1.1.2", "release_tag_version": "v1.0.6", "release_env": "prod" } }
51
10,570
hyperswitch-client-core
ota/config.json
.json
{ "config": { "version": "v1", "release_config_timeout": 10000, "package_timeout": 10000, "properties": {} }, "package": { "name": "sdk", "version": "v1.0.0", "properties": { "manifest": {}, "manifest_hash": {} }, "index": "", "splits": [] }, "resources": {} }
107
10,571
hyperswitch-client-core
scripts/pushToS3.js
.js
const { run } = require("./prepareS3.js"); const { version } = require("../reactNativeWeb/version.json"); const path = require("path"); const BASE_PATH = "mobile"; let params = { s3Bucket: process.env.BUCKET_NAME, distributionId: process.env.DIST_ID, urlPrefix: `v${version.split(".")[0]}`, version: `${BASE_PATH}/${version}`, distFolder: path.resolve(__dirname, "..", "reactNativeWeb/dist"), region: process.env.AWS_REGION, }; run(params);
116
10,573
hyperswitch-client-core
scripts/prepareS3.js
.js
const { PutObjectCommand } = require("@aws-sdk/client-s3"); const { CreateInvalidationCommand, GetDistributionConfigCommand, UpdateDistributionCommand, GetInvalidationCommand, CloudFrontClient, } = require("@aws-sdk/client-cloudfront"); const FileSystem = require("fs"); const { globSync } = require("fast-glob"); const Mime = require("mime-types"); const { S3Client } = require("@aws-sdk/client-s3"); const CACHE_CONTROL = "max-age=315360000"; const EXPIRATION_DATE = "Thu, 31 Dec 2037 23:55:55 GMT"; function withSlash(str) { return typeof str === "string" ? `/${str}` : ""; } function withHyphen(str) { return typeof str === "string" ? `${str}-` : ""; } function createCloudFrontClient(region) { return new CloudFrontClient({ region }); } function createS3Client(region) { return new S3Client({ region }); } async function doInvalidation(distributionId, urlPrefix, region, s3Bucket) { const cloudfrontClient = createCloudFrontClient(region); const cloudfrontInvalidationRef = new Date().toISOString(); const cfParams = { DistributionId: distributionId, InvalidationBatch: { CallerReference: cloudfrontInvalidationRef, Paths: { Quantity: s3Bucket === process.env.S3_SANDBOX_BUCKET ? 2 : 1, Items: s3Bucket === process.env.S3_SANDBOX_BUCKET ? [`/mobile${withSlash(urlPrefix)}/*`, `/mobile${withSlash("v0")}/*`] : [`/mobile${withSlash(urlPrefix)}/*`], }, }, }; const command = new CreateInvalidationCommand(cfParams); let response = await cloudfrontClient.send(command); const invalidationId = response.Invalidation.Id; let retryCounter = 0; while (response.Invalidation.Status === "InProgress" && retryCounter < 100) { await new Promise((resolve) => setTimeout(resolve, 3000)); const getInvalidationParams = { DistributionId: distributionId, Id: invalidationId, }; const statusCommand = new GetInvalidationCommand(getInvalidationParams); response = await cloudfrontClient.send(statusCommand); retryCounter++; } if (retryCounter >= 100) { console.log(`Still InProgress after ${retryCounter} retries`); } } async function getDistribution(distributionId, region) { const getDistributionConfigCmd = new GetDistributionConfigCommand({ Id: distributionId, }); const cloudfrontClient = createCloudFrontClient(region); const { DistributionConfig, ETag } = await cloudfrontClient.send( getDistributionConfigCmd ); return { DistributionConfig, ETag }; } async function updateDistribution({ urlPrefix, distributionId, version, DistributionConfig, ETag, region, }) { const cloudfrontClient = createCloudFrontClient(region); let matchingItem; matchingItem = DistributionConfig.Origins.Items.find((item) => item.Id.startsWith("mobile-v1") ); if (matchingItem) { matchingItem.OriginPath = `/${version}`; } else { const defaultItem = DistributionConfig.Origins.Items.find((item) => item.OriginPath === "") || DistributionConfig.Origins.Items[0]; if (defaultItem) { const clonedOrigin = JSON.parse(JSON.stringify(defaultItem)); clonedOrigin.Id = `${withHyphen(urlPrefix)}${clonedOrigin.Id}`; clonedOrigin.OriginPath = `/${version}`; DistributionConfig.Origins.Items.unshift(clonedOrigin); DistributionConfig.Origins.Quantity += 1; if (DistributionConfig.CacheBehaviors.Items.length > 0) { const clonedBehavior = JSON.parse( JSON.stringify(DistributionConfig.CacheBehaviors.Items[0]) ); if (urlPrefix) clonedBehavior.PathPattern = `${urlPrefix}/*`; clonedBehavior.TargetOriginId = clonedOrigin.Id; DistributionConfig.CacheBehaviors.Items.unshift(clonedBehavior); DistributionConfig.CacheBehaviors.Quantity += 1; } } } const updateDistributionCmd = new UpdateDistributionCommand({ DistributionConfig, Id: distributionId, IfMatch: ETag, }); await cloudfrontClient.send(updateDistributionCmd); } async function uploadFile(s3Bucket, version, urlPrefix, distFolder, region) { const entries = globSync(`${distFolder}/**/*`); const s3Client = createS3Client(region); for (const val of entries) { const fileName = val.replace(`${distFolder}/`, ""); const bufferData = FileSystem.readFileSync(val); const mimeType = Mime.lookup(val); const params = { Bucket: s3Bucket, Key: `${version}/mobile${withSlash(urlPrefix)}/${fileName}`, Body: bufferData, Metadata: { "Cache-Control": CACHE_CONTROL, Expires: EXPIRATION_DATE, }, ContentType: mimeType, }; await s3Client.send(new PutObjectCommand(params)); if (s3Bucket === process.env.S3_SANDBOX_BUCKET) { const sandboxParams = { ...params, Key: `${version}/mobile${withSlash("v0")}/${fileName}`, }; await s3Client.send(new PutObjectCommand(sandboxParams)); } console.log(`Successfully uploaded to ${params.Key}`); } } const run = async (params) => { console.log("run parameters ---", params); let { s3Bucket, distributionId, urlPrefix, version, distFolder, region } = params; try { const isVersioned = urlPrefix === "v0" || urlPrefix === "v1"; if (isVersioned) { await uploadFile(s3Bucket, version, "v0", distFolder, region); await uploadFile(s3Bucket, version, "v1", distFolder, region); } else { await uploadFile(s3Bucket, version, urlPrefix, distFolder, region); } if (s3Bucket !== process.env.S3_PROD_BUCKET) { const distributionInfo = await getDistribution(distributionId, region); console.log("distributionInfo completed"); await updateDistribution({ ...distributionInfo, distributionId, urlPrefix, version, region, }); console.log("updateDistribution completed"); if (isVersioned) { await doInvalidation(distributionId, "v0", region, s3Bucket); await doInvalidation(distributionId, "v1", region, s3Bucket); } else { await doInvalidation(distributionId, urlPrefix, region, s3Bucket); } console.log("doInvalidation completed"); } } catch (err) { console.error("Error", err); throw err; } }; module.exports = { run, };
1,516
10,574
hyperswitch-client-core
detox-tests/tsconfig.json
.json
{ "compilerOptions": { "target": "ES2022", "module": "commonjs", }, "include": ["**/*.ts"] }
42
10,575
hyperswitch-client-core
detox-tests/package.json
.json
{ "name": "detox-tests", "version": "1.0.0", "main": "e2e/jest.config.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "@types/jest": "^29.5.14", "@types/node": "^22.10.2", "ts-jest": "^29.2.5", "typescript": "^5.7.2" } }
139
10,576
hyperswitch-client-core
detox-tests/babel.config.js
.js
module.exports = { presets: [ '@babel/preset-env', // Handles modern JavaScript features like `export` ], plugins: [ '@babel/plugin-transform-modules-commonjs', // Transforms ES modules to CommonJS for Jest compatibility ], };
54
10,577
hyperswitch-client-core
detox-tests/e2e/card-flow-e2e.test.ts
.ts
import * as testIds from "../../src/utility/test/TestUtils.bs.js"; import { device } from "detox" import { visaSandboxCard, LAUNCH_PAYMENT_SHEET_BTN_TEXT } from "../fixtures/Constants" import { waitForVisibility, typeTextInInput } from "../utils/DetoxHelpers" describe('card-flow-e2e-test', () => { jest.retryTimes(6); beforeAll(async () => { await device.launchApp({ launchArgs: { detoxEnableSynchronization: 1 }, newInstance: true, }); await device.enableSynchronization(); }); it('demo app should load successfully', async () => { await waitForVisibility(element(by.text(LAUNCH_PAYMENT_SHEET_BTN_TEXT))) }); it('payment sheet should open', async () => { await element(by.text(LAUNCH_PAYMENT_SHEET_BTN_TEXT)).tap(); await waitForVisibility(element(by.text('Test Mode'))) }) it('should enter details in card form', async () => { const cardNumberInput = await element(by.id(testIds.cardNumberInputTestId)) const expiryInput = await element(by.id(testIds.expiryInputTestId)) const cvcInput = await element(by.id(testIds.cvcInputTestId)) await waitFor(cardNumberInput).toExist(); await waitForVisibility(cardNumberInput); await cardNumberInput.tap(); await cardNumberInput.clearText(); await typeTextInInput(cardNumberInput, visaSandboxCard.cardNumber) await waitFor(expiryInput).toExist(); await waitForVisibility(expiryInput); await expiryInput.typeText(visaSandboxCard.expiryDate); await waitFor(cvcInput).toExist(); await waitForVisibility(cvcInput); await cvcInput.typeText(visaSandboxCard.cvc); }); it('should be able to succesfully complete card payment', async () => { const payNowButton = await element(by.id(testIds.payButtonTestId)) await waitFor(payNowButton).toExist(); await waitForVisibility(payNowButton) await payNowButton.tap(); if (device.getPlatform() === "ios") await waitForVisibility(element(by.text('Payment complete'))) else await waitForVisibility(element(by.text('succeeded'))) }) });
476
10,578
hyperswitch-client-core
detox-tests/e2e/jest.config.js
.js
/** @type {import('@jest/types').Config.InitialOptions} */ module.exports = { preset: 'ts-jest', rootDir: '..', testMatch: ['<rootDir>/e2e/**/*.test.ts'], testTimeout: 1200000, maxWorkers: 1, globalSetup: 'detox/runners/jest/globalSetup', globalTeardown: 'detox/runners/jest/globalTeardown', reporters: ['detox/runners/jest/reporter'], testEnvironment: 'detox/runners/jest/testEnvironment', verbose: true, transform: { // Add a transformer for `.bs.js` files '\\.bs\\.js$': 'babel-jest', // or specify a custom transformer if needed }, };
171
10,579
hyperswitch-client-core
detox-tests/fixtures/Constants.ts
.ts
type card = { cardNumber: string, expiryDate: string, cvc: string, } export const visaSandboxCard = { cardNumber: "4242424242424242", expiryDate: "04/44", cvc: "123" } export const LAUNCH_PAYMENT_SHEET_BTN_TEXT = "Launch Payment Sheet"
86
10,580
hyperswitch-client-core
detox-tests/utils/DetoxHelpers.ts
.ts
const DEFAULT_TIMEOUT = 10000; export async function waitForVisibility(element: Detox.IndexableNativeElement, timeout = DEFAULT_TIMEOUT) { await waitFor(element) .toBeVisible() .withTimeout(timeout); } export async function typeTextInInput(element: Detox.IndexableNativeElement, text: string) { device.getPlatform() == "ios" ? await element.typeText(text) : await element.replaceText(text); }
94
10,581
hyperswitch-client-core
src/routes/App.res
.res
open ReactNative open Style module ContextWrapper = { @react.component let make = (~props, ~rootTag, ~children) => { <NativePropContext nativeProp={SdkTypes.nativeJsonToRecord(props, rootTag)}> <LocaleStringDataContext> <CountryStateDataContext> <ViewportContext> <LoadingContext> <PaymentScreenContext> <ThemeContext> <LoggerContext> <CardDataContext> <AllApiDataContext> children </AllApiDataContext> </CardDataContext> </LoggerContext> </ThemeContext> </PaymentScreenContext> </LoadingContext> </ViewportContext> </CountryStateDataContext> </LocaleStringDataContext> </NativePropContext> } } module App = { @react.component let make = () => { <View style={viewStyle(~flex=1., ())}> {WebKit.platform === #android ? <StatusBar translucent=true backgroundColor="transparent" /> : React.null} <NavigatorRouterParent /> </View> } } @react.component let make = (~props, ~rootTag) => { <ErrorBoundary rootTag level=FallBackScreen.Top> <ContextWrapper props rootTag> <PortalHost> <App /> </PortalHost> </ContextWrapper> </ErrorBoundary> }
288
10,582
hyperswitch-client-core
src/routes/NavigatorRouter.res
.res
@react.component let make = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let retrievePayment = AllPaymentHooks.useRetrieveHook() let getSessionToken = AllPaymentHooks.useSessionToken() let savedPaymentMethods = AllPaymentHooks.useGetSavedPMHook() let (allApiData, setAllApiData) = React.useContext(AllApiDataContext.allApiDataContext) let handleSuccessFailure = AllPaymentHooks.useHandleSuccessFailure() let (loading, _) = React.useContext(LoadingContext.loadingContext) let error = ErrorHooks.useErrorWarningValidationOnLoad() let errorOnApiCalls = ErrorHooks.useShowErrorOrWarning() let logger = LoggerHook.useLoggerHook() let handlePMLResponse = retrieve => { PaymentMethodListType.jsonTopaymentMethodListType(retrieve) } let handlePMLAdditionalResponse = retrieve => { let { mandateType, paymentType, merchantName, requestExternalThreeDsAuthentication, } = PaymentMethodListType.jsonToMandateData(retrieve) let redirect_url = PaymentMethodListType.jsonToRedirectUrlType(retrieve) { ...allApiData.additionalPMLData, redirect_url, mandateType, paymentType, merchantName, requestExternalThreeDsAuthentication, } } let handleSessionResponse = session => { let sessionList: AllApiDataContext.sessions = if session->ErrorUtils.isError { if session->ErrorUtils.getErrorCode == "\"IR_16\"" { errorOnApiCalls(ErrorUtils.errorWarning.usedCL, ()) } else if session->ErrorUtils.getErrorCode == "\"IR_09\"" { errorOnApiCalls(ErrorUtils.errorWarning.invalidCL, ()) } None } else if session != JSON.Encode.null { switch session->Utils.getDictFromJson->SessionsType.itemToObjMapper { | Some(sessions) => Some(sessions) | None => None } } else { None } sessionList } React.useEffect1(() => { let launchTime = nativeProp.hyperParams.launchTime->Option.getOr(Date.now()) let latency = Date.now() -. launchTime let appId = nativeProp.hyperParams.appId->Option.getOr("") ++ ".hyperswitch://" logger(~logType=INFO, ~value=appId, ~category=USER_EVENT, ~eventName=APP_RENDERED, ~latency, ()) error() //KountModule.launchKountIfAvailable(nativeProp.clientSecret, _x => ()) if nativeProp.clientSecret != "" && nativeProp.publishableKey != "" { Promise.all3(( retrievePayment(List, nativeProp.clientSecret, nativeProp.publishableKey), savedPaymentMethods(), getSessionToken(), )) ->Promise.then(((paymentMethodListData, customerSavedPMData, sessionTokenData)) => { if ErrorUtils.isError(paymentMethodListData) { errorOnApiCalls( INVALID_PK((Error, Static(ErrorUtils.getErrorMessage(paymentMethodListData)))), (), ) } else if paymentMethodListData == JSON.Encode.null { handleSuccessFailure(~apiResStatus=PaymentConfirmTypes.defaultConfirmError, ()) } else { let paymentList = handlePMLResponse(paymentMethodListData) let additionalPMLData = handlePMLAdditionalResponse(paymentMethodListData) let sessions = handleSessionResponse(sessionTokenData) let savedPaymentMethods = PMLUtils.handleCustomerPMLResponse( ~customerSavedPMData, ~sessions, ~isPaymentMethodManagement=false, ~nativeProp, ) setAllApiData({ paymentList, additionalPMLData, sessions, savedPaymentMethods, }) let latency = Date.now() -. launchTime logger( ~logType=INFO, ~value="Loaded", ~category=USER_EVENT, ~eventName=LOADER_CHANGED, ~latency, (), ) } Promise.resolve() }) ->ignore } None }, [nativeProp]) BackHandlerHook.useBackHandler(~loading, ~sdkState=nativeProp.sdkState) { switch nativeProp.sdkState { | PaymentSheet => <ParentPaymentSheet /> | HostedCheckout => <HostedCheckout /> | CardWidget => <CardWidget /> | CustomWidget(walletType) => <CustomWidget walletType /> | ExpressCheckoutWidget => <ExpressCheckoutWidget /> | WidgetPaymentSheet => <ParentPaymentSheet /> | Headless | NoView | PaymentMethodsManagement => React.null } } }
1,004
10,583
hyperswitch-client-core
src/routes/AppExports.js
.js
export {make as default} from './App.bs.js'; // import {ActivityIndicator, View} from 'react-native'; // export default App = props => { // return ( // <View // style={{ // backgroundColor: // props.props.type == 'card' ? 'transparent' : '#00000070', // flex: 1, // justifyContent: 'center', // }}> // <ActivityIndicator size="large" /> // </View> // ); // };
109
10,584
hyperswitch-client-core
src/routes/NavigatorRouterParent.res
.res
@react.component let make = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) switch nativeProp.sdkState { | PaymentMethodsManagement => <PMMangementNavigatorRouter /> | _ => <NavigatorRouter /> } }
60
10,585
hyperswitch-client-core
src/routes/PMMangementNavigatorRouter.res
.res
@react.component let make = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let (allApiData, setAllApiData) = React.useContext(AllApiDataContext.allApiDataContext) let showErrorOrWarning = ErrorHooks.useShowErrorOrWarning() let savedPaymentMethods = AllPaymentHooks.useGetSavedPMHook() let logger = LoggerHook.useLoggerHook() React.useEffect(() => { let launchTime = nativeProp.hyperParams.launchTime->Option.getOr(Date.now()) let latency = Date.now() -. launchTime let appId = nativeProp.hyperParams.appId->Option.getOr("") ++ ".hyperswitch://" logger(~logType=INFO, ~value=appId, ~category=USER_EVENT, ~eventName=APP_RENDERED, ~latency, ()) if nativeProp.ephemeralKey->Option.getOr("") != "" { savedPaymentMethods() ->Promise.then(customerSavedPMData => { let savedPaymentMethods = PMLUtils.handleCustomerPMLResponse( ~customerSavedPMData, ~sessions=None, ~isPaymentMethodManagement=true, ~nativeProp, ) setAllApiData({ ...allApiData, savedPaymentMethods, }) Promise.resolve() }) ->ignore } None }, [nativeProp]) switch nativeProp.ephemeralKey { | Some(ephemeralKey) => ephemeralKey != "" ? <PaymentMethodsManagement /> : { showErrorOrWarning(ErrorUtils.errorWarning.invalidEphemeralKey, ()) React.null } | None => showErrorOrWarning(ErrorUtils.errorWarning.invalidEphemeralKey, ()) React.null } }
381
10,586
hyperswitch-client-core
src/routes/GlobalConfirmButton.res
.res
open ReactNative @react.component let make = (~confirmButtonDataRef) => { <View> {confirmButtonDataRef} </View> }
33
10,587
hyperswitch-client-core
src/routes/ParentPaymentSheet.res
.res
open SDKLoadCheckHook module SdkLoadingScreen = { @react.component let make = () => { <> <Space height=20. /> <CustomLoader height="38" /> <Space height=8. /> <CustomLoader height="38" /> <Space height=50. /> <CustomLoader height="38" /> </> } } @react.component let make = () => { let (paymentScreenType, _) = React.useContext(PaymentScreenContext.paymentScreenTypeContext) let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let (allApiData, _) = React.useContext(AllApiDataContext.allApiDataContext) let (confirmButtonDataRef, setConfirmButtonDataRef) = React.useState(_ => React.null) let setConfirmButtonDataRef = React.useCallback1(confirmButtonDataRef => { setConfirmButtonDataRef(_ => confirmButtonDataRef) }, [setConfirmButtonDataRef]) let enablePartialLoading = nativeProp.configuration.enablePartialLoading let canLoadSDK = useSDKLoadCheck(~enablePartialLoading) <FullScreenSheetWrapper> {switch (allApiData.savedPaymentMethods, allApiData.additionalPMLData.paymentType, canLoadSDK) { | (_, _, false) => <SdkLoadingScreen /> | (Loading, _, _) => nativeProp.configuration.defaultView ? <PaymentSheet setConfirmButtonDataRef /> : <SdkLoadingScreen /> | (Some(data), _, _) => paymentScreenType == PaymentScreenContext.SAVEDCARDSCREEN && data.pmList->Option.getOr([])->Array.length > 0 && allApiData.additionalPMLData.mandateType !== SETUP_MANDATE ? <SavedPaymentScreen setConfirmButtonDataRef savedPaymentMethordContextObj=data /> : <PaymentSheet setConfirmButtonDataRef /> | (None, _, _) => <PaymentSheet setConfirmButtonDataRef /> }} <GlobalConfirmButton confirmButtonDataRef /> <Space height=15. /> </FullScreenSheetWrapper> }
457
10,588
hyperswitch-client-core
src/routes/Update.js
.js
import React from 'react'; import App from './AppExports.js'; import { sentryReactNative, initiateSentry, } from '../components/modules/Sentry.bs.js'; const NewApp = props => { return ( <App props={props.props} rootTag={props.rootTag} /> ); }; const SentryApp = React.memo(props => { initiateSentry(process.env.SENTRY_DSN, process.env.SENTRY_ENV); return sentryReactNative.wrap(NewApp)(props); }); export default ( SentryApp );
117
10,589
hyperswitch-client-core
src/routes/FullScreenSheetWrapper.res
.res
open ReactNative open Style @react.component let make = (~children) => { let (loading, setLoading) = React.useContext(LoadingContext.loadingContext) let handleSuccessFailure = AllPaymentHooks.useHandleSuccessFailure() let onModalClose = React.useCallback0(() => { setLoading(PaymentCancelled) setTimeout(() => { handleSuccessFailure( ~apiResStatus=PaymentConfirmTypes.defaultCancelError, ~closeSDK=true, ~reset=false, (), ) }, 300)->ignore }) let {paymentSheetOverlay} = ThemebasedStyle.useThemeBasedStyle() let (sheetFlex, _) = React.useState(_ => Animated.Value.create(0.)) React.useEffect0(() => { Animated.timing( sheetFlex, { toValue: {1.->Animated.Value.Timing.fromRawValue}, isInteraction: true, useNativeDriver: false, }, )->Animated.start() None }) let (heightPosition, _) = React.useState(_ => Animated.Value.create(0.)) React.useEffect1(() => { if loading == LoadingContext.PaymentCancelled || loading == LoadingContext.PaymentSuccess { Animated.timing( heightPosition, { toValue: { 1000.->Animated.Value.Timing.fromRawValue }, isInteraction: true, useNativeDriver: false, delay: 0., duration: 300., easing: Easing.linear, }, )->Animated.start() } None }, [loading]) <View style={viewStyle( ~flex=1., ~alignContent=#"flex-end", ~backgroundColor=paymentSheetOverlay, ~justifyContent=#"flex-end", ~paddingTop=48.->dp, (), )}> <Animated.View style={viewStyle( ~transform=[translateY(~translateY=heightPosition->Animated.StyleProp.float)], ~flexGrow={sheetFlex->Animated.StyleProp.float}, (), )}> <CustomView onDismiss=onModalClose> <CustomView.Wrapper onModalClose> {children} </CustomView.Wrapper> </CustomView> </Animated.View> <LoadingOverlay /> </View> }
495
10,590
hyperswitch-client-core
src/types/PaymentConfirmTypes.res
.res
// type redirectToUrl = { // returnUrl: string, // url: string, // } type pollConfig = { pollId: string, delayInSecs: int, frequency: int, } type threeDsData = { threeDsAuthenticationUrl: string, threeDsAuthorizeUrl: string, messageVersion: string, directoryServerId: string, pollConfig: pollConfig, } type sessionToken = { wallet_name: string, open_banking_session_token: string, } type nextAction = { redirectToUrl: string, type_: string, threeDsData?: threeDsData, session_token?: sessionToken, } type error = {message?: string, code?: string, type_?: string, status?: string} type intent = {nextAction: nextAction, status: string, error: error} open Utils let defaultNextAction = { redirectToUrl: "", type_: "", } let defaultConfirmError = { type_: "", status: "failed", code: "confirmPayment failed", message: "An unknown error has occurred please retry", } let defaultCancelError = { type_: "", status: "cancelled", code: "", message: "", } let getNextAction = (dict, str) => { dict ->Dict.get(str) ->Option.flatMap(JSON.Decode.object) ->Option.map(json => { let threeDSDataDict = json ->Dict.get("three_ds_data") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.object ->Option.getOr(Dict.make()) let pollConfigDict = threeDSDataDict ->Dict.get("poll_config") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.object ->Option.getOr(Dict.make()) let sessionTokenDict = json ->Dict.get("session_token") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.object ->Option.getOr(Dict.make()) { redirectToUrl: getString(json, "redirect_to_url", ""), type_: getString(json, "type", ""), threeDsData: { threeDsAuthorizeUrl: getString(threeDSDataDict, "three_ds_authorize_url", ""), threeDsAuthenticationUrl: getString(threeDSDataDict, "three_ds_authentication_url", ""), messageVersion: getString(threeDSDataDict, "message_version", ""), directoryServerId: getString(threeDSDataDict, "directory_server_id", ""), pollConfig: { pollId: getString(pollConfigDict, "poll_id", ""), delayInSecs: getOptionFloat(pollConfigDict, "delay_in_secs") ->Option.getOr(0.) ->Int.fromFloat, frequency: getOptionFloat(pollConfigDict, "frequency")->Option.getOr(0.)->Int.fromFloat, }, }, session_token: { wallet_name: getString(sessionTokenDict, "wallet_name", ""), open_banking_session_token: getString(sessionTokenDict, "open_banking_session_token", ""), }, } }) ->Option.getOr(defaultNextAction) } let itemToObjMapper = dict => { let errorDict = Dict.get(dict, "error") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.object ->Option.getOr(Dict.make()) { nextAction: getNextAction(dict, "next_action"), status: getString(dict, "status", ""), error: { message: getString( errorDict, "message", getString(dict, "error_message", getString(dict, "error", "confirmPayment failed")), ), code: getString(errorDict, "code", getString(dict, "error_code", "")), type_: getString(errorDict, "type", getString(dict, "type", "confirmPayment failed")), status: getString(dict, "status", "failed"), }, } } type responseFromJava = { paymentMethodData: string, clientSecret: string, paymentMethodType: string, publishableKey: string, error: string, confirm: bool, } let itemToObjMapperJava = dict => { { paymentMethodData: getString(dict, "paymentMethodData", ""), clientSecret: getString(dict, "clientSecret", ""), paymentMethodType: getString(dict, "paymentMethodType", ""), publishableKey: getString(dict, "publishableKey", ""), error: getString(dict, "error", ""), confirm: getBool(dict, "confirm", false), } }
968
10,591
hyperswitch-client-core
src/types/Types.res
.res
type redirectTypeJson = { name: string, text: string, header: string, fields: array<string>, } type retrieve = Payment | List let defaultRedirectType = { name: "", text: "", header: "", fields: [], } type config = { priorityArr: array<string>, redirectionList: array<redirectTypeJson>, } let defaultConfig = { priorityArr: { let priorityArr = ["card", "klarna", "afterpay_clearpay", "crypto", "paypal", "google_pay"] priorityArr->Array.reverse priorityArr }, redirectionList: [ { name: "klarna", text: "Klarna", header: "", fields: ["email", "country"], }, { name: "afterpay_clearpay", text: "AfterPay", header: "", fields: ["email", "name"], }, { name: "affirm", text: "Affirm", header: "", fields: ["email"], }, { name: "ali_pay", text: "Alipay", header: "", fields: [], }, { name: "eps", text: "EPS", header: "", fields: ["bank"], }, { name: "we_chat_pay", text: "WeChat Pay", header: "", fields: [], }, { name: "blik", text: "Blik", header: "", fields: ["blik_code"], }, { name: "ideal", text: "iDEAL", header: "", fields: [], }, { name: "crypto", text: "Crypto", header: "", fields: ["name"], }, { name: "trustly", text: "Trustly", header: "", fields: ["country"], }, { name: "sofort", text: "Sofort", header: "", fields: [], }, { name: "open_banking_pis", text: "Open Banking", header: "", fields: [], }, { name: "becs", text: "BECS Debit", header: "", fields: [], }, // { // name: "google_pay", // text: "Google Pay", // header: "", // fields: ["name"], // }, // { // name: "apple_pay", // text: "Apple Pay", // header: "", // fields: ["name"], // }, ], }
582
10,592
hyperswitch-client-core
src/types/ConfirmButtonType.res
.res
type setChildRef = ( ~isAllValuesValid: bool, ~handlePress: ReactNative.Event.pressEvent => unit, ~hasSomeFields: bool=?, ~paymentMethod: string, ~paymentExperience: PaymentMethodListType.payment_experience_type=?, unit, ) => unit
65
10,593
hyperswitch-client-core
src/types/RequiredFieldsTypes.res
.res
@val external importStatesAndCountries: string => promise<JSON.t> = "import" type addressCountry = UseContextData | UseBackEndData(array<string>) type payment_method_types_in_bank_debit = BECS | Other type paymentMethodsFields = | Email | FullName | InfoElement | Country | Bank | SpecialField(React.element) | UnKnownField(string) | BillingName | ShippingName | PhoneNumber | AddressLine1 | AddressLine2 | AddressCity | StateAndCity | CountryAndPincode(array<string>) | AddressPincode | AddressState | AddressCountry(addressCountry) | BlikCode | Currency(array<string>) | AccountNumber | BSBNumber | PhoneCountryCode type requiredField = | StringField(string) | FullNameField(string, string) type required_fields_type = { required_field: requiredField, display_name: string, field_type: paymentMethodsFields, value: string, } type required_fields = array<required_fields_type> let getRequiredFieldName = (requiredField: requiredField) => { switch requiredField { | StringField(name) => name | FullNameField(firstName, _lastName) => firstName } } let getPaymentMethodsFieldTypeFromString = str => { switch str { | "user_email_address" => Email | "user_full_name" => FullName | "user_country" | "country" => Country | "user_bank" => Bank | "user_phone_number" => PhoneNumber | "user_phone_number_country_code" => PhoneCountryCode | "user_address_line1" | "user_shipping_address_line1" => AddressLine1 | "user_address_line2" | "user_shipping_address_line2" => AddressLine2 | "user_address_city" | "user_shipping_address_city" => AddressCity | "user_address_pincode" | "user_shipping_address_pincode" => AddressPincode | "user_address_state" | "user_shipping_address_state" => AddressState | "user_blik_code" => BlikCode | "user_billing_name" => BillingName | "user_shipping_name" => ShippingName | "user_bank_account_number" => AccountNumber | "user_bsb_number" => BSBNumber | var => UnKnownField(var) } } let getArrayValFromJsonDict = (dict, key) => { dict ->JSON.Decode.object ->Option.getOr(Dict.make()) ->Dict.get(key) ->Option.flatMap(JSON.Decode.array) ->Option.getOr([]) ->Array.filterMap(JSON.Decode.string) } let getPaymentMethodsFieldTypeFromDict = (dict: Dict.t<JSON.t>) => { switch ( dict->Dict.get("user_currency"), dict->Dict.get("user_address_country"), dict->Dict.get("user_country"), dict->Dict.get("user_shipping_address_country"), ) { | (Some(user_currency), _, _, _) => let options = user_currency->getArrayValFromJsonDict("options") Currency(options) | (_, Some(user_address_country), _, _) | (_, _, Some(user_address_country), _) => let options = user_address_country->getArrayValFromJsonDict("options") switch options->Array.get(0)->Option.getOr("") { | "" => UnKnownField("empty_list") | "ALL" => AddressCountry(UseContextData) | _ => AddressCountry(UseBackEndData(options)) } | (_, _, _, Some(user_shipping_address_country)) => let options = user_shipping_address_country->getArrayValFromJsonDict("options") switch options->Array.get(0)->Option.getOr("") { | "" => UnKnownField("empty_list") | "ALL" => AddressCountry(UseContextData) | _ => AddressCountry(UseBackEndData(options)) } | _ => UnKnownField("empty_list") } } let getFieldType = dict => { let fieldClass = dict->Dict.get("field_type")->Option.getOr(JSON.Encode.null)->JSON.Classify.classify switch fieldClass { | String(val) => val->getPaymentMethodsFieldTypeFromString | Object(dict) => dict->getPaymentMethodsFieldTypeFromDict | _ => UnKnownField("unknown_field_type") } } let getPaymentMethodsFieldsOrder = paymentMethodField => { switch paymentMethodField { | FullName | ShippingName | BillingName => 1 | AccountNumber => -1 | Email => 2 | BSBNumber => 3 | AddressLine1 => 4 | AddressLine2 => 5 | AddressCity => 6 | AddressCountry(_) => 7 | AddressState => 8 | StateAndCity => 9 | CountryAndPincode(_) => 10 | AddressPincode => 11 | InfoElement => 99 | _ => 0 } } let sortRequirFields = ( firstPaymentMethodField: required_fields_type, secondPaymentMethodField: required_fields_type, ) => { if firstPaymentMethodField.field_type === secondPaymentMethodField.field_type { let requiredFieldsPath = firstPaymentMethodField.required_field->getRequiredFieldName->String.split(".") let fieldName = requiredFieldsPath ->Array.get(requiredFieldsPath->Array.length - 1) ->Option.getOr("") switch fieldName { | "first_name" => -1 | "last_name" => 1 | _ => 0 } } else { firstPaymentMethodField.field_type->getPaymentMethodsFieldsOrder - secondPaymentMethodField.field_type->getPaymentMethodsFieldsOrder } } let mergeNameFields = (arr, ~fieldType, ~displayName=?) => { let nameFields = arr->Array.filter(requiredField => { requiredField.field_type === fieldType && displayName ->Option.map(displayName => requiredField.display_name === displayName) ->Option.getOr(true) }) switch (nameFields[0], nameFields[1]) { | (Some(firstNameField), Some(lastNameField)) => let value = switch (firstNameField.value, lastNameField.value) { | (firstNameValue, "") => firstNameValue | ("", lastNameValue) => lastNameValue | (firstNameValue, lastNameValue) => [firstNameValue, lastNameValue]->Array.join(" ") } arr->Array.filterMap(x => { if x === firstNameField { { ...x, required_field: FullNameField( firstNameField.required_field->getRequiredFieldName, lastNameField.required_field->getRequiredFieldName, ), value, }->Some } else if x === lastNameField { None } else { Some(x) } }) | _ => arr } } let getRequiredFieldsFromDict = dict => { let requiredFields = dict->Dict.get("required_fields")->Option.flatMap(JSON.Decode.object) switch requiredFields { | Some(val) => let arr = val ->Dict.valuesToArray ->Array.map(item => { let itemToObj = item->JSON.Decode.object->Option.getOr(Dict.make()) { required_field: Utils.getString(itemToObj, "required_field", "")->StringField, display_name: Utils.getString(itemToObj, "display_name", ""), field_type: itemToObj->getFieldType, value: Utils.getString(itemToObj, "value", ""), } }) ->Belt.SortArray.stableSortBy(sortRequirFields) arr ->mergeNameFields(~fieldType=FullName) ->mergeNameFields(~fieldType=FullName, ~displayName="card_holder_name") ->mergeNameFields(~fieldType=Email) ->mergeNameFields(~fieldType=BillingName) ->mergeNameFields(~fieldType=ShippingName) | _ => [] } } let getErrorMsg = ( ~field_type: paymentMethodsFields, ~localeObject: LocaleDataType.localeStrings, ) => { switch field_type { | AddressLine1 => localeObject.line1EmptyText | AddressCity => localeObject.cityEmptyText | AddressPincode => localeObject.postalCodeEmptyText | Email => localeObject.emailEmptyText | _ => localeObject.mandatoryFieldText } } let numberOfDigitsValidation = ( ~text, ~localeObject: LocaleDataType.localeStrings, ~digits, ~display_name, ) => { if text->Validation.containsOnlyDigits && text->Validation.clearSpaces->String.length > 0 { if text->String.length == digits { None } else { Some( localeObject.enterValidDigitsText ++ " " ++ digits->Int.toString ++ localeObject.digitsText ++ " " ++ display_name->Option.getOr("")->Utils.underscoresToSpaces, ) } } else { Some(localeObject.enterValidDetailsText) } } let checkIsValid = ( ~text: string, ~field_type: paymentMethodsFields, ~localeObject: LocaleDataType.localeStrings, ~paymentMethodType: option<payment_method_types_in_bank_debit>, ~display_name=?, ) => { if text == "" { getErrorMsg(~field_type, ~localeObject)->Some } else { switch field_type { | Email => switch text->EmailValidation.isEmailValid { | Some(false) => Some(localeObject.emailInvalidText) | Some(true) => None | None => Some(localeObject.emailEmptyText) } | AccountNumber => switch paymentMethodType { | Some(BECS) => numberOfDigitsValidation(~text, ~localeObject, ~digits=9, ~display_name) | _ => None } | BSBNumber => numberOfDigitsValidation(~text, ~localeObject, ~digits=6, ~display_name) | _ => None } } } let allowOnlyDigits = ( ~text, ~fieldType, ~prev, ~paymentMethodType: option<payment_method_types_in_bank_debit>, ) => { let val = text->Option.getOr("")->Validation.clearSpaces switch fieldType { | AccountNumber => switch paymentMethodType { | Some(BECS) => if val->String.length <= 9 { Some(val) } else { prev } | _ => None } | BSBNumber => if val->String.length <= 6 { Some(val) } else { prev } | _ => text } } let getKeyboardType = (~field_type: paymentMethodsFields) => { switch field_type { | Email => #"email-address" | AccountNumber => #"number-pad" | BSBNumber => #"number-pad" | _ => #default } } let toCamelCase = str => { str ->String.split("_") ->Array.map(item => { let arr = item->String.split("") let firstChar = arr->Array.get(0)->Option.getOr("")->String.toUpperCase [firstChar]->Array.concat(arr->Array.sliceToEnd(~start=1))->Array.join("") }) ->Array.join(" ") } let useGetPlaceholder = ( ~field_type: paymentMethodsFields, ~display_name: string, ~required_field: requiredField, ) => { let localeObject = GetLocale.useGetLocalObj() let getName = placeholder => { let requiredFieldsPath = required_field->getRequiredFieldName->String.split(".") let fieldName = requiredFieldsPath ->Array.get(requiredFieldsPath->Array.length - 1) ->Option.getOr("") switch field_type { | FullName => if display_name === "card_holder_name" { localeObject.cardHolderName } else { switch fieldName { | "first_name" => localeObject.fullNameLabel | "last_name" => localeObject.fullNameLabel | "card_holder_name" => localeObject.cardHolderName | _ => placeholder } } | BillingName => localeObject.billingNameLabel | ShippingName => localeObject.fullNamePlaceholder | _ => placeholder } } () => switch field_type { | Email => localeObject.emailLabel | FullName => localeObject.fullNamePlaceholder->getName | ShippingName => localeObject.fullNamePlaceholder->getName | Country => localeObject.countryLabel | Bank => localeObject.bankLabel | BillingName => localeObject.fullNamePlaceholder->getName | AddressLine1 => localeObject.line1Placeholder | AddressLine2 => localeObject.line2Placeholder | AddressCity => localeObject.cityLabel | AddressPincode => localeObject.postalCodeLabel | AddressState => localeObject.stateLabel | AddressCountry(_) => localeObject.countryLabel | Currency(_) => localeObject.currencyLabel | InfoElement => localeObject.mandatoryFieldText // | ShippingCountry(_) => localeObject.countryLabel // | ShippingAddressLine1 => localeObject.line1Placeholder // | ShippingAddressLine2 => localeObject.line2Placeholder // | ShippingAddressCity => localeObject.cityLabel // | ShippingAddressPincode => localeObject.postalCodeLabel // | ShippingAddressState => localeObject.stateLabel | PhoneCountryCode | SpecialField(_) | AccountNumber | BSBNumber | UnKnownField(_) | PhoneNumber | StateAndCity | CountryAndPincode(_) | BlikCode => display_name->toCamelCase } } let rec flattenObject = (obj, addIndicatorForObject) => { let newDict = Dict.make() switch obj->JSON.Decode.object { | Some(obj) => obj ->Dict.toArray ->Array.forEach(entry => { let (key, value) = entry if value === JSON.Null { Dict.set(newDict, key, value) } else { switch value->JSON.Decode.object { | Some(_valueObj) => { if addIndicatorForObject { Dict.set(newDict, key, JSON.Encode.object(Dict.make())) } let flattenedSubObj = flattenObject(value, addIndicatorForObject) flattenedSubObj ->Dict.toArray ->Array.forEach(subEntry => { let (subKey, subValue) = subEntry Dict.set(newDict, `${key}.${subKey}`, subValue) }) } | None => Dict.set(newDict, key, value) } } }) | _ => () } newDict } let rec setNested = (dict, keys, value) => { switch keys->Array.get(0) { | Some(currKey) => if keys->Array.length === 1 { Dict.set(dict, currKey, value) } else { let subDict = switch Dict.get(dict, currKey) { | Some(json) => switch json->JSON.Decode.object { | Some(obj) => obj | None => dict } | None => { let subDict = Dict.make() Dict.set(dict, currKey, subDict->JSON.Encode.object) subDict } } let remainingKeys = keys->Array.sliceToEnd(~start=1) setNested(subDict, remainingKeys, value) } | None => () } } let unflattenObject = obj => { let newDict = Dict.make() switch obj->JSON.Decode.object { | Some(dict) => dict ->Dict.toArray ->Array.forEach(entry => { let (key, value) = entry setNested(newDict, key->String.split("."), value) }) | None => () } newDict } let getArrayOfTupleFromDict = dict => { dict ->Dict.keysToArray ->Array.map(key => (key, Dict.get(dict, key)->Option.getOr(JSON.Encode.null))) } let mergeTwoFlattenedJsonDicts = (dict1, dict2) => { let dict1Entries = dict1 ->Dict.toArray ->Array.filter(((_, val)) => { //to remove undefined values val->JSON.stringifyAny->Option.isSome && val->JSON.Classify.classify != Null }) let dict2Entries = dict2 ->Dict.toArray ->Array.filter(((_, val)) => { //to remove undefined values val->JSON.stringifyAny->Option.isSome && val->JSON.Classify.classify != Null }) dict1Entries->Array.concat(dict2Entries)->Dict.fromArray->JSON.Encode.object->unflattenObject } let getIsBillingField = requiredFieldType => { switch requiredFieldType { | AddressLine1 | AddressLine2 | AddressCity | AddressPincode | AddressState | AddressCountry(_) => true | _ => false } } let getIsAnyBillingDetailEmpty = (requiredFields: array<required_fields_type>) => { requiredFields->Array.reduce(false, (acc, requiredField) => { if getIsBillingField(requiredField.field_type) { requiredField.value === "" || acc } else { acc } }) } let filterDynamicFieldsFromRendering = ( requiredFields: array<required_fields_type>, finalJson: dict<(JSON.t, option<string>)>, ) => { let isAnyBillingDetailEmpty = requiredFields->getIsAnyBillingDetailEmpty requiredFields->Array.filter(requiredField => { let isShowBillingField = getIsBillingField(requiredField.field_type) && isAnyBillingDetailEmpty let isRenderRequiredField = switch requiredField.required_field { | StringField(_) => requiredField.value === "" | FullNameField(firstNameVal, lastNameVal) => switch (finalJson->Dict.get(firstNameVal), finalJson->Dict.get(lastNameVal)) { | (Some((_, Some(_))), Some((_, Some(_)))) | (Some((_, Some(_))), _) | (_, Some((_, Some(_)))) => true | _ => false } } isRenderRequiredField || isShowBillingField }) } let getRequiredFieldPath = (~isSaveCardsFlow, ~requiredField: required_fields_type) => { let isFieldTypeName = requiredField.field_type === FullName || requiredField.field_type === BillingName let isDisplayNameCardHolderName = requiredField.display_name === "card_holder_name" let isRequiedFieldCardHolderName = requiredField.required_field === StringField("payment_method_data.card.card_holder_name") isSaveCardsFlow && isFieldTypeName && isDisplayNameCardHolderName && isRequiedFieldCardHolderName ? StringField("payment_method_data.card_token.card_holder_name") : requiredField.required_field } let getIsSaveCardHaveName = (saveCardData: SdkTypes.savedDataType) => { switch saveCardData { | SAVEDLISTCARD(savedCard) => savedCard.cardHolderName->Option.getOr("") !== "" | SAVEDLISTWALLET(_) => false | NONE => false } } let filterRequiredFields = ( requiredFields: array<required_fields_type>, isSaveCardsFlow, saveCardsData: option<SdkTypes.savedDataType>, ) => { switch (isSaveCardsFlow, saveCardsData) { | (true, Some(saveCardsData)) => { let isSavedCardHaveName = saveCardsData->getIsSaveCardHaveName if isSavedCardHaveName { let val = requiredFields->Array.filter(requiredField => { requiredField.display_name !== "card_holder_name" }) val } else { requiredFields } } | _ => requiredFields } } let filterRequiredFieldsForShipping = ( requiredFields: array<required_fields_type>, shouldRenderShippingFields: bool, ) => { if shouldRenderShippingFields { requiredFields } else { requiredFields->Array.filter(requiredField => { !(requiredField.required_field->getRequiredFieldName->String.includes("shipping")) }) } } let getKey = (path, value) => { if path == "" { path } else { let arr = path->String.split(".") let key = arr->Array.slice(~start=0, ~end=arr->Array.length - 1)->Array.join(".") ++ "." ++ value key } } let getKeysValArray = (requiredFields, isSaveCardsFlow, clientCountry, countries) => { requiredFields->Array.reduce(Dict.make(), (acc, requiredField) => { let (value, isValid) = switch (requiredField.value, requiredField.field_type) { | ("", AddressCountry(values)) => { let values = switch values { | UseContextData => countries | UseBackEndData(a) => a } ( values->Array.includes(clientCountry) ? clientCountry->JSON.Encode.string : values->Array.length === 1 ? values->Array.get(0)->Option.getOr("")->JSON.Encode.string : JSON.Encode.null, None, ) } | ("", _) => (JSON.Encode.null, Some("Required")) | (value, _) => (value->JSON.Encode.string, None) } let requiredFieldPath = getRequiredFieldPath(~isSaveCardsFlow, ~requiredField) switch requiredFieldPath { | StringField(fieldPath) => acc->Dict.set(fieldPath, (value, isValid)) | FullNameField(firstName, lastName) => let arr = requiredField.value->String.split(" ") let firstNameVal = arr->Array.get(0)->Option.getOr("") let lastNameVal = arr->Array.filterWithIndex((_, index) => index !== 0)->Array.join(" ") let (firstNameVal, isFirstNameValid) = firstNameVal === "" ? (JSON.Encode.null, Some("First Name is required")) : (JSON.Encode.string(firstNameVal), None) let (lastNameVal, isLastNameValid) = lastNameVal === "" ? (JSON.Encode.null, Some("Last Name is required")) : (JSON.Encode.string(lastNameVal), None) acc->Dict.set(firstName, (firstNameVal, isFirstNameValid)) acc->Dict.set(lastName, (lastNameVal, isLastNameValid)) } acc }) }
4,910
10,594
hyperswitch-client-core
src/types/NativeSdkPropsKeys.res
.res
type keys = { locale: string, colors: string, light: string, dark: string, primary: string, background: string, componentBackground: string, componentBorder: string, componentDivider: string, componentText: string, primaryText: string, secondaryText: string, placeholderText: string, icon: string, error: string, shapes: string, borderRadius: string, borderWidth: string, shadow: string, shadow_color: string, shadow_opacity: string, shadow_blurRadius: string, shadow_offset: string, shadow_intensity: string, x: string, y: string, font: string, family: string, scale: string, headingTextSizeAdjust: string, subHeadingTextSizeAdjust: string, placeholderTextSizeAdjust: string, buttonTextSizeAdjust: string, errorTextSizeAdjust: string, linkTextSizeAdjust: string, modalTextSizeAdjust: string, cardTextSizeAdjust: string, primaryButton: string, primaryButton_font: string, primaryButton_family: string, primaryButton_scale: string, primaryButton_shapes: string, primaryButton_borderRadius: string, primaryButton_borderWidth: string, primaryButton_shadow: string, primaryButton_color: string, primaryButton_intensity: string, primaryButton_opacity: string, primaryButton_blurRadius: string, primaryButton_offset: string, primaryButton_light: string, primaryButton_dark: string, primaryButton_background: string, primaryButton_text: string, primaryButton_border: string, loadingBgColor: string, loadingFgColor: string, } let iosKeys: keys = { locale: "locale", colors: "colors", light: "", dark: "", primary: "primary", background: "background", componentBackground: "componentBackground", componentBorder: "componentBorder", componentDivider: "componentDivider", componentText: "componentText", primaryText: "text", secondaryText: "textSecondary", placeholderText: "componentPlaceholderText", icon: "icon", error: "danger", shapes: "", borderRadius: "cornerRadius", borderWidth: "borderWidth", shadow: "shadow", shadow_color: "color", shadow_opacity: "opacity", shadow_blurRadius: "radius", shadow_offset: "offset", shadow_intensity: "intensity", x: "x", y: "y", font: "font", family: "base", scale: "sizeScaleFactor", headingTextSizeAdjust: "headingTextSizeAdjust", subHeadingTextSizeAdjust: "subHeadingTextSizeAdjust", placeholderTextSizeAdjust: "placeholderTextSizeAdjust", buttonTextSizeAdjust: "buttonTextSizeAdjust", errorTextSizeAdjust: "errorTextSizeAdjust", linkTextSizeAdjust: "linkTextSizeAdjust", modalTextSizeAdjust: "modalTextSizeAdjust", cardTextSizeAdjust: "cardTextSizeAdjust", primaryButton: "primaryButton", primaryButton_font: "font", primaryButton_family: "family", primaryButton_scale: "scale", primaryButton_shapes: "", primaryButton_borderRadius: "cornerRadius", primaryButton_borderWidth: "borderWidth", primaryButton_shadow: "shadow", primaryButton_color: "", primaryButton_intensity: "intensity", primaryButton_opacity: "opacity", primaryButton_blurRadius: "blurRadius", primaryButton_offset: "offset", primaryButton_light: "", primaryButton_dark: "", primaryButton_background: "backgroundColor", primaryButton_text: "textColor", primaryButton_border: "borderColor", loadingBgColor: "loaderBackground", loadingFgColor: "loaderForeground", } let androidKeys = { locale: "locale", colors: "", light: "colorsLight", dark: "colorsDark", primary: "primary", background: "surface", componentBackground: "component", componentBorder: "componentBorder", componentDivider: "componentDivider", componentText: "onComponent", primaryText: "onSurface", secondaryText: "subtitle", placeholderText: "placeholderText", icon: "appBarIcon", error: "error", shapes: "shapes", borderRadius: "cornerRadiusDp", borderWidth: "borderStrokeWidthDp", shadow: "shadow", shadow_color: "color", shadow_opacity: "", shadow_blurRadius: "", shadow_offset: "", shadow_intensity: "intensity", x: "", y: "", font: "typography", family: "fontResId", scale: "sizeScaleFactor", headingTextSizeAdjust: "headingTextSizeAdjust", subHeadingTextSizeAdjust: "subHeadingTextSizeAdjust", placeholderTextSizeAdjust: "placeholderTextSizeAdjust", buttonTextSizeAdjust: "buttonTextSizeAdjust", errorTextSizeAdjust: "errorTextSizeAdjust", linkTextSizeAdjust: "linkTextSizeAdjust", modalTextSizeAdjust: "modalTextSizeAdjust", cardTextSizeAdjust: "cardTextSizeAdjust", primaryButton: "primaryButton", primaryButton_font: "typography", primaryButton_family: "fontResId", primaryButton_scale: "fontSizeSp", primaryButton_shapes: "shapes", primaryButton_borderRadius: "cornerRadiusDp", primaryButton_borderWidth: "borderWidth", primaryButton_shadow: "shadow", primaryButton_color: "color", primaryButton_opacity: "", primaryButton_intensity: "intensity", primaryButton_blurRadius: "", primaryButton_offset: "", primaryButton_light: "colorsLight", primaryButton_dark: "colorsDark", primaryButton_background: "background", primaryButton_text: "onBackground", primaryButton_border: "border", loadingBgColor: "loaderBackground", loadingFgColor: "loaderForeground", } let rnKeys = { locale: "locale", colors: "colors", light: "light", dark: "dark", primary: "primary", background: "background", componentBackground: "componentBackground", componentBorder: "componentBorder", componentDivider: "componentDivider", componentText: "componentText", primaryText: "primaryText", secondaryText: "secondaryText", placeholderText: "placeholderText", icon: "icon", error: "error", shapes: "shapes", borderRadius: "borderRadius", borderWidth: "borderWidth", shadow: "shadow", shadow_color: "color", shadow_opacity: "opacity", shadow_blurRadius: "blurRadius", shadow_offset: "offset", shadow_intensity: "intensity", x: "x", y: "y", font: "typography", family: "fontResId", scale: "sizeScaleFactor", headingTextSizeAdjust: "headingTextSizeAdjust", subHeadingTextSizeAdjust: "subHeadingTextSizeAdjust", placeholderTextSizeAdjust: "placeholderTextSizeAdjust", buttonTextSizeAdjust: "buttonTextSizeAdjust", errorTextSizeAdjust: "errorTextSizeAdjust", linkTextSizeAdjust: "linkTextSizeAdjust", modalTextSizeAdjust: "modalTextSizeAdjust", cardTextSizeAdjust: "cardTextSizeAdjust", primaryButton: "primaryButton", primaryButton_font: "typography", primaryButton_family: "fontResId", primaryButton_scale: "fontSizeSp", primaryButton_shapes: "shapes", primaryButton_borderRadius: "borderRadius", primaryButton_borderWidth: "borderWidth", primaryButton_shadow: "shadow", primaryButton_color: "colors", primaryButton_intensity: "intensity", primaryButton_opacity: "", primaryButton_blurRadius: "", primaryButton_offset: "", primaryButton_light: "light", primaryButton_dark: "dark", primaryButton_background: "background", primaryButton_text: "text", primaryButton_border: "border", loadingBgColor: "loaderBackground", loadingFgColor: "loaderForeground", }
1,785
10,595
hyperswitch-client-core
src/types/SessionsType.res
.res
open SdkTypes type samsungPaySession = { wallet_name: string, version: string, service_id: string, order_number: string, merchant: JSON.t, amount: JSON.t, protocol: string, allowed_brands: array<JSON.t>, } type sessions = { wallet_name: payment_method_type_wallet, session_token: string, session_id: string, merchant_info: JSON.t, allowed_payment_methods: array<JSON.t>, transaction_info: JSON.t, shipping_address_required: bool, billing_address_required: bool, email_required: bool, shipping_address_parameters: JSON.t, delayed_session_token: bool, connector: string, sdk_next_action: JSON.t, secrets: JSON.t, session_token_data: JSON.t, payment_request_data: JSON.t, connector_reference_id: JSON.t, connector_sdk_public_key: JSON.t, connector_merchant_id: JSON.t, merchant: JSON.t, order_number: string, service_id: string, amount: JSON.t, protocol: string, allowed_brands: array<JSON.t>, } let defaultToken = { wallet_name: NONE, session_token: "", session_id: "", merchant_info: JSON.Encode.null, allowed_payment_methods: [], transaction_info: JSON.Encode.null, shipping_address_required: false, billing_address_required: false, email_required: false, shipping_address_parameters: JSON.Encode.null, delayed_session_token: false, connector: "", sdk_next_action: JSON.Encode.null, secrets: JSON.Encode.null, session_token_data: JSON.Encode.null, payment_request_data: JSON.Encode.null, connector_reference_id: JSON.Encode.null, connector_sdk_public_key: JSON.Encode.null, connector_merchant_id: JSON.Encode.null, merchant: JSON.Encode.null, order_number: "", service_id: "", amount: JSON.Encode.null, protocol: "", allowed_brands: [], } let getWallet = str => { switch str { | "apple_pay" => APPLE_PAY | "paypal" => PAYPAL | "klarna" => KLARNA | "google_pay" => GOOGLE_PAY | "samsung_pay" => SAMSUNG_PAY | _ => NONE } } open Utils let itemToObjMapper = dict => { dict ->Dict.get("session_token") ->Option.flatMap(JSON.Decode.array) ->Option.map(arr => { arr->Array.map(json => { let dict = json->getDictFromJson { wallet_name: getString(dict, "wallet_name", "")->getWallet, session_token: getString(dict, "session_token", ""), session_id: getString(dict, "session_id", ""), merchant_info: getJsonObjectFromDict(dict, "merchant_info"), allowed_payment_methods: getArray(dict, "allowed_payment_methods"), transaction_info: getJsonObjectFromDict(dict, "transaction_info"), shipping_address_required: getBool(dict, "shipping_address_required", false), billing_address_required: getBool(dict, "billing_address_required", false), email_required: getBool(dict, "email_required", false), shipping_address_parameters: getJsonObjectFromDict(dict, "shipping_address_parameters"), delayed_session_token: getBool(dict, "delayed_session_token", false), connector: getString(dict, "connector", ""), sdk_next_action: getJsonObjectFromDict(dict, "transaction_info"), secrets: getJsonObjectFromDict(dict, "transaction_info"), session_token_data: getJsonObjectFromDict(dict, "session_token_data"), payment_request_data: getJsonObjectFromDict(dict, "payment_request_data"), connector_reference_id: getJsonObjectFromDict(dict, "connector_reference_id"), connector_sdk_public_key: getJsonObjectFromDict(dict, "connector_sdk_public_key"), connector_merchant_id: getJsonObjectFromDict(dict, "connector_merchant_id"), merchant: getJsonObjectFromDict(dict, "merchant"), order_number: getString(dict, "order_number", ""), service_id: getString(dict, "service_id", ""), amount: getJsonObjectFromDict(dict, "amount"), protocol: getString(dict, "protocol", ""), allowed_brands: getArray(dict, "allowed_brands"), } }) }) }
922
10,596
hyperswitch-client-core
src/types/SamsungPayType.res
.res
open Utils type payment3DS = { \"type": string, version: string, data: string, } type addressType = BILLING_ADDRESS | SHIPPING_ADDRESS type addressCollectedFromSpay = {billingDetails?: string, shippingDetails?: string} type paymentCredential = { \"3_d_s": payment3DS, card_brand: string, card_last4digits: string, method: string, recurring_payment: bool, } type paymentMethodData = {payment_credential: paymentCredential} let defaultSPayPaymentMethodData = { payment_credential: { card_brand: "", recurring_payment: false, card_last4digits: "", method: "", \"3_d_s": { \"type": "", version: "", data: "", }, }, } let get3DSData = (dict, str) => { dict ->Dict.get(str) ->Option.flatMap(JSON.Decode.object) ->Option.map(json => { { \"type": getString(json, "type", ""), version: getString(json, "version", ""), data: getString(json, "data", ""), } }) ->Option.getOr({\"type": "", version: "", data: ""}) } let getPaymentMethodData = dict => { { payment_credential: { card_brand: getString(dict, "payment_card_brand", ""), recurring_payment: getBool(dict, "recurring_payment", false), card_last4digits: getString(dict, "payment_last4_fpan", ""), method: getString(dict, "method", ""), \"3_d_s": get3DSData(dict, "3DS"), }, } } type paymentDataFromSPay = {paymentMethodData: paymentMethodData, email?: string} let itemToObjMapper = dict => { getPaymentMethodData(dict) } let getSamsungPaySessionObject = (sessionData: AllApiDataContext.sessions) => { let sessionObject = switch sessionData { | Some(sessionData) => sessionData ->Array.find(item => item.wallet_name == SAMSUNG_PAY) ->Option.getOr(SessionsType.defaultToken) | _ => SessionsType.defaultToken } sessionObject } let getAddressFromDict = dict => { switch dict { | Some(dict) => let addressDetails: SdkTypes.addressDetails = { address: Some({ first_name: ?getOptionString(dict, "first_name"), last_name: ?getOptionString(dict, "last_name"), city: ?getOptionString(dict, "city"), country: ?getOptionString(dict, "country"), line1: ?getOptionString(dict, "line1"), line2: ?getOptionString(dict, "line2"), zip: ?getOptionString(dict, "zip"), state: ?getOptionString(dict, "state"), }), email: dict->getOptionString("email"), phone: Some({ number: ?getOptionString(dict, "phoneNumber"), }), } Some(addressDetails) | _ => None } } let getAddress = address => { switch address { | Some(address) => address ->JSON.parseExn ->JSON.Decode.object ->getAddressFromDict | None => None } } let getAddressObj = (addressDetails, addressType: addressType) => { switch addressDetails { | Some(details) => { let address = addressType == BILLING_ADDRESS ? details.billingDetails : details.shippingDetails getAddress(address) } | None => None } }
764
10,597
hyperswitch-client-core
src/types/LocaleDataType.res
.res
type localeStrings = { locale: string, cardDetailsLabel: string, cardNumberLabel: string, localeDirection: string, inValidCardErrorText: string, unsupportedCardErrorText: string, inCompleteCVCErrorText: string, inValidCVCErrorText: string, inCompleteExpiryErrorText: string, inValidExpiryErrorText: string, pastExpiryErrorText: string, poweredBy: string, validThruText: string, sortCodeText: string, cvcTextLabel: string, emailLabel: string, emailInvalidText: string, emailEmptyText: string, accountNumberText: string, fullNameLabel: string, line1Label: string, line1Placeholder: string, line1EmptyText: string, line2Label: string, line2Placeholder: string, cityLabel: string, cityEmptyText: string, postalCodeLabel: string, postalCodeEmptyText: string, stateLabel: string, fullNamePlaceholder: string, countryLabel: string, currencyLabel: string, bankLabel: string, redirectText: string, bankDetailsText: string, orPayUsing: string, addNewCard: string, useExisitingSavedCards: string, saveCardDetails: string, addBankAccount: string, achBankDebitTermsPart1: string, achBankDebitTermsPart2: string, sepaDebitTermsPart1: string, sepaDebitTermsPart2: string, becsDebitTerms: string, cardTermsPart1: string, cardTermsPart2: string, payNowButton: string, cardNumberEmptyText: string, cardExpiryDateEmptyText: string, cvcNumberEmptyText: string, enterFieldsText: string, enterValidDetailsText: string, card: string, billingNameLabel: string, billingNamePlaceholder: string, cardHolderName: string, cardNickname: string, firstName: string, lastName: string, billingDetails: string, requiredText: string, cardHolderNameRequiredText: string, invalidDigitsCardHolderNameError: string, invalidDigitsNickNameError: string, lastNameRequiredText: string, cardExpiresText: string, addPaymentMethodLabel: string, walletDisclaimer: string, deletePaymentMethod?: string, enterValidDigitsText: string, digitsText: string, selectCardBrand: string, mandatoryFieldText: string, } let defaultLocale = { locale: "en", localeDirection: "ltr", cardNumberLabel: "Card Number", cardDetailsLabel: "Card Details", inValidCardErrorText: "Card number is invalid.", unsupportedCardErrorText: "Card brand is not supported.", inCompleteCVCErrorText: "Your card's security code is incomplete.", inValidCVCErrorText: "Your card's security code is invalid.", inCompleteExpiryErrorText: "Your card's expiration date is incomplete.", inValidExpiryErrorText: "Your card's expiration date is invalid.", pastExpiryErrorText: "Your card's expiration date is invalid", poweredBy: "Powered By Hyperswitch", validThruText: "Expiry", sortCodeText: "Sort Code", accountNumberText: "Account Number", cvcTextLabel: "CVC", emailLabel: "Email", emailInvalidText: "Invalid email address", emailEmptyText: "Email cannot be empty", line1Label: "Address line 1", line1Placeholder: "Street address", line1EmptyText: "Address line 1 cannot be empty", line2Label: "Address line 2", line2Placeholder: "Apt., unit number, etc (optional)", cityLabel: "City", cityEmptyText: "City cannot be empty", postalCodeLabel: "Postal Code", postalCodeEmptyText: "Postal code cannot be empty", stateLabel: "State", fullNameLabel: "Full name", fullNamePlaceholder: "First and last name", countryLabel: "Country", currencyLabel: "Currency", bankLabel: "Select Bank", redirectText: "After submitting your order, you will be redirected to securely complete your purchase.", bankDetailsText: "After submitting these details, you will get bank account information to make payment. Please make sure to take a note of it.", orPayUsing: "Or pay using", addNewCard: "Add credit/debit card", useExisitingSavedCards: "Use saved payment methods", saveCardDetails: "Save card details", addBankAccount: "Add bank account", achBankDebitTermsPart1: "By providing your account number and confirming this payment, you are authorizing ", achBankDebitTermsPart2: " and Hyperswitch, our payment service provider, to send instructions to your bank to debit your account and your bank to debit your account in accordance with those instructions. You are entitled to a refund from your bank under the terms and conditions of your agreement with your bank.", sepaDebitTermsPart1: "By providing your payment information and confirming this payment, you authorise (A) ", sepaDebitTermsPart2: " and our payment service provider(s) to send instructions to your bank to debit your account and (B) your bank to debit your account in accordance with those instructions. As part of your rights, you are entitled to a refund from your bank under the terms and conditions of your agreement with your bank. Your rights are explained in a statement that you can obtain from your bank. You agree to receive notifications for future debits up to 2 days before they occur.", becsDebitTerms: "By providing your bank account details and confirming this payment, you agree to this Direct Debit Request and the Direct Debit Request service agreement and authorise to debit your account through the Bulk Electronic Clearing System (BECS) on behalf of Hyperswitch Payment Widget (the \"Merchant\") for any amounts separately communicated to you by the Merchant. You certify that you are either an account holder or an authorised signatory on the account listed above.", cardTermsPart1: "You allow ", cardTermsPart2: " to automatically charge your card for future payments.", payNowButton: "Pay Now", cardNumberEmptyText: "Card Number cannot be empty", cardExpiryDateEmptyText: "Card expiry date cannot be empty", cvcNumberEmptyText: "CVC Number cannot be empty", enterFieldsText: "Please enter all fields", enterValidDetailsText: "Please enter valid details", card: "Card", billingNameLabel: "Billing name", cardHolderName: "Card Holder Name", cardNickname: "Card Nickname", billingNamePlaceholder: "First and last name", firstName: "First name", lastName: "Last name", billingDetails: "Billing Details", requiredText: "Required", cardHolderNameRequiredText: "Card Holder's name required", invalidDigitsCardHolderNameError: "Card Holder's name cannot have digits", lastNameRequiredText: "Last Name Required", invalidDigitsNickNameError: "Nickname cannot have more than 2 digits", cardExpiresText: "expires", addPaymentMethodLabel: "Add new payment method", walletDisclaimer: "Wallet details will be saved upon selection", deletePaymentMethod: "Delete", enterValidDigitsText: "Please enter valid ", digitsText: " digits ", selectCardBrand: "Select a card brand", mandatoryFieldText: "This field is mandatory", }
1,676
10,598
hyperswitch-client-core
src/types/GooglePayTypeNew.res
.res
open SdkTypes open Utils type merchantInfo = { merchantId: string, merchantName: string, } type allowedPaymentMethodsParameters = { allowedAuthMethods: array<string>, allowedCardNetworks: array<string>, billingAddressRequired: bool, } type tokenizationSpecificationParameters = { gateway: string, gatewayMerchantId: string, } type tokenizationSpecification = { type_: string, parameters: tokenizationSpecificationParameters, } type allowedPaymentMethods = { type_: string, parameters: allowedPaymentMethodsParameters, tokenizationSpecification: tokenizationSpecification, } type transactionInfo = { totalPriceStatus: string, totalPrice: string, currencyCode: string, countryCode: string, } type shippingAddressParameters = {phoneNumberRequired: bool} type paymentData = { apiVersion: int, apiVersionMinor: int, merchantInfo: JSON.t, allowedPaymentMethods: array<JSON.t>, transactionInfo: JSON.t, shippingAddressRequired: bool, emailRequired: bool, shippingAddressParameters: JSON.t, } type requestType = { environment: JSON.t, paymentDataRequest: paymentData, } let arrayJsonToCamelCase = arr => { arr->Array.map(item => { item->transformKeysSnakeToCamel }) } let itemToObject = (data: SessionsType.sessions, emailRequired): paymentData => { apiVersion: 2, apiVersionMinor: 0, merchantInfo: data.merchant_info->transformKeysSnakeToCamel, allowedPaymentMethods: data.allowed_payment_methods->arrayJsonToCamelCase, transactionInfo: data.transaction_info->transformKeysSnakeToCamel, shippingAddressRequired: data.shipping_address_required, emailRequired: emailRequired || data.email_required, shippingAddressParameters: data.shipping_address_parameters->transformKeysSnakeToCamel, } type assurance_details = { account_verified: bool, card_holder_authenticated: bool, } type info = { card_network: string, card_details: string, assurance_details?: assurance_details, billing_address?: addressDetails, } type tokenizationData = {token: string, \"type": string} type paymentMethodData = { description?: string, info?: info, \"type"?: string, tokenization_data?: tokenizationData, } let getAssuranceDetails = (dict, str) => { dict ->Dict.get(str) ->Option.flatMap(JSON.Decode.object) ->Option.map(json => { { account_verified: getBool(json, "accountVerified", false), card_holder_authenticated: getBool(json, "cardHolderAuthenticated", false), } }) } let getBillingAddress = (dict, str, statesList) => { dict ->Dict.get(str) ->Option.flatMap(JSON.Decode.object) ->Option.map(json => { let (first_name, last_name) = getOptionString(json, "name")->splitName let country = switch getOptionString(json, "countryCode") { | Some(country) => Some(country->String.toUpperCase) | None => None } { address: Some({ first_name, last_name, city: ?getOptionString(json, "locality"), ?country, line1: ?getOptionString(json, "address1"), line2: ?getOptionString(json, "address2"), zip: ?getOptionString(json, "postalCode"), state: ?switch getOptionString(json, "administrativeArea") { | Some(area) => Some(getStateNameFromStateCodeAndCountry(statesList, area, country)) | None => None }, }), email: getOptionString(json, "email"), phone: Some({ number: ?getOptionString(json, "phoneNumber"), }), } }) } let getBillingContact = (dict, str, statesList) => { dict ->Dict.get(str) ->Option.flatMap(JSON.Decode.object) ->Option.map(json => { let name = json->getDictFromJsonKey("name") let postalAddress = json->getDictFromJsonKey("postalAddress") let country = switch getOptionString(postalAddress, "isoCountryCode") { | Some(country) => Some(country->String.toUpperCase) | None => None } let street = getString(postalAddress, "street", "")->String.split("\n") let line1 = Array.at(street, 0) let line2 = if Array.length(street) > 1 { Some(Array.join(Array.sliceToEnd(street, ~start=1), " ")) } else { None } { address: Some({ first_name: ?getOptionString(name, "givenName"), last_name: ?getOptionString(name, "familyName"), city: ?getOptionString(postalAddress, "city"), ?country, ?line1, ?line2, zip: ?getOptionString(postalAddress, "postalCode"), state: ?switch getOptionString(postalAddress, "state") { | Some(area) => Some(getStateNameFromStateCodeAndCountry(statesList, area, country)) | None => None }, }), email: getOptionString(json, "emailAddress"), phone: Some({ number: ?getOptionString(json, "phoneNumber"), }), } }) } let getInfo = (str, dict, statesJson) => { dict ->Dict.get(str) ->Option.flatMap(JSON.Decode.object) ->Option.map(json => { { card_network: getString(json, "cardNetwork", ""), card_details: getString(json, "cardDetails", ""), assurance_details: ?getAssuranceDetails(json, "assuranceDetails"), billing_address: ?getBillingAddress(json, "billingAddress", statesJson), } }) } let getTokenizationData = (str, dict) => { dict ->Dict.get(str) ->Option.flatMap(JSON.Decode.object) ->Option.map(json => { { token: getString(json, "token", ""), \"type": getString(json, "type", ""), } }) } let getPaymentMethodData = (str, dict, statesJson) => { dict ->Dict.get(str) ->Option.flatMap(JSON.Decode.object) ->Option.map(json => { let info = getInfo("info", json, statesJson) { description: getString(json, "description", ""), tokenization_data: ?getTokenizationData("tokenizationData", json), ?info, \"type": getString(json, "type", ""), } }) ->Option.getOr({}) } type paymentDataFromGPay = { paymentMethodData: paymentMethodData, email?: string, shippingDetails?: addressDetails, } let itemToObjMapper = (dict, statesJson) => { paymentMethodData: getPaymentMethodData("paymentMethodData", dict, statesJson), email: ?getOptionString(dict, "email"), shippingDetails: ?getBillingAddress(dict, "shippingAddress", statesJson), } let arrayJsonToCamelCase = arr => { arr->Array.map(item => { item->Utils.transformKeysSnakeToCamel }) } let getGpayToken = ( ~obj: SessionsType.sessions, ~appEnv: GlobalVars.envType, ~requiredFields: option<RequiredFieldsTypes.required_fields>=?, ) => { environment: appEnv == PROD ? "PRODUCTION"->JSON.Encode.string : "Test"->JSON.Encode.string, paymentDataRequest: obj->itemToObject( switch requiredFields { | Some(fields) => fields ->Array.find(v => { v.display_name == "email" }) ->Option.isSome | None => true }, ), } let getGpayTokenStringified = ( ~obj: SessionsType.sessions, ~appEnv: GlobalVars.envType, ~requiredFields: option<RequiredFieldsTypes.required_fields>=?, ) => getGpayToken(~obj, ~appEnv, ~requiredFields?)->Utils.getStringFromRecord let getAllowedPaymentMethods = ( ~obj: SessionsType.sessions, ~requiredFields: option<RequiredFieldsTypes.required_fields>=?, ) => { obj->itemToObject( switch requiredFields { | Some(fields) => fields ->Array.find(v => { v.display_name == "email" }) ->Option.isSome | None => true }, ) }.allowedPaymentMethods->Utils.getStringFromRecord let getValue = (func, addressDetails: option<SdkTypes.addressDetails>) => addressDetails->Option.flatMap(func) let getNestedValue = (func, addressExtractor, addressDetails) => addressDetails->Option.flatMap(addressExtractor)->Option.flatMap(func) let getPhoneNumber = (addressDetails: option<SdkTypes.addressDetails>) => getNestedValue(phone => phone.number, address => address.phone, addressDetails) let getPhoneCountryCode = addressDetails => getNestedValue(phone => phone.country_code, address => address.phone, addressDetails) let getEmailAddress = (addressDetails: option<SdkTypes.addressDetails>) => getValue(address => address.email, addressDetails) let getAddressField = extractor => addressDetails => getNestedValue(extractor, address => address.address, addressDetails) let getAddressLine1 = getAddressField(address => address.line1) let getAddressLine2 = getAddressField(address => address.line2) let getAddressCity = getAddressField(address => address.city) let getAddressState = getAddressField(address => address.state) let getAddressCountry = getAddressField(address => address.country) let getAddressPincode = getAddressField(address => address.zip) let getFirstName = getAddressField(address => address.first_name) let getLastName = getAddressField(address => address.last_name) let getFlattenData = ( required_fields: RequiredFieldsTypes.required_fields, ~billingAddress: option<SdkTypes.addressDetails>, ~shippingAddress: option<SdkTypes.addressDetails>, ~email=None, ~phoneNumber=None, ) => { let flattenedData = Dict.make() required_fields->Array.forEach(required_field => { switch required_field.required_field { | StringField(path) => let isShippingField = path->String.includes("shipping") let address = if isShippingField { shippingAddress } else { billingAddress } let value = switch required_field.field_type { | PhoneNumber => phoneNumber ->Option.orElse(billingAddress->getPhoneNumber) ->Option.orElse(shippingAddress->getPhoneNumber) | Email => email ->Option.orElse(billingAddress->getEmailAddress) ->Option.orElse(shippingAddress->getEmailAddress) | AddressLine1 => address->getAddressLine1 | AddressLine2 => address->getAddressLine2 | AddressCity => address->getAddressCity | AddressPincode => address->getAddressPincode | AddressState => address->getAddressState | Country | AddressCountry(_) => address->getAddressCountry | PhoneCountryCode => address->getPhoneCountryCode | _ => None } if value !== None { flattenedData->Dict.set(path, value->Option.getOr("")->JSON.Encode.string) } | FullNameField(first_name, last_name) => let (firstName, lastName) = if required_field.field_type == Email { let value = email ->Option.orElse(billingAddress->getEmailAddress) ->Option.orElse(shippingAddress->getEmailAddress) ->Option.getOr("") ->JSON.Encode.string (value, value) } else { let isShippingField = first_name->String.includes("shipping") let primaryAddress = if isShippingField { shippingAddress } else { billingAddress } let fallbackAddress = if isShippingField { billingAddress } else { shippingAddress } ( primaryAddress ->getFirstName ->Option.orElse(fallbackAddress->getFirstName) ->Option.getOr("") ->JSON.Encode.string, primaryAddress ->getLastName ->Option.orElse(fallbackAddress->getLastName) ->Option.getOr("") ->JSON.Encode.string, ) } if firstName != JSON.Encode.null { flattenedData->Dict.set(first_name, firstName) } if lastName !== JSON.Encode.null { flattenedData->Dict.set(last_name, lastName) } } }) flattenedData } let getPaymentMethodData = (required_field, ~shippingAddress, ~billingAddress, ~email=None) => { required_field ->getFlattenData(~shippingAddress, ~billingAddress, ~email) ->JSON.Encode.object ->RequiredFieldsTypes.unflattenObject ->Dict.get("payment_method_data") ->Option.getOr(JSON.Encode.null) ->Utils.getDictFromJson }
2,772
10,599
hyperswitch-client-core
src/types/ExternalThreeDsTypes.res
.res
type statusType = { status: string, message: string, } type sdkEphemeralKey = { kty: string, crv: string, x: string, y: string, } type sdkInformation = { sdk_app_id: string, sdk_enc_data: string, sdk_ephem_pub_key: sdkEphemeralKey, sdk_trans_id: string, sdk_reference_number: string, sdk_max_timeout: int, } type authCallBody = { client_secret: string, device_channel: string, threeds_method_comp_ind: string, sdk_information: sdkInformation, } type aReqParams = { deviceData: string, messageVersion: string, sdkTransId: string, sdkAppId: string, sdkEphemeralKey: Js.Json.t, sdkReferenceNo: string, } type authCallResponse = { transStatus: string, acsSignedContent: string, acsRefNumber: string, acsTransactionId: string, threeDSRequestorAppURL: option<string>, threeDSServerTransId: string, dsTransactionId: string, } type pollCallResponse = { pollId: string, status: string, } type errorType = { errorCode: string, errorMessage: string, } type authResponse = AUTH_RESPONSE(authCallResponse) | AUTH_ERROR(errorType) let authResponseItemToObjMapper = (dict): authResponse => { dict->ErrorUtils.isError ? AUTH_ERROR({ errorCode: dict->ErrorUtils.getErrorCode, errorMessage: dict->ErrorUtils.getErrorMessage, }) : AUTH_RESPONSE({ transStatus: dict->Utils.getDictFromJson->Utils.getString("trans_status", ""), acsSignedContent: dict->Utils.getDictFromJson->Utils.getString("acs_signed_content", ""), acsRefNumber: dict->Utils.getDictFromJson->Utils.getString("acs_reference_number", ""), acsTransactionId: dict->Utils.getDictFromJson->Utils.getString("acs_trans_id", ""), threeDSRequestorAppURL: dict ->Utils.getDictFromJson ->Utils.getOptionString("three_ds_requestor_app_url"), threeDSServerTransId: dict ->Utils.getDictFromJson ->Utils.getString("three_dsserver_trans_id", ""), dsTransactionId: "", }) } let pollResponseItemToObjMapper = (dict): pollCallResponse => { { pollId: dict->Utils.getString("poll_id", ""), status: dict->Utils.getString("status", ""), } }
560
10,600
hyperswitch-client-core
src/types/SdkTypes.res
.res
open Utils type localeTypes = | En | He | Fr | En_GB | Ar | Ja | De | Fr_BE | Es | Ca | Pt | It | Pl | Nl | NI_BE | Sv | Ru | Lt | Cs | Sk | Ls | Cy | El | Et | Fi | Nb | Bs | Da | Ms | Tr_CY type fontFamilyTypes = DefaultIOS | DefaultAndroid | CustomFont(string) | DefaultWeb type payment_method_type_wallet = GOOGLE_PAY | APPLE_PAY | PAYPAL | SAMSUNG_PAY | NONE | KLARNA let walletNameMapper = str => { switch str { | "google_pay" => "Google Pay" | "apple_pay" => "Apple Pay" | "paypal" => "Paypal" | "samsung_pay" => "Samsung Pay" | _ => "" } } let walletNameToTypeMapper = str => { switch str { | "Google Pay" => GOOGLE_PAY | "Apple Pay" => APPLE_PAY | "Paypal" => PAYPAL | "Samsung Pay" => SAMSUNG_PAY | _ => NONE } } type savedCard = { cardScheme?: string, // walletType?: string, name?: string, cardHolderName?: string, cardNumber?: string, expiry_date?: string, payment_token?: string, paymentMethodId?: string, mandate_id?: string, nick_name?: string, isDefaultPaymentMethod?: bool, requiresCVV: bool, created?: string, lastUsedAt?: string, } type savedWallet = { payment_method_type?: string, walletType?: string, payment_token?: string, paymentMethodId?: string, isDefaultPaymentMethod?: bool, created?: string, lastUsedAt?: string, } type savedDataType = | SAVEDLISTCARD(savedCard) | SAVEDLISTWALLET(savedWallet) | NONE type colors = { primary: option<string>, background: option<string>, componentBackground: option<string>, componentBorder: option<string>, componentDivider: option<string>, componentText: option<string>, primaryText: option<string>, secondaryText: option<string>, placeholderText: option<string>, icon: option<string>, error: option<string>, loaderBackground: option<string>, loaderForeground: option<string>, } type defaultColors = {light: option<colors>, dark: option<colors>} type colorType = | Colors(colors) | DefaultColors(defaultColors) // IOS Specific type offsetType = { x: option<float>, y: option<float>, } type shadowConfig = { color: option<string>, opacity: option<float>, blurRadius: option<float>, offset: option<offsetType>, intensity: option<float>, } type shapes = { borderRadius: option<float>, borderWidth: option<float>, shadow: option<shadowConfig>, // IOS Specific } type font = { family: option<fontFamilyTypes>, scale: option<float>, headingTextSizeAdjust: option<float>, subHeadingTextSizeAdjust: option<float>, placeholderTextSizeAdjust: option<float>, buttonTextSizeAdjust: option<float>, errorTextSizeAdjust: option<float>, linkTextSizeAdjust: option<float>, modalTextSizeAdjust: option<float>, cardTextSizeAdjust: option<float>, } type primaryButtonColor = { background: option<string>, text: option<string>, border: option<string>, } type primaryButtonColorType = | PrimaryButtonColor(option<primaryButtonColor>) | PrimaryButtonDefault({light: option<primaryButtonColor>, dark: option<primaryButtonColor>}) type primaryButton = { shapes: option<shapes>, primaryButtonColor: option<primaryButtonColorType>, } type googlePayButtonType = BUY | BOOK | CHECKOUT | DONATE | ORDER | PAY | SUBSCRIBE | PLAIN type googlePayThemeBaseStyle = { light: ReactNative.Appearance.t, dark: ReactNative.Appearance.t, } type googlePayConfiguration = { buttonType: googlePayButtonType, buttonStyle: option<googlePayThemeBaseStyle>, } type applePayButtonType = [ | #buy | #setUp | #inStore | #donate | #checkout | #book | #subscribe | #plain ] type applePayButtonStyle = [#white | #whiteOutline | #black] type applePayThemeBaseStyle = { light: applePayButtonStyle, dark: applePayButtonStyle, } type applePayConfiguration = { buttonType: applePayButtonType, buttonStyle: option<applePayThemeBaseStyle>, } type themeType = Default | Light | Dark | Minimal | FlatMinimal type appearance = { locale: option<localeTypes>, colors: option<colorType>, shapes: option<shapes>, font: option<font>, primaryButton: option<primaryButton>, googlePay: googlePayConfiguration, applePay: applePayConfiguration, theme: themeType, } type address = { first_name?: string, last_name?: string, city?: string, country?: string, line1?: string, line2?: string, zip?: string, state?: string, } type phone = { number?: string, country_code?: string, } type addressDetails = { address: option<address>, email: option<string>, phone: option<phone>, } type customerConfiguration = { id: option<string>, ephemeralKeySecret: option<string>, } type placeholder = { cardNumber: string, expiryDate: string, cvv: string, } type configurationType = { allowsDelayedPaymentMethods: bool, appearance: appearance, shippingDetails: option<addressDetails>, primaryButtonLabel: option<string>, paymentSheetHeaderText: option<string>, savedPaymentScreenHeaderText: option<string>, merchantDisplayName: string, defaultBillingDetails: option<addressDetails>, primaryButtonColor: option<string>, allowsPaymentMethodsRequiringShippingAddress: bool, displaySavedPaymentMethodsCheckbox: bool, displaySavedPaymentMethods: bool, placeholder: placeholder, defaultView: bool, netceteraSDKApiKey: option<string>, displayDefaultSavedPaymentIcon: bool, enablePartialLoading: bool, } type sdkState = | PaymentSheet | HostedCheckout | CardWidget | CustomWidget(payment_method_type_wallet) | ExpressCheckoutWidget | PaymentMethodsManagement | WidgetPaymentSheet | Headless | NoView let widgetToStrMapper = str => { switch str { | GOOGLE_PAY => "GOOGLE_PAY" | PAYPAL => "PAYPAL" | _ => "" } } let walletTypeToStrMapper = walletType => { switch walletType { | GOOGLE_PAY => "google_pay" | APPLE_PAY => "apple_pay" | PAYPAL => "paypal" | SAMSUNG_PAY => "samsung_pay" | _ => "" } } let sdkStateToStrMapper = sdkState => { switch sdkState { | PaymentSheet => "PAYMENT_SHEET" | HostedCheckout => "HOSTED_CHECKOUT" | CardWidget => "CARD_FORM" | CustomWidget(str) => str->widgetToStrMapper | ExpressCheckoutWidget => "EXPRESS_CHECKOUT_WIDGET" | PaymentMethodsManagement => "PAYMENT_METHODS_MANAGEMENT" | WidgetPaymentSheet => "WIDGET_PAYMENT" | Headless => "HEADLESS" | NoView => "NO_VIEW" } } type hyperParams = { confirm: bool, appId?: string, country: string, disableBranding: bool, userAgent: option<string>, launchTime?: float, sdkVersion: string, device_model: option<string>, os_type: option<string>, os_version: option<string>, deviceBrand: option<string>, } type nativeProp = { publishableKey: string, clientSecret: string, paymentMethodId: string, ephemeralKey: option<string>, customBackendUrl: option<string>, customLogUrl: option<string>, sessionId: string, from: string, configuration: configurationType, env: GlobalVars.envType, sdkState: sdkState, rootTag: int, hyperParams: hyperParams, customParams: Dict.t<JSON.t>, } let defaultAppearance: appearance = { locale: None, colors: switch WebKit.platform { | #android => Some( DefaultColors({ light: None, dark: None, }), ) | #ios => Some( Colors({ primary: None, background: None, componentBackground: None, componentBorder: None, componentDivider: None, componentText: None, primaryText: None, secondaryText: None, placeholderText: None, icon: None, error: None, loaderBackground: None, loaderForeground: None, }), ) | _ => None }, shapes: Some({ borderRadius: None, borderWidth: None, shadow: None, }), font: Some({ family: None, scale: None, headingTextSizeAdjust: None, subHeadingTextSizeAdjust: None, placeholderTextSizeAdjust: None, buttonTextSizeAdjust: None, errorTextSizeAdjust: None, linkTextSizeAdjust: None, modalTextSizeAdjust: None, cardTextSizeAdjust: None, }), primaryButton: Some({ shapes: Some({ borderRadius: None, borderWidth: None, shadow: None, }), primaryButtonColor: switch WebKit.platform { | #android => Some( PrimaryButtonDefault({ light: Some({ background: None, text: None, border: None, }), dark: Some({ background: None, text: None, border: None, }), }), ) | #ios => Some( PrimaryButtonColor( Some({ background: None, text: None, border: None, }), ), ) | _ => None }, }), googlePay: { buttonType: PLAIN, buttonStyle: None, }, applePay: { buttonType: #plain, buttonStyle: None, }, theme: Default, } let getColorFromDict = (colorDict, keys: NativeSdkPropsKeys.keys) => { primary: retOptionalStr(getProp(keys.primary, colorDict)), background: retOptionalStr(getProp(keys.background, colorDict)), componentBackground: retOptionalStr(getProp(keys.componentBackground, colorDict)), componentBorder: retOptionalStr(getProp(keys.componentBorder, colorDict)), componentDivider: retOptionalStr(getProp(keys.componentDivider, colorDict)), componentText: retOptionalStr(getProp(keys.componentText, colorDict)), primaryText: retOptionalStr(getProp(keys.primaryText, colorDict)), secondaryText: retOptionalStr(getProp(keys.secondaryText, colorDict)), placeholderText: retOptionalStr(getProp(keys.placeholderText, colorDict)), icon: retOptionalStr(getProp(keys.icon, colorDict)), error: retOptionalStr(getProp(keys.error, colorDict)), loaderBackground: retOptionalStr(getProp(keys.loadingBgColor, colorDict)), loaderForeground: retOptionalStr(getProp(keys.loadingFgColor, colorDict)), } let getPrimaryButtonColorFromDict = (primaryButtonColorDict, keys: NativeSdkPropsKeys.keys) => { { background: retOptionalStr(getProp(keys.primaryButton_background, primaryButtonColorDict)), text: retOptionalStr(getProp(keys.primaryButton_text, primaryButtonColorDict)), border: retOptionalStr(getProp(keys.primaryButton_border, primaryButtonColorDict)), } } let localeTypeToString = locale => { switch locale { | Some(En) => "en" | Some(He) => "he" | Some(Fr) => "fr" | Some(En_GB) => "en-GB" | Some(Ar) => "ar" | Some(Ja) => "ja" | Some(De) => "de" | Some(Fr_BE) => "fr-BE" | Some(Es) => "es" | Some(Ca) => "ca" | Some(Pt) => "pt" | Some(It) => "it" | Some(Pl) => "pl" | Some(Nl) => "nl" | Some(NI_BE) => "nI-BE" | Some(Sv) => "sv" | Some(Ru) => "ru" | Some(Lt) => "lt" | Some(Cs) => "cs" | Some(Sk) => "sk" | Some(Ls) => "ls" | Some(Cy) => "cy" | Some(El) => "el" | Some(Et) => "et" | Some(Fi) => "fi" | Some(Nb) => "nb" | Some(Bs) => "bs" | Some(Da) => "da" | Some(Ms) => "ms" | Some(Tr_CY) => "tr-CY" | None => "en" } } let localeStringToType = locale => { switch locale { | "he" => Some(He) | "fr" => Some(Fr) | "en-GB" => Some(En_GB) | "ar" => Some(Ar) | "ja" => Some(Ja) | "de" => Some(De) | "fr-BE" => Some(Fr_BE) | "es" => Some(Es) | "ca" => Some(Ca) | "pt" => Some(Pt) | "it" => Some(It) | "pl" => Some(Pl) | "nl" => Some(Nl) | "nI-BE" => Some(NI_BE) | "sv" => Some(Sv) | "ru" => Some(Ru) | "lt" => Some(Lt) | "cs" => Some(Cs) | "sk" => Some(Sk) | "ls" => Some(Ls) | "cy" => Some(Cy) | "el" => Some(El) | "et" => Some(Et) | "fi" => Some(Fi) | "nb" => Some(Nb) | "bs" => Some(Bs) | "da" => Some(Da) | "ms" => Some(Ms) | "tr-CY" => Some(Tr_CY) | _ => Some(En) } } let getAppearanceObj = ( appearanceDict: Dict.t<JSON.t>, keys: NativeSdkPropsKeys.keys, from: string, ) => { let fontDict = getObj(appearanceDict, keys.font, Dict.make()) let primaryButtonDict = getObj(appearanceDict, keys.primaryButton, Dict.make()) let primaryButtonShapesDict = switch keys.primaryButton_shapes { | "" => primaryButtonDict | _ => getObj(primaryButtonDict, keys.primaryButton_shapes, Dict.make()) } let googlePayDict = getObj(appearanceDict, "googlePay", Dict.make()) let googlePayButtonStyle = getOptionalObj(googlePayDict, "buttonStyle") let applePayDict = getObj(appearanceDict, "applePay", Dict.make()) let applePayButtonStyle = getOptionalObj(applePayDict, "buttonStyle") { locale: switch retOptionalStr(getProp(keys.locale, appearanceDict)) { | Some(str) => localeStringToType(str) | _ => Some(En) }, colors: from == "rn" || from == "flutter" ? { let colors = getObj(appearanceDict, keys.colors, Dict.make()) let colorsLightDict = colors->Dict.get(keys.light)->Option.flatMap(JSON.Decode.object) let colorsDarkDict = colors->Dict.get(keys.dark)->Option.flatMap(JSON.Decode.object) Some( colorsLightDict === None && colorsDarkDict === None ? Colors(getColorFromDict(colors, keys)) : DefaultColors({ light: Some(getColorFromDict(colorsLightDict->Option.getOr(Dict.make()), keys)), dark: Some(getColorFromDict(colorsDarkDict->Option.getOr(Dict.make()), keys)), }), ) } : switch keys.colors { | "" => let colorsLightDict = getObj(appearanceDict, keys.light, Dict.make()) let colorsDarkDict = getObj(appearanceDict, keys.dark, Dict.make()) Some( DefaultColors({ light: Some(getColorFromDict(colorsLightDict, keys)), dark: Some(getColorFromDict(colorsDarkDict, keys)), }), ) | _ => let colors = getObj(appearanceDict, keys.colors, Dict.make()) Some(Colors(getColorFromDict(colors, keys))) }, shapes: { let shapesDict = getObj(appearanceDict, keys.shapes, Dict.make()) let shadowDict = getObj( keys.shapes == "" ? appearanceDict : shapesDict, keys.shadow, Dict.make(), ) let offsetDict = getObj(shadowDict, keys.shadow_offset, Dict.make()) Some({ borderRadius: retOptionalFloat(getProp(keys.borderRadius, shapesDict)), borderWidth: retOptionalFloat(getProp(keys.borderWidth, shapesDict)), shadow: Some({ color: retOptionalStr(getProp(keys.shadow_color, shadowDict)), opacity: retOptionalFloat(getProp(keys.shadow_opacity, shadowDict)), blurRadius: retOptionalFloat(getProp(keys.shadow_blurRadius, shadowDict)), offset: Some({ x: retOptionalFloat(getProp(keys.x, offsetDict)), y: retOptionalFloat(getProp(keys.y, offsetDict)), }), intensity: retOptionalFloat(getProp(keys.shadow_intensity, shadowDict)), }), }) }, font: Some({ family: switch retOptionalStr(getProp(keys.family, fontDict)) { | Some(str) => Some(CustomFont(str)) | None => switch WebKit.platform { | #ios => DefaultIOS | #iosWebView => DefaultIOS | #android => DefaultAndroid | #androidWebView => DefaultAndroid | #web | #next => DefaultWeb }->Some }, scale: retOptionalFloat(getProp(keys.scale, fontDict)), // headingTextSizeAdjust: retOptionalFloat(getProp(keys.headingTextSizeAdjust, fontDict)), // subHeadingTextSizeAdjust: retOptionalFloat(getProp(keys.subHeadingTextSizeAdjust, fontDict)), // placeholderTextSizeAdjust: retOptionalFloat( // getProp(keys.placeholderTextSizeAdjust, fontDict), // ), // buttonTextSizeAdjust: retOptionalFloat(getProp(keys.buttonTextSizeAdjust, fontDict)), // errorTextSizeAdjust: retOptionalFloat(getProp(keys.errorTextSizeAdjust, fontDict)), // linkTextSizeAdjust: retOptionalFloat(getProp(keys.linkTextSizeAdjust, fontDict)), // modalTextSizeAdjust: retOptionalFloat(getProp(keys.modalTextSizeAdjust, fontDict)), // cardTextSizeAdjust: retOptionalFloat(getProp(keys.cardTextSizeAdjust, fontDict)), headingTextSizeAdjust: retOptionalFloat(getProp(keys.scale, fontDict)), subHeadingTextSizeAdjust: retOptionalFloat(getProp(keys.scale, fontDict)), placeholderTextSizeAdjust: retOptionalFloat(getProp(keys.scale, fontDict)), buttonTextSizeAdjust: retOptionalFloat(getProp(keys.scale, fontDict)), errorTextSizeAdjust: retOptionalFloat(getProp(keys.scale, fontDict)), linkTextSizeAdjust: retOptionalFloat(getProp(keys.scale, fontDict)), modalTextSizeAdjust: retOptionalFloat(getProp(keys.scale, fontDict)), cardTextSizeAdjust: retOptionalFloat(getProp(keys.scale, fontDict)), }), primaryButton: Some({ shapes: Some({ borderRadius: retOptionalFloat( getProp(keys.primaryButton_borderRadius, primaryButtonShapesDict), ), borderWidth: retOptionalFloat( getProp(keys.primaryButton_borderWidth, primaryButtonShapesDict), ), shadow: { let primaryButtonShadowDict = getObj( keys.primaryButton_shapes == "" ? appearanceDict : primaryButtonShapesDict, keys.primaryButton_shadow, Dict.make(), ) let primaryButtonOffsetDict = getObj( primaryButtonShadowDict, keys.primaryButton_offset, Dict.make(), ) Some({ color: retOptionalStr(getProp(keys.primaryButton_color, primaryButtonShadowDict)), opacity: retOptionalFloat(getProp(keys.primaryButton_opacity, primaryButtonShadowDict)), blurRadius: retOptionalFloat( getProp(keys.primaryButton_blurRadius, primaryButtonShadowDict), ), offset: Some({ x: retOptionalFloat(getProp(keys.x, primaryButtonOffsetDict)), y: retOptionalFloat(getProp(keys.y, primaryButtonOffsetDict)), }), intensity: retOptionalFloat( getProp(keys.primaryButton_intensity, primaryButtonShadowDict), ), }) }, }), primaryButtonColor: from == "rn" || from == "flutter" ? { let primaryButtonColors = getObj( primaryButtonDict, keys.primaryButton_color, Dict.make(), ) let primaryButtonColorsLightDict = primaryButtonColors ->Dict.get(keys.primaryButton_light) ->Option.flatMap(JSON.Decode.object) let primaryButtonColorsDarkDict = primaryButtonColors ->Dict.get(keys.primaryButton_dark) ->Option.flatMap(JSON.Decode.object) Some( primaryButtonColorsLightDict === None && primaryButtonColorsDarkDict === None ? PrimaryButtonColor(Some(getPrimaryButtonColorFromDict(primaryButtonColors, keys))) : PrimaryButtonDefault({ light: Some( getPrimaryButtonColorFromDict( primaryButtonColorsLightDict->Option.getOr(Dict.make()), keys, ), ), dark: Some( getPrimaryButtonColorFromDict( primaryButtonColorsDarkDict->Option.getOr(Dict.make()), keys, ), ), }), ) } : switch keys.primaryButton_color { | "" => Some(PrimaryButtonColor(Some(getPrimaryButtonColorFromDict(primaryButtonDict, keys)))) | _ => let primaryButtonColorLightDict = getObj( primaryButtonDict, keys.primaryButton_light, Dict.make(), ) let primaryButtonColorDarkDict = getObj( primaryButtonDict, keys.primaryButton_dark, Dict.make(), ) Some( PrimaryButtonDefault({ light: Some(getPrimaryButtonColorFromDict(primaryButtonColorLightDict, keys)), dark: Some(getPrimaryButtonColorFromDict(primaryButtonColorDarkDict, keys)), }), ) }, }), googlePay: { buttonType: switch getString(googlePayDict, "buttonType", "") { | "BUY" => BUY | "BOOK" => BOOK | "CHECKOUT" => CHECKOUT | "DONATE" => DONATE | "ORDER" => ORDER | "PAY" => PAY | "SUBSCRIBE" => SUBSCRIBE | _ => PLAIN }, buttonStyle: switch googlePayButtonStyle { | Some(googlePayButtonStyle) => Some({ light: switch getString(googlePayButtonStyle, "light", "") { | "light" => #light | "dark" => #dark | _ => #dark }, dark: switch getString(googlePayButtonStyle, "dark", "") { | "light" => #light | "dark" => #dark | _ => #light }, }) | None => None }, }, applePay: { buttonType: switch getString(applePayDict, "buttonType", "") { | "buy" => #buy | "setUp" => #setUp | "inStore" => #inStore | "donate" => #donate | "checkout" => #checkout | "book" => #book | "subscribe" => #subscribe | _ => #plain }, buttonStyle: switch applePayButtonStyle { | Some(applePayButtonStyle) => Some({ light: switch getString(applePayButtonStyle, "light", "") { | "white" => #white | "whiteOutline" => #whiteOutline | "black" => #black | _ => #black }, dark: switch getString(applePayButtonStyle, "dark", "") { | "white" => #white | "whiteOutline" => #whiteOutline | "black" => #black | _ => #white }, }) | None => None }, }, theme: switch getString(appearanceDict, "theme", "") { | "Light" => Light | "Dark" => Dark | "Minimal" => Minimal | "FlatMinimal" => FlatMinimal | _ => Default }, } } let getPrimaryColor = (colors, ~theme=Default) => switch colors { | Colors(c) => c.primary | DefaultColors(df) => switch theme { | Dark => df.dark->Option.flatMap(d => d.primary) | _ => df.light->Option.flatMap(l => l.primary) } } let parseConfigurationDict = (configObj, from) => { let shippingDetailsDict = configObj->Dict.get("shippingDetails")->Option.flatMap(JSON.Decode.object) let billingDetailsDict = getObj(configObj, "defaultBillingDetails", Dict.make()) let _customerDict = configObj->Dict.get("customer")->Option.flatMap(JSON.Decode.object) let addressDict = getOptionalObj(billingDetailsDict, "address") let billingName = getOptionString(billingDetailsDict, "name") ->Option.getOr("default") ->String.split(" ") let appearanceDict = configObj->Dict.get("appearance")->Option.flatMap(JSON.Decode.object) let appearance = { from == "rn" || from == "flutter" || WebKit.platform === #web ? switch appearanceDict { | Some(appObj) => getAppearanceObj(appObj, NativeSdkPropsKeys.rnKeys, from) | None => defaultAppearance } : switch appearanceDict { | Some(appObj) => switch WebKit.platform { | #ios | #iosWebView => getAppearanceObj(appObj, NativeSdkPropsKeys.iosKeys, from) | #android | #androidWebView => getAppearanceObj(appObj, NativeSdkPropsKeys.androidKeys, from) | _ => defaultAppearance } | None => defaultAppearance } } let placeholderDict = configObj ->Dict.get("placeholder") ->Option.flatMap(JSON.Decode.object) ->Option.getOr(Dict.make()) let configuration = { allowsDelayedPaymentMethods: getBool(configObj, "allowsDelayedPaymentMethods", false), appearance, shippingDetails: switch shippingDetailsDict { | Some(shippingObj) => let addressObj = getOptionalObj(shippingObj, "address") let (first_name, last_name) = getOptionString(shippingObj, "name")->splitName //need changes switch addressObj { | None => None | Some(addressObj) => Some({ address: Some({ first_name, last_name, city: ?getOptionString(addressObj, "city"), country: ?getOptionString(addressObj, "country"), line1: ?getOptionString(addressObj, "line1"), line2: ?getOptionString(addressObj, "line2"), zip: ?getOptionString(addressObj, "postalCode"), state: ?getOptionString(addressObj, "state"), }), phone: Some({ number: ?getOptionString(shippingObj, "phoneNumber"), }), //isCheckboxSelected: getOptionBool(shippingObj, "isCheckboxSelected"), email: None, //getOptionString(shippingObj, "email"), //name: None, getOptionString(shippingObj, "name"), }) } | None => None }, primaryButtonLabel: getOptionString(configObj, "primaryButtonLabel"), paymentSheetHeaderText: getOptionString(configObj, "paymentSheetHeaderLabel"), savedPaymentScreenHeaderText: getOptionString(configObj, "savedPaymentSheetHeaderLabel"), displayDefaultSavedPaymentIcon: getBool(configObj, "displayDefaultSavedPaymentIcon", true), enablePartialLoading: getBool(configObj, "enablePartialLoading", false), // customer: switch customerDict { // | Some(obj) => // Some({ // id: getOptionString(obj, "id"), // ephemeralKeySecret: getOptionString(obj, "ephemeralKeySecret"), // }) // | _ => None // }, merchantDisplayName: getString(configObj, "merchantDisplayName", ""), defaultBillingDetails: switch addressDict { | None => None | Some(addressDict) => Some({ address: Some({ first_name: ?( billingName->Array.get(0) === Some("default") ? None : billingName->Array.get(0) ), last_name: ?(billingName->Array.length > 1 ? billingName[1] : None), city: ?getOptionString(addressDict, "city"), country: ?getOptionString(addressDict, "country"), line1: ?getOptionString(addressDict, "line1"), line2: ?getOptionString(addressDict, "line2"), zip: ?getOptionString(addressDict, "postalCode"), state: ?getOptionString(addressDict, "state"), }), phone: Some({ number: ?getOptionString(billingDetailsDict, "phoneNumber"), }), email: None, //getOptionString(billingDetailsDict, "email"), //name: None, getOptionString(billingDetailsDict, "name"), }) }, primaryButtonColor: getOptionString(configObj, "primaryButtonColor"), allowsPaymentMethodsRequiringShippingAddress: getBool( configObj, "allowsPaymentMethodsRequiringShippingAddress", false, ), displaySavedPaymentMethodsCheckbox: getBool( configObj, "displaySavedPaymentMethodsCheckbox", true, ), displaySavedPaymentMethods: getBool(configObj, "displaySavedPaymentMethods", true), defaultView: getBool(configObj, "defaultView", false), netceteraSDKApiKey: getOptionString(configObj, "netceteraSDKApiKey"), placeholder: { cardNumber: getString(placeholderDict, "cardNumber", "1234 1234 1234 1234"), expiryDate: getString(placeholderDict, "expiryDate", "MM / YY"), cvv: getString(placeholderDict, "cvv", "CVC"), }, } configuration } let nativeJsonToRecord = (jsonFromNative, rootTag) => { let dictfromNative = jsonFromNative->JSON.Decode.object->Option.getOr(Dict.make()) let configurationDict = getObj(dictfromNative, "configuration", Dict.make()) let from = getOptionString(dictfromNative, "from")->Option.getOr("native") let publishableKey = getString(dictfromNative, "publishableKey", "") let customBackendUrl = switch getOptionString(dictfromNative, "customBackendUrl") { | Some("") => None | val => val } let customLogUrl = switch getOptionString(dictfromNative, "customLogUrl") { | Some("") => None | val => val } let hyperParams = getObj(dictfromNative, "hyperParams", Dict.make()) { from, env: GlobalVars.checkEnv(publishableKey), rootTag, publishableKey, clientSecret: getString(dictfromNative, "clientSecret", ""), paymentMethodId: String.split(getString(dictfromNative, "clientSecret", ""), "_secret_") ->Array.get(0) ->Option.getOr(""), ephemeralKey: getOptionString(dictfromNative, "ephemeralKey"), customBackendUrl, customLogUrl, sessionId: "", sdkState: switch getString(dictfromNative, "type", "") { | "payment" => PaymentSheet | "hostedCheckout" => HostedCheckout | "google_pay" => CustomWidget(GOOGLE_PAY) | "paypal" => CustomWidget(PAYPAL) | "card" => CardWidget | "widgetPayment" => WidgetPaymentSheet | "paymentMethodsManagement" => PaymentMethodsManagement | "expressCheckout" => ExpressCheckoutWidget | "headless" => Headless | _ => NoView }, configuration: parseConfigurationDict(configurationDict, from), hyperParams: { appId: ?getOptionString(hyperParams, "appId"), country: getString(hyperParams, "country", ""), disableBranding: getBool(hyperParams, "disableBranding", true), userAgent: getOptionString(hyperParams, "user-agent"), confirm: getBool(hyperParams, "confirm", false), launchTime: ?getOptionFloat(hyperParams, "launchTime"), sdkVersion: getString(hyperParams, "sdkVersion", ""), device_model: getOptionString(hyperParams, "device_model"), os_type: getOptionString(hyperParams, "os_type"), os_version: getOptionString(hyperParams, "os_version"), deviceBrand: getOptionString(hyperParams, "deviceBrand"), }, customParams: getObj(dictfromNative, "customParams", Dict.make()), } }
7,441
10,601
hyperswitch-client-core
src/types/TabViewType.res
.res
type route = { key: int, icon?: string, title: string, accessible?: bool, accessibilityLabel?: string, testID?: string, componentHoc: ( ~isScreenFocus: bool, ~setConfirmButtonDataRef: React.element => unit, ) => React.element, } type scene = {route: route} type navigationState = { index: int, routes: array<route>, } type listener = int => unit type sceneRendererProps = { layout: ReactNative.Event.LayoutEvent.layout, position: ReactNative.Animated.Interpolation.t, jumpTo: string => unit, } type eventEmitterProps = {addEnterListener: (listener, unit) => unit} type onPageScrollEventData = { position: float, offset: float, } type onPageSelectedEventData = {position: float, offset: float} type pageScrollState = [#idle | #dragging | #settling] type onPageScrollStateChangedEventData = {pageScrollState: pageScrollState} type localeDirection = [#ltr | #rtl] type orientation = [#horizontal | #vertical] type overScrollMode = [#auto | #always | #never] type keyboardDismissMode = [#auto | #none | #"on-drag"] type tabBarPosition = [#top | #bottom] type pagerViewProps = { scrollEnabled: option<bool>, layoutDirection: option<localeDirection>, initialPage: option<int>, orientation: option<orientation>, offscreenPageLimit: option<int>, pageMargin: option<int>, overScrollMode: option<overScrollMode>, overdrag: option<bool>, keyboardDismissMode: option<keyboardDismissMode>, onPageScroll: onPageScrollEventData => unit, onPageSelected: onPageSelectedEventData => unit, onPageScrollStateChanged: onPageScrollStateChangedEventData => unit, } type pagerProps = { scrollEnabled: option<bool>, layoutDirection: option<localeDirection>, initialPage: option<int>, orientation: option<orientation>, offscreenPageLimit: option<int>, pageMargin: option<int>, overScrollMode: option<overScrollMode>, overdrag: option<bool>, keyboardDismissMode: option<keyboardDismissMode>, swipeEnabled: option<bool>, animationEnabled: option<bool>, onSwipeStart: unit => unit, onSwipeEnd: unit => unit, }
505
10,602
hyperswitch-client-core
src/types/PaymentMethodListType.res
.res
open Utils type payment_experience_type = INVOKE_SDK_CLIENT | REDIRECT_TO_URL | NONE type mandatePaymentType = { amount: int, currency: string, confirm: bool, customer_id: string, authentication_type: string, mandate_id: string, off_session: bool, business_country: string, business_label: string, } type card_networks = { card_network: string, eligible_connectors: array<JSON.t>, } type payment_method_types_card = { payment_method: string, payment_method_type: string, card_networks: option<array<card_networks>>, required_field: RequiredFieldsTypes.required_fields, } type bank_names = { bank_name: array<string>, eligible_connectors: array<JSON.t>, } type payment_method_types_bank_redirect = { payment_method: string, payment_method_type: string, bank_names: array<bank_names>, required_field: RequiredFieldsTypes.required_fields, } type payment_experience = { payment_experience_type: string, payment_experience_type_decode: payment_experience_type, eligible_connectors: array<JSON.t>, } type payment_method_types_wallet = { payment_method: string, payment_method_type: string, payment_method_type_wallet: SdkTypes.payment_method_type_wallet, payment_experience: array<payment_experience>, required_field: RequiredFieldsTypes.required_fields, } type payment_method_types_pay_later = { payment_method: string, payment_method_type: string, payment_experience: array<payment_experience>, required_field: RequiredFieldsTypes.required_fields, } type payment_method_types_open_banking = { payment_method: string, payment_method_type: string, payment_experience: array<payment_experience>, required_field: RequiredFieldsTypes.required_fields, } type payment_method_types_bank_debit = { payment_method: string, payment_method_type: string, payment_experience: array<payment_experience>, payment_method_type_var: RequiredFieldsTypes.payment_method_types_in_bank_debit, required_field: RequiredFieldsTypes.required_fields, } type payment_method = | CARD(payment_method_types_card) | WALLET(payment_method_types_wallet) | PAY_LATER(payment_method_types_pay_later) | BANK_REDIRECT(payment_method_types_bank_redirect) | CRYPTO(payment_method_types_pay_later) | OPEN_BANKING(payment_method_types_open_banking) | BANK_DEBIT(payment_method_types_bank_debit) type online = { user_agent?: string, accept_header?: string, language?: SdkTypes.localeTypes, color_depth?: int, java_enabled?: bool, java_script_enabled?: bool, screen_height?: int, screen_width?: int, time_zone?: int, device_model?: string, os_type?: string, os_version?: string, } type customer_acceptance = { acceptance_type: string, accepted_at: string, online: online, } type mandate_data = {customer_acceptance: customer_acceptance} type redirectType = { client_secret: string, return_url?: string, customer_id?: string, email?: string, payment_method?: string, payment_method_type?: string, payment_experience?: string, connector?: array<JSON.t>, payment_method_data?: JSON.t, billing?: SdkTypes.addressDetails, shipping?: SdkTypes.addressDetails, payment_token?: string, setup_future_usage?: string, payment_type?: string, mandate_data?: mandate_data, browser_info?: online, customer_acceptance?: customer_acceptance, card_cvc?: string, } let flattenPaymentListArray = (plist, item) => { let dict = item->getDictFromJson let payment_method_types_array = dict->getArray("payment_method_types") switch dict->getString("payment_method", "") { | "card" => payment_method_types_array->Array.map(item2 => { let dict2 = item2->getDictFromJson CARD({ payment_method: "card", payment_method_type: dict2->getString("payment_method_type", ""), card_networks: switch dict2->getArray("card_networks") { | [] => None | data => Some( data->Array.map(item3 => { let dict3 = item3->getDictFromJson { card_network: dict3->getString("card_network", ""), eligible_connectors: dict3->getArray("eligible_connectors"), } }), ) }, required_field: dict2->RequiredFieldsTypes.getRequiredFieldsFromDict, })->Js.Array.push(plist) }) | "wallet" => payment_method_types_array->Array.map(item2 => { let dict2 = item2->getDictFromJson WALLET({ payment_method: "wallet", payment_method_type: dict2->getString("payment_method_type", ""), payment_method_type_wallet: switch dict2->getString("payment_method_type", "") { | "google_pay" => GOOGLE_PAY | "apple_pay" => APPLE_PAY | "paypal" => PAYPAL | "samsung_pay" => SAMSUNG_PAY | _ => NONE }, payment_experience: dict2 ->getArray("payment_experience") ->Array.map(item3 => { let dict3 = item3->getDictFromJson { payment_experience_type: dict3->getString("payment_experience_type", ""), payment_experience_type_decode: switch dict3->getString("payment_experience_type", "") { | "invoke_sdk_client" => INVOKE_SDK_CLIENT | "redirect_to_url" => REDIRECT_TO_URL | _ => NONE }, eligible_connectors: dict3->getArray("eligible_connectors"), } }), required_field: dict2->RequiredFieldsTypes.getRequiredFieldsFromDict, })->Js.Array.push(plist) }) | "pay_later" => payment_method_types_array->Array.map(item2 => { let dict2 = item2->getDictFromJson PAY_LATER({ payment_method: "pay_later", payment_method_type: dict2->getString("payment_method_type", ""), payment_experience: dict2 ->getArray("payment_experience") ->Array.map(item3 => { let dict3 = item3->getDictFromJson { payment_experience_type: dict3->getString("payment_experience_type", ""), payment_experience_type_decode: switch dict3->getString("payment_experience_type", "") { | "invoke_sdk_client" => INVOKE_SDK_CLIENT | "redirect_to_url" => REDIRECT_TO_URL | _ => NONE }, eligible_connectors: dict3->getArray("eligible_connectors"), } }), required_field: dict2->RequiredFieldsTypes.getRequiredFieldsFromDict, })->Js.Array.push(plist) }) | "bank_redirect" => payment_method_types_array->Array.map(item2 => { let dict2 = item2->getDictFromJson BANK_REDIRECT({ payment_method: "bank_redirect", payment_method_type: dict2->getString("payment_method_type", ""), bank_names: dict2 ->getArray("bank_names") ->Array.map(item3 => { let dict3 = item3->getDictFromJson { bank_name: dict3 ->getArray("bank_name") ->Array.map(item4 => item4->JSON.stringify), eligible_connectors: dict3->getArray("eligible_connectors"), } }), required_field: dict2->RequiredFieldsTypes.getRequiredFieldsFromDict, })->Js.Array.push(plist) }) | "crypto" => payment_method_types_array->Array.map(item2 => { let dict2 = item2->getDictFromJson CRYPTO({ payment_method: "crypto", payment_method_type: dict2->getString("payment_method_type", ""), payment_experience: dict2 ->getArray("payment_experience") ->Array.map(item3 => { let dict3 = item3->getDictFromJson { payment_experience_type: dict3->getString("payment_experience_type", ""), payment_experience_type_decode: switch dict3->getString("payment_experience_type", "") { | "redirect_to_url" => REDIRECT_TO_URL | _ => NONE }, eligible_connectors: dict3->getArray("eligible_connectors"), } }), required_field: dict2->RequiredFieldsTypes.getRequiredFieldsFromDict, })->Js.Array.push(plist) }) | "open_banking" => payment_method_types_array->Array.map(item2 => { let dict2 = item2->getDictFromJson OPEN_BANKING({ payment_method: "open_banking", payment_method_type: dict2->getString("payment_method_type", ""), payment_experience: dict2 ->getArray("payment_experience") ->Array.map(item3 => { let dict3 = item3->getDictFromJson { payment_experience_type: dict3->getString("payment_experience_type", ""), payment_experience_type_decode: switch dict3->getString("payment_experience_type", "") { | "redirect_to_url" => REDIRECT_TO_URL | _ => NONE }, eligible_connectors: dict3->getArray("eligible_connectors"), } }), required_field: dict2->RequiredFieldsTypes.getRequiredFieldsFromDict, })->Js.Array.push(plist) }) | "bank_debit" => payment_method_types_array->Array.map(item2 => { let dict2 = item2->getDictFromJson BANK_DEBIT({ payment_method: "bank_debit", payment_method_type: dict2->getString("payment_method_type", ""), payment_method_type_var: switch dict2->getString("payment_method_type", "") { | "becs" => BECS | _ => Other }, payment_experience: dict2 ->getArray("payment_experience") ->Array.map(item3 => { let dict3 = item3->getDictFromJson { payment_experience_type: dict3->getString("payment_experience_type", ""), payment_experience_type_decode: switch dict3->getString("payment_experience_type", "") { | "redirect_to_url" => REDIRECT_TO_URL | _ => NONE }, eligible_connectors: dict3->getArray("eligible_connectors"), } }), required_field: dict2->RequiredFieldsTypes.getRequiredFieldsFromDict, })->Js.Array.push(plist) }) | _ => [] }->ignore plist } let getPaymentMethodType = pm => { switch pm { | CARD(_) => "card" | WALLET(payment_method_type) => payment_method_type.payment_method_type | PAY_LATER(payment_method_type) => payment_method_type.payment_method_type | BANK_REDIRECT(payment_method_type) => payment_method_type.payment_method_type | CRYPTO(payment_method_type) => payment_method_type.payment_method_type | OPEN_BANKING(payment_method_type) => payment_method_type.payment_method_type | BANK_DEBIT(payment_method_type) => payment_method_type.payment_method_type } } let getPaymentExperienceType = (payment_experience_type: payment_experience_type) => { switch payment_experience_type { | INVOKE_SDK_CLIENT => "INVOKE_SDK_CLIENT" | REDIRECT_TO_URL => "REDIRECT_TO_URL" | NONE => "" } } let sortPaymentListArray = (plist: array<payment_method>) => { let priorityArr = Types.defaultConfig.priorityArr plist->Array.sort((s1, s2) => { let intResult = priorityArr->Array.findIndex(x => x == s2->getPaymentMethodType) - priorityArr->Array.findIndex(x => x == s1->getPaymentMethodType) intResult->Ordering.fromInt }) plist } let jsonTopaymentMethodListType: JSON.t => array<payment_method> = res => { res ->getDictFromJson ->Dict.get("payment_methods") ->Option.flatMap(JSON.Decode.array) ->Option.getOr([]) ->Array.reduce(([]: array<payment_method>), flattenPaymentListArray) ->sortPaymentListArray } let jsonToRedirectUrlType: JSON.t => option<string> = res => { res ->getDictFromJson ->Dict.get("redirect_url") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.string } type mandateType = NORMAL | NEW_MANDATE | SETUP_MANDATE type jsonToMandateData = { mandateType: mandateType, paymentType: option<string>, merchantName: option<string>, requestExternalThreeDsAuthentication: option<bool>, } let jsonToMandateData: JSON.t => jsonToMandateData = res => { switch res ->getDictFromJson ->Dict.get("payment_type") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.string { | Some(pType) => { mandateType: switch pType { | "setup_mandate" => SETUP_MANDATE | "new_mandate" => NEW_MANDATE | _ => NORMAL }, paymentType: Some(pType), merchantName: res ->getDictFromJson ->Dict.get("merchant_name") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.string, requestExternalThreeDsAuthentication: res ->getDictFromJson ->Dict.get("request_external_three_ds_authentication") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.bool, } | None => { mandateType: NORMAL, paymentType: None, merchantName: None, requestExternalThreeDsAuthentication: None, } } } let getPaymentBody = (body, dynamicFieldsJson) => { let flattenedBodyDict = body->Utils.getJsonObjectFromRecord->RequiredFieldsTypes.flattenObject(true) let dynamicFieldsJsonDict = dynamicFieldsJson->Array.reduce(Dict.make(), (acc, (key, val, _)) => { acc->Dict.set(key, val) acc }) flattenedBodyDict ->RequiredFieldsTypes.mergeTwoFlattenedJsonDicts(dynamicFieldsJsonDict) ->RequiredFieldsTypes.getArrayOfTupleFromDict ->Dict.fromArray ->JSON.Encode.object } let jsonToSavedPMObj = data => { let customerSavedPMs = data->Utils.getDictFromJson->Utils.getArrayFromDict("customer_payment_methods", []) customerSavedPMs->Array.reduce([], (acc, obj) => { let savedPMData = obj->Utils.getDictFromJson let cardData = savedPMData->Dict.get("card")->Option.flatMap(JSON.Decode.object) let paymentMethodType = savedPMData ->Dict.get("payment_method") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.string ->Option.getOr("") switch paymentMethodType { | "card" => switch cardData { | Some(card) => acc->Array.push( SdkTypes.SAVEDLISTCARD({ cardScheme: card->Utils.getString("scheme", "cardv1"), name: card->Utils.getString("nick_name", ""), cardHolderName: card->Utils.getString("card_holder_name", ""), cardNumber: "**** "->String.concat(card->Utils.getString("last4_digits", "")), expiry_date: card->Utils.getString("expiry_month", "") ++ "/" ++ card->Utils.getString("expiry_year", "")->String.sliceToEnd(~start=-2), payment_token: savedPMData->Utils.getString("payment_token", ""), paymentMethodId: savedPMData->Utils.getString("payment_method_id", ""), nick_name: card->Utils.getString("nick_name", ""), isDefaultPaymentMethod: savedPMData->Utils.getBool("default_payment_method_set", false), requiresCVV: savedPMData->Utils.getBool("requires_cvv", false), created: savedPMData->Utils.getString("created", ""), lastUsedAt: savedPMData->Utils.getString("last_used_at", ""), }), ) | None => () } | "wallet" => acc->Array.push( SdkTypes.SAVEDLISTWALLET({ payment_method_type: savedPMData->Utils.getString("payment_method_type", ""), walletType: savedPMData ->Utils.getString("payment_method_type", "") ->SdkTypes.walletNameMapper, payment_token: savedPMData->Utils.getString("payment_token", ""), paymentMethodId: savedPMData->Utils.getString("payment_method_id", ""), isDefaultPaymentMethod: savedPMData->Utils.getBool("default_payment_method_set", false), created: savedPMData->Utils.getString("created", ""), lastUsedAt: savedPMData->Utils.getString("last_used_at", ""), }), ) // | TODO: add suport for "bank_debit" | _ => () } acc }) }
3,687
10,603
hyperswitch-client-core
src/types/LoggerTypes.res
.res
type logType = DEBUG | INFO | ERROR | WARNING type logCategory = API | USER_ERROR | USER_EVENT | MERCHANT_EVENT type logComponent = MOBILE type apiLogType = Request | Response | NoResponse | Err type sdkVersionFetched = | PACKAGE_JSON_NOT_STARTED | PACKAGE_JSON_LOADING | PACKAGE_JSON_REFERENCE_ERROR | PACKAGE_JSON_LOADED(string) type eventName = | APP_RENDERED | S3_API | INACTIVE_SCREEN | COUNTRY_CHANGED | SDK_CLOSED | PAYMENT_METHOD_CHANGED | PAYMENT_DATA_FILLED | PAYMENT_ATTEMPT | PAYMENT_SUCCESS | PAYMENT_FAILED | INPUT_FIELD_CHANGED | RETRIEVE_CALL_INIT | RETRIEVE_CALL | CONFIRM_CALL_INIT | CONFIRM_CALL | SESSIONS_CALL_INIT | SESSIONS_CALL | PAYMENT_METHODS_CALL_INIT | PAYMENT_METHODS_CALL | CUSTOMER_PAYMENT_METHODS_CALL_INIT | CUSTOMER_PAYMENT_METHODS_CALL | CONFIG_CALL_INIT | CONFIG_CALL | BLUR | FOCUS | REDIRECTING_USER | PAYMENT_SESSION_INITIATED | LOADER_CHANGED | SCAN_CARD | AUTHENTICATION_CALL_INIT | AUTHENTICATION_CALL | AUTHORIZE_CALL_INIT | AUTHORIZE_CALL | POLL_STATUS_CALL_INIT | POLL_STATUS_CALL | DISPLAY_THREE_DS_SDK | NETCETERA_SDK | APPLE_PAY_STARTED_FROM_JS | APPLE_PAY_CALLBACK_FROM_NATIVE | APPLE_PAY_PRESENT_FAIL_FROM_NATIVE | APPLE_PAY_BRIDGE_SUCCESS | NO_WALLET_ERROR | DELETE_PAYMENT_METHODS_CALL_INIT | DELETE_PAYMENT_METHODS_CALL | DELETE_SAVED_PAYMENT_METHOD | ADD_PAYMENT_METHOD_CALL_INIT | ADD_PAYMENT_METHOD_CALL | SAMSUNG_PAY type logFile = { timestamp: string, logType: logType, component: logComponent, category: logCategory, version: string, codePushVersion: string, clientCoreVersion: string, value: string, internalMetadata: string, sessionId: string, merchantId: string, paymentId: string, appId?: string, platform: string, userAgent: string, eventName: eventName, latency?: string, firstEvent: bool, paymentMethod?: string, paymentExperience?: string, source: string, }
550
10,604
hyperswitch-client-core
src/types/PlaidTypes.res
.res
type linkLogLevel = DEBUG | INFO | WARN | ERROR type commonPlaidLinkOptions = { logLevel?: linkLogLevel, extras?: Js.Dict.t<Js.Json.t>, } type linkTokenConfiguration = { token: string, noLoadingState?: bool, ...commonPlaidLinkOptions, } type linkInstitution = { id: string, name: string, } type linkError = { errorCode: string, errorType: string, errorMessage: string, displayMessage?: string, errorJson?: string, } type linkExitMetadata = { status?: string, institution?: linkInstitution, linkSessionId: string, requestId: string, metadataJson?: string, } type linkExit = { error?: linkError, metadata: linkExitMetadata, } type linkIOSPresentationStyle = FULL_SCREEN | MODAL type linkOpenProps = { onSuccess: linkExit => unit, onExit?: linkExit => unit, iOSPresentationStyle?: linkIOSPresentationStyle, logLevel?: linkLogLevel, }
226
10,605
hyperswitch-client-core
src/utility/libraries/ReactNativeSvg.res
.res
module Svg = { @module("react-native-svg/src") @react.component external make: ( ~uri: string=?, ~width: float=?, ~viewBox: string=?, ~height: float=?, ~fill: string=?, ~onError: unit => unit=?, ~onLoad: unit => unit=?, ~children: React.element=?, ) => React.element = "Svg" } module Defs = { @module("react-native-svg/src") @react.component external make: ( ~uri: string=?, ~width: string=?, ~viewBox: string=?, ~height: string=?, ~fill: string=?, ~onError: unit => unit=?, ~onLoad: unit => unit=?, ~children: React.element=?, ) => React.element = "Defs" } module RadialGradient = { @module("react-native-svg/src") @react.component external make: ( ~id: string=?, ~cx: string=?, ~cy: string=?, ~fx: string=?, ~fy: string=?, ~uri: string=?, ~gradientTransform: string=?, ~width: float=?, ~height: float=?, ~fill: string=?, ~onError: unit => unit=?, ~onLoad: unit => unit=?, ~children: React.element=?, ) => React.element = "RadialGradient" } module Stop = { @module("react-native-svg/src") @react.component external make: (~offset: string, ~stopColor: string, ~stopOpacity: string=?) => React.element = "Stop" } module Circle = { @module("react-native-svg/src") @react.component external make: ( ~uri: string=?, ~cx: string=?, ~cy: string=?, ~r: string=?, ~fill: string=?, ~opacity: string=?, ~stroke: string=?, ~strokeWidth: string=?, ~strokeLinecap: string=?, ~strokeDasharray: string=?, ~strokeDashoffset: string=?, ~transformOrigin: string=?, ~origin: string=?, ~onError: unit => unit=?, ~onLoad: unit => unit=?, ) => React.element = "Circle" } module AnimateTransform = { @module("react-native-svg/src") @react.component external make: ( ~attributeName: string=?, ~\"type": string=?, ~from: string=?, ~to: string=?, ~dur: string=?, ~repeatCount: string=?, ~values: string=?, ~keyTimes: string=?, ~keySplines: string=?, ~uri: string=?, ~width: float=?, ~height: float=?, ~fill: string=?, ~onError: unit => unit=?, ~onLoad: unit => unit=?, ) => React.element = "AnimateTransform" } module SvgUri = { @module("react-native-svg/css") @react.component external make: ( ~uri: string, ~width: float, ~height: float, ~fill: string, ~onError: unit => unit, ~onLoad: unit => unit, ) => React.element = "SvgCssUri" } module SvgCss = { @module("react-native-svg/css") @react.component external make: ( ~xml: string, ~width: float, ~height: float, ~fill: string, ~onError: unit => unit, ~onLoad: unit => unit, ) => React.element = "SvgCss" }
832
10,606
hyperswitch-client-core
src/utility/libraries/RescriptCoreFuture.res
.res
module Dict = { type key = string let map = (mapper, dict) => { dict ->Dict.toArray ->Array.map(entry => { let (key, val) = entry (key, mapper(val)) }) ->Dict.fromArray } let fromList = list => { Dict.fromArray(list->List.toArray) } } module Nullable = { external isNullable: 'a => bool = "#is_nullable" } module JSON = { let stringArray = arr => arr->Js.Json.stringArray let numberArray = arr => arr->Js.Json.numberArray let objectArray = arr => arr->Js.Json.objectArray }
149
10,607
hyperswitch-client-core
src/utility/libraries/portal/PortalManager.res
.res
type portalItem = { key: int, children: React.element, } type portals = { mount: (int, React.element) => unit, update: (int, React.element) => unit, unmount: int => unit, } @react.component let make = React.forwardRef((ref: Js.Nullable.t<React.ref<Nullable.t<portals>>>) => { let (portals, setPortals) = React.useState(_ => []) let mount = React.useCallback0((key, children) => { setPortals(prevPortals => [...prevPortals, {key, children}]) }) let update = React.useCallback0((key, children) => { setPortals( prevPortals => prevPortals->Array.map(item => item.key === key ? {...item, children} : item), ) }) let unmount = React.useCallback0(key => { setPortals(prevPortals => prevPortals->Array.filter(item => item.key !== key)) }) React.useImperativeHandle0(ref, () => Value({ mount, update, unmount, })) { portals ->Array.map(({key, children}) => <ReactNative.View key={key->Int.toString} collapsable=false pointerEvents=#"box-none" style=ReactNative.StyleSheet.absoluteFill> {children} </ReactNative.View> ) ->React.array } })
319
10,608
hyperswitch-client-core
src/utility/libraries/portal/Portal.res
.res
@react.component let make = (~children) => { let portalManager = React.useContext(PortalContext.portalContext) let currentPortalKey = React.useRef(null) React.useEffect1(() => { switch currentPortalKey.current->Nullable.toOption { | Some(key) => portalManager.update(key, children) | None => currentPortalKey.current = Value(portalManager.mount(children)) } Some( () => { switch currentPortalKey.current->Nullable.toOption { | Some(key) => portalManager.unmount(key) currentPortalKey.current = Null | None => () } }, ) }, [children]) React.null }
147
10,609
hyperswitch-client-core
src/utility/libraries/portal/PortalHost.res
.res
open ReactNative open PortalContext @react.component let make = (~children) => { let managerRef = React.useRef(null) let nextKey = React.useRef(0) let queue = React.useRef([]) React.useEffect1(() => { switch managerRef.current->Nullable.toOption { | Some(manager: PortalManager.portals) => while queue.current->Array.length > 0 { switch queue.current->Array.pop { | Some(Mount(val)) => manager.mount(val.key, val.children)->ignore | Some(Update(val)) => manager.update(val.key, children)->ignore | Some(Unmount(val)) => manager.unmount(val.key) | None => () } } | None => () } None }, [managerRef.current]) let mount = React.useCallback0(children => { let key = nextKey.current + 1 switch managerRef.current->Nullable.toOption { | Some(manager) => manager.mount(key, children) | None => queue.current->Array.push(Mount({key, children})) } key }) let update = React.useCallback0((key, children) => { switch managerRef.current->Nullable.toOption { | Some(manager) => manager.update(key, children) | None => let index = queue.current->Array.findIndex(o => switch o { | Mount(_) => true | Update(val) => val.key === key | _ => false } ) if index > -1 { queue.current[index] = Update({key, children}) } else { queue.current->Array.push(Update({key, children})) } } }) let unmount = React.useCallback0(key => { switch managerRef.current->Nullable.toOption { | Some(manager) => manager.unmount(key) | None => queue.current->Array.push(Unmount({key: key})) } }) <PortalContext value={mount, update, unmount}> <View style={Style.viewStyle(~flex=1., ())} collapsable=false pointerEvents=#"box-none"> children </View> <PortalManager ref={managerRef} /> </PortalContext> }
480
10,610
hyperswitch-client-core
src/utility/libraries/portal/PortalContext.res
.res
type operation = | Mount({key: int, children: React.element}) | Unmount({key: int}) | Update({key: int, children: React.element}) type portalMethods = { mount: React.element => int, update: (int, React.element) => unit, unmount: int => unit, } let defaultVal = { mount: _ => 0, unmount: _ => (), update: (_, _) => (), } let portalContext = React.createContext(defaultVal) module Provider = { let make = React.Context.provider(portalContext) } @react.component let make = (~children, ~value) => { <Provider value> children </Provider> }
151
10,611
hyperswitch-client-core
src/utility/libraries/bsfetch/Fetch__Iterator.ml
.ml
module Next = struct type 'a t external done_ : _ t -> bool option = "done" [@@bs.get] external value : 'a t -> 'a option = "value" [@@bs.get] [@@bs.return nullable] end type 'a t external next : 'a t -> 'a Next.t = "next" [@@bs.send] let rec forEach ~f t = let item = next t in match Next.(done_ item, value item) with | Some true, Some value -> f value [@bs] | Some true, None -> () | (Some false | None), Some value -> f value [@bs]; forEach ~f t | (Some false | None), None -> forEach ~f t
170
10,612
hyperswitch-client-core
src/utility/libraries/bsfetch/Fetch__Iterator.mli
.mli
(** We need to bind to JavaScript Iterators for FormData functionality. But ideally this binding should be moved into BuckleScript itself. @see {{: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols}} *) module Next : sig type 'a t external done_ : _ t -> bool option = "done" [@@bs.get] external value : 'a t -> 'a option = "value" [@@bs.get] [@@bs.return nullable] end type 'a t val forEach : f:('a -> unit [@bs]) -> 'a t -> unit (** [forEach ~f iterator] runs [f] on each item returned by the [iterator]. This is not defined by the platform but a convenience function. *) external next : 'a t -> 'a Next.t = "next" [@@bs.send]
190
10,613
hyperswitch-client-core
src/utility/libraries/bsfetch/Fetch.res
.res
type body type bodyInit type headers type headersInit type response type request type requestInit type abortController type signal /* external */ type arrayBuffer /* TypedArray */ type bufferSource /* Web IDL, either an arrayBuffer or arrayBufferView */ type formData /* XMLHttpRequest */ type readableStream /* Streams */ type urlSearchParams /* URL */ type blob type file module AbortController = { type t = abortController @get external signal: t => signal = "signal" @send external abort: t => unit = "abort" @new external make: unit => t = "AbortController" } type requestMethod = | Get | Head | Post | Put | Delete | Connect | Options | Trace | Patch | Other(string) let encodeRequestMethod = x => /* internal */ switch x { | Get => "GET" | Head => "HEAD" | Post => "POST" | Put => "PUT" | Delete => "DELETE" | Connect => "CONNECT" | Options => "OPTIONS" | Trace => "TRACE" | Patch => "PATCH" | Other(method_) => method_ } let decodeRequestMethod = x => /* internal */ switch x { | "GET" => Get | "HEAD" => Head | "POST" => Post | "PUT" => Put | "DELETE" => Delete | "CONNECT" => Connect | "OPTIONS" => Options | "TRACE" => Trace | "PATCH" => Patch | method_ => Other(method_) } type referrerPolicy = | None | NoReferrer | NoReferrerWhenDowngrade | SameOrigin | Origin | StrictOrigin | OriginWhenCrossOrigin | StrictOriginWhenCrossOrigin | UnsafeUrl let encodeReferrerPolicy = x => /* internal */ switch x { | NoReferrer => "no-referrer" | None => "" | NoReferrerWhenDowngrade => "no-referrer-when-downgrade" | SameOrigin => "same-origin" | Origin => "origin" | StrictOrigin => "strict-origin" | OriginWhenCrossOrigin => "origin-when-cross-origin" | StrictOriginWhenCrossOrigin => "strict-origin-when-cross-origin" | UnsafeUrl => "unsafe-url" } let decodeReferrerPolicy = x => /* internal */ switch x { | "no-referrer" => NoReferrer | "" => None | "no-referrer-when-downgrade" => NoReferrerWhenDowngrade | "same-origin" => SameOrigin | "origin" => Origin | "strict-origin" => StrictOrigin | "origin-when-cross-origin" => OriginWhenCrossOrigin | "strict-origin-when-cross-origin" => StrictOriginWhenCrossOrigin | "unsafe-url" => UnsafeUrl | e => raise(Failure("Unknown referrerPolicy: " ++ e)) } type requestType = | None /* default? unknown? just empty string in spec */ | Audio | Font | Image | Script | Style | Track | Video let decodeRequestType = x => /* internal */ switch x { | "audio" => Audio | "" => None | "font" => Font | "image" => Image | "script" => Script | "style" => Style | "track" => Track | "video" => Video | e => raise(Failure("Unknown requestType: " ++ e)) } type requestDestination = | None /* default? unknown? just empty string in spec */ | Document | Embed | Font | Image | Manifest | Media | Object | Report | Script | ServiceWorker | SharedWorker | Style | Worker | Xslt let decodeRequestDestination = x => /* internal */ switch x { | "document" => Document | "" => None | "embed" => Embed | "font" => Font | "image" => Image | "manifest" => Manifest | "media" => Media | "object" => Object | "report" => Report | "script" => Script | "serviceworker" => ServiceWorker | "sharedworder" => SharedWorker | "style" => Style | "worker" => Worker | "xslt" => Xslt | e => raise(Failure("Unknown requestDestination: " ++ e)) } type requestMode = | Navigate | SameOrigin | NoCORS | CORS let encodeRequestMode = x => /* internal */ switch x { | Navigate => "navigate" | SameOrigin => "same-origin" | NoCORS => "no-cors" | CORS => "cors" } let decodeRequestMode = x => /* internal */ switch x { | "navigate" => Navigate | "same-origin" => SameOrigin | "no-cors" => NoCORS | "cors" => CORS | e => raise(Failure("Unknown requestMode: " ++ e)) } type requestCredentials = | Omit | SameOrigin | Include let encodeRequestCredentials = x => /* internal */ switch x { | Omit => "omit" | SameOrigin => "same-origin" | Include => "include" } let decodeRequestCredentials = x => /* internal */ switch x { | "omit" => Omit | "same-origin" => SameOrigin | "include" => Include | e => raise(Failure("Unknown requestCredentials: " ++ e)) } type requestCache = | Default | NoStore | Reload | NoCache | ForceCache | OnlyIfCached let encodeRequestCache = x => /* internal */ switch x { | Default => "default" | NoStore => "no-store" | Reload => "reload" | NoCache => "no-cache" | ForceCache => "force-cache" | OnlyIfCached => "only-if-cached" } let decodeRequestCache = x => /* internal */ switch x { | "default" => Default | "no-store" => NoStore | "reload" => Reload | "no-cache" => NoCache | "force-cache" => ForceCache | "only-if-cached" => OnlyIfCached | e => raise(Failure("Unknown requestCache: " ++ e)) } type requestRedirect = | Follow | Error | Manual let encodeRequestRedirect = x => /* internal */ switch x { | Follow => "follow" | Error => "error" | Manual => "manual" } let decodeRequestRedirect = x => /* internal */ switch x { | "follow" => Follow | "error" => Error | "manual" => Manual | e => raise(Failure("Unknown requestRedirect: " ++ e)) } module HeadersInit = { type t = headersInit let make: {..} => t = Utils.getJsonObjectFromRecord let makeWithDict: Js.Dict.t<string> => t = Utils.getJsonObjectFromRecord let makeWithArray: array<(string, string)> => t = Utils.getJsonObjectFromRecord } module Headers = { type t = headers @new external make: t = "Headers" @new external makeWithInit: headersInit => t = "Headers" @send external append: (t, string, string) => unit = "append" @send external delete: (t, string) => unit = "delete" /* entries */ /* very experimental */ @send @return({null_to_opt: null_to_opt}) external get: (t, string) => option<string> = "get" @send external has: (t, string) => bool = "has" /* keys */ /* very experimental */ @send external set: (t, string, string) => unit = "set" /* values */ /* very experimental */ } module BodyInit = { type t = bodyInit let make: string => t = Utils.getJsonObjectFromRecord let makeWithBlob: blob => t = Utils.getJsonObjectFromRecord let makeWithBufferSource: bufferSource => t = Utils.getJsonObjectFromRecord let makeWithFormData: formData => t = Utils.getJsonObjectFromRecord let makeWithUrlSearchParams: urlSearchParams => t = Utils.getJsonObjectFromRecord } module Body = { module Impl = ( T: { type t }, ) => { @get external body: T.t => readableStream = "body" @get external bodyUsed: T.t => bool = "bodyUsed" @send external arrayBuffer: T.t => Js.Promise.t<arrayBuffer> = "arrayBuffer" @send external blob: T.t => Js.Promise.t<blob> = "blob" @send external formData: T.t => Js.Promise.t<formData> = "formData" @send external json: T.t => Js.Promise.t<Js.Json.t> = "json" @send external text: T.t => Js.Promise.t<string> = "text" } type t = body include Impl({ type t = t }) } module RequestInit = { type t = requestInit let map = (f, x) => /* internal */ switch x { | Some(v) => Some(f(v)) | None => None } @obj external make: ( ~method: string=?, ~headers: headersInit=?, ~body: bodyInit=?, ~referrer: string=?, ~referrerPolicy: string=?, ~mode: string=?, ~credentials: string=?, ~cache: string=?, ~redirect: string=?, ~integrity: string=?, ~keepalive: bool=?, ~signal: signal=?, ) => requestInit = "" let make = ( ~method_: option<requestMethod>=?, ~headers: option<headersInit>=?, ~body: option<bodyInit>=?, ~referrer: option<string>=?, ~referrerPolicy: referrerPolicy=None, ~mode: option<requestMode>=?, ~credentials: option<requestCredentials>=?, ~cache: option<requestCache>=?, ~redirect: option<requestRedirect>=?, ~integrity: string="", ~keepalive: option<bool>=?, ~signal: option<signal>=?, (), ) => make( ~method=?map(encodeRequestMethod, method_), ~headers?, ~body?, ~referrer?, ~referrerPolicy=encodeReferrerPolicy(referrerPolicy), ~mode=?map(encodeRequestMode, mode), ~credentials=?map(encodeRequestCredentials, credentials), ~cache=?map(encodeRequestCache, cache), ~redirect=?map(encodeRequestRedirect, redirect), ~integrity, ~keepalive?, ~signal?, ) } module Request = { type t = request include Body.Impl({ type t = t }) @new external make: string => t = "Request" @new external makeWithInit: (string, requestInit) => t = "Request" @new external makeWithRequest: t => t = "Request" @new external makeWithRequestInit: (t, requestInit) => t = "Request" @get external method__: t => string = "method" let method_: t => requestMethod = self => decodeRequestMethod(method__(self)) @get external url: t => string = "url" @get external headers: t => headers = "headers" @get external type_: t => string = "type" let type_: t => requestType = self => decodeRequestType(type_(self)) @get external destination: t => string = "destination" let destination: t => requestDestination = self => decodeRequestDestination(destination(self)) @get external referrer: t => string = "referrer" @get external referrerPolicy: t => string = "referrerPolicy" let referrerPolicy: t => referrerPolicy = self => decodeReferrerPolicy(referrerPolicy(self)) @get external mode: t => string = "mode" let mode: t => requestMode = self => decodeRequestMode(mode(self)) @get external credentials: t => string = "credentials" let credentials: t => requestCredentials = self => decodeRequestCredentials(credentials(self)) @get external cache: t => string = "cache" let cache: t => requestCache = self => decodeRequestCache(cache(self)) @get external redirect: t => string = "redirect" let redirect: t => requestRedirect = self => decodeRequestRedirect(redirect(self)) @get external integrity: t => string = "integrity" @get external keepalive: t => bool = "keepalive" @get external signal: t => signal = "signal" } module Response = { type t = response include Body.Impl({ type t = t }) @val external error: unit => t = "error" @val external redirect: string => t = "redirect" @val external redirectWithStatus: (string, int /* enum-ish */) => t = "redirect" @get external headers: t => headers = "headers" @get external ok: t => bool = "ok" @get external redirected: t => bool = "redirected" @get external status: t => int = "status" @get external statusText: t => string = "statusText" @get external type_: t => string = "type" @get external url: t => string = "url" @send external clone: t => t = "clone" } module FormData = { module EntryValue = { type t let classify: t => [> #String(string) | #File(file)] = t => if Js.typeof(t) == "string" { #String(Obj.magic(t)) } else { #File(Obj.magic(t)) } } module Iterator = Fetch__Iterator type t = formData @new external make: unit => t = "FormData" @send external append: (t, string, string) => unit = "append" @send external delete: (t, string) => unit = "delete" @send external get: (t, string) => option<EntryValue.t> = "get" @send external getAll: (t, string) => array<EntryValue.t> = "getAll" @send external set: (t, string, string) => unit = "set" @send external has: (t, string) => bool = "has" @send external keys: t => Iterator.t<string> = "keys" @send external values: t => Iterator.t<EntryValue.t> = "values" @send external appendObject: (t, string, {..}, ~filename: string=?) => unit = "append" @send external appendBlob: (t, string, blob, ~filename: string=?) => unit = "append" @send external appendFile: (t, string, file, ~filename: string=?) => unit = "append" @send external setObject: (t, string, {..}, ~filename: string=?) => unit = "set" @send external setBlob: (t, string, blob, ~filename: string=?) => unit = "set" @send external setFile: (t, string, file, ~filename: string=?) => unit = "set" @send external entries: t => Iterator.t<(string, EntryValue.t)> = "entries" } @val external fetch: string => Js.Promise.t<response> = "fetch" @val external fetchWithInit: (string, requestInit) => Js.Promise.t<response> = "fetch" @val external fetchWithRequest: request => Js.Promise.t<response> = "fetch" @val external fetchWithRequestInit: (request, requestInit) => Js.Promise.t<response> = "fetch"
3,653
10,614
hyperswitch-client-core
src/utility/logics/PMLUtils.res
.res
let handleCustomerPMLResponse = ( ~customerSavedPMData, ~sessions: AllApiDataContext.sessions, ~isPaymentMethodManagement, ~nativeProp: SdkTypes.nativeProp, ) => { switch customerSavedPMData { | Some(obj) => { let spmData = obj->PaymentMethodListType.jsonToSavedPMObj let isSamsungDevice = nativeProp.hyperParams.deviceBrand->Option.getOr("") == "samsung" let sessionSpmData = spmData->Array.filter(data => { switch data { | SAVEDLISTWALLET(val) => let walletType = val.walletType->Option.getOr("")->SdkTypes.walletNameToTypeMapper switch (walletType, WebKit.platform) { | (GOOGLE_PAY, #android) | (GOOGLE_PAY, #androidWebView) | (APPLE_PAY, #ios) | (APPLE_PAY, #iosWebView) => true | (SAMSUNG_PAY, #android) | (SAMSUNG_PAY, #androidWebView) => isSamsungDevice && WebKit.platform === #android | _ => false } | _ => false } }) let walletSpmData = spmData->Array.filter(data => { switch data { | SAVEDLISTWALLET(val) => let walletType = val.walletType->Option.getOr("")->SdkTypes.walletNameToTypeMapper switch walletType { | GOOGLE_PAY | APPLE_PAY | SAMSUNG_PAY => false | _ => true } | _ => false } }) let cardSpmData = spmData->Array.filter(data => { switch data { | SAVEDLISTCARD(_) => true | _ => false } }) let filteredSpmData = switch sessions { | Some(sessions) => let walletNameArray = sessions->Array.map(wallet => wallet.wallet_name) let filteredSessionSpmData = sessionSpmData->Array.filter(data => switch data { | SAVEDLISTWALLET(data) => walletNameArray->Array.includes( data.walletType->Option.getOr("")->SdkTypes.walletNameToTypeMapper, ) | _ => false } ) filteredSessionSpmData->Array.concat(walletSpmData->Array.concat(cardSpmData)) | _ => isPaymentMethodManagement ? spmData : walletSpmData->Array.concat(cardSpmData) } let isGuestFromPMList = obj ->Utils.getDictFromJson ->Dict.get("is_guest_customer") ->Option.flatMap(JSON.Decode.bool) ->Option.getOr(false) let savedPaymentMethods: AllApiDataContext.savedPaymentMethods = Some({ pmList: Some(filteredSpmData), isGuestCustomer: isGuestFromPMList, selectedPaymentMethod: None, }) savedPaymentMethods } | None => None } }
647
10,615
hyperswitch-client-core
src/utility/logics/ThreeDsUtils.res
.res
open ExternalThreeDsTypes let getThreeDsNextActionObj = ( nextActionObj: option<PaymentConfirmTypes.nextAction>, ): PaymentConfirmTypes.nextAction => { nextActionObj->Option.getOr({ redirectToUrl: "", type_: "", threeDsData: { threeDsAuthenticationUrl: "", threeDsAuthorizeUrl: "", messageVersion: "", directoryServerId: "", pollConfig: { pollId: "", delayInSecs: 0, frequency: 0, }, }, }) } let getThreeDsDataObj = ( nextActionObj: PaymentConfirmTypes.nextAction, ): PaymentConfirmTypes.threeDsData => { nextActionObj.threeDsData->Option.getOr({ threeDsAuthenticationUrl: "", threeDsAuthorizeUrl: "", messageVersion: "", directoryServerId: "", pollConfig: { pollId: "", delayInSecs: 0, frequency: 0, }, }) } let generateAuthenticationCallBody = (clientSecret, aReqParams) => { let ephemeralKeyDict = aReqParams.sdkEphemeralKey ->JSON.Decode.string ->Option.getOr("") ->JSON.parseExn ->JSON.Decode.object ->Option.getOr(Dict.make()) let body: authCallBody = { client_secret: clientSecret, device_channel: "APP", threeds_method_comp_ind: "N", sdk_information: { sdk_app_id: aReqParams.sdkAppId, sdk_enc_data: aReqParams.deviceData, sdk_ephem_pub_key: { kty: ephemeralKeyDict->Utils.getString("kty", ""), crv: ephemeralKeyDict->Utils.getString("crv", ""), x: ephemeralKeyDict->Utils.getString("x", ""), y: ephemeralKeyDict->Utils.getString("y", ""), }, sdk_trans_id: aReqParams.sdkTransId, sdk_reference_number: aReqParams.sdkReferenceNo, sdk_max_timeout: 10, }, } let stringifiedBody = body->JSON.stringifyAny->Option.getOr("") stringifiedBody } let getAuthCallHeaders = publishableKey => { [ ("Content-Type", "application/json"), ("api-key", publishableKey), ("Accept", "application/json"), // ("x-feature", "router-custom-be"), ]->Dict.fromArray } let isStatusSuccess = (status: statusType) => { status.status === "success" } // let getMessageVersionFromConfirmResponse = dict => { // let externalAuthDict = // Dict.get(dict, "external_authentication_details") // ->Option.getOr(JSON.Encode.null) // ->JSON.Decode.object // ->Option.getOr(Dict.make()) // Utils.getString(externalAuthDict, "version", "") // } let sdkEnvironmentToStrMapper = (env: GlobalVars.envType) => { switch env { | GlobalVars.SANDBOX => "SANDBOX" | GlobalVars.PROD => "PROD" | GlobalVars.INTEG => "INTEG" } }
683
10,616
hyperswitch-client-core
src/utility/logics/GZipUtils.res
.res
type options = {to: string} @module("pako") external inflate: (Fetch.arrayBuffer, options) => string = "inflate" let extractZipFromResp = resp => { resp ->Promise.then(response => response->Fetch.Response.arrayBuffer) ->Promise.then(async arrayBuffer => arrayBuffer->inflate({ to: "string", }) ) ->Promise.then(async data => data) } // let fetchAndExtractZip = link => { // Fetch.fetchWithInit(link, Fetch.RequestInit.make(~method_=Get, ()))->extractZipFromResp // } let extractJson = async resp => { try { JSON.parseExn(await extractZipFromResp(resp)) } catch { | _ => JSON.Encode.null } } // let fetchAndExtractJson = async link => { // try { // JSON.parseExn(await fetchAndExtractZip(link)) // } catch { // | _ => JSON.Encode.null // } // }
210
10,617
hyperswitch-client-core
src/utility/logics/PaymentUtils.res
.res
let checkIfMandate = (paymentType: PaymentMethodListType.mandateType) => { paymentType == NEW_MANDATE || paymentType == SETUP_MANDATE } let showUseExisitingSavedCardsBtn = ( ~isGuestCustomer, ~pmList, ~mandateType, ~displaySavedPaymentMethods, ) => { !isGuestCustomer && pmList->Option.getOr([])->Array.length > 0 && (mandateType == PaymentMethodListType.NEW_MANDATE || mandateType == NORMAL) && displaySavedPaymentMethods } let generatePaymentMethodData = ( ~prop: PaymentMethodListType.payment_method_types_card, ~cardData: CardDataContext.cardData, ~cardHolderName: option<'a>, ~nickname: option<'a>, ) => { let (month, year) = Validation.getExpiryDates(cardData.expireDate) [ ( prop.payment_method, [ ("card_number", cardData.cardNumber->Validation.clearSpaces->JSON.Encode.string), ("card_exp_month", month->JSON.Encode.string), ("card_exp_year", year->JSON.Encode.string), ( "card_holder_name", switch cardHolderName { | Some(cardHolderName) => cardHolderName->JSON.Encode.string | None => JSON.Encode.null }, ), ( "nick_name", switch nickname { | Some(nick) => nick->JSON.Encode.string | None => JSON.Encode.null }, ), ("card_cvc", cardData.cvv->JSON.Encode.string), ( "card_network", switch cardData.selectedCoBadgedCardBrand { | Some(selectedCoBadgedCardBrand) => selectedCoBadgedCardBrand->JSON.Encode.string | None => switch cardData.cardBrand { | "" => JSON.Encode.null | cardBrand => cardBrand->JSON.Encode.string } }, ), ] ->Dict.fromArray ->JSON.Encode.object, ), ] ->Dict.fromArray ->JSON.Encode.object ->Some } let generateCardConfirmBody = ( ~nativeProp: SdkTypes.nativeProp, ~prop: PaymentMethodListType.payment_method_types_card, ~payment_method_data=?, ~allApiData: AllApiDataContext.allApiData, ~isNicknameSelected=false, ~payment_token=?, ~isSaveCardCheckboxVisible=?, ~isGuestCustomer, (), ): PaymentMethodListType.redirectType => { let isMandate = allApiData.additionalPMLData.mandateType->checkIfMandate { client_secret: nativeProp.clientSecret, return_url: ?Utils.getReturnUrl(~appId=nativeProp.hyperParams.appId, ~appURL=allApiData.additionalPMLData.redirect_url), payment_method: prop.payment_method, payment_method_type: ?Some(prop.payment_method_type), connector: ?switch prop.card_networks { | Some(cardNetwork) => cardNetwork ->Array.get(0) ->Option.mapOr(None, card_network => card_network.eligible_connectors->Some) | None => None }, ?payment_method_data, ?payment_token, billing: ?nativeProp.configuration.defaultBillingDetails, shipping: ?nativeProp.configuration.shippingDetails, // setup_future_usage: ?switch (allApiData.mandateType != NORMAL, isNicknameSelected) { // | (true, _) => Some("off_session") // | (false, true) => Some("on_session") // | (false, false) => None // }, // setup_future_usage: { // isNicknameSelected || isMandate->Option.getOr(false) // ? "off_session" // : "on_session" // }, payment_type: ?allApiData.additionalPMLData.paymentType, // mandate_data: ?( // (isNicknameSelected && isMandate->Option.getOr(false)) || // isMandate->Option.getOr(false) && // !isNicknameSelected && // !(isSaveCardCheckboxVisible->Option.getOr(false)) || // (allApiData.mandateType == NORMAL && isNicknameSelected) // ? Some({ // customer_acceptance: { // acceptance_type: "online", // accepted_at: Date.now()->Date.fromTime->Date.toISOString, // online: { // ip_address: ?nativeProp.hyperParams.ip, // user_agent: ?nativeProp.hyperParams.userAgent, // }, // }, // }) // : None // ), // moved customer_acceptance outside mandate_data customer_acceptance: ?( payment_token->Option.isNone && ((isNicknameSelected && isMandate) || isMandate && !isNicknameSelected && !(isSaveCardCheckboxVisible->Option.getOr(false)) || allApiData.additionalPMLData.mandateType == NORMAL && isNicknameSelected || allApiData.additionalPMLData.mandateType == SETUP_MANDATE) && !isGuestCustomer ? 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, device_model: ?nativeProp.hyperParams.device_model, os_type: ?nativeProp.hyperParams.os_type, os_version: ?nativeProp.hyperParams.os_version, }, } } let checkIsCVCRequired = (pmObject: SdkTypes.savedDataType) => switch pmObject { | SAVEDLISTCARD(obj) => obj.requiresCVV | _ => false } let generateSavedCardConfirmBody = ( ~nativeProp: SdkTypes.nativeProp, ~payment_token, ~savedCardCvv, ): PaymentMethodListType.redirectType => { client_secret: nativeProp.clientSecret, payment_method: "card", payment_token, card_cvc: ?(savedCardCvv->Option.isSome ? Some(savedCardCvv->Option.getOr("")) : None), } let generateWalletConfirmBody = ( ~nativeProp: SdkTypes.nativeProp, ~payment_token, ~payment_method_type, ): PaymentMethodListType.redirectType => { client_secret: nativeProp.clientSecret, payment_token, payment_method: "wallet", payment_method_type, } let getActionType = (nextActionObj: option<PaymentConfirmTypes.nextAction>) => { let actionType = nextActionObj->Option.getOr({type_: "", redirectToUrl: ""}) actionType.type_ } let getCardNetworks = cardNetworks => { switch cardNetworks { | Some(cardNetworks) => cardNetworks->Array.map((item: PaymentMethodListType.card_networks) => item.card_network) | None => [] } }
1,547
10,618
hyperswitch-client-core
src/utility/logics/Utils.res
.res
let getProp = (str, dict) => { dict->Dict.get(str) } let retOptionalStr = x => { switch x { | Some(c) => c->JSON.Decode.string | None => None } } let retOptionalFloat = x => { switch x { | Some(c) => c->JSON.Decode.float | None => None } } let getOptionString = (dict, key) => { dict->Dict.get(key)->Option.flatMap(JSON.Decode.string) } let getOptionFloat = (dict, key) => { dict->Dict.get(key)->retOptionalFloat } let getString = (dict, key, default) => { getOptionString(dict, key)->Option.getOr(default) } let getBool = (dict, key, default) => { dict ->Dict.get(key) ->Option.flatMap(JSON.Decode.bool) ->Option.getOr(default) } let getObj = (dict, key, default) => { dict ->Dict.get(key) ->Option.flatMap(JSON.Decode.object) ->Option.getOr(default) } let getOptionalObj = (dict, key) => { dict ->Dict.get(key) ->Option.flatMap(JSON.Decode.object) } let getOptionalArrayFromDict = (dict, key) => { dict->Dict.get(key)->Option.flatMap(JSON.Decode.array) } let getArrayFromDict = (dict, key, default) => { dict->getOptionalArrayFromDict(key)->Option.getOr(default) } let getDictFromJson = (json: JSON.t) => { json->JSON.Decode.object->Option.getOr(Dict.make()) } let getDictFromJsonKey = (json, key) => { json->Dict.get(key)->Option.getOr(JSON.Encode.null)->getDictFromJson } let getArray = (dict, key) => { dict->getOptionalArrayFromDict(key)->Option.getOr([]) } let getJsonObjectFromDict = (dict, key) => { dict->Dict.get(key)->Option.getOr(JSON.Encode.object(Dict.make())) } let convertToScreamingSnakeCase = text => { text->String.trim->String.replaceRegExp(%re("/ /g"), "_")->String.toUpperCase } // TODO subtraction 365 days can be done in exactly one year way // let formattedDateTimeFloat = (dateTime: Date.t, format: string) => { // (dateTime->dateFlotToDateTimeObject->Date.toString->DayJs.getDayJsForString).format(. format) // } let toCamelCase = str => { if str->String.includes(":") { str } else { str ->String.toLowerCase ->String.unsafeReplaceRegExpBy0(%re(`/([-_][a-z])/g`), ( ~match as letter, ~offset as _, ~input as _, ) => { letter->String.toUpperCase }) ->String.replaceRegExp(%re(`/[^a-zA-Z]/g`), "") } } let rec transformKeysSnakeToCamel = (json: JSON.t) => { let dict = json->getDictFromJson dict ->Dict.toArray ->Array.map(((key, value)) => { let x = switch JSON.Classify.classify(value) { | Object(obj) => (key->toCamelCase, obj->JSON.Encode.object->transformKeysSnakeToCamel) | Array(arr) => ( key->toCamelCase, { arr ->Array.map(item => if item->JSON.Decode.object->Option.isSome { item->transformKeysSnakeToCamel } else { item } ) ->JSON.Encode.array }, ) | String(str) => { let val = if str == "Final" { "FINAL" } else if str == "example" { "adyen" } else if str == "exampleGatewayMerchantId" { "Sampras123ECOM" } else { str } (key->toCamelCase, val->JSON.Encode.string) } | Number(val) => (key->toCamelCase, val->Float.toString->JSON.Encode.string) | Null | Bool(_) => (key->toCamelCase, value) } x }) ->Dict.fromArray ->JSON.Encode.object } let getHeader = (apiKey, appId, ~redirectUri=?) => { [ ("api-key", apiKey), ("x-app-id", Js.String.replace(".hyperswitch://", "", appId->Option.getOr(""))), ("x-redirect-uri", redirectUri->Option.getOr("")), // ("x-feature", "router-custom-be"), ]->Dict.fromArray } let getCountryFlags = isoAlpha2 => { Array.map(isoAlpha2->String.split(""), letter => { String.fromCodePoint( 0x1F1E6 + letter->String.charCodeAt(0)->Int.fromFloat - "A"->String.charCodeAt(0)->Int.fromFloat, ) })->Array.join("") ++ " " } let getStateNames = (list: CountryStateDataHookTypes.states, country: string) => { let options = list->Dict.get(country)->Option.getOr([]) options->Array.reduce([], (arr, item) => { arr ->Array.push(item) ->ignore arr }) } let getClientCountry = (countryArr: CountryStateDataHookTypes.countries, clientTimeZone) => { countryArr ->Array.find(item => item.timeZones->Array.find(i => i == clientTimeZone)->Option.isSome) ->Option.getOr(CountryStateDataHookTypes.defaultTimeZone) } let getStateNameFromStateCodeAndCountry = ( list: CountryStateDataHookTypes.states, stateCode: string, country: option<string>, ) => { switch (list, country) { | (list, Some(country)) => let options = list ->Dict.get(country) ->Option.getOr([]) let val = options->Array.find(item => item.code === stateCode) switch val { | Some(stateObj) => stateObj.value | None => stateCode } | (_, _) => stateCode } } let splitName = (str: option<string>) => { switch str { | None => ("", "") | Some(s) => if s == "" { ("", "") } else { let lastSpaceIndex = String.lastIndexOf(s, " ") if lastSpaceIndex === -1 { (s, "") } else { let first = String.slice(s, ~start=0, ~end=lastSpaceIndex) let last = String.slice(s, ~start=lastSpaceIndex + 1, ~end=s->String.length) (first, last) } } } } let getStringFromJson = (json, default) => { json->JSON.Decode.string->Option.getOr(default) } let underscoresToSpaces = str => { str->String.replaceAll("_", " ") } let toCamelCase = str => { if str->String.includes(":") { str } else { str ->String.toLowerCase ->Js.String2.unsafeReplaceBy0(%re(`/([-_][a-z])/g`), (letter, _, _) => { letter->String.toUpperCase }) ->String.replaceRegExp(%re(`/[^a-zA-Z]/g`), "") } } let toSnakeCase = str => { str->Js.String2.unsafeReplaceBy0(%re("/[A-Z]/g"), (letter, _, _) => `_${letter->String.toLowerCase}` ) } let toKebabCase = str => { str ->String.split("") ->Array.mapWithIndex((item, i) => { if item->String.toUpperCase === item { `${i != 0 ? "-" : ""}${item->String.toLowerCase}` } else { item } }) ->Array.join("") } type case = CamelCase | SnakeCase | KebabCase let rec transformKeys = (json: JSON.t, to: case) => { let toCase = switch to { | CamelCase => toCamelCase | SnakeCase => toSnakeCase | KebabCase => toKebabCase } let dict = json->getDictFromJson dict ->Dict.toArray ->Array.map(((key, value)) => { let x = switch JSON.Classify.classify(value) { | Object(obj) => (key->toCase, obj->JSON.Encode.object->transformKeys(to)) | Array(arr) => ( key->toCase, { arr ->Array.map(item => if item->JSON.Decode.object->Option.isSome { item->transformKeys(to) } else { item } ) ->JSON.Encode.array }, ) | String(str) => { let val = if str == "Final" { "FINAL" } else if str == "example" || str == "Adyen" { "adyen" } else { str } (key->toCase, val->JSON.Encode.string) } // | Number(val) => (key->toCase, val->Float.toString->JSON.Encode.string) | Number(val) => (key->toCase, val->Float.toInt->JSON.Encode.int) | Null | Bool(_) => (key->toCase, value) } x }) ->Dict.fromArray ->JSON.Encode.object } let getStrArray = (dict, key) => { dict ->getOptionalArrayFromDict(key) ->Option.getOr([]) ->Array.map(json => json->getStringFromJson("")) } let getOptionalStrArray: (Dict.t<JSON.t>, string) => option<array<string>> = (dict, key) => { switch dict->getOptionalArrayFromDict(key) { | Some(val) => val->Array.length === 0 ? None : Some(val->Array.map(json => json->getStringFromJson(""))) | None => None } } let getArrofJsonString = (arr: array<string>) => { arr->Array.map(item => item->JSON.Encode.string) } let getCustomReturnAppUrl = (~appId) => { switch appId { | Some(id) => Some(id ++ ".hyperswitch://") | None => None } } let getReturnUrlWeb = (~appURL) => switch appURL { | Some(url) => url->Some | _ => None // Window.location.href->Some } let getReturnUrl = (~appId, ~appURL: option<string>=None, ~useAppUrl=false) => { switch WebKit.platform { | #android => switch appURL { | Some(_) => getCustomReturnAppUrl(~appId) | _ => None } | #ios => switch (appURL, useAppUrl) { | (Some(url), true) => url->Some | (Some(_), false) => getCustomReturnAppUrl(~appId) | _ => None } | _ => getReturnUrlWeb(~appURL) } } let getStringFromRecord = record => record->JSON.stringifyAny->Option.getOr("") let getJsonObjectFromRecord = record => record->Obj.magic let getError = (err, defaultError) => { switch err->Exn.asJsExn { | Some(exn) => exn->Exn.message->Option.getOr(defaultError)->JSON.Encode.string | None => defaultError->JSON.Encode.string } }
2,550
10,619
hyperswitch-client-core
src/utility/logics/Window.res
.res
type listener<'ev> = 'ev => unit @val @scope("window") @val external postMessage: (string, string) => unit = "postMessage" @val @scope(("window", "parent")) @val external postMessageToParent: (string, string) => unit = "postMessage" @val @scope("window") external addEventListener: (string, listener<'ev>) => unit = "addEventListener" @val @scope("window") external removeEventListener: (string, listener<'ev>) => unit = "removeEventListener" type location = {href: string} @val @scope("window") external location: location = "location" @get external getHref: location => string = "href" @set external setHref: (location, string) => unit = "href" let setHref = url => { setHref(location, url) } type tab = {location: location, close: unit => unit} @val @scope("window") external open_: string => Nullable.t<tab> = "open" type status = [#loading | #idle | #ready | #error | #load] type style = {mutable display: string} type parent = {style: style} type parentElement = {parentElement: parent} type rec element = { mutable getAttribute: string => status, mutable src: string, mutable async: bool, mutable rel: string, mutable href: string, mutable \"as": string, mutable crossorigin: string, mutable onclick: unit => unit, mutable appendChild: element => unit, mutable removeChild: element => unit, setAttribute: (string, string) => unit, removeAttribute: string => unit, parentElement: parentElement, } @val @scope("document") external querySelector: string => Nullable.t<element> = "querySelector" type event = {\"type": string} @val @scope("document") external createElement: string => element = "createElement" @val @scope(("document", "head")) external appendChildToHead: element => unit = "appendChild" @val @scope(("document", "body")) external appendChildToBody: element => unit = "appendChild" @send external addEventListenerToElement: (element, status, event => unit) => unit = "addEventListener" @send external removeEventListenerFromElement: (element, status, event => unit) => unit = "removeEventListener" let getStatusString = status => { switch status { | #loading => "loading" | #idle => "idle" | #ready => "ready" | #error => "error" | #load => "load" } } let useScript = (src: string) => { let (status, setStatus) = React.useState(_ => src != "" ? #loading : #idle) React.useEffect(() => { if src == "" { setStatus(_ => #idle) } let script = querySelector(`script[src="${src}"]`) switch script->Nullable.toOption { | Some(dom) => setStatus(_ => dom.getAttribute("data-status")) None | None => let script = createElement("script") script.src = src script.async = true script.setAttribute("data-status", #loading->getStatusString) appendChildToHead(script) let setAttributeFromEvent = (event: event) => { setStatus(_ => event.\"type" === "load" ? #ready : #error) script.setAttribute( "data-status", (event.\"type" === "load" ? #ready : #error)->getStatusString, ) } script->addEventListenerToElement(#load, setAttributeFromEvent) script->addEventListenerToElement(#error, setAttributeFromEvent) Some( () => { script->removeEventListenerFromElement(#load, setAttributeFromEvent) script->removeEventListenerFromElement(#error, setAttributeFromEvent) }, ) } }, [src]) status } let useLink = (src: string) => { let (status, setStatus) = React.useState(_ => src != "" ? #loading : #idle) React.useEffect(() => { if src == "" { setStatus(_ => #idle) } let link = querySelector(`link[href="${src}"]`) switch link->Nullable.toOption { | Some(dom) => setStatus(_ => dom.getAttribute("data-status")) None | None => let link = createElement("link") link.href = src link.rel = "stylesheet" link.async = true link.setAttribute("data-status", #loading->getStatusString) appendChildToHead(link) let setAttributeFromEvent = (event: event) => { setStatus(_ => event.\"type" === "load" ? #ready : #error) link.setAttribute( "data-status", (event.\"type" === "load" ? #ready : #error)->getStatusString, ) } link->addEventListenerToElement(#load, setAttributeFromEvent) link->addEventListenerToElement(#error, setAttributeFromEvent) Some( () => { link->removeEventListenerFromElement(#load, setAttributeFromEvent) link->removeEventListenerFromElement(#error, setAttributeFromEvent) }, ) } }, [src]) status } type postMessage = {postMessage: string => unit} type messageHandlers = { exitPaymentSheet?: postMessage, sdkInitialised?: postMessage, launchApplePay?: postMessage, } type webKit = {messageHandlers?: messageHandlers} @scope("window") external webKit: Nullable.t<webKit> = "webkit" type androidInterface = { sdkInitialised: string => unit, exitPaymentSheet: string => unit, launchGPay: string => unit, } @scope("window") external androidInterface: Nullable.t<androidInterface> = "AndroidInterface" type billingContact = { addressLines: array<string>, administrativeArea: string, countryCode: string, familyName: string, givenName: string, locality: string, postalCode: string, } type shippingContact = { emailAddress: string, phoneNumber: string, addressLines: array<string>, administrativeArea: string, countryCode: string, familyName: string, givenName: string, locality: string, postalCode: string, } type paymentResult = {token: JSON.t, billingContact: JSON.t, shippingContact: JSON.t} type applePayEvent = {validationURL: string, payment: paymentResult} type innerSession type session = { begin: unit => unit, abort: unit => unit, mutable oncancel: unit => unit, canMakePayments: unit => bool, mutable onvalidatemerchant: applePayEvent => unit, completeMerchantValidation: JSON.t => unit, mutable onpaymentauthorized: applePayEvent => unit, completePayment: JSON.t => unit, \"STATUS_SUCCESS": string, \"STATUS_FAILURE": string, } type applePaySession @scope("window") @val external sessionForApplePay: Nullable.t<session> = "ApplePaySession" type window = {\"ApplePaySession": applePaySession} @val external window: window = "window" @val external btoa: 'a => string = "btoa" @new external applePaySession: (int, JSON.t) => session = "ApplePaySession" type buttonProps = { onClick: unit => unit, buttonType: string, buttonSizeMode: string, buttonColor: string, buttonRadius: float, } type client = { isReadyToPay: JSON.t => Promise.t<JSON.t>, createButton: buttonProps => element, loadPaymentData: JSON.t => Promise.t<JSON.t>, } @new external google: JSON.t => client = "google.payments.api.PaymentsClient" @get external data: ReactEvent.Form.t => string = "data" let map: Map.t<string, Dict.t<JSON.t> => unit> = Map.make() let registerEventListener = (str: string, callback) => { map->Map.set(str, callback) } let useEventListener = () => { React.useEffect0(() => { let handleMessage = event => { try { let optionalJson = event ->data ->JSON.parseExn ->JSON.Decode.object map ->Map.keys ->Iterator.forEach(key => { switch key { | Some(key) => switch optionalJson->Option.flatMap(Dict.get(_, key)) { | Some(data) => switch map->Map.get(key) { | Some(callback) => data->JSON.Decode.object->Option.getOr(Dict.make())->callback | None => () } | None => () } | _ => () } }) } catch { | _ => () } } addEventListener("message", handleMessage) Some(() => removeEventListener("message", handleMessage)) }) }
1,941
10,620
hyperswitch-client-core
src/utility/logics/LoggerUtils.res
.res
open LoggerTypes let eventToStrMapper = (eventName: eventName) => { (eventName :> string) } let sdkVersionRef = ref(PACKAGE_JSON_NOT_STARTED) let logFileToObj = logFile => { [ ("timestamp", logFile.timestamp->JSON.Encode.string), ( "log_type", switch logFile.logType { | DEBUG => "DEBUG" | INFO => "INFO" | ERROR => "ERROR" | WARNING => "WARNING" }->JSON.Encode.string, ), ( "component", switch logFile.component { | MOBILE => "MOBILE" }->JSON.Encode.string, ), ( "category", switch logFile.category { | API => "API" | USER_ERROR => "USER_ERROR" | USER_EVENT => "USER_EVENT" | MERCHANT_EVENT => "MERCHANT_EVENT" }->JSON.Encode.string, ), ("version", logFile.version->JSON.Encode.string), // repoversion of orca-android ("code_push_version", logFile.codePushVersion->JSON.Encode.string), // replace with ota version ("client_core_version", logFile.clientCoreVersion->JSON.Encode.string), ("value", logFile.value->JSON.Encode.string), ("internal_metadata", logFile.internalMetadata->JSON.Encode.string), ("session_id", logFile.sessionId->JSON.Encode.string), ("merchant_id", logFile.merchantId->JSON.Encode.string), ("payment_id", logFile.paymentId->JSON.Encode.string), ( "app_id", logFile.appId ->Option.getOr(WebKit.platform->JSON.stringifyAny->Option.getOr("defaultAppId")) ->JSON.Encode.string, ), ("platform", logFile.platform->Utils.convertToScreamingSnakeCase->JSON.Encode.string), ("user_agent", logFile.userAgent->JSON.Encode.string), ("event_name", logFile.eventName->eventToStrMapper->JSON.Encode.string), ("first_event", (logFile.firstEvent ? "true" : "false")->JSON.Encode.string), ( "payment_method", logFile.paymentMethod ->Option.getOr("") ->Utils.convertToScreamingSnakeCase ->JSON.Encode.string, ), ( "payment_experience", switch logFile.paymentExperience { | None => "" | Some(exp) => exp }->JSON.Encode.string, ), ("latency", logFile.latency->Option.getOr("")->JSON.Encode.string), ("source", logFile.source->JSON.Encode.string), ] ->Dict.fromArray ->JSON.Encode.object } let sendLogs = (logFile, uri: option<string>, publishableKey, appId) => { if WebKit.platform != #next { switch uri { | Some("") | None => () | Some(uri) => let data = logFile->logFileToObj->JSON.stringify CommonHooks.fetchApi( ~uri, ~method_=Post, ~bodyStr=data, ~headers=Utils.getHeader(publishableKey, appId), ~mode=NoCORS, (), ) ->Promise.then(res => res->Fetch.Response.json) ->Promise.catch(_ => { Promise.resolve(JSON.Encode.null) }) ->ignore } } } type dataModule = {version: string} @val external importStates: string => promise<dataModule> = "import" let getClientCoreVersion = () => { if sdkVersionRef.contents == PACKAGE_JSON_NOT_STARTED { sdkVersionRef := PACKAGE_JSON_LOADING importStates("./../../../package.json") ->Promise.then(res => { sdkVersionRef := PACKAGE_JSON_LOADED(res.version) Promise.resolve() }) ->Promise.catch(_ => { sdkVersionRef := PACKAGE_JSON_REFERENCE_ERROR Promise.resolve() }) ->ignore } } let getClientCoreVersionNoFromRef = () => { switch sdkVersionRef.contents { | PACKAGE_JSON_LOADED(version) => version | PACKAGE_JSON_REFERENCE_ERROR => "reference_error" | _ => "loading" } }
877
10,621
hyperswitch-client-core
src/utility/logics/UIUtils.res
.res
module RenderIf = { @react.component let make = (~condition, ~children) => { if condition { children } else { React.null } } }
42
10,622
hyperswitch-client-core
src/utility/reusableCodeFromWeb/PostalCodes.res
.res
type postalCodes = { @dead note: string, @dead country: string, iso: string, @dead format: string, regex: string, } let defaultPostalCode = { note: "", country: "", iso: "", format: "", regex: "", } let postalCode = [ { note: "The first two digits (ranging from 10–43) correspond to the province, while the last two digits correspond either to the city/delivery zone (range 01–50) or to the district/delivery zone (range 51–99). Afghanistan Postal code lookup", country: "Afghanistan", iso: "AF", format: "NNNN", regex: "^\\d{4}$", }, { note: "With Finland, first two numbers are 22.", country: "Åland Islands", iso: "AX", format: "NNNNN", regex: "^\\d{5}$", }, { note: "Introduced in 2006, gradually implemented throughout 2007.", country: "Albania", iso: "AL", format: "NNNN", regex: "^\\d{4}$", }, { note: "First two as in ISO 3166-2:DZ", country: "Algeria", iso: "DZ", format: "NNNNN", regex: "^\\d{5}$", }, { note: "U.S. ZIP codes (range 96799)", country: "American Samoa", iso: "AS", format: "NNNNN (optionally NNNNN-NNNN or NNNNN-NNNNNN)", regex: "^\\d{5}(-{1}\\d{4,6})$", }, { note: "Each parish now has its own post code.", country: "Andorra", iso: "AD", format: "CCNNN", regex: "^[Aa][Dd]\\d{3}$", }, { note: "", country: "Angola", iso: "AO", format: "- no codes -", regex: "", }, { note: "Single code used for all addresses.", country: "Anguilla", iso: "AI", format: "AI-2640", regex: "^[Aa][I][-][2][6][4][0]$", }, { note: "", country: "Antigua and Barbuda", iso: "AG", format: "- no codes -", regex: "", }, { note: "Codigo Postal Argentino (CPA), where the first A is the province code as in ISO 3166-2:AR, the four numbers are the old postal codes, the three last letters indicate a side of the block. Previously NNNN which &#10;o the minimum requirement as of 2006.", country: "Argentina", iso: "AR", format: "1974-1998 NNNN; From 1999 ANNNNAAA", regex: "^\\d{4}|[A-Za-z]\\d{4}[a-zA-Z]{3}$", }, { note: "Previously used NNNNNN system inherited from former Soviet Union.", country: "Armenia", iso: "AM", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Aruba", iso: "AW", format: "- no codes -", regex: "", }, { note: "Single code used for all addresses. Part of UK system.", country: "Ascension island", iso: "AC", format: "AAAANAA one code: ASCN 1ZZ", regex: "^[Aa][Ss][Cc][Nn]\\s{0,1}[1][Zz][Zz]$", }, { note: "In general, the first digit identifies the state or territory.", country: "Australia", iso: "AU", format: "NNNN", regex: "^\\d{4}$", }, { note: "The first digit denotes regions, which are partly identical to one of the nine provinces—called Bundesländer; the last the nearest post office in the area.", country: "Austria", iso: "AT", format: "NNNN", regex: "^\\d{4}$", }, { note: "Previously used NNNNNN system inherited from former Soviet Union.", country: "Azerbaijan", iso: "AZ", format: "CCNNNN", regex: "^[Aa][Zz]\\d{4}$", }, { note: "", country: "Bahamas", iso: "BS", format: "- no codes -", regex: "", }, { note: "Valid post code numbers are 101 to 1216 with gaps in the range. Known as block number (Arabic: رقم المجمع‎) formally. The first digit in NNN format and the first two digits in NNNN format refer to one of the 12 municipalities of the country. PO Box address doesn't need a block number or city name, just the PO Box number followed by the name of the country, Bahrain.", country: "Bahrain", iso: "BH", format: "NNN or NNNN", regex: "^\\d{3,4}$", }, { note: "", country: "Bangladesh", iso: "BD", format: "NNNN", regex: "^\\d{4}$", }, { note: "Only one postal code currently assigned. 11000 applies to the General Post Office building in Cheapside, Bridgetown, to enable delivery to Barbados by global package delivery companies whose software requires a postal code.", country: "Barbados", iso: "BB", format: "CCNNNNN", regex: "^[Aa][Zz]\\d{5}$", }, { note: "Retained system inherited from former Soviet Union.", country: "Belarus", iso: "BY", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "In general, the first digit gives the province.", country: "Belgium", iso: "BE", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Belize", iso: "BZ", format: "- no codes -", regex: "", }, { note: "", country: "Benin", iso: "BJ", format: "- no codes -", regex: "", }, { note: "AA NN for street addresses, AA AA for P.O. Box addresses. The second half of the postcode identifies the street delivery walk (e.g.: Hamilton HM 12) or the PO Box number range (e.g.: Hamilton HM BX). See Postal codes in Bermuda.", country: "Bermuda", iso: "BM", format: "AA NN or AA AA", regex: "^[A-Za-z]{2}\\s([A-Za-z]{2}|\\d{2})$", }, { note: "", country: "Bhutan", iso: "BT", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Bolivia", iso: "BO", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Bonaire, Sint Eustatius and Saba", iso: "BQ", format: "- no codes -", regex: "", }, { note: "", country: "Bosnia and Herzegovina", iso: "BA", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Botswana", iso: "BW", format: "- no codes -", regex: "", }, { note: "Código de Endereçamento Postal (CEP): -000 to -899 are used for streets, roads, avenues, boulevards; -900 to -959 are used for buildings with a high postal use; -960 to -969 are for promotional use; -970 to -989 are post offices and regular P.O. boxes; and -990 to -998 are used for community P.O. boxes. -999 is used for special services.", country: "Brazil", iso: "BR", format: "NNNNN-NNN (NNNNN from 1971 to 1992)", regex: "^\\d{5}-\\d{3}$", }, { note: "Single code used for all addresses.", country: "British Antarctic Territory", iso: "", format: "BIQQ 1ZZ", regex: "^[Bb][Ii][Qq]{2}\\s{0,1}[1][Zz]{2}$", }, { note: "UK territory, but not UK postcode.", country: "British Indian Ocean Territory", iso: "IO", format: "AAAANAA one code: BBND 1ZZ", regex: "^[Bb]{2}[Nn][Dd]\\s{0,1}[1][Zz]{2}$", }, { note: "Specifically, VG1110 through VG1160[1]", country: "British Virgin Islands", iso: "VG", format: "CCNNNN", regex: "^[Vv][Gg]\\d{4}$", }, { note: "", country: "Brunei", iso: "BN", format: "AANNNN", regex: "^[A-Za-z]{2}\\d{4}$", }, { note: "", country: "Bulgaria", iso: "BG", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Burkina Faso", iso: "BF", format: "- no codes -", regex: "", }, { note: "", country: "Burundi", iso: "BI", format: "- no codes -", regex: "", }, { note: "", country: "Cambodia", iso: "KH", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Cameroon", iso: "CM", format: "- no codes -", regex: "", }, { note: "The system was gradually introduced starting in April 1971 in Ottawa. The letters D, F, I, O, Q, and U are not used to avoid confusion with other letters or numbers.", country: "Canada", iso: "CA", format: "ANA NAN", regex: "^(?=[^DdFfIiOoQqUu\\d\\s])[A-Za-z]\\d(?=[^DdFfIiOoQqUu\\d\\s])[A-Za-z]\\s{0,1}\\d(?=[^DdFfIiOoQqUu\\d\\s])[A-Za-z]\\d$", }, { note: "The first digit indicates the island.", country: "Cape Verde", iso: "CV", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Cayman Islands", iso: "KY", format: "CCN-NNNN", regex: "^[Kk][Yy]\\d[-\\s]{0,1}\\d{4}$", }, { note: "", country: "Central African Republic", iso: "CF", format: "- no codes -", regex: "", }, { note: "", country: "Chad", iso: "TD", format: "NNNNN", regex: "^\\d{5}$", }, { note: "May only be required for bulk mail.", country: "Chile", iso: "CL", format: "NNNNNNN (NNN-NNNN)", regex: "^\\d{7}\\s\\(\\d{3}-\\d{4}\\)$", }, { note: "A postal code or youbian (邮编) in a subordinate division will have the same first two digits as its governing one (see Political divisions of China. The postal services in Macau or Hong Kong Special Administrative Regions remain separate from Mainland China, with no post code system currently used.", country: "China", iso: "CN", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "Part of the Australian postal code system.", country: "Christmas Island", iso: "CX", format: "NNNN", regex: "^\\d{4}$", }, { note: "Part of the Australian postal code system.", country: "Cocos (Keeling) Island", iso: "CC", format: "NNNN", regex: "^\\d{4}$", }, { note: "First NN = 32 departments Códigos Postales | 4-72", country: "Colombia", iso: "CO", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "", country: "Comoros", iso: "KM", format: "- no codes -", regex: "", }, { note: "", country: "Congo (Brazzaville)", iso: "CG", format: "- no codes -", regex: "", }, { note: "", country: "Congo, Democratic Republic", iso: "CD", format: "- no codes -", regex: "^[Cc][Dd]$", }, { note: "", country: "Cook Islands", iso: "CK", format: "- no codes -", regex: "", }, { note: "First codes the provinces, next two the canton, last two the district.", country: "Costa Rica", iso: "CR", format: "NNNNN (NNNN until 2007)", regex: "^\\d{4,5}$", }, { note: "", country: "Côte d'Ivoire (Ivory Coast)", iso: "CI", format: "- no codes -", regex: "", }, { note: "", country: "Croatia", iso: "HR", format: "NNNNN", regex: "^\\d{5}$", }, { note: "May only be required for bulk mail. The letters CP are frequently used before the postal code. This is not a country code, but an abbreviation for \"codigo postal\" or postal code.", country: "Cuba", iso: "CU", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Curaçao", iso: "CW", format: "- no codes -", regex: "", }, { note: "Post code system covers whole island, but not used in Northern Cyprus where 'Mersin 10, Turkey' is used instead.", country: "Cyprus", iso: "CY", format: "NNNN", regex: "^\\d{4}$", }, { note: "With Slovak Republic, Poštovní směrovací číslo (PSČ) - postal routing number.", country: "Czech Republic", iso: "CZ", format: "NNNNN (NNN NN)", regex: "^\\d{5}\\s\\(\\d{3}\\s\\d{2}\\)$", }, { note: "Numbering follows the dispatch of postal trains from Copenhagen.[3] Also used by Greenland, e.g.: DK-3900 Nuuk.", country: "Denmark", iso: "DK", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Djibouti", iso: "DJ", format: "- no codes -", regex: "", }, { note: "", country: "Dominica", iso: "DM", format: "- no codes -", regex: "", }, { note: "", country: "Dominican Republic", iso: "DO", format: "NNNNN", regex: "^\\d{5}$", }, { note: "No postal code system in use since Indonesian withdrawal in 1999.", country: "East Timor", iso: "TL", format: "- no codes -", regex: "", }, { note: "", country: "Ecuador", iso: "EC", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "Used for all inbound mail to El Salvador. The postal office then distributes the mail internally depending on their destination.", country: "El Salvador", iso: "SV", format: "1101", regex: "^1101$", }, { note: "", country: "Egypt", iso: "EG", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Equatorial Guinea", iso: "GQ", format: "- no codes -", regex: "", }, { note: "", country: "Eritrea", iso: "ER", format: "- no codes -", regex: "", }, { note: "", country: "Estonia", iso: "EE", format: "NNNNN", regex: "^\\d{5}$", }, { note: "The code is only used on a trial basis for Addis Ababa addresses.", country: "Ethiopia", iso: "ET", format: "NNNN", regex: "^\\d{4}$", }, { note: "UK territory, but not UK postcode", country: "Falkland Islands", iso: "FK", format: "AAAANAA one code: FIQQ 1ZZ", regex: "^[Ff][Ii][Qq]{2}\\s{0,1}[1][Zz]{2}$", }, { note: "Self-governing territory within the Kingdom of Denmark, but not Danish postcode.", country: "Faroe Islands", iso: "FO", format: "NNN", regex: "^\\d{3}$", }, { note: "", country: "Fiji", iso: "FJ", format: "- no codes -", regex: "", }, { note: "A lower first digit indicates a place in south (for example 00100 Helsinki), a higher indicates a place further to north (99800 in Ivalo). The last digit is usually 0, except for postal codes for PO Box number ranges, in which case it is 1. Country code for Finland: \"FI\". In the Åland Islands, the postal code is prefixed with \"AX\", not \"FI\". Some postal codes for rural settlements may end with 5, and there are some unique postal codes for large companies and institutions, e.g. 00014 HELSINGIN YLIOPISTO (university), 00102 EDUSKUNTA (parliament), 00020 NORDEA (a major Scandinavian bank).", country: "Finland", iso: "FI", format: "NNNNN", regex: "^\\d{5}$", }, { note: "The first two digits give the département number, while in Paris, Lyon and Marseille, the last two digits of the postal code indicates the arrondissement. Both of the 2 corsican départements use \"20\" as the first two digits. Also used by French overseas departments and territories. Monaco is also part of the French postal code system, but the country code MC- is used for Monegasque addresses.", country: "France", iso: "FR", format: "NNNNN", regex: "^\\d{5}$", }, { note: "Overseas Department of France. French codes used. Range 97300 - 97390.", country: "French Guiana", iso: "GF", format: "973NN", regex: "^973\\d{2}$", }, { note: "Overseas Department of France. French codes used. Range 98700 - 98790.", country: "French Polynesia", iso: "PF", format: "987NN", regex: "^987\\d{2}$", }, { note: "French codes in the 98400 range have been reserved.", country: "French Southern and Antarctic Territories", iso: "TF", format: "- no codes -", regex: "", }, { note: "Two digit postal zone goes after city name.", country: "Gabon", iso: "GA", format: "NN [city name] NN", regex: "^\\d{2}\\s[a-zA-Z-_ ]\\s\\d{2}$", }, { note: "", country: "Gambia", iso: "GM", format: "- no codes -", regex: "", }, { note: "", country: "Georgia", iso: "GE", format: "NNNN", regex: "^\\d{4}$", }, { note: "Postleitzahl (PLZ)", country: "Germany", iso: "DE", format: "NN", regex: "^\\d{2}$", }, { note: "Postleitzahl (PLZ)", country: "Germany", iso: "DE", format: "NNNN", regex: "^\\d{4}$", }, { note: "Postleitzahl (PLZ), introduced after the German reunification. Between 1989 and 1993 the old separate 4-digit postal codes of former West- and East-Germany were distinguished by preceding \"W-\" or \"O-\" ('Ost' for East).", country: "Germany", iso: "DE", format: "NNNNN", regex: "^\\d{5}$", }, { note: "[citation needed]", country: "Ghana", iso: "GH", format: "- no codes -", regex: "", }, { note: "Single code used for all addresses.", country: "Gibraltar", iso: "GI", format: "GX11 1AA", regex: "^[Gg][Xx][1]{2}\\s{0,1}[1][Aa]{2}$", }, { note: "", country: "Greece", iso: "GR", format: "NNN NN", regex: "^\\d{3}\\s{0,1}\\d{2}$", }, { note: "Part of the Danish postal code system.", country: "Greenland", iso: "GL", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Grenada", iso: "GD", format: "- no codes -", regex: "", }, { note: "Overseas Department of France. French codes used. Range 97100 - 97190.", country: "Guadeloupe", iso: "GP", format: "971NN", regex: "^971\\d{2}$", }, { note: "U.S. ZIP codes. Range 96910 - 96932.", country: "Guam", iso: "GU", format: "NNNNN", regex: "^\\d{5}$", }, { note: "The first two numbers identify the department, the third number the route and the last two the office.", country: "Guatemala", iso: "GT", format: "NNNNN", regex: "^\\d{5}$", }, { note: "UK-format postcode (first two letters are always GY not GG)", country: "Guernsey", iso: "GG", format: "AAN NAA, AANN NAA", regex: "^[A-Za-z]{2}\\d\\s{0,1}\\d[A-Za-z]{2}$", }, { note: "", country: "Guinea", iso: "GN", format: "- no codes -", regex: "", }, { note: "", country: "Guinea Bissau", iso: "GW", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Guyana", iso: "GY", format: "- no codes -", regex: "", }, { note: "", country: "Haiti", iso: "HT", format: "NNNN", regex: "^\\d{4}$", }, { note: "Part of the Australian postcode system.", country: "Heard and McDonald Islands", iso: "HM", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Honduras", iso: "HN", format: "NNNNN", regex: "^\\d{5}$", }, { note: "[1] The dummy postal code of Hong Kong is 999077 but it is unnecessary in fact", country: "Hong Kong", iso: "HK", format: "- no codes -", regex: "", }, { note: "The code defines an area, usually one code per settlement except the six largest towns. One code can identify more (usually) small settlements as well.", country: "Hungary", iso: "HU", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Iceland", iso: "IS", format: "NNN", regex: "^\\d{3}$", }, { note: "Postal Index Number (PIN)", country: "India", iso: "IN", format: "NNNNNN,&#10;NNN NNN", regex: "^\\d{6}$", }, { note: "Kode Pos. Included East Timor (ranges 88xxx and 89xxx) until 1999, no longer used. For Indonesia postal code information visit [2]", country: "Indonesia", iso: "ID", format: "NNNNN", regex: "^\\d{5}$", }, { note: "(Persian: کد پستی)", country: "Iran", iso: "IR", format: "NNNNN-NNNNN", regex: "^\\d{5}-\\d{5}$", }, { note: "", country: "Iraq", iso: "IQ", format: "NNNNN", regex: "^\\d{5}$", }, { note: "Currently no postal codes; however, Dublin is divided into postal districts on syntax Dublin 9. A national post code system is planned. See also Republic of Ireland postal addresses.", country: "Ireland", iso: "IE", format: "- no codes -", regex: "", }, { note: "UK-format postcode. The first two letters are always IM.", country: "Isle of Man", iso: "IM", format: "CCN NAA, CCNN NAA", regex: "^[Ii[Mm]\\d{1,2}\\s\\d\\[A-Z]{2}$", }, { note: "Postcode is always written BEFORE the city/place name, i.e. to the Right in Hebrew or Arabic script - to the Left in Latin script. This also allows the legacy postal code version (even though deprecated) since it's still in high use.", country: "Israel", iso: "IL", format: "NNNNNNN, NNNNN", regex: "^\\b\\d{5}(\\d{2})?$", }, { note: "Codice di Avviamento Postale (CAP). Also used by San Marino and Vatican City. First two digits identify province with some exceptions, because there are more than 100 provinces.", country: "Italy", iso: "IT", format: "NNNNN", regex: "^\\d{5}$", }, { note: "Jamaica currently has no national postal code system, except for Kingston and Lower St. Andrew, which are divided into postal districts numbered 1-20[4] &#10;Before the 2007 suspension, the first two letters of a national post code were always 'JM' (for Jamaica) while the third was for one of the four zones (A-D) into which the island was divided. The last two letters were for the parish, while the two digits were for the local post office.[5]", country: "Jamaica", iso: "JM", format: "Before suspension: CCAAANN &#10;After suspension: NN", regex: "^\\d{2}$", }, { note: "See also Japanese addressing system.", country: "Japan", iso: "JP", format: "NNNNNNN (NNN-NNNN)", regex: "^\\d{7}\\s\\(\\d{3}-\\d{4}\\)$", }, { note: "UK-format postcode.", country: "Jersey", iso: "JE", format: "CCN NAA", regex: "^[Jj][Ee]\\d\\s{0,1}\\d[A-Za-z]{2}$", }, { note: "Deliveries to PO Boxes only.", country: "Jordan", iso: "JO", format: "NNNNN", regex: "^\\d{5}$", }, { note: "[6]", country: "Kazakhstan", iso: "KZ", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "Deliveries to PO Boxes only. The postal code refers to the post office at which the receiver's P. O. Box is located.", country: "Kenya", iso: "KE", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Kiribati", iso: "KI", format: "- no codes -", regex: "", }, { note: "", country: "Korea, North", iso: "KP", format: "- no codes -", regex: "", }, { note: "", country: "Korea, South", iso: "KR", format: "NNNNNN (NNN-NNN)(1988~2015)", regex: "^\\d{6}\\s\\(\\d{3}-\\d{3}\\)$", }, { note: "A separate postal code for Kosovo was introduced by the UNMIK postal administration in 2004. Serbian postcodes are still widely used in the Serbian enclaves. No country code has been assigned.", country: "Kosovo", iso: "XK", format: "NNNNN", regex: "^\\d{5}$", }, { note: "The first two digits represent the sector and the last three digits represents the post office.", country: "Kuwait", iso: "KW", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Kyrgyzstan", iso: "KG", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "", country: "Latvia", iso: "LV", format: "LV-NNNN", regex: "^[Ll][Vv][- ]{0,1}\\d{4}$", }, { note: "", country: "Laos", iso: "LA", format: "NNNNN", regex: "^\\d{5}$", }, { note: "The first four digits represent the region or postal zone,the last four digits represent the building see also Lebanon Postal code website.", country: "Lebanon", iso: "LB", format: "NNNN NNNN", regex: "^\\d{4}\\s{0,1}\\d{4}$", }, { note: "", country: "Lesotho", iso: "LS", format: "NNN", regex: "^\\d{3}$", }, { note: "Two digit postal zone after city name.", country: "Liberia", iso: "LR", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Libya", iso: "LY", format: "NNNNN", regex: "^\\d{5}$", }, { note: "With Switzerland, ordered from west to east. Range 9485 - 9498.", country: "Liechtenstein", iso: "LI", format: "NNNN", regex: "^\\d{4}$", }, { note: "References: http://www.post.lt/en/help/postal-code-search. Previously 9999 which was actually the old Soviet 999999 format code with the first 2 digits dropped.", country: "Lithuania", iso: "LT", format: "LT-NNNNN", regex: "^[Ll][Tt][- ]{0,1}\\d{5}$", }, { note: "References: http://www.upu.int/post_code/en/countries/LUX.pdf", country: "Luxembourg", iso: "LU", format: "NNNN", regex: "^\\d{4}$", }, { note: "[2]", country: "Macau", iso: "MO", format: "- no codes -", regex: "", }, { note: "", country: "Macedonia", iso: "MK", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Madagascar", iso: "MG", format: "NNN", regex: "^\\d{3}$", }, { note: "", country: "Malawi", iso: "MW", format: "- no codes -", regex: "", }, { note: "", country: "Maldives", iso: "MV", format: "NNNN, NNNNN", regex: "^\\d{4,5}$", }, { note: "", country: "Malaysia", iso: "MY", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Mali", iso: "ML", format: "- no codes -", regex: "", }, { note: "Kodiċi Postali", country: "Malta", iso: "MT", format: "AAANNNN (AAA NNNN)", regex: "^[A-Za-z]{3}\\s{0,1}\\d{4}$", }, { note: "U.S. ZIP codes. Range 96960 - 96970.", country: "Marshall Islands", iso: "MH", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Mauritania", iso: "MR", format: "- no codes -", regex: "", }, { note: "", country: "Mauritius", iso: "MU", format: "- no codes -", regex: "", }, { note: "Overseas Department of France. French codes used. Range 97200 - 97290.", country: "Martinique", iso: "MQ", format: "972NN", regex: "^972\\d{2}$", }, { note: "Overseas Department of France. French codes used. Range 97600 - 97690.", country: "Mayotte", iso: "YT", format: "976NN", regex: "^976\\d{2}$", }, { note: "US ZIP Code. Range 96941 - 96944.", country: "Micronesia", iso: "FM", format: "NNNNN or NNNNN-NNNN", regex: "^\\d{5}(-{1}\\d{4})$", }, { note: "The first two digits identify the state (or a part thereof), except for Nos. 00 to 16, which indicate delegaciones (boroughs) of the Federal District (Mexico City).", country: "Mexico", iso: "MX", format: "NNNNN", regex: "^\\d{5}$", }, { note: "U.S. ZIP codes. Range 96941 - 96944.", country: "Micronesia", iso: "FM", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Moldova", iso: "MD", format: "CCNNNN (CC-NNNN)", regex: "^[Mm][Dd][- ]{0,1}\\d{4}$", }, { note: "Uses the French Postal System, but with an \"MC\" Prefix for Monaco.", country: "Monaco", iso: "MC", format: "980NN", regex: "^980\\d{2}$", }, { note: "First digit: region / zone&#10;Second digit: province / district&#10;Last three digits: locality / delivery block[7]", country: "Mongolia", iso: "MN", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Montenegro", iso: "ME", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Montserrat", iso: "MS", format: "MSR 1110-1350", regex: "^[Mm][Ss][Rr]\\s{0,1}\\d{4}$", }, { note: "", country: "Morocco", iso: "MA", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Mozambique", iso: "MZ", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Myanmar", iso: "MM", format: "NNNNN", regex: "^\\d{5}$", }, { note: "Postal Code ranges from 9000-9299 (note: mainly 9000 is used)", country: "Namibia", iso: "NA", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Nauru", iso: "NR", format: "- no codes -", regex: "", }, { note: "", country: "Nepal", iso: "NP", format: "NNNNN", regex: "^\\d{5}$", }, { note: "The combination of the postcode and the housenumber gives a unique identifier of the address.", country: "Netherlands", iso: "NL", format: "NNNN AA", regex: "^\\d{4}\\s{0,1}[A-Za-z]{2}$", }, { note: "Overseas Department of France. French codes used. Range 98800 - 98890.", country: "New Caledonia", iso: "NC", format: "988NN", regex: "^988\\d{2}$", }, { note: "Postcodes were originally intended for bulk mailing and were not needed for addressing individual items. However, new post codes for general use were phased in from June 2006 and came into force by July 2008.", country: "New Zealand", iso: "NZ", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Nicaragua", iso: "NI", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Niger", iso: "NE", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Nigeria", iso: "NG", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "", country: "Niue", iso: "NU", format: "- no codes -", regex: "", }, { note: "Part of the Australian postal code system.", country: "Norfolk Island", iso: "NF", format: "NNNN", regex: "^\\d{4}$", }, { note: "U.S. ZIP codes. Range 96950 - 96952.", country: "Northern Mariana Islands", iso: "MP", format: "NNNNN", regex: "^\\d{5}$", }, { note: "From south to north", country: "Norway", iso: "NO", format: "NNNN", regex: "^\\d{4}$", }, { note: "Deliveries to P.O. Boxes only.", country: "Oman", iso: "OM", format: "NNN", regex: "^\\d{3}$", }, { note: "Pakistan postal codes list", country: "Pakistan", iso: "PK", format: "NNNNN", regex: "^\\d{5}$", }, { note: "U.S. ZIP codes. All locations 96940.", country: "Palau", iso: "PW", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Panama", iso: "PA", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "", country: "Papua New Guinea", iso: "PG", format: "NNN", regex: "^\\d{3}$", }, { note: "", country: "Paraguay", iso: "PY", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Peru", iso: "PE", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Philippines", iso: "PH", format: "NNNN", regex: "^\\d{4}$", }, { note: "UK territory, but not UK postcode", country: "Pitcairn Islands", iso: "PN", format: "AAAANAA one code: PCRN 1ZZ", regex: "^[Pp][Cc][Rr][Nn]\\s{0,1}[1][Zz]{2}$", }, { note: "", country: "Poland", iso: "PL", format: "NNNNN (NN-NNN)", regex: "^\\d{2}[- ]{0,1}\\d{3}$", }, { note: "", country: "Portugal", iso: "PT", format: "NNNN", regex: "^\\d{4}$", }, { note: "", country: "Portugal", iso: "PT", format: "NNNN-NNN (NNNN NNN)", regex: "^\\d{4}[- ]{0,1}\\d{3}$", }, { note: "U.S. ZIP codes. ZIP codes 006XX for NW PR, 007XX for SE PR, in which XX designates the town or post office and 009XX for the San Juan Metropolitan Area, in which XX designates the area or borough of San Juan. The last four digits identify an area within the post office. For example 00716-2604: 00716-for the east section of the city of Ponce and 2604 for Aceitillo St. in the neighborhood of Los Caobos. US Post office is changing the PR address format to the American one: 1234 No Name Avenue, San Juan, PR 00901.", country: "Puerto Rico", iso: "PR", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Qatar", iso: "QA", format: "- no codes -", regex: "", }, { note: "Overseas Department of France. French codes used. Range 97400 - 97490.", country: "Réunion", iso: "RE", format: "974NN", regex: "^974\\d{2}$", }, { note: "Previously 99999 in Bucharest and 9999 in rest of country.", country: "Romania", iso: "RO", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "Placed on a line of its own.", country: "Russia", iso: "RU", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "Overseas Collectivity of France. French codes used.", country: "Saint Barthélemy", iso: "BL", format: "97133", regex: "^97133$", }, { note: "Single code used for all addresses.", country: "Saint Helena", iso: "SH", format: "STHL 1ZZ", regex: "^[Ss][Tt][Hh][Ll]\\s{0,1}[1][Zz]{2}$", }, { note: "", country: "Saint Kitts and Nevis", iso: "KN", format: "- no codes -", regex: "", }, { note: "", country: "Saint Lucia", iso: "LC", format: "- no codes -", regex: "", }, { note: "Overseas Collectivity of France. French codes used.", country: "Saint Martin", iso: "MF", format: "97150", regex: "^97150$", }, { note: "Overseas Collectivity of France. French codes used.", country: "Saint Pierre and Miquelon", iso: "PM", format: "97500", regex: "^97500$", }, { note: "", country: "Saint Vincent and the Grenadines", iso: "VC", format: "CCNNNN", regex: "^[Vv][Cc]\\d{4}$", }, { note: "With Italy, uses a five-digit numeric CAP of Emilia Romagna. Range 47890 and 47899", country: "San Marino", iso: "SM", format: "4789N", regex: "^4789\\d$", }, { note: "", country: "Sao Tome and Principe", iso: "ST", format: "- no codes -", regex: "", }, { note: "A complete 13-digit code has 5-digit number representing region, sector, city, and zone; 4-digit X between 2000 and 5999; 4-digit Y between 6000 and 9999 [3]. Digits of 5-digit code may represent postal region, sector, branch, section, and block respectively [4].", country: "Saudi Arabia", iso: "SA", format: "NNNNN for PO Boxes. NNNNN-NNNN for home delivery.", regex: "^\\d{5}(-{1}\\d{4})?$", }, { note: "The letters CP or C.P. are often written in front of the postcode. This is not a country code, but simply an abbreviation for \"code postal\".", country: "Senegal", iso: "SN", format: "NNNNN", regex: "^\\d{5}$", }, { note: "Poštanski adresni kod (PAK)", country: "Serbia", iso: "RS", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Serbia", iso: "RS", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Seychelles", iso: "SC", format: "- no codes -", regex: "", }, { note: "", country: "Sint Maarten", iso: "SX", format: "- no codes -", regex: "", }, { note: "", country: "Sierra Leone", iso: "SL", format: "- no codes -", regex: "", }, { note: "", country: "Singapore", iso: "SG", format: "NN", regex: "^\\d{2}$", }, { note: "", country: "Singapore", iso: "SG", format: "NNNN", regex: "^\\d{4}$", }, { note: "Each building has its own unique postcode.", country: "Singapore", iso: "SG", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "with Czech Republic from west to east, Poštové smerovacie číslo (PSČ) - postal routing number.", country: "Slovakia", iso: "SK", format: "NNNNN (NNN NN)", regex: "^\\d{5}\\s\\(\\d{3}\\s\\d{2}\\)$", }, { note: "", country: "Slovenia", iso: "SI", format: "NNNN (CC-NNNN)", regex: "^([Ss][Ii][- ]{0,1}){0,1}\\d{4}$", }, { note: "", country: "Solomon Islands", iso: "SB", format: "- no codes -", regex: "", }, { note: "A 5 digit code has been publicized, but never taken into use.", country: "Somalia", iso: "SO", format: "- no codes -", regex: "", }, { note: "Postal codes are allocated to individual Post Office branches, some have two codes to differentiate between P.O. Boxes and street delivery addresses. Included Namibia (ranges 9000-9299) until 1992, no longer used.", country: "South Africa", iso: "ZA", format: "NNNN", regex: "^\\d{4}$", }, { note: "One code for all addresses.", country: "South Georgia and the South Sandwich Islands", iso: "GS", format: "SIQQ 1ZZ", regex: "^[Ss][Ii][Qq]{2}\\s{0,1}[1][Zz]{2}$", }, { note: "", country: "South Korea", iso: "KR", format: "NNNNNN (NNN-NNN)", regex: "^\\d{6}\\s\\(\\d{3}-\\d{3}\\)$", }, { note: "First two indicate the province, range 01-52", country: "Spain", iso: "ES", format: "NNNNN", regex: "^\\d{5}$", }, { note: "Reference: http://mohanjith.net/ZIPLook/ Incorporates Colombo postal districts, e.g.: Colombo 1 is \"00100\". You can search for specific postal codes here.", country: "Sri Lanka", iso: "LK", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Sudan", iso: "SD", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Suriname", iso: "SR", format: "- no codes -", regex: "", }, { note: "The letter identifies one of the country's four districts.", country: "Swaziland", iso: "SZ", format: "ANNN", regex: "^[A-Za-z]\\d{3}$", }, { note: "", country: "Sweden", iso: "SE", format: "NNNNN (NNN NN)", regex: "^\\d{3}\\s*\\d{2}$", }, { note: "With Liechtenstein, ordered from west to east. In Geneva and other big cities, like Basel, Bern, Zurich, there may be one or two digits after the name of the city when the generic City code (1211) is used instead of the area-specific code (1201, 1202...), e.g.: 1211 Geneva 13. The digit identifies the post office. This addressing is generally used for P.O. box deliveries.", country: "Switzerland", iso: "CH", format: "NNNN", regex: "^\\d{4}$", }, { note: "Norway postal codes", country: "Svalbard and Jan Mayen", iso: "SJ", format: "NNNN", regex: "^\\d{4}$", }, { note: "A 4-digit system has been announced. Status unknown.", country: "Syria", iso: "SY", format: "- no codes -", regex: "", }, { note: "The first three digits of the postal code are required; the last two digits are optional. Codes are known as youdi quhao (郵遞區號), and are also assigned to Senkaku Islands (Diaoyutai), though Japanese-administered, the Pratas Islands and the Spratly Islands. See List of postal codes in Taiwan.", country: "Taiwan", iso: "TW", format: "NNNNN", regex: "^\\d{5}$", }, { note: "Retained system from former Soviet Union.", country: "Tajikistan", iso: "TJ", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "", country: "Tanzania", iso: "TZ", format: "- no codes -", regex: "", }, { note: "The first two specify the province, numbers as in ISO 3166-2:TH, the third and fourth digits specify a district (amphoe)", country: "Thailand", iso: "TH", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "Togo", iso: "TG", format: "- no codes -", regex: "", }, { note: "", country: "Tokelau", iso: "TK", format: "- no codes -", regex: "", }, { note: "", country: "Tonga", iso: "TO", format: "- no codes -", regex: "", }, { note: "First two digits specify a postal district (one of 72), next two digits a carrier route, last two digits a building or zone along that route", country: "Trinidad and Tobago", iso: "TT", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "Single code used for all addresses.", country: "Tristan da Cunha", iso: "SH", format: "TDCU 1ZZ", regex: "^[Tt][Dd][Cc][Uu]\\s{0,1}[1][Zz]{2}$", }, { note: "", country: "Tunisia", iso: "TN", format: "NNNN", regex: "^\\d{4}$", }, { note: "First two digits are the city numbers.[8]", country: "Turkey", iso: "TR", format: "NNNNN", regex: "^\\d{5}$", }, { note: "Retained system from former Soviet Union.", country: "Turkmenistan", iso: "TM", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "Single code used for all addresses.", country: "Turks and Caicos Islands", iso: "TC", format: "TKCA 1ZZ", regex: "^[Tt][Kk][Cc][Aa]\\s{0,1}[1][Zz]{2}$", }, { note: "", country: "Tuvalu", iso: "TV", format: "- no codes -", regex: "", }, { note: "", country: "Uganda", iso: "UG", format: "- no codes -", regex: "", }, { note: "", country: "Ukraine", iso: "UA", format: "NNNNN", regex: "^\\d{5}$", }, { note: "", country: "United Arab Emirates", iso: "AE", format: "- no codes -", regex: "", }, { note: "Known as the postcode. The first letter(s) indicate the postal area, such as the town or part of London. Placed on a separate line below the city (or county, if used). The UK postcode is made up of two parts separated by a space. These are known as the outward postcode and the inward postcode. The outward postcode is always one of the following formats: AN, ANN, AAN, AANN, ANA, AANA, AAA. The inward postcode is always formatted as NAA. A valid inward postcode never contains the letters: C, I, K, M, O or V. The British Forces Post Office has a different system, but as of 2012 has also adopted UK-style postcodes that begin with \"BF1\" for electronic compatibility.", country: "United Kingdom", iso: "GB", format: "A(A)N(A/N)NAA (A[A]N[A/N] NAA)", regex: "^[A-Z]{1,2}[0-9R][0-9A-Z]?\\s*[0-9][A-Z-[CIKMOV]]{2}", }, { note: "Known as the ZIP Code with five digits 99999* or the ZIP+4 Code with nine digits 99999-9999* (while the minimum requirement is the first five digits, the U.S. Postal Service encourages everyone to use all nine). Also used by the former US Pacific Territories: Federated States of Micronesia; Palau; and the Marshall Islands, as well as in current US territories American Samoa, Guam, Northern Mariana Islands, Puerto Rico, and the United States Virgin Islands. An individual delivery point may be represented as an 11-digit number, but these are usually represented by Intelligent Mail barcode or formerly POSTNET bar code.", country: "United States", iso: "US", format: "NNNNN (optionally NNNNN-NNNN)", regex: "^\\b\\d{5}\\b(?:[- ]{1}\\d{4})?$", }, { note: "", country: "Uruguay", iso: "UY", format: "NNNNN", regex: "^\\d{5}$", }, { note: "U.S. ZIP codes. Range 00801 - 00851.", country: "U.S. Virgin Islands", iso: "VI", format: "NNNNN", regex: "^\\d{5}$", }, { note: "Почтовые индексы", country: "Uzbekistan", iso: "UZ", format: "NNN NNN", regex: "^\\d{3} \\d{3}$", }, { note: "", country: "Vanuatu", iso: "VU", format: "- no codes -", regex: "", }, { note: "Single code used for all addresses. Part of the Italian postal code system.", country: "Vatican", iso: "VA", format: "120", regex: "^120$", }, { note: "", country: "Venezuela", iso: "VE", format: "NNNN or NNNN A", regex: "^\\d{4}(\\s[a-zA-Z]{1})?$", }, { note: "First two indicate a province.", country: "Vietnam", iso: "VN", format: "NNNNNN", regex: "^\\d{6}$", }, { note: "Overseas Department of France. French codes used. Range 98600 - 98690.", country: "Wallis and Futuna", iso: "WF", format: "986NN", regex: "^986\\d{2}$", }, { note: "System for Sana'a Governorate using geocoding \"عنواني\" based on the OpenPostcode algorithm is inaugurated in 2014.[9]", country: "Yemen", iso: "YE", format: "- no codes -", regex: "", }, { note: "", country: "Zambia", iso: "ZM", format: "NNNNN", regex: "^\\d{5}$", }, { note: "System is being planned.", country: "Zimbabwe", iso: "ZW", format: "- no codes -", regex: "", }, ]
14,693
10,623
hyperswitch-client-core
src/utility/reusableCodeFromWeb/ErrorUtils.res
.res
type errorType = Error | Warning type errorStringType = Dynamic(string => string) | Static(string) type errorTupple = (errorType, errorStringType) type errorKey = | INVALID_PK(errorTupple) | INVALID_EK(errorTupple) | DEPRECATED_LOADSTRIPE(errorTupple) | REQUIRED_PARAMETER(errorTupple) | UNKNOWN_KEY(errorTupple) | UNKNOWN_VALUE(errorTupple) | TYPE_BOOL_ERROR(errorTupple) | TYPE_STRING_ERROR(errorTupple) | INVALID_FORMAT(errorTupple) | USED_CL(errorTupple) | INVALID_CL(errorTupple) | NO_DATA(errorTupple) type errorWarning = { invalidPk: errorKey, invalidEphemeralKey: errorKey, deprecatedLoadStripe: errorKey, reguirParameter: errorKey, typeBoolError: errorKey, unknownKey: errorKey, typeStringError: errorKey, unknownValue: errorKey, invalidFormat: errorKey, usedCL: errorKey, invalidCL: errorKey, noData: errorKey, } let isError = (res: JSON.t) => { res ->JSON.Decode.object ->Option.getOr(Dict.make()) ->Dict.get("error") ->Option.isSome } let getErrorCode = (res: JSON.t) => { res ->JSON.Decode.object ->Option.getOr(Dict.make()) ->Dict.get("error") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.object ->Option.getOr(Dict.make()) ->Dict.get("code") ->Option.getOr(JSON.Encode.null) ->JSON.stringify } let getErrorMessage = (res: JSON.t) => { res ->JSON.Decode.object ->Option.getOr(Dict.make()) ->Dict.get("error") ->Option.getOr(JSON.Encode.null) ->JSON.Decode.object ->Option.getOr(Dict.make()) ->Dict.get("message") ->Option.getOr(JSON.Encode.null) ->JSON.stringify } let errorWarning = { invalidPk: INVALID_PK( Error, Static( "INTEGRATION ERROR: Invalid Publishable key, starts with pk_snd_(sandbox/test) or pk_prd_(production/live)", ), ), invalidEphemeralKey: INVALID_EK(Error, Static("INTEGRATION ERROR: Ephemeral key not available.")), deprecatedLoadStripe: DEPRECATED_LOADSTRIPE( Warning, Static("loadStripe is deprecated. Please use loadOrca instead."), ), reguirParameter: REQUIRED_PARAMETER( Error, Dynamic( // str => {`INTEGRATION ERROR: ${str} is a required field/parameter or ${str} cannot be empty`}, str => {`INTEGRATION ERROR: ${str}`}, ), ), unknownKey: UNKNOWN_KEY( Warning, Dynamic( str => { `Unknown Key: ${str} is a unknown/invalid key, please provide a correct key. This might cause issue in the future` }, ), ), typeBoolError: TYPE_BOOL_ERROR( Warning, Dynamic( str => { `Type Error: '${str}' Expected boolean` }, ), ), typeStringError: TYPE_STRING_ERROR( Warning, Dynamic( str => { `Type Error: '${str}' Expected string` }, ), ), unknownValue: UNKNOWN_VALUE( Warning, Dynamic( str => { `Unknown Value: ${str}. Please provide a correct value. This might cause issue in the future` }, ), ), invalidFormat: INVALID_FORMAT(Error, Dynamic(str => {str})), usedCL: USED_CL(Error, Static("Data Error: The client secret has been already used.")), invalidCL: INVALID_CL(Error, Static("Data Error: The client secret is invalid.")), noData: NO_DATA(Error, Static("There is no customer default saved payment method data")), }
878
10,624
hyperswitch-client-core
src/utility/reusableCodeFromWeb/StatesAndCountry.json
.json
{"country":[{"isoAlpha2":"AF","value":"Afghanistan","timeZones":["Asia/Kabul"]},{"isoAlpha2":"AX","value":"Aland Islands","timeZones":["Europe/Mariehamn"]},{"isoAlpha2":"AL","value":"Albania","timeZones":["Europe/Tirane"]},{"isoAlpha2":"DZ","value":"Algeria","timeZones":["Africa/Algiers"]},{"isoAlpha2":"AS","value":"American Samoa","timeZones":["Pacific/Pago_Pago"]},{"isoAlpha2":"AD","value":"Andorra","timeZones":["Europe/Andorra"]},{"isoAlpha2":"AO","value":"Angola","timeZones":["Africa/Luanda"]},{"isoAlpha2":"AI","value":"Anguilla","timeZones":["America/Anguilla"]},{"isoAlpha2":"AQ","value":"Antarctica","timeZones":["Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Mawson","Antarctica/McMurdo","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok"]},{"isoAlpha2":"AG","value":"Antigua and Barbuda","timeZones":["America/Antigua"]},{"isoAlpha2":"AR","value":"Argentina","timeZones":["America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia"]},{"isoAlpha2":"AM","value":"Armenia","timeZones":["Asia/Yerevan"]},{"isoAlpha2":"AW","value":"Aruba","timeZones":["America/Aruba"]},{"isoAlpha2":"AU","value":"Australia","timeZones":["Antarctica/Macquarie","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney"]},{"isoAlpha2":"AT","value":"Austria","timeZones":["Europe/Vienna"]},{"isoAlpha2":"AZ","value":"Azerbaijan","timeZones":["Asia/Baku"]},{"isoAlpha2":"BH","value":"Bahrain","timeZones":["Asia/Bahrain"]},{"isoAlpha2":"BD","value":"Bangladesh","timeZones":["Asia/Dhaka"]},{"isoAlpha2":"BB","value":"Barbados","timeZones":["America/Barbados"]},{"isoAlpha2":"BY","value":"Belarus","timeZones":["Europe/Minsk"]},{"isoAlpha2":"BE","value":"Belgium","timeZones":["Europe/Brussels"]},{"isoAlpha2":"BZ","value":"Belize","timeZones":["America/Belize"]},{"isoAlpha2":"BJ","value":"Benin","timeZones":["Africa/Porto-Novo"]},{"isoAlpha2":"BM","value":"Bermuda","timeZones":["Atlantic/Bermuda"]},{"isoAlpha2":"BT","value":"Bhutan","timeZones":["Asia/Thimphu"]},{"isoAlpha2":"BO","value":"Bolivia","timeZones":["America/La_Paz"]},{"isoAlpha2":"BQ","value":"Bonaire, Sint Eustatius and Saba","timeZones":["America/Anguilla"]},{"isoAlpha2":"BA","value":"Bosnia and Herzegovina","timeZones":["Europe/Sarajevo"]},{"isoAlpha2":"BW","value":"Botswana","timeZones":["Africa/Gaborone"]},{"isoAlpha2":"BV","value":"Bouvet Island","timeZones":["Europe/Oslo"]},{"isoAlpha2":"BR","value":"Brazil","timeZones":["America/Araguaina","America/Bahia","America/Belem","America/Boa_Vista","America/Campo_Grande","America/Cuiaba","America/Eirunepe","America/Fortaleza","America/Maceio","America/Manaus","America/Noronha","America/Porto_Velho","America/Recife","America/Rio_Branco","America/Santarem","America/Sao_Paulo"]},{"isoAlpha2":"IO","value":"British Indian Ocean Territory","timeZones":["Indian/Chagos"]},{"isoAlpha2":"BN","value":"Brunei","timeZones":["Asia/Brunei"]},{"isoAlpha2":"BG","value":"Bulgaria","timeZones":["Europe/Sofia"]},{"isoAlpha2":"BF","value":"Burkina Faso","timeZones":["Africa/Ouagadougou"]},{"isoAlpha2":"BI","value":"Burundi","timeZones":["Africa/Bujumbura"]},{"isoAlpha2":"KH","value":"Cambodia","timeZones":["Asia/Phnom_Penh"]},{"isoAlpha2":"CM","value":"Cameroon","timeZones":["Africa/Douala"]},{"isoAlpha2":"CA","value":"Canada","timeZones":["America/Atikokan","America/Blanc-Sablon","America/Cambridge_Bay","America/Creston","America/Dawson","America/Dawson_Creek","America/Edmonton","America/Fort_Nelson","America/Glace_Bay","America/Goose_Bay","America/Halifax","America/Inuvik","America/Iqaluit","America/Moncton","America/Nipigon","America/Pangnirtung","America/Rainy_River","America/Rankin_Inlet","America/Regina","America/Resolute","America/St_Johns","America/Swift_Current","America/Thunder_Bay","America/Toronto","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yellowknife"]},{"isoAlpha2":"CV","value":"Cape Verde","timeZones":["Atlantic/Cape_Verde"]},{"isoAlpha2":"KY","value":"Cayman Islands","timeZones":["America/Cayman"]},{"isoAlpha2":"CF","value":"Central African Republic","timeZones":["Africa/Bangui"]},{"isoAlpha2":"TD","value":"Chad","timeZones":["Africa/Ndjamena"]},{"isoAlpha2":"CL","value":"Chile","timeZones":["America/Punta_Arenas","America/Santiago","Pacific/Easter"]},{"isoAlpha2":"CN","value":"China","timeZones":["Asia/Shanghai","Asia/Urumqi"]},{"isoAlpha2":"CX","value":"Christmas Island","timeZones":["Indian/Christmas"]},{"isoAlpha2":"CC","value":"Cocos (Keeling) Islands","timeZones":["Indian/Cocos"]},{"isoAlpha2":"CO","value":"Colombia","timeZones":["America/Bogota"]},{"isoAlpha2":"KM","value":"Comoros","timeZones":["Indian/Comoro"]},{"isoAlpha2":"CG","value":"Congo","timeZones":["Africa/Brazzaville"]},{"isoAlpha2":"CK","value":"Cook Islands","timeZones":["Pacific/Rarotonga"]},{"isoAlpha2":"CR","value":"Costa Rica","timeZones":["America/Costa_Rica"]},{"isoAlpha2":"CI","value":"Cote D'Ivoire (Ivory Coast)","timeZones":["Africa/Abidjan"]},{"isoAlpha2":"HR","value":"Croatia","timeZones":["Europe/Zagreb"]},{"isoAlpha2":"CU","value":"Cuba","timeZones":["America/Havana"]},{"isoAlpha2":"CW","value":"Curaçao","timeZones":["America/Curacao"]},{"isoAlpha2":"CY","value":"Cyprus","timeZones":["Asia/Famagusta","Asia/Nicosia"]},{"isoAlpha2":"CZ","value":"Czech Republic","timeZones":["Europe/Prague"]},{"isoAlpha2":"CD","value":"Democratic Republic of the Congo","timeZones":["Africa/Kinshasa","Africa/Lubumbashi"]},{"isoAlpha2":"DK","value":"Denmark","timeZones":["Europe/Copenhagen"]},{"isoAlpha2":"DJ","value":"Djibouti","timeZones":["Africa/Djibouti"]},{"isoAlpha2":"DM","value":"Dominica","timeZones":["America/Dominica"]},{"isoAlpha2":"DO","value":"Dominican Republic","timeZones":["America/Santo_Domingo"]},{"isoAlpha2":"EC","value":"Ecuador","timeZones":["America/Guayaquil","Pacific/Galapagos"]},{"isoAlpha2":"EG","value":"Egypt","timeZones":["Africa/Cairo"]},{"isoAlpha2":"SV","value":"El Salvador","timeZones":["America/El_Salvador"]},{"isoAlpha2":"GQ","value":"Equatorial Guinea","timeZones":["Africa/Malabo"]},{"isoAlpha2":"ER","value":"Eritrea","timeZones":["Africa/Asmara"]},{"isoAlpha2":"EE","value":"Estonia","timeZones":["Europe/Tallinn"]},{"isoAlpha2":"SZ","value":"Eswatini","timeZones":["Africa/Mbabane"]},{"isoAlpha2":"ET","value":"Ethiopia","timeZones":["Africa/Addis_Ababa"]},{"isoAlpha2":"FK","value":"Falkland Islands","timeZones":["Atlantic/Stanley"]},{"isoAlpha2":"FO","value":"Faroe Islands","timeZones":["Atlantic/Faroe"]},{"isoAlpha2":"FJ","value":"Fiji Islands","timeZones":["Pacific/Fiji"]},{"isoAlpha2":"FI","value":"Finland","timeZones":["Europe/Helsinki"]},{"isoAlpha2":"FR","value":"France","timeZones":["Europe/Paris"]},{"isoAlpha2":"GF","value":"French Guiana","timeZones":["America/Cayenne"]},{"isoAlpha2":"PF","value":"French Polynesia","timeZones":["Pacific/Gambier","Pacific/Marquesas","Pacific/Tahiti"]},{"isoAlpha2":"TF","value":"French Southern Territories","timeZones":["Indian/Kerguelen"]},{"isoAlpha2":"GA","value":"Gabon","timeZones":["Africa/Libreville"]},{"isoAlpha2":"GE","value":"Georgia","timeZones":["Asia/Tbilisi"]},{"isoAlpha2":"DE","value":"Germany","timeZones":["Europe/Berlin","Europe/Busingen"]},{"isoAlpha2":"GH","value":"Ghana","timeZones":["Africa/Accra"]},{"isoAlpha2":"GI","value":"Gibraltar","timeZones":["Europe/Gibraltar"]},{"isoAlpha2":"GR","value":"Greece","timeZones":["Europe/Athens"]},{"isoAlpha2":"GL","value":"Greenland","timeZones":["America/Danmarkshavn","America/Nuuk","America/Scoresbysund","America/Thule"]},{"isoAlpha2":"GD","value":"Grenada","timeZones":["America/Grenada"]},{"isoAlpha2":"GP","value":"Guadeloupe","timeZones":["America/Guadeloupe"]},{"isoAlpha2":"GU","value":"Guam","timeZones":["Pacific/Guam"]},{"isoAlpha2":"GT","value":"Guatemala","timeZones":["America/Guatemala"]},{"isoAlpha2":"GG","value":"Guernsey and Alderney","timeZones":["Europe/Guernsey"]},{"isoAlpha2":"GN","value":"Guinea","timeZones":["Africa/Conakry"]},{"isoAlpha2":"GW","value":"Guinea-Bissau","timeZones":["Africa/Bissau"]},{"isoAlpha2":"GY","value":"Guyana","timeZones":["America/Guyana"]},{"isoAlpha2":"HT","value":"Haiti","timeZones":["America/Port-au-Prince"]},{"isoAlpha2":"HM","value":"Heard Island and McDonald Islands","timeZones":["Indian/Kerguelen"]},{"isoAlpha2":"HN","value":"Honduras","timeZones":["America/Tegucigalpa"]},{"isoAlpha2":"HK","value":"Hong Kong S.A.R.","timeZones":["Asia/Hong_Kong"]},{"isoAlpha2":"HU","value":"Hungary","timeZones":["Europe/Budapest"]},{"isoAlpha2":"IS","value":"Iceland","timeZones":["Atlantic/Reykjavik"]},{"isoAlpha2":"IN","value":"India","timeZones":["Asia/Kolkata"]},{"isoAlpha2":"ID","value":"Indonesia","timeZones":["Asia/Jakarta","Asia/Jayapura","Asia/Makassar","Asia/Pontianak"]},{"isoAlpha2":"IR","value":"Iran","timeZones":["Asia/Tehran"]},{"isoAlpha2":"IQ","value":"Iraq","timeZones":["Asia/Baghdad"]},{"isoAlpha2":"IE","value":"Ireland","timeZones":["Europe/Dublin"]},{"isoAlpha2":"IL","value":"Israel","timeZones":["Asia/Jerusalem"]},{"isoAlpha2":"IT","value":"Italy","timeZones":["Europe/Rome"]},{"isoAlpha2":"JM","value":"Jamaica","timeZones":["America/Jamaica"]},{"isoAlpha2":"JP","value":"Japan","timeZones":["Asia/Tokyo"]},{"isoAlpha2":"JE","value":"Jersey","timeZones":["Europe/Jersey"]},{"isoAlpha2":"JO","value":"Jordan","timeZones":["Asia/Amman"]},{"isoAlpha2":"KZ","value":"Kazakhstan","timeZones":["Asia/Almaty","Asia/Aqtau","Asia/Aqtobe","Asia/Atyrau","Asia/Oral","Asia/Qostanay","Asia/Qyzylorda"]},{"isoAlpha2":"KE","value":"Kenya","timeZones":["Africa/Nairobi"]},{"isoAlpha2":"KI","value":"Kiribati","timeZones":["Pacific/Enderbury","Pacific/Kiritimati","Pacific/Tarawa"]},{"isoAlpha2":"XK","value":"Kosovo","timeZones":["Europe/Belgrade"]},{"isoAlpha2":"KW","value":"Kuwait","timeZones":["Asia/Kuwait"]},{"isoAlpha2":"KG","value":"Kyrgyzstan","timeZones":["Asia/Bishkek"]},{"isoAlpha2":"LA","value":"Laos","timeZones":["Asia/Vientiane"]},{"isoAlpha2":"LV","value":"Latvia","timeZones":["Europe/Riga"]},{"isoAlpha2":"LB","value":"Lebanon","timeZones":["Asia/Beirut"]},{"isoAlpha2":"LS","value":"Lesotho","timeZones":["Africa/Maseru"]},{"isoAlpha2":"LR","value":"Liberia","timeZones":["Africa/Monrovia"]},{"isoAlpha2":"LY","value":"Libya","timeZones":["Africa/Tripoli"]},{"isoAlpha2":"LI","value":"Liechtenstein","timeZones":["Europe/Vaduz"]},{"isoAlpha2":"LT","value":"Lithuania","timeZones":["Europe/Vilnius"]},{"isoAlpha2":"LU","value":"Luxembourg","timeZones":["Europe/Luxembourg"]},{"isoAlpha2":"MO","value":"Macau S.A.R.","timeZones":["Asia/Macau"]},{"isoAlpha2":"MG","value":"Madagascar","timeZones":["Indian/Antananarivo"]},{"isoAlpha2":"MW","value":"Malawi","timeZones":["Africa/Blantyre"]},{"isoAlpha2":"MY","value":"Malaysia","timeZones":["Asia/Kuala_Lumpur","Asia/Kuching"]},{"isoAlpha2":"MV","value":"Maldives","timeZones":["Indian/Maldives"]},{"isoAlpha2":"ML","value":"Mali","timeZones":["Africa/Bamako"]},{"isoAlpha2":"MT","value":"Malta","timeZones":["Europe/Malta"]},{"isoAlpha2":"IM","value":"Man (Isle of)","timeZones":["Europe/Isle_of_Man"]},{"isoAlpha2":"MH","value":"Marshall Islands","timeZones":["Pacific/Kwajalein","Pacific/Majuro"]},{"isoAlpha2":"MQ","value":"Martinique","timeZones":["America/Martinique"]},{"isoAlpha2":"MR","value":"Mauritania","timeZones":["Africa/Nouakchott"]},{"isoAlpha2":"MU","value":"Mauritius","timeZones":["Indian/Mauritius"]},{"isoAlpha2":"YT","value":"Mayotte","timeZones":["Indian/Mayotte"]},{"isoAlpha2":"MX","value":"Mexico","timeZones":["America/Bahia_Banderas","America/Cancun","America/Chihuahua","America/Hermosillo","America/Matamoros","America/Mazatlan","America/Merida","America/Mexico_City","America/Monterrey","America/Ojinaga","America/Tijuana"]},{"isoAlpha2":"FM","value":"Micronesia","timeZones":["Pacific/Chuuk","Pacific/Kosrae","Pacific/Pohnpei"]},{"isoAlpha2":"MD","value":"Moldova","timeZones":["Europe/Chisinau"]},{"isoAlpha2":"MC","value":"Monaco","timeZones":["Europe/Monaco"]},{"isoAlpha2":"MN","value":"Mongolia","timeZones":["Asia/Choibalsan","Asia/Hovd","Asia/Ulaanbaatar"]},{"isoAlpha2":"ME","value":"Montenegro","timeZones":["Europe/Podgorica"]},{"isoAlpha2":"MS","value":"Montserrat","timeZones":["America/Montserrat"]},{"isoAlpha2":"MA","value":"Morocco","timeZones":["Africa/Casablanca"]},{"isoAlpha2":"MZ","value":"Mozambique","timeZones":["Africa/Maputo"]},{"isoAlpha2":"MM","value":"Myanmar","timeZones":["Asia/Yangon"]},{"isoAlpha2":"NA","value":"Namibia","timeZones":["Africa/Windhoek"]},{"isoAlpha2":"NR","value":"Nauru","timeZones":["Pacific/Nauru"]},{"isoAlpha2":"NP","value":"Nepal","timeZones":["Asia/Kathmandu"]},{"isoAlpha2":"NL","value":"Netherlands","timeZones":["Europe/Amsterdam"]},{"isoAlpha2":"NC","value":"New Caledonia","timeZones":["Pacific/Noumea"]},{"isoAlpha2":"NZ","value":"New Zealand","timeZones":["Pacific/Auckland","Pacific/Chatham"]},{"isoAlpha2":"NI","value":"Nicaragua","timeZones":["America/Managua"]},{"isoAlpha2":"NE","value":"Niger","timeZones":["Africa/Niamey"]},{"isoAlpha2":"NG","value":"Nigeria","timeZones":["Africa/Lagos"]},{"isoAlpha2":"NU","value":"Niue","timeZones":["Pacific/Niue"]},{"isoAlpha2":"NF","value":"Norfolk Island","timeZones":["Pacific/Norfolk"]},{"isoAlpha2":"KP","value":"North Korea","timeZones":["Asia/Pyongyang"]},{"isoAlpha2":"MK","value":"North Macedonia","timeZones":["Europe/Skopje"]},{"isoAlpha2":"MP","value":"Northern Mariana Islands","timeZones":["Pacific/Saipan"]},{"isoAlpha2":"NO","value":"Norway","timeZones":["Europe/Oslo"]},{"isoAlpha2":"OM","value":"Oman","timeZones":["Asia/Muscat"]},{"isoAlpha2":"PK","value":"Pakistan","timeZones":["Asia/Karachi"]},{"isoAlpha2":"PW","value":"Palau","timeZones":["Pacific/Palau"]},{"isoAlpha2":"PS","value":"Palestinian Territory Occupied","timeZones":["Asia/Gaza","Asia/Hebron"]},{"isoAlpha2":"PA","value":"Panama","timeZones":["America/Panama"]},{"isoAlpha2":"PG","value":"Papua New Guinea","timeZones":["Pacific/Bougainville","Pacific/Port_Moresby"]},{"isoAlpha2":"PY","value":"Paraguay","timeZones":["America/Asuncion"]},{"isoAlpha2":"PE","value":"Peru","timeZones":["America/Lima"]},{"isoAlpha2":"PH","value":"Philippines","timeZones":["Asia/Manila"]},{"isoAlpha2":"PN","value":"Pitcairn Island","timeZones":["Pacific/Pitcairn"]},{"isoAlpha2":"PL","value":"Poland","timeZones":["Europe/Warsaw"]},{"isoAlpha2":"PT","value":"Portugal","timeZones":["Atlantic/Azores","Atlantic/Madeira","Europe/Lisbon"]},{"isoAlpha2":"PR","value":"Puerto Rico","timeZones":["America/Puerto_Rico"]},{"isoAlpha2":"QA","value":"Qatar","timeZones":["Asia/Qatar"]},{"isoAlpha2":"RE","value":"Reunion","timeZones":["Indian/Reunion"]},{"isoAlpha2":"RO","value":"Romania","timeZones":["Europe/Bucharest"]},{"isoAlpha2":"RU","value":"Russia","timeZones":["Asia/Anadyr","Asia/Barnaul","Asia/Chita","Asia/Irkutsk","Asia/Kamchatka","Asia/Khandyga","Asia/Krasnoyarsk","Asia/Magadan","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Sakhalin","Asia/Srednekolymsk","Asia/Tomsk","Asia/Ust-Nera","Asia/Vladivostok","Asia/Yakutsk","Asia/Yekaterinburg","Europe/Astrakhan","Europe/Kaliningrad","Europe/Kirov","Europe/Moscow","Europe/Samara","Europe/Saratov","Europe/Ulyanovsk","Europe/Volgograd"]},{"isoAlpha2":"RW","value":"Rwanda","timeZones":["Africa/Kigali"]},{"isoAlpha2":"SH","value":"Saint Helena","timeZones":["Atlantic/St_Helena"]},{"isoAlpha2":"KN","value":"Saint Kitts and Nevis","timeZones":["America/St_Kitts"]},{"isoAlpha2":"LC","value":"Saint Lucia","timeZones":["America/St_Lucia"]},{"isoAlpha2":"PM","value":"Saint Pierre and Miquelon","timeZones":["America/Miquelon"]},{"isoAlpha2":"VC","value":"Saint Vincent and the Grenadines","timeZones":["America/St_Vincent"]},{"isoAlpha2":"BL","value":"Saint-Barthelemy","timeZones":["America/St_Barthelemy"]},{"isoAlpha2":"MF","value":"Saint-Martin (French part)","timeZones":["America/Marigot"]},{"isoAlpha2":"WS","value":"Samoa","timeZones":["Pacific/Apia"]},{"isoAlpha2":"SM","value":"San Marino","timeZones":["Europe/San_Marino"]},{"isoAlpha2":"ST","value":"Sao Tome and Principe","timeZones":["Africa/Sao_Tome"]},{"isoAlpha2":"SA","value":"Saudi Arabia","timeZones":["Asia/Riyadh"]},{"isoAlpha2":"SN","value":"Senegal","timeZones":["Africa/Dakar"]},{"isoAlpha2":"RS","value":"Serbia","timeZones":["Europe/Belgrade"]},{"isoAlpha2":"SC","value":"Seychelles","timeZones":["Indian/Mahe"]},{"isoAlpha2":"SL","value":"Sierra Leone","timeZones":["Africa/Freetown"]},{"isoAlpha2":"SG","value":"Singapore","timeZones":["Asia/Singapore"]},{"isoAlpha2":"SX","value":"Sint Maarten (Dutch part)","timeZones":["America/Anguilla"]},{"isoAlpha2":"SK","value":"Slovakia","timeZones":["Europe/Bratislava"]},{"isoAlpha2":"SI","value":"Slovenia","timeZones":["Europe/Ljubljana"]},{"isoAlpha2":"SB","value":"Solomon Islands","timeZones":["Pacific/Guadalcanal"]},{"isoAlpha2":"SO","value":"Somalia","timeZones":["Africa/Mogadishu"]},{"isoAlpha2":"ZA","value":"South Africa","timeZones":["Africa/Johannesburg"]},{"isoAlpha2":"GS","value":"South Georgia","timeZones":["Atlantic/South_Georgia"]},{"isoAlpha2":"KR","value":"South Korea","timeZones":["Asia/Seoul"]},{"isoAlpha2":"SS","value":"South Sudan","timeZones":["Africa/Juba"]},{"isoAlpha2":"ES","value":"Spain","timeZones":["Africa/Ceuta","Atlantic/Canary","Europe/Madrid"]},{"isoAlpha2":"LK","value":"Sri Lanka","timeZones":["Asia/Colombo"]},{"isoAlpha2":"SD","value":"Sudan","timeZones":["Africa/Khartoum"]},{"isoAlpha2":"SR","value":"Suriname","timeZones":["America/Paramaribo"]},{"isoAlpha2":"SJ","value":"Svalbard and Jan Mayen Islands","timeZones":["Arctic/Longyearbyen"]},{"isoAlpha2":"SE","value":"Sweden","timeZones":["Europe/Stockholm"]},{"isoAlpha2":"CH","value":"Switzerland","timeZones":["Europe/Zurich"]},{"isoAlpha2":"SY","value":"Syria","timeZones":["Asia/Damascus"]},{"isoAlpha2":"TW","value":"Taiwan","timeZones":["Asia/Taipei"]},{"isoAlpha2":"TJ","value":"Tajikistan","timeZones":["Asia/Dushanbe"]},{"isoAlpha2":"TZ","value":"Tanzania","timeZones":["Africa/Dar_es_Salaam"]},{"isoAlpha2":"TH","value":"Thailand","timeZones":["Asia/Bangkok"]},{"isoAlpha2":"BS","value":"The Bahamas","timeZones":["America/Nassau"]},{"isoAlpha2":"GM","value":"The Gambia ","timeZones":["Africa/Banjul"]},{"isoAlpha2":"TL","value":"Timor-Leste","timeZones":["Asia/Dili"]},{"isoAlpha2":"TG","value":"Togo","timeZones":["Africa/Lome"]},{"isoAlpha2":"TK","value":"Tokelau","timeZones":["Pacific/Fakaofo"]},{"isoAlpha2":"TO","value":"Tonga","timeZones":["Pacific/Tongatapu"]},{"isoAlpha2":"TT","value":"Trinidad and Tobago","timeZones":["America/Port_of_Spain"]},{"isoAlpha2":"TN","value":"Tunisia","timeZones":["Africa/Tunis"]},{"isoAlpha2":"TR","value":"Turkey","timeZones":["Europe/Istanbul"]},{"isoAlpha2":"TM","value":"Turkmenistan","timeZones":["Asia/Ashgabat"]},{"isoAlpha2":"TC","value":"Turks and Caicos Islands","timeZones":["America/Grand_Turk"]},{"isoAlpha2":"TV","value":"Tuvalu","timeZones":["Pacific/Funafuti"]},{"isoAlpha2":"UG","value":"Uganda","timeZones":["Africa/Kampala"]},{"isoAlpha2":"UA","value":"Ukraine","timeZones":["Europe/Kiev","Europe/Simferopol","Europe/Uzhgorod","Europe/Zaporozhye"]},{"isoAlpha2":"AE","value":"United Arab Emirates","timeZones":["Asia/Dubai"]},{"isoAlpha2":"GB","value":"United Kingdom","timeZones":["Europe/London"]},{"isoAlpha2":"US","value":"United States","timeZones":["America/Adak","America/Anchorage","America/Boise","America/Chicago","America/Denver","America/Detroit","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/Los_Angeles","America/Menominee","America/Metlakatla","America/New_York","America/Nome","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Phoenix","America/Sitka","America/Yakutat","Pacific/Honolulu"]},{"isoAlpha2":"UM","value":"United States Minor Outlying Islands","timeZones":["Pacific/Midway","Pacific/Wake"]},{"isoAlpha2":"UY","value":"Uruguay","timeZones":["America/Montevideo"]},{"isoAlpha2":"UZ","value":"Uzbekistan","timeZones":["Asia/Samarkand","Asia/Tashkent"]},{"isoAlpha2":"VU","value":"Vanuatu","timeZones":["Pacific/Efate"]},{"isoAlpha2":"VA","value":"Vatican City State (Holy See)","timeZones":["Europe/Vatican"]},{"isoAlpha2":"VE","value":"Venezuela","timeZones":["America/Caracas"]},{"isoAlpha2":"VN","value":"Vietnam","timeZones":["Asia/Ho_Chi_Minh"]},{"isoAlpha2":"VG","value":"Virgin Islands (British)","timeZones":["America/Tortola"]},{"isoAlpha2":"VI","value":"Virgin Islands (US)","timeZones":["America/St_Thomas"]},{"isoAlpha2":"WF","value":"Wallis and Futuna Islands","timeZones":["Pacific/Wallis"]},{"isoAlpha2":"EH","value":"Western Sahara","timeZones":["Africa/El_Aaiun"]},{"isoAlpha2":"YE","value":"Yemen","timeZones":["Asia/Aden"]},{"isoAlpha2":"ZM","value":"Zambia","timeZones":["Africa/Lusaka"]},{"isoAlpha2":"ZW","value":"Zimbabwe","timeZones":["Africa/Harare"]}],"states":{"AF":[{"value":"Badakhshan","code":"BDS"},{"value":"Badghis","code":"BDG"},{"value":"Baghlan","code":"BGL"},{"value":"Balkh","code":"BAL"},{"value":"Bamyan","code":"BAM"},{"value":"Daykundi","code":"DAY"},{"value":"Farah","code":"FRA"},{"value":"Faryab","code":"FYB"},{"value":"Ghazni","code":"GHA"},{"value":"Ghōr","code":"GHO"},{"value":"Helmand","code":"HEL"},{"value":"Herat","code":"HER"},{"value":"Jowzjan","code":"JOW"},{"value":"Kabul","code":"KAB"},{"value":"Kandahar","code":"KAN"},{"value":"Kapisa","code":"KAP"},{"value":"Khost","code":"KHO"},{"value":"Kunar","code":"KNR"},{"value":"Kunduz Province","code":"KDZ"},{"value":"Laghman","code":"LAG"},{"value":"Logar","code":"LOG"},{"value":"Nangarhar","code":"NAN"},{"value":"Nimruz","code":"NIM"},{"value":"Nuristan","code":"NUR"},{"value":"Paktia","code":"PIA"},{"value":"Paktika","code":"PKA"},{"value":"Panjshir","code":"PAN"},{"value":"Parwan","code":"PAR"},{"value":"Samangan","code":"SAM"},{"value":"Sar-e Pol","code":"SAR"},{"value":"Takhar","code":"TAK"},{"value":"Urozgan","code":"URU"},{"value":"Zabul","code":"ZAB"}],"AX":[{"value":"Brändö","code":"Brändö"},{"value":"Eckerö","code":"Eckerö"},{"value":"Finström","code":"Finström"},{"value":"Föglö","code":"Föglö"},{"value":"Geta","code":"Geta"},{"value":"Hammarland","code":"Hammarland"},{"value":"Jomala","code":"Jomala"},{"value":"Kökar","code":"Kökar"},{"value":"Kumlinge","code":"Kumlinge"},{"value":"Lemland","code":"Lemland"},{"value":"Lumparland","code":"Lumparland"},{"value":"Mariehamn","code":"Mariehamn"},{"value":"Saltvik","code":"Saltvik"},{"value":"Sottunga","code":"Sottunga"},{"value":"Sund","code":"Sund"},{"value":"Vårdö","code":"Vårdö"}],"AL":[{"value":"Berat County","code":"01"},{"value":"Berat District","code":"BR"},{"value":"Bulqizë District","code":"BU"},{"value":"Delvinë District","code":"DL"},{"value":"Devoll District","code":"DV"},{"value":"Dibër County","code":"09"},{"value":"Dibër District","code":"DI"},{"value":"Durrës County","code":"02"},{"value":"Durrës District","code":"DR"},{"value":"Elbasan County","code":"03"},{"value":"Fier County","code":"04"},{"value":"Fier District","code":"FR"},{"value":"Gjirokastër County","code":"05"},{"value":"Gjirokastër District","code":"GJ"},{"value":"Gramsh District","code":"GR"},{"value":"Has District","code":"HA"},{"value":"Kavajë District","code":"KA"},{"value":"Kolonjë District","code":"ER"},{"value":"Korçë County","code":"06"},{"value":"Korçë District","code":"KO"},{"value":"Krujë District","code":"KR"},{"value":"Kuçovë District","code":"KC"},{"value":"Kukës County","code":"07"},{"value":"Kukës District","code":"KU"},{"value":"Kurbin District","code":"KB"},{"value":"Lezhë County","code":"08"},{"value":"Lezhë District","code":"LE"},{"value":"Librazhd District","code":"LB"},{"value":"Lushnjë District","code":"LU"},{"value":"Malësi e Madhe District","code":"MM"},{"value":"Mallakastër District","code":"MK"},{"value":"Mat District","code":"MT"},{"value":"Mirditë District","code":"MR"},{"value":"Peqin District","code":"PQ"},{"value":"Përmet District","code":"PR"},{"value":"Pogradec District","code":"PG"},{"value":"Pukë District","code":"PU"},{"value":"Sarandë District","code":"SR"},{"value":"Shkodër County","code":"10"},{"value":"Shkodër District","code":"SH"},{"value":"Skrapar District","code":"SK"},{"value":"Tepelenë District","code":"TE"},{"value":"Tirana County","code":"11"},{"value":"Tirana District","code":"TR"},{"value":"Tropojë District","code":"TP"},{"value":"Vlorë County","code":"12"},{"value":"Vlorë District","code":"VL"}],"DZ":[{"value":"Adrar","code":"01"},{"value":"Aïn Defla","code":"44"},{"value":"Aïn Témouchent","code":"46"},{"value":"Algiers","code":"16"},{"value":"Annaba","code":"23"},{"value":"Batna","code":"05"},{"value":"Béchar","code":"08"},{"value":"Béjaïa","code":"06"},{"value":"Béni Abbès","code":"53"},{"value":"Biskra","code":"07"},{"value":"Blida","code":"09"},{"value":"Bordj Baji Mokhtar","code":"52"},{"value":"Bordj Bou Arréridj","code":"34"},{"value":"Bouïra","code":"10"},{"value":"Boumerdès","code":"35"},{"value":"Chlef","code":"02"},{"value":"Constantine","code":"25"},{"value":"Djanet","code":"56"},{"value":"Djelfa","code":"17"},{"value":"El Bayadh","code":"32"},{"value":"El M'ghair","code":"49"},{"value":"El Menia","code":"50"},{"value":"El Oued","code":"39"},{"value":"El Tarf","code":"36"},{"value":"Ghardaïa","code":"47"},{"value":"Guelma","code":"24"},{"value":"Illizi","code":"33"},{"value":"In Guezzam","code":"58"},{"value":"In Salah","code":"57"},{"value":"Jijel","code":"18"},{"value":"Khenchela","code":"40"},{"value":"Laghouat","code":"03"},{"value":"M'Sila","code":"28"},{"value":"Mascara","code":"29"},{"value":"Médéa","code":"26"},{"value":"Mila","code":"43"},{"value":"Mostaganem","code":"27"},{"value":"Naama","code":"45"},{"value":"Oran","code":"31"},{"value":"Ouargla","code":"30"},{"value":"Ouled Djellal","code":"51"},{"value":"Oum El Bouaghi","code":"04"},{"value":"Relizane","code":"48"},{"value":"Saïda","code":"20"},{"value":"Sétif","code":"19"},{"value":"Sidi Bel Abbès","code":"22"},{"value":"Skikda","code":"21"},{"value":"Souk Ahras","code":"41"},{"value":"Tamanghasset","code":"11"},{"value":"Tébessa","code":"12"},{"value":"Tiaret","code":"14"},{"value":"Timimoun","code":"54"},{"value":"Tindouf","code":"37"},{"value":"Tipasa","code":"42"},{"value":"Tissemsilt","code":"38"},{"value":"Tizi Ouzou","code":"15"},{"value":"Tlemcen","code":"13"},{"value":"Touggourt","code":"55"}],"AS":[{"value":"American Samoa","code":"American Samoa"}],"AD":[{"value":"Andorra la Vella","code":"07"},{"value":"Canillo","code":"02"},{"value":"Encamp","code":"03"},{"value":"Escaldes-Engordany","code":"08"},{"value":"La Massana","code":"04"},{"value":"Ordino","code":"05"},{"value":"Sant Julià de Lòria","code":"06"}],"AO":[{"value":"Bengo Province","code":"BGO"},{"value":"Benguela Province","code":"BGU"},{"value":"Bié Province","code":"BIE"},{"value":"Cabinda Province","code":"CAB"},{"value":"Cuando Cubango Province","code":"CCU"},{"value":"Cuanza Norte Province","code":"CNO"},{"value":"Cuanza Sul","code":"CUS"},{"value":"Cunene Province","code":"CNN"},{"value":"Huambo Province","code":"HUA"},{"value":"Huíla Province","code":"HUI"},{"value":"Luanda Province","code":"LUA"},{"value":"Lunda Norte Province","code":"LNO"},{"value":"Lunda Sul Province","code":"LSU"},{"value":"Malanje Province","code":"MAL"},{"value":"Moxico Province","code":"MOX"},{"value":"Uíge Province","code":"UIG"},{"value":"Zaire Province","code":"ZAI"}],"AI":[{"value":"Blowing Point","code":"Blowing Point"},{"value":"East End","code":"East End"},{"value":"George Hill","code":"George Hill"},{"value":"Island Harbour","code":"Island Harbour"},{"value":"North Hill","code":"North Hill"},{"value":"North Side","code":"North Side"},{"value":"Sandy Ground","code":"Sandy Ground"},{"value":"Sandy Hill","code":"Sandy Hill"},{"value":"South Hill","code":"South Hill"},{"value":"Stoney Ground","code":"Stoney Ground"},{"value":"The Farrington","code":"The Farrington"},{"value":"The Quarter","code":"The Quarter"},{"value":"The Valley","code":"The Valley"},{"value":"West End","code":"West End"}],"AQ":[{"value":"Antarctica","code":"Antarctica"}],"AG":[{"value":"Barbuda","code":"10"},{"value":"Redonda","code":"11"},{"value":"Saint George Parish","code":"03"},{"value":"Saint John Parish","code":"04"},{"value":"Saint Mary Parish","code":"05"},{"value":"Saint Paul Parish","code":"06"},{"value":"Saint Peter Parish","code":"07"},{"value":"Saint Philip Parish","code":"08"}],"AR":[{"value":"Buenos Aires","code":"B"},{"value":"Catamarca","code":"K"},{"value":"Chaco","code":"H"},{"value":"Chubut","code":"U"},{"value":"Ciudad Autónoma de Buenos Aires","code":"C"},{"value":"Córdoba","code":"X"},{"value":"Corrientes","code":"W"},{"value":"Entre Ríos","code":"E"},{"value":"Formosa","code":"P"},{"value":"Jujuy","code":"Y"},{"value":"La Pampa","code":"L"},{"value":"La Rioja","code":"F"},{"value":"Mendoza","code":"M"},{"value":"Misiones","code":"N"},{"value":"Neuquén","code":"Q"},{"value":"Río Negro","code":"R"},{"value":"Salta","code":"A"},{"value":"San Juan","code":"J"},{"value":"San Luis","code":"D"},{"value":"Santa Cruz","code":"Z"},{"value":"Santa Fe","code":"S"},{"value":"Santiago del Estero","code":"G"},{"value":"Tierra del Fuego","code":"V"},{"value":"Tucumán","code":"T"}],"AM":[{"value":"Aragatsotn Region","code":"AG"},{"value":"Ararat Province","code":"AR"},{"value":"Armavir Region","code":"AV"},{"value":"Gegharkunik Province","code":"GR"},{"value":"Kotayk Region","code":"KT"},{"value":"Lori Region","code":"LO"},{"value":"Shirak Region","code":"SH"},{"value":"Syunik Province","code":"SU"},{"value":"Tavush Region","code":"TV"},{"value":"Vayots Dzor Region","code":"VD"},{"value":"Yerevan","code":"ER"}],"AW":[{"value":"Noord","code":"Noord"},{"value":"Oranjestad East","code":"Oranjestad East"},{"value":"Oranjestad West","code":"Oranjestad West"},{"value":"Paradera","code":"Paradera"},{"value":"San Nicolaas Noord","code":"San Nicolaas Noord"},{"value":"San Nicolaas Zuid","code":"San Nicolaas Zuid"},{"value":"Santa Cruz","code":"Santa Cruz"},{"value":"Savaneta","code":"Savaneta"}],"AU":[{"value":"Australian Capital Territory","code":"ACT"},{"value":"New South Wales","code":"NSW"},{"value":"Northern Territory","code":"NT"},{"value":"Queensland","code":"QLD"},{"value":"South Australia","code":"SA"},{"value":"Tasmania","code":"TAS"},{"value":"Victoria","code":"VIC"},{"value":"Western Australia","code":"WA"}],"AT":[{"value":"Burgenland","code":"1"},{"value":"Carinthia","code":"2"},{"value":"Lower Austria","code":"3"},{"value":"Salzburg","code":"5"},{"value":"Styria","code":"6"},{"value":"Tyrol","code":"7"},{"value":"Upper Austria","code":"4"},{"value":"Vienna","code":"9"},{"value":"Vorarlberg","code":"8"}],"AZ":[{"value":"Absheron District","code":"ABS"},{"value":"Agdam District","code":"AGM"},{"value":"Agdash District","code":"AGS"},{"value":"Aghjabadi District","code":"AGC"},{"value":"Agstafa District","code":"AGA"},{"value":"Agsu District","code":"AGU"},{"value":"Astara District","code":"AST"},{"value":"Babek District","code":"BAB"},{"value":"Baku","code":"BA"},{"value":"Balakan District","code":"BAL"},{"value":"Barda District","code":"BAR"},{"value":"Beylagan District","code":"BEY"},{"value":"Bilasuvar District","code":"BIL"},{"value":"Dashkasan District","code":"DAS"},{"value":"Fizuli District","code":"FUZ"},{"value":"Ganja","code":"GA"},{"value":"Gədəbəy","code":"GAD"},{"value":"Gobustan District","code":"QOB"},{"value":"Goranboy District","code":"GOR"},{"value":"Goychay","code":"GOY"},{"value":"Goygol District","code":"GYG"},{"value":"Hajigabul District","code":"HAC"},{"value":"Imishli District","code":"IMI"},{"value":"Ismailli District","code":"ISM"},{"value":"Jabrayil District","code":"CAB"},{"value":"Jalilabad District","code":"CAL"},{"value":"Julfa District","code":"CUL"},{"value":"Kalbajar District","code":"KAL"},{"value":"Kangarli District","code":"KAN"},{"value":"Khachmaz District","code":"XAC"},{"value":"Khizi District","code":"XIZ"},{"value":"Khojali District","code":"XCI"},{"value":"Kurdamir District","code":"KUR"},{"value":"Lachin District","code":"LAC"},{"value":"Lankaran","code":"LAN"},{"value":"Lankaran District","code":"LA"},{"value":"Lerik District","code":"LER"},{"value":"Martuni","code":"XVD"},{"value":"Masally District","code":"MAS"},{"value":"Mingachevir","code":"MI"},{"value":"Nakhchivan Autonomous Republic","code":"NX"},{"value":"Neftchala District","code":"NEF"},{"value":"Oghuz District","code":"OGU"},{"value":"Ordubad District","code":"ORD"},{"value":"Qabala District","code":"QAB"},{"value":"Qakh District","code":"QAX"},{"value":"Qazakh District","code":"QAZ"},{"value":"Quba District","code":"QBA"},{"value":"Qubadli District","code":"QBI"},{"value":"Qusar District","code":"QUS"},{"value":"Saatly District","code":"SAT"},{"value":"Sabirabad District","code":"SAB"},{"value":"Sadarak District","code":"SAD"},{"value":"Salyan District","code":"SAL"},{"value":"Samukh District","code":"SMX"},{"value":"Shabran District","code":"SBN"},{"value":"Shahbuz District","code":"SAH"},{"value":"Shaki","code":"SA"},{"value":"Shaki District","code":"SAK"},{"value":"Shamakhi District","code":"SMI"},{"value":"Shamkir District","code":"SKR"},{"value":"Sharur District","code":"SAR"},{"value":"Shirvan","code":"SR"},{"value":"Shusha District","code":"SUS"},{"value":"Siazan District","code":"SIY"},{"value":"Sumqayit","code":"SM"},{"value":"Tartar District","code":"TAR"},{"value":"Tovuz District","code":"TOV"},{"value":"Ujar District","code":"UCA"},{"value":"Yardymli District","code":"YAR"},{"value":"Yevlakh","code":"YE"},{"value":"Yevlakh District","code":"YEV"},{"value":"Zangilan District","code":"ZAN"},{"value":"Zaqatala District","code":"ZAQ"},{"value":"Zardab District","code":"ZAR"}],"BH":[{"value":"Capital","code":"13"},{"value":"Central","code":"16"},{"value":"Muharraq","code":"15"},{"value":"Northern","code":"17"},{"value":"Southern","code":"14"}],"BD":[{"value":"Barisal ","code":"A"},{"value":"Chittagong ","code":"B"},{"value":"Dhaka ","code":"C"},{"value":"Khulna ","code":"D"},{"value":"Mymensingh ","code":"H"},{"value":"Rajshahi ","code":"E"},{"value":"Rangpur ","code":"F"},{"value":"Sylhet ","code":"G"}],"BB":[{"value":"Christ Church","code":"01"},{"value":"Saint Andrew","code":"02"},{"value":"Saint George","code":"03"},{"value":"Saint James","code":"04"},{"value":"Saint John","code":"05"},{"value":"Saint Joseph","code":"06"},{"value":"Saint Lucy","code":"07"},{"value":"Saint Michael","code":"08"},{"value":"Saint Peter","code":"09"},{"value":"Saint Philip","code":"10"},{"value":"Saint Thomas","code":"11"}],"BY":[{"value":"Brest Region","code":"BR"},{"value":"Gomel Region","code":"HO"},{"value":"Grodno Region","code":"HR"},{"value":"Minsk","code":"HM"},{"value":"Minsk Region","code":"MI"},{"value":"Mogilev Region","code":"MA"},{"value":"Vitebsk Region","code":"VI"}],"BE":[{"value":"Antwerp","code":"VAN"},{"value":"Brussels-Capital Region","code":"BRU"},{"value":"East Flanders","code":"VOV"},{"value":"Flanders","code":"VLG"},{"value":"Flemish Brabant","code":"VBR"},{"value":"Hainaut","code":"WHT"},{"value":"Liège","code":"WLG"},{"value":"Limburg","code":"VLI"},{"value":"Luxembourg","code":"WLX"},{"value":"Namur","code":"WNA"},{"value":"Wallonia","code":"WAL"},{"value":"Walloon Brabant","code":"WBR"},{"value":"West Flanders","code":"VWV"}],"BZ":[{"value":"Belize District","code":"BZ"},{"value":"Cayo District","code":"CY"},{"value":"Corozal District","code":"CZL"},{"value":"Orange Walk District","code":"OW"},{"value":"Stann Creek District","code":"SC"},{"value":"Toledo District","code":"TOL"}],"BJ":[{"value":"Alibori Department","code":"AL"},{"value":"Atakora Department","code":"AK"},{"value":"Atlantique Department","code":"AQ"},{"value":"Borgou Department","code":"BO"},{"value":"Collines Department","code":"CO"},{"value":"Donga Department","code":"DO"},{"value":"Kouffo Department","code":"KO"},{"value":"Littoral Department","code":"LI"},{"value":"Mono Department","code":"MO"},{"value":"Ouémé Department","code":"OU"},{"value":"Plateau Department","code":"PL"},{"value":"Zou Department","code":"ZO"}],"BM":[{"value":"Devonshire","code":"DEV"},{"value":"Hamilton","code":"HA"},{"value":"Paget","code":"PAG"},{"value":"Pembroke","code":"PEM"},{"value":"Saint George's","code":"SGE"},{"value":"Sandys","code":"SAN"},{"value":"Smith's","code":"SMI"},{"value":"Southampton","code":"SOU"},{"value":"Warwick","code":"WAR"}],"BT":[{"value":"Bumthang ","code":"33"},{"value":"Chukha ","code":"12"},{"value":"Dagana ","code":"22"},{"value":"Gasa ","code":"GA"},{"value":"Haa ","code":"13"},{"value":"Lhuntse ","code":"44"},{"value":"Mongar ","code":"42"},{"value":"Paro ","code":"11"},{"value":"Pemagatshel ","code":"43"},{"value":"Punakha ","code":"23"},{"value":"Samdrup Jongkhar ","code":"45"},{"value":"Samtse ","code":"14"},{"value":"Sarpang ","code":"31"},{"value":"Thimphu ","code":"15"},{"value":"Trashi Yangtse\t","code":"TY"},{"value":"Trashigang ","code":"41"},{"value":"Trongsa ","code":"32"},{"value":"Tsirang ","code":"21"},{"value":"Wangdue Phodrang ","code":"24"},{"value":"Zhemgang ","code":"34"}],"BO":[{"value":"Beni Department","code":"B"},{"value":"Chuquisaca Department","code":"H"},{"value":"Cochabamba Department","code":"C"},{"value":"La Paz Department","code":"L"},{"value":"Oruro Department","code":"O"},{"value":"Pando Department","code":"N"},{"value":"Potosí Department","code":"P"},{"value":"Santa Cruz Department","code":"S"},{"value":"Tarija Department","code":"T"}],"BQ":[{"value":"Bonaire","code":"BQ1"},{"value":"Saba","code":"BQ2"},{"value":"Sint Eustatius","code":"BQ3"}],"BA":[{"value":"Bosnian Podrinje Canton","code":"05"},{"value":"Brčko District","code":"BRC"},{"value":"Canton 10","code":"10"},{"value":"Central Bosnia Canton","code":"06"},{"value":"Federation of Bosnia and Herzegovina","code":"BIH"},{"value":"Herzegovina-Neretva Canton","code":"07"},{"value":"Posavina Canton","code":"02"},{"value":"Republika Srpska","code":"SRP"},{"value":"Sarajevo Canton","code":"09"},{"value":"Tuzla Canton","code":"03"},{"value":"Una-Sana Canton","code":"01"},{"value":"West Herzegovina Canton","code":"08"},{"value":"Zenica-Doboj Canton","code":"04"}],"BW":[{"value":"Central District","code":"CE"},{"value":"Ghanzi District","code":"GH"},{"value":"Kgalagadi District","code":"KG"},{"value":"Kgatleng District","code":"KL"},{"value":"Kweneng District","code":"KW"},{"value":"Ngamiland","code":"NG"},{"value":"North-East District","code":"NE"},{"value":"North-West District","code":"NW"},{"value":"South-East District","code":"SE"},{"value":"Southern District","code":"SO"}],"BV":[{"value":"Bouvet Island","code":"Bouvet Island"}],"BR":[{"value":"Acre","code":"AC"},{"value":"Alagoas","code":"AL"},{"value":"Amapá","code":"AP"},{"value":"Amazonas","code":"AM"},{"value":"Bahia","code":"BA"},{"value":"Ceará","code":"CE"},{"value":"Distrito Federal","code":"DF"},{"value":"Espírito Santo","code":"ES"},{"value":"Goiás","code":"GO"},{"value":"Maranhão","code":"MA"},{"value":"Mato Grosso","code":"MT"},{"value":"Mato Grosso do Sul","code":"MS"},{"value":"Minas Gerais","code":"MG"},{"value":"Pará","code":"PA"},{"value":"Paraíba","code":"PB"},{"value":"Paraná","code":"PR"},{"value":"Pernambuco","code":"PE"},{"value":"Piauí","code":"PI"},{"value":"Rio de Janeiro","code":"RJ"},{"value":"Rio Grande do Norte","code":"RN"},{"value":"Rio Grande do Sul","code":"RS"},{"value":"Rondônia","code":"RO"},{"value":"Roraima","code":"RR"},{"value":"Santa Catarina","code":"SC"},{"value":"São Paulo","code":"SP"},{"value":"Sergipe","code":"SE"},{"value":"Tocantins","code":"TO"}],"IO":[{"value":"British Indian Ocean Territory","code":"British Indian Ocean Territory"}],"BN":[{"value":"Belait District","code":"BE"},{"value":"Brunei-Muara District","code":"BM"},{"value":"Temburong District","code":"TE"},{"value":"Tutong District","code":"TU"}],"BG":[{"value":"Blagoevgrad Province","code":"01"},{"value":"Burgas Province","code":"02"},{"value":"Dobrich Province","code":"08"},{"value":"Gabrovo Province","code":"07"},{"value":"Haskovo Province","code":"26"},{"value":"Kardzhali Province","code":"09"},{"value":"Kyustendil Province","code":"10"},{"value":"Lovech Province","code":"11"},{"value":"Montana Province","code":"12"},{"value":"Pazardzhik Province","code":"13"},{"value":"Pernik Province","code":"14"},{"value":"Pleven Province","code":"15"},{"value":"Plovdiv Province","code":"16"},{"value":"Razgrad Province","code":"17"},{"value":"Ruse Province","code":"18"},{"value":"Shumen","code":"27"},{"value":"Silistra Province","code":"19"},{"value":"Sliven Province","code":"20"},{"value":"Smolyan Province","code":"21"},{"value":"Sofia City Province","code":"22"},{"value":"Sofia Province","code":"23"},{"value":"Stara Zagora Province","code":"24"},{"value":"Targovishte Province","code":"25"},{"value":"Varna Province","code":"03"},{"value":"Veliko Tarnovo Province","code":"04"},{"value":"Vidin Province","code":"05"},{"value":"Vratsa Province","code":"06"},{"value":"Yambol Province","code":"28"}],"BF":[{"value":"Balé Province","code":"BAL"},{"value":"Bam Province","code":"BAM"},{"value":"Banwa Province","code":"BAN"},{"value":"Bazèga Province","code":"BAZ"},{"value":"Boucle du Mouhoun Region","code":"01"},{"value":"Bougouriba Province","code":"BGR"},{"value":"Boulgou","code":"BLG"},{"value":"Cascades Region","code":"02"},{"value":"Centre","code":"03"},{"value":"Centre-Est Region","code":"04"},{"value":"Centre-Nord Region","code":"05"},{"value":"Centre-Ouest Region","code":"06"},{"value":"Centre-Sud Region","code":"07"},{"value":"Comoé Province","code":"COM"},{"value":"Est Region","code":"08"},{"value":"Ganzourgou Province","code":"GAN"},{"value":"Gnagna Province","code":"GNA"},{"value":"Gourma Province","code":"GOU"},{"value":"Hauts-Bassins Region","code":"09"},{"value":"Houet Province","code":"HOU"},{"value":"Ioba Province","code":"IOB"},{"value":"Kadiogo Province","code":"KAD"},{"value":"Kénédougou Province","code":"KEN"},{"value":"Komondjari Province","code":"KMD"},{"value":"Kompienga Province","code":"KMP"},{"value":"Kossi Province","code":"KOS"},{"value":"Koulpélogo Province","code":"KOP"},{"value":"Kouritenga Province","code":"KOT"},{"value":"Kourwéogo Province","code":"KOW"},{"value":"Léraba Province","code":"LER"},{"value":"Loroum Province","code":"LOR"},{"value":"Mouhoun","code":"MOU"},{"value":"Nahouri Province","code":"NAO"},{"value":"Namentenga Province","code":"NAM"},{"value":"Nayala Province","code":"NAY"},{"value":"Nord Region, Burkina Faso","code":"10"},{"value":"Noumbiel Province","code":"NOU"},{"value":"Oubritenga Province","code":"OUB"},{"value":"Oudalan Province","code":"OUD"},{"value":"Passoré Province","code":"PAS"},{"value":"Plateau-Central Region","code":"11"},{"value":"Poni Province","code":"PON"},{"value":"Sahel Region","code":"12"},{"value":"Sanguié Province","code":"SNG"},{"value":"Sanmatenga Province","code":"SMT"},{"value":"Séno Province","code":"SEN"},{"value":"Sissili Province","code":"SIS"},{"value":"Soum Province","code":"SOM"},{"value":"Sourou Province","code":"SOR"},{"value":"Sud-Ouest Region","code":"13"},{"value":"Tapoa Province","code":"TAP"},{"value":"Tuy Province","code":"TUI"},{"value":"Yagha Province","code":"YAG"},{"value":"Yatenga Province","code":"YAT"},{"value":"Ziro Province","code":"ZIR"},{"value":"Zondoma Province","code":"ZON"},{"value":"Zoundwéogo Province","code":"ZOU"}],"BI":[{"value":"Bubanza Province","code":"BB"},{"value":"Bujumbura Mairie Province","code":"BM"},{"value":"Bujumbura Rural Province","code":"BL"},{"value":"Bururi Province","code":"BR"},{"value":"Cankuzo Province","code":"CA"},{"value":"Cibitoke Province","code":"CI"},{"value":"Gitega Province","code":"GI"},{"value":"Karuzi Province","code":"KR"},{"value":"Kayanza Province","code":"KY"},{"value":"Kirundo Province","code":"KI"},{"value":"Makamba Province","code":"MA"},{"value":"Muramvya Province","code":"MU"},{"value":"Muyinga Province","code":"MY"},{"value":"Mwaro Province","code":"MW"},{"value":"Ngozi Province","code":"NG"},{"value":"Rumonge Province","code":"RM"},{"value":"Rutana Province","code":"RT"},{"value":"Ruyigi Province","code":"RY"}],"KH":[{"value":"Banteay Meanchey","code":"1"},{"value":"Battambang","code":"2"},{"value":"Kampong Cham","code":"3"},{"value":"Kampong Chhnang","code":"4"},{"value":"Kampong Speu","code":"5"},{"value":"Kampong Thom","code":"6"},{"value":"Kampot","code":"7"},{"value":"Kandal","code":"8"},{"value":"Kep","code":"23"},{"value":"Koh Kong","code":"9"},{"value":"Kratie","code":"10"},{"value":"Mondulkiri","code":"11"},{"value":"Oddar Meanchey","code":"22"},{"value":"Pailin","code":"24"},{"value":"Phnom Penh","code":"12"},{"value":"Preah Vihear","code":"13"},{"value":"Prey Veng","code":"14"},{"value":"Pursat","code":"15"},{"value":"Ratanakiri","code":"16"},{"value":"Siem Reap","code":"17"},{"value":"Sihanoukville","code":"18"},{"value":"Stung Treng","code":"19"},{"value":"Svay Rieng","code":"20"},{"value":"Takeo","code":"21"}],"CM":[{"value":"Adamawa","code":"AD"},{"value":"Centre","code":"CE"},{"value":"East","code":"ES"},{"value":"Far North","code":"EN"},{"value":"Littoral","code":"LT"},{"value":"North","code":"NO"},{"value":"Northwest","code":"NW"},{"value":"South","code":"SU"},{"value":"Southwest","code":"SW"},{"value":"West","code":"OU"}],"CA":[{"value":"Alberta","code":"AB"},{"value":"British Columbia","code":"BC"},{"value":"Manitoba","code":"MB"},{"value":"New Brunswick","code":"NB"},{"value":"Newfoundland and Labrador","code":"NL"},{"value":"Northwest Territories","code":"NT"},{"value":"Nova Scotia","code":"NS"},{"value":"Nunavut","code":"NU"},{"value":"Ontario","code":"ON"},{"value":"Prince Edward Island","code":"PE"},{"value":"Quebec","code":"QC"},{"value":"Saskatchewan","code":"SK"},{"value":"Yukon","code":"YT"}],"CV":[{"value":"Barlavento Islands","code":"B"},{"value":"Boa Vista","code":"BV"},{"value":"Brava","code":"BR"},{"value":"Maio Municipality","code":"MA"},{"value":"Mosteiros","code":"MO"},{"value":"Paul","code":"PA"},{"value":"Porto Novo","code":"PN"},{"value":"Praia","code":"PR"},{"value":"Ribeira Brava Municipality","code":"RB"},{"value":"Ribeira Grande","code":"RG"},{"value":"Ribeira Grande de Santiago","code":"RS"},{"value":"Sal","code":"SL"},{"value":"Santa Catarina","code":"CA"},{"value":"Santa Catarina do Fogo","code":"CF"},{"value":"Santa Cruz","code":"CR"},{"value":"São Domingos","code":"SD"},{"value":"São Filipe","code":"SF"},{"value":"São Lourenço dos Órgãos","code":"SO"},{"value":"São Miguel","code":"SM"},{"value":"São Vicente","code":"SV"},{"value":"Sotavento Islands","code":"S"},{"value":"Tarrafal","code":"TA"},{"value":"Tarrafal de São Nicolau","code":"TS"}],"KY":[{"value":"Cayman Brac","code":"Cayman Brac"},{"value":"Grand Cayman","code":"Grand Cayman"},{"value":"Little Cayman","code":"Little Cayman"}],"CF":[{"value":"Bamingui-Bangoran Prefecture","code":"BB"},{"value":"Bangui","code":"BGF"},{"value":"Basse-Kotto Prefecture","code":"BK"},{"value":"Haut-Mbomou Prefecture","code":"HM"},{"value":"Haute-Kotto Prefecture","code":"HK"},{"value":"Kémo Prefecture","code":"KG"},{"value":"Lobaye Prefecture","code":"LB"},{"value":"Mambéré-Kadéï","code":"HS"},{"value":"Mbomou Prefecture","code":"MB"},{"value":"Nana-Grébizi Economic Prefecture","code":"KB"},{"value":"Nana-Mambéré Prefecture","code":"NM"},{"value":"Ombella-M'Poko Prefecture","code":"MP"},{"value":"Ouaka Prefecture","code":"UK"},{"value":"Ouham Prefecture","code":"AC"},{"value":"Ouham-Pendé Prefecture","code":"OP"},{"value":"Sangha-Mbaéré","code":"SE"},{"value":"Vakaga Prefecture","code":"VK"}],"TD":[{"value":"Bahr el Gazel","code":"BG"},{"value":"Batha","code":"BA"},{"value":"Borkou","code":"BO"},{"value":"Chari-Baguirmi","code":"CB"},{"value":"Ennedi-Est","code":"EE"},{"value":"Ennedi-Ouest","code":"EO"},{"value":"Guéra","code":"GR"},{"value":"Hadjer-Lamis","code":"HL"},{"value":"Kanem","code":"KA"},{"value":"Lac","code":"LC"},{"value":"Logone Occidental","code":"LO"},{"value":"Logone Oriental","code":"LR"},{"value":"Mandoul","code":"MA"},{"value":"Mayo-Kebbi Est","code":"ME"},{"value":"Mayo-Kebbi Ouest","code":"MO"},{"value":"Moyen-Chari","code":"MC"},{"value":"N'Djamena","code":"ND"},{"value":"Ouaddaï","code":"OD"},{"value":"Salamat","code":"SA"},{"value":"Sila","code":"SI"},{"value":"Tandjilé","code":"TA"},{"value":"Tibesti","code":"TI"},{"value":"Wadi Fira","code":"WF"}],"CL":[{"value":"Aisén del General Carlos Ibañez del Campo","code":"AI"},{"value":"Antofagasta","code":"AN"},{"value":"Arica y Parinacota","code":"AP"},{"value":"Atacama","code":"AT"},{"value":"Biobío","code":"BI"},{"value":"Coquimbo","code":"CO"},{"value":"La Araucanía","code":"AR"},{"value":"Libertador General Bernardo O'Higgins","code":"LI"},{"value":"Los Lagos","code":"LL"},{"value":"Los Ríos","code":"LR"},{"value":"Magallanes y de la Antártica Chilena","code":"MA"},{"value":"Maule","code":"ML"},{"value":"Ñuble","code":"NB"},{"value":"Región Metropolitana de Santiago","code":"RM"},{"value":"Tarapacá","code":"TA"},{"value":"Valparaíso","code":"VS"}],"CN":[{"value":"Anhui","code":"AH"},{"value":"Beijing","code":"BJ"},{"value":"Chongqing","code":"CQ"},{"value":"Fujian","code":"FJ"},{"value":"Gansu","code":"GS"},{"value":"Guangdong","code":"GD"},{"value":"Guangxi Zhuang","code":"GX"},{"value":"Guizhou","code":"GZ"},{"value":"Hainan","code":"HI"},{"value":"Hebei","code":"HE"},{"value":"Heilongjiang","code":"HL"},{"value":"Henan","code":"HA"},{"value":"Hong Kong SAR","code":"HK"},{"value":"Hubei","code":"HB"},{"value":"Hunan","code":"HN"},{"value":"Inner Mongolia","code":"NM"},{"value":"Jiangsu","code":"JS"},{"value":"Jiangxi","code":"JX"},{"value":"Jilin","code":"JL"},{"value":"Liaoning","code":"LN"},{"value":"Macau SAR","code":"MO"},{"value":"Ningxia Huizu","code":"NX"},{"value":"Qinghai","code":"QH"},{"value":"Shaanxi","code":"SN"},{"value":"Shandong","code":"SD"},{"value":"Shanghai","code":"SH"},{"value":"Shanxi","code":"SX"},{"value":"Sichuan","code":"SC"},{"value":"Taiwan","code":"TW"},{"value":"Tianjin","code":"TJ"},{"value":"Xinjiang","code":"XJ"},{"value":"Xizang","code":"XZ"},{"value":"Yunnan","code":"YN"},{"value":"Zhejiang","code":"ZJ"}],"CX":[{"value":"Christmas Island","code":"Christmas Island"}],"CC":[{"value":"Cocos (Keeling) Islands","code":"Cocos (Keeling) Islands"}],"CO":[{"value":"Amazonas","code":"AMA"},{"value":"Antioquia","code":"ANT"},{"value":"Arauca","code":"ARA"},{"value":"Archipiélago de San Andrés, Providencia y Santa Catalina","code":"SAP"},{"value":"Atlántico","code":"ATL"},{"value":"Bogotá D.C.","code":"DC"},{"value":"Bolívar","code":"BOL"},{"value":"Boyacá","code":"BOY"},{"value":"Caldas","code":"CAL"},{"value":"Caquetá","code":"CAQ"},{"value":"Casanare","code":"CAS"},{"value":"Cauca","code":"CAU"},{"value":"Cesar","code":"CES"},{"value":"Chocó","code":"CHO"},{"value":"Córdoba","code":"COR"},{"value":"Cundinamarca","code":"CUN"},{"value":"Guainía","code":"GUA"},{"value":"Guaviare","code":"GUV"},{"value":"Huila","code":"HUI"},{"value":"La Guajira","code":"LAG"},{"value":"Magdalena","code":"MAG"},{"value":"Meta","code":"MET"},{"value":"Nariño","code":"NAR"},{"value":"Norte de Santander","code":"NSA"},{"value":"Putumayo","code":"PUT"},{"value":"Quindío","code":"QUI"},{"value":"Risaralda","code":"RIS"},{"value":"Santander","code":"SAN"},{"value":"Sucre","code":"SUC"},{"value":"Tolima","code":"TOL"},{"value":"Valle del Cauca","code":"VAC"},{"value":"Vaupés","code":"VAU"},{"value":"Vichada","code":"VID"}],"KM":[{"value":"Anjouan","code":"A"},{"value":"Grande Comore","code":"G"},{"value":"Mohéli","code":"M"}],"CG":[{"value":"Bouenza Department","code":"11"},{"value":"Brazzaville","code":"BZV"},{"value":"Cuvette Department","code":"8"},{"value":"Cuvette-Ouest Department","code":"15"},{"value":"Kouilou Department","code":"5"},{"value":"Lékoumou Department","code":"2"},{"value":"Likouala Department","code":"7"},{"value":"Niari Department","code":"9"},{"value":"Plateaux Department","code":"14"},{"value":"Pointe-Noire","code":"16"},{"value":"Pool Department","code":"12"},{"value":"Sangha Department","code":"13"}],"CK":[{"value":"Cook Islands","code":"Cook Islands"}],"CR":[{"value":"Alajuela Province","code":"A"},{"value":"Guanacaste Province","code":"G"},{"value":"Heredia Province","code":"H"},{"value":"Limón Province","code":"L"},{"value":"Provincia de Cartago","code":"C"},{"value":"Puntarenas Province","code":"P"},{"value":"San José Province","code":"SJ"}],"CI":[{"value":"Abidjan","code":"AB"},{"value":"Agnéby","code":"16"},{"value":"Bafing Region","code":"17"},{"value":"Bas-Sassandra District","code":"BS"},{"value":"Bas-Sassandra Region","code":"09"},{"value":"Comoé District","code":"CM"},{"value":"Denguélé District","code":"DN"},{"value":"Denguélé Region","code":"10"},{"value":"Dix-Huit Montagnes","code":"06"},{"value":"Fromager","code":"18"},{"value":"Gôh-Djiboua District","code":"GD"},{"value":"Haut-Sassandra","code":"02"},{"value":"Lacs District","code":"LC"},{"value":"Lacs Region","code":"07"},{"value":"Lagunes District","code":"LG"},{"value":"Lagunes region","code":"01"},{"value":"Marahoué Region","code":"12"},{"value":"Montagnes District","code":"MG"},{"value":"Moyen-Cavally","code":"19"},{"value":"Moyen-Comoé","code":"05"},{"value":"N'zi-Comoé","code":"11"},{"value":"Sassandra-Marahoué District","code":"SM"},{"value":"Savanes Region","code":"03"},{"value":"Sud-Bandama","code":"15"},{"value":"Sud-Comoé","code":"13"},{"value":"Vallée du Bandama District","code":"VB"},{"value":"Vallée du Bandama Region","code":"04"},{"value":"Woroba District","code":"WR"},{"value":"Worodougou","code":"14"},{"value":"Yamoussoukro","code":"YM"},{"value":"Zanzan Region","code":"ZZ"}],"HR":[{"value":"Bjelovar-Bilogora","code":"07"},{"value":"Brod-Posavina","code":"12"},{"value":"Dubrovnik-Neretva","code":"19"},{"value":"Istria","code":"18"},{"value":"Karlovac","code":"04"},{"value":"Koprivnica-Križevci","code":"06"},{"value":"Krapina-Zagorje","code":"02"},{"value":"Lika-Senj","code":"09"},{"value":"Međimurje","code":"20"},{"value":"Osijek-Baranja","code":"14"},{"value":"Požega-Slavonia","code":"11"},{"value":"Primorje-Gorski Kotar","code":"08"},{"value":"Šibenik-Knin","code":"15"},{"value":"Sisak-Moslavina","code":"03"},{"value":"Split-Dalmatia","code":"17"},{"value":"Varaždin","code":"05"},{"value":"Virovitica-Podravina","code":"10"},{"value":"Vukovar-Syrmia","code":"16"},{"value":"Zadar","code":"13"},{"value":"Zagreb","code":"01"},{"value":"Zagreb","code":"21"}],"CU":[{"value":"Artemisa Province","code":"15"},{"value":"Camagüey Province","code":"09"},{"value":"Ciego de Ávila Province","code":"08"},{"value":"Cienfuegos Province","code":"06"},{"value":"Granma Province","code":"12"},{"value":"Guantánamo Province","code":"14"},{"value":"Havana Province","code":"03"},{"value":"Holguín Province","code":"11"},{"value":"Isla de la Juventud","code":"99"},{"value":"Las Tunas Province","code":"10"},{"value":"Matanzas Province","code":"04"},{"value":"Mayabeque Province","code":"16"},{"value":"Pinar del Río Province","code":"01"},{"value":"Sancti Spíritus Province","code":"07"},{"value":"Santiago de Cuba Province","code":"13"},{"value":"Villa Clara Province","code":"05"}],"CW":[{"value":"Curaçao","code":"Curaçao"}],"CY":[{"value":"Famagusta District (Mağusa)","code":"04"},{"value":"Kyrenia District (Keryneia)","code":"06"},{"value":"Larnaca District (Larnaka)","code":"03"},{"value":"Limassol District (Leymasun)","code":"02"},{"value":"Nicosia District (Lefkoşa)","code":"01"},{"value":"Paphos District (Pafos)","code":"05"}],"CZ":[{"value":"Benešov","code":"201"},{"value":"Beroun","code":"202"},{"value":"Blansko","code":"641"},{"value":"Břeclav","code":"644"},{"value":"Brno-město","code":"642"},{"value":"Brno-venkov","code":"643"},{"value":"Bruntál","code":"801"},{"value":"Česká Lípa","code":"511"},{"value":"České Budějovice","code":"311"},{"value":"Český Krumlov","code":"312"},{"value":"Cheb","code":"411"},{"value":"Chomutov","code":"422"},{"value":"Chrudim","code":"531"},{"value":"Děčín","code":"421"},{"value":"Domažlice","code":"321"},{"value":"Frýdek-Místek","code":"802"},{"value":"Havlíčkův Brod","code":"631"},{"value":"Hodonín","code":"645"},{"value":"Hradec Králové","code":"521"},{"value":"Jablonec nad Nisou","code":"512"},{"value":"Jeseník","code":"711"},{"value":"Jičín","code":"522"},{"value":"Jihlava","code":"632"},{"value":"Jihočeský kraj","code":"31"},{"value":"Jihomoravský kraj","code":"64"},{"value":"Jindřichův Hradec","code":"313"},{"value":"Karlovarský kraj","code":"41"},{"value":"Karlovy Vary","code":"412"},{"value":"Karviná","code":"803"},{"value":"Kladno","code":"203"},{"value":"Klatovy","code":"322"},{"value":"Kolín","code":"204"},{"value":"Kraj Vysočina","code":"63"},{"value":"Královéhradecký kraj","code":"52"},{"value":"Kroměříž","code":"721"},{"value":"Kutná Hora","code":"205"},{"value":"Liberec","code":"513"},{"value":"Liberecký kraj","code":"51"},{"value":"Litoměřice","code":"423"},{"value":"Louny","code":"424"},{"value":"Mělník","code":"206"},{"value":"Mladá Boleslav","code":"207"},{"value":"Moravskoslezský kraj","code":"80"},{"value":"Most","code":"425"},{"value":"Náchod","code":"523"},{"value":"Nový Jičín","code":"804"},{"value":"Nymburk","code":"208"},{"value":"Olomouc","code":"712"},{"value":"Olomoucký kraj","code":"71"},{"value":"Opava","code":"805"},{"value":"Ostrava-město","code":"806"},{"value":"Pardubice","code":"532"},{"value":"Pardubický kraj","code":"53"},{"value":"Pelhřimov","code":"633"},{"value":"Písek","code":"314"},{"value":"Plzeň-jih","code":"324"},{"value":"Plzeň-město","code":"323"},{"value":"Plzeň-sever","code":"325"},{"value":"Plzeňský kraj","code":"32"},{"value":"Prachatice","code":"315"},{"value":"Praha-východ","code":"209"},{"value":"Praha-západ","code":"20A"},{"value":"Praha, Hlavní město","code":"10"},{"value":"Přerov","code":"714"},{"value":"Příbram","code":"20B"},{"value":"Prostějov","code":"713"},{"value":"Rakovník","code":"20C"},{"value":"Rokycany","code":"326"},{"value":"Rychnov nad Kněžnou","code":"524"},{"value":"Semily","code":"514"},{"value":"Sokolov","code":"413"},{"value":"Strakonice","code":"316"},{"value":"Středočeský kraj","code":"20"},{"value":"Šumperk","code":"715"},{"value":"Svitavy","code":"533"},{"value":"Tábor","code":"317"},{"value":"Tachov","code":"327"},{"value":"Teplice","code":"426"},{"value":"Třebíč","code":"634"},{"value":"Trutnov","code":"525"},{"value":"Uherské Hradiště","code":"722"},{"value":"Ústecký kraj","code":"42"},{"value":"Ústí nad Labem","code":"427"},{"value":"Ústí nad Orlicí","code":"534"},{"value":"Vsetín","code":"723"},{"value":"Vyškov","code":"646"},{"value":"Žďár nad Sázavou","code":"635"},{"value":"Zlín","code":"724"},{"value":"Zlínský kraj","code":"72"},{"value":"Znojmo","code":"647"}],"CD":[{"value":"Bas-Uélé","code":"BU"},{"value":"Équateur","code":"EQ"},{"value":"Haut-Katanga","code":"HK"},{"value":"Haut-Lomami","code":"HL"},{"value":"Haut-Uélé","code":"HU"},{"value":"Ituri","code":"IT"},{"value":"Kasaï","code":"KS"},{"value":"Kasaï Central","code":"KC"},{"value":"Kasaï Oriental","code":"KE"},{"value":"Kinshasa","code":"KN"},{"value":"Kongo Central","code":"BC"},{"value":"Kwango","code":"KG"},{"value":"Kwilu","code":"KL"},{"value":"Lomami","code":"LO"},{"value":"Lualaba","code":"LU"},{"value":"Mai-Ndombe","code":"MN"},{"value":"Maniema","code":"MA"},{"value":"Mongala","code":"MO"},{"value":"Nord-Kivu","code":"NK"},{"value":"Nord-Ubangi","code":"NU"},{"value":"Sankuru","code":"SA"},{"value":"Sud-Kivu","code":"SK"},{"value":"Sud-Ubangi","code":"SU"},{"value":"Tanganyika","code":"TA"},{"value":"Tshopo","code":"TO"},{"value":"Tshuapa","code":"TU"}],"DK":[{"value":"Capital Region of Denmark","code":"84"},{"value":"Central Denmark Region","code":"82"},{"value":"North Denmark Region","code":"81"},{"value":"Region of Southern Denmark","code":"83"},{"value":"Region Zealand","code":"85"}],"DJ":[{"value":"Ali Sabieh Region","code":"AS"},{"value":"Arta Region","code":"AR"},{"value":"Dikhil Region","code":"DI"},{"value":"Djibouti","code":"DJ"},{"value":"Obock Region","code":"OB"},{"value":"Tadjourah Region","code":"TA"}],"DM":[{"value":"Saint Andrew Parish","code":"02"},{"value":"Saint David Parish","code":"03"},{"value":"Saint George Parish","code":"04"},{"value":"Saint John Parish","code":"05"},{"value":"Saint Joseph Parish","code":"06"},{"value":"Saint Luke Parish","code":"07"},{"value":"Saint Mark Parish","code":"08"},{"value":"Saint Patrick Parish","code":"09"},{"value":"Saint Paul Parish","code":"10"},{"value":"Saint Peter Parish","code":"11"}],"DO":[{"value":"Azua Province","code":"02"},{"value":"Baoruco Province","code":"03"},{"value":"Barahona Province","code":"04"},{"value":"Dajabón Province","code":"05"},{"value":"Distrito Nacional","code":"01"},{"value":"Duarte Province","code":"06"},{"value":"El Seibo Province","code":"08"},{"value":"Espaillat Province","code":"09"},{"value":"Hato Mayor Province","code":"30"},{"value":"Hermanas Mirabal Province","code":"19"},{"value":"Independencia","code":"10"},{"value":"La Altagracia Province","code":"11"},{"value":"La Romana Province","code":"12"},{"value":"La Vega Province","code":"13"},{"value":"María Trinidad Sánchez Province","code":"14"},{"value":"Monseñor Nouel Province","code":"28"},{"value":"Monte Cristi Province","code":"15"},{"value":"Monte Plata Province","code":"29"},{"value":"Pedernales Province","code":"16"},{"value":"Peravia Province","code":"17"},{"value":"Puerto Plata Province","code":"18"},{"value":"Samaná Province","code":"20"},{"value":"San Cristóbal Province","code":"21"},{"value":"San José de Ocoa Province","code":"31"},{"value":"San Juan Province","code":"22"},{"value":"San Pedro de Macorís","code":"23"},{"value":"Sánchez Ramírez Province","code":"24"},{"value":"Santiago Province","code":"25"},{"value":"Santiago Rodríguez Province","code":"26"},{"value":"Santo Domingo Province","code":"32"},{"value":"Valverde Province","code":"27"}],"EC":[{"value":"Azuay","code":"A"},{"value":"Bolívar","code":"B"},{"value":"Cañar","code":"F"},{"value":"Carchi","code":"C"},{"value":"Chimborazo","code":"H"},{"value":"Cotopaxi","code":"X"},{"value":"El Oro","code":"O"},{"value":"Esmeraldas","code":"E"},{"value":"Galápagos","code":"W"},{"value":"Guayas","code":"G"},{"value":"Imbabura","code":"I"},{"value":"Loja","code":"L"},{"value":"Los Ríos","code":"R"},{"value":"Manabí","code":"M"},{"value":"Morona-Santiago","code":"S"},{"value":"Napo","code":"N"},{"value":"Orellana","code":"D"},{"value":"Pastaza","code":"Y"},{"value":"Pichincha","code":"P"},{"value":"Santa Elena","code":"SE"},{"value":"Santo Domingo de los Tsáchilas","code":"SD"},{"value":"Sucumbíos","code":"U"},{"value":"Tungurahua","code":"T"},{"value":"Zamora Chinchipe","code":"Z"}],"EG":[{"value":"Alexandria","code":"ALX"},{"value":"Aswan","code":"ASN"},{"value":"Asyut","code":"AST"},{"value":"Beheira","code":"BH"},{"value":"Beni Suef","code":"BNS"},{"value":"Cairo","code":"C"},{"value":"Dakahlia","code":"DK"},{"value":"Damietta","code":"DT"},{"value":"Faiyum","code":"FYM"},{"value":"Gharbia","code":"GH"},{"value":"Giza","code":"GZ"},{"value":"Ismailia","code":"IS"},{"value":"Kafr el-Sheikh","code":"KFS"},{"value":"Luxor","code":"LX"},{"value":"Matrouh","code":"MT"},{"value":"Minya","code":"MN"},{"value":"Monufia","code":"MNF"},{"value":"New Valley","code":"WAD"},{"value":"North Sinai","code":"SIN"},{"value":"Port Said","code":"PTS"},{"value":"Qalyubia","code":"KB"},{"value":"Qena","code":"KN"},{"value":"Red Sea","code":"BA"},{"value":"Sharqia","code":"SHR"},{"value":"Sohag","code":"SHG"},{"value":"South Sinai","code":"JS"},{"value":"Suez","code":"SUZ"}],"SV":[{"value":"Ahuachapán Department","code":"AH"},{"value":"Cabañas Department","code":"CA"},{"value":"Chalatenango Department","code":"CH"},{"value":"Cuscatlán Department","code":"CU"},{"value":"La Libertad Department","code":"LI"},{"value":"La Paz Department","code":"PA"},{"value":"La Unión Department","code":"UN"},{"value":"Morazán Department","code":"MO"},{"value":"San Miguel Department","code":"SM"},{"value":"San Salvador Department","code":"SS"},{"value":"San Vicente Department","code":"SV"},{"value":"Santa Ana Department","code":"SA"},{"value":"Sonsonate Department","code":"SO"},{"value":"Usulután Department","code":"US"}],"GQ":[{"value":"Annobón Province","code":"AN"},{"value":"Bioko Norte Province","code":"BN"},{"value":"Bioko Sur Province","code":"BS"},{"value":"Centro Sur Province","code":"CS"},{"value":"Insular Region","code":"I"},{"value":"Kié-Ntem Province","code":"KN"},{"value":"Litoral Province","code":"LI"},{"value":"Río Muni","code":"C"},{"value":"Wele-Nzas Province","code":"WN"}],"ER":[{"value":"Anseba Region","code":"AN"},{"value":"Debub Region","code":"DU"},{"value":"Gash-Barka Region","code":"GB"},{"value":"Maekel Region","code":"MA"},{"value":"Northern Red Sea Region","code":"SK"},{"value":"Southern Red Sea Region","code":"DK"}],"EE":[{"value":"Harju County","code":"37"},{"value":"Hiiu County","code":"39"},{"value":"Ida-Viru County","code":"44"},{"value":"Järva County","code":"51"},{"value":"Jõgeva County","code":"49"},{"value":"Lääne County","code":"57"},{"value":"Lääne-Viru County","code":"59"},{"value":"Pärnu County","code":"67"},{"value":"Põlva County","code":"65"},{"value":"Rapla County","code":"70"},{"value":"Saare County","code":"74"},{"value":"Tartu County","code":"78"},{"value":"Valga County","code":"82"},{"value":"Viljandi County","code":"84"},{"value":"Võru County","code":"86"}],"SZ":[{"value":"Hhohho District","code":"HH"},{"value":"Lubombo District","code":"LU"},{"value":"Manzini District","code":"MA"},{"value":"Shiselweni District","code":"SH"}],"ET":[{"value":"Addis Ababa","code":"AA"},{"value":"Afar Region","code":"AF"},{"value":"Amhara Region","code":"AM"},{"value":"Benishangul-Gumuz Region","code":"BE"},{"value":"Dire Dawa","code":"DD"},{"value":"Gambela Region","code":"GA"},{"value":"Harari Region","code":"HA"},{"value":"Oromia Region","code":"OR"},{"value":"Somali Region","code":"SO"},{"value":"Southern Nations, Nationalities, and Peoples' Region","code":"SN"},{"value":"Tigray Region","code":"TI"}],"FK":[{"value":"Falkland Islands","code":"Falkland Islands"}],"FO":[{"value":"Eysturoy","code":"EY"},{"value":"Northern Isles","code":"NO"},{"value":"Sandoy","code":"SA"},{"value":"Streymoy","code":"ST"},{"value":"Suðuroy","code":"SU"},{"value":"Vágar","code":"VA"}],"FJ":[{"value":"Ba","code":"01"},{"value":"Bua","code":"02"},{"value":"Cakaudrove","code":"03"},{"value":"Central Division","code":"C"},{"value":"Eastern Division","code":"E"},{"value":"Kadavu","code":"04"},{"value":"Lau","code":"05"},{"value":"Lomaiviti","code":"06"},{"value":"Macuata","code":"07"},{"value":"Nadroga-Navosa","code":"08"},{"value":"Naitasiri","code":"09"},{"value":"Namosi","code":"10"},{"value":"Northern Division","code":"N"},{"value":"Ra","code":"11"},{"value":"Rewa","code":"12"},{"value":"Rotuma","code":"R"},{"value":"Serua","code":"13"},{"value":"Tailevu","code":"14"},{"value":"Western Division","code":"W"}],"FI":[{"value":"Åland Islands","code":"01"},{"value":"Central Finland","code":"08"},{"value":"Central Ostrobothnia","code":"07"},{"value":"Finland Proper","code":"19"},{"value":"Kainuu","code":"05"},{"value":"Kymenlaakso","code":"09"},{"value":"Lapland","code":"10"},{"value":"North Karelia","code":"13"},{"value":"Northern Ostrobothnia","code":"14"},{"value":"Northern Savonia","code":"15"},{"value":"Ostrobothnia","code":"12"},{"value":"Päijänne Tavastia","code":"16"},{"value":"Pirkanmaa","code":"11"},{"value":"Satakunta","code":"17"},{"value":"South Karelia","code":"02"},{"value":"Southern Ostrobothnia","code":"03"},{"value":"Southern Savonia","code":"04"},{"value":"Tavastia Proper","code":"06"},{"value":"Uusimaa","code":"18"}],"FR":[{"value":"Ain","code":"01"},{"value":"Aisne","code":"02"},{"value":"Allier","code":"03"},{"value":"Alpes-de-Haute-Provence","code":"04"},{"value":"Alpes-Maritimes","code":"06"},{"value":"Alsace","code":"6AE"},{"value":"Ardèche","code":"07"},{"value":"Ardennes","code":"08"},{"value":"Ariège","code":"09"},{"value":"Aube","code":"10"},{"value":"Aude","code":"11"},{"value":"Auvergne-Rhône-Alpes","code":"ARA"},{"value":"Aveyron","code":"12"},{"value":"Bas-Rhin","code":"67"},{"value":"Bouches-du-Rhône","code":"13"},{"value":"Bourgogne-Franche-Comté","code":"BFC"},{"value":"Bretagne","code":"BRE"},{"value":"Calvados","code":"14"},{"value":"Cantal","code":"15"},{"value":"Centre-Val de Loire","code":"CVL"},{"value":"Charente","code":"16"},{"value":"Charente-Maritime","code":"17"},{"value":"Cher","code":"18"},{"value":"Clipperton","code":"CP"},{"value":"Corrèze","code":"19"},{"value":"Corse","code":"20R"},{"value":"Corse-du-Sud","code":"2A"},{"value":"Côte-d'Or","code":"21"},{"value":"Côtes-d'Armor","code":"22"},{"value":"Creuse","code":"23"},{"value":"Deux-Sèvres","code":"79"},{"value":"Dordogne","code":"24"},{"value":"Doubs","code":"25"},{"value":"Drôme","code":"26"},{"value":"Essonne","code":"91"},{"value":"Eure","code":"27"},{"value":"Eure-et-Loir","code":"28"},{"value":"Finistère","code":"29"},{"value":"French Guiana","code":"973"},{"value":"French Polynesia","code":"PF"},{"value":"French Southern and Antarctic Lands","code":"TF"},{"value":"Gard","code":"30"},{"value":"Gers","code":"32"},{"value":"Gironde","code":"33"},{"value":"Grand-Est","code":"GES"},{"value":"Guadeloupe","code":"971"},{"value":"Haut-Rhin","code":"68"},{"value":"Haute-Corse","code":"2B"},{"value":"Haute-Garonne","code":"31"},{"value":"Haute-Loire","code":"43"},{"value":"Haute-Marne","code":"52"},{"value":"Haute-Saône","code":"70"},{"value":"Haute-Savoie","code":"74"},{"value":"Haute-Vienne","code":"87"},{"value":"Hautes-Alpes","code":"05"},{"value":"Hautes-Pyrénées","code":"65"},{"value":"Hauts-de-France","code":"HDF"},{"value":"Hauts-de-Seine","code":"92"},{"value":"Hérault","code":"34"},{"value":"Île-de-France","code":"IDF"},{"value":"Ille-et-Vilaine","code":"35"},{"value":"Indre","code":"36"},{"value":"Indre-et-Loire","code":"37"},{"value":"Isère","code":"38"},{"value":"Jura","code":"39"},{"value":"La Réunion","code":"974"},{"value":"Landes","code":"40"},{"value":"Loir-et-Cher","code":"41"},{"value":"Loire","code":"42"},{"value":"Loire-Atlantique","code":"44"},{"value":"Loiret","code":"45"},{"value":"Lot","code":"46"},{"value":"Lot-et-Garonne","code":"47"},{"value":"Lozère","code":"48"},{"value":"Maine-et-Loire","code":"49"},{"value":"Manche","code":"50"},{"value":"Marne","code":"51"},{"value":"Martinique","code":"972"},{"value":"Mayenne","code":"53"},{"value":"Mayotte","code":"976"},{"value":"Métropole de Lyon","code":"69M"},{"value":"Meurthe-et-Moselle","code":"54"},{"value":"Meuse","code":"55"},{"value":"Morbihan","code":"56"},{"value":"Moselle","code":"57"},{"value":"Nièvre","code":"58"},{"value":"Nord","code":"59"},{"value":"Normandie","code":"NOR"},{"value":"Nouvelle-Aquitaine","code":"NAQ"},{"value":"Occitanie","code":"OCC"},{"value":"Oise","code":"60"},{"value":"Orne","code":"61"},{"value":"Paris","code":"75C"},{"value":"Pas-de-Calais","code":"62"},{"value":"Pays-de-la-Loire","code":"PDL"},{"value":"Provence-Alpes-Côte-d’Azur","code":"PAC"},{"value":"Puy-de-Dôme","code":"63"},{"value":"Pyrénées-Atlantiques","code":"64"},{"value":"Pyrénées-Orientales","code":"66"},{"value":"Rhône","code":"69"},{"value":"Saint Pierre and Miquelon","code":"PM"},{"value":"Saint-Barthélemy","code":"BL"},{"value":"Saint-Martin","code":"MF"},{"value":"Saône-et-Loire","code":"71"},{"value":"Sarthe","code":"72"},{"value":"Savoie","code":"73"},{"value":"Seine-et-Marne","code":"77"},{"value":"Seine-Maritime","code":"76"},{"value":"Seine-Saint-Denis","code":"93"},{"value":"Somme","code":"80"},{"value":"Tarn","code":"81"},{"value":"Tarn-et-Garonne","code":"82"},{"value":"Territoire de Belfort","code":"90"},{"value":"Val-d'Oise","code":"95"},{"value":"Val-de-Marne","code":"94"},{"value":"Var","code":"83"},{"value":"Vaucluse","code":"84"},{"value":"Vendée","code":"85"},{"value":"Vienne","code":"86"},{"value":"Vosges","code":"88"},{"value":"Wallis and Futuna","code":"WF"},{"value":"Yonne","code":"89"},{"value":"Yvelines","code":"78"}],"GF":[{"value":"French Guiana","code":"French Guiana"}],"PF":[{"value":"French Polynesia","code":"French Polynesia"}],"TF":[{"value":"French Southern Territories","code":"French Southern Territories"}],"GA":[{"value":"Estuaire Province","code":"1"},{"value":"Haut-Ogooué Province","code":"2"},{"value":"Moyen-Ogooué Province","code":"3"},{"value":"Ngounié Province","code":"4"},{"value":"Nyanga Province","code":"5"},{"value":"Ogooué-Ivindo Province","code":"6"},{"value":"Ogooué-Lolo Province","code":"7"},{"value":"Ogooué-Maritime Province","code":"8"},{"value":"Woleu-Ntem Province","code":"9"}],"GE":[{"value":"Abkhazia","code":"AB"},{"value":"Adjara","code":"AJ"},{"value":"Guria","code":"GU"},{"value":"Imereti","code":"IM"},{"value":"Kakheti","code":"KA"},{"value":"Khelvachauri Municipality","code":"29"},{"value":"Kvemo Kartli","code":"KK"},{"value":"Mtskheta-Mtianeti","code":"MM"},{"value":"Racha-Lechkhumi and Kvemo Svaneti","code":"RL"},{"value":"Samegrelo-Zemo Svaneti","code":"SZ"},{"value":"Samtskhe-Javakheti","code":"SJ"},{"value":"Senaki Municipality","code":"50"},{"value":"Shida Kartli","code":"SK"},{"value":"Tbilisi","code":"TB"}],"DE":[{"value":"Baden-Württemberg","code":"BW"},{"value":"Bavaria","code":"BY"},{"value":"Berlin","code":"BE"},{"value":"Brandenburg","code":"BB"},{"value":"Bremen","code":"HB"},{"value":"Hamburg","code":"HH"},{"value":"Hessen","code":"HE"},{"value":"Lower Saxony","code":"NI"},{"value":"Mecklenburg-Vorpommern","code":"MV"},{"value":"North Rhine-Westphalia","code":"NW"},{"value":"Rhineland-Palatinate","code":"RP"},{"value":"Saarland","code":"SL"},{"value":"Saxony","code":"SN"},{"value":"Saxony-Anhalt","code":"ST"},{"value":"Schleswig-Holstein","code":"SH"},{"value":"Thuringia","code":"TH"}],"GH":[{"value":"Ahafo","code":"AF"},{"value":"Ashanti","code":"AH"},{"value":"Bono","code":"BO"},{"value":"Bono East","code":"BE"},{"value":"Central","code":"CP"},{"value":"Eastern","code":"EP"},{"value":"Greater Accra","code":"AA"},{"value":"North East","code":"NE"},{"value":"Northern","code":"NP"},{"value":"Oti","code":"OT"},{"value":"Savannah","code":"SV"},{"value":"Upper East","code":"UE"},{"value":"Upper West","code":"UW"},{"value":"Volta","code":"TV"},{"value":"Western","code":"WP"},{"value":"Western North","code":"WN"}],"GI":[{"value":"Gibraltar","code":"Gibraltar"}],"GR":[{"value":"Achaea Regional Unit","code":"13"},{"value":"Aetolia-Acarnania Regional Unit","code":"01"},{"value":"Arcadia Prefecture","code":"12"},{"value":"Argolis Regional Unit","code":"11"},{"value":"Attica Region","code":"I"},{"value":"Boeotia Regional Unit","code":"03"},{"value":"Central Greece Region","code":"H"},{"value":"Central Macedonia","code":"B"},{"value":"Chania Regional Unit","code":"94"},{"value":"Corfu Prefecture","code":"22"},{"value":"Corinthia Regional Unit","code":"15"},{"value":"Crete Region","code":"M"},{"value":"Drama Regional Unit","code":"52"},{"value":"East Attica Regional Unit","code":"A2"},{"value":"East Macedonia and Thrace","code":"A"},{"value":"Epirus Region","code":"D"},{"value":"Euboea","code":"04"},{"value":"Grevena Prefecture","code":"51"},{"value":"Imathia Regional Unit","code":"53"},{"value":"Ioannina Regional Unit","code":"33"},{"value":"Ionian Islands Region","code":"F"},{"value":"Karditsa Regional Unit","code":"41"},{"value":"Kastoria Regional Unit","code":"56"},{"value":"Kefalonia Prefecture","code":"23"},{"value":"Kilkis Regional Unit","code":"57"},{"value":"Kozani Prefecture","code":"58"},{"value":"Laconia","code":"16"},{"value":"Larissa Prefecture","code":"42"},{"value":"Lefkada Regional Unit","code":"24"},{"value":"Pella Regional Unit","code":"59"},{"value":"Peloponnese Region","code":"J"},{"value":"Phthiotis Prefecture","code":"06"},{"value":"Preveza Prefecture","code":"34"},{"value":"Serres Prefecture","code":"62"},{"value":"South Aegean","code":"L"},{"value":"Thessaloniki Regional Unit","code":"54"},{"value":"West Greece Region","code":"G"},{"value":"West Macedonia Region","code":"C"}],"GL":[{"value":"Greenland","code":"Greenland"}],"GD":[{"value":"Carriacou and Petite Martinique","code":"10"},{"value":"Saint Andrew Parish","code":"01"},{"value":"Saint David Parish","code":"02"},{"value":"Saint George Parish","code":"03"},{"value":"Saint John Parish","code":"04"},{"value":"Saint Mark Parish","code":"05"},{"value":"Saint Patrick Parish","code":"06"}],"GP":[{"value":"Guadeloupe","code":"Guadeloupe"}],"GU":[{"value":"Agana Heights","code":"Agana Heights"},{"value":"Asan-Maina","code":"Asan-Maina"},{"value":"Barrigada","code":"Barrigada"},{"value":"Chalan Pago-Ordot","code":"Chalan Pago-Ordot"},{"value":"Dededo","code":"Dededo"},{"value":"Hågat","code":"Hågat"},{"value":"Hagåtña","code":"Hagåtña"},{"value":"Inarajan (Inalåhan)","code":"Inarajan (Inalåhan)"},{"value":"Mangilao","code":"Mangilao"},{"value":"Merizo (Malesso)","code":"Merizo (Malesso)"},{"value":"Mongmong-Toto-Maite","code":"Mongmong-Toto-Maite"},{"value":"Piti","code":"Piti"},{"value":"Santa Rita (Sånta Rita-Sumai)","code":"Santa Rita (Sånta Rita-Sumai)"},{"value":"Sinajana","code":"Sinajana"},{"value":"Talofofo (Talo'fo'fo)","code":"Talofofo (Talo'fo'fo)"},{"value":"Tamuning","code":"Tamuning"},{"value":"Umatac (Humåtak)","code":"Umatac (Humåtak)"},{"value":"Yigo","code":"Yigo"},{"value":"Yona","code":"Yona"}],"GT":[{"value":"Alta Verapaz ","code":"16"},{"value":"Baja Verapaz ","code":"15"},{"value":"Chimaltenango ","code":"04"},{"value":"Chiquimula ","code":"20"},{"value":"El Progreso ","code":"02"},{"value":"Escuintla ","code":"05"},{"value":"Guatemala ","code":"01"},{"value":"Huehuetenango ","code":"13"},{"value":"Izabal ","code":"18"},{"value":"Jalapa ","code":"21"},{"value":"Jutiapa ","code":"22"},{"value":"Petén ","code":"17"},{"value":"Quetzaltenango ","code":"09"},{"value":"Quiché ","code":"14"},{"value":"Retalhuleu ","code":"11"},{"value":"Sacatepéquez ","code":"03"},{"value":"San Marcos ","code":"12"},{"value":"Santa Rosa ","code":"06"},{"value":"Sololá ","code":"07"},{"value":"Suchitepéquez ","code":"10"},{"value":"Totonicapán ","code":"08"},{"value":"Zacapa","code":"19"}],"GG":[{"value":"Guernsey and Alderney","code":"Guernsey and Alderney"}],"GN":[{"value":"Beyla Prefecture","code":"BE"},{"value":"Boffa Prefecture","code":"BF"},{"value":"Boké Prefecture","code":"BK"},{"value":"Boké Region","code":"B"},{"value":"Conakry","code":"C"},{"value":"Coyah Prefecture","code":"CO"},{"value":"Dabola Prefecture","code":"DB"},{"value":"Dalaba Prefecture","code":"DL"},{"value":"Dinguiraye Prefecture","code":"DI"},{"value":"Dubréka Prefecture","code":"DU"},{"value":"Faranah Prefecture","code":"FA"},{"value":"Forécariah Prefecture","code":"FO"},{"value":"Fria Prefecture","code":"FR"},{"value":"Gaoual Prefecture","code":"GA"},{"value":"Guéckédou Prefecture","code":"GU"},{"value":"Kankan Prefecture","code":"KA"},{"value":"Kankan Region","code":"K"},{"value":"Kérouané Prefecture","code":"KE"},{"value":"Kindia Prefecture","code":"KD"},{"value":"Kindia Region","code":"D"},{"value":"Kissidougou Prefecture","code":"KS"},{"value":"Koubia Prefecture","code":"KB"},{"value":"Koundara Prefecture","code":"KN"},{"value":"Kouroussa Prefecture","code":"KO"},{"value":"Labé Prefecture","code":"LA"},{"value":"Labé Region","code":"L"},{"value":"Lélouma Prefecture","code":"LE"},{"value":"Lola Prefecture","code":"LO"},{"value":"Macenta Prefecture","code":"MC"},{"value":"Mali Prefecture","code":"ML"},{"value":"Mamou Prefecture","code":"MM"},{"value":"Mamou Region","code":"M"},{"value":"Mandiana Prefecture","code":"MD"},{"value":"Nzérékoré Prefecture","code":"NZ"},{"value":"Nzérékoré Region","code":"N"},{"value":"Pita Prefecture","code":"PI"},{"value":"Siguiri Prefecture","code":"SI"},{"value":"Télimélé Prefecture","code":"TE"},{"value":"Tougué Prefecture","code":"TO"},{"value":"Yomou Prefecture","code":"YO"}],"GW":[{"value":"Bafatá","code":"BA"},{"value":"Biombo Region","code":"BM"},{"value":"Bolama Region","code":"BL"},{"value":"Cacheu Region","code":"CA"},{"value":"Gabú Region","code":"GA"},{"value":"Leste Province","code":"L"},{"value":"Norte Province","code":"N"},{"value":"Oio Region","code":"OI"},{"value":"Quinara Region","code":"QU"},{"value":"Sul Province","code":"S"},{"value":"Tombali Region","code":"TO"}],"GY":[{"value":"Barima-Waini","code":"BA"},{"value":"Cuyuni-Mazaruni","code":"CU"},{"value":"Demerara-Mahaica","code":"DE"},{"value":"East Berbice-Corentyne","code":"EB"},{"value":"Essequibo Islands-West Demerara","code":"ES"},{"value":"Mahaica-Berbice","code":"MA"},{"value":"Pomeroon-Supenaam","code":"PM"},{"value":"Potaro-Siparuni","code":"PT"},{"value":"Upper Demerara-Berbice","code":"UD"},{"value":"Upper Takutu-Upper Essequibo","code":"UT"}],"HT":[{"value":"Artibonite","code":"AR"},{"value":"Centre","code":"CE"},{"value":"Grand'Anse","code":"GA"},{"value":"Nippes","code":"NI"},{"value":"Nord","code":"ND"},{"value":"Nord-Est","code":"NE"},{"value":"Nord-Ouest","code":"NO"},{"value":"Ouest","code":"OU"},{"value":"Sud","code":"SD"},{"value":"Sud-Est","code":"SE"}],"HM":[{"value":"Heard Island and McDonald Islands","code":"Heard Island and McDonald Islands"}],"HN":[{"value":"Atlántida Department","code":"AT"},{"value":"Bay Islands Department","code":"IB"},{"value":"Choluteca Department","code":"CH"},{"value":"Colón Department","code":"CL"},{"value":"Comayagua Department","code":"CM"},{"value":"Copán Department","code":"CP"},{"value":"Cortés Department","code":"CR"},{"value":"El Paraíso Department","code":"EP"},{"value":"Francisco Morazán Department","code":"FM"},{"value":"Gracias a Dios Department","code":"GD"},{"value":"Intibucá Department","code":"IN"},{"value":"La Paz Department","code":"LP"},{"value":"Lempira Department","code":"LE"},{"value":"Ocotepeque Department","code":"OC"},{"value":"Olancho Department","code":"OL"},{"value":"Santa Bárbara Department","code":"SB"},{"value":"Valle Department","code":"VA"},{"value":"Yoro Department","code":"YO"}],"HK":[{"value":"Central and Western","code":"HCW"},{"value":"Eastern","code":"HEA"},{"value":"Islands","code":"NIS"},{"value":"Kowloon City","code":"KKC"},{"value":"Kwai Tsing","code":"NKT"},{"value":"Kwun Tong","code":"KKT"},{"value":"North","code":"NNO"},{"value":"Sai Kung","code":"NSK"},{"value":"Sha Tin","code":"NST"},{"value":"Sham Shui Po","code":"KSS"},{"value":"Southern","code":"HSO"},{"value":"Tai Po","code":"NTP"},{"value":"Tsuen Wan","code":"NTW"},{"value":"Tuen Mun","code":"NTM"},{"value":"Wan Chai","code":"HWC"},{"value":"Wong Tai Sin","code":"KWT"},{"value":"Yau Tsim Mong","code":"KYT"},{"value":"Yuen Long","code":"NYL"}],"HU":[{"value":"Bács-Kiskun","code":"BK"},{"value":"Baranya","code":"BA"},{"value":"Békés","code":"BE"},{"value":"Békéscsaba","code":"BC"},{"value":"Borsod-Abaúj-Zemplén","code":"BZ"},{"value":"Budapest","code":"BU"},{"value":"Csongrád County","code":"CS"},{"value":"Debrecen","code":"DE"},{"value":"Dunaújváros","code":"DU"},{"value":"Eger","code":"EG"},{"value":"Érd","code":"ER"},{"value":"Fejér County","code":"FE"},{"value":"Győr","code":"GY"},{"value":"Győr-Moson-Sopron County","code":"GS"},{"value":"Hajdú-Bihar County","code":"HB"},{"value":"Heves County","code":"HE"},{"value":"Hódmezővásárhely","code":"HV"},{"value":"Jász-Nagykun-Szolnok County","code":"JN"},{"value":"Kaposvár","code":"KV"},{"value":"Kecskemét","code":"KM"},{"value":"Komárom-Esztergom","code":"KE"},{"value":"Miskolc","code":"MI"},{"value":"Nagykanizsa","code":"NK"},{"value":"Nógrád County","code":"NO"},{"value":"Nyíregyháza","code":"NY"},{"value":"Pécs","code":"PS"},{"value":"Pest County","code":"PE"},{"value":"Salgótarján","code":"ST"},{"value":"Somogy County","code":"SO"},{"value":"Sopron","code":"SN"},{"value":"Szabolcs-Szatmár-Bereg County","code":"SZ"},{"value":"Szeged","code":"SD"},{"value":"Székesfehérvár","code":"SF"},{"value":"Szekszárd","code":"SS"},{"value":"Szolnok","code":"SK"},{"value":"Szombathely","code":"SH"},{"value":"Tatabánya","code":"TB"},{"value":"Tolna County","code":"TO"},{"value":"Vas County","code":"VA"},{"value":"Veszprém","code":"VM"},{"value":"Veszprém County","code":"VE"},{"value":"Zala County","code":"ZA"},{"value":"Zalaegerszeg","code":"ZE"}],"IS":[{"value":"Capital Region","code":"1"},{"value":"Eastern Region","code":"7"},{"value":"Northeastern Region","code":"6"},{"value":"Northwestern Region","code":"5"},{"value":"Southern Peninsula Region","code":"2"},{"value":"Southern Region","code":"8"},{"value":"Western Region","code":"3"},{"value":"Westfjords","code":"4"}],"IN":[{"value":"Andaman and Nicobar Islands","code":"AN"},{"value":"Andhra Pradesh","code":"AP"},{"value":"Arunachal Pradesh","code":"AR"},{"value":"Assam","code":"AS"},{"value":"Bihar","code":"BR"},{"value":"Chandigarh","code":"CH"},{"value":"Chhattisgarh","code":"CT"},{"value":"Dadra and Nagar Haveli and Daman and Diu","code":"DH"},{"value":"Delhi","code":"DL"},{"value":"Goa","code":"GA"},{"value":"Gujarat","code":"GJ"},{"value":"Haryana","code":"HR"},{"value":"Himachal Pradesh","code":"HP"},{"value":"Jammu and Kashmir","code":"JK"},{"value":"Jharkhand","code":"JH"},{"value":"Karnataka","code":"KA"},{"value":"Kerala","code":"KL"},{"value":"Ladakh","code":"LA"},{"value":"Lakshadweep","code":"LD"},{"value":"Madhya Pradesh","code":"MP"},{"value":"Maharashtra","code":"MH"},{"value":"Manipur","code":"MN"},{"value":"Meghalaya","code":"ML"},{"value":"Mizoram","code":"MZ"},{"value":"Nagaland","code":"NL"},{"value":"Odisha","code":"OR"},{"value":"Puducherry","code":"PY"},{"value":"Punjab","code":"PB"},{"value":"Rajasthan","code":"RJ"},{"value":"Sikkim","code":"SK"},{"value":"Tamil Nadu","code":"TN"},{"value":"Telangana","code":"TG"},{"value":"Tripura","code":"TR"},{"value":"Uttar Pradesh","code":"UP"},{"value":"Uttarakhand","code":"UK"},{"value":"West Bengal","code":"WB"}],"ID":[{"value":"Aceh","code":"AC"},{"value":"Bali","code":"BA"},{"value":"Banten","code":"BT"},{"value":"Bengkulu","code":"BE"},{"value":"DI Yogyakarta","code":"YO"},{"value":"DKI Jakarta","code":"JK"},{"value":"Gorontalo","code":"GO"},{"value":"Jambi","code":"JA"},{"value":"Jawa Barat","code":"JB"},{"value":"Jawa Tengah","code":"JT"},{"value":"Jawa Timur","code":"JI"},{"value":"Kalimantan Barat","code":"KB"},{"value":"Kalimantan Selatan","code":"KS"},{"value":"Kalimantan Tengah","code":"KT"},{"value":"Kalimantan Timur","code":"KI"},{"value":"Kalimantan Utara","code":"KU"},{"value":"Kepulauan Bangka Belitung","code":"BB"},{"value":"Kepulauan Riau","code":"KR"},{"value":"Lampung","code":"LA"},{"value":"Maluku","code":"MA"},{"value":"Maluku Utara","code":"MU"},{"value":"Nusa Tenggara Barat","code":"NB"},{"value":"Nusa Tenggara Timur","code":"NT"},{"value":"Papua","code":"PA"},{"value":"Papua Barat","code":"PB"},{"value":"Papua Barat Daya","code":"PD"},{"value":"Papua Pegunungan","code":"PE"},{"value":"Papua Selatan","code":"PS"},{"value":"Papua Tengah","code":"PT"},{"value":"Riau","code":"RI"},{"value":"Sulawesi Barat","code":"SR"},{"value":"Sulawesi Selatan","code":"SN"},{"value":"Sulawesi Tengah","code":"ST"},{"value":"Sulawesi Tenggara","code":"SG"},{"value":"Sulawesi Utara","code":"SA"},{"value":"Sumatera Barat","code":"SB"},{"value":"Sumatera Selatan","code":"SS"},{"value":"Sumatera Utara","code":"SU"}],"IR":[{"value":"Alborz","code":"30"},{"value":"Ardabil","code":"24"},{"value":"Bushehr","code":"18"},{"value":"Chaharmahal and Bakhtiari","code":"14"},{"value":"East Azerbaijan","code":"03"},{"value":"Fars","code":"07"},{"value":"Gilan","code":"01"},{"value":"Golestan","code":"27"},{"value":"Hamadan","code":"13"},{"value":"Hormozgan","code":"22"},{"value":"Ilam","code":"16"},{"value":"Isfahan","code":"10"},{"value":"Kerman","code":"08"},{"value":"Kermanshah","code":"05"},{"value":"Khuzestan","code":"06"},{"value":"Kohgiluyeh and Boyer-Ahmad","code":"17"},{"value":"Kurdistan","code":"12"},{"value":"Lorestan","code":"15"},{"value":"Markazi","code":"00"},{"value":"Mazandaran","code":"02"},{"value":"North Khorasan","code":"28"},{"value":"Qazvin","code":"26"},{"value":"Qom","code":"25"},{"value":"Razavi Khorasan","code":"09"},{"value":"Semnan","code":"20"},{"value":"Sistan and Baluchestan","code":"11"},{"value":"South Khorasan","code":"29"},{"value":"Tehran","code":"23"},{"value":"West Azarbaijan","code":"04"},{"value":"Yazd","code":"21"},{"value":"Zanjan","code":"19"}],"IQ":[{"value":"Al Anbar","code":"AN"},{"value":"Al Muthanna","code":"MU"},{"value":"Al-Qādisiyyah","code":"QA"},{"value":"Babylon","code":"BB"},{"value":"Baghdad","code":"BG"},{"value":"Basra","code":"BA"},{"value":"Dhi Qar","code":"DQ"},{"value":"Diyala","code":"DI"},{"value":"Dohuk","code":"DA"},{"value":"Erbil","code":"AR"},{"value":"Karbala","code":"KA"},{"value":"Kirkuk","code":"KI"},{"value":"Maysan","code":"MA"},{"value":"Najaf","code":"NA"},{"value":"Nineveh","code":"NI"},{"value":"Saladin","code":"SD"},{"value":"Sulaymaniyah","code":"SU"},{"value":"Wasit","code":"WA"}],"IE":[{"value":"Carlow","code":"CW"},{"value":"Cavan","code":"CN"},{"value":"Clare","code":"CE"},{"value":"Connacht","code":"C"},{"value":"Cork","code":"CO"},{"value":"Donegal","code":"DL"},{"value":"Dublin","code":"D"},{"value":"Galway","code":"G"},{"value":"Kerry","code":"KY"},{"value":"Kildare","code":"KE"},{"value":"Kilkenny","code":"KK"},{"value":"Laois","code":"LS"},{"value":"Leinster","code":"L"},{"value":"Limerick","code":"LK"},{"value":"Longford","code":"LD"},{"value":"Louth","code":"LH"},{"value":"Mayo","code":"MO"},{"value":"Meath","code":"MH"},{"value":"Monaghan","code":"MN"},{"value":"Munster","code":"M"},{"value":"Offaly","code":"OY"},{"value":"Roscommon","code":"RN"},{"value":"Sligo","code":"SO"},{"value":"Tipperary","code":"TA"},{"value":"Ulster","code":"U"},{"value":"Waterford","code":"WD"},{"value":"Westmeath","code":"WH"},{"value":"Wexford","code":"WX"},{"value":"Wicklow","code":"WW"}],"IL":[{"value":"Central District","code":"M"},{"value":"Haifa District","code":"HA"},{"value":"Jerusalem District","code":"JM"},{"value":"Northern District","code":"Z"},{"value":"Southern District","code":"D"},{"value":"Tel Aviv District","code":"TA"}],"IT":[{"value":"Abruzzo","code":"65"},{"value":"Agrigento","code":"AG"},{"value":"Alessandria","code":"AL"},{"value":"Ancona","code":"AN"},{"value":"Aosta Valley","code":"23"},{"value":"Apulia","code":"75"},{"value":"Ascoli Piceno","code":"AP"},{"value":"Asti","code":"AT"},{"value":"Avellino","code":"AV"},{"value":"Barletta-Andria-Trani","code":"BT"},{"value":"Basilicata","code":"77"},{"value":"Belluno","code":"BL"},{"value":"Benevento","code":"BN"},{"value":"Bergamo","code":"BG"},{"value":"Biella","code":"BI"},{"value":"Brescia","code":"BS"},{"value":"Brindisi","code":"BR"},{"value":"Calabria","code":"78"},{"value":"Caltanissetta","code":"CL"},{"value":"Campania","code":"72"},{"value":"Campobasso","code":"CB"},{"value":"Caserta","code":"CE"},{"value":"Catanzaro","code":"CZ"},{"value":"Chieti","code":"CH"},{"value":"Como","code":"CO"},{"value":"Cosenza","code":"CS"},{"value":"Cremona","code":"CR"},{"value":"Crotone","code":"KR"},{"value":"Cuneo","code":"CN"},{"value":"Emilia-Romagna","code":"45"},{"value":"Enna","code":"EN"},{"value":"Fermo","code":"FM"},{"value":"Ferrara","code":"FE"},{"value":"Foggia","code":"FG"},{"value":"Forlì-Cesena","code":"FC"},{"value":"Friuli–Venezia Giulia","code":"36"},{"value":"Frosinone","code":"FR"},{"value":"Gorizia","code":"GO"},{"value":"Grosseto","code":"GR"},{"value":"Imperia","code":"IM"},{"value":"Isernia","code":"IS"},{"value":"L'Aquila","code":"AQ"},{"value":"La Spezia","code":"SP"},{"value":"Latina","code":"LT"},{"value":"Lazio","code":"62"},{"value":"Lecce","code":"LE"},{"value":"Lecco","code":"LC"},{"value":"Liguria","code":"42"},{"value":"Livorno","code":"LI"},{"value":"Lodi","code":"LO"},{"value":"Lombardy","code":"25"},{"value":"Lucca","code":"LU"},{"value":"Macerata","code":"MC"},{"value":"Mantua","code":"MN"},{"value":"Marche","code":"57"},{"value":"Massa and Carrara","code":"MS"},{"value":"Matera","code":"MT"},{"value":"Medio Campidano","code":"VS"},{"value":"Modena","code":"MO"},{"value":"Molise","code":"67"},{"value":"Monza and Brianza","code":"MB"},{"value":"Novara","code":"NO"},{"value":"Nuoro","code":"NU"},{"value":"Oristano","code":"OR"},{"value":"Padua","code":"PD"},{"value":"Palermo","code":"PA"},{"value":"Parma","code":"PR"},{"value":"Pavia","code":"PV"},{"value":"Perugia","code":"PG"},{"value":"Pesaro and Urbino","code":"PU"},{"value":"Pescara","code":"PE"},{"value":"Piacenza","code":"PC"},{"value":"Piedmont","code":"21"},{"value":"Pisa","code":"PI"},{"value":"Pistoia","code":"PT"},{"value":"Pordenone","code":"PN"},{"value":"Potenza","code":"PZ"},{"value":"Prato","code":"PO"},{"value":"Ragusa","code":"RG"},{"value":"Ravenna","code":"RA"},{"value":"Reggio Emilia","code":"RE"},{"value":"Rieti","code":"RI"},{"value":"Rimini","code":"RN"},{"value":"Rovigo","code":"RO"},{"value":"Salerno","code":"SA"},{"value":"Sardinia","code":"88"},{"value":"Sassari","code":"SS"},{"value":"Savona","code":"SV"},{"value":"Sicily","code":"82"},{"value":"Siena","code":"SI"},{"value":"Siracusa","code":"SR"},{"value":"Sondrio","code":"SO"},{"value":"South Sardinia","code":"SU"},{"value":"Taranto","code":"TA"},{"value":"Teramo","code":"TE"},{"value":"Terni","code":"TR"},{"value":"Trapani","code":"TP"},{"value":"Trentino-South Tyrol","code":"32"},{"value":"Treviso","code":"TV"},{"value":"Trieste","code":"TS"},{"value":"Tuscany","code":"52"},{"value":"Udine","code":"UD"},{"value":"Umbria","code":"55"},{"value":"Varese","code":"VA"},{"value":"Veneto","code":"34"},{"value":"Verbano-Cusio-Ossola","code":"VB"},{"value":"Vercelli","code":"VC"},{"value":"Verona","code":"VR"},{"value":"Vibo Valentia","code":"VV"},{"value":"Vicenza","code":"VI"},{"value":"Viterbo","code":"VT"}],"JM":[{"value":"Clarendon Parish","code":"13"},{"value":"Hanover Parish","code":"09"},{"value":"Kingston Parish","code":"01"},{"value":"Manchester Parish","code":"12"},{"value":"Portland Parish","code":"04"},{"value":"Saint Andrew","code":"02"},{"value":"Saint Ann Parish","code":"06"},{"value":"Saint Catherine Parish","code":"14"},{"value":"Saint Elizabeth Parish","code":"11"},{"value":"Saint James Parish","code":"08"},{"value":"Saint Mary Parish","code":"05"},{"value":"Saint Thomas Parish","code":"03"},{"value":"Trelawny Parish","code":"07"},{"value":"Westmoreland Parish","code":"10"}],"JP":[{"value":"Aichi Prefecture","code":"23"},{"value":"Akita Prefecture","code":"05"},{"value":"Aomori Prefecture","code":"02"},{"value":"Chiba Prefecture","code":"12"},{"value":"Ehime Prefecture","code":"38"},{"value":"Fukui Prefecture","code":"18"},{"value":"Fukuoka Prefecture","code":"40"},{"value":"Fukushima Prefecture","code":"07"},{"value":"Gifu Prefecture","code":"21"},{"value":"Gunma Prefecture","code":"10"},{"value":"Hiroshima Prefecture","code":"34"},{"value":"Hokkaidō Prefecture","code":"01"},{"value":"Hyōgo Prefecture","code":"28"},{"value":"Ibaraki Prefecture","code":"08"},{"value":"Ishikawa Prefecture","code":"17"},{"value":"Iwate Prefecture","code":"03"},{"value":"Kagawa Prefecture","code":"37"},{"value":"Kagoshima Prefecture","code":"46"},{"value":"Kanagawa Prefecture","code":"14"},{"value":"Kōchi Prefecture","code":"39"},{"value":"Kumamoto Prefecture","code":"43"},{"value":"Kyōto Prefecture","code":"26"},{"value":"Mie Prefecture","code":"24"},{"value":"Miyagi Prefecture","code":"04"},{"value":"Miyazaki Prefecture","code":"45"},{"value":"Nagano Prefecture","code":"20"},{"value":"Nagasaki Prefecture","code":"42"},{"value":"Nara Prefecture","code":"29"},{"value":"Niigata Prefecture","code":"15"},{"value":"Ōita Prefecture","code":"44"},{"value":"Okayama Prefecture","code":"33"},{"value":"Okinawa Prefecture","code":"47"},{"value":"Ōsaka Prefecture","code":"27"},{"value":"Saga Prefecture","code":"41"},{"value":"Saitama Prefecture","code":"11"},{"value":"Shiga Prefecture","code":"25"},{"value":"Shimane Prefecture","code":"32"},{"value":"Shizuoka Prefecture","code":"22"},{"value":"Tochigi Prefecture","code":"09"},{"value":"Tokushima Prefecture","code":"36"},{"value":"Tokyo","code":"13"},{"value":"Tottori Prefecture","code":"31"},{"value":"Toyama Prefecture","code":"16"},{"value":"Wakayama Prefecture","code":"30"},{"value":"Yamagata Prefecture","code":"06"},{"value":"Yamaguchi Prefecture","code":"35"},{"value":"Yamanashi Prefecture","code":"19"}],"JE":[{"value":"Jersey","code":"Jersey"}],"JO":[{"value":"Ajloun","code":"AJ"},{"value":"Amman","code":"AM"},{"value":"Aqaba","code":"AQ"},{"value":"Balqa","code":"BA"},{"value":"Irbid","code":"IR"},{"value":"Jerash","code":"JA"},{"value":"Karak","code":"KA"},{"value":"Ma'an","code":"MN"},{"value":"Madaba","code":"MD"},{"value":"Mafraq","code":"MA"},{"value":"Tafilah","code":"AT"},{"value":"Zarqa","code":"AZ"}],"KZ":[{"value":"Akmola Region","code":"AKM"},{"value":"Aktobe Region","code":"AKT"},{"value":"Almaty","code":"ALA"},{"value":"Almaty Region","code":"ALM"},{"value":"Atyrau Region","code":"ATY"},{"value":"Baikonur","code":"BAY"},{"value":"East Kazakhstan Region","code":"VOS"},{"value":"Jambyl Region","code":"ZHA"},{"value":"Karaganda Region","code":"KAR"},{"value":"Kostanay Region","code":"KUS"},{"value":"Kyzylorda Region","code":"KZY"},{"value":"Mangystau Region","code":"MAN"},{"value":"North Kazakhstan Region","code":"SEV"},{"value":"Nur-Sultan","code":"AST"},{"value":"Pavlodar Region","code":"PAV"},{"value":"Turkestan Region","code":"YUZ"},{"value":"West Kazakhstan Province","code":"ZAP"}],"KE":[{"value":"Baringo","code":"01"},{"value":"Bomet","code":"02"},{"value":"Bungoma","code":"03"},{"value":"Busia","code":"04"},{"value":"Elgeyo-Marakwet","code":"05"},{"value":"Embu","code":"06"},{"value":"Garissa","code":"07"},{"value":"Homa Bay","code":"08"},{"value":"Isiolo","code":"09"},{"value":"Kajiado","code":"10"},{"value":"Kakamega","code":"11"},{"value":"Kericho","code":"12"},{"value":"Kiambu","code":"13"},{"value":"Kilifi","code":"14"},{"value":"Kirinyaga","code":"15"},{"value":"Kisii","code":"16"},{"value":"Kisumu","code":"17"},{"value":"Kitui","code":"18"},{"value":"Kwale","code":"19"},{"value":"Laikipia","code":"20"},{"value":"Lamu","code":"21"},{"value":"Machakos","code":"22"},{"value":"Makueni","code":"23"},{"value":"Mandera","code":"24"},{"value":"Marsabit","code":"25"},{"value":"Meru","code":"26"},{"value":"Migori","code":"27"},{"value":"Mombasa","code":"28"},{"value":"Murang'a","code":"29"},{"value":"Nairobi City","code":"30"},{"value":"Nakuru","code":"31"},{"value":"Nandi","code":"32"},{"value":"Narok","code":"33"},{"value":"Nyamira","code":"34"},{"value":"Nyandarua","code":"35"},{"value":"Nyeri","code":"36"},{"value":"Samburu","code":"37"},{"value":"Siaya","code":"38"},{"value":"Taita–Taveta","code":"39"},{"value":"Tana River","code":"40"},{"value":"Tharaka-Nithi","code":"41"},{"value":"Trans Nzoia","code":"42"},{"value":"Turkana","code":"43"},{"value":"Uasin Gishu","code":"44"},{"value":"Vihiga","code":"45"},{"value":"Wajir","code":"46"},{"value":"West Pokot","code":"47"}],"KI":[{"value":"Gilbert Islands","code":"G"},{"value":"Line Islands","code":"L"},{"value":"Phoenix Islands","code":"P"}],"XK":[{"value":"Đakovica District (Gjakove)","code":"XDG"},{"value":"Gjilan District","code":"XGJ"},{"value":"Kosovska Mitrovica District","code":"XKM"},{"value":"Peć District","code":"XPE"},{"value":"Pristina (Priştine)","code":"XPI"},{"value":"Prizren District","code":"XPR"},{"value":"Uroševac District (Ferizaj)","code":"XUF"}],"KW":[{"value":"Al Ahmadi","code":"AH"},{"value":"Al Farwaniyah","code":"FA"},{"value":"Al Jahra","code":"JA"},{"value":"Capital","code":"KU"},{"value":"Hawalli","code":"HA"},{"value":"Mubarak Al-Kabeer","code":"MU"}],"KG":[{"value":"Batken Region","code":"B"},{"value":"Bishkek","code":"GB"},{"value":"Chuy Region","code":"C"},{"value":"Issyk-Kul Region","code":"Y"},{"value":"Jalal-Abad Region","code":"J"},{"value":"Naryn Region","code":"N"},{"value":"Osh","code":"GO"},{"value":"Osh Region","code":"O"},{"value":"Talas Region","code":"T"}],"LA":[{"value":"Attapeu Province","code":"AT"},{"value":"Bokeo Province","code":"BK"},{"value":"Bolikhamsai Province","code":"BL"},{"value":"Champasak Province","code":"CH"},{"value":"Houaphanh Province","code":"HO"},{"value":"Khammouane Province","code":"KH"},{"value":"Luang Namtha Province","code":"LM"},{"value":"Luang Prabang Province","code":"LP"},{"value":"Oudomxay Province","code":"OU"},{"value":"Phongsaly Province","code":"PH"},{"value":"Sainyabuli Province","code":"XA"},{"value":"Salavan Province","code":"SL"},{"value":"Savannakhet Province","code":"SV"},{"value":"Sekong Province","code":"XE"},{"value":"Vientiane Prefecture","code":"VT"},{"value":"Vientiane Province","code":"VI"},{"value":"Xaisomboun","code":"XN"},{"value":"Xaisomboun Province","code":"XS"},{"value":"Xiangkhouang Province","code":"XI"}],"LV":[{"value":"Aglona Municipality","code":"001"},{"value":"Aizkraukle Municipality","code":"002"},{"value":"Aizpute Municipality","code":"003"},{"value":"Aknīste Municipality","code":"004"},{"value":"Aloja Municipality","code":"005"},{"value":"Alsunga Municipality","code":"006"},{"value":"Alūksne Municipality","code":"007"},{"value":"Amata Municipality","code":"008"},{"value":"Ape Municipality","code":"009"},{"value":"Auce Municipality","code":"010"},{"value":"Babīte Municipality","code":"012"},{"value":"Baldone Municipality","code":"013"},{"value":"Baltinava Municipality","code":"014"},{"value":"Balvi Municipality","code":"015"},{"value":"Bauska Municipality","code":"016"},{"value":"Beverīna Municipality","code":"017"},{"value":"Brocēni Municipality","code":"018"},{"value":"Burtnieki Municipality","code":"019"},{"value":"Carnikava Municipality","code":"020"},{"value":"Cēsis Municipality","code":"022"},{"value":"Cesvaine Municipality","code":"021"},{"value":"Cibla Municipality","code":"023"},{"value":"Dagda Municipality","code":"024"},{"value":"Daugavpils","code":"DGV"},{"value":"Daugavpils Municipality","code":"025"},{"value":"Dobele Municipality","code":"026"},{"value":"Dundaga Municipality","code":"027"},{"value":"Durbe Municipality","code":"028"},{"value":"Engure Municipality","code":"029"},{"value":"Ērgļi Municipality","code":"030"},{"value":"Garkalne Municipality","code":"031"},{"value":"Grobiņa Municipality","code":"032"},{"value":"Gulbene Municipality","code":"033"},{"value":"Iecava Municipality","code":"034"},{"value":"Ikšķile Municipality","code":"035"},{"value":"Ilūkste Municipality","code":"036"},{"value":"Inčukalns Municipality","code":"037"},{"value":"Jaunjelgava Municipality","code":"038"},{"value":"Jaunpiebalga Municipality","code":"039"},{"value":"Jaunpils Municipality","code":"040"},{"value":"Jēkabpils","code":"JKB"},{"value":"Jēkabpils Municipality","code":"042"},{"value":"Jelgava","code":"JEL"},{"value":"Jelgava Municipality","code":"041"},{"value":"Jūrmala","code":"JUR"},{"value":"Kandava Municipality","code":"043"},{"value":"Kārsava Municipality","code":"044"},{"value":"Ķegums Municipality","code":"051"},{"value":"Ķekava Municipality","code":"052"},{"value":"Kocēni Municipality","code":"045"},{"value":"Koknese Municipality","code":"046"},{"value":"Krāslava Municipality","code":"047"},{"value":"Krimulda Municipality","code":"048"},{"value":"Krustpils Municipality","code":"049"},{"value":"Kuldīga Municipality","code":"050"},{"value":"Lielvārde Municipality","code":"053"},{"value":"Liepāja","code":"LPX"},{"value":"Līgatne Municipality","code":"055"},{"value":"Limbaži Municipality","code":"054"},{"value":"Līvāni Municipality","code":"056"},{"value":"Lubāna Municipality","code":"057"},{"value":"Ludza Municipality","code":"058"},{"value":"Madona Municipality","code":"059"},{"value":"Mālpils Municipality","code":"061"},{"value":"Mārupe Municipality","code":"062"},{"value":"Mazsalaca Municipality","code":"060"},{"value":"Mērsrags Municipality","code":"063"},{"value":"Naukšēni Municipality","code":"064"},{"value":"Nereta Municipality","code":"065"},{"value":"Nīca Municipality","code":"066"},{"value":"Ogre Municipality","code":"067"},{"value":"Olaine Municipality","code":"068"},{"value":"Ozolnieki Municipality","code":"069"},{"value":"Pārgauja Municipality","code":"070"},{"value":"Pāvilosta Municipality","code":"071"},{"value":"Pļaviņas Municipality","code":"072"},{"value":"Preiļi Municipality","code":"073"},{"value":"Priekule Municipality","code":"074"},{"value":"Priekuļi Municipality","code":"075"},{"value":"Rauna Municipality","code":"076"},{"value":"Rēzekne","code":"REZ"},{"value":"Rēzekne Municipality","code":"077"},{"value":"Riebiņi Municipality","code":"078"},{"value":"Riga","code":"RIX"},{"value":"Roja Municipality","code":"079"},{"value":"Ropaži Municipality","code":"080"},{"value":"Rucava Municipality","code":"081"},{"value":"Rugāji Municipality","code":"082"},{"value":"Rūjiena Municipality","code":"084"},{"value":"Rundāle Municipality","code":"083"},{"value":"Sala Municipality","code":"085"},{"value":"Salacgrīva Municipality","code":"086"},{"value":"Salaspils Municipality","code":"087"},{"value":"Saldus Municipality","code":"088"},{"value":"Saulkrasti Municipality","code":"089"},{"value":"Sēja Municipality","code":"090"},{"value":"Sigulda Municipality","code":"091"},{"value":"Skrīveri Municipality","code":"092"},{"value":"Skrunda Municipality","code":"093"},{"value":"Smiltene Municipality","code":"094"},{"value":"Stopiņi Municipality","code":"095"},{"value":"Strenči Municipality","code":"096"},{"value":"Talsi Municipality","code":"097"},{"value":"Tērvete Municipality","code":"098"},{"value":"Tukums Municipality","code":"099"},{"value":"Vaiņode Municipality","code":"100"},{"value":"Valka Municipality","code":"101"},{"value":"Valmiera","code":"VMR"},{"value":"Varakļāni Municipality","code":"102"},{"value":"Vārkava Municipality","code":"103"},{"value":"Vecpiebalga Municipality","code":"104"},{"value":"Vecumnieki Municipality","code":"105"},{"value":"Ventspils","code":"VEN"},{"value":"Ventspils Municipality","code":"106"},{"value":"Viesīte Municipality","code":"107"},{"value":"Viļaka Municipality","code":"108"},{"value":"Viļāni Municipality","code":"109"},{"value":"Zilupe Municipality","code":"110"}],"LB":[{"value":"Akkar","code":"AK"},{"value":"Baalbek-Hermel","code":"BH"},{"value":"Beirut","code":"BA"},{"value":"Beqaa","code":"BI"},{"value":"Mount Lebanon","code":"JL"},{"value":"Nabatieh","code":"NA"},{"value":"North","code":"AS"},{"value":"South","code":"JA"}],"LS":[{"value":"Berea District","code":"D"},{"value":"Butha-Buthe District","code":"B"},{"value":"Leribe District","code":"C"},{"value":"Mafeteng District","code":"E"},{"value":"Maseru District","code":"A"},{"value":"Mohale's Hoek District","code":"F"},{"value":"Mokhotlong District","code":"J"},{"value":"Qacha's Nek District","code":"H"},{"value":"Quthing District","code":"G"},{"value":"Thaba-Tseka District","code":"K"}],"LR":[{"value":"Bomi County","code":"BM"},{"value":"Bong County","code":"BG"},{"value":"Gbarpolu County","code":"GP"},{"value":"Grand Bassa County","code":"GB"},{"value":"Grand Cape Mount County","code":"CM"},{"value":"Grand Gedeh County","code":"GG"},{"value":"Grand Kru County","code":"GK"},{"value":"Lofa County","code":"LO"},{"value":"Margibi County","code":"MG"},{"value":"Maryland County","code":"MY"},{"value":"Montserrado County","code":"MO"},{"value":"Nimba","code":"NI"},{"value":"River Cess County","code":"RI"},{"value":"River Gee County","code":"RG"},{"value":"Sinoe County","code":"SI"}],"LY":[{"value":"Al Wahat District","code":"WA"},{"value":"Benghazi","code":"BA"},{"value":"Derna District","code":"DR"},{"value":"Ghat District","code":"GT"},{"value":"Jabal al Akhdar","code":"JA"},{"value":"Jabal al Gharbi District","code":"JG"},{"value":"Jafara","code":"JI"},{"value":"Jufra","code":"JU"},{"value":"Kufra District","code":"KF"},{"value":"Marj District","code":"MJ"},{"value":"Misrata District","code":"MI"},{"value":"Murqub","code":"MB"},{"value":"Murzuq District","code":"MQ"},{"value":"Nalut District","code":"NL"},{"value":"Nuqat al Khams","code":"NQ"},{"value":"Sabha District","code":"SB"},{"value":"Sirte District","code":"SR"},{"value":"Tripoli District","code":"TB"},{"value":"Wadi al Hayaa District","code":"WD"},{"value":"Wadi al Shatii District","code":"WS"},{"value":"Zawiya District","code":"ZA"}],"LI":[{"value":"Balzers","code":"01"},{"value":"Eschen","code":"02"},{"value":"Gamprin","code":"03"},{"value":"Mauren","code":"04"},{"value":"Planken","code":"05"},{"value":"Ruggell","code":"06"},{"value":"Schaan","code":"07"},{"value":"Schellenberg","code":"08"},{"value":"Triesen","code":"09"},{"value":"Triesenberg","code":"10"},{"value":"Vaduz","code":"11"}],"LT":[{"value":"Akmenė District Municipality","code":"01"},{"value":"Alytus City Municipality","code":"02"},{"value":"Alytus County","code":"AL"},{"value":"Alytus District Municipality","code":"03"},{"value":"Birštonas Municipality","code":"05"},{"value":"Biržai District Municipality","code":"06"},{"value":"Druskininkai municipality","code":"07"},{"value":"Elektrėnai municipality","code":"08"},{"value":"Ignalina District Municipality","code":"09"},{"value":"Jonava District Municipality","code":"10"},{"value":"Joniškis District Municipality","code":"11"},{"value":"Jurbarkas District Municipality","code":"12"},{"value":"Kaišiadorys District Municipality","code":"13"},{"value":"Kalvarija municipality","code":"14"},{"value":"Kaunas City Municipality","code":"15"},{"value":"Kaunas County","code":"KU"},{"value":"Kaunas District Municipality","code":"16"},{"value":"Kazlų Rūda municipality","code":"17"},{"value":"Kėdainiai District Municipality","code":"18"},{"value":"Kelmė District Municipality","code":"19"},{"value":"Klaipeda City Municipality","code":"20"},{"value":"Klaipėda County","code":"KL"},{"value":"Klaipėda District Municipality","code":"21"},{"value":"Kretinga District Municipality","code":"22"},{"value":"Kupiškis District Municipality","code":"23"},{"value":"Lazdijai District Municipality","code":"24"},{"value":"Marijampolė County","code":"MR"},{"value":"Marijampolė Municipality","code":"25"},{"value":"Mažeikiai District Municipality","code":"26"},{"value":"Molėtai District Municipality","code":"27"},{"value":"Neringa Municipality","code":"28"},{"value":"Pagėgiai municipality","code":"29"},{"value":"Pakruojis District Municipality","code":"30"},{"value":"Palanga City Municipality","code":"31"},{"value":"Panevėžys City Municipality","code":"32"},{"value":"Panevėžys County","code":"PN"},{"value":"Panevėžys District Municipality","code":"33"},{"value":"Pasvalys District Municipality","code":"34"},{"value":"Plungė District Municipality","code":"35"},{"value":"Prienai District Municipality","code":"36"},{"value":"Radviliškis District Municipality","code":"37"},{"value":"Raseiniai District Municipality","code":"38"},{"value":"Rietavas municipality","code":"39"},{"value":"Rokiškis District Municipality","code":"40"},{"value":"Šakiai District Municipality","code":"41"},{"value":"Šalčininkai District Municipality","code":"42"},{"value":"Šiauliai City Municipality","code":"43"},{"value":"Šiauliai County","code":"SA"},{"value":"Šiauliai District Municipality","code":"44"},{"value":"Šilalė District Municipality","code":"45"},{"value":"Šilutė District Municipality","code":"46"},{"value":"Širvintos District Municipality","code":"47"},{"value":"Skuodas District Municipality","code":"48"},{"value":"Švenčionys District Municipality","code":"49"},{"value":"Tauragė County","code":"TA"},{"value":"Tauragė District Municipality","code":"50"},{"value":"Telšiai County","code":"TE"},{"value":"Telšiai District Municipality","code":"51"},{"value":"Trakai District Municipality","code":"52"},{"value":"Ukmergė District Municipality","code":"53"},{"value":"Utena County","code":"UT"},{"value":"Utena District Municipality","code":"54"},{"value":"Varėna District Municipality","code":"55"},{"value":"Vilkaviškis District Municipality","code":"56"},{"value":"Vilnius City Municipality","code":"57"},{"value":"Vilnius County","code":"VL"},{"value":"Vilnius District Municipality","code":"58"},{"value":"Visaginas Municipality","code":"59"},{"value":"Zarasai District Municipality","code":"60"}],"LU":[{"value":"Canton of Capellen","code":"CA"},{"value":"Canton of Clervaux","code":"CL"},{"value":"Canton of Diekirch","code":"DI"},{"value":"Canton of Echternach","code":"EC"},{"value":"Canton of Esch-sur-Alzette","code":"ES"},{"value":"Canton of Grevenmacher","code":"GR"},{"value":"Canton of Luxembourg","code":"LU"},{"value":"Canton of Mersch","code":"ME"},{"value":"Canton of Redange","code":"RD"},{"value":"Canton of Remich","code":"RM"},{"value":"Canton of Vianden","code":"VD"},{"value":"Canton of Wiltz","code":"WI"},{"value":"Diekirch District","code":"D"},{"value":"Grevenmacher District","code":"G"},{"value":"Luxembourg District","code":"L"}],"MO":[{"value":"Macau S.A.R.","code":"Macau S.A.R."}],"MG":[{"value":"Antananarivo Province","code":"T"},{"value":"Antsiranana Province","code":"D"},{"value":"Fianarantsoa Province","code":"F"},{"value":"Mahajanga Province","code":"M"},{"value":"Toamasina Province","code":"A"},{"value":"Toliara Province","code":"U"}],"MW":[{"value":"Balaka District","code":"BA"},{"value":"Blantyre District","code":"BL"},{"value":"Central Region","code":"C"},{"value":"Chikwawa District","code":"CK"},{"value":"Chiradzulu District","code":"CR"},{"value":"Chitipa district","code":"CT"},{"value":"Dedza District","code":"DE"},{"value":"Dowa District","code":"DO"},{"value":"Karonga District","code":"KR"},{"value":"Kasungu District","code":"KS"},{"value":"Likoma District","code":"LK"},{"value":"Lilongwe District","code":"LI"},{"value":"Machinga District","code":"MH"},{"value":"Mangochi District","code":"MG"},{"value":"Mchinji District","code":"MC"},{"value":"Mulanje District","code":"MU"},{"value":"Mwanza District","code":"MW"},{"value":"Mzimba District","code":"MZ"},{"value":"Nkhata Bay District","code":"NB"},{"value":"Nkhotakota District","code":"NK"},{"value":"Northern Region","code":"N"},{"value":"Nsanje District","code":"NS"},{"value":"Ntcheu District","code":"NU"},{"value":"Ntchisi District","code":"NI"},{"value":"Phalombe District","code":"PH"},{"value":"Rumphi District","code":"RU"},{"value":"Salima District","code":"SA"},{"value":"Southern Region","code":"S"},{"value":"Thyolo District","code":"TH"},{"value":"Zomba District","code":"ZO"}],"MY":[{"value":"Johor","code":"01"},{"value":"Kedah","code":"02"},{"value":"Kelantan","code":"03"},{"value":"Kuala Lumpur","code":"14"},{"value":"Labuan","code":"15"},{"value":"Malacca","code":"04"},{"value":"Negeri Sembilan","code":"05"},{"value":"Pahang","code":"06"},{"value":"Penang","code":"07"},{"value":"Perak","code":"08"},{"value":"Perlis","code":"09"},{"value":"Putrajaya","code":"16"},{"value":"Sabah","code":"12"},{"value":"Sarawak","code":"13"},{"value":"Selangor","code":"10"},{"value":"Terengganu","code":"11"}],"MV":[{"value":"Addu Atoll","code":"01"},{"value":"Alif Alif Atoll","code":"02"},{"value":"Alif Dhaal Atoll","code":"00"},{"value":"Central Province","code":"CE"},{"value":"Dhaalu Atoll","code":"17"},{"value":"Faafu Atoll","code":"14"},{"value":"Gaafu Alif Atoll","code":"27"},{"value":"Gaafu Dhaalu Atoll","code":"28"},{"value":"Gnaviyani Atoll","code":"29"},{"value":"Haa Alif Atoll","code":"07"},{"value":"Haa Dhaalu Atoll","code":"23"},{"value":"Kaafu Atoll","code":"26"},{"value":"Laamu Atoll","code":"05"},{"value":"Lhaviyani Atoll","code":"03"},{"value":"Malé","code":"MLE"},{"value":"Meemu Atoll","code":"12"},{"value":"Noonu Atoll","code":"25"},{"value":"North Central Province","code":"NC"},{"value":"North Province","code":"NO"},{"value":"Raa Atoll","code":"13"},{"value":"Shaviyani Atoll","code":"24"},{"value":"South Central Province","code":"SC"},{"value":"South Province","code":"SU"},{"value":"Thaa Atoll","code":"08"},{"value":"Upper South Province","code":"US"},{"value":"Vaavu Atoll","code":"04"}],"ML":[{"value":"Bamako","code":"BKO"},{"value":"Gao Region","code":"7"},{"value":"Kayes Region","code":"1"},{"value":"Kidal Region","code":"8"},{"value":"Koulikoro Region","code":"2"},{"value":"Ménaka Region","code":"9"},{"value":"Mopti Region","code":"5"},{"value":"Ségou Region","code":"4"},{"value":"Sikasso Region","code":"3"},{"value":"Taoudénit Region","code":"10"},{"value":"Tombouctou Region","code":"6"}],"MT":[{"value":"Attard","code":"01"},{"value":"Balzan","code":"02"},{"value":"Birgu","code":"03"},{"value":"Birkirkara","code":"04"},{"value":"Birżebbuġa","code":"05"},{"value":"Cospicua","code":"06"},{"value":"Dingli","code":"07"},{"value":"Fgura","code":"08"},{"value":"Floriana","code":"09"},{"value":"Fontana","code":"10"},{"value":"Għajnsielem","code":"13"},{"value":"Għarb","code":"14"},{"value":"Għargħur","code":"15"},{"value":"Għasri","code":"16"},{"value":"Għaxaq","code":"17"},{"value":"Gudja","code":"11"},{"value":"Gżira","code":"12"},{"value":"Ħamrun","code":"18"},{"value":"Iklin","code":"19"},{"value":"Kalkara","code":"21"},{"value":"Kerċem","code":"22"},{"value":"Kirkop","code":"23"},{"value":"Lija","code":"24"},{"value":"Luqa","code":"25"},{"value":"Marsa","code":"26"},{"value":"Marsaskala","code":"27"},{"value":"Marsaxlokk","code":"28"},{"value":"Mdina","code":"29"},{"value":"Mellieħa","code":"30"},{"value":"Mġarr","code":"31"},{"value":"Mosta","code":"32"},{"value":"Mqabba","code":"33"},{"value":"Msida","code":"34"},{"value":"Mtarfa","code":"35"},{"value":"Munxar","code":"36"},{"value":"Nadur","code":"37"},{"value":"Naxxar","code":"38"},{"value":"Paola","code":"39"},{"value":"Pembroke","code":"40"},{"value":"Pietà","code":"41"},{"value":"Qala","code":"42"},{"value":"Qormi","code":"43"},{"value":"Qrendi","code":"44"},{"value":"Rabat","code":"46"},{"value":"San Ġwann","code":"49"},{"value":"San Lawrenz","code":"50"},{"value":"Sannat","code":"52"},{"value":"Santa Luċija","code":"53"},{"value":"Santa Venera","code":"54"},{"value":"Senglea","code":"20"},{"value":"Siġġiewi","code":"55"},{"value":"Sliema","code":"56"},{"value":"St. Julian's","code":"48"},{"value":"St. Paul's Bay","code":"51"},{"value":"Swieqi","code":"57"},{"value":"Ta' Xbiex","code":"58"},{"value":"Tarxien","code":"59"},{"value":"Valletta","code":"60"},{"value":"Victoria","code":"45"},{"value":"Xagħra","code":"61"},{"value":"Xewkija","code":"62"},{"value":"Xgħajra","code":"63"},{"value":"Żabbar","code":"64"},{"value":"Żebbuġ Gozo","code":"65"},{"value":"Żebbuġ Malta","code":"66"},{"value":"Żejtun","code":"67"},{"value":"Żurrieq","code":"68"}],"IM":[{"value":"Man (Isle of)","code":"Man (Isle of)"}],"MH":[{"value":"Ralik Chain","code":"L"},{"value":"Ratak Chain","code":"T"}],"MQ":[{"value":"Martinique","code":"Martinique"}],"MR":[{"value":"Adrar","code":"07"},{"value":"Assaba","code":"03"},{"value":"Brakna","code":"05"},{"value":"Dakhlet Nouadhibou","code":"08"},{"value":"Gorgol","code":"04"},{"value":"Guidimaka","code":"10"},{"value":"Hodh Ech Chargui","code":"01"},{"value":"Hodh El Gharbi","code":"02"},{"value":"Inchiri","code":"12"},{"value":"Nouakchott-Nord","code":"14"},{"value":"Nouakchott-Ouest","code":"13"},{"value":"Nouakchott-Sud","code":"15"},{"value":"Tagant","code":"09"},{"value":"Tiris Zemmour","code":"11"},{"value":"Trarza","code":"06"}],"MU":[{"value":"Agalega Islands","code":"AG"},{"value":"Black River","code":"BL"},{"value":"Flacq","code":"FL"},{"value":"Grand Port","code":"GP"},{"value":"Moka","code":"MO"},{"value":"Pamplemousses","code":"PA"},{"value":"Plaines Wilhems","code":"PW"},{"value":"Port Louis","code":"PL"},{"value":"Rivière du Rempart","code":"RR"},{"value":"Rodrigues Island","code":"RO"},{"value":"Saint Brandon Islands","code":"CC"},{"value":"Savanne","code":"SA"}],"YT":[{"value":"Mayotte","code":"Mayotte"}],"MX":[{"value":"Aguascalientes","code":"AGU"},{"value":"Baja California","code":"BCN"},{"value":"Baja California Sur","code":"BCS"},{"value":"Campeche","code":"CAM"},{"value":"Chiapas","code":"CHP"},{"value":"Chihuahua","code":"CHH"},{"value":"Ciudad de México","code":"CMX"},{"value":"Coahuila de Zaragoza","code":"COA"},{"value":"Colima","code":"COL"},{"value":"Durango","code":"DUR"},{"value":"Estado de México","code":"MEX"},{"value":"Guanajuato","code":"GUA"},{"value":"Guerrero","code":"GRO"},{"value":"Hidalgo","code":"HID"},{"value":"Jalisco","code":"JAL"},{"value":"Michoacán de Ocampo","code":"MIC"},{"value":"Morelos","code":"MOR"},{"value":"Nayarit","code":"NAY"},{"value":"Nuevo León","code":"NLE"},{"value":"Oaxaca","code":"OAX"},{"value":"Puebla","code":"PUE"},{"value":"Querétaro","code":"QUE"},{"value":"Quintana Roo","code":"ROO"},{"value":"San Luis Potosí","code":"SLP"},{"value":"Sinaloa","code":"SIN"},{"value":"Sonora","code":"SON"},{"value":"Tabasco","code":"TAB"},{"value":"Tamaulipas","code":"TAM"},{"value":"Tlaxcala","code":"TLA"},{"value":"Veracruz de Ignacio de la Llave","code":"VER"},{"value":"Yucatán","code":"YUC"},{"value":"Zacatecas","code":"ZAC"}],"FM":[{"value":"Chuuk State","code":"TRK"},{"value":"Kosrae State","code":"KSA"},{"value":"Pohnpei State","code":"PNI"},{"value":"Yap State","code":"YAP"}],"MD":[{"value":"Anenii Noi District","code":"AN"},{"value":"Bălți Municipality","code":"BA"},{"value":"Basarabeasca District","code":"BS"},{"value":"Bender Municipality","code":"BD"},{"value":"Briceni District","code":"BR"},{"value":"Cahul District","code":"CA"},{"value":"Călărași District","code":"CL"},{"value":"Cantemir District","code":"CT"},{"value":"Căușeni District","code":"CS"},{"value":"Chișinău Municipality","code":"CU"},{"value":"Cimișlia District","code":"CM"},{"value":"Criuleni District","code":"CR"},{"value":"Dondușeni District","code":"DO"},{"value":"Drochia District","code":"DR"},{"value":"Dubăsari District","code":"DU"},{"value":"Edineț District","code":"ED"},{"value":"Fălești District","code":"FA"},{"value":"Florești District","code":"FL"},{"value":"Gagauzia","code":"GA"},{"value":"Glodeni District","code":"GL"},{"value":"Hîncești District","code":"HI"},{"value":"Ialoveni District","code":"IA"},{"value":"Nisporeni District","code":"NI"},{"value":"Ocnița District","code":"OC"},{"value":"Orhei District","code":"OR"},{"value":"Rezina District","code":"RE"},{"value":"Rîșcani District","code":"RI"},{"value":"Sîngerei District","code":"SI"},{"value":"Șoldănești District","code":"SD"},{"value":"Soroca District","code":"SO"},{"value":"Ștefan Vodă District","code":"SV"},{"value":"Strășeni District","code":"ST"},{"value":"Taraclia District","code":"TA"},{"value":"Telenești District","code":"TE"},{"value":"Transnistria autonomous territorial unit","code":"SN"},{"value":"Ungheni District","code":"UN"}],"MC":[{"value":"La Colle","code":"CL"},{"value":"La Condamine","code":"CO"},{"value":"Moneghetti","code":"MG"}],"MN":[{"value":"Arkhangai Province","code":"073"},{"value":"Bayan-Ölgii Province","code":"071"},{"value":"Bayankhongor Province","code":"069"},{"value":"Bulgan Province","code":"067"},{"value":"Darkhan-Uul Province","code":"037"},{"value":"Dornod Province","code":"061"},{"value":"Dornogovi Province","code":"063"},{"value":"Dundgovi Province","code":"059"},{"value":"Govi-Altai Province","code":"065"},{"value":"Govisümber Province","code":"064"},{"value":"Khentii Province","code":"039"},{"value":"Khovd Province","code":"043"},{"value":"Khövsgöl Province","code":"041"},{"value":"Ömnögovi Province","code":"053"},{"value":"Orkhon Province","code":"035"},{"value":"Övörkhangai Province","code":"055"},{"value":"Selenge Province","code":"049"},{"value":"Sükhbaatar Province","code":"051"},{"value":"Töv Province","code":"047"},{"value":"Uvs Province","code":"046"},{"value":"Zavkhan Province","code":"057"}],"ME":[{"value":"Andrijevica Municipality","code":"01"},{"value":"Bar Municipality","code":"02"},{"value":"Berane Municipality","code":"03"},{"value":"Bijelo Polje Municipality","code":"04"},{"value":"Budva Municipality","code":"05"},{"value":"Danilovgrad Municipality","code":"07"},{"value":"Gusinje Municipality","code":"22"},{"value":"Kolašin Municipality","code":"09"},{"value":"Kotor Municipality","code":"10"},{"value":"Mojkovac Municipality","code":"11"},{"value":"Nikšić Municipality","code":"12"},{"value":"Old Royal Capital Cetinje","code":"06"},{"value":"Petnjica Municipality","code":"23"},{"value":"Plav Municipality","code":"13"},{"value":"Pljevlja Municipality","code":"14"},{"value":"Plužine Municipality","code":"15"},{"value":"Podgorica Municipality","code":"16"},{"value":"Rožaje Municipality","code":"17"},{"value":"Šavnik Municipality","code":"18"},{"value":"Tivat Municipality","code":"19"},{"value":"Ulcinj Municipality","code":"20"},{"value":"Žabljak Municipality","code":"21"}],"MS":[{"value":"Montserrat","code":"Montserrat"}],"MA":[{"value":"Agadir-Ida-Ou-Tanane","code":"AGD"},{"value":"Al Haouz","code":"HAO"},{"value":"Al Hoceïma","code":"HOC"},{"value":"Aousserd (EH)","code":"AOU"},{"value":"Assa-Zag (EH-partial)","code":"ASZ"},{"value":"Azilal","code":"AZI"},{"value":"Béni Mellal","code":"BEM"},{"value":"Béni Mellal-Khénifra","code":"05"},{"value":"Benslimane","code":"BES"},{"value":"Berkane","code":"BER"},{"value":"Berrechid","code":"BRR"},{"value":"Boujdour (EH)","code":"BOD"},{"value":"Boulemane","code":"BOM"},{"value":"Casablanca","code":"CAS"},{"value":"Casablanca-Settat","code":"06"},{"value":"Chefchaouen","code":"CHE"},{"value":"Chichaoua","code":"CHI"},{"value":"Chtouka-Ait Baha","code":"CHT"},{"value":"Dakhla-Oued Ed-Dahab (EH)","code":"12"},{"value":"Drâa-Tafilalet","code":"08"},{"value":"Driouch","code":"DRI"},{"value":"El Hajeb","code":"HAJ"},{"value":"El Jadida","code":"JDI"},{"value":"El Kelâa des Sraghna","code":"KES"},{"value":"Errachidia","code":"ERR"},{"value":"Es-Semara (EH-partial)","code":"ESM"},{"value":"Essaouira","code":"ESI"},{"value":"Fahs-Anjra","code":"FAH"},{"value":"Fès","code":"FES"},{"value":"Fès-Meknès","code":"03"},{"value":"Figuig","code":"FIG"},{"value":"Fquih Ben Salah","code":"FQH"},{"value":"Guelmim","code":"GUE"},{"value":"Guelmim-Oued Noun (EH-partial)","code":"10"},{"value":"Guercif","code":"GUF"},{"value":"Ifrane","code":"IFR"},{"value":"Inezgane-Ait Melloul","code":"INE"},{"value":"Jerada","code":"JRA"},{"value":"Kénitra","code":"KEN"},{"value":"Khémisset","code":"KHE"},{"value":"Khénifra","code":"KHN"},{"value":"Khouribga","code":"KHO"},{"value":"L'Oriental","code":"02"},{"value":"Laâyoune (EH)","code":"LAA"},{"value":"Laâyoune-Sakia El Hamra (EH-partial)","code":"11"},{"value":"Larache","code":"LAR"},{"value":"M’diq-Fnideq","code":"MDF"},{"value":"Marrakech","code":"MAR"},{"value":"Marrakesh-Safi","code":"07"},{"value":"Médiouna","code":"MED"},{"value":"Meknès","code":"MEK"},{"value":"Midelt","code":"MID"},{"value":"Mohammadia","code":"MOH"},{"value":"Moulay Yacoub","code":"MOU"},{"value":"Nador","code":"NAD"},{"value":"Nouaceur","code":"NOU"},{"value":"Ouarzazate","code":"OUA"},{"value":"Oued Ed-Dahab (EH)","code":"OUD"},{"value":"Ouezzane","code":"OUZ"},{"value":"Oujda-Angad","code":"OUJ"},{"value":"Rabat","code":"RAB"},{"value":"Rabat-Salé-Kénitra","code":"04"},{"value":"Rehamna","code":"REH"},{"value":"Safi","code":"SAF"},{"value":"Salé","code":"SAL"},{"value":"Sefrou","code":"SEF"},{"value":"Settat","code":"SET"},{"value":"Sidi Bennour","code":"SIB"},{"value":"Sidi Ifni","code":"SIF"},{"value":"Sidi Kacem","code":"SIK"},{"value":"Sidi Slimane","code":"SIL"},{"value":"Skhirate-Témara","code":"SKH"},{"value":"Souss-Massa","code":"09"},{"value":"Tan-Tan (EH-partial)","code":"TNT"},{"value":"Tanger-Assilah","code":"TNG"},{"value":"Tanger-Tétouan-Al Hoceïma","code":"01"},{"value":"Taounate","code":"TAO"},{"value":"Taourirt","code":"TAI"},{"value":"Tarfaya (EH-partial)","code":"TAF"},{"value":"Taroudannt","code":"TAR"},{"value":"Tata","code":"TAT"},{"value":"Taza","code":"TAZ"},{"value":"Tétouan","code":"TET"},{"value":"Tinghir","code":"TIN"},{"value":"Tiznit","code":"TIZ"},{"value":"Youssoufia","code":"YUS"},{"value":"Zagora","code":"ZAG"}],"MZ":[{"value":"Cabo Delgado Province","code":"P"},{"value":"Gaza Province","code":"G"},{"value":"Inhambane Province","code":"I"},{"value":"Manica Province","code":"B"},{"value":"Maputo","code":"MPM"},{"value":"Maputo Province","code":"L"},{"value":"Nampula Province","code":"N"},{"value":"Niassa Province","code":"A"},{"value":"Sofala Province","code":"S"},{"value":"Tete Province","code":"T"},{"value":"Zambezia Province","code":"Q"}],"MM":[{"value":"Ayeyarwady Region","code":"07"},{"value":"Bago","code":"02"},{"value":"Chin State","code":"14"},{"value":"Kachin State","code":"11"},{"value":"Kayah State","code":"12"},{"value":"Kayin State","code":"13"},{"value":"Magway Region","code":"03"},{"value":"Mandalay Region","code":"04"},{"value":"Mon State","code":"15"},{"value":"Naypyidaw Union Territory","code":"18"},{"value":"Rakhine State","code":"16"},{"value":"Sagaing Region","code":"01"},{"value":"Shan State","code":"17"},{"value":"Tanintharyi Region","code":"05"},{"value":"Yangon Region","code":"06"}],"NA":[{"value":"Erongo Region","code":"ER"},{"value":"Hardap Region","code":"HA"},{"value":"Karas Region","code":"KA"},{"value":"Kavango East Region","code":"KE"},{"value":"Kavango West Region","code":"KW"},{"value":"Khomas Region","code":"KH"},{"value":"Kunene Region","code":"KU"},{"value":"Ohangwena Region","code":"OW"},{"value":"Omaheke Region","code":"OH"},{"value":"Omusati Region","code":"OS"},{"value":"Oshana Region","code":"ON"},{"value":"Oshikoto Region","code":"OT"},{"value":"Otjozondjupa Region","code":"OD"},{"value":"Zambezi Region","code":"CA"}],"NR":[{"value":"Aiwo District","code":"01"},{"value":"Anabar District","code":"02"},{"value":"Anetan District","code":"03"},{"value":"Anibare District","code":"04"},{"value":"Baiti District","code":"05"},{"value":"Boe District","code":"06"},{"value":"Buada District","code":"07"},{"value":"Denigomodu District","code":"08"},{"value":"Ewa District","code":"09"},{"value":"Ijuw District","code":"10"},{"value":"Meneng District","code":"11"},{"value":"Nibok District","code":"12"},{"value":"Uaboe District","code":"13"},{"value":"Yaren District","code":"14"}],"NP":[{"value":"Bagmati","code":"P3"},{"value":"Gandaki","code":"P4"},{"value":"Karnali","code":"P6"},{"value":"Koshi","code":"P1"},{"value":"Lumbini","code":"P5"},{"value":"Madhesh","code":"P2"},{"value":"Sudurpashchim","code":"P7"}],"NL":[{"value":"Bonaire","code":"BQ1"},{"value":"Drenthe","code":"DR"},{"value":"Flevoland","code":"FL"},{"value":"Friesland","code":"FR"},{"value":"Gelderland","code":"GE"},{"value":"Groningen","code":"GR"},{"value":"Limburg","code":"LI"},{"value":"North Brabant","code":"NB"},{"value":"North Holland","code":"NH"},{"value":"Overijssel","code":"OV"},{"value":"Saba","code":"BQ2"},{"value":"Sint Eustatius","code":"BQ3"},{"value":"South Holland","code":"ZH"},{"value":"Utrecht","code":"UT"},{"value":"Zeeland","code":"ZE"}],"NC":[{"value":"Loyalty Islands Province","code":"03"},{"value":"North Province","code":"02"},{"value":"South Province","code":"01"}],"NZ":[{"value":"Auckland Region","code":"AUK"},{"value":"Bay of Plenty Region","code":"BOP"},{"value":"Canterbury Region","code":"CAN"},{"value":"Chatham Islands","code":"CIT"},{"value":"Gisborne District","code":"GIS"},{"value":"Hawke's Bay Region","code":"HKB"},{"value":"Manawatu-Wanganui Region","code":"MWT"},{"value":"Marlborough Region","code":"MBH"},{"value":"Nelson Region","code":"NSN"},{"value":"Northland Region","code":"NTL"},{"value":"Otago Region","code":"OTA"},{"value":"Southland Region","code":"STL"},{"value":"Taranaki Region","code":"TKI"},{"value":"Tasman District","code":"TAS"},{"value":"Waikato Region","code":"WKO"},{"value":"Wellington Region","code":"WGN"},{"value":"West Coast Region","code":"WTC"}],"NI":[{"value":"Boaco","code":"BO"},{"value":"Carazo","code":"CA"},{"value":"Chinandega","code":"CI"},{"value":"Chontales","code":"CO"},{"value":"Estelí","code":"ES"},{"value":"Granada","code":"GR"},{"value":"Jinotega","code":"JI"},{"value":"León","code":"LE"},{"value":"Madriz","code":"MD"},{"value":"Managua","code":"MN"},{"value":"Masaya","code":"MS"},{"value":"Matagalpa","code":"MT"},{"value":"North Caribbean Coast","code":"AN"},{"value":"Nueva Segovia","code":"NS"},{"value":"Río San Juan","code":"SJ"},{"value":"Rivas","code":"RI"},{"value":"South Caribbean Coast","code":"AS"}],"NE":[{"value":"Agadez Region","code":"1"},{"value":"Diffa Region","code":"2"},{"value":"Dosso Region","code":"3"},{"value":"Maradi Region","code":"4"},{"value":"Tahoua Region","code":"5"},{"value":"Tillabéri Region","code":"6"},{"value":"Zinder Region","code":"7"}],"NG":[{"value":"Abia","code":"AB"},{"value":"Abuja Federal Capital Territory","code":"FC"},{"value":"Adamawa","code":"AD"},{"value":"Akwa Ibom","code":"AK"},{"value":"Anambra","code":"AN"},{"value":"Bauchi","code":"BA"},{"value":"Bayelsa","code":"BY"},{"value":"Benue","code":"BE"},{"value":"Borno","code":"BO"},{"value":"Cross River","code":"CR"},{"value":"Delta","code":"DE"},{"value":"Ebonyi","code":"EB"},{"value":"Edo","code":"ED"},{"value":"Ekiti","code":"EK"},{"value":"Enugu","code":"EN"},{"value":"Gombe","code":"GO"},{"value":"Imo","code":"IM"},{"value":"Jigawa","code":"JI"},{"value":"Kaduna","code":"KD"},{"value":"Kano","code":"KN"},{"value":"Katsina","code":"KT"},{"value":"Kebbi","code":"KE"},{"value":"Kogi","code":"KO"},{"value":"Kwara","code":"KW"},{"value":"Lagos","code":"LA"},{"value":"Nasarawa","code":"NA"},{"value":"Niger","code":"NI"},{"value":"Ogun","code":"OG"},{"value":"Ondo","code":"ON"},{"value":"Osun","code":"OS"},{"value":"Oyo","code":"OY"},{"value":"Plateau","code":"PL"},{"value":"Rivers","code":"RI"},{"value":"Sokoto","code":"SO"},{"value":"Taraba","code":"TA"},{"value":"Yobe","code":"YO"},{"value":"Zamfara","code":"ZA"}],"NU":[{"value":"Niue","code":"Niue"}],"NF":[{"value":"Norfolk Island","code":"Norfolk Island"}],"KP":[{"value":"Chagang Province","code":"04"},{"value":"Kangwon Province","code":"07"},{"value":"North Hamgyong Province","code":"09"},{"value":"North Hwanghae Province","code":"06"},{"value":"North Pyongan Province","code":"03"},{"value":"Pyongyang","code":"01"},{"value":"Rason","code":"13"},{"value":"Ryanggang Province","code":"10"},{"value":"South Hamgyong Province","code":"08"},{"value":"South Hwanghae Province","code":"05"},{"value":"South Pyongan Province","code":"02"}],"MK":[{"value":"Aerodrom Municipality","code":"01"},{"value":"Aračinovo Municipality","code":"02"},{"value":"Berovo Municipality","code":"03"},{"value":"Bitola Municipality","code":"04"},{"value":"Bogdanci Municipality","code":"05"},{"value":"Bogovinje Municipality","code":"06"},{"value":"Bosilovo Municipality","code":"07"},{"value":"Brvenica Municipality","code":"08"},{"value":"Butel Municipality","code":"09"},{"value":"Čair Municipality","code":"79"},{"value":"Čaška Municipality","code":"80"},{"value":"Centar Municipality","code":"77"},{"value":"Centar Župa Municipality","code":"78"},{"value":"Češinovo-Obleševo Municipality","code":"81"},{"value":"Čučer-Sandevo Municipality","code":"82"},{"value":"Debarca Municipality","code":"22"},{"value":"Delčevo Municipality","code":"23"},{"value":"Demir Hisar Municipality","code":"25"},{"value":"Demir Kapija Municipality","code":"24"},{"value":"Dojran Municipality","code":"26"},{"value":"Dolneni Municipality","code":"27"},{"value":"Drugovo Municipality","code":"28"},{"value":"Gazi Baba Municipality","code":"17"},{"value":"Gevgelija Municipality","code":"18"},{"value":"Gjorče Petrov Municipality","code":"29"},{"value":"Gostivar Municipality","code":"19"},{"value":"Gradsko Municipality","code":"20"},{"value":"Greater Skopje","code":"85"},{"value":"Ilinden Municipality","code":"34"},{"value":"Jegunovce Municipality","code":"35"},{"value":"Karbinci","code":"37"},{"value":"Karpoš Municipality","code":"38"},{"value":"Kavadarci Municipality","code":"36"},{"value":"Kičevo Municipality","code":"40"},{"value":"Kisela Voda Municipality","code":"39"},{"value":"Kočani Municipality","code":"42"},{"value":"Konče Municipality","code":"41"},{"value":"Kratovo Municipality","code":"43"},{"value":"Kriva Palanka Municipality","code":"44"},{"value":"Krivogaštani Municipality","code":"45"},{"value":"Kruševo Municipality","code":"46"},{"value":"Kumanovo Municipality","code":"47"},{"value":"Lipkovo Municipality","code":"48"},{"value":"Lozovo Municipality","code":"49"},{"value":"Makedonska Kamenica Municipality","code":"51"},{"value":"Makedonski Brod Municipality","code":"52"},{"value":"Mavrovo and Rostuša Municipality","code":"50"},{"value":"Mogila Municipality","code":"53"},{"value":"Negotino Municipality","code":"54"},{"value":"Novaci Municipality","code":"55"},{"value":"Novo Selo Municipality","code":"56"},{"value":"Ohrid Municipality","code":"58"},{"value":"Oslomej Municipality","code":"57"},{"value":"Pehčevo Municipality","code":"60"},{"value":"Petrovec Municipality","code":"59"},{"value":"Plasnica Municipality","code":"61"},{"value":"Prilep Municipality","code":"62"},{"value":"Probištip Municipality","code":"63"},{"value":"Radoviš Municipality","code":"64"},{"value":"Rankovce Municipality","code":"65"},{"value":"Resen Municipality","code":"66"},{"value":"Rosoman Municipality","code":"67"},{"value":"Saraj Municipality","code":"68"},{"value":"Sopište Municipality","code":"70"},{"value":"Staro Nagoričane Municipality","code":"71"},{"value":"Štip Municipality","code":"83"},{"value":"Struga Municipality","code":"72"},{"value":"Strumica Municipality","code":"73"},{"value":"Studeničani Municipality","code":"74"},{"value":"Šuto Orizari Municipality","code":"84"},{"value":"Sveti Nikole Municipality","code":"69"},{"value":"Tearce Municipality","code":"75"},{"value":"Tetovo Municipality","code":"76"},{"value":"Valandovo Municipality","code":"10"},{"value":"Vasilevo Municipality","code":"11"},{"value":"Veles Municipality","code":"13"},{"value":"Vevčani Municipality","code":"12"},{"value":"Vinica Municipality","code":"14"},{"value":"Vraneštica Municipality","code":"15"},{"value":"Vrapčište Municipality","code":"16"},{"value":"Zajas Municipality","code":"31"},{"value":"Zelenikovo Municipality","code":"32"},{"value":"Želino Municipality","code":"30"},{"value":"Zrnovci Municipality","code":"33"}],"MP":[{"value":"Northern Mariana Islands","code":"Northern Mariana Islands"}],"NO":[{"value":"Agder","code":"42"},{"value":"Innlandet","code":"34"},{"value":"Jan Mayen","code":"22"},{"value":"Møre og Romsdal","code":"15"},{"value":"Nordland","code":"18"},{"value":"Oslo","code":"03"},{"value":"Rogaland","code":"11"},{"value":"Svalbard","code":"21"},{"value":"Troms og Finnmark","code":"54"},{"value":"Trøndelag","code":"50"},{"value":"Vestfold og Telemark","code":"38"},{"value":"Vestland","code":"46"},{"value":"Viken","code":"30"}],"OM":[{"value":"Ad Dakhiliyah","code":"DA"},{"value":"Ad Dhahirah","code":"ZA"},{"value":"Al Batinah North","code":"BS"},{"value":"Al Batinah Region","code":"BA"},{"value":"Al Batinah South","code":"BJ"},{"value":"Al Buraimi","code":"BU"},{"value":"Al Wusta","code":"WU"},{"value":"Ash Sharqiyah North","code":"SS"},{"value":"Ash Sharqiyah Region","code":"SH"},{"value":"Ash Sharqiyah South","code":"SJ"},{"value":"Dhofar","code":"ZU"},{"value":"Musandam","code":"MU"},{"value":"Muscat","code":"MA"}],"PK":[{"value":"Azad Kashmir","code":"JK"},{"value":"Balochistan","code":"BA"},{"value":"Federally Administered Tribal Areas","code":"TA"},{"value":"Gilgit-Baltistan","code":"GB"},{"value":"Islamabad Capital Territory","code":"IS"},{"value":"Khyber Pakhtunkhwa","code":"KP"},{"value":"Punjab","code":"PB"},{"value":"Sindh","code":"SD"}],"PW":[{"value":"Aimeliik","code":"002"},{"value":"Airai","code":"004"},{"value":"Angaur","code":"010"},{"value":"Hatohobei","code":"050"},{"value":"Kayangel","code":"100"},{"value":"Koror","code":"150"},{"value":"Melekeok","code":"212"},{"value":"Ngaraard","code":"214"},{"value":"Ngarchelong","code":"218"},{"value":"Ngardmau","code":"222"},{"value":"Ngatpang","code":"224"},{"value":"Ngchesar","code":"226"},{"value":"Ngeremlengui","code":"227"},{"value":"Ngiwal","code":"228"},{"value":"Peleliu","code":"350"},{"value":"Sonsorol","code":"370"}],"PS":[{"value":"Bethlehem","code":"BTH"},{"value":"Deir El Balah","code":"DEB"},{"value":"Gaza","code":"GZA"},{"value":"Hebron","code":"HBN"},{"value":"Jenin","code":"JEN"},{"value":"Jericho ","code":"JRH"},{"value":"Jerusalem (Quds)","code":"JEM"},{"value":"Khan Yunis","code":"KYS"},{"value":"Nablus","code":"NBS"},{"value":"North Gaza","code":"NGZ"},{"value":"Qalqilya","code":"QQA"},{"value":"Rafah","code":"RFH"},{"value":"Ramallah","code":"RBH"},{"value":"Salfit","code":"SLT"},{"value":"Tubas","code":"TBS"},{"value":"Tulkarm","code":"TKM"}],"PA":[{"value":"Bocas del Toro Province","code":"1"},{"value":"Chiriquí Province","code":"4"},{"value":"Coclé Province","code":"2"},{"value":"Colón Province","code":"3"},{"value":"Darién Province","code":"5"},{"value":"Emberá-Wounaan Comarca","code":"EM"},{"value":"Guna Yala","code":"KY"},{"value":"Herrera Province","code":"6"},{"value":"Los Santos Province","code":"7"},{"value":"Ngöbe-Buglé Comarca","code":"NB"},{"value":"Panamá Oeste Province","code":"10"},{"value":"Panamá Province","code":"8"},{"value":"Veraguas Province","code":"9"}],"PG":[{"value":"Bougainville","code":"NSB"},{"value":"Central Province","code":"CPM"},{"value":"Chimbu Province","code":"CPK"},{"value":"East New Britain","code":"EBR"},{"value":"East Sepik","code":"ESW"},{"value":"Eastern Highlands Province","code":"EHG"},{"value":"Enga Province","code":"EPW"},{"value":"Gulf","code":"GPK"},{"value":"Hela","code":"HLA"},{"value":"Jiwaka Province","code":"JWK"},{"value":"Madang Province","code":"MPM"},{"value":"Manus Province","code":"MRL"},{"value":"Milne Bay Province","code":"MBA"},{"value":"Morobe Province","code":"MPL"},{"value":"New Ireland Province","code":"NIK"},{"value":"Oro Province","code":"NPP"},{"value":"Port Moresby","code":"NCD"},{"value":"Sandaun Province","code":"SAN"},{"value":"Southern Highlands Province","code":"SHM"},{"value":"West New Britain Province","code":"WBK"},{"value":"Western Highlands Province","code":"WHM"},{"value":"Western Province","code":"WPD"}],"PY":[{"value":"Alto Paraguay Department","code":"16"},{"value":"Alto Paraná Department","code":"10"},{"value":"Amambay Department","code":"13"},{"value":"Asuncion","code":"ASU"},{"value":"Boquerón Department","code":"19"},{"value":"Caaguazú","code":"5"},{"value":"Caazapá","code":"6"},{"value":"Canindeyú","code":"14"},{"value":"Central Department","code":"11"},{"value":"Concepción Department","code":"1"},{"value":"Cordillera Department","code":"3"},{"value":"Guairá Department","code":"4"},{"value":"Itapúa","code":"7"},{"value":"Misiones Department","code":"8"},{"value":"Ñeembucú Department","code":"12"},{"value":"Paraguarí Department","code":"9"},{"value":"Presidente Hayes Department","code":"15"},{"value":"San Pedro Department","code":"2"}],"PE":[{"value":"Amazonas","code":"AMA"},{"value":"Áncash","code":"ANC"},{"value":"Apurímac","code":"APU"},{"value":"Arequipa","code":"ARE"},{"value":"Ayacucho","code":"AYA"},{"value":"Cajamarca","code":"CAJ"},{"value":"Callao","code":"CAL"},{"value":"Cusco","code":"CUS"},{"value":"Huancavelica","code":"HUV"},{"value":"Huanuco","code":"HUC"},{"value":"Ica","code":"ICA"},{"value":"Junín","code":"JUN"},{"value":"La Libertad","code":"LAL"},{"value":"Lambayeque","code":"LAM"},{"value":"Lima","code":"LIM"},{"value":"Loreto","code":"LOR"},{"value":"Madre de Dios","code":"MDD"},{"value":"Moquegua","code":"MOQ"},{"value":"Pasco","code":"PAS"},{"value":"Piura","code":"PIU"},{"value":"Puno","code":"PUN"},{"value":"San Martín","code":"SAM"},{"value":"Tacna","code":"TAC"},{"value":"Tumbes","code":"TUM"},{"value":"Ucayali","code":"UCA"}],"PH":[{"value":"Abra","code":"ABR"},{"value":"Agusan del Norte","code":"AGN"},{"value":"Agusan del Sur","code":"AGS"},{"value":"Aklan","code":"AKL"},{"value":"Albay","code":"ALB"},{"value":"Antique","code":"ANT"},{"value":"Apayao","code":"APA"},{"value":"Aurora","code":"AUR"},{"value":"Autonomous Region in Muslim Mindanao","code":"14"},{"value":"Basilan","code":"BAS"},{"value":"Bataan","code":"BAN"},{"value":"Batanes","code":"BTN"},{"value":"Batangas","code":"BTG"},{"value":"Benguet","code":"BEN"},{"value":"Bicol","code":"05"},{"value":"Biliran","code":"BIL"},{"value":"Bohol","code":"BOH"},{"value":"Bukidnon","code":"BUK"},{"value":"Bulacan","code":"BUL"},{"value":"Cagayan","code":"CAG"},{"value":"Cagayan Valley","code":"02"},{"value":"Calabarzon","code":"40"},{"value":"Camarines Norte","code":"CAN"},{"value":"Camarines Sur","code":"CAS"},{"value":"Camiguin","code":"CAM"},{"value":"Capiz","code":"CAP"},{"value":"Caraga","code":"13"},{"value":"Catanduanes","code":"CAT"},{"value":"Cavite","code":"CAV"},{"value":"Cebu","code":"CEB"},{"value":"Central Luzon","code":"03"},{"value":"Central Visayas","code":"07"},{"value":"Compostela Valley","code":"COM"},{"value":"Cordillera Administrative","code":"15"},{"value":"Cotabato","code":"NCO"},{"value":"Davao","code":"11"},{"value":"Davao del Norte","code":"DAV"},{"value":"Davao del Sur","code":"DAS"},{"value":"Davao Occidental","code":"DVO"},{"value":"Davao Oriental","code":"DAO"},{"value":"Dinagat Islands","code":"DIN"},{"value":"Eastern Samar","code":"EAS"},{"value":"Eastern Visayas","code":"08"},{"value":"Guimaras","code":"GUI"},{"value":"Ifugao","code":"IFU"},{"value":"Ilocos","code":"01"},{"value":"Ilocos Norte","code":"ILN"},{"value":"Ilocos Sur","code":"ILS"},{"value":"Iloilo","code":"ILI"},{"value":"Isabela","code":"ISA"},{"value":"Kalinga","code":"KAL"},{"value":"La Union","code":"LUN"},{"value":"Laguna","code":"LAG"},{"value":"Lanao del Norte","code":"LAN"},{"value":"Lanao del Sur","code":"LAS"},{"value":"Leyte","code":"LEY"},{"value":"Maguindanao","code":"MAG"},{"value":"Marinduque","code":"MAD"},{"value":"Masbate","code":"MAS"},{"value":"Metro Manila","code":"NCR"},{"value":"Mimaropa","code":"41"},{"value":"Misamis Occidental","code":"MSC"},{"value":"Misamis Oriental","code":"MSR"},{"value":"Mountain Province","code":"MOU"},{"value":"Negros Occidental","code":"NEC"},{"value":"Negros Oriental","code":"NER"},{"value":"Northern Mindanao","code":"10"},{"value":"Northern Samar","code":"NSA"},{"value":"Nueva Ecija","code":"NUE"},{"value":"Nueva Vizcaya","code":"NUV"},{"value":"Occidental Mindoro","code":"MDC"},{"value":"Oriental Mindoro","code":"MDR"},{"value":"Palawan","code":"PLW"},{"value":"Pampanga","code":"PAM"},{"value":"Pangasinan","code":"PAN"},{"value":"Quezon","code":"QUE"},{"value":"Quirino","code":"QUI"},{"value":"Rizal","code":"RIZ"},{"value":"Romblon","code":"ROM"},{"value":"Sarangani","code":"SAR"},{"value":"Siquijor","code":"SIG"},{"value":"Soccsksargen","code":"12"},{"value":"Sorsogon","code":"SOR"},{"value":"South Cotabato","code":"SCO"},{"value":"Southern Leyte","code":"SLE"},{"value":"Sultan Kudarat","code":"SUK"},{"value":"Sulu","code":"SLU"},{"value":"Surigao del Norte","code":"SUN"},{"value":"Surigao del Sur","code":"SUR"},{"value":"Tarlac","code":"TAR"},{"value":"Tawi-Tawi","code":"TAW"},{"value":"Western Samar","code":"WSA"},{"value":"Western Visayas","code":"06"},{"value":"Zambales","code":"ZMB"},{"value":"Zamboanga del Norte","code":"ZAN"},{"value":"Zamboanga del Sur","code":"ZAS"},{"value":"Zamboanga Peninsula","code":"09"},{"value":"Zamboanga Sibugay","code":"ZSI"}],"PN":[{"value":"Pitcairn Island","code":"Pitcairn Island"}],"PL":[{"value":"Greater Poland","code":"30"},{"value":"Holy Cross","code":"26"},{"value":"Kuyavia-Pomerania","code":"04"},{"value":"Lesser Poland","code":"12"},{"value":"Lower Silesia","code":"02"},{"value":"Lublin","code":"06"},{"value":"Lubusz","code":"08"},{"value":"Łódź","code":"10"},{"value":"Mazovia","code":"14"},{"value":"Podlaskie","code":"20"},{"value":"Pomerania","code":"22"},{"value":"Silesia","code":"24"},{"value":"Subcarpathia","code":"18"},{"value":"Upper Silesia","code":"16"},{"value":"Warmia-Masuria","code":"28"},{"value":"West Pomerania","code":"32"}],"PT":[{"value":"Açores","code":"20"},{"value":"Aveiro","code":"01"},{"value":"Beja","code":"02"},{"value":"Braga","code":"03"},{"value":"Bragança","code":"04"},{"value":"Castelo Branco","code":"05"},{"value":"Coimbra","code":"06"},{"value":"Évora","code":"07"},{"value":"Faro","code":"08"},{"value":"Guarda","code":"09"},{"value":"Leiria","code":"10"},{"value":"Lisbon","code":"11"},{"value":"Madeira","code":"30"},{"value":"Portalegre","code":"12"},{"value":"Porto","code":"13"},{"value":"Santarém","code":"14"},{"value":"Setúbal","code":"15"},{"value":"Viana do Castelo","code":"16"},{"value":"Vila Real","code":"17"},{"value":"Viseu","code":"18"}],"PR":[{"value":"Adjuntas","code":"001"},{"value":"Aguada","code":"003"},{"value":"Aguadilla","code":"005"},{"value":"Aguas Buenas","code":"007"},{"value":"Aibonito","code":"009"},{"value":"Añasco","code":"011"},{"value":"Arecibo","code":"013"},{"value":"Arecibo","code":"AR"},{"value":"Arroyo","code":"015"},{"value":"Barceloneta","code":"017"},{"value":"Barranquitas","code":"019"},{"value":"Bayamon","code":"BY"},{"value":"Bayamón","code":"021"},{"value":"Cabo Rojo","code":"023"},{"value":"Caguas","code":"CG"},{"value":"Caguas","code":"025"},{"value":"Camuy","code":"027"},{"value":"Canóvanas","code":"029"},{"value":"Carolina","code":"CL"},{"value":"Carolina","code":"031"},{"value":"Cataño","code":"033"},{"value":"Cayey","code":"035"},{"value":"Ceiba","code":"037"},{"value":"Ciales","code":"039"},{"value":"Cidra","code":"041"},{"value":"Coamo","code":"043"},{"value":"Comerío","code":"045"},{"value":"Corozal","code":"047"},{"value":"Culebra","code":"049"},{"value":"Dorado","code":"051"},{"value":"Fajardo","code":"053"},{"value":"Florida","code":"054"},{"value":"Guánica","code":"055"},{"value":"Guayama","code":"057"},{"value":"Guayanilla","code":"059"},{"value":"Guaynabo","code":"GN"},{"value":"Guaynabo","code":"061"},{"value":"Gurabo","code":"063"},{"value":"Hatillo","code":"065"},{"value":"Hormigueros","code":"067"},{"value":"Humacao","code":"069"},{"value":"Isabela","code":"071"},{"value":"Jayuya","code":"073"},{"value":"Juana Díaz","code":"075"},{"value":"Juncos","code":"077"},{"value":"Lajas","code":"079"},{"value":"Lares","code":"081"},{"value":"Las Marías","code":"083"},{"value":"Las Piedras","code":"085"},{"value":"Loíza","code":"087"},{"value":"Luquillo","code":"089"},{"value":"Manatí","code":"091"},{"value":"Maricao","code":"093"},{"value":"Maunabo","code":"095"},{"value":"Mayagüez","code":"MG"},{"value":"Mayagüez","code":"097"},{"value":"Moca","code":"099"},{"value":"Morovis","code":"101"},{"value":"Naguabo","code":"103"},{"value":"Naranjito","code":"105"},{"value":"Orocovis","code":"107"},{"value":"Patillas","code":"109"},{"value":"Peñuelas","code":"111"},{"value":"Ponce","code":"PO"},{"value":"Ponce","code":"113"},{"value":"Quebradillas","code":"115"},{"value":"Rincón","code":"117"},{"value":"Río Grande","code":"119"},{"value":"Sabana Grande","code":"121"},{"value":"Salinas","code":"123"},{"value":"San Germán","code":"125"},{"value":"San Juan","code":"127"},{"value":"San Juan","code":"SJ"},{"value":"San Lorenzo","code":"129"},{"value":"San Sebastián","code":"131"},{"value":"Santa Isabel","code":"133"},{"value":"Toa Alta","code":"135"},{"value":"Toa Baja","code":"TB"},{"value":"Toa Baja","code":"137"},{"value":"Trujillo Alto","code":"TA"},{"value":"Trujillo Alto","code":"139"},{"value":"Utuado","code":"141"},{"value":"Vega Alta","code":"143"},{"value":"Vega Baja","code":"145"},{"value":"Vieques","code":"147"},{"value":"Villalba","code":"149"},{"value":"Yabucoa","code":"151"},{"value":"Yauco","code":"153"}],"QA":[{"value":"Al Daayen","code":"ZA"},{"value":"Al Khor","code":"KH"},{"value":"Al Rayyan Municipality","code":"RA"},{"value":"Al Wakrah","code":"WA"},{"value":"Al-Shahaniya","code":"SH"},{"value":"Doha","code":"DA"},{"value":"Madinat ash Shamal","code":"MS"},{"value":"Umm Salal Municipality","code":"US"}],"RE":[{"value":"Reunion","code":"Reunion"}],"RO":[{"value":"Alba","code":"AB"},{"value":"Arad County","code":"AR"},{"value":"Arges","code":"AG"},{"value":"Bacău County","code":"BC"},{"value":"Bihor County","code":"BH"},{"value":"Bistrița-Năsăud County","code":"BN"},{"value":"Botoșani County","code":"BT"},{"value":"Braila","code":"BR"},{"value":"Brașov County","code":"BV"},{"value":"Bucharest","code":"B"},{"value":"Buzău County","code":"BZ"},{"value":"Călărași County","code":"CL"},{"value":"Caraș-Severin County","code":"CS"},{"value":"Cluj County","code":"CJ"},{"value":"Constanța County","code":"CT"},{"value":"Covasna County","code":"CV"},{"value":"Dâmbovița County","code":"DB"},{"value":"Dolj County","code":"DJ"},{"value":"Galați County","code":"GL"},{"value":"Giurgiu County","code":"GR"},{"value":"Gorj County","code":"GJ"},{"value":"Harghita County","code":"HR"},{"value":"Hunedoara County","code":"HD"},{"value":"Ialomița County","code":"IL"},{"value":"Iași County","code":"IS"},{"value":"Ilfov County","code":"IF"},{"value":"Maramureș County","code":"MM"},{"value":"Mehedinți County","code":"MH"},{"value":"Mureș County","code":"MS"},{"value":"Neamț County","code":"NT"},{"value":"Olt County","code":"OT"},{"value":"Prahova County","code":"PH"},{"value":"Sălaj County","code":"SJ"},{"value":"Satu Mare County","code":"SM"},{"value":"Sibiu County","code":"SB"},{"value":"Suceava County","code":"SV"},{"value":"Teleorman County","code":"TR"},{"value":"Timiș County","code":"TM"},{"value":"Tulcea County","code":"TL"},{"value":"Vâlcea County","code":"VL"},{"value":"Vaslui County","code":"VS"},{"value":"Vrancea County","code":"VN"}],"RU":[{"value":"Altai Krai","code":"ALT"},{"value":"Altai Republic","code":"AL"},{"value":"Amur Oblast","code":"AMU"},{"value":"Arkhangelsk","code":"ARK"},{"value":"Astrakhan Oblast","code":"AST"},{"value":"Belgorod Oblast","code":"BEL"},{"value":"Bryansk Oblast","code":"BRY"},{"value":"Chechen Republic","code":"CE"},{"value":"Chelyabinsk Oblast","code":"CHE"},{"value":"Chukotka Autonomous Okrug","code":"CHU"},{"value":"Chuvash Republic","code":"CU"},{"value":"Irkutsk","code":"IRK"},{"value":"Ivanovo Oblast","code":"IVA"},{"value":"Jewish Autonomous Oblast","code":"YEV"},{"value":"Kabardino-Balkar Republic","code":"KB"},{"value":"Kaliningrad","code":"KGD"},{"value":"Kaluga Oblast","code":"KLU"},{"value":"Kamchatka Krai","code":"KAM"},{"value":"Karachay-Cherkess Republic","code":"KC"},{"value":"Kemerovo Oblast","code":"KEM"},{"value":"Khabarovsk Krai","code":"KHA"},{"value":"Khanty-Mansi Autonomous Okrug","code":"KHM"},{"value":"Kirov Oblast","code":"KIR"},{"value":"Komi Republic","code":"KO"},{"value":"Kostroma Oblast","code":"KOS"},{"value":"Krasnodar Krai","code":"KDA"},{"value":"Krasnoyarsk Krai","code":"KYA"},{"value":"Kurgan Oblast","code":"KGN"},{"value":"Kursk Oblast","code":"KRS"},{"value":"Leningrad Oblast","code":"LEN"},{"value":"Lipetsk Oblast","code":"LIP"},{"value":"Magadan Oblast","code":"MAG"},{"value":"Mari El Republic","code":"ME"},{"value":"Moscow","code":"MOW"},{"value":"Moscow Oblast","code":"MOS"},{"value":"Murmansk Oblast","code":"MUR"},{"value":"Nenets Autonomous Okrug","code":"NEN"},{"value":"Nizhny Novgorod Oblast","code":"NIZ"},{"value":"Novgorod Oblast","code":"NGR"},{"value":"Novosibirsk","code":"NVS"},{"value":"Omsk Oblast","code":"OMS"},{"value":"Orenburg Oblast","code":"ORE"},{"value":"Oryol Oblast","code":"ORL"},{"value":"Penza Oblast","code":"PNZ"},{"value":"Perm Krai","code":"PER"},{"value":"Primorsky Krai","code":"PRI"},{"value":"Pskov Oblast","code":"PSK"},{"value":"Republic of Adygea","code":"AD"},{"value":"Republic of Bashkortostan","code":"BA"},{"value":"Republic of Buryatia","code":"BU"},{"value":"Republic of Dagestan","code":"DA"},{"value":"Republic of Ingushetia","code":"IN"},{"value":"Republic of Kalmykia","code":"KL"},{"value":"Republic of Karelia","code":"KR"},{"value":"Republic of Khakassia","code":"KK"},{"value":"Republic of Mordovia","code":"MO"},{"value":"Republic of North Ossetia-Alania","code":"SE"},{"value":"Republic of Tatarstan","code":"TA"},{"value":"Rostov Oblast","code":"ROS"},{"value":"Ryazan Oblast","code":"RYA"},{"value":"Saint Petersburg","code":"SPE"},{"value":"Sakha Republic","code":"SA"},{"value":"Sakhalin","code":"SAK"},{"value":"Samara Oblast","code":"SAM"},{"value":"Saratov Oblast","code":"SAR"},{"value":"Smolensk Oblast","code":"SMO"},{"value":"Stavropol Krai","code":"STA"},{"value":"Sverdlovsk","code":"SVE"},{"value":"Tambov Oblast","code":"TAM"},{"value":"Tomsk Oblast","code":"TOM"},{"value":"Tula Oblast","code":"TUL"},{"value":"Tuva Republic","code":"TY"},{"value":"Tver Oblast","code":"TVE"},{"value":"Tyumen Oblast","code":"TYU"},{"value":"Udmurt Republic","code":"UD"},{"value":"Ulyanovsk Oblast","code":"ULY"},{"value":"Vladimir Oblast","code":"VLA"},{"value":"Volgograd Oblast","code":"VGG"},{"value":"Vologda Oblast","code":"VLG"},{"value":"Voronezh Oblast","code":"VOR"},{"value":"Yamalo-Nenets Autonomous Okrug","code":"YAN"},{"value":"Yaroslavl Oblast","code":"YAR"},{"value":"Zabaykalsky Krai","code":"ZAB"}],"RW":[{"value":"Eastern Province","code":"02"},{"value":"Kigali district","code":"01"},{"value":"Northern Province","code":"03"},{"value":"Southern Province","code":"05"},{"value":"Western Province","code":"04"}],"SH":[{"value":"Saint Helena","code":"Saint Helena"}],"KN":[{"value":"Christ Church Nichola Town Parish","code":"01"},{"value":"Nevis","code":"N"},{"value":"Saint Anne Sandy Point Parish","code":"02"},{"value":"Saint George Gingerland Parish","code":"04"},{"value":"Saint James Windward Parish","code":"05"},{"value":"Saint John Capisterre Parish","code":"06"},{"value":"Saint John Figtree Parish","code":"07"},{"value":"Saint Kitts","code":"K"},{"value":"Saint Mary Cayon Parish","code":"08"},{"value":"Saint Paul Capisterre Parish","code":"09"},{"value":"Saint Paul Charlestown Parish","code":"10"},{"value":"Saint Peter Basseterre Parish","code":"11"},{"value":"Saint Thomas Lowland Parish","code":"12"},{"value":"Saint Thomas Middle Island Parish","code":"13"},{"value":"Trinity Palmetto Point Parish","code":"15"}],"LC":[{"value":"Anse la Raye Quarter","code":"01"},{"value":"Canaries","code":"12"},{"value":"Castries Quarter","code":"02"},{"value":"Choiseul Quarter","code":"03"},{"value":"Dauphin Quarter","code":"04"},{"value":"Dennery Quarter","code":"05"},{"value":"Gros Islet Quarter","code":"06"},{"value":"Laborie Quarter","code":"07"},{"value":"Micoud Quarter","code":"08"},{"value":"Praslin Quarter","code":"09"},{"value":"Soufrière Quarter","code":"10"},{"value":"Vieux Fort Quarter","code":"11"}],"PM":[{"value":"Saint Pierre and Miquelon","code":"Saint Pierre and Miquelon"}],"VC":[{"value":"Charlotte Parish","code":"01"},{"value":"Grenadines Parish","code":"06"},{"value":"Saint Andrew Parish","code":"02"},{"value":"Saint David Parish","code":"03"},{"value":"Saint George Parish","code":"04"},{"value":"Saint Patrick Parish","code":"05"}],"BL":[{"value":"Saint-Barthelemy","code":"Saint-Barthelemy"}],"MF":[{"value":"Saint-Martin (French part)","code":"Saint-Martin (French part)"}],"WS":[{"value":"A'ana","code":"AA"},{"value":"Aiga-i-le-Tai","code":"AL"},{"value":"Atua","code":"AT"},{"value":"Fa'asaleleaga","code":"FA"},{"value":"Gaga'emauga","code":"GE"},{"value":"Gaga'ifomauga","code":"GI"},{"value":"Palauli","code":"PA"},{"value":"Satupa'itea","code":"SA"},{"value":"Tuamasaga","code":"TU"},{"value":"Va'a-o-Fonoti","code":"VF"},{"value":"Vaisigano","code":"VS"}],"SM":[{"value":"Acquaviva","code":"01"},{"value":"Borgo Maggiore","code":"06"},{"value":"Chiesanuova","code":"02"},{"value":"Domagnano","code":"03"},{"value":"Faetano","code":"04"},{"value":"Fiorentino","code":"05"},{"value":"Montegiardino","code":"08"},{"value":"San Marino","code":"07"},{"value":"Serravalle","code":"09"}],"ST":[{"value":"Príncipe Province","code":"P"},{"value":"São Tomé Province","code":"S"}],"SA":[{"value":"'Asir","code":"14"},{"value":"Al Bahah","code":"11"},{"value":"Al Jawf","code":"12"},{"value":"Al Madinah","code":"03"},{"value":"Al-Qassim","code":"05"},{"value":"Eastern Province","code":"04"},{"value":"Ha'il","code":"06"},{"value":"Jizan","code":"09"},{"value":"Makkah","code":"02"},{"value":"Najran","code":"10"},{"value":"Northern Borders","code":"08"},{"value":"Riyadh","code":"01"},{"value":"Tabuk","code":"07"}],"SN":[{"value":"Dakar","code":"DK"},{"value":"Diourbel Region","code":"DB"},{"value":"Fatick","code":"FK"},{"value":"Kaffrine","code":"KA"},{"value":"Kaolack","code":"KL"},{"value":"Kédougou","code":"KE"},{"value":"Kolda","code":"KD"},{"value":"Louga","code":"LG"},{"value":"Matam","code":"MT"},{"value":"Saint-Louis","code":"SL"},{"value":"Sédhiou","code":"SE"},{"value":"Tambacounda Region","code":"TC"},{"value":"Thiès Region","code":"TH"},{"value":"Ziguinchor","code":"ZG"}],"RS":[{"value":"Belgrade","code":"00"},{"value":"Bor District","code":"14"},{"value":"Braničevo District","code":"11"},{"value":"Central Banat District","code":"02"},{"value":"Jablanica District","code":"23"},{"value":"Kolubara District","code":"09"},{"value":"Mačva District","code":"08"},{"value":"Moravica District","code":"17"},{"value":"Nišava District","code":"20"},{"value":"North Bačka District","code":"01"},{"value":"North Banat District","code":"03"},{"value":"Pčinja District","code":"24"},{"value":"Pirot District","code":"22"},{"value":"Podunavlje District","code":"10"},{"value":"Pomoravlje District","code":"13"},{"value":"Rasina District","code":"19"},{"value":"Raška District","code":"18"},{"value":"South Bačka District","code":"06"},{"value":"South Banat District","code":"04"},{"value":"Srem District","code":"07"},{"value":"Šumadija District","code":"12"},{"value":"Toplica District","code":"21"},{"value":"Vojvodina","code":"VO"},{"value":"West Bačka District","code":"05"},{"value":"Zaječar District","code":"15"},{"value":"Zlatibor District","code":"16"}],"SC":[{"value":"Anse Boileau","code":"02"},{"value":"Anse Royale","code":"05"},{"value":"Anse-aux-Pins","code":"01"},{"value":"Au Cap","code":"04"},{"value":"Baie Lazare","code":"06"},{"value":"Baie Sainte Anne","code":"07"},{"value":"Beau Vallon","code":"08"},{"value":"Bel Air","code":"09"},{"value":"Bel Ombre","code":"10"},{"value":"Cascade","code":"11"},{"value":"Glacis","code":"12"},{"value":"Grand'Anse Mahé","code":"13"},{"value":"Grand'Anse Praslin","code":"14"},{"value":"La Digue","code":"15"},{"value":"La Rivière Anglaise","code":"16"},{"value":"Les Mamelles","code":"24"},{"value":"Mont Buxton","code":"17"},{"value":"Mont Fleuri","code":"18"},{"value":"Plaisance","code":"19"},{"value":"Pointe La Rue","code":"20"},{"value":"Port Glaud","code":"21"},{"value":"Roche Caiman","code":"25"},{"value":"Saint Louis","code":"22"},{"value":"Takamaka","code":"23"}],"SL":[{"value":"Eastern Province","code":"E"},{"value":"Northern Province","code":"N"},{"value":"Southern Province","code":"S"},{"value":"Western Area","code":"W"}],"SG":[{"value":"Central Singapore","code":"01"},{"value":"North East","code":"02"},{"value":"North West","code":"03"},{"value":"South East","code":"04"},{"value":"South West","code":"05"}],"SX":[{"value":"Sint Maarten (Dutch part)","code":"Sint Maarten (Dutch part)"}],"SK":[{"value":"Banská Bystrica Region","code":"BC"},{"value":"Bratislava Region","code":"BL"},{"value":"Košice Region","code":"KI"},{"value":"Nitra Region","code":"NI"},{"value":"Prešov Region","code":"PV"},{"value":"Trenčín Region","code":"TC"},{"value":"Trnava Region","code":"TA"},{"value":"Žilina Region","code":"ZI"}],"SI":[{"value":"Ajdovščina Municipality","code":"001"},{"value":"Ankaran Municipality","code":"213"},{"value":"Beltinci Municipality","code":"002"},{"value":"Benedikt Municipality","code":"148"},{"value":"Bistrica ob Sotli Municipality","code":"149"},{"value":"Bled Municipality","code":"003"},{"value":"Bloke Municipality","code":"150"},{"value":"Bohinj Municipality","code":"004"},{"value":"Borovnica Municipality","code":"005"},{"value":"Bovec Municipality","code":"006"},{"value":"Braslovče Municipality","code":"151"},{"value":"Brda Municipality","code":"007"},{"value":"Brežice Municipality","code":"009"},{"value":"Brezovica Municipality","code":"008"},{"value":"Cankova Municipality","code":"152"},{"value":"Cerklje na Gorenjskem Municipality","code":"012"},{"value":"Cerknica Municipality","code":"013"},{"value":"Cerkno Municipality","code":"014"},{"value":"Cerkvenjak Municipality","code":"153"},{"value":"City Municipality of Celje","code":"011"},{"value":"City Municipality of Novo Mesto","code":"085"},{"value":"Črenšovci Municipality","code":"015"},{"value":"Črna na Koroškem Municipality","code":"016"},{"value":"Črnomelj Municipality","code":"017"},{"value":"Destrnik Municipality","code":"018"},{"value":"Divača Municipality","code":"019"},{"value":"Dobje Municipality","code":"154"},{"value":"Dobrepolje Municipality","code":"020"},{"value":"Dobrna Municipality","code":"155"},{"value":"Dobrova–Polhov Gradec Municipality","code":"021"},{"value":"Dobrovnik Municipality","code":"156"},{"value":"Dol pri Ljubljani Municipality","code":"022"},{"value":"Dolenjske Toplice Municipality","code":"157"},{"value":"Domžale Municipality","code":"023"},{"value":"Dornava Municipality","code":"024"},{"value":"Dravograd Municipality","code":"025"},{"value":"Duplek Municipality","code":"026"},{"value":"Gorenja Vas–Poljane Municipality","code":"027"},{"value":"Gorišnica Municipality","code":"028"},{"value":"Gorje Municipality","code":"207"},{"value":"Gornja Radgona Municipality","code":"029"},{"value":"Gornji Grad Municipality","code":"030"},{"value":"Gornji Petrovci Municipality","code":"031"},{"value":"Grad Municipality","code":"158"},{"value":"Grosuplje Municipality","code":"032"},{"value":"Hajdina Municipality","code":"159"},{"value":"Hoče–Slivnica Municipality","code":"160"},{"value":"Hodoš Municipality","code":"161"},{"value":"Horjul Municipality","code":"162"},{"value":"Hrastnik Municipality","code":"034"},{"value":"Hrpelje–Kozina Municipality","code":"035"},{"value":"Idrija Municipality","code":"036"},{"value":"Ig Municipality","code":"037"},{"value":"Ivančna Gorica Municipality","code":"039"},{"value":"Izola Municipality","code":"040"},{"value":"Jesenice Municipality","code":"041"},{"value":"Jezersko Municipality","code":"163"},{"value":"Juršinci Municipality","code":"042"},{"value":"Kamnik Municipality","code":"043"},{"value":"Kanal ob Soči Municipality","code":"044"},{"value":"Kidričevo Municipality","code":"045"},{"value":"Kobarid Municipality","code":"046"},{"value":"Kobilje Municipality","code":"047"},{"value":"Kočevje Municipality","code":"048"},{"value":"Komen Municipality","code":"049"},{"value":"Komenda Municipality","code":"164"},{"value":"Koper City Municipality","code":"050"},{"value":"Kostanjevica na Krki Municipality","code":"197"},{"value":"Kostel Municipality","code":"165"},{"value":"Kozje Municipality","code":"051"},{"value":"Kranj City Municipality","code":"052"},{"value":"Kranjska Gora Municipality","code":"053"},{"value":"Križevci Municipality","code":"166"},{"value":"Kungota","code":"055"},{"value":"Kuzma Municipality","code":"056"},{"value":"Laško Municipality","code":"057"},{"value":"Lenart Municipality","code":"058"},{"value":"Lendava Municipality","code":"059"},{"value":"Litija Municipality","code":"060"},{"value":"Ljubljana City Municipality","code":"061"},{"value":"Ljubno Municipality","code":"062"},{"value":"Ljutomer Municipality","code":"063"},{"value":"Log–Dragomer Municipality","code":"208"},{"value":"Logatec Municipality","code":"064"},{"value":"Loška Dolina Municipality","code":"065"},{"value":"Loški Potok Municipality","code":"066"},{"value":"Lovrenc na Pohorju Municipality","code":"167"},{"value":"Luče Municipality","code":"067"},{"value":"Lukovica Municipality","code":"068"},{"value":"Majšperk Municipality","code":"069"},{"value":"Makole Municipality","code":"198"},{"value":"Maribor City Municipality","code":"070"},{"value":"Markovci Municipality","code":"168"},{"value":"Medvode Municipality","code":"071"},{"value":"Mengeš Municipality","code":"072"},{"value":"Metlika Municipality","code":"073"},{"value":"Mežica Municipality","code":"074"},{"value":"Miklavž na Dravskem Polju Municipality","code":"169"},{"value":"Miren–Kostanjevica Municipality","code":"075"},{"value":"Mirna Municipality","code":"212"},{"value":"Mirna Peč Municipality","code":"170"},{"value":"Mislinja Municipality","code":"076"},{"value":"Mokronog–Trebelno Municipality","code":"199"},{"value":"Moravče Municipality","code":"077"},{"value":"Moravske Toplice Municipality","code":"078"},{"value":"Mozirje Municipality","code":"079"},{"value":"Municipality of Apače","code":"195"},{"value":"Municipality of Cirkulane","code":"196"},{"value":"Municipality of Ilirska Bistrica","code":"038"},{"value":"Municipality of Krško","code":"054"},{"value":"Municipality of Škofljica","code":"123"},{"value":"Murska Sobota City Municipality","code":"080"},{"value":"Muta Municipality","code":"081"},{"value":"Naklo Municipality","code":"082"},{"value":"Nazarje Municipality","code":"083"},{"value":"Nova Gorica City Municipality","code":"084"},{"value":"Odranci Municipality","code":"086"},{"value":"Oplotnica","code":"171"},{"value":"Ormož Municipality","code":"087"},{"value":"Osilnica Municipality","code":"088"},{"value":"Pesnica Municipality","code":"089"},{"value":"Piran Municipality","code":"090"},{"value":"Pivka Municipality","code":"091"},{"value":"Podčetrtek Municipality","code":"092"},{"value":"Podlehnik Municipality","code":"172"},{"value":"Podvelka Municipality","code":"093"},{"value":"Poljčane Municipality","code":"200"},{"value":"Polzela Municipality","code":"173"},{"value":"Postojna Municipality","code":"094"},{"value":"Prebold Municipality","code":"174"},{"value":"Preddvor Municipality","code":"095"},{"value":"Prevalje Municipality","code":"175"},{"value":"Ptuj City Municipality","code":"096"},{"value":"Puconci Municipality","code":"097"},{"value":"Rače–Fram Municipality","code":"098"},{"value":"Radeče Municipality","code":"099"},{"value":"Radenci Municipality","code":"100"},{"value":"Radlje ob Dravi Municipality","code":"101"},{"value":"Radovljica Municipality","code":"102"},{"value":"Ravne na Koroškem Municipality","code":"103"},{"value":"Razkrižje Municipality","code":"176"},{"value":"Rečica ob Savinji Municipality","code":"209"},{"value":"Renče–Vogrsko Municipality","code":"201"},{"value":"Ribnica Municipality","code":"104"},{"value":"Ribnica na Pohorju Municipality","code":"177"},{"value":"Rogaška Slatina Municipality","code":"106"},{"value":"Rogašovci Municipality","code":"105"},{"value":"Rogatec Municipality","code":"107"},{"value":"Ruše Municipality","code":"108"},{"value":"Šalovci Municipality","code":"033"},{"value":"Selnica ob Dravi Municipality","code":"178"},{"value":"Semič Municipality","code":"109"},{"value":"Šempeter–Vrtojba Municipality","code":"183"},{"value":"Šenčur Municipality","code":"117"},{"value":"Šentilj Municipality","code":"118"},{"value":"Šentjernej Municipality","code":"119"},{"value":"Šentjur Municipality","code":"120"},{"value":"Šentrupert Municipality","code":"211"},{"value":"Sevnica Municipality","code":"110"},{"value":"Sežana Municipality","code":"111"},{"value":"Škocjan Municipality","code":"121"},{"value":"Škofja Loka Municipality","code":"122"},{"value":"Slovenj Gradec City Municipality","code":"112"},{"value":"Slovenska Bistrica Municipality","code":"113"},{"value":"Slovenske Konjice Municipality","code":"114"},{"value":"Šmarje pri Jelšah Municipality","code":"124"},{"value":"Šmarješke Toplice Municipality","code":"206"},{"value":"Šmartno ob Paki Municipality","code":"125"},{"value":"Šmartno pri Litiji Municipality","code":"194"},{"value":"Sodražica Municipality","code":"179"},{"value":"Solčava Municipality","code":"180"},{"value":"Šoštanj Municipality","code":"126"},{"value":"Središče ob Dravi","code":"202"},{"value":"Starše Municipality","code":"115"},{"value":"Štore Municipality","code":"127"},{"value":"Straža Municipality","code":"203"},{"value":"Sveta Ana Municipality","code":"181"},{"value":"Sveta Trojica v Slovenskih Goricah Municipality","code":"204"},{"value":"Sveti Andraž v Slovenskih Goricah Municipality","code":"182"},{"value":"Sveti Jurij ob Ščavnici Municipality","code":"116"},{"value":"Sveti Jurij v Slovenskih Goricah Municipality","code":"210"},{"value":"Sveti Tomaž Municipality","code":"205"},{"value":"Tabor Municipality","code":"184"},{"value":"Tišina Municipality","code":"010"},{"value":"Tolmin Municipality","code":"128"},{"value":"Trbovlje Municipality","code":"129"},{"value":"Trebnje Municipality","code":"130"},{"value":"Trnovska Vas Municipality","code":"185"},{"value":"Tržič Municipality","code":"131"},{"value":"Trzin Municipality","code":"186"},{"value":"Turnišče Municipality","code":"132"},{"value":"Velika Polana Municipality","code":"187"},{"value":"Velike Lašče Municipality","code":"134"},{"value":"Veržej Municipality","code":"188"},{"value":"Videm Municipality","code":"135"},{"value":"Vipava Municipality","code":"136"},{"value":"Vitanje Municipality","code":"137"},{"value":"Vodice Municipality","code":"138"},{"value":"Vojnik Municipality","code":"139"},{"value":"Vransko Municipality","code":"189"},{"value":"Vrhnika Municipality","code":"140"},{"value":"Vuzenica Municipality","code":"141"},{"value":"Zagorje ob Savi Municipality","code":"142"},{"value":"Žalec Municipality","code":"190"},{"value":"Zavrč Municipality","code":"143"},{"value":"Železniki Municipality","code":"146"},{"value":"Žetale Municipality","code":"191"},{"value":"Žiri Municipality","code":"147"},{"value":"Žirovnica Municipality","code":"192"},{"value":"Zreče Municipality","code":"144"},{"value":"Žužemberk Municipality","code":"193"}],"SB":[{"value":"Central Province","code":"CE"},{"value":"Choiseul Province","code":"CH"},{"value":"Guadalcanal Province","code":"GU"},{"value":"Honiara","code":"CT"},{"value":"Isabel Province","code":"IS"},{"value":"Makira-Ulawa Province","code":"MK"},{"value":"Malaita Province","code":"ML"},{"value":"Rennell and Bellona Province","code":"RB"},{"value":"Temotu Province","code":"TE"},{"value":"Western Province","code":"WE"}],"SO":[{"value":"Awdal Region","code":"AW"},{"value":"Bakool","code":"BK"},{"value":"Banaadir","code":"BN"},{"value":"Bari","code":"BR"},{"value":"Bay","code":"BY"},{"value":"Galguduud","code":"GA"},{"value":"Gedo","code":"GE"},{"value":"Hiran","code":"HI"},{"value":"Lower Juba","code":"JH"},{"value":"Lower Shebelle","code":"SH"},{"value":"Middle Juba","code":"JD"},{"value":"Middle Shebelle","code":"SD"},{"value":"Mudug","code":"MU"},{"value":"Nugal","code":"NU"},{"value":"Sanaag Region","code":"SA"},{"value":"Togdheer Region","code":"TO"}],"ZA":[{"value":"Eastern Cape","code":"EC"},{"value":"Free State","code":"FS"},{"value":"Gauteng","code":"GP"},{"value":"KwaZulu-Natal","code":"KZN"},{"value":"Limpopo","code":"LP"},{"value":"Mpumalanga","code":"MP"},{"value":"North West","code":"NW"},{"value":"Northern Cape","code":"NC"},{"value":"Western Cape","code":"WC"}],"GS":[{"value":"South Georgia","code":"South Georgia"}],"KR":[{"value":"Busan","code":"26"},{"value":"Daegu","code":"27"},{"value":"Daejeon","code":"30"},{"value":"Gangwon Province","code":"42"},{"value":"Gwangju","code":"29"},{"value":"Gyeonggi Province","code":"41"},{"value":"Incheon","code":"28"},{"value":"Jeju","code":"49"},{"value":"North Chungcheong Province","code":"43"},{"value":"North Gyeongsang Province","code":"47"},{"value":"North Jeolla Province","code":"45"},{"value":"Sejong City","code":"50"},{"value":"Seoul","code":"11"},{"value":"South Chungcheong Province","code":"44"},{"value":"South Gyeongsang Province","code":"48"},{"value":"South Jeolla Province","code":"46"},{"value":"Ulsan","code":"31"}],"SS":[{"value":"Central Equatoria","code":"EC"},{"value":"Eastern Equatoria","code":"EE"},{"value":"Jonglei State","code":"JG"},{"value":"Lakes","code":"LK"},{"value":"Northern Bahr el Ghazal","code":"BN"},{"value":"Unity","code":"UY"},{"value":"Upper Nile","code":"NU"},{"value":"Warrap","code":"WR"},{"value":"Western Bahr el Ghazal","code":"BW"},{"value":"Western Equatoria","code":"EW"}],"ES":[{"value":"A Coruña","code":"C"},{"value":"Albacete","code":"AB"},{"value":"Alicante","code":"A"},{"value":"Almeria","code":"AL"},{"value":"Araba","code":"VI"},{"value":"Asturias","code":"O"},{"value":"Ávila","code":"AV"},{"value":"Badajoz","code":"BA"},{"value":"Barcelona","code":"B"},{"value":"Bizkaia","code":"BI"},{"value":"Burgos","code":"BU"},{"value":"Caceres","code":"CC"},{"value":"Cádiz","code":"CA"},{"value":"Canarias","code":"CN"},{"value":"Cantabria","code":"S"},{"value":"Castellón","code":"CS"},{"value":"Ceuta","code":"CE"},{"value":"Ciudad Real","code":"CR"},{"value":"Córdoba","code":"CO"},{"value":"Cuenca","code":"CU"},{"value":"Gipuzkoa","code":"SS"},{"value":"Girona","code":"GI"},{"value":"Granada","code":"GR"},{"value":"Guadalajara","code":"GU"},{"value":"Huelva","code":"H"},{"value":"Huesca","code":"HU"},{"value":"Islas Baleares","code":"PM"},{"value":"Jaén","code":"J"},{"value":"La Rioja","code":"LO"},{"value":"Las Palmas","code":"GC"},{"value":"León","code":"LE"},{"value":"Lleida","code":"L"},{"value":"Lugo","code":"LU"},{"value":"Madrid","code":"M"},{"value":"Málaga","code":"MA"},{"value":"Melilla","code":"ML"},{"value":"Murcia","code":"MU"},{"value":"Navarra","code":"NA"},{"value":"Ourense","code":"OR"},{"value":"Palencia","code":"P"},{"value":"Pontevedra","code":"PO"},{"value":"Salamanca","code":"SA"},{"value":"Santa Cruz de Tenerife","code":"TF"},{"value":"Segovia","code":"SG"},{"value":"Sevilla","code":"SE"},{"value":"Soria","code":"SO"},{"value":"Tarragona","code":"T"},{"value":"Teruel","code":"TE"},{"value":"Toledo","code":"TO"},{"value":"Valencia","code":"V"},{"value":"Valladolid","code":"VA"},{"value":"Zamora","code":"ZA"},{"value":"Zaragoza","code":"Z"}],"LK":[{"value":"Ampara District","code":"52"},{"value":"Anuradhapura District","code":"71"},{"value":"Badulla District","code":"81"},{"value":"Batticaloa District","code":"51"},{"value":"Central Province","code":"2"},{"value":"Colombo District","code":"11"},{"value":"Eastern Province","code":"5"},{"value":"Galle District","code":"31"},{"value":"Gampaha District","code":"12"},{"value":"Hambantota District","code":"33"},{"value":"Jaffna District","code":"41"},{"value":"Kalutara District","code":"13"},{"value":"Kandy District","code":"21"},{"value":"Kegalle District","code":"92"},{"value":"Kilinochchi District","code":"42"},{"value":"Mannar District","code":"43"},{"value":"Matale District","code":"22"},{"value":"Matara District","code":"32"},{"value":"Monaragala District","code":"82"},{"value":"Mullaitivu District","code":"45"},{"value":"North Central Province","code":"7"},{"value":"North Western Province","code":"6"},{"value":"Northern Province","code":"4"},{"value":"Nuwara Eliya District","code":"23"},{"value":"Polonnaruwa District","code":"72"},{"value":"Puttalam District","code":"62"},{"value":"Ratnapura district","code":"91"},{"value":"Sabaragamuwa Province","code":"9"},{"value":"Southern Province","code":"3"},{"value":"Trincomalee District","code":"53"},{"value":"Uva Province","code":"8"},{"value":"Vavuniya District","code":"44"},{"value":"Western Province","code":"1"}],"SD":[{"value":"Al Jazirah","code":"GZ"},{"value":"Al Qadarif","code":"GD"},{"value":"Blue Nile","code":"NB"},{"value":"Central Darfur","code":"DC"},{"value":"East Darfur","code":"DE"},{"value":"Kassala","code":"KA"},{"value":"Khartoum","code":"KH"},{"value":"North Darfur","code":"DN"},{"value":"North Kordofan","code":"KN"},{"value":"Northern","code":"NO"},{"value":"Red Sea","code":"RS"},{"value":"River Nile","code":"NR"},{"value":"Sennar","code":"SI"},{"value":"South Darfur","code":"DS"},{"value":"South Kordofan","code":"KS"},{"value":"West Darfur","code":"DW"},{"value":"West Kordofan","code":"GK"},{"value":"White Nile","code":"NW"}],"SR":[{"value":"Brokopondo District","code":"BR"},{"value":"Commewijne District","code":"CM"},{"value":"Coronie District","code":"CR"},{"value":"Marowijne District","code":"MA"},{"value":"Nickerie District","code":"NI"},{"value":"Para District","code":"PR"},{"value":"Paramaribo District","code":"PM"},{"value":"Saramacca District","code":"SA"},{"value":"Sipaliwini District","code":"SI"},{"value":"Wanica District","code":"WA"}],"SJ":[{"value":"Svalbard and Jan Mayen Islands","code":"Svalbard and Jan Mayen Islands"}],"SE":[{"value":"Blekinge County","code":"K"},{"value":"Dalarna County","code":"W"},{"value":"Gävleborg County","code":"X"},{"value":"Gotland County","code":"I"},{"value":"Halland County","code":"N"},{"value":"Jämtland County","code":"Z"},{"value":"Jönköping County","code":"F"},{"value":"Kalmar County","code":"H"},{"value":"Kronoberg County","code":"G"},{"value":"Norrbotten County","code":"BD"},{"value":"Örebro County","code":"T"},{"value":"Östergötland County","code":"E"},{"value":"Skåne County","code":"M"},{"value":"Södermanland County","code":"D"},{"value":"Stockholm County","code":"AB"},{"value":"Uppsala County","code":"C"},{"value":"Värmland County","code":"S"},{"value":"Västerbotten County","code":"AC"},{"value":"Västernorrland County","code":"Y"},{"value":"Västmanland County","code":"U"},{"value":"Västra Götaland County","code":"O"}],"CH":[{"value":"Aargau","code":"AG"},{"value":"Appenzell Ausserrhoden","code":"AR"},{"value":"Appenzell Innerrhoden","code":"AI"},{"value":"Basel-Land","code":"BL"},{"value":"Basel-Stadt","code":"BS"},{"value":"Bern","code":"BE"},{"value":"Fribourg","code":"FR"},{"value":"Geneva","code":"GE"},{"value":"Glarus","code":"GL"},{"value":"Graubünden","code":"GR"},{"value":"Jura","code":"JU"},{"value":"Lucerne","code":"LU"},{"value":"Neuchâtel","code":"NE"},{"value":"Nidwalden","code":"NW"},{"value":"Obwalden","code":"OW"},{"value":"Schaffhausen","code":"SH"},{"value":"Schwyz","code":"SZ"},{"value":"Solothurn","code":"SO"},{"value":"St. Gallen","code":"SG"},{"value":"Thurgau","code":"TG"},{"value":"Ticino","code":"TI"},{"value":"Uri","code":"UR"},{"value":"Valais","code":"VS"},{"value":"Vaud","code":"VD"},{"value":"Zug","code":"ZG"},{"value":"Zürich","code":"ZH"}],"SY":[{"value":"Al-Hasakah","code":"HA"},{"value":"Al-Raqqah","code":"RA"},{"value":"Aleppo","code":"HL"},{"value":"As-Suwayda","code":"SU"},{"value":"Damascus","code":"DI"},{"value":"Daraa","code":"DR"},{"value":"Deir ez-Zor","code":"DY"},{"value":"Hama","code":"HM"},{"value":"Homs","code":"HI"},{"value":"Idlib","code":"ID"},{"value":"Latakia","code":"LA"},{"value":"Quneitra","code":"QU"},{"value":"Rif Dimashq","code":"RD"},{"value":"Tartus","code":"TA"}],"TW":[{"value":"Changhua","code":"CHA"},{"value":"Chiayi","code":"CYI"},{"value":"Chiayi","code":"CYQ"},{"value":"Hsinchu","code":"HSQ"},{"value":"Hsinchu","code":"HSZ"},{"value":"Hualien","code":"HUA"},{"value":"Kaohsiung","code":"KHH"},{"value":"Keelung","code":"KEE"},{"value":"Kinmen","code":"KIN"},{"value":"Lienchiang","code":"LIE"},{"value":"Miaoli","code":"MIA"},{"value":"Nantou","code":"NAN"},{"value":"New Taipei","code":"NWT"},{"value":"Penghu","code":"PEN"},{"value":"Pingtung","code":"PIF"},{"value":"Taichung","code":"TXG"},{"value":"Tainan","code":"TNN"},{"value":"Taipei","code":"TPE"},{"value":"Taitung","code":"TTT"},{"value":"Taoyuan","code":"TAO"},{"value":"Yilan","code":"ILA"},{"value":"Yunlin","code":"YUN"}],"TJ":[{"value":"districts of Republican Subordination","code":"RA"},{"value":"Gorno-Badakhshan Autonomous Province","code":"GB"},{"value":"Khatlon Province","code":"KT"},{"value":"Sughd Province","code":"SU"}],"TZ":[{"value":"Arusha","code":"01"},{"value":"Dar es Salaam","code":"02"},{"value":"Dodoma","code":"03"},{"value":"Geita","code":"27"},{"value":"Iringa","code":"04"},{"value":"Kagera","code":"05"},{"value":"Katavi","code":"28"},{"value":"Kigoma","code":"08"},{"value":"Kilimanjaro","code":"09"},{"value":"Lindi","code":"12"},{"value":"Manyara","code":"26"},{"value":"Mara","code":"13"},{"value":"Mbeya","code":"14"},{"value":"Morogoro","code":"16"},{"value":"Mtwara","code":"17"},{"value":"Mwanza","code":"18"},{"value":"Njombe","code":"29"},{"value":"Pemba North","code":"06"},{"value":"Pemba South","code":"10"},{"value":"Pwani","code":"19"},{"value":"Rukwa","code":"20"},{"value":"Ruvuma","code":"21"},{"value":"Shinyanga","code":"22"},{"value":"Simiyu","code":"30"},{"value":"Singida","code":"23"},{"value":"Songwe","code":"31"},{"value":"Tabora","code":"24"},{"value":"Tanga","code":"25"},{"value":"Zanzibar North","code":"07"},{"value":"Zanzibar South","code":"11"},{"value":"Zanzibar West","code":"15"}],"TH":[{"value":"Amnat Charoen","code":"37"},{"value":"Ang Thong","code":"15"},{"value":"Bangkok","code":"10"},{"value":"Bueng Kan","code":"38"},{"value":"Buri Ram","code":"31"},{"value":"Chachoengsao","code":"24"},{"value":"Chai Nat","code":"18"},{"value":"Chaiyaphum","code":"36"},{"value":"Chanthaburi","code":"22"},{"value":"Chiang Mai","code":"50"},{"value":"Chiang Rai","code":"57"},{"value":"Chon Buri","code":"20"},{"value":"Chumphon","code":"86"},{"value":"Kalasin","code":"46"},{"value":"Kamphaeng Phet","code":"62"},{"value":"Kanchanaburi","code":"71"},{"value":"Khon Kaen","code":"40"},{"value":"Krabi","code":"81"},{"value":"Lampang","code":"52"},{"value":"Lamphun","code":"51"},{"value":"Loei","code":"42"},{"value":"Lop Buri","code":"16"},{"value":"Mae Hong Son","code":"58"},{"value":"Maha Sarakham","code":"44"},{"value":"Mukdahan","code":"49"},{"value":"Nakhon Nayok","code":"26"},{"value":"Nakhon Pathom","code":"73"},{"value":"Nakhon Phanom","code":"48"},{"value":"Nakhon Ratchasima","code":"30"},{"value":"Nakhon Sawan","code":"60"},{"value":"Nakhon Si Thammarat","code":"80"},{"value":"Nan","code":"55"},{"value":"Narathiwat","code":"96"},{"value":"Nong Bua Lam Phu","code":"39"},{"value":"Nong Khai","code":"43"},{"value":"Nonthaburi","code":"12"},{"value":"Pathum Thani","code":"13"},{"value":"Pattani","code":"94"},{"value":"Pattaya","code":"S"},{"value":"Phangnga","code":"82"},{"value":"Phatthalung","code":"93"},{"value":"Phayao","code":"56"},{"value":"Phetchabun","code":"67"},{"value":"Phetchaburi","code":"76"},{"value":"Phichit","code":"66"},{"value":"Phitsanulok","code":"65"},{"value":"Phra Nakhon Si Ayutthaya","code":"14"},{"value":"Phrae","code":"54"},{"value":"Phuket","code":"83"},{"value":"Prachin Buri","code":"25"},{"value":"Prachuap Khiri Khan","code":"77"},{"value":"Ranong","code":"85"},{"value":"Ratchaburi","code":"70"},{"value":"Rayong","code":"21"},{"value":"Roi Et","code":"45"},{"value":"Sa Kaeo","code":"27"},{"value":"Sakon Nakhon","code":"47"},{"value":"Samut Prakan","code":"11"},{"value":"Samut Sakhon","code":"74"},{"value":"Samut Songkhram","code":"75"},{"value":"Saraburi","code":"19"},{"value":"Satun","code":"91"},{"value":"Si Sa Ket","code":"33"},{"value":"Sing Buri","code":"17"},{"value":"Songkhla","code":"90"},{"value":"Sukhothai","code":"64"},{"value":"Suphan Buri","code":"72"},{"value":"Surat Thani","code":"84"},{"value":"Surin","code":"32"},{"value":"Tak","code":"63"},{"value":"Trang","code":"92"},{"value":"Trat","code":"23"},{"value":"Ubon Ratchathani","code":"34"},{"value":"Udon Thani","code":"41"},{"value":"Uthai Thani","code":"61"},{"value":"Uttaradit","code":"53"},{"value":"Yala","code":"95"},{"value":"Yasothon","code":"35"}],"BS":[{"value":"Acklins","code":"AK"},{"value":"Acklins and Crooked Islands","code":"AC"},{"value":"Berry Islands","code":"BY"},{"value":"Bimini","code":"BI"},{"value":"Black Point","code":"BP"},{"value":"Cat Island","code":"CI"},{"value":"Central Abaco","code":"CO"},{"value":"Central Andros","code":"CS"},{"value":"Central Eleuthera","code":"CE"},{"value":"Crooked Island","code":"CK"},{"value":"East Grand Bahama","code":"EG"},{"value":"Exuma","code":"EX"},{"value":"Freeport","code":"FP"},{"value":"Fresh Creek","code":"FC"},{"value":"Governor's Harbour","code":"GH"},{"value":"Grand Cay","code":"GC"},{"value":"Green Turtle Cay","code":"GT"},{"value":"Harbour Island","code":"HI"},{"value":"High Rock","code":"HR"},{"value":"Hope Town","code":"HT"},{"value":"Inagua","code":"IN"},{"value":"Kemps Bay","code":"KB"},{"value":"Long Island","code":"LI"},{"value":"Mangrove Cay","code":"MC"},{"value":"Marsh Harbour","code":"MH"},{"value":"Mayaguana District","code":"MG"},{"value":"New Providence","code":"NP"},{"value":"Nichollstown and Berry Islands","code":"NB"},{"value":"North Abaco","code":"NO"},{"value":"North Andros","code":"NS"},{"value":"North Eleuthera","code":"NE"},{"value":"Ragged Island","code":"RI"},{"value":"Rock Sound","code":"RS"},{"value":"Rum Cay District","code":"RC"},{"value":"San Salvador and Rum Cay","code":"SR"},{"value":"San Salvador Island","code":"SS"},{"value":"Sandy Point","code":"SP"},{"value":"South Abaco","code":"SO"},{"value":"South Andros","code":"SA"},{"value":"South Eleuthera","code":"SE"},{"value":"Spanish Wells","code":"SW"},{"value":"West Grand Bahama","code":"WG"}],"GM":[{"value":"Banjul","code":"B"},{"value":"Central River Division","code":"M"},{"value":"Lower River Division","code":"L"},{"value":"North Bank Division","code":"N"},{"value":"Upper River Division","code":"U"},{"value":"West Coast Division","code":"W"}],"TL":[{"value":"Aileu municipality","code":"AL"},{"value":"Ainaro Municipality","code":"AN"},{"value":"Baucau Municipality","code":"BA"},{"value":"Bobonaro Municipality","code":"BO"},{"value":"Cova Lima Municipality","code":"CO"},{"value":"Dili municipality","code":"DI"},{"value":"Ermera District","code":"ER"},{"value":"Lautém Municipality","code":"LA"},{"value":"Liquiçá Municipality","code":"LI"},{"value":"Manatuto District","code":"MT"},{"value":"Manufahi Municipality","code":"MF"},{"value":"Viqueque Municipality","code":"VI"}],"TG":[{"value":"Centrale Region","code":"C"},{"value":"Kara Region","code":"K"},{"value":"Maritime","code":"M"},{"value":"Plateaux Region","code":"P"},{"value":"Savanes Region","code":"S"}],"TK":[{"value":"Tokelau","code":"Tokelau"}],"TO":[{"value":"Haʻapai","code":"02"},{"value":"ʻEua","code":"01"},{"value":"Niuas","code":"03"},{"value":"Tongatapu","code":"04"},{"value":"Vavaʻu","code":"05"}],"TT":[{"value":"Arima","code":"ARI"},{"value":"Chaguanas","code":"CHA"},{"value":"Couva-Tabaquite-Talparo Regional Corporation","code":"CTT"},{"value":"Diego Martin Regional Corporation","code":"DMN"},{"value":"Eastern Tobago","code":"ETO"},{"value":"Penal-Debe Regional Corporation","code":"PED"},{"value":"Point Fortin","code":"PTF"},{"value":"Port of Spain","code":"POS"},{"value":"Princes Town Regional Corporation","code":"PRT"},{"value":"Rio Claro-Mayaro Regional Corporation","code":"MRC"},{"value":"San Fernando","code":"SFO"},{"value":"San Juan-Laventille Regional Corporation","code":"SJL"},{"value":"Sangre Grande Regional Corporation","code":"SGE"},{"value":"Siparia Regional Corporation","code":"SIP"},{"value":"Tunapuna-Piarco Regional Corporation","code":"TUP"},{"value":"Western Tobago","code":"WTO"}],"TN":[{"value":"Ariana","code":"12"},{"value":"Béja","code":"31"},{"value":"Ben Arous","code":"13"},{"value":"Bizerte","code":"23"},{"value":"Gabès","code":"81"},{"value":"Gafsa","code":"71"},{"value":"Jendouba","code":"32"},{"value":"Kairouan","code":"41"},{"value":"Kasserine","code":"42"},{"value":"Kebili","code":"73"},{"value":"Kef","code":"33"},{"value":"Mahdia","code":"53"},{"value":"Manouba","code":"14"},{"value":"Medenine","code":"82"},{"value":"Monastir","code":"52"},{"value":"Nabeul","code":"21"},{"value":"Sfax","code":"61"},{"value":"Sidi Bouzid","code":"43"},{"value":"Siliana","code":"34"},{"value":"Sousse","code":"51"},{"value":"Tataouine","code":"83"},{"value":"Tozeur","code":"72"},{"value":"Tunis","code":"11"},{"value":"Zaghouan","code":"22"}],"TR":[{"value":"Adana","code":"01"},{"value":"Adıyaman","code":"02"},{"value":"Afyonkarahisar","code":"03"},{"value":"Ağrı","code":"04"},{"value":"Aksaray","code":"68"},{"value":"Amasya","code":"05"},{"value":"Ankara","code":"06"},{"value":"Antalya","code":"07"},{"value":"Ardahan","code":"75"},{"value":"Artvin","code":"08"},{"value":"Aydın","code":"09"},{"value":"Balıkesir","code":"10"},{"value":"Bartın","code":"74"},{"value":"Batman","code":"72"},{"value":"Bayburt","code":"69"},{"value":"Bilecik","code":"11"},{"value":"Bingöl","code":"12"},{"value":"Bitlis","code":"13"},{"value":"Bolu","code":"14"},{"value":"Burdur","code":"15"},{"value":"Bursa","code":"16"},{"value":"Çanakkale","code":"17"},{"value":"Çankırı","code":"18"},{"value":"Çorum","code":"19"},{"value":"Denizli","code":"20"},{"value":"Diyarbakır","code":"21"},{"value":"Düzce","code":"81"},{"value":"Edirne","code":"22"},{"value":"Elazığ","code":"23"},{"value":"Erzincan","code":"24"},{"value":"Erzurum","code":"25"},{"value":"Eskişehir","code":"26"},{"value":"Gaziantep","code":"27"},{"value":"Giresun","code":"28"},{"value":"Gümüşhane","code":"29"},{"value":"Hakkâri","code":"30"},{"value":"Hatay","code":"31"},{"value":"Iğdır","code":"76"},{"value":"Isparta","code":"32"},{"value":"İstanbul","code":"34"},{"value":"İzmir","code":"35"},{"value":"Kahramanmaraş","code":"46"},{"value":"Karabük","code":"78"},{"value":"Karaman","code":"70"},{"value":"Kars","code":"36"},{"value":"Kastamonu","code":"37"},{"value":"Kayseri","code":"38"},{"value":"Kilis","code":"79"},{"value":"Kırıkkale","code":"71"},{"value":"Kırklareli","code":"39"},{"value":"Kırşehir","code":"40"},{"value":"Kocaeli","code":"41"},{"value":"Konya","code":"42"},{"value":"Kütahya","code":"43"},{"value":"Malatya","code":"44"},{"value":"Manisa","code":"45"},{"value":"Mardin","code":"47"},{"value":"Mersin","code":"33"},{"value":"Muğla","code":"48"},{"value":"Muş","code":"49"},{"value":"Nevşehir","code":"50"},{"value":"Niğde","code":"51"},{"value":"Ordu","code":"52"},{"value":"Osmaniye","code":"80"},{"value":"Rize","code":"53"},{"value":"Sakarya","code":"54"},{"value":"Samsun","code":"55"},{"value":"Şanlıurfa","code":"63"},{"value":"Siirt","code":"56"},{"value":"Sinop","code":"57"},{"value":"Sivas","code":"58"},{"value":"Şırnak","code":"73"},{"value":"Tekirdağ","code":"59"},{"value":"Tokat","code":"60"},{"value":"Trabzon","code":"61"},{"value":"Tunceli","code":"62"},{"value":"Uşak","code":"64"},{"value":"Van","code":"65"},{"value":"Yalova","code":"77"},{"value":"Yozgat","code":"66"},{"value":"Zonguldak","code":"67"}],"TM":[{"value":"Ahal Region","code":"A"},{"value":"Ashgabat","code":"S"},{"value":"Balkan Region","code":"B"},{"value":"Daşoguz Region","code":"D"},{"value":"Lebap Region","code":"L"},{"value":"Mary Region","code":"M"}],"TC":[{"value":"Turks and Caicos Islands","code":"Turks and Caicos Islands"}],"TV":[{"value":"Funafuti","code":"FUN"},{"value":"Nanumanga","code":"NMG"},{"value":"Nanumea","code":"NMA"},{"value":"Niutao Island Council","code":"NIT"},{"value":"Nui","code":"NUI"},{"value":"Nukufetau","code":"NKF"},{"value":"Nukulaelae","code":"NKL"},{"value":"Vaitupu","code":"VAI"}],"UG":[{"value":"Abim District","code":"314"},{"value":"Adjumani District","code":"301"},{"value":"Agago District","code":"322"},{"value":"Alebtong District","code":"323"},{"value":"Amolatar District","code":"315"},{"value":"Amudat District","code":"324"},{"value":"Amuria District","code":"216"},{"value":"Amuru District","code":"316"},{"value":"Apac District","code":"302"},{"value":"Arua District","code":"303"},{"value":"Budaka District","code":"217"},{"value":"Bududa District","code":"218"},{"value":"Bugiri District","code":"201"},{"value":"Buhweju District","code":"420"},{"value":"Buikwe District","code":"117"},{"value":"Bukedea District","code":"219"},{"value":"Bukomansimbi District","code":"118"},{"value":"Bukwo District","code":"220"},{"value":"Bulambuli District","code":"225"},{"value":"Buliisa District","code":"416"},{"value":"Bundibugyo District","code":"401"},{"value":"Bunyangabu District","code":"430"},{"value":"Bushenyi District","code":"402"},{"value":"Busia District","code":"202"},{"value":"Butaleja District","code":"221"},{"value":"Butambala District","code":"119"},{"value":"Butebo District","code":"233"},{"value":"Buvuma District","code":"120"},{"value":"Buyende District","code":"226"},{"value":"Central Region","code":"C"},{"value":"Dokolo District","code":"317"},{"value":"Eastern Region","code":"E"},{"value":"Gomba District","code":"121"},{"value":"Gulu District","code":"304"},{"value":"Ibanda District","code":"417"},{"value":"Iganga District","code":"203"},{"value":"Isingiro District","code":"418"},{"value":"Jinja District","code":"204"},{"value":"Kaabong District","code":"318"},{"value":"Kabale District","code":"404"},{"value":"Kabarole District","code":"405"},{"value":"Kaberamaido District","code":"213"},{"value":"Kagadi District","code":"427"},{"value":"Kakumiro District","code":"428"},{"value":"Kalangala District","code":"101"},{"value":"Kaliro District","code":"222"},{"value":"Kalungu District","code":"122"},{"value":"Kampala District","code":"102"},{"value":"Kamuli District","code":"205"},{"value":"Kamwenge District","code":"413"},{"value":"Kanungu District","code":"414"},{"value":"Kapchorwa District","code":"206"},{"value":"Kasese District","code":"406"},{"value":"Katakwi District","code":"207"},{"value":"Kayunga District","code":"112"},{"value":"Kibaale District","code":"407"},{"value":"Kiboga District","code":"103"},{"value":"Kibuku District","code":"227"},{"value":"Kiruhura District","code":"419"},{"value":"Kiryandongo District","code":"421"},{"value":"Kisoro District","code":"408"},{"value":"Kitgum District","code":"305"},{"value":"Koboko District","code":"319"},{"value":"Kole District","code":"325"},{"value":"Kotido District","code":"306"},{"value":"Kumi District","code":"208"},{"value":"Kween District","code":"228"},{"value":"Kyankwanzi District","code":"123"},{"value":"Kyegegwa District","code":"422"},{"value":"Kyenjojo District","code":"415"},{"value":"Kyotera District","code":"125"},{"value":"Lamwo District","code":"326"},{"value":"Lira District","code":"307"},{"value":"Luuka District","code":"229"},{"value":"Luwero District","code":"104"},{"value":"Lwengo District","code":"124"},{"value":"Lyantonde District","code":"114"},{"value":"Manafwa District","code":"223"},{"value":"Maracha District","code":"320"},{"value":"Masaka District","code":"105"},{"value":"Masindi District","code":"409"},{"value":"Mayuge District","code":"214"},{"value":"Mbale District","code":"209"},{"value":"Mbarara District","code":"410"},{"value":"Mitooma District","code":"423"},{"value":"Mityana District","code":"115"},{"value":"Moroto District","code":"308"},{"value":"Moyo District","code":"309"},{"value":"Mpigi District","code":"106"},{"value":"Mubende District","code":"107"},{"value":"Mukono District","code":"108"},{"value":"Nakapiripirit District","code":"311"},{"value":"Nakaseke District","code":"116"},{"value":"Nakasongola District","code":"109"},{"value":"Namayingo District","code":"230"},{"value":"Namisindwa District","code":"234"},{"value":"Namutumba District","code":"224"},{"value":"Napak District","code":"327"},{"value":"Nebbi District","code":"310"},{"value":"Ngora District","code":"231"},{"value":"Northern Region","code":"N"},{"value":"Ntoroko District","code":"424"},{"value":"Ntungamo District","code":"411"},{"value":"Nwoya District","code":"328"},{"value":"Omoro District","code":"331"},{"value":"Otuke District","code":"329"},{"value":"Oyam District","code":"321"},{"value":"Pader District","code":"312"},{"value":"Pakwach District","code":"332"},{"value":"Pallisa District","code":"210"},{"value":"Rakai District","code":"110"},{"value":"Rubanda District","code":"429"},{"value":"Rubirizi District","code":"425"},{"value":"Rukiga District","code":"431"},{"value":"Rukungiri District","code":"412"},{"value":"Sembabule District","code":"111"},{"value":"Serere District","code":"232"},{"value":"Sheema District","code":"426"},{"value":"Sironko District","code":"215"},{"value":"Soroti District","code":"211"},{"value":"Tororo District","code":"212"},{"value":"Wakiso District","code":"113"},{"value":"Western Region","code":"W"},{"value":"Yumbe District","code":"313"},{"value":"Zombo District","code":"330"}],"UA":[{"value":"Autonomous Republic of Crimea","code":"43"},{"value":"Cherkaska oblast","code":"71"},{"value":"Chernihivska oblast","code":"74"},{"value":"Chernivetska oblast","code":"77"},{"value":"Dnipropetrovska oblast","code":"12"},{"value":"Donetska oblast","code":"14"},{"value":"Ivano-Frankivska oblast","code":"26"},{"value":"Kharkivska oblast","code":"63"},{"value":"Khersonska oblast","code":"65"},{"value":"Khmelnytska oblast","code":"68"},{"value":"Kirovohradska oblast","code":"35"},{"value":"Kyiv","code":"30"},{"value":"Kyivska oblast","code":"32"},{"value":"Luhanska oblast","code":"09"},{"value":"Lvivska oblast","code":"46"},{"value":"Mykolaivska oblast","code":"48"},{"value":"Odeska oblast","code":"51"},{"value":"Poltavska oblast","code":"53"},{"value":"Rivnenska oblast","code":"56"},{"value":"Sevastopol","code":"40"},{"value":"Sumska oblast","code":"59"},{"value":"Ternopilska oblast","code":"61"},{"value":"Vinnytska oblast","code":"05"},{"value":"Volynska oblast","code":"07"},{"value":"Zakarpatska Oblast","code":"21"},{"value":"Zaporizka oblast","code":"23"},{"value":"Zhytomyrska oblast","code":"18"}],"AE":[{"value":"Abu Dhabi Emirate","code":"AZ"},{"value":"Ajman Emirate","code":"AJ"},{"value":"Dubai","code":"DU"},{"value":"Fujairah","code":"FU"},{"value":"Ras al-Khaimah","code":"RK"},{"value":"Sharjah Emirate","code":"SH"},{"value":"Umm al-Quwain","code":"UQ"}],"GB":[{"value":"Aberdeen","code":"ABE"},{"value":"Aberdeenshire","code":"ABD"},{"value":"Angus","code":"ANS"},{"value":"Antrim","code":"ANT"},{"value":"Antrim and Newtownabbey","code":"ANN"},{"value":"Ards","code":"ARD"},{"value":"Ards and North Down","code":"AND"},{"value":"Argyll and Bute","code":"AGB"},{"value":"Armagh City and District Council","code":"ARM"},{"value":"Armagh, Banbridge and Craigavon","code":"ABC"},{"value":"Ascension Island","code":"SH-AC"},{"value":"Ballymena Borough","code":"BLA"},{"value":"Ballymoney","code":"BLY"},{"value":"Banbridge","code":"BNB"},{"value":"Barnsley","code":"BNS"},{"value":"Bath and North East Somerset","code":"BAS"},{"value":"Bedford","code":"BDF"},{"value":"Belfast district","code":"BFS"},{"value":"Birmingham","code":"BIR"},{"value":"Blackburn with Darwen","code":"BBD"},{"value":"Blackpool","code":"BPL"},{"value":"Blaenau Gwent County Borough","code":"BGW"},{"value":"Bolton","code":"BOL"},{"value":"Bournemouth","code":"BMH"},{"value":"Bracknell Forest","code":"BRC"},{"value":"Bradford","code":"BRD"},{"value":"Bridgend County Borough","code":"BGE"},{"value":"Brighton and Hove","code":"BNH"},{"value":"Buckinghamshire","code":"BKM"},{"value":"Bury","code":"BUR"},{"value":"Caerphilly County Borough","code":"CAY"},{"value":"Calderdale","code":"CLD"},{"value":"Cambridgeshire","code":"CAM"},{"value":"Carmarthenshire","code":"CMN"},{"value":"Carrickfergus Borough Council","code":"CKF"},{"value":"Castlereagh","code":"CSR"},{"value":"Causeway Coast and Glens","code":"CCG"},{"value":"Central Bedfordshire","code":"CBF"},{"value":"Ceredigion","code":"CGN"},{"value":"Cheshire East","code":"CHE"},{"value":"Cheshire West and Chester","code":"CHW"},{"value":"City and County of Cardiff","code":"CRF"},{"value":"City and County of Swansea","code":"SWA"},{"value":"City of Bristol","code":"BST"},{"value":"City of Derby","code":"DER"},{"value":"City of Kingston upon Hull","code":"KHL"},{"value":"City of Leicester","code":"LCE"},{"value":"City of London","code":"LND"},{"value":"City of Nottingham","code":"NGM"},{"value":"City of Peterborough","code":"PTE"},{"value":"City of Plymouth","code":"PLY"},{"value":"City of Portsmouth","code":"POR"},{"value":"City of Southampton","code":"STH"},{"value":"City of Stoke-on-Trent","code":"STE"},{"value":"City of Sunderland","code":"SND"},{"value":"City of Westminster","code":"WSM"},{"value":"City of Wolverhampton","code":"WLV"},{"value":"City of York","code":"YOR"},{"value":"Clackmannanshire","code":"CLK"},{"value":"Coleraine Borough Council","code":"CLR"},{"value":"Conwy County Borough","code":"CWY"},{"value":"Cookstown District Council","code":"CKT"},{"value":"Cornwall","code":"CON"},{"value":"County Durham","code":"DUR"},{"value":"Coventry","code":"COV"},{"value":"Craigavon Borough Council","code":"CGV"},{"value":"Cumbria","code":"CMA"},{"value":"Darlington","code":"DAL"},{"value":"Denbighshire","code":"DEN"},{"value":"Derbyshire","code":"DBY"},{"value":"Derry City and Strabane","code":"DRS"},{"value":"Derry City Council","code":"DRY"},{"value":"Devon","code":"DEV"},{"value":"Doncaster","code":"DNC"},{"value":"Dorset","code":"DOR"},{"value":"Down District Council","code":"DOW"},{"value":"Dudley","code":"DUD"},{"value":"Dumfries and Galloway","code":"DGY"},{"value":"Dundee","code":"DND"},{"value":"Dungannon and South Tyrone Borough Council","code":"DGN"},{"value":"East Ayrshire","code":"EAY"},{"value":"East Dunbartonshire","code":"EDU"},{"value":"East Lothian","code":"ELN"},{"value":"East Renfrewshire","code":"ERW"},{"value":"East Riding of Yorkshire","code":"ERY"},{"value":"East Sussex","code":"ESX"},{"value":"Edinburgh","code":"EDH"},{"value":"England","code":"ENG"},{"value":"Essex","code":"ESS"},{"value":"Falkirk","code":"FAL"},{"value":"Fermanagh and Omagh","code":"FMO"},{"value":"Fermanagh District Council","code":"FER"},{"value":"Fife","code":"FIF"},{"value":"Flintshire","code":"FLN"},{"value":"Gateshead","code":"GAT"},{"value":"Glasgow","code":"GLG"},{"value":"Gloucestershire","code":"GLS"},{"value":"Gwynedd","code":"GWN"},{"value":"Halton","code":"HAL"},{"value":"Hampshire","code":"HAM"},{"value":"Hartlepool","code":"HPL"},{"value":"Herefordshire","code":"HEF"},{"value":"Hertfordshire","code":"HRT"},{"value":"Highland","code":"HLD"},{"value":"Inverclyde","code":"IVC"},{"value":"Isle of Wight","code":"IOW"},{"value":"Isles of Scilly","code":"IOS"},{"value":"Kent","code":"KEN"},{"value":"Kirklees","code":"KIR"},{"value":"Knowsley","code":"KWL"},{"value":"Lancashire","code":"LAN"},{"value":"Larne Borough Council","code":"LRN"},{"value":"Leeds","code":"LDS"},{"value":"Leicestershire","code":"LEC"},{"value":"Limavady Borough Council","code":"LMV"},{"value":"Lincolnshire","code":"LIN"},{"value":"Lisburn and Castlereagh","code":"LBC"},{"value":"Lisburn City Council","code":"LSB"},{"value":"Liverpool","code":"LIV"},{"value":"London Borough of Barking and Dagenham","code":"BDG"},{"value":"London Borough of Barnet","code":"BNE"},{"value":"London Borough of Bexley","code":"BEX"},{"value":"London Borough of Brent","code":"BEN"},{"value":"London Borough of Bromley","code":"BRY"},{"value":"London Borough of Camden","code":"CMD"},{"value":"London Borough of Croydon","code":"CRY"},{"value":"London Borough of Ealing","code":"EAL"},{"value":"London Borough of Enfield","code":"ENF"},{"value":"London Borough of Hackney","code":"HCK"},{"value":"London Borough of Hammersmith and Fulham","code":"HMF"},{"value":"London Borough of Haringey","code":"HRY"},{"value":"London Borough of Harrow","code":"HRW"},{"value":"London Borough of Havering","code":"HAV"},{"value":"London Borough of Hillingdon","code":"HIL"},{"value":"London Borough of Hounslow","code":"HNS"},{"value":"London Borough of Islington","code":"ISL"},{"value":"London Borough of Lambeth","code":"LBH"},{"value":"London Borough of Lewisham","code":"LEW"},{"value":"London Borough of Merton","code":"MRT"},{"value":"London Borough of Newham","code":"NWM"},{"value":"London Borough of Redbridge","code":"RDB"},{"value":"London Borough of Richmond upon Thames","code":"RIC"},{"value":"London Borough of Southwark","code":"SWK"},{"value":"London Borough of Sutton","code":"STN"},{"value":"London Borough of Tower Hamlets","code":"TWH"},{"value":"London Borough of Waltham Forest","code":"WFT"},{"value":"London Borough of Wandsworth","code":"WND"},{"value":"Magherafelt District Council","code":"MFT"},{"value":"Manchester","code":"MAN"},{"value":"Medway","code":"MDW"},{"value":"Merthyr Tydfil County Borough","code":"MTY"},{"value":"Metropolitan Borough of Wigan","code":"WGN"},{"value":"Mid and East Antrim","code":"MEA"},{"value":"Mid Ulster","code":"MUL"},{"value":"Middlesbrough","code":"MDB"},{"value":"Midlothian","code":"MLN"},{"value":"Milton Keynes","code":"MIK"},{"value":"Monmouthshire","code":"MON"},{"value":"Moray","code":"MRY"},{"value":"Moyle District Council","code":"MYL"},{"value":"Neath Port Talbot County Borough","code":"NTL"},{"value":"Newcastle upon Tyne","code":"NET"},{"value":"Newport","code":"NWP"},{"value":"Newry and Mourne District Council","code":"NYM"},{"value":"Newry, Mourne and Down","code":"NMD"},{"value":"Newtownabbey Borough Council","code":"NTA"},{"value":"Norfolk","code":"NFK"},{"value":"North Ayrshire","code":"NAY"},{"value":"North Down Borough Council","code":"NDN"},{"value":"North East Lincolnshire","code":"NEL"},{"value":"North Lanarkshire","code":"NLK"},{"value":"North Lincolnshire","code":"NLN"},{"value":"North Somerset","code":"NSM"},{"value":"North Tyneside","code":"NTY"},{"value":"North Yorkshire","code":"NYK"},{"value":"Northamptonshire","code":"NTH"},{"value":"Northern Ireland","code":"NIR"},{"value":"Northumberland","code":"NBL"},{"value":"Nottinghamshire","code":"NTT"},{"value":"Oldham","code":"OLD"},{"value":"Omagh District Council","code":"OMH"},{"value":"Orkney Islands","code":"ORK"},{"value":"Outer Hebrides","code":"ELS"},{"value":"Oxfordshire","code":"OXF"},{"value":"Pembrokeshire","code":"PEM"},{"value":"Perth and Kinross","code":"PKN"},{"value":"Poole","code":"POL"},{"value":"Powys","code":"POW"},{"value":"Reading","code":"RDG"},{"value":"Redcar and Cleveland","code":"RCC"},{"value":"Renfrewshire","code":"RFW"},{"value":"Rhondda Cynon Taf","code":"RCT"},{"value":"Rochdale","code":"RCH"},{"value":"Rotherham","code":"ROT"},{"value":"Royal Borough of Greenwich","code":"GRE"},{"value":"Royal Borough of Kensington and Chelsea","code":"KEC"},{"value":"Royal Borough of Kingston upon Thames","code":"KTT"},{"value":"Rutland","code":"RUT"},{"value":"Saint Helena","code":"SH-HL"},{"value":"Salford","code":"SLF"},{"value":"Sandwell","code":"SAW"},{"value":"Scotland","code":"SCT"},{"value":"Scottish Borders","code":"SCB"},{"value":"Sefton","code":"SFT"},{"value":"Sheffield","code":"SHF"},{"value":"Shetland Islands","code":"ZET"},{"value":"Shropshire","code":"SHR"},{"value":"Slough","code":"SLG"},{"value":"Solihull","code":"SOL"},{"value":"Somerset","code":"SOM"},{"value":"South Ayrshire","code":"SAY"},{"value":"South Gloucestershire","code":"SGC"},{"value":"South Lanarkshire","code":"SLK"},{"value":"South Tyneside","code":"STY"},{"value":"Southend-on-Sea","code":"SOS"},{"value":"St Helens","code":"SHN"},{"value":"Staffordshire","code":"STS"},{"value":"Stirling","code":"STG"},{"value":"Stockport","code":"SKP"},{"value":"Stockton-on-Tees","code":"STT"},{"value":"Strabane District Council","code":"STB"},{"value":"Suffolk","code":"SFK"},{"value":"Surrey","code":"SRY"},{"value":"Swindon","code":"SWD"},{"value":"Tameside","code":"TAM"},{"value":"Telford and Wrekin","code":"TFW"},{"value":"Thurrock","code":"THR"},{"value":"Torbay","code":"TOB"},{"value":"Torfaen","code":"TOF"},{"value":"Trafford","code":"TRF"},{"value":"United Kingdom","code":"UKM"},{"value":"Vale of Glamorgan","code":"VGL"},{"value":"Wakefield","code":"WKF"},{"value":"Wales","code":"WLS"},{"value":"Walsall","code":"WLL"},{"value":"Warrington","code":"WRT"},{"value":"Warwickshire","code":"WAR"},{"value":"West Berkshire","code":"WBK"},{"value":"West Dunbartonshire","code":"WDU"},{"value":"West Lothian","code":"WLN"},{"value":"West Sussex","code":"WSX"},{"value":"Wiltshire","code":"WIL"},{"value":"Windsor and Maidenhead","code":"WNM"},{"value":"Wirral","code":"WRL"},{"value":"Wokingham","code":"WOK"},{"value":"Worcestershire","code":"WOR"},{"value":"Wrexham County Borough","code":"WRX"}],"US":[{"value":"Alabama","code":"AL"},{"value":"Alaska","code":"AK"},{"value":"American Samoa","code":"AS"},{"value":"Arizona","code":"AZ"},{"value":"Arkansas","code":"AR"},{"value":"Baker Island","code":"UM-81"},{"value":"California","code":"CA"},{"value":"Colorado","code":"CO"},{"value":"Connecticut","code":"CT"},{"value":"Delaware","code":"DE"},{"value":"District of Columbia","code":"DC"},{"value":"Florida","code":"FL"},{"value":"Georgia","code":"GA"},{"value":"Guam","code":"GU"},{"value":"Hawaii","code":"HI"},{"value":"Howland Island","code":"UM-84"},{"value":"Idaho","code":"ID"},{"value":"Illinois","code":"IL"},{"value":"Indiana","code":"IN"},{"value":"Iowa","code":"IA"},{"value":"Jarvis Island","code":"UM-86"},{"value":"Johnston Atoll","code":"UM-67"},{"value":"Kansas","code":"KS"},{"value":"Kentucky","code":"KY"},{"value":"Kingman Reef","code":"UM-89"},{"value":"Louisiana","code":"LA"},{"value":"Maine","code":"ME"},{"value":"Maryland","code":"MD"},{"value":"Massachusetts","code":"MA"},{"value":"Michigan","code":"MI"},{"value":"Midway Atoll","code":"UM-71"},{"value":"Minnesota","code":"MN"},{"value":"Mississippi","code":"MS"},{"value":"Missouri","code":"MO"},{"value":"Montana","code":"MT"},{"value":"Navassa Island","code":"UM-76"},{"value":"Nebraska","code":"NE"},{"value":"Nevada","code":"NV"},{"value":"New Hampshire","code":"NH"},{"value":"New Jersey","code":"NJ"},{"value":"New Mexico","code":"NM"},{"value":"New York","code":"NY"},{"value":"North Carolina","code":"NC"},{"value":"North Dakota","code":"ND"},{"value":"Northern Mariana Islands","code":"MP"},{"value":"Ohio","code":"OH"},{"value":"Oklahoma","code":"OK"},{"value":"Oregon","code":"OR"},{"value":"Palmyra Atoll","code":"UM-95"},{"value":"Pennsylvania","code":"PA"},{"value":"Puerto Rico","code":"PR"},{"value":"Rhode Island","code":"RI"},{"value":"South Carolina","code":"SC"},{"value":"South Dakota","code":"SD"},{"value":"Tennessee","code":"TN"},{"value":"Texas","code":"TX"},{"value":"United States Minor Outlying Islands","code":"UM"},{"value":"United States Virgin Islands","code":"VI"},{"value":"Utah","code":"UT"},{"value":"Vermont","code":"VT"},{"value":"Virginia","code":"VA"},{"value":"Wake Island","code":"UM-79"},{"value":"Washington","code":"WA"},{"value":"West Virginia","code":"WV"},{"value":"Wisconsin","code":"WI"},{"value":"Wyoming","code":"WY"}],"UM":[{"value":"Baker Island","code":"81"},{"value":"Howland Island","code":"84"},{"value":"Jarvis Island","code":"86"},{"value":"Johnston Atoll","code":"67"},{"value":"Kingman Reef","code":"89"},{"value":"Midway Islands","code":"71"},{"value":"Navassa Island","code":"76"},{"value":"Palmyra Atoll","code":"95"},{"value":"Wake Island","code":"79"}],"UY":[{"value":"Artigas","code":"AR"},{"value":"Canelones","code":"CA"},{"value":"Cerro Largo","code":"CL"},{"value":"Colonia","code":"CO"},{"value":"Durazno","code":"DU"},{"value":"Flores","code":"FS"},{"value":"Florida","code":"FD"},{"value":"Lavalleja","code":"LA"},{"value":"Maldonado","code":"MA"},{"value":"Montevideo","code":"MO"},{"value":"Paysandú","code":"PA"},{"value":"Río Negro","code":"RN"},{"value":"Rivera","code":"RV"},{"value":"Rocha","code":"RO"},{"value":"Salto","code":"SA"},{"value":"San José","code":"SJ"},{"value":"Soriano","code":"SO"},{"value":"Tacuarembó","code":"TA"},{"value":"Treinta y Tres","code":"TT"}],"UZ":[{"value":"Andijan Region","code":"AN"},{"value":"Bukhara Region","code":"BU"},{"value":"Fergana Region","code":"FA"},{"value":"Jizzakh Region","code":"JI"},{"value":"Karakalpakstan","code":"QR"},{"value":"Namangan Region","code":"NG"},{"value":"Navoiy Region","code":"NW"},{"value":"Qashqadaryo Region","code":"QA"},{"value":"Samarqand Region","code":"SA"},{"value":"Sirdaryo Region","code":"SI"},{"value":"Surxondaryo Region","code":"SU"},{"value":"Tashkent","code":"TK"},{"value":"Tashkent Region","code":"TO"},{"value":"Xorazm Region","code":"XO"}],"VU":[{"value":"Malampa","code":"MAP"},{"value":"Penama","code":"PAM"},{"value":"Sanma","code":"SAM"},{"value":"Shefa","code":"SEE"},{"value":"Tafea","code":"TAE"},{"value":"Torba","code":"TOB"}],"VA":[{"value":"Vatican City State (Holy See)","code":"Vatican City State (Holy See)"}],"VE":[{"value":"Amazonas","code":"Z"},{"value":"Anzoátegui","code":"B"},{"value":"Apure","code":"C"},{"value":"Aragua","code":"D"},{"value":"Barinas","code":"E"},{"value":"Bolívar","code":"F"},{"value":"Carabobo","code":"G"},{"value":"Cojedes","code":"H"},{"value":"Delta Amacuro","code":"Y"},{"value":"Distrito Capital","code":"A"},{"value":"Falcón","code":"I"},{"value":"Federal Dependencies of Venezuela","code":"W"},{"value":"Guárico","code":"J"},{"value":"La Guaira","code":"X"},{"value":"Lara","code":"K"},{"value":"Mérida","code":"L"},{"value":"Miranda","code":"M"},{"value":"Monagas","code":"N"},{"value":"Nueva Esparta","code":"O"},{"value":"Portuguesa","code":"P"},{"value":"Sucre","code":"R"},{"value":"Táchira","code":"S"},{"value":"Trujillo","code":"T"},{"value":"Yaracuy","code":"U"},{"value":"Zulia","code":"V"}],"VN":[{"value":"An Giang","code":"44"},{"value":"Bà Rịa-Vũng Tàu","code":"43"},{"value":"Bắc Giang","code":"54"},{"value":"Bắc Kạn","code":"53"},{"value":"Bạc Liêu","code":"55"},{"value":"Bắc Ninh","code":"56"},{"value":"Bến Tre","code":"50"},{"value":"Bình Dương","code":"57"},{"value":"Bình Định","code":"31"},{"value":"Bình Phước","code":"58"},{"value":"Bình Thuận","code":"40"},{"value":"Cà Mau","code":"59"},{"value":"Cần Thơ","code":"CT"},{"value":"Cao Bằng","code":"04"},{"value":"Đà Nẵng","code":"DN"},{"value":"Đắk Lắk","code":"33"},{"value":"Đắk Nông","code":"72"},{"value":"Điện Biên","code":"71"},{"value":"Đồng Nai","code":"39"},{"value":"Đồng Tháp","code":"45"},{"value":"Gia Lai","code":"30"},{"value":"Hà Giang","code":"03"},{"value":"Hà Nam","code":"63"},{"value":"Hà Nội","code":"HN"},{"value":"Hà Tĩnh","code":"23"},{"value":"Hải Dương","code":"61"},{"value":"Hải Phòng","code":"HP"},{"value":"Hậu Giang","code":"73"},{"value":"Hồ Chí Minh","code":"SG"},{"value":"Hòa Bình","code":"14"},{"value":"Hưng Yên","code":"66"},{"value":"Khánh Hòa","code":"34"},{"value":"Kiên Giang","code":"47"},{"value":"Kon Tum","code":"28"},{"value":"Lai Châu","code":"01"},{"value":"Lâm Đồng","code":"35"},{"value":"Lạng Sơn","code":"09"},{"value":"Lào Cai","code":"02"},{"value":"Long An","code":"41"},{"value":"Nam Định","code":"67"},{"value":"Nghệ An","code":"22"},{"value":"Ninh Bình","code":"18"},{"value":"Ninh Thuận","code":"36"},{"value":"Phú Thọ","code":"68"},{"value":"Phú Yên","code":"32"},{"value":"Quảng Bình","code":"24"},{"value":"Quảng Nam","code":"27"},{"value":"Quảng Ngãi","code":"29"},{"value":"Quảng Ninh","code":"13"},{"value":"Quảng Trị","code":"25"},{"value":"Sóc Trăng","code":"52"},{"value":"Sơn La","code":"05"},{"value":"Tây Ninh","code":"37"},{"value":"Thái Bình","code":"20"},{"value":"Thái Nguyên","code":"69"},{"value":"Thanh Hóa","code":"21"},{"value":"Thừa Thiên-Huế","code":"26"},{"value":"Tiền Giang","code":"46"},{"value":"Trà Vinh","code":"51"},{"value":"Tuyên Quang","code":"07"},{"value":"Vĩnh Long","code":"49"},{"value":"Vĩnh Phúc","code":"70"},{"value":"Yên Bái","code":"06"}],"VG":[{"value":"Virgin Islands (British)","code":"Virgin Islands (British)"}],"VI":[{"value":"Saint Croix","code":"SC"},{"value":"Saint John","code":"SJ"},{"value":"Saint Thomas","code":"ST"}],"WF":[{"value":"Wallis and Futuna Islands","code":"Wallis and Futuna Islands"}],"EH":[{"value":"Western Sahara","code":"Western Sahara"}],"YE":[{"value":"'Adan","code":"AD"},{"value":"'Amran","code":"AM"},{"value":"Abyan","code":"AB"},{"value":"Al Bayda'","code":"BA"},{"value":"Al Hudaydah","code":"HU"},{"value":"Al Jawf","code":"JA"},{"value":"Al Mahrah","code":"MR"},{"value":"Al Mahwit","code":"MW"},{"value":"Amanat Al Asimah","code":"SA"},{"value":"Dhamar","code":"DH"},{"value":"Hadhramaut","code":"HD"},{"value":"Hajjah","code":"HJ"},{"value":"Ibb","code":"IB"},{"value":"Lahij","code":"LA"},{"value":"Ma'rib","code":"MA"},{"value":"Raymah","code":"RA"},{"value":"Saada","code":"SD"},{"value":"Sana'a","code":"SN"},{"value":"Shabwah","code":"SH"},{"value":"Socotra","code":"SU"},{"value":"Ta'izz","code":"TA"}],"ZM":[{"value":"Central Province","code":"02"},{"value":"Copperbelt Province","code":"08"},{"value":"Eastern Province","code":"03"},{"value":"Luapula Province","code":"04"},{"value":"Lusaka Province","code":"09"},{"value":"Muchinga Province","code":"10"},{"value":"Northern Province","code":"05"},{"value":"Northwestern Province","code":"06"},{"value":"Southern Province","code":"07"},{"value":"Western Province","code":"01"}],"ZW":[{"value":"Bulawayo Province","code":"BU"},{"value":"Harare Province","code":"HA"},{"value":"Manicaland","code":"MA"},{"value":"Mashonaland Central Province","code":"MC"},{"value":"Mashonaland East Province","code":"ME"},{"value":"Mashonaland West Province","code":"MW"},{"value":"Masvingo Province","code":"MV"},{"value":"Matabeleland North Province","code":"MN"},{"value":"Matabeleland South Province","code":"MS"},{"value":"Midlands Province","code":"MI"}]}}
68,064
10,625
hyperswitch-client-core
src/utility/reusableCodeFromWeb/Validation.res
.res
type cardIssuer = | VISA | MASTERCARD | AMEX | MAESTRO | DINERSCLUB | DISCOVER | BAJAJ | SODEXO | RUPAY | JCB | CARTESBANCAIRES | NOTFOUND let toInt = val => val->Int.fromString->Option.getOr(0) let cardType = val => { switch val->String.toUpperCase { | "VISA" => VISA | "MASTERCARD" => MASTERCARD | "AMEX" => AMEX | "MAESTRO" => MAESTRO | "DINERSCLUB" => DINERSCLUB | "DISCOVER" => DISCOVER | "BAJAJ" => BAJAJ | "SODEXO" => SODEXO | "RUPAY" => RUPAY | "JCB" => JCB | "CARTESBANCAIRES" => CARTESBANCAIRES | _ => NOTFOUND } } let getobjFromCardPattern = cardBrand => { let patternsDict = CardPattern.cardPatterns patternsDict ->Array.filter(item => { cardBrand === item.issuer }) ->Array.get(0) ->Option.getOr(CardPattern.defaultCardPattern) } let clearSpaces = value => { value->String.replaceRegExp(%re("/\D+/g"), "") } let slice = (val, start: int, end: int) => { val->String.slice(~start, ~end) } let getStrFromIndex = (arr: array<string>, index) => { arr->Array.get(index)->Option.getOr("") } let formatCVCNumber = (val, cardType) => { let clearValue = val->clearSpaces let obj = getobjFromCardPattern(cardType) clearValue->slice(0, obj.maxCVCLength) } let getCurrentMonthAndYear = (dateTimeIsoString: string) => { let tempTimeDateString = dateTimeIsoString->String.replace("Z", "") let tempTimeDate = tempTimeDateString->String.split("T") let date = tempTimeDate->Array.get(0)->Option.getOr("") let dateComponents = date->String.split("-") let currentMonth = dateComponents->Array.get(1)->Option.getOr("") let currentYear = dateComponents->Array.get(0)->Option.getOr("") (currentMonth->toInt, currentYear->toInt) } let formatCardNumber = (val, cardType) => { let clearValue = val->clearSpaces let formatedCard = switch cardType { | AMEX => `${clearValue->slice(0, 4)} ${clearValue->slice(4, 10)} ${clearValue->slice(10, 15)}` | DINERSCLUB => if clearValue->String.length > 14 { `${clearValue->slice(0, 4)} ${clearValue->slice(4, 8)} ${clearValue->slice( 8, 12, )} ${clearValue->slice(12, 16)} ${clearValue->slice(16, 19)}` } else { `${clearValue->slice(0, 4)} ${clearValue->slice(4, 10)} ${clearValue->slice(10, 14)}` } | MASTERCARD | DISCOVER | SODEXO | RUPAY | VISA => `${clearValue->slice(0, 4)} ${clearValue->slice(4, 8)} ${clearValue->slice( 8, 12, )} ${clearValue->slice(12, 16)} ${clearValue->slice(16, 19)}` | _ => `${clearValue->slice(0, 4)} ${clearValue->slice(4, 8)} ${clearValue->slice( 8, 12, )} ${clearValue->slice(12, 19)}` } formatedCard->String.trim } let splitExpiryDates = val => { let split = val->String.split("/") let value = split->Array.map(item => item->String.trim) let month = value->Array.get(0)->Option.getOr("") let year = value->Array.get(1)->Option.getOr("") (month, year) } let getExpiryDates = val => { let date = Date.make()->Date.toISOString let (month, year) = splitExpiryDates(val) let (_, currentYear) = getCurrentMonthAndYear(date) let prefix = currentYear->Int.toString->String.slice(~start=0, ~end=2) (month, `${prefix}${year}`) } let formatCardExpiryNumber = val => { let clearValue = val->clearSpaces let expiryVal = clearValue->toInt let formatted = if expiryVal >= 2 && expiryVal <= 9 && clearValue->String.length == 1 { `0${clearValue} / ` } else if clearValue->String.length == 2 && expiryVal > 12 { let val = clearValue->String.split("") `0${val->getStrFromIndex(0)} / ${val->getStrFromIndex(1)}` } else { clearValue } if clearValue->String.length >= 3 { `${formatted->slice(0, 2)} / ${formatted->slice(2, 4)}` } else { formatted } } let getAllMatchedCardSchemes = cardNumber => { CardPattern.cardPatterns->Array.reduce([], (acc, item) => { if String.match(cardNumber, item.pattern)->Option.isSome { acc->Array.push(item.issuer) } acc }) } let isCardSchemeEnabled = (~cardScheme, ~enabledCardSchemes) => { enabledCardSchemes->Array.includes(cardScheme) } let getFirstValidCardScheme = (~cardNumber, ~enabledCardSchemes) => { let allMatchedCards = getAllMatchedCardSchemes(cardNumber->clearSpaces) allMatchedCards ->Array.find(card => isCardSchemeEnabled(~cardScheme=card, ~enabledCardSchemes)) ->Option.getOr("") } let getEligibleCoBadgedCardSchemes = (~matchedCardSchemes, ~enabledCardSchemes) => { matchedCardSchemes->Array.filter(ele => enabledCardSchemes->Array.includes(ele)) } let getCardBrand = cardNumber => { try { let card = cardNumber->String.replaceRegExp(%re("/[^\d]/g"), "") let rupayRanges = [ (508227, 508227), (508500, 508999), (603741, 603741), (606985, 607384), (607385, 607484), (607485, 607984), (608001, 608100), (608101, 608200), (608201, 608300), (608301, 608350), (608351, 608500), (652150, 652849), (652850, 653049), (653050, 653149), (817290, 817290), (817368, 817368), (817378, 817378), (353800, 353800), ] let masterCardRanges = [(222100, 272099)] let doesFallInRange = (cardRanges, isin) => { let intIsin = isin ->String.replaceRegExp(%re("/[^\d]/g"), "") ->String.substring(~start=0, ~end=6) ->Int.fromString ->Option.getOr(0) let range = cardRanges->Array.map(currCardRange => { let (min, max) = currCardRange intIsin >= min && intIsin <= max }) range->Array.includes(true) } let patternsDict = CardPattern.cardPatterns if doesFallInRange(rupayRanges, card) { "RUPAY" } else if doesFallInRange(masterCardRanges, card) { "MASTERCARD" } else { patternsDict ->Array.map(item => { if String.match(card, item.pattern)->Option.isSome { item.issuer } else { "" } }) ->Array.filter(item => item !== "") ->Array.get(0) ->Option.getOr("") } } catch { | _error => "" } } let calculateLuhn = value => { let card = value->clearSpaces let splitArr = card->String.split("") splitArr->Array.reverse let unCheckArr = splitArr->Array.filterWithIndex((_, i) => { mod(i, 2) == 0 }) let checkArr = splitArr ->Array.filterWithIndex((_, i) => { mod(i + 1, 2) == 0 }) ->Array.map(item => { let val = item->toInt let double = val * 2 if double > 9 { let str = double->Int.toString let arr = str->String.split("") (arr->Array.get(0)->Option.getOr("")->toInt + arr[1]->Option.getOr("")->toInt)->Int.toString } else { double->Int.toString } }) let sumofCheckArr = Array.reduce(checkArr, 0, (acc, val) => acc + val->toInt) let sumofUnCheckedArr = Array.reduce(unCheckArr, 0, (acc, val) => acc + val->toInt) let totalSum = sumofCheckArr + sumofUnCheckedArr mod(totalSum, 10) == 0 } // let getCardBrandIcon = (cardType, paymentType) => { // open CardThemeType // switch cardType { // | VISA => <Icon size=28 name="visa-light" /> // | MASTERCARD => <Icon size=28 name="mastercard" /> // | AMEX => <Icon size=28 name="amex-light" /> // | MAESTRO => <Icon size=28 name="maestro" /> // | DINERSCLUB => <Icon size=28 name="diners" /> // | DISCOVER => <Icon size=28 name="discover" /> // | BAJAJ => <Icon size=28 name="card" /> // | SODEXO => <Icon size=28 name="card" /> // | RUPAY => <Icon size=28 name="rupay-card" /> // | JCB => <Icon size=28 name="jcb-card" /> // | NOTFOUND => // switch paymentType { // | Payment => <Icon size=28 name="base-card" /> // | Card // | CardNumberElement // | CardExpiryElement // | CardCVCElement // | NONE => // <Icon size=28 name="default-card" /> // } // } // } let getExpiryValidity = cardExpiry => { let date = Date.make()->Date.toISOString let (month, year) = getExpiryDates(cardExpiry) let (currentMonth, currentYear) = getCurrentMonthAndYear(date) let valid = if currentYear == year->toInt && month->toInt >= currentMonth && month->toInt <= 12 { true } else if ( year->toInt > currentYear && year->toInt < 2099 && month->toInt >= 1 && month->toInt <= 12 ) { true } else { false } valid } let containsOnlyDigits = text => { %re("/^[0-9]*$/")->Js.Re.test_(text) } // let max = (a, b) => { // a > b ? a : b // } // let getMaxLength = val => { // let obj = getobjFromCardPattern(val->getCardBrand) // let maxValue = obj.length->Array.reduce(0, max) // if maxValue <= 12 { // maxValue + 2 // } else if maxValue <= 16 { // maxValue + 3 // } else if maxValue <= 19 { // maxValue + 4 // } else { // maxValue + 2 // } // } let cvcNumberInRange = (val, cardBrand) => { let clearValue = val->clearSpaces let obj = getobjFromCardPattern(cardBrand) let cvcLengthInRange = obj.cvcLength ->Array.find(item => { clearValue->String.length == item }) ->Option.isSome cvcLengthInRange } let cvcNumberEqualsMaxLength = (val, cardBrand) => { let clearValue = val->clearSpaces let obj = getobjFromCardPattern(cardBrand) let cvcMaxLengthEquals = clearValue->String.length == obj.maxCVCLength cvcMaxLengthEquals } // let genreateFontsLink = (fonts: array<CardThemeType.fonts>) => { // if fonts->Array.length > 0 { // fonts // ->Array.map(item => // if item.cssSrc != "" { // let link = document["createElement"](. "link") // link["href"] = item.cssSrc // link["rel"] = "stylesheet" // document["body"]["appendChild"](. link) // } else if item.family != "" && item.src != "" { // let newStyle = document["createElement"](. "style") // newStyle["appendChild"](. // document["createTextNode"](. // `\ // @font-face {\ // font-family: "${item.family}";\ // src: url(${item.src});\ // font-weight: "${item.weight}";\ // }\ // `, // ), // )->ignore // document["body"]["appendChild"](. newStyle) // } // ) // ->ignore // } // } let maxCardLength = cardBrand => { let obj = getobjFromCardPattern(cardBrand) Array.reduce(obj.length, 0, (acc, val) => acc > val ? acc : val) } let cardValid = (cardNumber, cardBrand) => { let clearValue = cardNumber->clearSpaces Array.includes(getobjFromCardPattern(cardBrand).length, clearValue->String.length) && calculateLuhn(cardNumber) } let isCardNumberEqualsMax = (cardNumber, cardBrand) => { let clearValue = cardNumber->clearSpaces clearValue->String.length == maxCardLength(cardBrand) || clearValue->String.length == 16 } // let cardValid = (cardNumber, cardBrand) => { // let clearValueLength = cardNumber->clearSpaces->String.length // (clearValueLength == maxCardLength(cardBrand) || // (cardBrand === "Visa" && clearValueLength == 16)) && calculateLuhn(cardNumber) // } // let blurRef = (ref: React.ref<Nullable.t<Dom.element>>) => { // ref.current->Nullable.toOption->Option.forEach(input => input->blur)->ignore // } // let handleInputFocus = ( // ~currentRef: React.ref<Nullable.t<Dom.element>>, // ~destinationRef: React.ref<Nullable.t<Dom.element>>, // ) => { // let optionalRef = destinationRef.current->Nullable.toOption // switch optionalRef { // | Some(_) => optionalRef->Option.forEach(input => input->focus)->ignore // | None => blurRef(currentRef) // } // } // let getCardElementValue = (iframeId, key) => { // let firstIframeVal = if (Window.parent->Window.frames)["0"]->Window.name !== iframeId { // switch (Window.parent->Window.frames)["0"] // ->Window.document // ->Window.getElementById(key) // ->Nullable.toOption { // | Some(dom) => dom->Window.value // | None => "" // } // } else { // "" // } // let secondIframeVal = if (Window.parent->Window.frames)["1"]->Window.name !== iframeId { // switch (Window.parent->Window.frames)["1"] // ->Window.document // ->Window.getElementById(key) // ->Nullable.toOption { // | Some(dom) => dom->Window.value // | None => "" // } // } else { // "" // } // let thirdIframeVal = if (Window.parent->Window.frames)["2"]->Window.name !== iframeId { // switch (Window.parent->Window.frames)["2"] // ->Window.document // ->Window.getElementById(key) // ->Nullable.toOption { // | Some(dom) => dom->Window.value // | None => "" // } // } else { // "" // } // thirdIframeVal === "" ? secondIframeVal === "" ? firstIframeVal : secondIframeVal : thirdIframeVal // } let checkMaxCardCvv = (cvcNumber, cardBrand) => { cvcNumber->String.length > 0 && cvcNumberEqualsMaxLength(cvcNumber, cardBrand) } let checkCardCVC = (cvcNumber, cardBrand) => { cvcNumber->String.length > 0 && cvcNumberInRange(cvcNumber, cardBrand) } let checkCardExpiry = expiry => { expiry->String.length > 0 && getExpiryValidity(expiry) } // let commonKeyDownEvent = (ev, srcRef, destRef, srcEle, destEle, setEle) => { // let key = ReactEvent.Keyboard.keyCode(ev) // if key == 8 && srcEle == "" { // handleInputFocus(~currentRef=srcRef, ~destinationRef=destRef) // setEle(_ => slice(destEle, 0, -1)) // ev->ReactEvent.Keyboard.preventDefault // } // } // let pincodeVisibility = cardNumber => { // let brand = getCardBrand(cardNumber) // let brandPattern = // CardPattern.cardPatterns // ->Array.filter(obj => obj.issuer == brand) // ->Array.get(0) // ->Option.getOr(CardPattern.defaultCardPattern) // brandPattern.pincodeRequired // } // let swapCardOption = (cardOpts: array<string>, dropOpts: array<string>, selectedOption: string) => { // let popEle = Array.pop(cardOpts) // dropOpts->Array.push(popEle->Option.getOr("")) // cardOpts->Array.push(selectedOption) // let temp: array<string> = dropOpts->Array.filter(item => item != selectedOption) // (cardOpts, temp) // } // let setCardValid = (cardnumber, setIsCardValid) => { // let cardBrand = getCardBrand(cardnumber) // if cardValid(cardnumber, cardBrand) { // setIsCardValid(_ => Some(true)) // } else if ( // !cardValid(cardnumber, cardBrand) && cardnumber->String.length == maxCardLength(cardBrand) // ) { // setIsCardValid(_ => Some(false)) // } else if !(cardnumber->String.length == maxCardLength(cardBrand)) { // setIsCardValid(_ => None) // } // } // let setExpiryValid = (expiry, setIsExpiryValid) => { // if isExipryValid(expiry) { // setIsExpiryValid(_ => Some(true)) // } else if !getExpiryValidity(expiry) && isExipryComplete(expiry) { // setIsExpiryValid(_ => Some(false)) // } else if !isExipryComplete(expiry) { // setIsExpiryValid(_ => None) // } // } // let getLayoutClass = layout => { // open PaymentType // switch layout { // | ObjectLayout(obj) => obj // | StringLayout(str) => { // ...defaultLayout, // type_: str, // } // } // } // let getAllBanknames = obj => { // obj->Array.reduce([], (acc, item: PaymentMethodListType.bankNames) => { // item.bank_name->Array.map(val => acc->Array.push(val))->ignore // acc // }) // } // let getConnector = (bankList, selectedBank, banks, default) => { // bankList // ->Array.filter((item: PaymentMethodListType.bankNames) => { // item.bank_name->Array.includes(selectedBank->Utils.getBankKeys(banks, default)) // }) // ->Array.get(0) // ->Option.getOr(PaymentMethodListType.deafultBankNames) // } // let getAllConnectors = obj => { // obj->Array.reduce([], (acc, item: PaymentMethodListType.bankNames) => { // item.eligible_connectors->Array.map(val => acc->Array.push(val))->ignore // acc // }) // } // let clientTimeZone = dateTimeFormat(.).resolvedOptions(.).timeZone // let clientCountry = Utils.getClientCountry(clientTimeZone) // let postalRegex = (postalCodes: array<PostalCodeType.postalCodes>) => { // let countryPostal = Utils.getCountryPostal(clientCountry.isoAlpha2, postalCodes) // countryPostal.regex == "" ? "" : countryPostal.regex // } let isValidZip = (~zipCode, ~country) => { let _ = country let countryObj = CountryStateDataHookTypes.defaultTimeZone // Country.country // ->Array.find(item => item.countryName === country) // ->Option.getOr(Country.defaultTimeZone) let postalCode = PostalCodes.postalCode ->Array.find(item => item.iso == countryObj.isoAlpha2) ->Option.getOr(PostalCodes.defaultPostalCode) let isZipCodeValid = RegExp.test(postalCode.regex->Js.Re.fromString, zipCode) zipCode->String.length > 0 && isZipCodeValid } let containsDigit = text => { switch text->String.match(%re("/\d/")) { | Some(_) => true | None => false } } let containsMoreThanTwoDigits = text => { switch text->String.match(%re("/\d/g")) { | Some(matches) => matches->Array.length > 2 | None => false } }
5,183
10,626
hyperswitch-client-core
src/utility/reusableCodeFromWeb/Bank.res
.res
type bank = { displayName: string, hyperSwitch: string, } let bankNameConverter = (var: array<string>) => { let final = var->Array.map(item => { let x = item ->String.split("_") ->Array.map(w => { w->String.charAt(0)->String.toUpperCase ++ w->String.sliceToEnd(~start=1) }) let data = x->Array.join(" ") { displayName: data, hyperSwitch: item, } }) final->Js.Array.sortInPlace }
120
10,627
hyperswitch-client-core
src/utility/reusableCodeFromWeb/ErrorHooks.res
.res
let useShowErrorOrWarning = () => { let customAlert = AlertHook.useAlerts() (inputKey: ErrorUtils.errorKey, ~dynamicStr="", ()) => { let (type_, str) = switch inputKey { | INVALID_PK(var) => var | INVALID_EK(var) => var | DEPRECATED_LOADSTRIPE(var) => var | REQUIRED_PARAMETER(var) => var | UNKNOWN_KEY(var) => var | UNKNOWN_VALUE(var) => var | TYPE_BOOL_ERROR(var) => var | TYPE_STRING_ERROR(var) => var | INVALID_FORMAT(var) => var | USED_CL(var) => var | INVALID_CL(var) => var | NO_DATA(var) => var } switch (type_, str) { | (Error, Static(string)) => customAlert(~errorType="error", ~message=string) | (Warning, Static(string)) => customAlert(~errorType="warning", ~message=string) | (Error, Dynamic(fn)) => customAlert(~errorType="error", ~message=fn(dynamicStr)) | (Warning, Dynamic(fn)) => customAlert(~errorType="warning", ~message=fn(dynamicStr)) } } } let useErrorWarningValidationOnLoad = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let isPublishableKeyValid = GlobalVars.isValidPK(nativeProp.env, nativeProp.publishableKey) let isClientSecretValid = RegExp.test( `.+_secret_[A-Za-z0-9]+`->Js.Re.fromString, nativeProp.clientSecret, ) let showErrorOrWarning = useShowErrorOrWarning() () => { if !isPublishableKeyValid { switch nativeProp.sdkState { | PaymentSheet | WidgetPaymentSheet => showErrorOrWarning(ErrorUtils.errorWarning.invalidPk, ()) | HostedCheckout => showErrorOrWarning(ErrorUtils.errorWarning.invalidPk, ()) | CardWidget | CustomWidget(_) | ExpressCheckoutWidget => () | Headless => showErrorOrWarning(ErrorUtils.errorWarning.invalidPk, ()) | NoView | PaymentMethodsManagement => () } } else if !isClientSecretValid { let dynamicStr = "ClientSecret is expected to be in format pay_******_secret_*****" switch nativeProp.sdkState { | PaymentSheet | WidgetPaymentSheet => showErrorOrWarning(ErrorUtils.errorWarning.invalidFormat, ~dynamicStr, ()) | HostedCheckout => showErrorOrWarning(ErrorUtils.errorWarning.invalidFormat, ~dynamicStr, ()) | CardWidget | CustomWidget(_) | ExpressCheckoutWidget => () | Headless => showErrorOrWarning(ErrorUtils.errorWarning.invalidFormat, ~dynamicStr, ()) | NoView | PaymentMethodsManagement => () } } // else if nativeProp.configuration.merchantDisplayName === "" { // let dynamicStr = "When a configuration is passed to PaymentSheet, the merchant display name cannot be an empty string" // showErrorOrWarning(errorWarning.reguirParameter, ~dynamicStr, ()) // } } }
671
10,628
hyperswitch-client-core
src/utility/constants/GlobalVars.res
.res
type envType = INTEG | SANDBOX | PROD let checkEnv = publishableKey => { if publishableKey != "" && publishableKey->String.startsWith("pk_prd_") { PROD } else { SANDBOX } } let isValidPK = (env: envType, publishableKey) => { switch (env, publishableKey) { | (_, "") => false | (PROD, pk) => pk->String.startsWith("pk_prd_") | (SANDBOX, pk) => pk->String.startsWith("pk_snd_") | (INTEG, pk) => pk->String.startsWith("pk_snd_") } }
154
10,629
hyperswitch-client-core
src/utility/constants/GlobalHooks.res
.res
let useGetBaseUrl = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) () => { switch nativeProp.customBackendUrl { | Some(url) => url | None => switch nativeProp.env { | PROD => "https://api.hyperswitch.io" | SANDBOX => "https://sandbox.hyperswitch.io" | INTEG => "https://integ-api.hyperswitch.io" } } } } let useGetS3AssetsVersion = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) () => { switch nativeProp.env { | PROD | SANDBOX | INTEG => "/assets/v1" } } } let useGetAssetUrlWithVersion = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) let appendVersion = useGetS3AssetsVersion()() () => { switch nativeProp.env { | PROD => "https://checkout.hyperswitch.io" | SANDBOX => "https://beta.hyperswitch.io" | INTEG => "https://dev.hyperswitch.io" } ++ appendVersion } } let useGetLoggingUrl = () => { let (nativeProp, _) = React.useContext(NativePropContext.nativePropContext) () => { switch (nativeProp.customBackendUrl, nativeProp.customLogUrl) { | (Some(_), None) => None | (_, Some(url)) => Some(url) | (None, None) => switch nativeProp.env { | PROD => Some("https://api.hyperswitch.io/logs/sdk") | _ => Some("https://sandbox.hyperswitch.io/logs/sdk") } } } }
415
10,630