Skip to main content

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:

  • NuveiFields component – a UI component that renders input fields for cardholder name, card number, expiration date, and CVV. It supports dynamic styling, validations, and localization via i18NLabels. It also manages user interactions, card type detection, and triggers payment initialization.
  • useNuveiFields hook – 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 paymentOption object, including saving user payment preferences if provided.
  • Returns a fully prepared NVPaymentBody object.

What the function does

  1. Payload Configuration

    • Builds a paymentOption object 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.
  2. Data Filtering

    • Removes amount and currency from the merchant settings before constructing the payload (as per native code requirements).
  3. Payload Construction

    • Combines the following data sources into a single NVPaymentBody:
      • Card data (card)
      • Merchant settings (nvPaymentMerchantSettings)
      • Payment settings (paymentSettings)
      • SDK source application metadata
    • Ensures compatibility with the Nuvei API’s required structure.
  4. 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:

  1. Builds the paymentOption object with the provided card.
  2. If available, includes savePm and userPaymentOptionId from paymentSettings.paymentOption.
  3. Filters out amount and currency from the merchant settings.
  4. Constructs the final payload object with all merchant, payment, and SDK data.
  5. Logs the payload to the console.
  6. Returns a Promise resolving to the completed NVPaymentBody.

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 returns null, the payload still initializes with deviceDetails: undefined.
    The SDK will proceed safely without interruption.

Invalid or Missing Data

  • If mandatory fields (sessionToken, amount, or currency) 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.savePm is defined → sets savePm in paymentOption.
  • If userPaymentOptionId exists → converts to string and assigns to paymentOption.userPaymentOptionId.

Assemble payload

  • Removes amount and currency from nvPaymentMerchantSettings (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 NVPaymentBody object.

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 TextInput component.
  • Optionally shows an error message below the input.
  • Accepts additional styles for the container, label, input, and error text.
  • Fully supports TextInput props such as value, onChangeText, keyboardType, placeholder.

What the component does

  1. Label Rendering

    • Displays a text label above the input field.
    • Uses default styling defined in the component but allows customization through the labelStyle prop.
  2. Input Field

    • Renders a TextInput component with predefined border, padding, and radius styles.
    • Allows full customization through the inputStyle prop or by passing standard TextInput props.
  3. Error Handling

    • Optionally displays an error message below the input field.
    • The text color and font size can be customized via errorStyle.
  4. Layout and Styling

    • The component arranges the label, input, and error vertically.
    • Extra layout customization can be applied using the extraStyles prop.

Data structure

Request

type LabelAndErrorContainerPropsType = PropsWithChildren<{
label: string | undefined;
extraStyles?: object;
errorText?: string;
labelStyle?: TextStyle;
errorStyle?: TextStyle;
}>;
NameTypeDescription
labelstringText displayed above the input.
extraStylesobjectAdditional styles for the container
errorTextstringText displayed below the input when an error occurs.
labelStyleTextStyleCustom style for the label text.
errorStyleTextStyleCustom 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 LabelAndErrorContainer with a TextInput, providing a labeled input with error handling.
  • Combines label, text input, and error message into one component.
  • Passes all TextInput props (value, onChangeText, keyboardType, secureTextEntry) to the internal TextInput.
  • 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

NuveiFields Input Component

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.

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 tokenize and initPayment logic through the useNuveiFields.
  • Displays a loading overlay (ModalBackdrop) during payment initialization.
  • Calls onSuccess on successful payment or onFail when any error occurs.

What the SDK does

  1. Initial Setup

    • Accepts props for transactionDetails, paymentSettings, uiSettings, and callback handlers (onSuccess, onFail).
    • Initializes all card-related states and logic through useNuveiFields.
  2. UI Rendering

    • Dynamically builds customized styles based on uiSettings (border, color, font).
    • Renders four input fields:
      1. Cardholder Name
      2. Card Number (with detected card brand logo)
      3. Expiration Date
      4. CVV
    • Each field supports localized labels and placeholders via uiSettings.i18NLabels.
  3. Validation and Tokenization

    • When the “Pay” button is pressed:
      • Calls validateFields() to check all form inputs.
      • If validation passes, triggers initPayment() from useNuveiFields to begin payment initialization.
      • Shows ModalBackdrop while the payment is processing.
  4. 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.
  5. Dynamic Card Detection

    • Automatically detects card type (Visa, MasterCard, Maestro) via checkCardType().
    • Displays the appropriate card logo next to the card number input.

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 true if 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

  • transactionDetails must be a valid TransactionDetails object (with amount, currency, merchant details).
  • uiSettings should contain all visual customization values (colors, borders, fonts).
  • A valid PaymentSettings object 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 tokenize or initPayment trigger onFail(error)

Payment declined

  • If the backend returns a declined transaction, the component calls onFail with the declined response.

UI behavior

  • The loader (ModalBackdrop) is displayed until the operation completes.

Diagram and description

NuveiFields

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

  1. State Management

    • Stores card data (number, expiry, cvv, cardHolderName) using useState.
    • Tracks field-specific error messages in a state object (errors).
    • Keeps reference to fetched cardDetails after calling getCardDetails().
  2. Input Handling

    • Dynamically formats the following:
      • Card Number: grouped into 4-digit segments (#### #### #### ####).
      • Expiry Date: formatted as MM/YY.
      • CVV: restricted to numeric characters.
    • Automatically updates local state after each change.
  3. 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).
    • Returns true if there are errors, false if validation passes.
  4. Tokenization

    • Sends card data securely to the Nuvei API using tokenizePost(sessionToken, card).
    • Returns a ccToken that represents the card details without exposing sensitive information.
  5. Payment Initialization

    • Builds a CardInfo object and triggers the 3D Secure authentication via useAuth3D().
    • Handles both success and failure outcomes via onSuccess and onError callbacks.
    • Returns a Promise that resolves once the payment process completes.

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: ensures MM/YY format.
    • cvv: digits only.
  • Triggers validation on change (if implemented).
validateFields()
  • Validates all card input fields before payment.
  • Uses helper functions like checkCardType, validateExpiry, validateCVV, and validateName.
  • Returns: An object containing:
    • hasErrors: boolean -> true if 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:

  1. Builds the request body with card data.
  2. Calls tokenizePost(sessionToken, card).
  3. Awaits the Nuvei response containing a tokenized card.
  4. Returns the response to be used in initPayment().
initPayment(onComplete)
  • Initializes the full payment process, including 3D Secure flow.

Steps:

  1. Constructs a CardInfo object from the current card state.
  2. Calls auth3D() to trigger 3D Secure authentication.
  3. Uses provided paymentSettings and transactionDetails.
  4. 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 errors state and displayed below input fields.

Network or SDK errors

  • If tokenize or initPayment fails, the parent component calls onFail(error).

3D Secure authentication errors

  • Returned by auth3D() through the onError callback.

Diagram and description

NuveiFields logic

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.

  1. 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)
  1. 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()

  1. 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);

  1. 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

  1. Tokenizing Card Data (tokenize)
  • Wrapper around: tokenizePost(transactionDetails.sessionToken, card)

  • Used when a token is needed.

  1. 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

NuveiFields context

  1. Context Creation
const Context = createContext<ContextType>({});

A context is created with a default value — currently an empty object.

  1. 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.

  1. useNuveiFieldsContext Hook
export const useNuveiFieldsContext = () => useContext(Context);

This hook gives the using component direct access to the context.