Skip to main content

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.

NuveiProvider

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. It must be imported by the merchant application, and they have to provide the needed data (props) in order to initialize the context and use the SDK functionality.

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.
  • Provide setter functions for all of the above.
  • Configure global SDK settings:
    • environment: sets the API environment (STAGING or PRODUCTION).
    • blockCards: array of BlockCardsType rules checked in getCardDetails() to block specific cards.
  • Ensure that payment and UI-related contexts (_3DS2ServiceContextProvider, PayServiceContextProvider, SimplyConnectContextProvider, NuveiFieldsProvider) are properly nested and have access to shared data.

Data structure

Context Type

type ContextType = {
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;
merchantSettings: UseCheckoutSettingsType | null;
setMerchantSettings: (value: UseCheckoutSettingsType) => void;
defaultCardDetails: DefaultCardDetails;
setDefaultCardDetails: (value: DefaultCardDetails) => void;
customNuveiFieldsCardNumberError: string;
setCustomNuveiFieldsCardNumberError: (message: string) => void;
environment: EnvironmentEnum;
nvPaymentMerchantSettings: NvPaymentMerchantSettings | null;
setNvPaymentMerchantSettings: (value: NvPaymentMerchantSettings) => void;
simplyConnectCountryCode: string;
setSimplyConnectCountryCode: (value: string) => void;
blockCards: BlockCardsType[] | null;
getCardDetailsEnabled: boolean;
};

NuveiProvider Props

type NuveiProviderPropsType = {
children: ReactNode;
environment?: EnvironmentEnum;
blockCards?: BlockCardsType[];
getCardDetailsEnabled?: boolean;
};

getCardDetailsEnabled defaults to false. Set it to true to allow useGetCardDetails to request metadata for a card entered in NuveiFields or selected in Simply Connect.

Key functions

nvPaymentMerchantSettings, setNvPaymentMerchantSettings(value)
  • Stores and updates the current active merchant and transaction settings data.
  • The NvPaymentMerchantSettings contains amount, currency, sessionToken, and merchant identifiers.
simplyConnectOnSuccess, setSimplyConnectOnSuccess(callback)
  • simplyConnectOnSuccess holds the callback executed after a successful Simply Connect event
  • setSimplyConnectOnSuccess registers a new callback function dynamically.
simplyConnectOnFail, setSimplyConnectOnFail(callback)
  • simplyConnectOnFail holds the callback executed when Simply Connect fails.
  • Accepts an error object with optional errorCode and a reason message.
simplyConnectI18NSettings, setSimplyConnectI18NSettings(value)
  • Manages the localization fields (labels, text, and translations) used by Simply Connect.
  • Can be updated to change the current language dynamically.
customNuveiFieldsCardNumberError, setCustomNuveiFieldsCardNumberError(message)
  • customNuveiFieldsCardNumberError stores a custom error message for card number validation errors.
  • setCustomNuveiFieldsCardNumberError updates the validation message.
simplyConnectCountryCode, setSimplyConnectCountryCode(value)
  • simplyConnectCountryCode stores the current billing country code used in Simply Connect.
  • setSimplyConnectCountryCode updates the country code.
merchantSettings, setMerchantSettings(value)
  • Holds the merchant’s configuration.
defaultCardDetails, setDefaultCardDetails(value)
  • Stores default cardholder data:
    • cardHolderName
    • cardNumber
    • CVV
    • expirationYear
    • expirationMonth
environment
  • Sets the SDK environment. Available values are EnvironmentEnum.STAGING and EnvironmentEnum.PROD.
  • When set, it automatically calls setGlobalEnvironment to 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 NuveiFields to prevent users from proceeding with blocked cards.

Integration

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

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;
  • SimplyConnectContextProvider;
  • NuveiFieldsProvider;
<_3DS2ServiceContextProvider>
<PayServiceContextProvider>
<SimplyConnectContextProvider>
<NuveiFieldsProvider>
{props.children}
</NuveiFieldsProvider>
</SimplyConnectContextProvider>
</PayServiceContextProvider>
</_3DS2ServiceContextProvider>

This ensures all payment logic — 3DS2 validation, authentication, card flow, and errors — is available everywhere.

All nested components can now access this state using: useNuveiContext();

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

What the context does

_3DS2ServiceContextProvider is a shared layer for 3DS2 flows.

  • 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 Transaction object ready for the next 3DS step.
  • Keeps an app ID in persistent storage (AsyncStorage) and generates it once per device.

Responsibilities

  • Accepts and stores configuration about the Directory Server (DS) such as DS id, public key, algorithm via initialize().

  • Keeps isInitialized flag and a dsPublicKeys map.

  • 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

Service type

export type _3DS2Service = {
isInitialized: boolean;
dsPublicKeys: Map<String, any>;
uiCustomization?: any;
configParams?: ServiceConfigParams;
};

Service Configuration Parameters

The configuration parameters object expects keys structured as ${CONFIG_GROUP}@@@${CONFIG_KEY}:

export type ServiceConfigParams = {
[key: string]: string | undefined;
};

Supported config keys:

  • DS@@@ID: Directory Server (DS) identifier.
  • DS@@@KEY: DS public key.
  • DS@@@ALG: DS public key algorithm (e.g., RSA or EC).
  • DS@@@ROOT_CA: DS Root CA certificate.
  • DS@@@ROOT_CA_ALG: DS Root CA certificate algorithm.
  • HOSTING_APP_GROUP_NAME@@@HOSTING_APP_IMAGE: Base64-encoded hosting application image.

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;
};
};

Context Value

type contextType = {
service: _3DS2Service | undefined;
initialize: (configParams: ServiceConfigParams, uiCustomization: any) => void;
createTransaction: (
directoryServerID: string,
messageVersion: string
) => Promise<Transaction | void>;
};

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 configParams like DS@@@ID, DS@@@KEY, DS@@@ALG, DS@@@ROOT_CA, DS@@@ROOT_CA_ALG.
    • Determines algorithm type (RSA or EC).
    • Stores a dsPublicKey object in service.current.dsPublicKeys.
    • Stores uiCustomization and configParams in the service.
    • Sets service.current.isInitialized = true.
getOrGenerateAppId()
  • Ensures a unique app id exists for the app.
  • What it does:
    • Tries to read APP_ID_KEY from AsyncStorage.
    • If the id is missing, generates a new id using UUID (uuidv4()), stores it and returns it.
  • Used by createTransaction() to get appId.
createTransaction(directoryServerID, messageVersion)
  • Creates a 3DS2 transaction object.
  • Steps:
    1. Checks if service is initialized.
    2. Validates directoryServerID and messageVersion.
    3. Checks if messageVersion is supported (from supportedVersions).
    4. Verifies DS public key info using service.current.dsPublicKeys.
    5. Collects device info via getDeviceInfo(sdkVersion).
    6. Encrypts device info using encrypt(deviceData, dsPublicKey, directoryServerID)
    7. Generates an ephemeral key pair with generateECKeyPair().
    8. Builds and returns a Transaction object with:
      • sdkEphemeralPublicKey = sdkEphemeralKeyPair.public
      • challengeKeys.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 returns undefined.
    • If directoryServerID or messageVersion is null or unsupported it logs and returns undefined.
    • 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.

Diagram and description

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.

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

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

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

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.

What the context does

PayServiceContext manages the initialization phase of the 3D Secure flow. It sends the authentication request to the backend (initAuth3D) by calling sendInitAuth3D(), 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 shares its data so that other hooks and components can easily access or update it.

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.

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

PayServiceContext Type

export type PayServiceContextType = {
initAuth3DResponse: InitPaymentResponse | null;
setInit3DResponse: Dispatch<InitPaymentResponse | null>;
initAuth3D: (
paymentSettings: PaymentSettings,
source: RequestSource,
nvPaymentMerchantSettings: NvPaymentMerchantSettings
) => Promise<
| {
response: InitPaymentResponse;
payload: NVPaymentBody;
}
| undefined
>;
clientPaymentResponse: any;
setClientPaymentResponse: Dispatch<SetStateAction<any>>;
initAuth3DPayload: NVPaymentBody | null;
setInit3DPayload: Dispatch<SetStateAction<NVPaymentBody | null>>;
transaction: MutableRefObject<any>;
};

NVPaymentBody (Request)

export type NVPaymentBody = {
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 response and payload returned by the API.
    • Returns an object with { response, payload }.
  • On failure:
    • Returns undefined.
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.

Error handling

  • If sendInitAuth3D() fails or returns null, the function stops and returns undefined.
  • 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

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.

What the hook does

  • Reads threeD configuration from the InitPaymentResponse and checks if 3DS2 is supported (v2Supported).
  • If 3DS2 is not supported, it falls back to the 3DS v1 flow by returning the original payment request payload.
  • If 3DS2 is supported:
    • Parses the Directory Server (DS) public key and algorithm.
    • Initializes a 3DS2 transaction through use3DS2ServiceContext.
    • Gathers browser and device information (screen size, locale, user agent, IP address, timezone).
    • Builds the object required for the authentication request.
    • Adds browser details and challenge window size to the request.
  • Supports force web challenge mode (used when the merchant wants to handle challenges in a webview).
  • Returns the final payload and server transaction ID for the next step in the payment process.

Data structure

Hook Signature

export const useGetAuth3DPayload: () => (
body: NVPaymentBody,
initPaymentResponse: InitPaymentResponse,
forceWebChallenge: boolean,
isCreatePayment: boolean
) => Promise<
| {
error: ERROR_CODES;
errorDescription: string;
result?: InitPaymentResponse;
}
| {
payload: Auth3DPayload;
serverTransId: string;
v2Supported: boolean;
}
>;

Parameters:

  • body: NVPaymentBody The current payment request payload containing payment details.
  • initPaymentResponse: InitPaymentResponse The response object received from the backend initAuth3D request.
  • forceWebChallenge: boolean Indicates whether to enforce forced web challenges (for example, to display challenge flow inside a WebView).
  • isCreatePayment: boolean True if this transaction represents a create payment action rather than auth verification.

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 NVPaymentBody = {
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

getNotificationURL(sessionToken: string, isCreatePayment: boolean)
  • Builds the notification URL for 3DS2 callbacks after challenge completion.
  • Used when forceWebChallenge is enabled.
useInit3DS2Transaction()
  • Initializes a new transaction with the 3DS2 SDK.
  • Returns both transaction and sdk metadata 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: 250x400
    • 02: 390x400
    • 03: 500x600
    • 04: 600x400
    • 05: Full screen
getTimezoneOffsetInHours()
  • Calculates the client timezone offset

Error handling

  • If payServiceContext or _3DSContext is null -> 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

  1. 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.
  1. Creating a Transaction

After initialization, it is generated:

  • transactionID.
  • sdkEphemeralPublicKey.
  • Device metadata.
  • Message version.
  1. 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)
  1. 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

  1. Handling the ACS Challenge

The ACS responds with CRes:

  • May request user interaction (OTP, PIN, biometrics).
  • May be automatic (frictionless).
  1. 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.
  1. 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.

What the hook does

  • If isDirect is true (default) and blockCards rules are active:
    • Calls getCardDetails to retrieve the card brand, card type, etc.
    • Validates card metadata against the configured blockCards rules using isCardBlocked.
    • If a match is found, immediately triggers onError with a descriptive blocked error message and prevents the payment flow from proceeding.
  • Starts the authorization flow via payServiceContext.initAuth3D(paymentSettings, source, nvPaymentMerchantSettings) to obtain initial response and payload.
  • Calls the client payment function (useClientPayment) with the returned payload and response.
  • Sets payServiceContext.setClientPaymentResponse(clientPaymentResponse).
  • Inspects the client payment response and delegates the 3DS outcome handling to handleClientPaymentResponse:
    • For v2 APPROVED (frictionless): returns the response and triggers onSuccess.
    • For v2 REDIRECT:
      • If forceWebChallengeChecked === true → returns webViewParams produced by forceWebChallengePaymentFrame.
      • Else → calls handle3d2Challenge(...) (the 3DS v2 challenge handler).
    • For non-v2 / v1 flows, if threeD contains acsUrl + paRequest + sessionToken → returns 3DS v1 webViewParams (via init3D1PaymentFrame).
  • If webViewParams are produced, the hook calls navigateToWebview(webViewParams) so the host app can present the ACS web page.
  • Otherwise, on any declined or error status, invokes the onError callback.

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

  • isDirect?: boolean (defaults to true) Indicates if the payment is a direct card payment (requiring card blocking validation check).
  • isCreatePayment: boolean true when creating a new payment.
  • paymentSettings: PaymentSettings Payment configuration object passed to initAuth3D.
  • forceWebChallengeChecked: boolean When true, forces the SDK to open a webview for 3DS v2 challenges instead of the normal 3DS v2 challenge.
  • nvPaymentMerchantSettings: NvPaymentMerchantSettings Order data used by initAuth3D.
  • navigateToWebview: (webViewParams: WebViewParams) => void Required callback when a webview must be shown.
  • onSuccess?: (res: any) => void Optional callback invoked when final payment status is APPROVED (after client payment).
  • onError?: (res: any) => void Optional callback invoked on errors or DECLINED statuses.

Key functions

forceWebChallengePaymentFrame(acsUrl, creq, sessionToken, isCreatePayment, toolbarBgColor?)
  • Builds webViewParams for 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 webViewParams for 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 clientPayment result:
    • if the status from a transaction is 'APPROVED' returns frictionless response
    • if the status is 'REDIRECT' returns force web challenge
    • otherwise (DECLINED, CANCELLED, ERROR) returns errors
auth3dErrorHandler(res: InitPaymentResponse)
  • Parses the response object from the payment authentication service.
  • Determines whether a transaction error occurred by checking res.status and res.transactionStatus values against ResponseStatuses.ERROR.
  • Extracts the appropriate numeric error code and descriptive reason string by prioritizing different payload error fields (e.g., gwExtendedErrorCode, gwErrorCode, paymentMethodErrorCode, etc.).
  • Returns an object containing { hasError: boolean; errCode: number; reason: string }.

Integration

import { useAuth3D } from './src/hooks/useAuth3d.tsx';

Error handling

  • If nvPaymentMerchantSettings is null -> nothing happens.
  • If payServiceContext?.initAuth3D(...) returns falsy -> returns nothing.
  • If response.status === 'ERROR' -> onError is called with response
  • If clientPaymentResult is missing or clientPaymentResult.response.status !== 'SUCCESS' or transactionStatus === 'DECLINED' -> onError may be invoked.
  • If required fields for webview construction are missing (acsUrl, creq/notificationUrl) -> return { error: ERROR_CODES.INTERNAL_ERROR }.

Diagram and description

  1. Initialize Auth3D on the Server (initAuth3D)

The first action is calling:

payServiceContext.initAuth3D(paymentSettings, source, nvPaymentMerchantSettings);

This prepares the backend for 3D authentication and returns:

  • response (server result).
  • payload (data needed for clientPayment).
  1. 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.

If isError(clientPaymentResult), this means the card or network blocked the payment.

If this step fails, the flow stops completely.

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

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

If both WebView and Challenge fail, the final result is treated as an authentication error.

  1. Completion (Success / Error)

After challenge execution:

  • If APPROVED → call onSuccess
  • If DECLINED or ERROR → call onError
  • If no response → treat as fatal error

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.

getPaymentRequestPayload

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.

What the function does

At a high level, this function 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), and returns a fully prepared NVPaymentBody object.

  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)
      • Selected payment settings (paymentSettings.paymentOption properties such as savePm and userPaymentOptionId)
      • 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 = {
...nvPaymentMerchantSettingsCopy,
paymentOption,
requestTimeout: nvPaymentMerchantSettingsCopy.timeout ?? 10,
timeout: nvPaymentMerchantSettingsCopy.timeout ?? 10,
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.

Integration

import { getPaymentRequestPayload } from './NuveiFields/getPaymentRequestPayload';

Error handling

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

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.

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

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
};