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.