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.

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.

What the component does

At a level, this component displays a label above a text input field, renders a customizable text input using the TextInput component, optionally shows an error message below the input, and supports custom container/label/input/error styling along with standard TextInput props.

  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.

NuveiFields

Overview

Purpose - NuveiFields renders a set of input fields (InputComponent) 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.

What the component does

  1. Initial Setup

    • Accepts props for transactionDetails, paymentSettings, uiSettings, payment result callbacks, and optional form-event callbacks.
    • 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 (Cardholder Name, Card Number, Expiration Date, CVV).
    • Card Number input includes dynamic brand logo detection.
    • Each field supports localized labels and placeholders via uiSettings.i18NLabels.
  3. Validation and Tokenization

    • Card validation is managed by the validation hooks and states.
    • Payment initialization is NOT managed directly by the NuveiFields component. Instead, the parent component must import the useNuveiFieldsPay hook, which returns a payHandler function that triggers validation, error check, payment initialization, and loading overlay state (ModalBackdrop).
  4. Success and Error Handling

    • The onSuccess(response) and onFail(error) callbacks provided as props to the component are invoked automatically when the payment hook completes successfully or fails.
    • The loading overlay (ModalBackdrop) inside the component is shown/hidden automatically during the payment operation.
  5. Dynamic Card Detection

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

    • Exposes validateFields() and tokenize() methods to the parent component via a ref, allowing imperative validation and tokenization from outside the component.

Data structure

Props

The NuveiFields component accepts the following props:

type Props = {
paymentSettings?: Partial<PaymentSettings>;
transactionDetails: TransactionDetails;
uiSettings: UiSettings;
onSuccess: (response: any) => void;
onFail: (response: any) => void;
forceWebChallenge: boolean;
callbacks?: {
onPaymentFormChange?: (payload: OnPaymentFormChangePayload) => void;
onFormValidated?: (payload: OnFormValidatedPayload) => void;
onInputUpdated?: (
hasFocus: boolean,
expMonth: string,
expYear: string
) => void;
onInputValidated?: (errors: string[]) => void;
};
};
PropTypeRequiredDescription
transactionDetailsTransactionDetailsYesDetails of the transaction including session token, merchant identifiers, amount, billing details, etc.
uiSettingsUiSettingsYesObject defining font sizes, colors, borders, custom i18N labels, and card lookup management.
paymentSettingsPartial<PaymentSettings>NoOptional client settings including Google Pay details or target backend settings.
onSuccess(response: any) => voidYesCallback invoked when the payment transaction completes successfully.
onFail(response: any) => voidYesCallback invoked when validation, network request, tokenization, or payment fails.
forceWebChallengebooleanYesIf set to true, enforces the web challenge for 3DS authentication.
callbacks{ onPaymentFormChange?, onFormValidated?, onInputUpdated?, onInputValidated? }NoEvent callbacks for field interaction and form validation.

When NuveiFields mounts or the callback props change, it registers the supplied functions in NuveiFieldsContext through setOnPaymentFormChange and setOnFormValidated. The input and validation code reads the callbacks from this shared context, so the events are emitted by the field components rather than directly by the parent screen.

onPaymentFormChange

Called when a payment form field gains or loses focus. Card-number values are masked in the event payload.

type OnPaymentFormChangePayload = {
pm: string;
label: string;
action: 'focus' | 'blur';
oldValue: string;
newValue: string;
validation: string | null;
paste: boolean;
};
FieldDescription
pmPayment method name. For Nuvei Fields this is cc_card.
labelLocalized label of the field, such as Card number or CVV.
actionWhether the field received focus or lost focus.
oldValueValue captured before the event. Sensitive card-number data is masked.
newValueCurrent value after the event. Sensitive card-number data is masked.
validationCurrent validation message, or null when the field is valid.
pastetrue when the value associated with a blur event was pasted.

How it works internally:

  1. Each InputComponent keeps its previously reported value in lastValueRef and tracks whether the latest edit appears to be a paste.
  2. On focus or blur, it calls validateFields(true). The true argument performs silent validation: errors are recalculated, but onInputValidated is not fired and the validateTriggered display flag is not toggled.
  3. For the card-number field, a custom blocked-card error takes precedence over the normal number validation error.
  4. The component builds the payload using the localized label, the previous and current values, and the current validation result. Card-number values pass through maskPaymentFormChangeValue before leaving the SDK.
  5. The callback runs only for focus and blur; ordinary keystrokes do not emit the event. A change of more than one character at once is treated as a paste, reported on blur, and then reset.
  6. After emitting, lastValueRef is updated so the next event's oldValue reflects the last reported value.

onFormValidated

Called when the overall form validity or set of invalid fields changes.

type OnFormValidatedPayload = {
isFormValid: boolean;
invalidFields: string[];
};

For Nuvei Fields, invalidFields can contain ccNameOnCard, ccCardNumber, ccExpYear, and ccCVV. A blocked card can also add creditCardBlocked.

How it works internally:

  1. NuveiFields watches the card state and the custom card-number error. Whenever either changes, it runs validateFields(true) to calculate the current form state without displaying new errors.
  2. It collects every field whose validation result is non-empty and maps the internal keys to the public names:
    • cardHolderNameccNameOnCard
    • numberccCardNumber
    • expiryccExpYear
    • cvvccCVV
  3. isFormValid is true only when the mapped invalidFields array is empty.
  4. A ref stores the previously emitted validity and comma-joined invalid-field list. The callback runs only if one of those values changed, preventing repeated identical events on re-render.
  5. Because validation is silent, this event does not toggle the error-display trigger, fire onInputValidated, or start a payment.
<NuveiFields
{...props}
callbacks={{
onPaymentFormChange: (payload) => {
console.log('Field event:', payload);
},
onFormValidated: ({ isFormValid, invalidFields }) => {
console.log('Form valid:', isFormValid, invalidFields);
},
}}
/>

TransactionDetails

This represents the transaction configurations (without the sensitive card details):

type TransactionDetails = {
sessionToken: string;
merchantId: string;
merchantSiteId: string;
clientRequestId?: string;
amount?: string;
currency?: string;
billingAddress?: BillingAddress;
shippingAddress?: ShippingAddress;
userDetails?: UserDetails;
requestTimeout?: number;
timeout?: number;
};

UiSettings

Defines visual formatting, internationalization labels, and card validation settings:

type UiSettings = {
customFonts: boolean;
backgroundColor: ColorType;
borderColor: ColorType;
borderWidth: number;
cornerRadius: number;
labelFontSize: number;
labelFontColor: ColorType;
fieldFontSize: number;
fieldFontColor: ColorType;
fieldBackgroundColor: ColorType;
placeholderFontColor: ColorType;
fieldBorderColor: ColorType;
fieldBorderWidth: number;
fieldCornerRadius: number;
errorFontSize: number;
errorFontColor: ColorType;
i18NTextManagement: boolean;
i18NLabels: i18NFieldsType;
getCardDetailsManagement: boolean;
cardBrand: string;
cardBrandError: string;
requestError: string;
};

Key functions and variables

useNuveiFieldsPay

  • Hook that returns a handler function (payHandler) to validate the input fields and trigger the payment process.

validateFields

  • Checks all input fields for correctness and returns { hasErrors: boolean, newErrors: errorsType, errorsArr: string[] }.

tokenize

  • Generates a card token.

checkCardType

  • Detects card type based on entered card number.

getCreditCardLogo

  • Returns brand logo image for detected card type.

Integration

Import the component and the payment hook:

import { NuveiFields, useNuveiFieldsPay } from 'react-native-nuvei';

Example usage in a payment screen component:

import React from 'react';
import { View, Button } from 'react-native';
import { NuveiFields, useNuveiFieldsPay } from 'react-native-nuvei';

export function PaymentScreen() {
const payHandler = useNuveiFieldsPay();

return (
<View>
<NuveiFields
transactionDetails={transactionDetails}
uiSettings={uiSettings}
paymentSettings={paymentSettings}
onSuccess={(res) => console.log('Success:', res)}
onFail={(err) => console.log('Fail:', err)}
forceWebChallenge={false}
/>
<Button title="Pay" onPress={payHandler} />
</View>
);
}

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

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.

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.

Card Type and Logo

  • Uses checkCardType(card.number) to determine card type.
  • Displays appropriate logo (Maestro icon or dynamic logo).

Payment Handler (via useNuveiFieldsPay)

  • Invoking payHandler (from useNuveiFieldsPay) will:
    • Validate form fields.
    • Display field-specific validation errors.
    • If no errors, sets loading state and starts payment initialization.
    • Automatically handles successes (onSuccess) and failures (onFail).

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.
  • WebView3D → handles 3D Secure challenge.

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.

What the module does

  1. Context Integration

    • Retrieves shared states (card data, validation errors, labels, loadingCardDetails flag) from NuveiFieldsContext.
    • Accesses global card blocking settings (blockCards) and custom card number error states from NuveiContext.
  2. Input Handling and Card Lookup

    • Dynamically formats and normalizes inputs as they are typed:
      • Card Number: grouped into 4-digit segments (#### #### #### ####).
      • Expiry Date: formatted as MM/YY.
      • CVV: restricted to numeric characters.
    • When a valid card format/type is detected on input:
      • Triggers an asynchronous BIN lookup via getCardDetails().
      • Checks the card against configured block rules.
    • Calls onUpdated(true) to notify the parent component of user activity.
  3. Validation

    • Exposes validateFields() (sourced from useValidateFields) which checks form completeness and formatting:
      • Card number format and brand detection.
      • Expiry date validity.
      • CVV length based on card type.
      • Cardholder name completeness.
    • Triggers the onInputValidated callback with an array of active error codes.
    • Returns { hasErrors: boolean, newErrors: errorsType }.
  4. Tokenization

    • Exposes the tokenize() function (sourced from useTokenize) which sends card details securely to the Nuvei API using tokenizePost(sessionToken, card) and returns the tokenization response.
  5. Payment Initialization

    • Exposes initPayment() which constructs a CardInfo payload and triggers 3D Secure verification via useAuth3D().
    • Returns a Promise that resolves on success or rejects on failure.

Data structure

Arguments

The useNuveiFields hook accepts the following parameters:

ParameterTypeDescription
transactionDetailsTransactionDetailsDetails of the transaction (merchant settings, sessionToken).
paymentSettingsPartial<PaymentSettings>Optional billing/shipping or payment method configurations.
setWebViewParamsPropsDispatch<SetStateAction<WebViewParams | null>>State setter function to handle WebView coordinates/parameters for 3D Secure challenge.
onUpdated(isFocus: boolean) => voidCallback triggered when field updates or blur event executes.
setShowErrorByFieldDispatch<SetStateAction<{[key: string]: boolean}>>State setter to manage error visibility dynamically per field.
forceWebChallengebooleanFlag indicating whether the 3D Secure challenge should be forced.

Return Value

The hook returns the following object:

{
handleInputChange: (field: CardFieldType, value: string) => void;
initPayment: () => Promise<any>;
card: CardType;
errors: errorsType;
setErrors: Dispatch<SetStateAction<errorsType>>;
setCard: Dispatch<SetStateAction<CardType>>;
setLabels: Dispatch<SetStateAction<UiSettings['i18NLabels']>>;
validateFields: (silent?: boolean) => { hasErrors: boolean; newErrors: errorsType };
tokenize: () => Promise<any>;
}

Key functions

handleInputChange(field, value)
  • Updates card input state and handles formatting.
  • Applies specific formatting/normalization:
    • number: groups into 4-digit segments and initiates asynchronous BIN details/block checks.
    • expiry: formats as MM/YY format.
    • cvv: digits only.
  • Resets validation error markers for the edited field.
validateFields(silent?: boolean)
  • Validates expiration, cardholder name, CVV, and card number.
  • Updates field error states.
  • Returns { hasErrors: boolean, newErrors: errorsType }.
tokenize()
  • Securely tokenizes the card details using tokenizePost(sessionToken, card).
  • Resolves with the tokenized card details, or rejects if validation fails or a network error occurs.
initPayment()
  • Builds the card details and initiates the 3D Secure verification flow via auth3D().
  • Resolves when payment completes successfully, or rejects with an error payload.

Integration

This hook is used internally by the NuveiFields component to bind inputs, manage states, perform validation, and handle card detail lookups:

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 retrieves shared state from NuveiFieldsContext (via useNuveiFieldsContext) instead of initialising its own state:
  • Card, errors, labels, loadingCardDetails — all sourced from NuveiFieldsContext.
  • validateFields — obtained from the useValidateFields hook (defined in NuveiFieldsContext).
  • tokenize — obtained from the useTokenize hook (defined in NuveiFieldsContext).

Also retrieves:

  • setCustomNuveiFieldsCardNumberError, blockCards from the global Nuvei context (useNuveiContext).
  • 3DS authentication handler (auth3D) via useAuth3D.
  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: Uses the returned card details to evaluate the configured card-blocking rules.

  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

useNuveiFieldsPay

Overview

Purpose - useNuveiFieldsPay is the hook that drives the "Pay" button action in the NuveiFields component.
It orchestrates field validation, 3D Secure payment initialization, loading state, and the final onSuccess / onFail callbacks — all sourced from NuveiFieldsContext.

Where it is used - Called once inside NuveiFields.tsx. Returns the payHandler function, which is bound directly to the Pay button's onPress.

What the hook does

At a high level, this hook runs validateFields() before attempting any payment network call. It guards against blocked card numbers (customNuveiFieldsCardNumberError) and in-progress card-detail fetches (loadingCardDetails), sets isLoading = true while the payment request is in flight and resets it when done, and invokes onSuccess from context on success or onFail on any error.

  1. Reads from context

    Consumes the following from useNuveiFieldsContext():

    • card — current card field values.
    • paymentSettings, transactionDetails, forceWebChallenge — payment configuration.
    • setIsLoading, setWebViewParamsProps — UI state setters.
    • onSuccess, onFail — result callbacks registered by the parent component.
    • loadingCardDetails — guard flag set while getCardDetails is pending.

    Also consumes:

    • customNuveiFieldsCardNumberError from useNuveiContext() — present when the card is blocked.
    • validateFields from useValidateFields().
    • auth3D from useAuth3D().
  2. initPayment() (internal async function)

    • Builds a CardInfo object from the current card state.
    • If customNuveiFieldsCardNumberError is set, immediately rejects with error code 10010.
    • Otherwise calls auth3D() to start the 3D Secure flow, passing:
      • paymentSettings (with card injected into paymentOption).
      • forceWebChallengeChecked.
      • navigateToWebview — sets webViewParamsProps to open the 3DS WebView.
      • onSuccess and onError (resolve / reject of the wrapping Promise).
      • source: RequestSource.FIELDS.
      • nvPaymentMerchantSettings: transactionDetails.
    • Returns a Promise that resolves or rejects when the auth flow completes.
  3. payHandler() (returned function)

    The main entry point bound to the Pay button:

    const { hasErrors } = validateFields();
    if (customNuveiFieldsCardNumberError || loadingCardDetails) return;
    if (!hasErrors) {
    setIsLoading(true);
    try {
    const res = await initPayment();
    onSuccess(res);
    } catch (error) {
    onFail(error);
    } finally {
    setIsLoading(false);
    }
    }
    • Runs validation first; if any field is invalid the Pay button does nothing (errors are shown on screen via validateFields).
    • Aborts silently if the card is blocked or card details are still loading.
    • On success calls onSuccess(res) and resets the loader.
    • On failure calls onFail(error) and resets the loader.

Key functions

initPayment()
  • Internal async function that builds the 3DS auth request and returns a Promise.
  • Not exported — only consumed by payHandler.
payHandler()
  • The value returned by the hook.
  • Async function bound to the Pay button.
  • Guards, validates, calls initPayment, and dispatches success / failure callbacks.

Integration

import { useNuveiFieldsPay } from './hooks/useNuveiFieldsPay';

const payHandler = useNuveiFieldsPay();
// ...
<Button onPress={payHandler} title="Pay" />

The hook must be called inside a component that is wrapped by NuveiFieldsProvider and NuveiProvider.

Error handling

Validation errors

  • If validateFields() returns hasErrors: true, payHandler returns early. Error messages are already set in the errors state and displayed under each field.

Blocked card

  • If customNuveiFieldsCardNumberError is set, payHandler returns early without initiating payment. initPayment also rejects immediately with errCode: 10010.

Card details still loading

  • If loadingCardDetails is true (i.e. getCardDetails API call is in progress), payHandler returns early to prevent a race condition.

3D Secure / network errors

  • Any rejection from auth3D() is caught by the try/catch in payHandler and forwarded to onFail(error).

payWithCcTempToken

Overview

Purpose - payWithCcTempToken processes a card payment with a temporary card token (ccTempToken) returned by useTokenize(). This lets an application separate card collection and tokenization from payment processing, without passing raw card details to the payment function.

Unlike useNuveiFieldsPay, this is a standalone async utility rather than a React hook. It does not read payment settings or callbacks from NuveiFieldsContext.

Signature

payWithCcTempToken(
body: NVPaymentBodyWithCcTempToken,
onError: (error: any) => void
): Promise<any>

Parameters

ParameterTypeDescription
bodyNVPaymentBodyWithCcTempTokenPayment request containing the temporary token in paymentOption.card.ccTempToken. It can also contain the standard transaction, merchant, address, user, and payment-option settings supported by NVPaymentBody.
onError(error: any) => voidCalled when initial payment setup fails, the card payment response contains an error, or the request throws.

NVPaymentBodyWithCcTempToken requires the following card structure:

paymentOption: {
card: {
ccTempToken: string;
cardHolderName?: string;
};
}

Payment flow

When called, payWithCcTempToken:

  1. Sets cardHolderName to an empty string when it is not supplied.
  2. Calls initPayment() with the supplied body.
  3. Stops and calls onError if the initial response contains a payment or 3D Secure setup error. The error is normalized with transactionStatus: 'ERROR', errCode, and reason.
  4. Calls cardClientPayment() when initialization succeeds.
  5. Calls onError with transactionStatus: 'ERROR' if the final payment response is an error; otherwise, it returns the successful payment response.

The utility automatically sets sourceApplication to DIRECT_ANDROID or DIRECT_IOS, based on the current React Native platform. On any failure it calls onError and resolves without a success response, so the caller should only handle the returned value when it is defined.

Integration

First obtain a temporary token from useTokenize(), then add it to the payment body:

import {
payWithCcTempToken,
useTokenize,
type NVPaymentBodyWithCcTempToken,
} from 'react-native-nuvei';

const tokenize = useTokenize();

const handleTokenizeAndPay = async () => {
try {
const { ccTempToken } = await tokenize();

const paymentBody: NVPaymentBodyWithCcTempToken = {
sessionToken: 'YOUR_SESSION_TOKEN',
merchantId: 'YOUR_MERCHANT_ID',
merchantSiteId: 'YOUR_MERCHANT_SITE_ID',
amount: '10.00',
currency: 'USD',
paymentOption: {
card: {
ccTempToken,
cardHolderName: 'John Doe',
},
},
};

const result = await payWithCcTempToken(paymentBody, (error) => {
console.error('Payment failed:', error);
});

if (result) {
console.log('Payment successful:', result);
}
} catch (error) {
// Handles errors from tokenization.
console.error('Tokenization failed:', error);
}
};

useShowCardNumberError

Overview

Purpose - useShowCardNumberError is a hook that returns the setCustomNuveiFieldsCardNumberError setter function from the global Nuvei context. This allows components to dynamically set or clear custom card number error messages (e.g., when a card is blocked by custom merchant rules).

Integration & Usage

import { useShowCardNumberError } from 'react-native-nuvei';

const setCardNumberError = useShowCardNumberError();

// Set a custom validation error message
setCardNumberError('This card is blocked.');

// Clear the custom error message
setCardNumberError('');

NuveiFieldsContext

Overview

Purpose - NuveiFieldsContext is the central state-management layer for the entire NuveiFields module. It owns all card-input state, validation state, payment lifecycle state, and callback refs shared between the NuveiFields component, useNuveiFields, useValidateFields, and useTokenize. Consuming components never need to lift state themselves — they simply call useNuveiFieldsContext() to access and mutate the shared store.

Where it is used - NuveiFieldsProvider must wrap the NuveiFields component tree. All hooks inside the module consume state through useNuveiFieldsContext().

State managed by the context

State / RefTypeDescription
cardCardTypeCurrent values for number, expiry, cvv, cardHolderName.
errorserrorsTypePer-field validation error strings.
labelsUiSettings['i18NLabels']Localised label/placeholder strings.
sessionTokenstringNuvei session token used for tokenization.
paymentSettingsPaymentSettingsPayment configuration passed to 3DS auth.
transactionDetailsTransactionDetailsMerchant and transaction metadata.
forceWebChallengebooleanForces the web-based 3DS challenge.
isLoadingbooleantrue while the payment call is in flight.
loadingCardDetailsbooleantrue while getCardDetails is pending.
webViewParamsPropsWebViewParams | nullParams to open the 3DS WebView.
validateTriggeredbooleanSet to true once validation has run (drives error display).
validateFieldsRefReact.MutableRefObjectRef to the validateFields function, exposed via useImperativeHandle.
onInputValidated (ref)onInputValidatedType | nullCallback fired with an errorsArr after each validation run.
onPaymentFormChange (ref)OnPaymentFormChangeType | nullCallback fired on every form-change event.
onFormValidated (ref)OnFormValidatedType | nullCallback fired when the whole form is validated.
onSuccess (ref)(response) => voidCalled when the payment succeeds.
onFail (ref)(error) => voidCalled when the payment fails.

Diagram and description

NuveiFields context

  1. Context Creation
export const NuveiFieldsContext = createContext<NuveiFieldsContextType | undefined>(undefined);

The context is typed as NuveiFieldsContextType | undefined. Consuming it outside a provider throws a descriptive error.

  1. Provider Component
export const NuveiFieldsProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
// ... all useState / useRef declarations ...
return (
<NuveiFieldsContext.Provider value={{ card, setCard, errors, setErrors, ... }}>
{children}
</NuveiFieldsContext.Provider>
);
};

The provider owns all state and callback refs listed above, initialises them, and passes them as the context value. All components inside <NuveiFieldsProvider> can access and mutate this shared state.

  1. useNuveiFieldsContext Hook
export const useNuveiFieldsContext = () => {
const context = useContext(NuveiFieldsContext);
if (!context) throw new Error('useNuveiFieldsContext must be used within a NuveiFieldsProvider');
return context;
};

Throws if called outside a provider, preventing silent misuse.

  1. Co-located utility hooks

Two additional hooks are exported from the same file and rely on useNuveiFieldsContext:

  • useValidateFields() — returns a validateFields(silent?) function that validates all four card fields, updates the errors state, populates errorsArr, and optionally calls onInputValidated.
  • useTokenize() — returns a tokenize() function that first runs validation via validateFieldsRef and, if there are no errors, calls tokenizePost(sessionToken, card).

Card Validation and Blocking (blockCards)

NuveiFields supports restricting or blocking specific credit/debit card types, brands, or issuing countries using the blockCards rules array configured in NuveiProvider.

How it works

When the user enters a card number in the credit card input form:

  1. Rule Evaluation Trigger

    • As the user types in the card number field, a check calls the getCardDetails() API.
    • The hook sets loadingCardDetails to true while the validation request is in flight.
  2. Fetching Card Details

    • The SDK calls the getCardDetails() API to fetch card properties such as card brand, card type (Credit or Debit), prepaid status, issuer country, and issuer bank.
  3. Rule Matching & Abort

    • The returned card properties are evaluated against the blockCards array.
    • If any rule matches (indicating the card is blocked):
      • The custom card error customNuveiFieldsCardNumberError is set with a message (either from labels.errorMessageCustomisation or dynamically generated from the matched rule).
      • The validation error message is shown directly under the card number field.
      • If the user attempts to complete the payment flow via initPayment() while a block is active, the flow is aborted early and rejects the promise with error code 10010.
    • If no rules match:
      • The custom error is cleared, allowing the payment to proceed.