Dependencies
react: provides state and context management.react-native: provides native UI components used to build the screens.uuid: creates unique identifiers.jose: used for cryptographic operations.react-native-device-info: retrieves device metadata.react-native-webview: displays the 3DS web view.react-native-localize: provides localization support.react-native-network-info: retrieves the device's IP address.react-native-quick-crypto: used for cryptographic operations.react-native-get-random-values: provides random value generation for crypto.@react-native-async-storage/async-storage: persistent storage for app identifiers.@react-native-community/checkbox: renders checkboxes for the UI.@react-native-picker/picker: renders dropdown lists for form fields.react-native-device-info-bridge: bridge for collecting device information.react-native-ecdh-bridge: bridge for generating ephemeral key pairs and encryption.
Nuvei Fields
Description
The Nuvei Fields module is designed to securely collect and process card payment data within a checkout. It provides a customizable interface for entering card details, validating input, and initiating payments.
This module consists of two main parts:
NuveiFieldscomponent – a UI component that renders input fields for cardholder name, card number, expiration date, and CVV. It supports dynamic styling, validations, and localization viai18NLabels. It also manages user interactions, card type detection, and triggers payment initialization.useNuveiFieldshook – a logic layer that handles fields data, input formatting, validation, tokenization, and 3D Secure (3DS) authentication.
initPayment
Overview
Purpose - getPaymentRequestPayload builds and returns the final payment initialization payload (NVPaymentBody) required to start a payment flow.
It merges merchant settings, user payment settings, and card information.
Where it is used - This function is used internally before calling the Nuvei API endpoint for initPayment.
Behavior
- Collects and merges payment-related data from multiple sources (card info, merchant settings, and payment settings).
- Configures the
paymentOptionobject, including saving user payment preferences if provided. - Returns a fully prepared
NVPaymentBodyobject.
What the function does
-
Payload Configuration
- Builds a
paymentOptionobject containing card details and optional parameters:savePm: whether the user wants to save their payment method.userPaymentOptionId: ID of a previously saved payment method, if available.
- Builds a
-
Data Filtering
- Removes
amountandcurrencyfrom the merchant settings before constructing the payload (as per native code requirements).
- Removes
-
Payload Construction
- Combines the following data sources into a single
NVPaymentBody:- Card data (
card) - Merchant settings (
nvPaymentMerchantSettings) - Payment settings (
paymentSettings) - SDK source application metadata
- Card data (
- Ensures compatibility with the Nuvei API’s required structure.
- Combines the following data sources into a single
-
Logging
- Outputs the final payload in the console for debugging purposes before sending the payment request.
Data structure
Request
const payload: NVPaymentBody = {
...nvPaymentMerchantSettings,
...paymentSettings,
paymentOption,
requestTimeout: 10,
timeout: 10,
sourceApplication: sourceApplication,
};
Key functions
getPaymentRequestPayload(card, paymentSettings, source, nvPaymentMerchantSettings)
- Asynchronously constructs the full payment initialization body required by
initPayment.
Behavior:
- Builds the
paymentOptionobject with the provided card. - If available, includes
savePmanduserPaymentOptionIdfrompaymentSettings.paymentOption. - Filters out
amountandcurrencyfrom the merchant settings. - Constructs the final
payloadobject with all merchant, payment, and SDK data. - Logs the payload to the console.
- Returns a
Promiseresolving to the completedNVPaymentBody.
getDeviceDetails()
- Imported utility function used to fetch the current device information (OS version, device model, manufacturer).
- Ensures each payment request includes device metadata.
Integration
import { getPaymentRequestPayload } from './initPayment';
Error handling
Device Info Errors
- If
getDeviceDetails()fails or returnsnull, the payload still initializes withdeviceDetails: undefined.
The SDK will proceed safely without interruption.
Invalid or Missing Data
- If mandatory fields (
sessionToken,amount, orcurrency) are missing, the Nuvei API will reject the request. - It is the responsibility of the caller to validate input data before invoking
getPaymentRequestPayload().
Network Errors
console.log()is used for diagnostic output only.
Diagram and description
flowchart TD
id1["getPaymentRequestPayload()"] ==> contains[Contains]
contains -.- card([card])
contains -.- pay([paymentSettings])
contains -.- src([source])
contains -.- merch([nvPaymentMerchantSettings])
id1 ==> id2["sourceApplication {checkout / direct / fields}"]
id2 ==> id4{paymentOption}
id4 == No ==> id5([savePm = false])
id4 =====> id7[payload: NVPaymentBody]
id4 == Yes ==> id6([savePm = true])
linkStyle 7 stroke:red;
linkStyle 9 stroke:green;
classDef bold font-weight:bold;
classDef smallDiamond stroke:#333,stroke-width:1px,font-size:12px,font-weight:bold;
class id1,id2,id5,id6,id7,contains,card,pay,src,merch bold;
class id4 smallDiamond;
getPaymentRequestPayload()
- Creates payload (NVPaymentBody) for Nuvei, combining card info, merchant settings, and source context.
Input Parameters
- card → Card details provided by the user.
- paymentSettings → Optional payment configuration (save payment method).
- source → Defines the origin of the request (CHECKOUT, DIRECT, FIELDS).
- nvPaymentMerchantSettings → Merchant settings (amount, currency, session token, etc).
Determine source application
-
Default: SIMPLYCONNECT_ANDROID.
-
Switch logic:
-
CHECKOUT: Android → SIMPLYCONNECT_ANDROID;
iOS → SIMPLYCONNECT_IOS.
-
DIRECT: Android → DIRECT_ANDROID;
iOS → DIRECT_IOS.
-
FIELDS: Android → FIELDS_ANDROID;
iOS → FIELDS_IOS.
-
Build payment option
- If
paymentSettings.paymentOption.savePmis defined → setssavePminpaymentOption. - If
userPaymentOptionIdexists → converts to string and assigns topaymentOption.userPaymentOptionId.
Assemble payload
- Removes
amountandcurrencyfromnvPaymentMerchantSettings(as per native code). - Merges filtered merchant settings.
- Identifiers: userTokenId, clientRequestId, countryCode, merchantId, merchantSiteId (from
nvPaymentMerchantSettings). - Payment option:
paymentOption.
Logging
- Logs payload to console →
console.log('Sending sendInitPayment: ', payload);
Return
- Returns the fully constructed
NVPaymentBodyobject.
InputComponent
Overview
Purpose - InputComponent is a reusable component that combines a label, a text input field, and an optional error message into a single layout.
It is designed to standardize form input behavior and styling across an application.
Where it is used - InputComponent can be used anywhere a labeled text input is required.
Behavior
- Displays a label above the text input field.
- Renders a customizable text input using the
TextInputcomponent. - Optionally shows an error message below the input.
- Accepts additional styles for the container, label, input, and error text.
- Fully supports
TextInputprops such asvalue,onChangeText,keyboardType,placeholder.
What the component does
-
Label Rendering
- Displays a text label above the input field.
- Uses default styling defined in the component but allows customization through the
labelStyleprop.
-
Input Field
- Renders a
TextInputcomponent with predefined border, padding, and radius styles. - Allows full customization through the
inputStyleprop or by passing standardTextInputprops.
- Renders a
-
Error Handling
- Optionally displays an error message below the input field.
- The text color and font size can be customized via
errorStyle.
-
Layout and Styling
- The component arranges the label, input, and error vertically.
- Extra layout customization can be applied using the
extraStylesprop.
Data structure
Request
type LabelAndErrorContainerPropsType = PropsWithChildren<{
label: string | undefined;
extraStyles?: object;
errorText?: string;
labelStyle?: TextStyle;
errorStyle?: TextStyle;
}>;
| Name | Type | Description |
|---|---|---|
| label | string | Text displayed above the input. |
| extraStyles | object | Additional styles for the container |
| errorText | string | Text displayed below the input when an error occurs. |
| labelStyle | TextStyle | Custom style for the label text. |
| errorStyle | TextStyle | Custom style for the error message. |
Key components
LabelAndErrorContainer(props)
- A functional component that wraps an input field together with its label and error message.
- Displays the label text above the input.
- Renders any child components (usually a
TextInput). - Shows an optional error message below the input.
- Applies default styles for label and error, allowing custom overrides via props.
InputComponent(props)
- A wrapper component that integrates
LabelAndErrorContainerwith aTextInput, providing a labeled input with error handling. - Combines label, text input, and error message into one component.
- Passes all
TextInputprops (value,onChangeText,keyboardType,secureTextEntry) to the internalTextInput. - Supports style customization for each section (label, input, error, container).
- Allows error message display without managing layout manually.
Integration
import { InputComponent } from './InputComponent';
<InputComponent
{...getInputProps({
fieldName: '...',
labelFieldName: '...',
placeholderFieldName: '...',
})}
/>
Error handling
Validation Errors - The component does not perform validation itself but can display validation messages passed via the errorText prop.
Diagram and description

LabelAndErrorContainer
Provides a wrapper around input fields, displaying a label above and an error message below.
- Receives props: label, extraStyles, errorText, labelStyle, errorStyle, and children.
- Renders a View with vertical layout (flexDirection: 'column').
- Displays the label (Text) styled with styles.label and any custom labelStyle.
- Renders the children (in this case, the TextInput).
- Displays the error message (Text) styled with styles.error and any custom errorStyle.
InputComponent
An input field with label, error handling, and blur event logic.
-
Receives props: label, errorText, extraStyles, labelStyle, inputStyle, errorStyle, blurHandler, fieldName, TextInput props.
-
Determines colorScheme (light or dark) and whether the platform is iOS.
-
Wraps everything inside
LabelAndErrorContainer, passing label, error, and styles. -
Inside the container, renders a
TextInput:- onBlur handler:
- If blurHandler and fieldName are provided → calls blurHandler(restProps.value ?? '', restProps.fieldName).
- Otherwise does nothing.
- Style: Combines default styles.textInput with any custom inputStyle.
- Placeholder color:
- If colorScheme === 'light' or platform is iOS →
use stylesStrings.FIELD_PLACEHOLDER_COLOR.
- Otherwises leaves it undefined.
- Returns the composed UI: label, input field, and error message.
- Styles:
- textInput: Gray border, padding, rounded corners, fixed height.
- error: Red text, small font, margin, max width 80%.
- label: Medium font size, left margin.
- Exported textInputStyles for reuse outside the component.
- onBlur handler:
Summary
LabelAndErrorContainer: Handles layout of label, input, and error.
InputComponent: Provides a styled TextInput with blur handling and placeholder color logic.
Key Behavior:
- Blur event triggers validation via blurHandler.
- Placeholder adapts to theme and platform.
- Error message is always displayed below the input.
NuveiFields
Overview
Purpose - NuveiFields renders a set of input fields for processing card payments. It collects user card data (cardholder name, card number, expiration date, CVV), validates it, and handles tokenization and payment initialization.
Where it is used - This component is used on checkout or payment screens where card payments are accepted.
Behaviour
- Renders form fields for cardholder name, card number (with dynamic card logo), expiration date, and CVV.
- Supports customizable UI via
uiSettings(colors, font sizes, border styles). - Validates all fields before attempting to process a payment.
- Calls
tokenizeandinitPaymentlogic through theuseNuveiFields. - Displays a loading overlay (
ModalBackdrop) during payment initialization. - Calls
onSuccesson successful payment oronFailwhen any error occurs.
What the SDK does
-
Initial Setup
- Accepts props for
transactionDetails,paymentSettings,uiSettings, and callback handlers (onSuccess,onFail). - Initializes all card-related states and logic through
useNuveiFields.
- Accepts props for
-
UI Rendering
- Dynamically builds customized styles based on
uiSettings(border, color, font). - Renders four input fields:
- Cardholder Name
- Card Number (with detected card brand logo)
- Expiration Date
- CVV
- Each field supports localized labels and placeholders via
uiSettings.i18NLabels.
- Dynamically builds customized styles based on
-
Validation and Tokenization
- When the “Pay” button is pressed:
- Calls
validateFields()to check all form inputs. - If validation passes, triggers
initPayment()fromuseNuveiFieldsto begin payment initialization. - Shows
ModalBackdropwhile the payment is processing.
- Calls
- When the “Pay” button is pressed:
-
Success and Error Handling
- If the payment succeeds ->
onSuccess(response)is called. - If it fails or throws an exception ->
onFail(error)is called. - Loading overlay (
ModalBackdrop) disappears once the process completes.
- If the payment succeeds ->
-
Dynamic Card Detection
- Automatically detects card type (
Visa,MasterCard,Maestro) viacheckCardType(). - Displays the appropriate card logo next to the card number input.
- Automatically detects card type (
Data structure
Request
const cardInfo: CardInfo = {
CVV: card.cvv,
cardHolderName: card.cardHolderName,
cardNumber: card.number,
expirationMonth: card.expiry.split('/')[0] || '',
expirationYear: card.expiry.split('/')[1] || '',
};
Key functions and variables
useNuveiFields
- Validation, tokenization, payment initialization.
validateFields
- Checks all input fields for correctness and returns
trueif valid.
tokenize
- Generates a card token.
initPayment
- Initiates backend payment flow.
checkCardType
- Detects card type based on entered card number.
getCreditCardLogo
- Returns brand logo image for detected card type.
Integration
import { NuveiFields } from './src/NuveiFields';
Requirements
transactionDetailsmust be a validTransactionDetailsobject (with amount, currency, merchant details).uiSettingsshould contain all visual customization values (colors, borders, fonts).- A valid
PaymentSettingsobject is required.
Error handling
Validation errors
- If any input field is empty or invalid,
validateFields()returns an error message that appears below the field.
Network or SDK errors
- Errors thrown during
tokenizeorinitPaymenttriggeronFail(error)
Payment declined
- If the backend returns a declined transaction, the component calls
onFailwith the declined response.
UI behavior
- The loader (
ModalBackdrop) is displayed until the operation completes.
Diagram and description

Component: NuveiFields
Purpose - Provides a complete card input and payment initialization for Nuvei, including validation, error handling, tokenization, and 3D Secure challenge.
Props
- paymentSettings: Partial payment configuration.
- transactionDetails: Transaction details (amount, currency, merchant info).
- uiSettings: UI customization (colors, fonts, borders).
- onSuccess: Callback when payment succeeds.
- onFail: Callback when payment fails.
- onInputUpdated: Optional callback when input focus/value changes.
- onInputValidated: Optional callback when validation runs.
- onCardDetailsUpdated: Optional callback when card details change.
- forceWebChallenge: Flag to enforce web challenge.
Context and State
- Uses useNuveiContext for card number error handling. States:
- showEmptyFieldError, validateTriggered, showErrorByField → validation flags.
- isLoading → payment in progress.
- webViewParamsProps, webviewOpen → 3D Secure challenge state.
Callback
- If props.onInputValidated exists → assigns the value to a local onInputValidated.
- If props.onCardDetailsUpdated exists → assigns the value to a local onCardDetailsUpdated.
Input Update Logic
- onUpdated: Splits expiry into month/year and calls onInputUpdated.
Effects
- Clear effect: resets custom card number error to
"". - Effect → opens webview when webViewParamsProps is set.
NuveiFields Hook
- card: Current card state.
- handleInputChange: Updates card fields.
- errors: Validation errors.
- validateFields: Runs validation.
- tokenize: Tokenizes card details.
- initPayment: Initiates payment.
- loadingCardDetails: Loading state for card details.
Validation
- showErrorFields: Marks all fields invalid, triggers validation.
- blurHandler: Marks specific field invalid, validates, resets empty field error, calls onUpdated(false) if value exists.
Imperative Handle hook
- validateFields() → triggers validation.
- tokenize() → tokenizes card details.
Input Props Helper
- getInputProps:
- Builds props for InputComponent
- Resolves labels/placeholders from i18N.
- Sets value to errorText based on validation state.
- Returns styles and handlers.
Card Type and Logo
- Uses checkCardType(card.number) to determine card type.
- Displays appropriate logo (Maestro icon or dynamic logo).
Payment Handler
- Uses payHandler to:
- Validate fields.
- Show error fields.
- If no errors and not loading → calls initPayment().
- On success → calls props.onSuccess.
- On fail → calls props.onFail.
- Always resets isLoading.
Render
- KeyboardAvoidingView → ensures proper keyboard handling.
- ScrollView → wraps inputs.
- InputComponent for cardHolderName.
- LabelAndErrorContainer + TextInput for card number (with logo).
- Two InputComponents side by side for expiry and cvv.
- Button → triggers payHandler.
- WebView3D → handles 3D Secure challenge.
Summary
NuveiFields is the main card input/payment component.
- It manages validation, error display, tokenization, and payment initiation.
- Integrates with 3D Secure (WebView3D) for authentication.
- Customizable via uiSettings and supports i18N labels.
NuveiFields Logic
Overview
Purpose - useNuveiFields manages all the logic for card payment processing in the Nuvei SDK.
It handles user input state, validation, tokenization, and payment initialization.
Where it is used - It is used internally by the NuveiFields component.
Behaviour
- Manages input states for all card fields (number, expiry date, CVV, cardholder name).
- Validates card data.
- Formats and normalizes card number, expiry, and CVV input.
- Handles tokenization via
tokenizePost(). - Initializes payment through the 3D Secure authentication process.
- Tracks and updates validation errors dynamically.
- Exposes main actions and states to the parent component.
What the SDK does
-
State Management
- Stores card data (
number,expiry,cvv,cardHolderName) usinguseState. - Tracks field-specific error messages in a state object (
errors). - Keeps reference to fetched
cardDetailsafter callinggetCardDetails().
- Stores card data (
-
Input Handling
- Dynamically formats the following:
- Card Number: grouped into 4-digit segments (
#### #### #### ####). - Expiry Date: formatted as
MM/YY. - CVV: restricted to numeric characters.
- Card Number: grouped into 4-digit segments (
- Automatically updates local state after each change.
- Dynamically formats the following:
-
Validation
- Ensures all fields contain valid data before proceeding with payment.
- Performs the following checks:
- Card number validity (
checkCardType()). - Expiry format and expiration date.
- CVV length based on card type.
- Cardholder name (letters only, non-empty).
- Card number validity (
- Returns
trueif there are errors,falseif validation passes.
-
Tokenization
- Sends card data securely to the Nuvei API using
tokenizePost(sessionToken, card). - Returns a
ccTokenthat represents the card details without exposing sensitive information.
- Sends card data securely to the Nuvei API using
-
Payment Initialization
- Builds a
CardInfoobject and triggers the 3D Secure authentication viauseAuth3D(). - Handles both success and failure outcomes via
onSuccessandonErrorcallbacks. - Returns a
Promisethat resolves once the payment process completes.
- Builds a
Data structure
Request
const cardInfo: CardInfo = {
CVV: card.cvv,
cardHolderName: card.cardHolderName,
cardNumber: card.number,
expirationMonth: card.expiry.split('/')[0] || '',
expirationYear: card.expiry.split('/')[1] || '',
};
Key functions
handleInputChange(field, value)
- Updates card input state with formatted values.
- Applies different formatting rules depending on the field:
number: formats as groups of 4 digits.expiry: ensuresMM/YYformat.cvv: digits only.
- Triggers validation on change (if implemented).
validateFields()
- Validates all card input fields before payment.
- Uses helper functions like
checkCardType,validateExpiry,validateCVV, andvalidateName. - Returns: An object containing:
hasErrors: boolean->trueif errors exist.newErrors: errorsType-> an object containing field-specific error messages.
Validation includes:
- Correct expiry date format and validity.
- Correct CVV length based on card type.
- Valid card number format.
- Valid cardholder name (non-empty and properly formatted).
tokenize()
- Sends card data and session token to the Nuvei API for tokenization.
Behavior:
- Builds the request body with card data.
- Calls
tokenizePost(sessionToken, card). - Awaits the Nuvei response containing a tokenized card.
- Returns the response to be used in
initPayment().
initPayment(onComplete)
- Initializes the full payment process, including 3D Secure flow.
Steps:
- Constructs a
CardInfoobject from the current card state. - Calls
auth3D()to trigger 3D Secure authentication. - Uses provided
paymentSettingsandtransactionDetails. - Resolves or rejects based on the payment result.
fetchCardInfo(cardNumber)
- Retrieves additional details about the provided card number using
getCardDetails().
Integration
import { useNuveiFields } from './NuveiFields.logic';
Error handling
Validation errors
- Detected in
validateFields(). - Errors are stored in the
errorsstate and displayed below input fields.
Network or SDK errors
- If
tokenizeorinitPaymentfails, the parent component callsonFail(error).
3D Secure authentication errors
- Returned by
auth3D()through theonErrorcallback.
Diagram and description

useNuveiFields
This hook manages all logic required for handling credit card input fields, validating them, formatting user input, fetching card details, and initializing a payment using 3DS authentication.
- Initialization When the hook is executed, it initializes:
- Card – number, expiry, CVV, and card holder name.
- Errors – validation errors for each field.
- Loading (loadingCardDetails) – indicates when card details are being fetched.
Retrieves:
- Nuvei context (setCustomNuveiFieldsCardNumberError)
- 3DS authentication handler (auth3D)
- Handling Input Changes (handleInputChange) Whenever the user types into any card field:
2.1 Trigger onUpdated - onUpdated(true)
-
Marks the field as focused or updated.
2.2 Clear previous validation
-
Removes the card number block error.
-
Clears UI error flags for the field.
2.3 Format and validate the field
-
Field Formatting
-
number: Groups digits into XXXX XXXX XXXX XXXX
-
expiry: Converts to MM/YY format
-
cvv: Removes all non-digits
-
cardHolderName: Text
After formatting, the hook updates state and validates using setCardPropAndValidate()
-
Getting Card Details Inside setCardPropAndValidate, after updating the card:
3.1 Detect card type
-
const parsedCard = getParsedCard(value);
3.2 If card type is valid it fetches card details
-
const res = await getCardDetails(body);
-
If successful: Extracts info, bin, last 4 digits, brand.
-
Sends results back to parent via: onCardDetailsUpdated(cardData, null);
-
If failed: onCardDetailsUpdated(null, errorObject);
- Validating Fields (validateFields) When the user attempts to proceed with payment:
4.1 Validate each field Number: card format + card type detection Expiry: MM/YY format, month range, date not expired CVV: correct length based on card type Name: non-empty + valid characters
4.2 Create error list
-
All failed validations are collected and passed to onInputValidated(errorCodes)
4.3 Update errors state
-
If any errors exist UI is updated
-
If there are no errors error state is cleared
- Tokenizing Card Data (tokenize)
-
Wrapper around: tokenizePost(transactionDetails.sessionToken, card)
-
Used when a token is needed.
- Initializing Payment (initPayment)
-
When ready to charge the card:
6.1 Prepare card info object
const cardInfo = {
CVV,
cardNumber,
cardHolderName,
expirationMonth,
expirationYear
}
6.2 Trigger 3DS authentication
auth3D({...})
This handles:
- challenge screens
- frictionless flows
- success and error callbacks
NuveiFieldsContext
Overview
Purpose - This context acts as a layer for managing shared state across all components related to the Nuvei Fields module.
This pattern is essential when working with complex validation, payment forms, or user input formatting. By using a context provider, the module becomes scalable and easier to maintain.
Diagram and description

- Context Creation
const Context = createContext<ContextType>({});
A context is created with a default value — currently an empty object.
- Provider Component
const NuveiFieldsContextProvider = (props) => {
return <Context.Provider value={{}}>{props.children}</Context.Provider>;
};
The provider wraps part of the React structure and uses a context value.
The value is {}, but this is a placeholder for future shared logic.
All components inside <NuveiFieldsContextProvider> can access the context.
- useNuveiFieldsContext Hook
export const useNuveiFieldsContext = () => useContext(Context);
This hook gives the using component direct access to the context.
ApplePay / GooglePay
Description
This module provides Google Pay and Apple Pay buttons for the checkout. It lets users pay quickly with saved cards.
The module consists of these two parts:
GooglePayButton- Uses
PaymentRequestfor Google Pay flow. - Checks
canMakePayment()and shows the payment form. - Gets a token and sends it to the backend (
initPayment+clientPaymentIosAndroid). - Calls
onSuccesswhen payment succeeds,onErroron failure. - Shows a loading backdrop while processing.
- Uses
ApplePayButton- Uses a
useApplePayhook to open Apple Pay on iOS. - Receives the Apple Pay payment response and sends it to backend (
clientPaymentIosAndroid). - Calls
onSuccess/onErrorbased on backend result.
- Uses a
ApplePay
Overview
Purpose - The ApplePayButton component initiates and handles Apple Pay transactions for iOS devices.
It provides a payment button that triggers the Apple Pay, processes the transaction, and returns the result through success or error callbacks.
Where it is used - On any checkout or payment screen where Apple Pay should be offered as a payment option.
What the component does
- Renders an Apple Pay button on iOS.
- Uses the
useApplePayhook to launch the Apple Pay with providednvPaymentdetails. - Sends the resulting payment token to the backend using
clientPaymentIosAndroid. - Handles different payment response statuses:
- Success -> triggers
onSuccesscallback with the response object. - Error / Declined -> triggers
onErrorcallback with an error object.
- Success -> triggers
- Returns
nullif nonvPaymentdata is provided (prevents rendering the button).
Data structure
Request
export type ApplePayButtonType = {
nvPayment: NVPaymentBody | null;
applePayMerchantId: string;
onSuccess: (res: any) => void;
onError: (res: any) => void;
};
const body = {
country: nvPayment.countryCode,
merchantId: nvPayment.merchantId,
mobileToken: JSON.stringify({
paymentData: paymentResponse,
}),
sessionToken: nvPayment.sessionToken,
merchantSiteId: nvPayment.merchantSiteId,
email: nvPayment.userTokenId,
platform: 'IOS',
};
Response
const dto: IClientPayment = {
merchantSiteId: input.merchantSiteId,
merchantId: input.merchantId,
paymentOption: {
card: {
externalToken: {
externalTokenProvider: isiOS ? APPLE_PAY_TOKEN : GOOGLE_PAY_TOKEN,
mobileToken: input.mobileToken,
},
},
paymentMethod: isiOS ? APPLE_PAY_TYPE_STAGING : GOOGLE_PAY_TYPE_STAGING,
},
sessionToken: input.sessionToken,
};
Key functions
useApplePay
- Custom hook that manages Apple Pay initialization and the payment flow.
handlePayment(_values, paymentResponse)
- Called after Apple Pay is completed.
- Builds the payment body and calls the backend service.
- Checks the response status and triggers the appropriate callback.
initiateApplePay()
- Triggered when the button is pressed.
- Launches the Apple Pay with the transaction amount, currency, and merchant ID.
- Catches and handles payment errors.
clientPaymentIosAndroid(body)
- Backend call that processes the Apple Pay transaction and returns the payment status.
ResponseStatuses
- Enum used to check whether the backend transaction succeeded or failed.
Integration
import { ApplePayButton } from './src/ApplePayButton';
Requirements
- Apple Pay must be configured for the app and device.
- A valid merchant ID must be passed via
applePayMerchantId. - The
nvPaymentobject must contain all required fields. - The backend must support the payment token generated by Apple Pay.
Error handling
- If
nvPaymentis not provided, the component returnsnull(button not rendered). - If the backend response status is not
SUCCESSor the transaction isDECLINED, theonErrorcallback is triggered with an error object. - If Apple Pay fails or is cancelled, the error is caught and logged, and
onErroris triggered. - The transaction logs are output to the console for debugging:
client payment bodyresponseClientPaymentPayment failedmessage if the process fails.
Diagrams and Screenshots
flowchart TD
id1[User clicks ApplePayButton] ==> id2["onPress()"]
id2 ==> id3{"initiateApplePay()"}
id3 == Fail ==> id4(["console.error('Payment failed')"])
id4 ==> fail(["onError(error)"])
id3 == Success ==> id5(["onApplePay()"])
id5 ==> id6["handleClientPayment()"]
id6 ==> id7{"clientPaymentIosAndroid"}
id7 == Fail ==> id8(["onError(errorObj)"])
id7 == Success ==> id9(["onSuccess(response)"])
classDef smallDiamond stroke:#333,stroke-width:1px,font-size:12px;
classDef bold font-weight:bold;
class id3,id7 smallDiamond;
class id1,id2,id3,id4,id5,id6,id7,id8,id9,fail bold;
linkStyle 2,7 stroke:red;
linkStyle 4,8 stroke:green;
onPress()
- Triggered when the user taps the Apple Pay button.
initiateApplePay()
- Calls
onApplePay()with payment details. - Provides
paymentValues(country, currency, amount, label). - Provides merchantId (Apple Pay merchant identifier).
- Wraps call in try/catch to handle errors.
onApplePay({paymentValues, merchantId})
- Function returned by the
useApplePayhook. - Opens the Apple Pay sheet on iOS.
- Lets the user confirm payment details.
- Returns a
paymentResponsecontaining encrypted Apple Pay data. - Passes the response into
handlePayment().
handleClientPayment(mobileToken)
- Executed after Apple Pay returns a response.
- Builds a request body with transaction and merchant details.
- Includes
mobileTokencontaining the encrypted Apple Pay paymentData. - Calls
clientPaymentIosAndroid(body)to send payment to backend. - Checks backend response for status and transaction result.
- If status is not SUCCESS or transaction is DECLINED → calls
onError(). If successful → callsonSuccess().
clientPaymentIosAndroid(body)
- Sends the payment request to the backend.
- Validates and finalizes the transaction using the mobile token.
- Returns a response with status and transactionStatus.
- Used to determine whether to call
onSuccess()oronError().
Screenshots




- The ApplePay screen contains one button -
Pay. - After the button is clicked the interface prompts the user to add a payment card. It also indicates a transaction of 160.00 euros to nuvei.com, with the label. The layout includes the Apple Pay logo and a button to initiate card addition.
- The next screen provides instructions for adding a credit, debit, or store card to Apple Pay. A button labeled
(Continue)is displayed at the bottom of the screen. - The screen instructs the user to position their debit or credit card within a frame for scanning. It also offers an alternative option to manually enter card details.
- This screen is for entering payment card details. The main heading is “Детайли на карта” (“Card Details”), followed by the instruction
(Enter your card information.). Below are two input fields: one labeled(Name)with the example value “Dohn Doe,” and another labeled(Card Number)for the card number. (The app hides sensitive information when taking a screenshot.) - The main heading is
(Card Details), followed by the instruction(Enter your card information.). Input fields are provided for(Expiration Date)and(Security Code), indicating that the user is expected to enter sensitive payment information. (The app hides sensitive information when taking a screenshot.) - The total amount due is indicated as
(Total 160.00 €). At the bottom of the screen, there is a button labeled(Add payment card), prompting the user to proceed with entering payment details.
GooglePay
Overview
Purpose - GooglePayButton renders a Google Pay payment control and handles the full client-side flow for Google Pay payments. It uses onSuccess and onError callbacks so parent screens can react to a completed or failed payment.
Where it is used - This component is used on checkout or payment screens where Google Pay is offered as a payment option.
Behaviour
- Renders a tappable Google Pay image + native
GooglePayButtoncomponent. - Checks whether Google Pay is available (
paymentRequest.canMakePayment()). - Shows the Google Pay sheet (
paymentRequest.show()), receives a payment token, then:- Calls
initPayment(backend initialization). - Calls
clientPaymentIosAndroid(finalize client payment).
- Calls
- Calls
onSuccesson successful transaction oronErroron any failure.
What the component does
- If
nvPaymentisnull, renders nothing (return null). - Creates a
PaymentRequestusinggooglePayRequestData(merchant info and country) andpaymentDetails(total amount + currency). - When user taps the button:
- Calls
paymentRequest.canMakePayment()— iffalse, triggersonError({ reason: 'Google Pay unavailable' }). - If
true, callspaymentRequest.show()which opens the Google Pay sheet.
- Calls
- After the user completes the sheet, the component extracts
paymentMethodDatafrom the response (referred to asmobileToken) and callshandleClientPayment. handleClientPayment:- Builds an
initPaymentrequest body (includespaymentOption.card.externalTokenwith providerGooglePayand the mobile token). - Calls
initPayment(...)and validates the response (checksResponseStatuses.SUCCESSandtransactionStatus !== 'DECLINED'). - If
initPaymentis OK, callsclientPaymentIosAndroid(...)with the mobile token and merchant/session identifiers. - If
clientPaymentIosAndroidsucceeds, callsonSuccess(resp). Otherwise callsonError(errorObj).
- Builds an
- Shows a
ModalBackdropwhileisLoadingis true.
Data structure
Request
export type GooglePayRequestDataType = {
merchantInfo: {
merchantId: string;
merchantName: string;
};
transactionInfo: {
countryCode: string;
};
};
const paymentDetails: PaymentDetailsType = {
total: {
amount: {
currency: nvPayment.currency,
value: nvPayment.amount,
},
},
};
const googlePayRequestData: GooglePayRequestDataType = {
merchantInfo: {
merchantId: String(nvPayment.merchantId),
merchantName: 'com.nuveisimplyconnectexample',
},
transactionInfo: {
countryCode: nvPayment.countryCode,
},
};
const initPaymentBody: NVPaymentBody = {
amount: nvPayment.amount,
billingAddress: {
email: nvPayment.userTokenId,
country: nvPayment.countryCode,
address: '',
city: '',
state: '',
zip: '',
},
currency: nvPayment.currency,
merchantId: nvPayment.merchantId,
merchantSiteId: nvPayment.merchantSiteId,
paymentOption: {
card: {
externalToken: {
externalTokenProvider: 'GooglePay',
mobileToken: mobileToken,
},
},
useInitPayment: true,
},
sessionToken: nvPayment.sessionToken,
sourceApplication: sourceApplication,
};
Key functions and variables
paymentDetails
- Object describing total amount / currency passed to
PaymentRequest.
googlePayRequestData
- Merchant info and country code used to initialize
PaymentRequest.
onPress
- Checks availability (
canMakePayment) then callsshowPaymentForm.
showPaymentForm
- Calls
paymentRequest.show()to open Google Pay; extractspaymentMethodDataand forwards it tohandleClientPayment.
handleClientPayment(mobileToken: string)
initPayment(initPaymentBody)- initializes / authorizes on the backend.- If OK,
clientPaymentIosAndroid(...)- finalizes payment on the backend. - Calls
onSuccessoronErroraccordingly.
ModalBackdrop
- UI overlay shown while
isLoading === true.
NativeGooglePayButton
- Component loaded via
requireNativeComponent('GooglePayButton'). This requires a corresponding view on Android / iOS.
Integration
import { GooglePayButton } from './src/GooglePayButton';
Requirements
nvPaymentmust be non-null and contain required fields.- Google Pay must be configured properly for the merchant
Error handling
- If
nvPaymentisnull-> component returnsnull(no rendering). - If
paymentRequest.canMakePayment()fails or returnsfalse->onError({ reason: 'Google Pay unavailable' }). - Any runtime error during
canMakePayment,show(),initPaymentorclientPaymentIosAndroidis caught and forwarded toonError. - Backend responses:
- If
status !== ResponseStatuses.SUCCESS, the component returns responsestatus = 'ERROR'and callsonError. - If
transactionStatus === 'DECLINED', the component returns responsestatus = 'DECLINED'and callsonError.
- If
Diagrams and Screenshots
flowchart TD
id1[User clicks GooglePayButton] ==> id2["onPress()"]
id2 ==> id3{canMakePayment}
id3 == No ==> id4(["onError({reason:'GooglePay unavailable'})"])
id3 == Yes ==> id5(["showPaymentForm()"])
id5 ==> id6["paymentRequest.show()"]
id6 ==> id7["handleClientPayment(mobileToken)"]
id7 ==> id8{"initPayment"}
id8 == Fail ==> id9(["onError(errorObj)"])
id8 == Success ==> id10(["onSuccess(respClientPayment)"])
classDef smallDiamond stroke:#333,stroke-width:1px,font-size:12px;
classDef bold font-weight:bold;
class id3,id8 smallDiamond
class id1,id2,id3,id4,id5,id6,id7,id8,id9,id10 bold;
linkStyle 2,7 stroke:red
linkStyle 3,8 stroke:green;
onPress()
- Triggered when the user taps the Google Pay button.
- Checks if Google Pay is available on the device by calling
paymentRequest.canMakePayment().
showPaymentForm()
- Displays the Google Pay payment sheet to the user.
- Waits for the user to select a payment method.
paymentRequest.show()
- Opens the Google Pay UI and lets the user confirm payment details.
- Returns a response object containing paymentMethodData.
- This is where the actual Google Pay interaction happens.
handleClientPayment(mobileToken)
- Handles the full payment flow.
- Builds the
initPaymentBodyrequest containing transaction, merchant, and token details. - Calls
initPayment()first, thenclientPaymentIosAndroid()to finalize. - Manages loading state
(isLoading)and error handling. - Decides whether to call
onSuccess()oronError()based on responses.
initPayment(initPaymentBody)
- Sends the payment request to the backend.
- Validates the transaction.
- Returns a response with status and transaction details.
- If status is not SUCCESS or transaction is DECLINED → triggers
onError(). ElseonSuccess().
Screenshots


- This screen displays a list of saved credit and debit cards, including
Visa,MasterCard, andAmerican Express. At the top of the screen, there is an option to add a payment method via Google Pay, highlighted by a button labeled(Buy with Google Pay). This interface allows users to manage their stored payment options and integrate Google Pay for transactions. - The screen contains a dropdown arrow next to the selected card, which allows users to expand and view a list of saved payment cards. The bottom of the screen displays the payment amount of
153.00 €, a button labeled(Pay now), and a note indicating that the payment will be executed according to the selected method. - This screen is for managing payment methods within the Google Pay app. The heading is
(Change payment method), followed by a list of recently used cards. This interface allows users to review the results of previous payment attempts and select a preferred method. The dropdown arrow next to each card enables access to the full list of saved payment options.
SimplyConnect
useCheckout
The useCheckout hook is the primary entry point for integrating the SimplyConnect checkout flow. it initializes the necessary context states and returns a function to trigger the navigation to the checkout screen.
Signature:
const startCheckout = useCheckout(
settings: UseCheckoutSettingsType,
countryCode: string,
navigate: () => void,
onSuccess: (response: any) => void,
onFail: (error: any) => void,
checkoutI18NFields?: i18NFieldsType
);
Usage:
import { useCheckout } from 'react-native-nuvei';
const startCheckout = useCheckout(
{ forceWebChallenge: false },
'US',
() => navigation.navigate('Checkout'),
(res) => console.log('Success', res),
(err) => console.log('Error', err)
);
// To trigger:
startCheckout({
merchantId: '...',
merchantSiteId: '...',
sessionToken: '...',
amount: '10.00',
currency: 'USD',
});
Description
The Simply Connect module provides a UI and logic for letting customers pick and use payment methods. It fetches the merchant’s available payment methods and the user’s saved payment options, shows them in a list, and handles payments that require a web page (3DS).
This module consists of these main parts:
-
SimplyConnectContextProvider– central part for the module. It loads:- user’s saved payment options (via
getUserUpos) - the merchant’s available payment methods (via
getMerchantPaymentMethods).
- user’s saved payment options (via
-
PaymentMethodProvider– context for a single payment method card (either a saved user method or a merchant method). It holds field values (card number, CVV, name), error visibility, and save payment method preference. -
MyPaymentMethods– lists the user’s saved payment methods. Chooses the correct logo per card brand and wraps each item withPaymentMethodProvider. -
SelectPaymentMethod– lists the merchant’s supported payment methods, filters out excluded methods, shows titles/logos and wraps each withPaymentMethodProviderso the user can choose and fill needed fields. -
WebView– opens payment pages or challenges inside a modal WebView. It listens to navigation changes, detects completion URLs, callscheckPaymentStatus, and triggers the global success/fail callbacks from the Nuvei context. -
SimplyConnectScreen(Content) – the visible screen that combines everything: optional Apple Pay / Google Pay buttons (if merchant supports them),MyPaymentMethods,SelectPaymentMethod, a loader/backdrop while data loads, and the WebView modal.
SimplyConnectContext
Overview
Purpose - SimplyConnectContextProvider is a component that provides logic for the SimplyConnect payment flow. It handles merchant-supported payment methods and user payment options, stores the currently selected payment card, manages loading and webview states.
Where it is used - This component is used to wrap screens and components that participate in the SimplyConnect flow — SimplyConnectScreen, MyPaymentMethods, SelectPaymentMethod, and WebView — providing them access to merchant payment data, user payment options, selected card details.
Behavior
- Fetches merchant payment methods and user payment options when the
nvPaymentMerchantSettingsfromuseNuveiContext()is available. - Tracks loading state (
isLoading) during network requests and after data updates. - Stores the currently selected card in
selectedCardand allows updates throughsetSelectedCard. - Provides a
webviewUrlstring for WebView-based payment flows. - Exposes a
refetch()method to manually re-fetch merchant and user payment data. - Automatically updates when the
nvPaymentMerchantSettingschanges.
What the context does
-
User Payment Options (UPOS)
- Fetches saved user payment methods using
getUserUpos()when a validnvPaymentMerchantSettingsis present. - Stores the response in
userPayments. - Used by
MyPaymentMethodsto display saved payment methods .
- Fetches saved user payment methods using
-
Merchant Payment Methods
- Fetches merchant-supported payment methods using
getMerchantPaymentMethods(). - Saves the response in
merchantPayments. - Enables UI components to display available payment methods (credit card, Apple Pay, Google Pay).
- Fetches merchant-supported payment methods using
-
Selected Card Management
- Maintains a
selectedCardobject containing:paymentMethodNametype(fromPaymentCardTypes)userPaymentOptionId
- Allows setting the user’s currently selected payment option through
setSelectedCard.
- Maintains a
-
Loading State
- Uses the
isLoadingflag to indicate ongoing network requests. - Set to
trueinitially and switched tofalseonce fetching completes. - Can be used by
BackdropLoaderto show/hide loading indicators.
- Uses the
-
WebView URL
- Stores a
webviewUrlstring that can be used to display external or embedded payment pages. - Managed through
setWebviewUrl.
- Stores a
-
Data Refetching
- Provides a
refetch()function to refresh user and merchant payment data manually.
- Provides a
Data structure
Request
type ContextType = {
userPayments: UserUposResponseType | null;
setUserPayments: (value: UserUposResponseType) => void;
refetch: () => Promise<void>;
merchantPayments: MerchantMethodsResponse | null;
setMerchantPayments: (value: MerchantMethodsResponse) => void;
selectedCard: SelectedCardType;
setSelectedCard: (value: SelectedCardType) => void;
isLoading: boolean;
setIsLoading: (value: boolean) => void;
webviewUrl: string;
setWebviewUrl: (value: string) => void;
};
type SelectedCardType = {
paymentMethodName: PaymentMethodNames | '';
type: PaymentCardTypes;
userPaymentOptionId: null | number;
};
| Name | Description |
|---|---|
userPayments | User's saved payment options fetched from getUserUpos() |
merchantPayments | Merchant's supported payment methods fetched from getMerchantPaymentMethods(). |
selectedCard | Currently selected payment card or method. |
isLoading | Indicates whether data is being loaded. |
webviewUrl | URL string for WebView-based payment flows. |
refetch | Manually triggers re-fetching of merchant and user payment data. |
setUserPayments | Updates user payment data. |
setMerchantPayments | Updates merchant payment data. |
setSelectedCard | Updates the currently selected card. |
setIsLoading | Sets the loading state. |
setWebviewUrl | Updates the current WebView URL. |
Key functions
SimplyConnectContextProvider
- Component that creates and provides context values for the SimplyConnect flow.
- Automatically fetches merchant and user payment data based on the current
nvPaymentMerchantSettingsfromuseNuveiContext(). - Re-fetches data whenever the
nvPaymentMerchantSettingschanges.
fetchData
- Asynchronous function that:
- Calls
getUserUpos()to retrieve user payment methods. - Calls
getMerchantPaymentMethods()to retrieve merchant-supported methods. - Updates
userPaymentsandmerchantPaymentsstate. - Handles loading state via
setIsLoading(true/false). - Catches and logs any network errors.
- Calls
Integration
import SimplyConnectContextProvider, { useSimplyConnectContext } from './Context/SimplyConnectContext';
Error handling
Missing merchant settings
- If
nvPaymentMerchantSettingsfromuseNuveiContext()is not available,fetchData()immediately returns and no network requests are made. - Ensure that
useNuveiContext()correctly provides a validnvPaymentMerchantSettingsobject before rendering this provider.
Network errors
- Both API calls (
getUserUpos,getMerchantPaymentMethods) are wrapped in a try/catch block. - Errors are logged to the console but do not crash the app.
isLoadingis always set tofalsein thefinallyblock, ensuring the UI does not remain stuck in a loading state.
Data loading
- The
isLoadingstate should be properly used by UI components (likeBackdropLoader) to represent ongoing operations. - Make sure to reset or update the loading indicator after manual refetches if necessary.
Diagram and description

SimplyConnectContext is a context provider responsible for managing and sharing all data related to:
- The user’s payment options (User UPOs).
- The available merchant payment methods.
- The currently selected payment card.
- The loading state of payment data.
- A dynamic WebView URL used for web actions.
- Refetch logic for refreshing the user and merchant payment data.
This context acts as the central data layer for the Simply Connect module, allowing different UI components to access, update, and react to payment-related information.
- Initialize default context
A context is created with a default object, ensuring that consuming components always receive consistent data and this avoids errors.
- Define internal state using useState
The provider maintains several state variables:
- userPayments - saved user payment options (UPOs).
- merchantPayments - available payment methods for merchant.
- selectedCard - currently selected credit/debit/payment option.
- webviewUrl - URL for WebView payments.
- isLoading - prevents UI rendering before data is loaded.
These values are exposed globally through the Provider.
const { nvPaymentMerchantSettings } = useNuveiContext();
The payment methods cannot be fetched until the merchant settings are available.
- fetchData()
This function is responsible for API calls and state updates:
- Prevents execution if nvPaymentMerchantSettings is not yet loaded.
- Fetches user payment methods.
- Fetches merchant payment methods.
- Saves both responses to state.
- Handles loading and errors.
- Fetch User UPOs
getUserUpos({
countryCode,
currencyCode,
merchantId,
merchantSiteId,
sessionToken,
});
Returns user-specific saved credit cards, debit cards, or other payment options.
- Fetch Merchant Payment Methods
getMerchantPaymentMethods({
countryCode,
languageCode,
merchantId,
merchantSiteId,
sessionToken,
userTokenId,
});
Returns a list of all payment types supported for the merchant in that country.
- Save fetched data to state
setUserPayments(userUpos);
setMerchantPayments(merchantPaymentTypes);
This makes the data accessible to all UI components via context.
- Update loading state
The state isLoading is set to false to indicate that the process is completed.
setIsLoading(false);
This signals the UI to render components relying on payment data.
- Trigger fetchData automatically
The Provider fetches data immediately once the merchant settings become available:
useEffect(() => {
fetchData();
}, [nvPaymentMerchantSettings]);
Ensures that data is always up to date.
- Expose values and actions through Provider
The Provider makes all important values accessible:
- payment data
- loading state
- setters
- refetch function
- selected card
- WebView URL
All child components gain full access through the context.
- Access via useSimplyConnectContext
Consumers can easily access the context using:
const { userPayments, selectedCard, refetch } = useSimplyConnectContext();
This makes the SimplyConnect module scalable, testable, and easy to maintain.
PaymentMethodCardContext
Overview
Purpose - PaymentMethodProvider provides the current user and merchant payment method data, card metadata (title, logo, type), input values, and setters (for values, error display and whether to save the payment method). The provider also initializes default card fields (number, CVV, name, expiry) when merchant card data is present.
Where it is used - It is used to wrap components that render or edit details for a specific payment method. The function usePaymentMethodContext() is called to read and update method details.
Behavior
- Exposes an object with:
- read-only information:
userMethodData,merchantMethodData,title,logoURL,cardType,paymentMethodType,localUrl. - editable state:
values,showErrors,savePm. - setters:
setNewValue,setShowErrors,setSavePm.
- read-only information:
- On mount, if
merchantMethodData.paymentMethod === PaymentMethodNames.cc_card, it seedsvalueswithdefaultCardDetailsfromuseNuveiContext():MerchantCardProps.NUMBER-> card numberMerchantCardProps.CVV-> CVVMerchantCardProps.NAME-> card holder nameMerchantCardProps.DATE->MM/YYYY
- Keeps
valuesas a string dictionary so UI components can bind to keys. - Provides
setNewValue(key, value)which merges the new key intovalues.
What the context does
-
Payment Method State
- Provides a single source for all data and UI state related to a chosen payment method (merchant + user data, card metadata, input values and flags).
-
Seeds Card Inputs
- When the merchant method is a credit card (
PaymentMethodNames.cc_card), the provider auto-populates common card fields fromdefaultCardDetailsexposed byuseNuveiContext().
- When the merchant method is a credit card (
-
Field Management
valuesholds current input values.setNewValue(key, value)safely merges updates intovalues. This enables form inputs to save by key (for example:"cardNumber","expiry","cvv").
-
Error and Save Controls
showErrorsandsetShowErrorscontrol global visibility of validation errors for the payment UI.savePmandsetSavePmindicate whether the user chose to save the payment method (can betrue,false, orundefinedif not set).
Data structure
Request
type ContextType = {
userMethodData: UserPaymentMethodType | null;
merchantMethodData: MerchantPaymentMethod | null;
title: string;
logoURL: string;
cardType: PaymentCardTypes;
paymentMethodType: PaymentMethodNames | null;
values: PaymentDetailsContextType;
setNewValue: (key: string, value: string) => void;
showErrors: boolean;
setShowErrors: (value: boolean) => void;
savePm: boolean | undefined;
setSavePm: (value: boolean) => void;
localUrl?: string;
};
| Name | Description |
|---|---|
userMethodData | User's saved payment method information. |
merchantMethodData | Merchant-provided method metadata. |
title | Display title for the payment method. |
logoURL | URL to icon/logo. |
cardType | Enum describing card grouping (MY_METHOD, MERCHANT_METHOD). |
paymentMethodType | Enum name of the payment method ( cc_card, ppp_GooglePay). |
values | Key -> value map for input fields for this method. |
setNewValue | Merge a value into values. |
showErrors | Validation errors. |
setShowErrors | Setter for showErrors. |
savePm | Whether user chose to save the payment method. |
setSavePm | Setter for savePm. |
localUrl | Optional local URL for the payment method. |
Key functions and variables
PaymentMethodProvider()
Top-level provider component that accepts the props below and returns a context provider wrapping children.
States
const [showErrors, setShowErrors] = useState(false);- Controls whether UI should display validation errors.
const [values, setValues] = useState<Record<string,string>>({});- Holds current input values for this payment method.
const [savePm, setSavePm] = useState<undefined | boolean>(undefined);- Tracks the user's save preference.
const { defaultCardDetails } = useNuveiContext();- Used to prefill card values when merchant method is
cc_card.
- Used to prefill card values when merchant method is
setNewValue(key, value)
- Functional updater that merges new key/value into
values
Seeding behavior ( useEffect() )
- Runs once on mount and, if
merchantMethodData?.paymentMethod === PaymentMethodNames.cc_card, seeds these key value pairs:MerchantCardProps.NUMBER,defaultCardDetails.cardNumberMerchantCardProps.CVV,defaultCardDetails.CVVMerchantCardProps.NAME,defaultCardDetails.cardHolderNameMerchantCardProps.DATE,${expirationMonth}/${expirationYear}(if both are valid)
Integration
import PaymentMethodProvider from './PaymentMethodCard/Context/PaymentMethodCardContext';
Example usage (SelectPaymentMethod)
return (
<PaymentMethodProvider
userMethodData={null}
merchantMethodData={methodData}
key={index}
title={getTitle()}
logoURL={
methodData.logoURL ? methodData.logoURL.replaceAll('svg', 'png') : ''
}
cardType={PaymentCardTypes.SELECT_METHOD}
paymentMethodType={methodData.paymentMethod}
>
<PaymentMethodCard SvgLogo={logoSvg} />
</PaymentMethodProvider>
);
Error handling
Missing useNuveiContext / defaultCardDetails
- If
useNuveiContext()doesn't providedefaultCardDetails, the provider won't seed card fields. The provider does not throw — it simply skips seeding when data is not available.
merchantMethodData mismatch
- The provider seeds values only when
merchantMethodData.paymentMethod === PaymentMethodNames.cc_card.
Invalid seeded data
- Expiry is set only when both
expirationMonthandexpirationYearare present. If either is missing or invalid theDATEkey will not be set.
Concurrent updates
setNewValueuses updates (merging old state). If multiple components update the same key at the same time, last update is used.
Diagram and description

PaymentMethodCardContext manages the state and behavior required to handle a specific payment method. This context provides:
- Metadata about the selected payment method (name, logo, card type).
- User-specific method data (saved payment method info).
- Merchant-specific configuration for this payment method.
- Default field values (auto-filled card details).
- User-entered values for payment fields.
- Validation error toggles.
- Option to save the payment method.
- Optional local URL for WebView.
The provider is responsible for payment-method-related logic and makes it accessible to nested components.
- Context initialization
A context is created with a predefined structure. Default values prevent errors before actual data loads.
- Props received
The provider receives important metadata:
- title, logoURL - for UI.
- cardType, paymentMethodType - to determine rendering logic.
- userMethodData - user’s saved payment method.
- merchantMethodData: merchant configuration.
- localUrl: optional routing info.
These define which payment method the user is interacting with.
- State initialization
Three internal states are created:
- showErrors – toggles validation messages.
- values – stores form input values.
- savePm – whether user wants to save the method.
These make the component fully reactive and interactive.
- Load default card details
- useNuveiContext() provides defaultCardDetails, which contain:
- cardNumber
- CVV
- cardHolderName
- expirationMonth
- expirationYear
Only applies when the payment method is a credit card.
- Auto-populate fields
If paymentMethod === cc_card, fields are pre-filled:
- card Number
- CVV
- cardHolderName
- expiration Date
This happens in a useEffect() so it runs once at mount.
- Provide context to children
All props, state and functions are exposed via:
<Context.Provider value={...}>
Any component within this provider gains access to:
- metadata
- current field values
- error state
- Children consume the context
usePaymentMethodContext() wraps useContext(Context). Children can read and update payment method data easily and safely.
PaymentMethodCard
Overview
Purpose - The PaymentMethodCard component displays a single payment method option inside the SimplyConnect payment flow.
It visually represents a merchant or user-saved payment method and allows the user to select, fill in required fields, and initiate payment.
Depending on its type (MY_METHOD or SELECT_METHOD), the component dynamically renders the appropriate fields and actions.
Where it is used - This component is used in checkout or payment setup screens, typically inside a list of available payment methods. It can represent both:
- Merchant payment methods — offered by the merchant at checkout.
- User payment methods — previously saved by the user in their account.
What the component does
- Reads the currently selected payment method from the
SimplyConnectContext. - Determines if the current card is selected based on:
userPaymentOptionId(for saved user methods)paymentMethodName(for merchant methods)
- When pressed:
- Updates the selected card in context with the appropriate method data.
- Dynamically renders:
- The correct logo (SVG, local image, or remote URL).
- The title of the payment method.
- The appropriate input fields depending on the payment method type.
- Save Checkbox for merchant methods.
- Pay Button for initiating payment.
- Delete Button for removing saved methods.
- Uses a fallback card SVG if the logo URL fails to load.
Data structure
The component consumes data from the PaymentMethodCardContext and SimplyConnectContext.
Request
SimplyConnectContext
type ContextType = {
userPayments: UserUposResponseType | null;
setUserPayments: (value: UserUposResponseType) => void;
refetch: () => Promise<void>;
merchantPayments: MerchantMethodsResponse | null;
setMerchantPayments: (value: MerchantMethodsResponse) => void;
selectedCard: SelectedCardType;
setSelectedCard: (value: SelectedCardType) => void;
isLoading: boolean;
setIsLoading: (value: boolean) => void;
webviewUrl: string;
setWebviewUrl: (value: string) => void;
};
PaymentMethodCardContext
type ContextType = {
userMethodData: UserPaymentMethodType | null;
merchantMethodData: MerchantPaymentMethod | null;
title: string;
logoURL: string;
cardType: PaymentCardTypes;
paymentMethodType: PaymentMethodNames | null;
values: PaymentDetailsContextType;
setNewValue: (key: string, value: string) => void;
showErrors: boolean;
setShowErrors: (value: boolean) => void;
savePm: boolean | undefined;
setSavePm: (value: boolean) => void;
localUrl?: string;
};
Key functions and variables
cardClickHandler()
Handles card selection:
- If the card is a saved user method (
MY_METHOD), setsselectedCardwithuserPaymentOptionId. - If the card is a merchant method (
SELECT_METHOD), setsselectedCardwithpaymentMethodName.
if (userMethodData && cardType === PaymentCardTypes.MY_METHOD) {
setSelectedCard({
type: cardType,
userPaymentOptionId: userMethodData.userPaymentOptionId,
paymentMethodName: userMethodData.paymentMethodName,
});
}
if (merchantMethodData && cardType === PaymentCardTypes.SELECT_METHOD) {
setSelectedCard({
type: cardType,
userPaymentOptionId: null,
paymentMethodName: merchantMethodData.paymentMethod,
});
}
fields rendering logic
The component determines which fields to render depending on cardType and paymentMethodType:
MY_METHOD+cc_card->MyMethodCreditCardSELECT_METHOD+cc_card->MerchantMethodCreditCardSELECT_METHOD+ any other ->DynamicFields
logo handling
- SVG Logo — if
SvgLogoprop is provided. - Local image — if
localUrlmatches an entry inlocalUrls. - Remote image — if
logoURLis valid. - Fallback — if loading fails, show
Card.svg.
Integration
Basic Usage
import PaymentMethodCard from './components/PaymentMethodCard';
import VisaSvg from '../../assets/icons/visa.svg';
<PaymentMethodProvider
userMethodData={null}
merchantMethodData={{
paymentMethod: 'cc_card',
}}
title="Visa"
logoURL="https://example.com/visa.png"
cardType={PaymentCardTypes.SELECT_METHOD}
paymentMethodType={PaymentMethodNames.cc_card}
>
<PaymentMethodCard SvgLogo={VisaSvg} />
</PaymentMethodProvider>
Requirements
SimplyConnectContextmust be initialized and provideselectedCardandsetSelectedCard.PaymentMethodCardContextmust be set up throughPaymentMethodProvider.- Local SVG fallback (
card.svg) must exist inassets/icons/. - For local logos, define mappings in
localUrls.
Error handling
- If the logo URL fails, the
onErrorhandler setserror = trueand the fallbackCard.svgis displayed. - If
selectedCarddoes not match the current card, fields remain hidden. - If no logo data is provided, fallback is automatically used.
Diagram and description
flowchart TD
id1(Initialize context) ==> id2(Create internal state)
id2 ==> id3(Read defaultCardDetails)
id3 ==> id4(Check if paymentMethodType is credit card)
id4 ==> id5(Fill payment fields)
id5 ==> id6(values is updated)
id6 ==> id7(setNewValue updates values)
id7 ==> id8(usePaymentMethodContext is called)
classDef bold font-weight:bold,padding:400px;
class id1,id2,id3,id4,id5,id6,id7,id8 bold;
PaymentMethodCard is a presentational component responsible for displaying a single payment method option. It is used inside a payment selection UI where users choose how they want to pay. The component receives data via props (such as the payment method name, logo, selection status, or an onPress handler) and renders a clickable card. When clicked, the component informs the parent which payment method was selected.
Component responsibilities:
-
Displays payment method details Shows an icon, name, and additional metadata related to the payment method.
-
Handles user interaction Allows the user to click the card to select the payment method.
-
Visual state handling Highlights the card if it is currently selected (border, background, checkmark).
-
Triggers a callback On click, it calls a function passed by the parent component.
- Receives Props
- The component receives everything it needs from its parent:
- payment method info (label, icon).
- selection state.
- callback for click events.
- Renders card
- The card is displayed with the provided icon and label. If isSelected is true, the card visually differs (highlighted border, background).
- Waits for user interaction
- The card stays visible and interactable.
- Handles click
- If the user clicks the card -> onPress is called.
- The responsibility for updating the selected method is passed to the parent.
- Re-render with new state
- The parent re-renders the component with updated props and sets isSelected to true
- Displays selected style
- The component highlights itself to indicate that it is selected.
DeleteButton
Overview
Purpose - DeleteButton is a component used inside the SimplyConnect module to allow the user to remove a stored payment method. It renders a trash icon and when pressed, it opens a confirmation modal. If the user confirms, it calls the backend to delete the payment method and refreshes the payment-method list.
Where it is used - DeleteButton is placed inside a payment-method card where usePaymentMethodContext(), useNuveiContext() and useSimplyConnectContext() are available. Other components rely on the contexts this component reads to supply nvPaymentMerchantSettings, userMethodData, and the refetch function.
Behavior
- Renders a pressable trash icon (SVG).
- On press -> opens a modal with confirmation text and two actions: CANCEL and DELETE.
- On DELETE -> validates required context data, shows loading state (via
setIsLoading), callsdeletePaymentMethod(...), awaits the response, callsrefetch()to refresh data, handles errors throughsimplyConnectOnFail, and finally clears loading state.
What the component does
Responsibilities
- Shows a confirmation UI before deleting a payment option.
- Gathers necessary identifiers from contexts and builds the HTTP DELETE request payload for deletion.
- Sets and clears a global
isLoadingflag fromuseSimplyConnectContext()while the deletion is in progress. - Triggers a data refresh (
refetch) after successful deletion. - Forwards any caught errors to the
simplyConnectOnFailcallback fromuseNuveiContext().
Key interactions with other layers
usePaymentMethodContext()— providesuserMethodData(the component expectsuserPaymentOptionId).useNuveiContext()— providesnvPaymentMerchantSettings(merchant/session/user info) andsimplyConnectOnFail(error handler).useSimplyConnectContext()— providesrefetch,setIsLoading, andisLoadingto manage and respond to the global loading state.
Data structure
await deletePaymentMethod({
merchantId: String(nvPaymentMerchantSettings.merchantId),
merchantSiteId: nvPaymentMerchantSettings.merchantSiteId,
sessionToken: nvPaymentMerchantSettings.sessionToken,
userPaymentOptionId: userMethodData.userPaymentOptionId,
userTokenId: nvPaymentMerchantSettings.userTokenId,
});
The data that is needed for deleting a payment method is extracted from the ``
nvPaymentMerchantSettings object which comes from useNuveiContext().
deletePaymentMethod performs a request to the backend and throws an error on failure.
Key functions and variables
const [modalVisible, setModalVisible] = useState(false)
- Controls visibility of the confirmation modal.
deleteHandler()
- What it does:
- Validates existence of
userMethodDataandnvPaymentMerchantSettings. If missing, logs a warning. - Calls
setIsLoading(true)and hides the modal (setModalVisible(false)). - Calls
deletePaymentMethod()with required identifiers. - On success, calls
refetch()to refresh the payment-method list. - On error, forwards the error to
simplyConnectOnFail(error)if provided. - In
finally, callssetIsLoading(false)to clear the loading state.
- Validates existence of
- Edge conditions:
- Missing
userMethodDataornvPaymentMerchantSettings-> warns. - Errors are forwarded to
simplyConnectOnFail.
- Missing
UI handlers
onPressof the trash icon ->setModalVisible(true).onPressof CANCEL ->setModalVisible(false).onPressof DELETE ->deleteHandler()(disabled ifisLoading).
Integration
The DeleteButton component is imported in PaymentMethodCard
import DeleteButton from './DeleteButton/DeleteButton';
<View>
...
{cardType === PaymentCardTypes.MY_METHOD && <DeleteButton />}
</View>
Error handling
- Missing contexts or data: If
userMethodDataornvPaymentMerchantSettingsare undefined, the handler logs a warning (console.warn(...)) and does not attempt deletion. - Network errors: Caught and passed to
simplyConnectOnFail(error)if provided. If that callback is not set, the error is removed after thefinallyblock clears loading. - Loading state:
setIsLoading(true)is executed before the network call and is always reset infinally, so UI will not remain stuck in loading if the request fails.
Diagram and description

DeleteButton is a component responsible for deleting a saved payment method. It displays a small delete icon; when tapped, it opens a confirmation popup (modal). If the user confirms, it sends a request to the backend to delete the selected payment method, shows a loading state, handles errors, and then refreshes the payment list.
The component interacts with:
- PaymentMethodCardContext - provides userMethodData;
- SimplyConnectContext - provides refetch, setIsLoading, isLoading;
- NuveiContext - provides
nvPaymentMerchantSettingsand error handlersimplyConnectOnFail;
Its key responsibilities:
- Displays delete button.
- Shows confirmation modal.
- Validates needed data (user method and
nvPaymentMerchantSettings). - Performs delete request.
- Triggers refetch of payment methods.
- Handles failure via callback.
- Component renders the delete icon
- The small trash-bin SVG icon appears inside a pressable element.
- User taps the delete icon
- The press event sets modalVisible = true.
- Confirmation modal opens
- A popup appears asking: "Are you sure you want to delete this payment method?"
- User chooses CANCEL or DELETE
- Cancel closes the modal and does nothing else.
- Delete triggers the asynchronous function deleteHandler().
- Validation of required data
The component checks:
- userMethodData exists.
nvPaymentMerchantSettingsexists (merchantId, sessionToken).- If missing -> logs warning and stops.
- Begin deletion process
- Modal closes.
- Loading state turned on using setIsLoading(true).
- Send deletion request
A backend call is made via deletePaymentMethod() with:
- merchant IDs;
- session token;
- userPaymentOptionId;
- On success: refetch data
The payment methods list is refreshed through refetch() from SimplyConnectContext.
- On failure: call simplyConnectOnFail
If provided, the global error handler is executed.
- Loading ends
setIsLoading(false) runs, UI updates, and modal stays closed.
MyPaymentMethods - CreditCard
Overview
Purpose - The CreditCard component renders the credit card input fields (CVV and Expiration Date) for user-saved payment methods inside the SimplyConnect payment flow.
It ensures proper validation, formatting, and error handling for credit card data before initiating a transaction.
Where it is used - This component is used inside payment method cards of type MY_METHOD.
It appears:
- In checkout screens when the user selects a saved credit card.
- In payment setup flows where CVV and expiration details are required to complete a transaction.
What the component does
- Reads card metadata (brand, expiration date) from
PaymentMethodCardContext. - Determines the CVV length requirement based on card brand (3 for most cards, 3 / 4 for Amex).
- Checks if the stored expiration date is in the past:
- If yes, renders an editable expiration date field.
- If no, expiration date input is not shown.
- Dynamically validates:
- CVV field (numeric input, correct length)
- Expiration date field (valid MM/YY format, not expired)
- Renders localized placeholders and labels using
simplyConnectI18NSettings. - Displays error states and messages when
showErrorsis active. - Ensures proper formatting:
- Automatically inserts
/after the month in expiration date. - Restricts input to digits only for CVV.
- Automatically inserts
Data structure
This component relies on PaymentMethodCardContext.
Request
type ContextType = {
userMethodData: UserPaymentMethodType | null;
merchantMethodData: MerchantPaymentMethod | null;
title: string;
logoURL: string;
cardType: PaymentCardTypes;
paymentMethodType: PaymentMethodNames | null;
values: PaymentDetailsContextType;
setNewValue: (key: string, value: string) => void;
showErrors: boolean;
setShowErrors: (value: boolean) => void;
savePm: boolean | undefined;
setSavePm: (value: boolean) => void;
localUrl?: string;
};
Key functions and variables
cardTypeSelectors
Maps various card brand identifiers to enum values.
Used to correctly determine CVV length and brand-specific behavior.
const cardTypeSelectors = {
[CardTypesEnum.amex]: CardTypesEnum.amex,
[CardTypesEnum.diners]: CardTypesEnum.diners,
[CardTypesEnum.diners_club_international]: CardTypesEnum.diners,
[CardTypesEnum.discover]: CardTypesEnum.discover,
[CardTypesEnum.discover_card]: CardTypesEnum.discover,
[CardTypesEnum.master_card]: CardTypesEnum.masterCard,
[CardTypesEnum.union_pay]: CardTypesEnum.unionPay,
[CardTypesEnum.visa]: CardTypesEnum.visa,
};
cvvValidationLength
Determined dynamically based on the selected card brand:
- Defaults to
3. - Set to
3 / 4for Amex and other brands that require different lengths.
onDateChange(v: string)
- Ensures only digits and
/are allowed. - Automatically inserts
/after typing the month (2 digits). - Prevents invalid characters.
onCvvChange(v: string)
- Removes any non-digit characters.
- Updates the CVV field value.
checkIsPastDate(month, year)
- Determines whether the stored expiration date is in the past.
- If
true, renders the expiration date field so the user can update it.
getErrors()
Returned from useGetCreditCardFieldsErrors:
- Validates CVV length.
- Validates expiration date format and whether it’s expired.
- Returns
cvvErroranddateErrorstrings used for displaying error messages.
Integration
import MyMethodCreditCard from './components/PaymentMethodCard/components/MyMethodCreditCard';
Requirements
- Must be wrapped inside a
PaymentMethodProvider. NuveiContextmust be initialized to provide i18n settings.userMethodDatamust containbrandand optionallyccExpMonth/ccExpYear.- If expiration date is in the past, user must input a new one.
Example Flow
- User selects a saved credit card.
- Component renders CVV field and, if needed, expiration date field.
- User enters the required data.
- Errors are validated in real time or on payment attempt (
showErrors = true).
Error handling
- Invalid CVV
- Shows an error message below the CVV input.
- Highlights the field with error border color.
- Invalid expiration date
- Shows error text below the field.
- Autoformats the date to
MM/YY. - Blocks invalid input (letters, symbols).
- Expired date
- Forces the user to update the date.
- Renders the date input dynamically if the stored date is expired.
Diagram and description

MyPaymentMethods-CreditCard is a component responsible for rendering and validating the CVV and expiration date fields for an already saved credit card (UPO – User Payment Option). It dynamically adjusts validation rules based on:
- Card brand (Visa, MasterCard, Amex).
- Whether the saved expiration date is already expired.
- CVV length can vary depending on the card brand.
It integrates with:
- PaymentMethodCardContext -> retrieves current field values, validation state, and setter functions.
- NuveiContext -> retrieves translations and localization settings.
- useGetCreditCardFieldsErrors() hook -> returns input validation errors.
- checkIsPastDate() -> detects whether expiration date is expired.
Its responsibilities:
- Shows expiration date input if the card is expired.
- Validates CVV and expiration date.
- Displays localized labels and placeholder text.
- Uses specific logic for the different card brands (Amex's CVV is 4 digits).
- Updates field values inside the shared PaymentMethodCardContext.
- Component renders the credit card UI
- The wrapper
<View>appears and prepares to show CVV and possibly expiration date inputs.
- Retrieves all required data from contexts and hooks
The component loads:
- values and setNewValue from PaymentMethodCardContext.
- userMethodData (for saved card info).
- Localization text from NuveiContext.
- Error validator function from useGetCreditCardFieldsErrors().
- Determine CVV validation length
There are two valid lengths for CVV:
- Amex → 4 digits.
- Others → 3 digits.
The component checks the brand and selects correct CVV length.
- Check if the expiration date stored in UPO is expired
- checkIsPastDate(month, year) returns whether the date is not expired.
- If expired -> expiration date field becomes visible.
- If not expired -> only CVV is shown (because date does not need editing).
- User enters CVV or expiration date
The component processes input:
- onDateChange() adds "/" formatting automatically (typing "12" becomes "12/").
- onCvvChange() removes any non-numeric characters.
- Performs validation
The hook useGetCreditCardFieldsErrors() returns:
- cvvError;
- dateError;
depending on:
- showErrors flag.
- card brand rules.
- wrong formatting or invalid values.
- Render error messages if needed
If validation fails:
- Red border is applied.
- Error text appears below input fields.
- Updates shared context values
Every input change updates the global PaymentMethodCardContext values so other components can access them.
SelectPaymentMethod - CreditCard
Overview
Purpose - The CreditCard component renders the complete credit card input form for merchant-managed payment methods inside the SimplyConnect payment flow.
Unlike MyMethodCreditCard, which focuses only on saved user cards (CVV and possibly expiration date), this component provides all fields required for a new card entry — including Cardholder Name, Card Number, Expiration Date, and CVV.
Where it is used - This component is used inside payment method cards of type MERCHANT_METHOD.
It appears:
- In checkout flows, when users enter a new card for payment.
- In merchant-managed payment screens, where full credit card details must be collected to process a transaction.
What the component does
- Provides an input form for cardholder name, card number, expiration date, and CVV.
- Handles real-time validation and formatting for each field:
- Cardholder Name: Text.
- Card Number: Adds spaces after every 4 digits automatically.
- Expiration Date: Auto-inserts
/after two digits (MM/YY). - CVV: Restricts to numeric input and validates correct length.
- Dynamically detects card type and displays the corresponding card brand logo:
- SVG logos for most card brands.
- PNG fallback for Maestro (
maestro.png).
- Adapts placeholders and labels based on localized text from
simplyConnectI18NSettings. - Displays inline error messages when
showErrorsis enabled. - Adjusts CVV placeholder and length for special card types (Amex 3- or 4-digit CVV).
Data structure
This component relies on PaymentMethodCardContext for data.
Request
type ContextType = {
userMethodData: UserPaymentMethodType | null;
merchantMethodData: MerchantPaymentMethod | null;
title: string;
logoURL: string;
cardType: PaymentCardTypes;
paymentMethodType: PaymentMethodNames | null;
values: PaymentDetailsContextType;
setNewValue: (key: string, value: string) => void;
showErrors: boolean;
setShowErrors: (value: boolean) => void;
savePm: boolean | undefined;
setSavePm: (value: boolean) => void;
localUrl?: string;
};
Format for the different card brands:
export const cardTypes: Record<CardTypesEnum, CardType> = {
[CardTypesEnum.amex]: {
numberLengths: [15],
regex: /^3[47][0-9]{5,}$/,
cvvLength: 4,
},
[CardTypesEnum.visa]: {
numberLengths: [13, 16, 19],
regex: /^4[0-9]{6,}([0-9]{3})?$/,
},
[CardTypesEnum.masterCard], [CardTypesEnum.master_card]: {
numberLengths: [16],
regex:
/^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$/,
},
[CardTypesEnum.diners],[CardTypesEnum.diners_club_international]: {
numberLengths: [14, 15],
regex: /^3(?:0[0-5]|[68][0-9])[0-9]{4,}$/,
},
[CardTypesEnum.discover], [CardTypesEnum.discover_card]: {
numberLengths: [16],
regex: /^6(?:011|5[0-9]{2})[0-9]{3,}$/,
},
[CardTypesEnum.jcb]: {
numberLengths: [16],
regex: /^(?:2131|1800|35[0-9]{3})[0-9]{3,}$/,
},
[CardTypesEnum.elo]: {
numberLengths: [],
regex:
/^((((636368)|(438935)|(504175)|(451416)|(636297))[0-9]{0,10})|((5067)|(4576)|(4011))[0-9]{0,12})$/,
},
[CardTypesEnum.hipercard], [CardTypesEnum.hiper_card]: {
numberLengths: [],
regex: /^(606282|3841)[0-9]{5,}$/,
},
[CardTypesEnum.unionPay], [CardTypesEnum.union_pay]: {
numberLengths: [16, 17, 18, 19],
regex: /^(62|88)[0-9]{5,}$/,
},
[CardTypesEnum.china_union]: {
numberLengths: [16, 17, 18, 19],
regex: /^(62|88)[0-9]{5,}$/,
},
[CardTypesEnum.maestro]: {
numberLengths: [12, 13, 14, 15, 16, 17, 18, 19],
regex:
/^(?:50[0-9]{2}|56[0-9]{2}|57[0-9]{2}|58[0-9]{2}|6304|6703|6759|676[1-3])[0-9]{8,15}$/,
},
};
checkCardType
export function checkCardType(rawValue: string): CardTypesEnum | null {
const value = rawValue.replace(/[^0-9]/g, '');
if (value.length <= 7) {
return null;
}
for (const [key, cardType] of Object.entries(cardTypes) as [
CardTypesEnum,
CardType,
][]) {
if (!cardType.regex.test(value)) {
continue;
}
if (
cardType.numberLengths.length > 0 &&
!cardType.numberLengths.includes(value.length)
) {
continue;
}
if (!validateUsingLuhnAlgorithm(value)) {
continue;
}
return key;
}
return null;
}
How the function works:
- Removes all non-digit characters
- Checks for minimal lenght (If the lenght is less than
8, it returnsnull) Card Numbermust match the template for a given card type (Visa, MasterCard, Amex)- Then once more checks the lenght of the given card number
- Returns the
key(type) if the number is correct / returnsnullif not
Key functions
onNameChange(v: string)
Updates the cardholder name field. No validation applied.
cardNumberChange(v: string)
- Inserts a space after every 4 digits as the user types.
- Detects when the user is deleting characters to avoid extra spaces.
- Updates the shared
cardNumbervalue.
onDateChange(v: string)
- Restricts input to digits and
/. - Automatically adds
/after typing two digits. - Prevents invalid characters and updates
expirationDate.
onCvvChange(v: string)
- Removes all non-numeric characters.
- Updates the
cvvfield with cleaned digits.
checkCardType(cardNumber)
Determines the current card brand (visa, mastercard, amex, maestro, etc.) and returns it as a string or enum.
validateCardAndGetCvvLength(cardNumber)
Returns { cvvValidationLength }, defining how many digits the CVV should have (3 or 4).
getCreditCardLogoFromCardNumber(cardType)
Returns a React component containing the SVG logo for the detected card brand.
Used to visually display the card type inside the input field.
useGetCreditCardFieldsErrors()
The function returns localized error messages if any field is invalid.
Integration
import MerchantMethodCreditCard from './components/PaymentMethodCard/components/MerchantMethodCreditCard';
Requirements
- Must be rendered inside a
PaymentMethodProvider. - Must have
NuveiContextinitialized for translations (simplyConnectI18NSettings). - All card-related values (
name,number,date,cvv) are managed through thePaymentMethodCardContext.
Example Flow
- User opens payment screen.
- Component renders all input fields.
- As user types:
- Fields are automatically formatted (spaces, slashes).
- Card logo is detected and displayed.
- Validation runs in real time if
showErrorsis true.
- Errors are shown inline with red text and borders when validation fails.
Error handling
| Field | Validation | Behavior on error |
|---|---|---|
| Cardholder Name | Must not be empty | Displays red border and error text |
| Card Number | Must contain valid digits and pass card type check | Shows logo only if card type is valid; displays error otherwise |
| Expiration Date | Must be in MM/YY format and not expired | Autoformats input; shows error if invalid or past |
| CVV | Numeric; must match required length (3 or 4 digits) | Displays error text and red border if invalid |
Diagram and description
flowchart TD
id1(Load Nuvei and PaymentMethod context) ==> id2(Extract current field values)
id2 --> id3(Detect card type)
id3 --> id4(Provide required CVV length)
id4 --> id5(Display card logo)
id5 --> id6(Prepare input handlers)
id6 --> id7(Render UI)
id7 --> id8(Wait for user interaction)
classDef bold font-weight:bold,padding:400px;
class id1,id2,id3,id4,id5,id6,id7,id8 bold;
MerchantMethodCreditCard is a component used for capturing credit card information within a payment process. It handles automatic formatting of card number and expiration date, detects the card type from the number, displays dynamic card logos, validates user input, and shows appropriate error messages. All field values are stored and updated through a shared payment method context, ensuring synchronization with the parent payment component.
- Load contexts
-
Nuvei context -> provides translations for all labels and placeholders.
-
PaymentMethod context -> contains:
- current input values.
- function setNewValue() for updating fields.
- boolean showErrors that enables error messages.
- Extract current field values
-
The component retrieves the current values for:
- Cardholder name;
- Card number;
- Expiration date;
- CVV;
These values are stored in the payment method context.
- Detect card type
-
checkCardType() inspects the card number and determines the brand. Some of the brands are:
- Visa;
- MasterCard;
- Amex;
- Maestro;
This affects:
- Which logo is shown.
- What CVV placeholder appears.
- How many digits CVV must have.
- Calculate required CVV length
-
validateCardAndGetCvvLength() returns:
- 3 digits for most cards.
- 4 digits for American Express (Amex).
- Generate card logo
Two possible outcomes:
- SVG component from getCreditCardLogoFromCardNumber().
- PNG Maestro image (only if card type is Maestro).
The UI displays whichever is available.
- Input handlers
-
onNameChange
- Updates the cardholder name directly.
-
cardNumberChange
- Adds a space after every 4 digits.
- Recognizes when user deletes.
- Updates the stored card number.
- Checks for card type and logo.
-
onDateChange
-
Rejects invalid characters.
-
Automatically inserts / after the month.
-
Updates expiration date
-
onCvvChange
- Removes everything except digits.
- Updates CVV.
- Validate fields
-
getErrors() checks:
- Name;
- Card number;
- Date;
- CVV;
If showErrors is true, corresponding error messages will be shown.
- Render UI
-
Cardholder name input
- Styled input and error message below if invalid.
-
Card number input
- Shows SVG or PNG card logo on the right.
- Shows error message if needed.
-
Expiration date input
- Supports MM/YY format.
- Shows errors.
-
CVV input
- Length depends on card type.
- Placeholder changes for Amex.
- Error message if needed.
- In a waiting state
The component remains active and updates any time the user types or validation state changes.
SelectPaymentMethod - DynamicFields
Overview
Purpose - The DynamicFields component renders dynamic input fields for merchant-managed payment methods inside the payment flow.
Unlike fixed components (CreditCard), this component adapts to the field definitions provided by the merchant. What will render depends on the configuration of each field.
Where it is used - This component is used inside payment method cards of type MERCHANT_METHOD.
What the component does
Dynamically renders form fields based on merchant configuration:
TextField- for text input.Dropdown- for predefined options.
Initializes field values when the component mounts:
- Text fields start empty.
- Dropdowns default to the first available option.
- Updates shared state in
PaymentMethodCardContextwhenever the user changes a value. - Displays inline error messages when
showErrorsis enabled and a required field is empty. - Ensures consistent styling across text inputs and dropdowns.
Data structure
This component relies on PaymentMethodCardContext for data.
Field definition (MerchantPaymentMethodFieldType)
export type MerchantPaymentMethodFieldType = {
name: string;
type: string;
caption: {
language: string;
message: string;
}[];
listValues?: {
code: string;
caption: string;
mandatoryFields: [];
}[];
};
name- unique identifier for the field.caption- localized labels for the field.listValues- optional array of predefined values. If present, the field is rendered as a dropdown.
Key functions
TextField({ field })
- Renders a text input field.
- Initializes value as an empty string.
- Shows error message if
showErrorsis true and the field is empty.
Dropdown({ field })
- Renders a dropdown list using
Picker. - Initializes value with the first item in
listValues. - Updates context when the user selects a new option.
DynamicFields()
- Iterates over all merchant-defined fields.
- Decides whether to render a
TextFieldorDropdownbased onlistValues. - Wraps all fields inside a styled container.
Integration
import DynamicFields from './components/PaymentMethodCard/components/DynamicFields';
Requirements
- Must be rendered inside a
PaymentMethodProvider. - Merchant field definitions (
merchantMethodData.fields) must be available in context. - Each field must have a
nameand at least onecaption.
Error handling
| FieldType | Validation | Behavior on error |
|---|---|---|
| TextField | Must not be empty | Displays red error text below the input |
| Dropdown | Must have a selected value | Defaults to first option; error shown if missing |
Diagram and description
flowchart TD
id1(Load merchantMethodData from context) ==> id2(Iterate through merchantMethodData.fields)
id2 ==> id3(Detect card type)
id3 ==> id4{Is the field a dropdown}
id4 == No ==> id5(Render TextField component)
id4 ======> id7(Each component initializes its default value)
id7 ==> id8(User interaction updates payment context)
id8 ==> id9(Show validation errors)
id4 == Yes ==> id6(Render Dropdown component)
linkStyle 3 stroke:red;
linkStyle 7 stroke:green;
classDef bold font-weight:bold;
classDef smallDiamond stroke:#333,stroke-width:1px,font-size:12px,font-weight:bold;
classDef size padding:400px;
class id1,id2,id3,id5,id6,id7,id8,id9 bold;
class id1,id2 size;
class id4 smallDiamond;
DynamicFields is a component used to dynamically render additional form fields required by a specific payment method. These fields come from merchantMethodData and may be either text inputs or dropdown (select) fields. For each field, the component initializes a default value, updates the payment context when the user changes input, and shows validation errors when required fields are empty.
It allows the payment system to support custom fields.
- Load merchantMethodData
-
Using the usePaymentMethodContext, the component reads merchantMethodData, which contains:
- An array of dynamic field definitions.
- Metadata - field types, required status, dropdown values.
This determines what fields should be displayed.
- Iterate through all fields
-
The component loops through merchantMethodData.fields. Each field may be:
- Text field;
- Dropdown field (if listValues is provided)
- Check if the field should be a dropdown
A field becomes a dropdown when:
- field.listValues?.length > 0
Render Dropdown component
- Initializes default value (first item in the list).
- Renders a Picker.
- Updates the payment method context when the user selects an option.
If not, it becomes a normal text input.
Render TextField component
- Initializes the field with an empty string.
- Displays a text input.
- Updates the payment context on each keystroke.
- Each component initializes its default value
-
Both field types use useEffect to set an initial value:
- TextField -> empty string
- Dropdown -> first list value
This ensures the form always has valid structure before user input.
- User interaction updates the context
- Whenever the user types or selects something:
- setNewValue(field.name, value).
This updates the global payment state, shared across the whole payment form.
- Show validation errors
- If showErrors is true and the user has not entered a value:
- TextField displays an error: "field is required"
- Component finishes rendering
The dynamic form is ready and reacts to user input in real time.
PayButton
Overview
Purpose - PayButton is a UI component responsible for initiating a payment process within the SimplyConnect module.
When the user presses the button, it validates all required payment fields and, if valid, executes the correct payment logic depending on the selected payment method and card type.
If the payment requires a 3D Secure authentication, the component automatically opens a WebView3D modal to handle that.
Where it is used - PayButton is used inside payment forms or payment method cards where the following contexts are available:
useNuveiContext()— provides merchant transaction information, translations, and callbacks likesimplyConnectOnSuccess.usePaymentMethodContext()— provides payment method data, card type, and a flag to display validation errors.useSimplyConnectContext()— provides asetIsLoadingstate to indicate loading while a payment is processing.
What the component does
Responsibilities
- Displays a payment button with a localized label and the current transaction amount.
- Validates fields using
useValidateFields()before initiating payment. - Determines the correct payment function to call (user or merchant, card or other method).
- Controls a
WebView3Dmodal for 3D Secure challenges. - Triggers loading state via
setIsLoading(true/false)while processing payment. - On success, calls the global success handler
simplyConnectOnSuccess(response)and closes the 3D modal.
Interactions with contexts
useNuveiContext()- Provides
transactionDetails,simplyConnectI18NSettings, andsimplyConnectOnSuccess.
- Provides
usePaymentMethodContext()- Provides
userMethodData,merchantMethodData,cardType, andsetShowErrors.
- Provides
useSimplyConnectContext()- Provides
setIsLoading, used to show/hide a loading indicator.
- Provides
usePaymentMethods(setWebViewParamsProps)- Returns a set of functions (
myMethodsCard,myOtherPaymentMethod) used to initiate specific payment requests.
- Returns a set of functions (
useValidateFields()- Returns a boolean (
fieldsValid) indicating whether required payment fields are correctly filled.
- Returns a boolean (
Data structure
const [webViewParamsProps, setWebViewParamsProps] = useState<WebViewParams | null>(null);
const [webviewOpen, setWebviewOpen] = useState(false);
webViewParamsProps— holds parameters for the 3D Secure web view (URL, challenge data).webviewOpen— boolean that controls the visibility of theWebView3Dmodal.
Key functions and variables
useEffect(() => { if (webViewParamsProps) setWebviewOpen(true); }, [webViewParamsProps])
- Whenever new 3D Secure parameters are set (
webViewParamsPropschanges), the web view modal automatically opens. - This ensures the user is immediately prompted to complete the authentication challenge.
const payHandler = async () => { ... }
This is the main function triggered when the user presses the Pay button.
- Validation:
Checks if the payment fields are valid usingfieldsValid.
If not valid -> setssetShowErrors(true)to display validation messages. - Loading state:
SetssetIsLoading(true)to indicate the payment is being processed. - Payment type selection:
Based on the card type (PaymentCardTypes.MY_METHODor merchant), it chooses the correct handler:- User methods:
PaymentMethodNames.cc_cardcallsmyMethodsCard()- Other calls
myOtherPaymentMethod()
- Merchant methods:
PaymentMethodNames.cc_cardcallsmerchantPaymentCard()- Other calls
merchantOtherMethod()
- User methods:
- Error handling:
Catches and logs any errors during payment processing. - Finally:
CallssetIsLoading(false)to end the loading state.
const onSuccess = (response: any) => { simplyConnectOnSuccess(response); setWebviewOpen(false); }
- This callback is passed to
WebView3D. - It runs after successful 3D authentication and finalizes the payment process.
const amount = transactionDetails?.amount ? Number(transactionDetails.amount).toFixed(2) : '';
- Formats the transaction amount into a two-decimal number.
- Used to display the final amount on the button label.
Integration
import PayButton from './PayButton/PayButton';
{isSelected && (
<>
{fields && <View style={styles.fieldsWrapper}>{fields}</View>}
{cardType === PaymentCardTypes.SELECT_METHOD && <SaveCheckbox />}
<PayButton />
</>
)}
This component is imported in PaymentMethodCard
Error handling
- Invalid fields:
IffieldsValidisfalse, the button does nothing except trigger error messages withsetShowErrors(true). - 3D Secure errors:
IfWebView3Dor the payment request fails, the error is caught inpayHandlerand logged (PAYMENT BUTTON ERROR). - Missing context providers:
If required contexts are missing (useNuveiContext,usePaymentMethodContext), the component may display incorrect data. - Loading state handling:
ThesetIsLoadingensures that the UI can show a spinner or disable interactions during processing, even if an error occurs.
Diagram and description
flowchart TD
id1(User presses pay button) ==> id2(Validate fields)
id2 ==> id3(Start loading)
id3 ==> id4(Execute payment function)
id4 ==> id5(Recieve WebView parameters)
id5 ==> id6(Open 3DS WebView)
id6 ==> id7(User completes challenge)
id7 ==> id8(Trigger callback)
id8 ==> id9(Close WebView and stop loading)
classDef bold font-weight:bold,padding:400px;
class id1,id2,id3,id4,id5,id6,id7,id8,id9 bold;
PayButton is responsible for initiating the payment process. It validates the user input, determines which payment method is selected, calls the correct payment API function, manages loading state, and opens a 3D Secure WebView if required.
It interacts with several contexts:
- NuveiContext -> transaction details data, translations, success callback.
- PaymentMethodContext -> selected method, field validation errors, card type.
- SimplyConnectContext -> loading spinner
- paymentLogic hooks -> actual payment functions (my card, merchant card, other methods)
It also manages:
- webViewParamsProps → parameters for 3D Secure.
- webviewOpen → whether the modal WebView is displayed.
- Component Render
The PayButton appears on screen with the label:
Pay {amount}{currency}.
- Context Loading
The component loads all required context data:
- Transaction information (amount + currency).
- Translations for the button text.
- Selected payment method.
- Validation functions.
- Loading state setter.
- Callbacks (success handler).
- Internal State
The component manages two internal states:
- webViewParamsProps which passes data to WebView.
- webviewOpen determines if WebView modal is visible.
- Payment Logic Hooks
The hook usePaymentMethods returns:
- myMethodsCard();
- myOtherPaymentMethod();
- merchantPaymentCard();
- merchantOtherMethod();
These are payment execution functions.
- User presses the pay button
When the <Pressable> is clicked, payHandler() executes.
- Field Validation
The hook useValidateFields() checks if form fields are valid.
If invalid, errors are shown and the function stops.
- Loading State
If fields are valid, setIsLoading(true) starts a spinner.
- Determine Payment Method
The component checks:
- Whether the payment method belongs to the user or to the merchant.
- Then it runs the proper async function.
- Running Payment Logic
Depending on the method:
- Pay with card.
- Pay with Apple Pay.
- Pay with Google Pay.
- Pay with alternative methods.
During these functions, webViewParamsProps may be set, which means a 3D Secure flow is required.
- Opening 3D Secure WebView
- A useEffect watches webViewParamsProps.
- When it becomes non-null -> open WebView modal.
- Completing 3DS Challenge
If the user completes the challenge successfully:
- onSuccess(response) is called.
- Success result is passed to the parent via simplyConnectOnSuccess().
- WebView closes.
- Finalizing
setIsLoading(false) always runs in the finally block.
PayButton - paymentLogic
Overview
Purpose - This file provides two hooks used for the payment:
useValidateFields()— checks whether the current payment form fields are valid for the selected payment method (user card; merchant card; other methods).usePaymentMethods(setWebViewParamsProps)— builds payment request data and sets the correct payment flow (user card, merchant card, other method). It handles 3D Secure flows (viauseAuth3D), calls the HTTP POST init payment endpoint (cardClientPayment) for non-3D flows, and usessetWebViewParamsPropsto trigger a WebView 3D modal when required.
Where it is used - These hooks are used inside payment forms / payment method components. They expect the same contexts that the rest of the SimplyConnect module uses:
useNuveiContext()— transaction details and callbacks (simplyConnectOnSuccess,simplyConnectOnFail) and merchant settings.usePaymentMethodContext()— current payment values, selected card type, user/merchant payment data and flags likesavePm.useSimplyConnectContext()— functions to toggle loading and set webview URL.
What the hooks and functions do
useValidateFields()
Responsibilities
- Reads
values,cardType,userMethodDataandmerchantMethodDatafromusePaymentMethodContext(). - Validates required fields depending on:
- If the selected card is a user-saved card (
PaymentCardTypes.MY_METHOD) and the saved method iscc_card: validates CVV length and checks if the expiration date is valid. - If the selected card is a merchant card or other merchant payment method:
- for
cc_cardvalidates card numbervalidateCardAndGetCvvLength), CVV length, cardholder name and expiration date; - for other merchant methods it ensures that all
valuesfields are not empty.
- for
- If the selected card is a user-saved card (
- Returns
truewhen fields are valid,falseotherwise.
usePaymentMethods(setWebViewParamsProps)
Responsibilities
- Prepares
paymentSettings/InitPaymentBodyobjects using data fromuseNuveiContext()(transaction details, merchant settings) andusePaymentMethodContext()(values, userMethodData, savePm). - Calls either the 3D Secure flow or the init payment endpoint
cardClientPaymentdepending on method and response:- Uses
useAuth3D()when a 3D authentication is needed - Uses
cardClientPayment()for payment methods that return a redirect url.
- Uses
- Manages loading state through
useSimplyConnectContext().setIsLoading. - Handles responses and uses
simplyConnectOnSuccess/simplyConnectOnFailcallbacks fromuseNuveiContext(). - When a redirect / web challenge is required, it calls
setWebViewParamsProps(webViewParams)to open the WebView 3D modal.
myMethodsCard()
Prepares an InitPaymentBody containing userPaymentOptionId, CVV, expiration date and then triggers the 3D flow via auth3d.
myOtherPaymentMethod()
Sends InitPaymentBody via cardClientPayment, inspects response and sets a redirect URL.
merchantPaymentCard()
Starts payment when merchant card fields are used. Expects date. Calls auth3d to perform 3D flow.
merchantOtherMethod()
Starts payment for other merchant payment methods. Builds InitPaymentBody with alternativePaymentMethod fields from values, calls cardClientPayment, and either sets webview redirect or calls simplyConnectOnSuccess.
Data structure
Request
myMethodsCard
const body: InitPaymentBody = {
amount: transactionDetails.amount,
billingAddress: {
country: transactionDetails.countryCode,
email: transactionDetails.userTokenId,
},
clientRequestId: transactionDetails.clientRequestId,
countryCode: transactionDetails.countryCode,
currency: transactionDetails.currency,
googlePayGateway: 'nuveidigital',
googlePayGatewayMerchantId: 'googletest',
googlePayMerchantId: 'BCR2DN6TZ6DP7P3X',
googlePayMerchantName: 'com.nuveisimplyconnectexample',
merchantId: String(transactionDetails.merchantId),
merchantSiteId: transactionDetails.merchantSiteId,
paymentOption: {
card: {
CVV: values.cvv,
expirationMonth: expirationMonth ?? '',
expirationYear: expirationYear ?? '',
},
userPaymentOptionId: userMethodData.userPaymentOptionId,
},
requestTimeout: 10,
sessionToken: transactionDetails.sessionToken,
timeout: 10,
userTokenId: transactionDetails.userTokenId,
webMasterId: 'sdk_android_ver1.3.2',
deviceDetails: {
deviceName: 'sdk_gphone64_arm64',
deviceOS: '16',
deviceType: 'SMARTPHONE',
ipAddress: '10.0.2.15',
},
};
myOtherPaymentMethod
const body: InitPaymentBody = {
currencyCode: transactionDetails.currency,
merchantId: transactionDetails.merchantId,
merchantSiteId: transactionDetails.merchantSiteId,
paymentOption: {
userPaymentOptionId: userMethodData.userPaymentOptionId,
},
sessionToken: transactionDetails.sessionToken,
userTokenId: transactionDetails.userTokenId,
};
merchantOtherMethod
const body: InitPaymentBody = {
currencyCode: transactionDetails.currency,
merchantId: transactionDetails.merchantId,
merchantSiteId: transactionDetails.merchantSiteId,
paymentOption: {
alternativePaymentMethod: {
paymentMethod: paymentMethodType,
},
savePm,
},
sessionToken: transactionDetails.sessionToken,
userTokenId: transactionDetails.userTokenId,
sourceApplication: SourceApplication.ANDROID_MOBILE_SDK_CHECKOUT,
};
Key functions
`useValidateFields()
`
userMethodData/merchantMethodData— decides which validation to use.validateCardAndGetCvvLength(number)— validates card number and returns CVV expected length for detected brand.isCvvValid(cvv, acceptedLength[])— verifies CVV length matches the expected.checkIsPastDate(month, year)andisCardDateValid(date)— determines if saved card is expired and if the date format from the input is acceptable.- returns
truewhen all required fields are valid.
usePaymentMethods(setWebViewParamsProps)
setWebViewParamsProps— setter used to passWebViewParams; when called, the UI opens theWebView3D modal.auth3dfromuseAuth3D()— used to run 3D secure flows.responseErrorHandler(res)— inspects response status and transactionStatus;setIsLoading(true/false)— used to start / stop loading when a payment is processing.
Integration
import { usePaymentMethods, useValidateFields } from './paymentLogic';
PayButton component uses the hooks from paymentLogic
Error handling
- Validation errors:
useValidateFields()returnsfalsewhen any required field is missing or invalid. That response is used fromfieldsValidinPayButtonwhich setssetShowErrors(true)so the user sees validation messages. - 3D Secure flow errors:
auth3dcalls are wrapped intry/catchblock. On error the hook logs the error. In finnaly blocksetIsLoadingis false. - init payment errors:
cardClientPayment(body)responses are checked viaresponseErrorHandler(res)- if the response is
ERRORorDECLINED, it callssimplyConnectOnFailand returnstrueto stop the processing.
- if the response is
- Loading state:
Each function initially setssetIsLoading(true)andsetIsLoading(false)infinally. This ensures UI is not left in a loading state after success or failure.
Diagram and description
flowchart TD
id1(Initialize useValidateFields) ==> id2(Validate fields based on payment type)
id2 ==> id3(Initialize usePaymentMethods)
id3 ==> id4(Build PaymentSettings object)
id4 ==> id5("Prepare 3DS (auth3d) config")
id5 ==> id6(Define payment handlers)
id6 ==> id7(Handlers create request body)
id7 ==> id8(Send payment request)
id8 ==> id9(Open WebView if needed)
id9 ==> id10(Return handler functions to PayButton)
classDef bold font-weight:bold,padding:400px;
class id1,id2,id3,id4,id5,id6,id7,id8,id9,id10 bold;
useValidateFields() — this hook is responsible for validating all input fields based on the selected payment method.
It checks:
- CVV format.
- Card number format.
- Expiration date validity.
- Required fields for alternative methods.
- Required fields for merchant payment methods.
- Whether the card is expired and if an updated date is entered.
- It returns a boolean true/false, telling whether the form is valid.
usePaymentMethods() - the hook returns four payment execution functions, one for each payment case:
- myMethodsCard — user saved card.
- myOtherPaymentMethod — user saved other method.
- merchantPaymentCard — merchant-provided card fields.
- merchantOtherMethod — merchant alternative payment method.
This hook:
- Builds the PaymentSettings object.
- Prepares 3D secure authentication (via useAuth3D).
- Sends requests to the backend (cardClientPayment).
- Opens 3D WebView if needed.
- Handles API errors and redirects.
- Calls success/fail callbacks.
This hook is directly used by PayButton to execute the payment.
- Initialize useValidateFields()
The hook reads from usePaymentMethodContext() to determine:
- Selected method type (user card, merchant card, alternative method).
- Entered values.
- Card brand and stored user card data.
It sets valid = true by default.
- Validate credit card fields
If the user selected a saved card:
- Extracts correct CVV length from stored card brand.
- Checks if card is expired.
If expired -> requires to renew expiration date.
- Validates CVV length and structure.
- Set valid = false on any error
- Validate merchant card fields
If the user is entering a new card:
- Validates card number structure.
- Validates CVV using brand-based rules.
- Validates expiration date.
- Validates card holder name.
Set valid = false on any missing or invalid data.
- Validate alternative payment method fields
For APMs:
- Ensures no field is empty
Sets valid = false if any value is missing
- Return the boolean
The hook returns true if all checks pass, otherwise false.
-
Initialize usePaymentMethods()
-
Read context and transactionDetails data
The hook loads:
- Merchant and user data.
- Payment fields.
- Global transactionDetails info (amount, token, merchantId).
- Callbacks (onError, onSuccess).
- Build PaymentSettings object
A configuration object is constructed:
- Card data (number, cvv, expiration).
- Merchant ID, session token.
- Google Pay merchant details.
- timeout.
- savePm state.
- user token.
This object is used by 3D secure.
- Prepare auth3d handler
The hook initializes the 3D secure function with:
- PaymentSettings.
- Success callback.
- Error callback.
- WebView opening callback.
- Define responseErrorHandler
Handles API responses:
If status is ERROR or DECLINED -> calls onError
- Stops payment process.
- Returns boolean
- Implement myMethodsCard()
-
For a saved credit card:
- Validates expiration.
- Calls 3D secure (auth3d).
- Handles loader.
- Catches errors.
- Implement myOtherPaymentMethod()
For alternative payment methods (APM):
- Builds request body with userPaymentOptionId.
- Calls backend with cardClientPayment().
- Handles redirect URL -> open WebView.
- Handles errors and uses loader for loading state.
- Implement merchantPaymentCard()
For a merchant card:
- Validates date.
- Triggers 3D Secure.
- No savePm or card number stored.
- Implement merchantOtherMethod()
For merchant alternative payment method:
- Builds request body with all dynamic fields.
- Sends API request.
- Handles redirect (open WebView).
- If no redirect -> calls success callback.
- Handles errors and loader
- Return all payment handlers
The hook returns:
{
myMethodsCard,
myOtherPaymentMethod,
merchantPaymentCard,
merchantOtherMethod,
}
These are used inside PayButton.
SaveCheckbox
Overview
Purpose - SaveCheckbox is a UI component inside the SimplyConnect module, that lets the user to choose whether to save a payment method. It renders a checkbox which differs depending on the platform, a text label (from i18n settings) and a small lock icon. When toggled, it updates a shared savePm boolean in usePaymentMethodContext().
Where it is used - SaveCheckbox is used inside a payment-method card or payment form where usePaymentMethodContext() and useNuveiContext() are available. Those contexts provide the boolean state savePm and the localized label text
(simplyConnectI18NSettings.saveDetailsText).
Behavior
- Shows a checkbox and a label; tapping the label toggles the checkbox.
- Uses different checkbox props for Android and iOS
- On mount it resets
savePmtofalse. - Updates
savePmviasetSavePm(value)when the user toggles.
What the component does
Responsibilities
- Displays a checkbox with a label that reads
simplyConnectI18NSettings?.saveDetailsText. - Reads
savePmandsetSavePmfromusePaymentMethodContext()to change the saved-payment preference. - Resets the
savePmflag tofalseon component mount (so the checkbox is unchecked initially) - Provides a small lock SVG at the right to visualize privacy.
Key interactions with other layers
usePaymentMethodContext()— providessavePm(boolean value) andsetSavePm(setter).useNuveiContext()— providessimplyConnectI18NSettingsfrom which the label text is read.
Data structure
This component only reads and writes one piece of state:
const { savePm: value, setSavePm } = usePaymentMethodContext();
value—boolean(true if user chose to save the payment method).setSavePm(value: boolean)— updates that boolean value.
Key functions and variables
const { savePm: value, setSavePm } = usePaymentMethodContext()
valueis the checkbox state (boolean).setSavePmis used to update that state.
const { simplyConnectI18NSettings } = useNuveiContext()
- Provides localized strings. Component uses
simplyConnectI18NSettings?.saveDetailsTextfor the label.
useEffect(() => { setSavePm(false) }, [])
- Runs once on mount and ensures the checkbox starts unchecked by setting
savePmtofalse. - This helps to avoid unintentionally remembering a previous UI state when the component mounts.
const props = Platform.OS === 'android' ? ... : ...
- Android props:
{ tintColors: { true: '#38279A' } } - iOS props: includes
tintColor,onCheckColor,onTintColor,(width/height of 16px), andboxType: BoxType.square - Checkbox appearance is consistent and slightly smaller on iOS.
onChange(value: boolean)
- Calls
setSavePm(value). - Related to
<CheckBox onValueChange={onChange} />and also used by the TouchableOpacity label to toggle (onPress={() => onChange(!value)}).
UI layout
- Left: checkbox + label (touchable).
- Right: small lock icon (
LockIcon height={20} width={20}). - Styles:
styles.sectionWrapperplaces items in a row with space between them;checkBoxWrappergroups checkbox and label.
Integration
import SaveCheckbox from './SaveCheckbox/SaveCheckbox';
{isSelected && (
<>
{fields && <View style={styles.fieldsWrapper}>{fields}</View>}
{cardType === PaymentCardTypes.SELECT_METHOD &&<SaveCheckbox />}
<PayButton />
</>
)}
This component is imported in PaymentMethodCard
Error handling
- Missing contexts or data: The component assumes
usePaymentMethodContext()anduseNuveiContext()exist. If either context is missing, the component can show empty/undefined label. - Platform differences: The
propsobject applies different settings for the platforms (Android, iOS). Appearance could be incorrect on a specific device.
Diagram and description
flowchart TD
id1(Render SaveCheckbox) ==> id2(Initialize savePm = false)
id2 ==> id3(Render checkbox, label and icon)
id3 ==> id4(User taps checkbox or label)
id4 ==> id5("Update context: setSavePm(value)")
id5 ==> id6(Component re-renders with value)
classDef bold font-weight:bold,padding:400px;
class id1,id2,id3,id4,id5,id6 bold;
SaveCheckbox is a UI component that allows the user to decide whether their payment method should be saved for future use. It reads and updates the shared payment context (PaymentMethodContext) and also displays localized text from the NuveiContext. Handles checkbox toggling, and renders an optional lock icon to visually indicate security.
The component works on both iOS and Android, using platform-specific properties for proper checkbox behavior.
- Render SaveCheckbox
The component mounts and receives access to:
- savePm and setSavePm from PaymentMethodContext.
- localized text (saveDetailsText) from NuveiContext.
- Initialize savePm = false
- Inside useEffect, the component sets: setSavePm(false)
- This ensures the checkbox always starts unchecked when entering the payment flow.
- Render checkbox, label and lock icon
The UI contains three main elements:
- A platform-specific
<CheckBox /> - A label that the user can also press to toggle the checkbox.
- A lock icon representing secure data storage.
- User taps checkbox or label
The user interaction can come from:
- Pressing the checkbox directly.
- Pressing the text label (wrapped in a TouchableOpacity). Both trigger the same callback.
- Update context: setSavePm(value)
-
The internal state is updated through context: onChange(nextValue);
-
This stores whether the user wants to save the payment method.
- Component re-renders with updated value
React re-renders the component, and the checkbox visually reflects the new state (checked or unchecked).
WebView
Overview
Purpose - WebViewScreen is a component that displays a modal popup containing a WebView.
It is used to handle payment flows that require monitoring navigation events and performing actions based on URL changes.
Where it is used - This component is used within the payment process flow to verify transaction results.
Behavior
- Opens a modal containing a full-screen webview.
- Loads a dynamic URL provided by the SimplyConnect context.
- Monitors navigation events to detect payment completion URLs.
- Checks the payment status when a completion URL is reached.
- Calls success or failure callbacks based on the payment result.
What the component does
-
WebView Rendering
- Renders a
WebViewwithin a modal overlay. - Uses full device width and height for the web content.
- Accepts any URL provided through context.
- Renders a
-
Navigation Monitoring
- Tracks every navigation event inside the
WebView. - Detects completion URLs (
autoclose.html) that indicate the end of a payment session. - Once detected, the component automatically triggers payment verification.
- Tracks every navigation event inside the
-
Payment Verification
- When the
WebViewreaches a completion URL, the SDK callscheckPaymentStatus(sessionToken)to verify the transaction. - If the response equals
PaymentResponseStatuses.SUCCESS, it calls thesimplyConnectOnSuccesscallback. - If the response equals
PaymentResponseStatuses.ERROR, it calls thesimplyConnectOnFailcallback.
- When the
-
Error Handling
- Logs WebView runtime errors and HTTP request failures to the console.
- Prevents crashes by handling failed navigation.
-
Modal Behavior
- The modal becomes visible only when a
webviewUrlexists. - It can be closed by calling
setWebviewUrl(''). - Fades in and out for smoother user experience.
- The modal becomes visible only when a
Data structure
| Name | Type | Description |
|---|---|---|
webviewUrl | string | URL loaded inside the WebView. |
setWebviewUrl | function | Function to set or clear the active WebView URL. |
transactionDetails | object | Contains payment transaction details and sessionToken. |
simplyConnectOnSuccess | function | Called when payment verification succeeds. |
simplyConnectOnFail | function | Called when payment verification fails. |
Key function
handleNavigationStateChange(navState: WebViewNavigation)
- Triggered whenever the WebView changes navigation state.
- Checks if the current URL matches any of the predefined completion URLs.
- When matched:
- Verifies the payment using the
checkPaymentStatusAPI. - Invokes success or failure callbacks based on API response.
- Verifies the payment using the
Integration
import WebView from './WebView/WebView';
Error handling
WebView Runtime Errors
onError={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
console.error('WebView error: ', nativeEvent);
}}
HTTP Errors
onHttpError={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
console.error('WebView HTTP error: ', nativeEvent);
}}
Payment Status Errors
- If the
checkPaymentStatuscall returnsPaymentResponseStatuses.ERRORthesimplyConnectOnFailcallback is executed with the response data.
Diagram and description
flowchart TD
id1(Render WebViewScreen) ==> id2(Check if webviewUrl exists)
id2 ==> id3(Load WebView with the URL)
id3 ==> id4(User navigates inside WebView)
id4 ==> id5(Detect completion URL)
id5 ==> id6(Check payment status)
id6 ==> id7(Trigger success or failure callback)
classDef bold font-weight:bold,padding:400px;
class id1,id2,id3,id4,id5,id6,id7 bold;
WebViewScreen displays a fullscreen modal containing a WebView used to complete a payment. When the WebView navigates to a specific “completion URL,” the component checks the payment status using the session token. Based on the response, it triggers either the success callback (simplyConnectOnSuccess) or the failure callback (simplyConnectOnFail).
The modal is shown only when webviewUrl is defined, and it closes when that value becomes an empty string.
- Render WebViewScreen
The component mounts and receives:
- webviewUrl and setWebviewUrl from SimplyConnectContext.
- transactionDetails, simplyConnectOnSuccess, and simplyConnectOnFail from NuveiContext.
WebView is not shown unless webviewUrl contains a valid URL.
- Check if webviewUrl exists
The <Modal> becomes visible only when webviewUrl has a value:
visible={!!webviewUrl}
If webviewUrl is empty, the user will not see the WebView.
- Load WebView with the provided URL
The WebView loads:
source={{ uri: webviewUrl }}
and initializes with:
- JavaScript enabled
- loading indicator
- hardware layer type (Android)
- User navigates inside the WebView
As the user interacts with the WebView, each URL navigation triggers:
onNavigationStateChange
This event contains the new URL.
- Detect completion URL
The component checks whether the current URL matches one of the predefined “autoclose” URLs:
completionUrls.some(...)
These URLs indicate that the payment process has finished inside the WebView.
- Check payment status
If a completion URL is detected:
The component calls checkPaymentStatus(transactionDetails.sessionToken)
Retrieves the final status of the payment (SUCCESS or ERROR)
- Trigger success or failure callback
Depending on the response:
- If SUCCESS -> calls simplyConnectOnSuccess(res)
- If ERROR -> call simplyConnectOnFail(res)
These callbacks notify the app that the payment is complete.
MyPaymentMethods
Overview
Purpose - The MyPaymentMethods component displays a list of the user’s active payment methods (saved credit cards or digital wallets).
It retrieves payment data from the SimplyConnectContext, filters active methods (upoStatus === 'enabled'), and renders a PaymentMethodCard for each one, wrapped in a PaymentMethodProvider.
Where it is used - In any screen that needs to display the user’s saved or active payment methods, such as a profile page or checkout screen.
What the component does
- Retrieves the user’s saved payment methods from context.
- For each valid method:
- Determines the card title which is the card number, depending on the payment type.
- Selects the appropriate logo (Visa, MasterCard, PayPal, ..) or a fallback generic card icon.
- Wraps each card in a
PaymentMethodProviderand renders it using thePaymentMethodCardcomponent.
- Displays a section label (
My payment methods) and renders the list of cards below it. - Returns
nullif there are no active methods or ifuserPaymentsis not available.
Data structure
UserPaymentMethodType
Request
export type UserPaymentMethodType = {
userPaymentOptionId: number;
upoName: string;
paymentMethodName: PaymentMethodNames;
upoStatus: UpoStatuses;
upoRegistrationDate: string;
upoRegistrationTime: string;
expiryDate: string | undefined;
depositSuccess: 'false' | 'true';
withdrawSuccess: 'false' | 'true';
billingAddress: {
countryCode: string;
email: string;
};
cccId: string | undefined;
upoData:
| undefined
| {
uniqueCC?: string;
ccCardNumber?: string;
cardProduct?: string;
bin?: string;
cardType?: string;
ccExpMonth?: string;
ccExpYear?: string;
allowDcc?: string;
secondaryBrand?: string;
issuerCountry?: string;
isDualBranded?: string;
optionalWdType?: string;
brand?: CardTypesEnum;
ccNameOnCard?: string;
lastUsedBrand?: CardTypesEnum;
email?: string;
vault_id?: string;
};
userTokenId: 'ran@sc';
paymentMethodDisplayName?: { language: string; message: string }[];
};
Response
export type UserUposResponseType = {
internalRequestId: number;
status: string;
errCode: number;
reason: '';
merchantId: string;
merchantSiteId: string;
version: string;
sessionToken: string;
paymentMethods: UserPaymentMethodType[];
};
Key functions and variables
filteredUserPaymentMethods
Memoized array of methods filtered to only include active (enabled).
getTitle(methodData)
Returns a display string for each payment method:
- For
cc_card- card number - For
apmgw_expresscheckout- paypal - For
apmgw_Sepa
mapPayments(methodData)
Creates the element for a single payment card:
- Determines the logo:
- Visa
- MasterCard
- Amex
- Discover
- Diners
- UnionPay
- Maestro
- Unknown - generic
Card.svg
- Wraps the card with:
<PaymentMethodProvider
userMethodData={methodData}
merchantMethodData={null}
key={methodData.userPaymentOptionId}
title={getTitle(methodData)}
logoURL={url}
cardType={PaymentCardTypes.MY_METHOD}
paymentMethodType={methodData.paymentMethodName}
localUrl={localUrl}
>
<PaymentMethodCard SvgLogo={Logo} />
</PaymentMethodProvider>
Integration
import MyPaymentMethods from './components/MyPaymentMethods';
Requirements
SimplyConnectContextmust be initialized and provide a validuserPaymentsobject.PaymentMethodCardandPaymentMethodProvidermust support the props passed from this component.- Payment logos (SVGs) should exist in the specified asset directory.
Error handling
- If
userPaymentsisundefinedor empty the component returnsnull. - If a payment method’s
brandorpaymentMethodNameis unrecognized, a defaultCardicon is used.
Diagram and description
flowchart TD
id1(Render MyPaymentMethods) ==> id2(Read userPayments)
id2 ==> id3(Filter only enabled methods)
id3 ==> id4(Display info for each method)
id4 ==> id5(Match each method with correct logo)
id5 ==> id6(Wrap each method inside PaymentMethodProvider)
id6 ==> id7(Render PaymentMethodCard inside that provider)
id7 ==> id8(Display cards list)
classDef bold font-weight:bold,padding:400px;
class id1,id2,id3,id4,id5,id6,id7,id8 bold;
MyPaymentMethods displays the list of payment methods saved by the user. It filters only the enabled payment methods, extracts the correct logo and title for each method, and renders them using PaymentMethodProvider and PaymentMethodCard. Each card is wrapped in its own context, allowing the card to behave independently (selection, validation, styling).
- Render MyPaymentMethods
The component mounts and prepares to show the user’s list of saved payment methods.
- Read userPayments from SimplyConnectContext
MyPaymentMethods relies on the global state from SimplyConnectContext, which includes:
- List of saved payment methods.
- Merchant payment options.
- Filter only enabled methods
Only payment methods with:
upoStatus === 'enabled'
are considered valid for display.
⚠️ Warning:
Expired, blocked, or unverified methods must be excluded.
- Create display title
Depending on the payment method type:
- credit card -> masked card number.
- PayPal (expresscheckout) -> email.
- SEPA -> account name.
💡 Tip:
Titles help users identify each saved method.
- Match each method with correct logo
Available card brands that are mapped:
- Visa;
- MasterCard;
- Amex;
- Discover;
- UnionPay;
- Maestro with a PNG fallback.
If no brand is matched, the default card icon is used.
- Wrap each method with PaymentMethodProvider
Provides:
- userMethodData;
- merchantMethodData (null);
- key (userPaymentOptionId);
- title;
- logoURL;
- cardType = MY_METHOD;
- paymentMethodType;
- localUrl;
Each card receives an independent state context.
- Render PaymentMethodCard
This is the actual visual card with icon, label, and selection behavior.
- Display the section label and list available payment methods
If there are saved methods:
- Shows “My payment methods”.
- Renders the card list inside a wrapper with spacing.
Screenshots
Android

iOS

SelectPaymentMethod
Overview
Purpose - The SelectPaymentMethod component displays the list of available merchant payment methods (those offered by the merchant for checkout).
It retrieves merchant payment data from the SimplyConnectContext, filters out excluded payment methods (using excludeMerchantMethods), and renders a PaymentMethodCard for each one inside a PaymentMethodProvider.
Where it is used - On checkout or payment setup screens where the user must select one of the available merchant payment options to proceed with the transaction.
What the component does
- Retrieves merchant payment methods from the
SimplyConnectContext. - For each valid method:
- Excludes methods defined in
excludeMerchantMethods. - Determines the logo:
- If the method is
cc_card,apmgw_ACH, orapmgw_PayWithCrypto, uses a generic card icon (card.svg).
- If the method is
- Extracts the title from the English entry (
language === 'en') inpaymentMethodDisplayName. - Replaces all
.svgextensions in the logo URL with.png(if applicable).
- Excludes methods defined in
- Wraps the data inside a
PaymentMethodProviderand renders it with aPaymentMethodCard. - Displays a section label —
"Select your payment method". - Returns
nullif there are no merchant payment methods available.
Data structure
MerchantPaymentMethod
Request
export type MerchantPaymentMethod = {
paymentMethod: PaymentMethodNames;
paymentMethodDisplayName: {
language: string;
message: string;
}[];
countries: string[];
currencies: string[];
logoURL: string;
fields: MerchantPaymentMethodFieldType[];
openInExternalBrowser: 'false';
blockedCards: [];
};
Response
export type MerchantMethodsResponse = {
internalRequestId: number;
status: ResponseStatuses;
errCode: number;
reason: string;
merchantId: string;
merchantSiteId: string;
version: string;
sessionToken: string;
paymentMethods: MerchantPaymentMethod[];
type: string;
};
Key functions and variables
mapPayments(methodData, index)
Responsible for rendering each payment method card.
Filters excluded methods:
- Apple Pay and Google Pay are excluded
Determines
Card.svglogo for: cc_cardapmgw_ACHapmgw_PayWithCryptoGenerates display title where the language is set toenand returns a message Creates wrapped card:
<PaymentMethodProvider
userMethodData={null}
merchantMethodData={methodData}
key={index}
title={getTitle()}
logoURL={
methodData.logoURL ? methodData.logoURL.replaceAll('svg', 'png') : ''
}
cardType={PaymentCardTypes.SELECT_METHOD}
paymentMethodType={methodData.paymentMethod}
>
<PaymentMethodCard SvgLogo={logoSvg} />
</PaymentMethodProvider>
Integration
import SelectPaymentMethod from './components/SelectPaymentMethod';
Requirements
SimplyConnectContextmust be initialized and provide a validmerchantPaymentsobject.PaymentMethodProviderandPaymentMethodCardcomponents must support the props used here.- The icon
card.svgshould exist in the../assets/icons/directory. - The list
excludeMerchantMethodsmust contain payment methods that should not be displayed.
Error handling
- If
merchantPaymentsisundefinedornull, the component returnsnull - If the
paymentMethodDisplayNamedoes not contain an English entry, the title will default to an empty string. - If the payment method’s logo is unavailable or invalid, the generic
Cardicon is used as fallback. - Excluded payment methods are skipped and not rendered.
Diagram and description
flowchart TD
id1(Render SelectPaymentMethod) ==> id2(Read merchantPayments)
id2 ==> id3(Filter only enabled methods)
id3 ==> id4(Display info for each method)
id4 ==> id5(Match each method with correct logo)
id5 ==> id6(Wrap each method inside PaymentMethodProvider)
id6 ==> id7(Render PaymentMethodCard inside that provider)
id7 ==> id8(Display cards list)
classDef bold font-weight:bold,padding:400px;
class id1,id2,id3,id4,id5,id6,id7,id8 bold;
SelectPaymentMethod displays a list of merchant-provided payment methods that the user can choose from on the checkout screen. It reads available methods from the SimplyConnectContext, filters enabled ones, prepares titles and icons, and renders each option using PaymentMethodCard wrapped in PaymentMethodProvider. The component is presentational and contains mapping logic. The selection is delegated to each individual PaymentMethodCard.
- Read merchant payment methods
const { merchantPayments } = useSimplyConnectContext();
If merchantPayments is missing, the component returns null.
⚠️ Warning:
Returning null means nothing renders.
- Render the title
A simple header improves readability:
"Select your payment method"
- Iterate through the merchant’s available payment methods
The mapping occurs through:
merchantPayments.paymentMethods.map(mapPayments);
Each payment method goes into mapPayments, which transforms raw backend data into a UI-ready card.
- Filter out excluded payment methods
Some payment methods are not meant to be displayed:
if (excludeMerchantMethods.includes(methodData.paymentMethod)) return null;
- Determine the correct icon for the method
Two possible sources:
- Local SVG icon (default Card.svg) which is used for:
- Credit cards;
- ACH;
- Crypto;
logoSvg = Card;
⭐ Recommendation:
Why SVG is used. It scales better and avoids pixelation on high-resolution screens.
- Merchant-provided image URL (PNG fallback)
The code automatically replaces .svg with .png:
logoURL = {
methodData.logoURL ? methodData.logoURL.replaceAll('svg', 'png') : ''
}
⚠️ Warning:
If the PNG variant does not exist, the UI will show a broken image.
To solve this problem always implement a fallback.
- Extract the English display name
The visible title on the card comes from the English version of the payment method’s localized titles:
methodData.paymentMethodDisplayName.find((m) => m.language === "en");
- Wrap card data in PaymentMethodProvider
This ensures that every PaymentMethodCard has access to:
- userMethodData (null).
- merchantMethodData.
- key (index).
- title.
- logoURL.
- cardType = SELECT_METHOD.
- paymentMethodType.
- localUrl.
⭐ Important: This provider is essential — without it, PaymentMethodCard will not know which method it represents or how to behave when selected.
- Render PaymentMethodCard
This is the interactive card the user taps. It handles:
- Touch interactions.
- Styling.
- Highlighting.
Screenshots
Android

SimplyConnectScreen
Overview
Purpose - SimplyConnectScreen is a screen component that provides a complete payment UI for the SimplyConnect flow. It displays platform-specific quick-pay buttons (Google Pay / Apple Pay) when available, lists saved payment methods, allows selection of a payment method, shows a loading backdrop while operations are in progress and opens an embedded WebView for web interaction.
Where it is used - This component is used to present the full SimplyConnect payment flow (quick-pay buttons, saved payment methods, method selection and web-based redirections).
Behavior
- Renders a full screen
SafeAreaViewwith a scrollable content area. - Shows Google Pay button on Android when merchant supports
ppp_GooglePay. - Shows Apple Pay button on iOS when merchant supports
ppp_ApplePay(usesapplePayMerchantId). - Renders
MyPaymentMethods(saved methods) andSelectPaymentMethod(manual selection). - Displays
BackdropLoaderwhileisLoadingfrom SimplyConnect context istrue. - Renders an embedded
WebViewcomponent (from./WebView/WebView) for flows that require external pages or redirections. - Dismisses keyboard when tapping outside inputs (via
TouchableWithoutFeedback+Keyboard.dismiss).
What the component does
-
Quick-Pay Buttons
- Detects available payment methods from
merchantPayments.paymentMethods. - On Android, renders
GooglePayButtonwhenppp_GooglePayis present. - On iOS, renders
ApplePayButtonwhenppp_ApplePayis present. - Buttons receive
nvPaymentMerchantSettingsand callsimplyConnectOnSuccess/simplyConnectOnFailon completion.
- Detects available payment methods from
-
Saved & Selectable Payment Methods
- Renders
MyPaymentMethodsto present user's stored payment options. - Renders
SelectPaymentMethodto allow manual selection of other supported methods.
- Renders
-
Loading State
- Uses
isLoadingfromSimplyConnectContextto showBackdropLoaderoverlay while the SDK performs network operations (fetching merchant payments, creating sessions).
- Uses
-
WebView Integration
- The
WebViewcomponent is responsible for modal display and navigation monitoring for some payment flows. - The
SimplyConnectContextProviderprovides the necessary contexts and data toWebViewviaSimplyConnectContext.
- The
-
Keyboard / UX
- The screen uses
TouchableWithoutFeedback+Keyboard.dismissto allow closing the keyboard when tapping outside inputs. ScrollViewuseskeyboardShouldPersistTaps="handled"to allow button presses while keyboard is open.
- The screen uses
Data structure
| Name | Type | Description |
|---|---|---|
nvPaymentMerchantSettings | object | Merchant settings object which is required for payment calls. |
simplyConnectOnSuccess | function | Callback from useNuveiContext() invoked on successful payment result. |
simplyConnectOnFail | function | Callback from useNuveiContext() invoked on failed payment result. |
merchantPayments | object | Contains merchant supported paymentMethods. |
isLoading | boolean | Controls the BackdropLoader. |
applePayMerchantId | string | Merchant identifier used by ApplePayButton. |
Key functions
SimplyConnectScreen
- Component that renders the
Contentof the SimplyConnect flow. It relies on theSimplyConnectContextProviderwhich is provided by the globalNuveiProvider.
Content
- Reads
nvPaymentMerchantSettings,simplyConnectOnSuccess,simplyConnectOnFailfromuseNuveiContext(). - Reads
isLoading,merchantPaymentsfromuseSimplyConnectContext(). - Determines
supportsGooglePayandsupportsApplePayusing:
merchantPayments?.paymentMethods?.some(
payment => payment.paymentMethod === PaymentMethodNames.ppp_GooglePay
)
- Renders
GooglePayBtnwith props:
<GooglePayBtn nvPayment={nvPaymentMerchantSettings} onSuccess={simplyConnectOnSuccess} onError={simplyConnectOnFail} />
- Renders
ApplePayBtnwith props:
<ApplePayButton nvPayment={nvPaymentMerchantSettings} applePayMerchantId={applePayMerchantId} onSuccess={simplyConnectOnSuccess} onError={simplyConnectOnFail} />
- Shows
BackdropLoader visible={isLoading}whileisLoadingis true. - Invokes
<WebView />component which handles modal presentation and navigation events.
Integration
export * from './SimplyConnectScreen';
The SimplyConnectScreen component is imported in index.tsx with all other components in it.
Error handling
Missing merchant settings
ContentreturnsnullifnvPaymentMerchantSettingsis falsy. EnsurenvPaymentMerchantSettingsis provided byuseNuveiContext().
Button / payment errors
- Quick-pay buttons (
GooglePayBtn,ApplePayButton) receiveonErrorwhich should callsimplyConnectOnFail. These components return error info.
Loading
BackdropLoaderis driven byisLoadingfromSimplyConnectContext.isLoadingshould be set correctly to avoid blocking the UI or failing to show progress.
Diagram and description
flowchart TD
id1[Render SimplyConnectScreen] ==> wrapper[Wrap children with context provider]
wrapper ==> id2[Render Content]
id2 ==> id3[Reads]
id3 -.-> id4([Order]) & id5([merchantPayments]) & id6([isLoading])
id2 ====> id7[Supports GooglePay / ApplePay]
%%id7 ==> id8(GooglePay) & id9(ApplePay)%%
id7 ==> id10[Render child components]
id10 ==> id11(MyPaymentMethods)
id11 ==> id12(SelectPaymentMethod)
id12 ==> id13(WebView)
classDef bold font-weight:bold;
class id1,id2,id3,id4,id5,id6,id7,id8,id9,id10,id11,id12,id13 bold;
SimplyConnectScreen is the main payment container screen. It loads merchant payment methods, shows wallet payment buttons (Google Pay / Apple Pay), displays saved payment methods, handles loading state, and renders the secure WebView when needed.
It is also responsible for wrapping the entire UI inside SimplyConnectContextProvider, which makes all payment-specific data available to nested components (MyPaymentMethods, SelectPaymentMethod, WebView).
⭐ Simple explanation:
SimplyConnectScreen is the “central brain” of the payment — it coordinates everything that happens during the payment flow.
- Wrap everything inside SimplyConnectContextProvider
<SimplyConnectContextProvider>
<Content />
</SimplyConnectContextProvider>
This ensures the entire payment screen can access:
- Merchant payment methods.
- User payment methods.
- Loading state.
- Current WebView URL.
⚠️ Important:
Without this provider, all nested components would fail — they rely on context values.
- Read global payment data inside
<Content />
const { nvPaymentMerchantSettings, simplyConnectOnSuccess, simplyConnectOnFail } =
useNuveiContext();
If nvPaymentMerchantSettings is null the payment flow cannot continue and the entire screen returns null -> nothing is shown. The parent component must initialize it before showing the screen.
- Detect platform-supported wallet payment methods
const supportsGooglePay = merchantPayments?.paymentMethods?.some(...)
const supportsApplePay = merchantPayments?.paymentMethods?.some(...)
This ensures that Google Pay / Apple Pay buttons appear only when:
- The merchant supports the method.
- The platform matches:
- Android - GooglePay
- iOS - ApplePay
💡 Tip:
Wallet buttons always appear above other payment methods — users recognize them instantly.
- Render payment UI inside a scrollable and keyboard-dismissable layout
The screen uses:
- SafeAreaView;
- ScrollView;
- TouchableWithoutFeedback (to dismiss keyboard)
This ensures good UX across different devices.
⭐ Recommendation:
Keeping payments scrollable prevents layout overflow on smaller Android devices.
- Conditionally render Google Pay / Apple Pay buttons
Google Pay (Android only)
{Platform.OS === 'android' && supportsGooglePay && (
<GooglePayBtn ... />
)}
Apple Pay (iOS only)
{Platform.OS === 'ios' && supportsApplePay && (
<ApplePayButton ... />
)}
- Render user’s saved payment methods
<MyPaymentMethods />
Displays cards saved to user's profile.
- Render merchant-available payment methods
<SelectPaymentMethod />
Shows card payments and alternative payment methods (APM).
⚠️ Important:
This list is dynamic and depends entirely on merchant configuration.
- Display loading overlay when performing requests
<BackdropLoader visible={isLoading} />
Shows a semi-transparent overlay to prevent user interaction during:
- API requests.
- WebView payment.
⚠️ Warning:
User input is not allowed while payment state is loading — it may trigger multiple payment attempts.
- Render the WebView modal
<WebView />
The WebView opens automatically when:
- SimplyConnect sets a webviewUrl.
It handles:
- Displaying payment frame.
- Detecting completion URL.
- Confirming payment result.
3D Service Context
Description
3D Service Context provides services used across the checkout / payment flow. It groups three context providers that together manage 3DS operations, payment initialization. 3D Service Context responsibilities include initializing directory server keys and UI customization, preparing and storing payloads and responses for 3D auth.
This module consists of three context components:
_3DS2ServiceContextProvider– a service context that initializes directory server ID, server public keys, root CA, UI customization. Generates or retrieves a persistent appId, collects device info, encrypts device data and produces aTransactionobject containing ephemeral keys and challenge keys needed for a 3DS v2 transaction.PayServiceContextProvider– a payment-service context that usesinitAuth3D(which calls the backendsendInitAuth3D). Stores the payload and response returned by the init call, holds atransactionref, and keeps client payment responses. It acts as the bridge between UI components and the server-side init / auth endpoints.NuveiProvider– the top-level context which contains: the currentnvPaymentMerchantSettings, merchant / checkout settings, default card values, i18n settings, and success / fail callbacks. It composes the other providers (_3DS2ServiceContextProvider,PayServiceContextProvider) so a single provider can be used for all payment-related services.
3DS2ServiceContext
Overview
Purpose - _3DS2ServiceContextProvider manages and shares the 3D Secure v2 (3DS2) helper functions and data across the app.
It creates 3DS2 transactions that include device data and ephemeral keys.
Where it is used - Wraps the parts of the app that need 3DS2 transactions. Other components/hooks read the shared service context with use3DS2ServiceContext().
Behavior
-
Stores a service object (
_3DS2Service) with initialization state, public keys, UI customization and config parameters. -
Uses
initialize(configParams, uiCustomization)to register directory server info and mark the service as ready. -
Exposes
createTransaction(directoryServerID, messageVersion)to:- collect device info,
- encrypt device info for the directory server,
- generate an ephemeral EC key pair,
- return a
Transactionobject ready for the next 3DS step.
-
Keeps an app ID in persistent storage (AsyncStorage) and generates it once per device.
What the context does
_3DS2ServiceContextProvider is a shared layer for 3DS2 flows.
Responsibilities
-
Accepts and stores configuration about the Directory Server (DS) such as DS id, public key, algorithm via
initialize(). -
Keeps
isInitializedflag and adsPublicKeysmap. -
Provides the following functions:
initialize(configParams, uiCustomization)— registers DS info and UI customization.createTransaction(directoryServerID, messageVersion)— builds a transaction object.use3DS2ServiceContext()— hook to access service and functions.
Data structure
Request
Service type
export type \_3DS2Service = {
isInitialized: boolean;
dsPublicKeys: Map<String, any>;
uiCustomization?: any;
configParams?: ServiceConfigParams;
};
Transaction
export type Transaction = {
directoryServerID: string;
dsPublicKey: any;
deviceData: string | undefined;
appId: string;
sdkReferenceNumber: string;
messageVersion: string;
uiCustomization: any;
configParameters: ServiceConfigParams | undefined;
sdkEphemeralPublicKey: string;
transactionID: string;
counterStoA: number;
challengeKeys: {
sdkJwk: JWK;
sdkReferenceNumber: string;
};
};
Key functions
initialize(configParams, uiCustomization)
- Checks for current service and if the service is initialized, logs error and returns undefined
- What it does:
- Reads keys from
configParamslikeDS@@@ID,DS@@@KEY,DS@@@ALG,DS@@@ROOT_CA,DS@@@ROOT_CA_ALG. - Determines algorithm type (RSA or EC).
- Stores a
dsPublicKeyobject inservice.current.dsPublicKeys. - Stores
uiCustomizationandconfigParamsin the service. - Sets
service.current.isInitialized = true.
- Reads keys from
getOrGenerateAppId()
- Ensures a unique app id exists for the app.
- What it does:
- Tries to read
APP_ID_KEYfrom AsyncStorage. - If the id is missing, generates a new id using UUID (
uuidv4()), stores it and returns it.
- Tries to read
- Used by
createTransaction()to get appId.
createTransaction(directoryServerID, messageVersion)
- Creates a 3DS2 transaction object.
- Steps:
- Checks if service is initialized.
- Validates
directoryServerIDandmessageVersion. - Checks if
messageVersionis supported (fromsupportedVersions). - Verifies DS public key info using
service.current.dsPublicKeys. - Collects device info via
getDeviceInfo(sdkVersion). - Encrypts device info using
encrypt(deviceData, dsPublicKey, directoryServerID) - Generates an ephemeral key pair with
generateECKeyPair(). - Builds and returns a
Transactionobject with:sdkEphemeralPublicKey=sdkEphemeralKeyPair.publicchallengeKeys.sdkJwk=sdkEphemeralKeyPair.private- a new
transactionID(UUID)
- On error: logs an error and returns
undefined.
Integration
This context provider is imported in Context
import { \_3DS2ServiceContextProvider } from './3DS2ServiceContext';
Error handling
initialize():- If called twice, it logs an error and returns without changing state.
- If required config is missing (like
DS@@@ID) it logs and returns.
createTransaction():- If the service is not initialized it logs:
"You must call initialize() first."and returnsundefined. - If
directoryServerIDormessageVersionis null or unsupported it logs and returnsundefined. - If DS public key cannot be found it logs and returns
undefined. - If device info encryption fails it logs the error and returns
undefined. - If generating ephemeral keys fails it logs the error and returns
undefined.
- If the service is not initialized it logs:
Diagram and description
flowchart TD
id1[Load service object] ==> id2["initialize(configParams, uiCustomization)"]
id2 ==> id3[Store]
id3 -.-> id4([DS public keys]) & id5([config]) & id6([uiCustomization])
id2 ===> id7[Call createTransaction]
id7 ==> id8[Validate input]
id8 ==> id9[Fetch or generate app Id]
id9 ==> id10[Collect device info and encrypt it]
id10 ==> id11[Generate EC ephemeral key pair]
id11 ==> id12[Create and return transaction object]
classDef bold font-weight:bold;
class id1,id2,id3,id4,id5,id6,id7,id8,id9,id10,id11,id12 bold;
3DS2ServiceContext manages the 3D Secure v2 (3DS2) setup and transaction creation. It is responsible for:
- Merchant configuration.
- Storing Directory Server (DS) public keys and settings.
- Managing the constant App ID.
- Collecting and encrypting device information.
- Generating EC ephemeral keys.
- Producing a Transaction object for the 3DS2 authentication flow.
This context is the 3DS2 logic layer used internally by the payment flow.
- The Provider is mounted
3DS2ServiceContextProvider is a wrapper for the app.
It creates a shared service instance:
const initialValue: _3DS2Service = {
isInitialized: false,
dsPublicKeys: new Map(),
};
First is created initialValue which is assigned to the service instance
const service = useRef<_3DS2Service>(initialValue);
💡 Info:
The service is stored inside useRef, so it never resets between renders.
- initialize(configParams, uiCustomization) is called
This is the entry point for loading 3DS2 configuration.
What the function does:
- Prevents double initialization.
- Reads the merchant’s DS configuration.
- Detects used algorithm.
- Saves the DS public key configuration into dsPublicKeys.
- Stores UI customization and config parameters.
⚠️ Important:
Initialization must happen before creating any transaction.
- App ID is created or retrieved
When creating a transaction, the app first ensures there is an App ID:
Checks AsyncStorage for App ID. If missing -> generates a unique ID (UUID) and saves it.
💡 Info:
The App ID uniquely identifies the device across 3DS2 flows.
- createTransaction(directoryServerID, messageVersion)
This is the main method used by the payment flow.
The method performs several steps:
-
Validate inputs:
- service must be initialized.
- Directory server ID must be provided.
- Version must be supported (2.1.0 or 2.2.0).
-
Collect device info:
- getDeviceInfo(sdkVersion) - gathers encrypted hardware & OS metadata required by the 3DS2.
-
Encrypt device info using DS public key:
- encrypt(deviceData, dsPublicKey, directoryServerID) - this returns encrypted device data.
⚠️ Warning:
If encryption fails the transaction cannot continue.
- Generate ephemeral EC key pair
A EC key pair is created and is sent to the server.
💡 Tip:
These keys exist only for the current transaction.
- Build the Transaction object:
export type Transaction = {
directoryServerID: string;
dsPublicKey: any;
deviceData: string | undefined;
appId: string;
sdkReferenceNumber: string;
messageVersion: string;
uiCustomization: any;
configParameters: ServiceConfigParams | undefined;
sdkEphemeralPublicKey: string;
transactionID: string;
counterStoA: number;
challengeKeys: {
sdkJwk: JWK;
sdkReferenceNumber: string;
};
};
This object is returned to the caller and used in the 3DS process.
PayServiceContext
Overview
Purpose - PayServiceContextProvider manages and shares the payment data and methods.
It provides a place to initialize the 3D Secure authentication (initAuth3D) and store the responses.
Where it is used - It wraps parts of the application that need access to payment and authentication data — the hooks useAuth3D and useNuveiFields.
Behavior
- Calls
sendInitAuth3D()to start a 3D Secure initialization. - Stores the response and payload for later use.
- Shares its data so that other hooks and components can easily access or update it.
What the context does
PayServiceContextProvider acts as a shared data layer for all payment logic.
Responsibilities
- Initialize 3D Secure authorization by calling
sendInitAuth3D(). - Store and update:
initAuth3DResponse— the result after starting 3DS.initAuth3DPayload— the request body that was sent.clientPaymentResponse— the result of the client payment.transaction— holds a transaction object.
- Provide setter functions to update all of the above.
- Make this data accessible to other parts of the SDK using
usePayServiceContext().
Data structure
Request
export type InitPaymentBody = {
currencyCode?: string;
amount?: string;
billingAddress?: {
country: string;
email: string;
address?: string;
city?: string;
state?: string;
zip?: string;
};
clientRequestId?: string;
countryCode?: string;
currency?: string;
googlePayGateway?: string;
googlePayGatewayMerchantId?: string;
googlePayMerchantId?: string;
googlePayMerchantName?: string;
merchantId?: string | number;
merchantSiteId?: string;
paymentOption: InitPaymentOptions;
requestTimeout?: number;
sessionToken: string;
timeout?: number;
userTokenId?: string;
webMasterId?: string;
deviceDetails?: DeviceDetails;
sourceApplication?: SourceApplication;
relatedTransactionId?: string;
};
Response
export type InitPaymentResponse = {
internalRequestId: number;
status: string;
errCode: number;
reason: string;
merchantId: string;
merchantSiteId: string;
version: string;
clientRequestId: string;
sessionToken: string;
orderId: string;
userTokenId: string;
transactionId: string;
transactionType: string;
transactionStatus: string;
gwErrorCode: number;
gwExtendedErrorCode: number;
paymentOption: {
card: {
ccCardNumber: string;
bin: string;
last4Digits: string;
ccExpMonth: string;
ccExpYear: string;
acquirerId: string;
ccTempToken: string;
threeD: ThreeD;
processedBrand: string;
};
};
customData: string;
result: string;
paymentMethodErrorCode?: number;
gwErrorReason?: string;
paymentMethodErrorReason?: string;
};
Key functions and variables
initAuth3D(paymentSettings, source, nvPaymentMerchantSettings)
- Asynchronously calls
sendInitAuth3D()to begin the 3D Secure process. - Parameters:
paymentSettings: contains merchant and payment configuration data.source: the request source (CHECKOUT,DIRECT,FIELDS).nvPaymentMerchantSettings: the merchant settings (containing amount, currency, sessionToken).
- On success:
- Stores both the
responseandpayloadreturned by the API. - Returns an object with
{ response, payload }.
- Stores both the
- On failure:
- Returns
undefined.
- Returns
initAuth3DResponse
- Holds the last response from the
initAuth3D()request. - Can be updated by calling
setInit3DResponse(response).
initAuth3DPayload
- Stores the payload that was sent during
initAuth3D()initialization.
clientPaymentResponse
- Keeps track of the client payment’s result after 3D Secure completion.
- Accessible to other components that need to check payment status.
Integration
import { PayServiceContextProvider } from './PayServiceContext';
return (
<Context.Provider
value={{
setNvPaymentMerchantSettings,
nvPaymentMerchantSettings,
setSimplyConnectOnFail,
setSimplyConnectOnSuccess,
simplyConnectOnSuccess: simplyConnectOnSuccess.current,
simplyConnectOnFail: simplyConnectOnFail.current,
simplyConnectI18NSettings,
setSimplyConnectI18NSettings,
setNavigateToWebView,
navigateToWebview: navigateToWebview.current,
merchantSettings,
setMerchantSettings,
defaultCardDetails,
setDefaultCardDetails
}}
>
<\_3DS2ServiceContextProvider>
<PayServiceContextProvider>
<PaymentScreenContextProvider>
{props.children}
</PaymentScreenContextProvider>
</PayServiceContextProvider>
</\_3DS2ServiceContextProvider>
</Context.Provider>
);
Error handling
- If
sendInitAuth3D()fails or returnsnull, the function stops and returnsundefined. - Components using this context should always check for a valid response before proceeding:
const result = await sendInitAuth3D(paymentSettings, nvPaymentMerchantSettings, source);
if (!result) {
return;
}
Diagram and description
flowchart TD
id1[initAuth3D] ==> id2[Call sendInitAuth3D]
id2 ==> id3[Receive response and payload]
id3 ==> id6[Store]
id6 -.-> id7([initAuth3DResponse])
id7 -.-> id8([initAuth3DPayload])
id3 ===> id9[Expose]
id9 -.-> id10([clientPaymentResponse])
id10 -.-> id11([transaction reference])
classDef bold font-weight:bold;
class id1,id2,id3,id4,id5,id6,id7,id8,id9,id10,id11 bold;
PayServiceContext manages the initialization phase of the 3D Secure flow. It sends the authentication request to the backend (initAuth3D), stores both the request payload and the backend response, keeps track of the client-side payment result, and exposes a shared transaction reference used later in the 3DS flow.
It is also responsible for storing the result of the backend request (response + payload) in a state so other components can read them at any time.
⭐ Simple explanation:
PayServiceContext is the starting point of the payment authentication process — it prepares and stores everything required before 3DS challenge can begin.
- Wrap payment-related screens inside PayServiceContextProvider
This makes the following data available everywhere in the payment flow:
- The InitAuth3D response from the backend.
- The InitAuth3D request payload/
- The client payment response after authentication.
- The transaction reference, used for 3DS operations.
- The initAuth3D() function that starts the backend request.
⚠️ Important:
Without this provider, no payment component can start 3DS — the authentication data won’t exist.
- Access global PayServiceContext data through the hook
export const usePayServiceContext = () => useContext(payServiceContext);
Where payServiceContext contains:
- initAuth3DResponse;
- setInit3DResponse;
- initAuth3D;
- clientPaymentResponse;
- setClientPaymentResponse;
- initAuth3DPayload;
- setInit3DPayload;
- transaction;
Each field provides part of the 3DS initialization.
💡 Tip:
initAuth3D() it's triggered automatically when the user selects a payment method.
- Calling initAuth3D() to start the backend authentication request
initAuth3D(paymentSettings, nvPaymentMerchantSettings, source) sends the first request to the backend to begin the 3D Secure flow.
const result = await sendInitAuth3D(paymentSettings, nvPaymentMerchantSettings, source);
The arguments used in sendInitAuth3D contain the following values:
- paymentSettings -> merchant configuration;
- nvPaymentMerchantSettings -> total amount, currency, sessionToken;
- source -> where the request came from;
⚠️ Important:
If this request fails, the entire 3DS2 payment flow stops immediately.
- Validate backend response
If the backend returns nothing:
if (!result) return;
Nothing is stored and the payment cannot continue.
- Store InitAuth3D response and payload
When the backend returns data:
setInit3DResponse(result.response); setInit3DPayload(result.payload);
This data includes:
- Transaction info.
- Fields needed for challenge.
💡 Useful:
Storing both the response and the payload ensures that nested components always have the exact data the backend sent.
- Expose and update clientPaymentResponse
The context exposes:
clientPaymentResponse setClientPaymentResponse(...)
This value is set after WebView payment completes and the final result is known.
⭐ Recommendation:
clientPaymentResponse is used to determine if the user should be navigated to a “success”, “fail”, or “loading” page.
- Shared transaction reference
const transaction = useRef(null);
This is used to store transaction-specific data that must be contained across in other components.
💡 Tip: Because it’s a useRef, the value is a constant even if the component re-renders multiple times.
- The context provides everything to all children
<payServiceContext.Provider value={{ ... }}>
{children}
</payServiceContext.Provider>
Any nested payment component can now:
- Start 3DS initialization.
- Access the backend data.
- Access the transaction reference.
- Store client responses.
Context
Overview
Purpose - NuveiProvider is a context provider that manages and shares payment state and callbacks across the SDK.
It centralizes data such as the current nvPaymentMerchantSettings, merchant settings, card details, internationalization (i18n) preferences, and navigation handlers for web views.
Where it is used - NuveiProvider wraps the main part of the application that requires access to Nuvei payment configuration and state.
Behavior
- Stores the active
nvPaymentMerchantSettingsand merchant configuration. - Manages the success and failure callbacks for Simply Connect.
- Holds i18n fields for localization.
- Provides a navigation handler to open web views dynamically.
- Shares default card details for convenience and auto-fill behavior.
- Configures the SDK environment (STAGING or PROD).
- Manages global card blocking rules via
blockCards. - Wraps and integrates additional providers:
_3DS2ServiceContextProvider,PayServiceContextProvider, andPaymentScreenContextProvider.
What the context does
NuveiProvider serves as a central controller for the payment SDK’s state management and callbacks.
Responsibilities
- Manage global state for:
nvPaymentMerchantSettings: current merchant transaction information.merchantSettings: merchant’s checkout and payment configuration.defaultCardDetails: card info.simplyConnectI18NSettings: localization data for Simply Connect screens.
- Store callback references for:
simplyConnectOnSuccess: executed when a Simply Connect operation succeeds.simplyConnectOnFail: executed when a Simply Connect operation fails.navigateToWebview: handles custom navigation to web views.
- Provide setter functions for all of the above.
- Configure global SDK settings:
environment: sets the API environment (STAGING or PROD).blockCards: array af string arrays ([string[]]), where each inner array combination of values to be checked in getCardDetails() and blocked if all exist.
- Ensure that payment and UI-related contexts (
_3DS2ServiceContextProvider,PayServiceContextProvider,PaymentScreenContextProvider) are properly nested and have access to shared data.
Data structure
Request
type ContextType = {
nvPaymentMerchantSettings: NvPaymentMerchantSettings | null;
setNvPaymentMerchantSettings: (value: NvPaymentMerchantSettings) => void;
simplyConnectOnSuccess: (response?: unknown) => void;
setSimplyConnectOnFail: (callback: (error: any) => void) => void;
simplyConnectOnFail: (error: any) => void;
setSimplyConnectOnSuccess: (callback: () => void) => void;
simplyConnectI18NSettings: i18NFieldsType | null;
setSimplyConnectI18NSettings: (value: i18NFieldsType) => void;
setNavigateToWebView: (callback: (webViewParams: any) => void) => void;
navigateToWebview: (webViewParams: any) => void;
merchantSettings: useCheckoutSettingsType | null;
setMerchantSettings: (value: useCheckoutSettingsType) => void;
defaultCardDetails: DefaultCardDetails;
setDefaultCardDetails: (value: DefaultCardDetails) => void;
environment: EnvironmentEnum;
blockCards: BlockCardsType[] | null;
};
NuveiProvider Props
type NuveiProviderPropsType = {
children: ReactNode;
environment?: EnvironmentEnum;
blockCards?: BlockCardsType[];
};
Key functions
nvPaymentMerchantSettings, setNvPaymentMerchantSettings(value)
- Stores and updates the current active merchant and transaction settings data.
- The
NvPaymentMerchantSettingscontains amount, currency, sessionToken, and merchant identifiers.
simplyConnectOnSuccess, setSimplyConnectOnSuccess(callback)
simplyConnectOnSuccessholds the callback executed after a successful Simply Connect eventsetSimplyConnectOnSuccessregisters a new callback function dynamically.
simplyConnectOnFail, setSimplyConnectOnFail(callback)
simplyConnectOnFailholds the callback executed when Simply Connect fails.- Accepts an error object with optional
errorCodeand areasonmessage.
simplyConnectI18NSettings, setSimplyConnectI18NSettings(value)
- Manages the localization fields (labels, text, and translations) used by Simply Connect.
- Can be updated to change the current language dynamically.
navigateToWebview, setNavigateToWebView(callback)
navigateToWebviewstores a callback for handling navigation to a web view.setNavigateToWebViewreplaces the current navigation function.
merchantSettings, setMerchantSettings(value)
- Holds the merchant’s configuration.
defaultCardDetails, setDefaultCardDetails(value)
- Stores default cardholder data:
cardHolderNamecardNumberCVVexpirationYearexpirationMonth
environment
- Sets the SDK environment. Available values are
EnvironmentEnum.STAGINGandEnvironmentEnum.PROD. - When set, it automatically calls
setGlobalEnvironmentto update the base URL for API requests.
blockCards
- An optional array of card BINs or identifiers that should be blocked across the SDK.
- These rules are respected by validation hooks and components like
NuveiFieldsto prevent users from proceeding with blocked cards.
Integration
All components that Context contains are exported in index.ts
export \* from './Context'
Error handling
- Callback setters (
setSimplyConnectOnFail,setSimplyConnectOnSuccess, etc.) should always be initialized before triggering their corresponding actions. - Components using the context should validate data before use:
const simplyConnectOnFail = useRef<
(error: { errorCode?: number; reason: string }) => void
>(() => { });
Diagram and description
flowchart TD
id1[Create global state] ==> id2[Expose callbacks]
id2 ==> id3[Provide context]
id3 ==> id4[Wrap children]
id4 -.-> id5([3DS2ServiceContext]) & id6([PayServiceContext])
classDef bold font-weight:bold;
class id1,id2,id3,id4,id5,id6 bold;
Context (NuveiProvider) is the root provider for thе SimplyConnect payment. It stores global payment configuration such as:
- The current merchant and transaction settings.
- Merchant settings.
- Internationalization (i18N).
- Default card form values.
- Merchant callbacks (onSuccess / onFail).
- Custom error messages.
It also wraps all children with:
- 3DS2ServiceContextProvider;
- PayServiceContextProvider;
This ensures all payment logic — 3DS2 validation, authentication, card flow, and errors — is available everywhere.
⭐ Simple explanation:
Context is the “global storage” for the entire payment. Everything depends on it.
- Initialize the global payment state
The provider initializes multiple values:
const [nvPaymentMerchantSettings, setNvPaymentMerchantSettings] = useState<NvPaymentMerchantSettings | null>(null);
const [merchantSettings, setMerchantSettings] = useState(null);
const [defaultCardDetails, setDefaultCardDetails] = useState({...});
const [customNuveiFieldsCardNumberError, setCustomNuveiFieldsCardNumberError] = useState('');
const [simplyConnectI18NSettings, setSimplyConnectI18NSettings] = useState(null);
📌 Important:
All payment screens rely on the objectnvPaymentMerchantSettings. If it is not set, the payment UI cannot function.
- Store success/failure callbacks using useRef
const simplyConnectOnSuccess = useRef<() => void>(() => {});
const simplyConnectOnFail = useRef<(error) => void>(() => {});
useRef ensures the callback always points to the latest merchant-provided handler.
These callbacks allow the merchant to react to:
- Successful payments.
- Failed / declined payments.
💡 Useful:
Using useRef avoids re-rendering the entire payment UI when callbacks change.
- Expose setter functions for callbacks
const setSimplyConnectOnSuccess = (callback: () => void) => {
simplyConnectOnSuccess.current = callback;
};
const setSimplyConnectOnFail = (
callback: (error: { errorCode?: number; reason: string }) => void
) => {
simplyConnectOnFail.current = callback;
};
This helps to configure:
- What happens on payment success.
- What happens on payment failure.
- Provide all values through Context.Provider
<Context.Provider value={{
nvPaymentMerchantSettings,
setNvPaymentMerchantSettings,
setSimplyConnectOnFail,
setSimplyConnectOnSuccess,
simplyConnectOnSuccess: simplyConnectOnSuccess.current,
simplyConnectOnFail: simplyConnectOnFail.current,
simplyConnectI18NSettings,
setSimplyConnectI18NSettings,
merchantSettings,
setMerchantSettings,
defaultCardDetails,
setDefaultCardDetails,
customNuveiFieldsCardNumberError,
setCustomNuveiFieldsCardNumberError,
}}>
All nested components can now access this state using:
useNuveiContext();
📌 Important:
This is the global data source for the whole payment flow. Missing it breaks everything.
- Wrap children with additional providers
<3DS2ServiceContextProvider>
<PayServiceContextProvider>{props.children}</PayServiceContextProvider>
</3DS2ServiceContextProvider>
This setup creates a nested provider hierarchy:
- Context – global configuration;
- 3DS2ServiceContext – handles 3DS2 flows;
- PayServiceContext – handles initAuth3D, payload, and payment responses;
⭐ Recommendation:
Provider nesting should be kept in this order — payment logic depends on the upper layers.
⚠️ Warning:
Reordering these providers may cause 3DS2 flows or authentication to break unexpectedly.
3D Secure
Description
3D Secure provides the full logic and tools required to run 3D Secure v2 (3DS2) and 3D Secure v1 (3DS1) authentication in a checkout. It ensures a secure verification process.
This module consists of two primary parts:
useAuth3D- this hook organises the complete 3D authentication for a card payment. It is typically used inside checkout screens or anywhere a card payment needs to be confirmed.useGetAuth3DPayload- this hook is responsible for preparing and constructing the 3DS2 payload required for the authentication request. It is used before triggering a client payment that requires a 3DS2 challenge.
3DAuth
Overview
Purpose - useGetAuth3DPayload and its related functions manage the initialization and preparation of the 3D Secure v2 (3DS2) authentication flow for card payments.
It is responsible for:
- Preparing and structuring the 3DS2 payload
- Initializing a 3DS2 transaction through the SDK service.
- Building and returning a fully configured payload
useGetAuth3DPayload is typically used before initiating a client payment or challenge flow.
Where it is used - Inside payment and checkout flows where a card payment requires 3DS2 authentication.
The returned payload is passed to the payment API call (doClientPayment or doClientAuth3D), which then either completes frictionless or initiates a challenge.
Behavior
- Reads
threeDconfiguration from theInitPaymentResponse. - Checks if 3DS2 is supported (
v2Supported). - If not supported -> falls back to 3DS v1 flow.
- If supported:
- Parses the Directory Server (DS) public key and algorithm.
- Initializes a 3DS2 transaction using the SDK service.
- Builds the object required for the authentication request.
- Adds to the request browser details and challenge window size.
- Returns the final payload and server transaction ID for the next step in the payment process.
What the hook does
- Retrieves 3DS2 directory server data (ID, public key, algorithm).
- Initializes a 3DS2 transaction through
use3DS2ServiceContext. - Gathers browser and device information (screen size, locale, user agent, IP address, timezone).
- Constructs and returns the final 3DS2 payload to be sent with the payment request.
- Supports force web challenge mode (used when the merchant wants to handle challenges in a webview).
Data structure
Request
export type ChallengeParameters = {
threeDSServerTransactionID: string;
acsTransactionID: string;
acsRefNumber: string;
acsSignedContent: string;
threeDSRequestorAppURL: string;
};
export type CReq = {
threeDSRequestorAppURL: string;
threeDSServerTransID: string;
acsTransID: string;
challengeCancel: string;
challengeDataEntry: string;
challengeHTMLDataEntry: string;
challengeNoEntry: string;
challengeWindowSize: string;
messageExtension: string;
messageType: string;
messageVersion: string;
oobContinue: string;
resendChallenge: string;
sdkTransID: string;
sdkCounterStoA: string;
whitelistingDataEntry: string;
};
export type InitPaymentBody = {
currencyCode?: string;
amount?: string;
billingAddress?: {
country: string;
email: string;
address?: string;
city?: string;
state?: string;
zip?: string;
};
clientRequestId?: string;
countryCode?: string;
currency?: string;
googlePayGateway?: string;
googlePayGatewayMerchantId?: string;
googlePayMerchantId?: string;
googlePayMerchantName?: string;
merchantId?: string | number;
merchantSiteId?: string;
paymentOption: InitPaymentOptions;
requestTimeout?: number;
sessionToken: string;
timeout?: number;
userTokenId?: string;
webMasterId?: string;
deviceDetails?: DeviceDetails;
sourceApplication?: SourceApplication;
relatedTransactionId?: string;
};
Response
export async function doClientPayment(body: InitPaymentBody) {
if (body.paymentOption.card?.cardNumber) {
body.paymentOption.card.cardNumber = body.paymentOption.card.cardNumber
.split(' ')
.join('');
}
try {
const response = await fetch(`${API_BASE_URL_V1}websdk/clientPayment.do`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
return await response.json();
} catch (error: any) {
return error;
}
}
export async function doClientAuth3D(body: InitPaymentBody) {
try {
const response = await fetch(`${API_BASE_URL_V1}clientAuthorize3d.do`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
return await response.json();
} catch (error: any) {
return error;
}
}
export type InitPaymentResponse = {
internalRequestId: number;
status: string;
errCode?: number;
reason: string;
merchantId: string;
merchantSiteId: string;
version: string;
clientRequestId: string;
sessionToken: string;
orderId: string;
userTokenId: string;
transactionId: string;
transactionType: string;
transactionStatus: string;
gwErrorCode?: number;
gwExtendedErrorCode: number;
paymentOption: {
card: {
ccCardNumber: string;
bin: string;
last4Digits: string;
ccExpMonth: string;
ccExpYear: string;
acquirerId: string;
ccTempToken: string;
threeD: ThreeD;
processedBrand: string;
};
};
customData: string;
result: string;
paymentMethodErrorCode?: number;
gwErrorReason?: string;
paymentMethodErrorReason?: string;
};
Key functions
getNotificationURL(sessionToken: string, isCreatePayment: boolean)
- Builds the notification URL for 3DS2 callbacks after challenge completion.
- Used when
forceWebChallengeis enabled.
useInit3DS2Transaction()
- Initializes a new transaction with the 3DS2 SDK.
- Returns both
transactionandsdkmetadata required for the authentication request.
getDirectoryServerPublicKeyAlg(directoryServerPublicKeyAndAlg: string[])
- Validates and extracts the algorithm from the directory server public key.
getAuthRequestParams(transaction: Transaction)
- Builds SDK authentication parameters (ephemeral key, reference number, transaction ID, ..).
filterClientAuthorize3d(threeD: ThreeD)
- Lists only the fields required by the backend during client authorization to keep the payload minimal and secure.
getScreenSizeLabel(width: number, height: number)
- Maps screen dimensions to one of the standard 3DS2 challenge window size labels:
01: 250x40002: 390x40003: 500x60004: 600x40005: Full screen
getTimezoneOffsetInHours()
- Calculates the client timezone offset
Integration
import { useGetAuth3DPayload } from '../utils/3DAuth.ts';
Error handling
- If
payServiceContextor_3DSContextisnull-> returns nothing (log error). - If directory server public key or algorithm is missing / invalid -> returns
ERROR_CODES.INTERNAL_ERROR. - If transaction initialization fails -> returns
ERROR_CODES.INTERNAL_ERROR. - If 3DS2 is not supported (
v2Supported === false) -> returns original payment body for v1 fallback. - If required SDK fields are missing -> challenge flow will not start and an error is returned.
Diagram and description
flowchart TD
id1[Init 3DS2 Service] ==> id2[Create transaction]
id2[Build Auth3D Payload] ==> id3[Send Challenge Req]
id3 ==> id4[Handle ASC Challenge]
id4 ==> id5[Recieve Challenge Res]
id5 ==> id6[Compplete Payment/Verify]
classDef bold font-weight:bold;
class id1,id2,id3,id4,id5,id6 bold;
The 3DAuth component is responsible for the 3D Secure v2 (3DS2) authentication inside the payment flow. It handles:
- Initializing 3DS2.
- Creating a 3DS transaction.
- Preparing the Auth3D payload.
- Launching the Challenge (CReq).
- Decrypting ACS responses.
- Running the challenge loop until completion.
- Finishing the payment or verification.
⭐ Explanation:
This component is a bridge between the app, the cardholder device, the Directory Server (DS), and the ACS (bank).
- Initializing the 3DS2 Service
The function useInit3DS2Transaction() performs:
- Loading Directory Server (DS) IDs.
- Loading the DS public key.
- Preparing configuration.
- Creating UI customizations for the challenge screens.
⚠️ Warning:
If the DS public key or algorithm is not valid, the entire 3DS2 process will stop — this is required for security.
💡 Tip: The public key and algorithm always should be passed together. Missing fields cause errors.
- Creating a Transaction
After initialization, it is generated:
- transactionID.
- sdkEphemeralPublicKey.
- Device metadata.
- Message version.
- Building the Auth3DPayload
The function useGetAuth3DPayload():
- Reads the card’s 3D configuration.
- Detects if 3DS2 is supported.
- Merges payloads from:
- The backend (server data).
- The SDK (device data).
- The app (screen size, language)
- Sending CReq (Challenge Request)
The function useDoChallenge() prepares the CReq message:
- Builds the JSON payload.
- Encrypts it using the ephemeral public key.
Sends it to the ACS URL
- Handling the ACS Challenge
The ACS responds with CRes:
- May request user interaction (OTP, PIN, biometrics).
- May be automatic (frictionless).
💬 Tip:
The component retries challenge steps and updates transaction counters (sdkCounterStoA) automatically.
- Receiving the Challenge Result (CRes)
The ACS response may indicate:
- Finalized challenge (success/failure).
- More challenge steps required.
- Protocol error.
- Runtime errors.
executeChallenge() validates:
- Message type.
- Challenge completion indicator.
- Completing the Payment / Verification
After challenge completion, useHandle3d2Challenge() decides:
- If the flow is a payment, call doClientPayment.
- If it's a card verification, call doClientAuth3D.
Finally, the backend processes:
- Transaction status.
- Authentication indicators.
useAuth3D
Overview
Purpose - useAuth3D manages the 3D Secure authentication flow for card payments. It coordinates:
- calling the payment service to start an auth3D flow (
initAuth3D). - performing the client-side payment call (
useClientPayment). - handling 3DS v2 and 3DS v1.
- invoking success/error callbacks.
Where it is used - Inside checkout screens (or anywhere an app needs to create/confirm a card payment) to run the full 3D authentication step.
Behavior
- Calls
payServiceContext.initAuth3D(paymentSettings, nvPaymentMerchantSettings)to obtain initialresponseandpayload. - Uses
clientPayment(payload, response, forceWebChallenge, isCreatePayment)to perform the client payment step. - Inspects the client payment response:
- If frictionless (APPROVED) — resolves success or passes response to
onSuccess. - If REDIRECT (3DS v2) — triggers either internal
handle3d2ChallengeorforceWebChallengepath returningwebViewParams. - If v1 — constructs
webViewParamsfor 3DS v1.
- If frictionless (APPROVED) — resolves success or passes response to
What the hook does
- Starts the authorization flow via
payServiceContext.initAuth3D(paymentSettings, nvPaymentMerchantSettings). - Calls the client payment function with the returned payload and response.
- Sets
payServiceContext.setClientPaymentResponse(clientPaymentResponse). - Delegates the 3DS outcome handling to
handleClientPaymentResponse:- For v2
APPROVED: returns the response (frictionless). - For v2
REDIRECT:- If
forceWebChallengeChecked === true→ returnswebViewParamsproduced byforceWebChallengePaymentFrame. - Else → calls
handle3d2Challenge(...)(the 3DS v2 challenge handler).
- If
- For non-v2 flows, if
threeDcontainsacsUrl+paRequest+sessionToken→ returns 3DS v1webViewParams(viainit3D1PaymentFrame).
- For v2
- If
webViewParamsare produced, the hook callsnavigateToWebview(webViewParams)so the host app can present the ACS web page.
Data structure
Request
export const useAuth3D: (isDirect?: boolean) => (props: {
isCreatePayment: boolean;
paymentSettings: PaymentSettings;
forceWebChallengeChecked: boolean;
navigateToWebview: (webViewParams: WebViewParams) => void;
onSuccess?: (res: any) => void;
onError?: (res: any) => void;
source: RequestSource;
nvPaymentMerchantSettings: NvPaymentMerchantSettings;
}) => Promise<void>
Parameters
isCreatePayment: booleantruewhen creating a new paymentpaymentSettings: PaymentSettingsPayment configuration object passed toinitAuth3D.forceWebChallengeChecked: booleanWhentrue, forces the SDK to open a webview for 3DS v2 challenges instead of the normal 3DS v2 challenge.nvPaymentMerchantSettings: NvPaymentMerchantSettings | nullOrder data used byinitAuth3D.navigateToWebview: (webViewParams: unknown) => voidRequired callback when a webview must be shownonSuccess?: (res:any) => voidOptional callback invoked when final payment status isAPPROVED(after client payment).onError?: (res:any) => voidOptional callback invoked on errors orDECLINEDstatuses.
Key functions
forceWebChallengePaymentFrame(acsUrl, creq, sessionToken, isCreatePayment, toolbarBgColor?)
- Builds
webViewParamsfor forcing a 3DS v2 web challenge frame
Where webViewParams contains:
const webViewParams = {
challengeType: CHALLENGE_TYPE.THREE_D2_FORCE_WEB,
acsUrl: acsUrl,
creq: creq,
termUrl: notificationURL,
toolbarBgColor: toolbarBgColor,
isCreatePayment: isCreatePayment,
};
handleForceWebChallenge({ clientPaymentInput, clientPaymentOutput, isCreatePayment, threeD })
- Wrapper to extract details from threeD and call
forceWebChallengePaymentFrame
init3D1PaymentFrame({ acsUrl, paRequest, sessionToken, isCreatePayment })
- Builds
webViewParamsfor a 3DS v1 web challenge frame
Where webViewParams contains:
const webViewParams = {
challengeType: CHALLENGE_TYPE.THREE_D1,
acsUrl: acsUrl,
paRequest: paRequest,
termUrl,
toolbarBgColor: '#40c1ac',
isCreatePayment: isCreatePayment,
};
useHandleClientPaymentResponse()
- Returns a function that handles the
clientPaymentresult:- if the
statusfrom a transaction is 'APPROVED' returns frictionless response - if the
statusis 'REDIRECT' returns force web challenge - otherwise (DECLINED, CANCELLED, ERROR) returns errors
- if the
Integration
import { useAuth3D } from './src/hooks/useAuth3d.tsx';
Error handling
- If
nvPaymentMerchantSettingsisnull-> nothing happens. - If
payServiceContext?.initAuth3D(...)returns falsy -> returns nothing. - If
response.status === 'ERROR'->onErroris called withresponse - If
clientPaymentResultis missing orclientPaymentResult.response.status !== 'SUCCESS'ortransactionStatus === 'DECLINED'->onErrormay be invoked. - If required fields for webview construction are missing (
acsUrl,creq/notificationUrl) -> return{ error: ERROR_CODES.INTERNAL_ERROR }.
Diagram and description
graph TD
id1["initAuth3D()"] ==> id2[clientPayment]
id2 ==> id3[Process clientPaymentResponse]
id3 ==> id4[Force Web Challenge] & id5[3DS2 Challenge]
id4 ==> id6[WebView redirect]
id4 ===> id8[Completion]
id5 ==> id7[Handle Challenge]
id5 ===> id8
id8 -.-> id9([Success]) & id10([Error])
classDef bold font-weight:bold;
class id1,id2,id3,id4,id5,id6,id7,id8,id9,id10 bold;
useAuth3D is part of the 3D Secure authentication flow. It coordinates:
- Initialization of the 3DS process via the server.
- Execution of the initial payment call.
- Detection of 3DS version (3DS1, 3DS2).
- Routing to the correct challenge method (challenge or forced web challenge).
- Handling success, errors, and WebView redirection.
- Notifying other layers through onSuccess or onError.
It acts as the controller for all 3DS operations in the payment flow.
- Initialize Auth3D on the Server (initAuth3D)
The first action is calling:
payServiceContext.initAuth3D(paymentSettings, nvPaymentMerchantSettings, source);
This prepares the backend for 3D authentication and returns:
- response (server result).
- payload (data needed for clientPayment).
⚠️ Warning:
If the server response is ERROR, the component immediately triggers onError.
- Execute the initial client payment (clientPayment)
This sends the first authentication payload to the server.
Returns:
- response – contains transactionStatus.
- payload – used for the next step.
- serverTransId – used in 3DS2.
- v2Supported – whether the card supports 3DS2.
💡 Tip:
If isError(clientPaymentResult), this means the card or network blocked the payment.
⚠️ Warning:
If this step fails, the flow stops completely.
- Process the client payment response
Handled by handleClientPaymentResponse()
This step decides the actual 3DS path:
It checks:
- Is this 3DS2?
- Is the flow frictionless?
- Does the ACS require a challenge?
- Do we need to redirect to WebView?
- Should we force a Web Challenge?
Possible transaction statuses:
- APPROVED → frictionless
- REDIRECT → challenge needed
- DECLINED → stop, call onError
- ERROR → stop, call onError
4A. Force Web Challenge (THREE_D2_FORCE_WEB)
Triggered only when:
Merchant enforces WebView challenge or forceWebChallengeChecked is true
It is used forceWebChallengePaymentFrame() which builds webViewParams
4B. 3DS2 Challenge (handle3d2Challenge)
Runs only if 3DS2 is supported and forceWebChallenge is false
- WebView or Challenge execution
Depending on Step 4:
If Web Challenge:
- The app navigates to WebView:
- navigateToWebview(webViewParams)
This opens the ACS page where the user completes the challenge.
If Challenge:
Automatically handling authentication screens.
⚠️ Warning:
If both WebView and Challenge fail, the final result is treated as an authentication error.
- Completion (Success / Error)
After challenge execution:
- If APPROVED → call onSuccess
- If DECLINED or ERROR → call onError
- If no response → treat as fatal error
💡 Tip:
Success requires both:
status: "SUCCESS";
transactionStatus: "APPROVED";
Otherwise the payment is not authenticated.
Public Utilities and Hooks
The Nuvei SDK provides several utility hooks and API functions that can be used for custom integrations or to enhance the payment flow.
Public API Functions
These functions are available in httpService.ts and can be used to interact directly with the Nuvei backend.
getCardDetails(payload: GetCardDetailPayload)
Retrieves metadata about a card based on its number or a saved payment method ID (UPO).
Usage:
import { getCardDetails } from 'react-native-nuvei';
const details = await getCardDetails({
cardNumber: '4111...',
merchantId: '...',
merchantSiteId: '...',
sessionToken: '...',
});
Returns: A CardDetails object containing:
brand: Card brand (e.g., 'visa', 'mastercard').cardType: 'Credit' or 'Debit'.isPrepaid: Boolean indicating if it's a prepaid card.issuerCountry: Country code of the issuing bank.issuerBankName: Name of the issuing bank.bin: The first 6 digits of the card.last4Digits: The last 4 digits of the card.
checkPaymentStatus(sessionToken: string)
Checks the final status of a payment for a specific session.
Usage:
import { checkPaymentStatus } from 'react-native-nuvei';
const status = await checkPaymentStatus(sessionToken);
setGlobalEnvironment(env: EnvironmentEnum)
Sets the SDK environment globally (STAGING or PROD).
Usage:
import { setGlobalEnvironment, EnvironmentEnum } from 'react-native-nuvei';
setGlobalEnvironment(EnvironmentEnum.PROD);
Utility Hooks
These hooks provide pre-built logic for common UI and validation tasks.
useGetCardDetails()
A SimplyConnect helper hook that returns a function to fetch details for the currently selected card in the context.
Usage:
import { useGetCardDetails } from 'react-native-nuvei';
const getDetails = useGetCardDetails();
try {
const details = await getDetails();
console.log(details.brand);
} catch (error) {
console.error(error.message);
}
useGetCreditCardFieldsErrors()
A utility hook that validates credit card fields using the current SimplyConnect i18n settings and validation rules.
Usage:
import { useGetCreditCardFieldsErrors } from 'react-native-nuvei';
const getErrors = useGetCreditCardFieldsErrors();
const { cvvError, dateError, nameError, numberError } = getErrors(
cardHolder,
cvv,
cardNumber,
expiry,
isValidCardType,
cvvLengthArray
);
useShowCardNumberError()
Returns the current custom card number error message from the Nuvei context. Useful for custom UI components that need to react to card block errors.
Usage:
import { useShowCardNumberError } from 'react-native-nuvei';
const cardNumberError = useShowCardNumberError();
Data Structures
GetCardDetailPayload
type GetCardDetailPayload = {
cardNumber?: string;
userPaymentOptionId?: number;
merchantId: string;
merchantSiteId: string;
sessionToken: string;
clientRequestId?: string;
};
CardDetails
type CardDetails = {
brand: string;
cardType: string;
isPrepaid: boolean;
issuerCountry: string;
issuerBankName: string;
bin: string;
last4Digits: string;
ccExpMonth: string;
ccExpYear: string;
secondaryBrand: string;
status: string;
// ... other metadata fields
};