React Native SDK
Use our React Native SDK to integrate your React Native application with our online payments platform while ensuring secure processing of customer payment data.
Our native SDK helps you communicate with the Client API. It offers:
- Convenient wrappers for API responses.
- Handling of all the details concerning the encryption of payment details.
- Caching of payment product logos and images to offer additional information about payment products.
- User-friendly formatting of payment data, such as card numbers and expiry dates.
- Input validation.
- Checks to determine to which issuer a card number is associated.
Our example app simulates the user interface for the whole payment flow based on the interaction between the app and our platform. Find the source code of the SDK and the example app on GitHub, including installation instructions.
To understand how to use this SDK, look at the following documentation:
- Mobile/Client Integration – Familiarise yourself with various concepts.
- Client API Reference – The SDK wraps the Client API and (among other things) exposes the responses of the web service calls as objects. Understanding the Client API will help you understand these SDK objects as well.
- The SDK on GitHub – The SDK contains a working example application, which can help you understand how to best use it.
- This current document will help you understand the global flow when creating payment pages using the SDK.
Why use the React Native SDK
Our React Native SDK helps you integrate online payments into Android and Swift applications through a single library. It handles many technical details for you, so you do not have to work directly with the Client API for common tasks. The main advantages of using the SDK are:
- Less code to write and maintain – The SDK includes ready-made functionality, which reduces development time and ongoing maintenance.
- Simple and secure authentication – The SDK takes care of authentication and security-related logic, making setup faster and safer.
- More stable integration over time – Most platform changes are handled within the SDK, minimising the impact on your application code.
- Faster setup and easier support – Using the SDK creates more standardised integrations, making onboarding quicker and support more efficient.
SDK integration
To create payments, you first need to integrate the SDK with your project. You can find all the versions of the SDK in our repository. We have prepared the requirements and installation instructions for the SDK below.
Requirements
This SDK is built for React Native applications and has the following peer dependencies:
- react
- react-native
Your backend must be able to create a Client Session using the Server API. The session response provides the values needed to initialise the SDK.
| Requirement | Minimum Version |
|---|---|
| React Native | 0.71 or higher |
| iOS Deployment Target | 15.6 or higher |
| Android minSdkVersion | API 21 (Android 5.0) |
| Java | 17 |
| Kotlin | 2.0 or higher |
Installation
Install this SDK using your preferred node package manager npm, yarn, or pnpm.
npm install onlinepayments-sdk-client-reactnative
You can also use the SDK as a CommonJS module or an ES module.
// ES module
import { init } from 'onlinepayments-sdk-client-reactnative';
// CommonJS
const { init } = require('onlinepayments-sdk-client-reactnative');
Android
When installing the SDK on Android, enable multidex support in your build.gradle file if minSdkVersion is set to 20 or lower.
defaultConfig {
...
multiDexEnabled true
...
}
dependencies {
...
implementation 'androidx.multidex:multidex:2.0.1'
...
}
After you successfully integrate the SDK with your project, you can proceed to integrate it with the entire payment system. The complete payment process consists of these steps:
- Initialisation of the SDK
- Fetching possible payment methods
- Fetching and displaying payment method details
- Validation of the provided data
- Encryption and transfer of payment data
- Finalising transaction
1. Initialise SDK
Firstly, you need to create a Session enabling communication between the Server API and the client. Your app must have its own server, acting as an intermediary between our Client and Server API.
Since the customer initiates the payment in your app, your Client application asks your Server application to create a Session. When a Server application receives a request, it can create a Session via CreateSession from the Server SDK.
Try our API Explorer to send a CreateSession request.
After configuring and connecting your application to the Server API, you receive a response containing information about the created Session. A typical response looks like this:
{
clientSessionId: '47e9dc332ca24273818be2a46072e006',
customerId: '9991-0d93d6a0e18443bd871c89ec6d38a873',
clientApiUrl: 'https://clientapi.com',
assetUrl: 'https://asset.com',
invalidTokens: []
}
Now pass clientSessionId, customerId, clientApiUrl and assetUrl to the Client application. Once the application receives a response from the Server application with the Session information, create a local Session object on your React Native app and initialise the SDK.
import { init } from 'onlinepayments-sdk-client-reactnative';
const sdk = init(
{
clientSessionId: '47e9dc332ca24273818be2a46072e006',
customerId: '9991-0d93d6a0e18443bd871c89ec6d38a873',
clientApiUrl: 'https://clientapi.com',
assetUrl: 'https://asset.com',
},
{
appIdentifier: 'MyShopApp/v1.0.0', // this identifies your application
},
);
Each Session has a fixed 3-hour lifespan. If it expires, you need to create a new Session.
2. Fetch possible payment methods
The next step is to get and display the possible payment options. Use the previously created sdk instance to retrieve the available payment products. Just fetch and display the BasicPaymentProduct and AccountOnFile lists to let your customer select one.
Use our convenient example application as a basis for your own implementation.
import type { PaymentContext } from 'onlinepayments-sdk-client-reactnative';
const paymentContext: PaymentContext = {
countryCode: 'NZ',
amountOfMoney: { amount: 1000, currencyCode: 'AUD' },
isRecurring: false,
};
try {
const { paymentProducts, accountsOnFile } = await sdk.getBasicPaymentProducts(paymentContext);
// Display the payment products and/or accounts on file.
} catch (error) {
// handle error state
}
Remember that each session call can throw errors. Wrap your code into the try/catch block to avoid this.
3. Fetch and display payment method details
For certain payment products, customers can opt for our platform to store their credentials for recurring payments. We refer to the stored data as an account on file (Card On File) or a token. You can reuse this account on file/token for subsequent payments if your customers chose the same payment method.
The list of available payment products that the SDK receives from the Client API also contains the accounts on file for each payment product. Your application can present this list to the user.
Depending on the method the customer chooses, consider cases of different data flows:
If the customer chooses a native form of payment, you need to use the SDK of the payment provider. You will need to handle the response only in the last step to inform the customer of their payment status. Read more about native payments in this dedicated chapter.
For payments with a third-party payment provider, you receive data with the redirection address in the payment properties. Redirect your customers in their browser to the third-party payment portal to continue the payment process. After the successful payment, your app needs to handle the redirection to the Client app. If the specific payment method requires additional data (e.g., Google Pay), you may already have the data within the PaymentProduct.
The standard payment process is a card payment. Once the customer selects the desired payment product or a stored account on file, the SDK can request the information your customers need to provide to finish the payment.
try {
const paymentProduct = await sdk.getPaymentProduct(1, paymentContext);
paymentProduct.getFields(); // array of all the fields the user needs to fill out.
paymentProduct.getRequiredFields(); // array of all the required fields the user needs to fill out.
paymentProduct.getField('cvv'); // returns a single PaymentProductField by id, or undefined if not found
// Display the form with fields to your user.
// Use the field helper functions to format and validate data.
} catch (error) {
// handle error state
}
If your customer selects an account on file, the system will automatically fill in the saved information in the respective input fields. The prefilled data on behalf of the customer is in line with applicable regulations. Depending on the individual use case, your customer may still have to provide some card data (i.e. CVC).
Use our example app for inspiration to create your screen.
4. Validate provided data
After your customer enters their payment information, your application needs to validate the received data. But before validation, you will first need to save the customer's input for the required information fields in a PaymentRequest instance. This class has a tokenize property used to indicate whether the app should store the customer's credentials for recurring payments.
import { PaymentRequest } from 'onlinepayments-sdk-client-reactnative';
// create payment request; if tokenize is not provided its default value is false.
const paymentRequest = new PaymentRequest(paymentProduct);
// to mark the payment request for tokenization:
paymentRequest.setTokenize(true);
// to read the current tokenization setting:
const isTokenized = paymentRequest.getTokenize(); // false by default
Alternatively, adapt the code sample by supplying both the account on file and the corresponding payment product:
import { PaymentRequest } from 'onlinepayments-sdk-client-reactnative';
// providing paymentProduct and accountOnFile via constructor.
const paymentRequest = new PaymentRequest(paymentProduct, accountOnFile);
// or using setAccountOnFile method:
paymentRequest.setAccountOnFile(accountOnFile);
Once you configure a payment request, supply the values for the payment product fields. Use the identifiers of the fields, such as "cardNumber" and "cvv", to set the field values for the payment request:
paymentRequest.getField('cardNumber').setValue('1245 1254 4575 45');
paymentRequest.getField('cvv').setValue('123');
Now you need to validate the received data using the available list of validators. Do that by performing validation on the PaymentRequest and validating both the field values and the payment request.
| Validate Field Values | Validate Payment Request |
|---|---|
|
|
Remember that the data entry interface must be fully transparent and understandable for your customers. So if there are validation errors, you should provide the customer with feedback about them. You receive error information during the validation of a payment field or the validation of the payment request, so you can use it to display appropriate error messages. Each validation error has a reference to the corresponding faulty field.
5. Encrypt and transfer payment data
After collecting all the data and validating the fields, create a PaymentRequest instance.
import { PaymentRequest } from 'onlinepayments-sdk-client-reactnative';
// paymentProduct is retrieved in the previous step.
const paymentRequest = new PaymentRequest(paymentProduct);
// set values directly on the corresponding PaymentRequestField instances.
paymentRequest.getField('cardNumber').setValue('1245 1254 4575 45');
paymentRequest.getField('cvv').setValue('123');
paymentRequest.getField('expiryDate').setValue('12/2027');
// OR with a helper method
paymentRequest.setValue('cardNumber', '1245 1254 4575 45');
paymentRequest.setValue('cvv', '123');
paymentRequest.setValue('expiryDate', '12/2027');
The expiry date format for Credit Card payment products depends on your merchant account settings, so it can be either MM/yyyy or MM/yy. The exact format is returned from the API, and the field validation and payment request validation will ensure that it is correct.
Finally, forward the encrypted PaymentRequest instance as follows:
const validationResult = paymentRequest.validate();
if (!validationResult.isValid) {
// use validationResult.errors to display errors to the user.
} else {
try {
const encryptedRequest = await sdk.encryptPaymentRequest(paymentRequest);
/*
* encryptedRequest.encryptedCustomerInput can safely be sent to your server.
* encryptedRequest.encodedClientMetaInfo contains encoded metadata.
*/
} catch (err) {
// payment request can not be encrypted, handle error state
}
}
6. Finalise transaction
After encrypting the customer data, send the encrypted object to your server and use it to make a CreatePayment request with the Server SDK. Then, provide the corresponding value from the encrypted object in the encryptedCustomerInput field to finalise the payment.
The response of the CreatePayment request may require additional actions from the Client, specified in the MerchantAction object. In most cases, this involves redirecting the customer to an external party (i.e. for a 3-D Secure check). Once your customers complete this check, our platform processes the actual transaction. Read the Server SDK documentation for more information.
Finally, you have to pass the information back to your Client application to display the transaction result to your customers.
Find a full overview of the payment flow in the Mobile/Client Integration guide.
SDK objects
The React Native SDK includes several objects. Choose the object of your interest from the list below to read more about it:
- OnlinePaymentSdk
- PaymentContext
- BasicPaymentProduct
- AccountOnFile
- PaymentProduct
- PaymentProductField
- PaymentRequest
- PaymentRequestField
- CreditCardTokenRequest
- Masking
OnlinePaymentSdk
An instance of OnlinePaymentSdk is required for all interactions with the SDK. The following code snippet shows how to initialise a OnlinePaymentSdk. You obtain session details by performing a Create Client Session call using the Server API. You can also include an optional SdkConfiguration that includes an appIdentifier property, serving as an identifier for your app.
import { init } from 'onlinepayments-sdk-client-reactnative';
const sdk = init(
{
clientSessionId: '47e9dc332ca24273818be2a46072e006',
customerId: '9991-0d93d6a0e18443bd871c89ec6d38a873',
clientApiUrl: 'https://clientapi.com',
assetUrl: 'https://asset.com',
},
{
appIdentifier: 'MyShopApp/v1.0.0', // this identifies your application
},
);
All methods the OnlinePaymentSdk offers are wrappers around the Client API. They create the request and convert the response to TypeScript objects that may contain convenience functions.
PaymentContext
PaymentContext is an object that contains the context/settings of the upcoming payment. Some methods of the OnlinePaymentSdk instance require it as an argument. This object can contain the following details:
export interface PaymentContext {
countryCode: string; // ISO 3166-1 alpha-2 country code
amountOfMoney: {
amount?: number; // Total amount in the smallest denominator of the currency
currencyCode: string; // ISO 4217 currency code
};
isRecurring?: boolean; // Set `true` when payment is recurring. Default false.
}
You can also import this interface as a type when using TypeScript:
import type { PaymentContext } from 'onlinepayments-sdk-client-reactnative';
const paymentContext: PaymentContext = {
// ...
};
BasicPaymentProduct
The SDK offers two types of objects to represent information about payment products:
- BasicPaymentProduct
- PaymentProduct
The instances of BasicPaymentProduct contain only the information required to display a simple list of payment products for the customer to choose from.
The object PaymentProduct contains additional information on each payment product. An example would be the specific form fields that the customer must fill out. You typically use this object when creating a form that asks for a customer's payment details. Read the PaymentProduct section for more info.
Below is an example of how to get display names and assets for the Visa product.
const basicPaymentProduct = basicPaymentProducts.paymentProducts.find((p) => p.id === 1);
basicPaymentProduct.id; // 1
basicPaymentProduct.label; // VISA
basicPaymentProduct.logo; // https://www.domain.com/path/to/visa/logo.gif
// this is valid only if there is a saved account on file
basicPaymentProduct.accountsOnFile[0].label; // optional display label for the account on file
basicPaymentProduct.accountsOnFile[0].getValue('cardNumber'); // masked card number, e.g. 4242 **** **** 4242
AccountOnFile
An instance of AccountOnFile represents information about a stored card product for the current customer. You must provide the available AccountOnFile IDs for the current payment in the request body of the Server API's CreateSession call if you want to let a customer use a previously tokenised payment method.
If the customer wants to use an existing AccountOnFile for a payment, you should add the selected AccountOnFile to the PaymentRequest. The code snippet below shows how to retrieve the display data for an account on file. You can show this label and the logo of the corresponding payment product to the customer.
// This contains all unique saved payment accounts from across all available payment products
const aof = paymentProduct.accountsOnFile[0];
// get display value of a field
aof.getValue('cardNumber'); // returns masked card number
aof.getValue('cardholderName'); // returns the cardholder name, if set
aof.getValue('expiryDate'); // returns the expiry date, if set
PaymentProduct
BasicPaymentProduct only contains the basic payment product information that customers need to distinguish them. However, when they select a payment product or an account on file, they must provide additional information. The system needs mandatory info like the credit card number and expiry date to process the payment. The instances of BasicPaymentProduct do not contain any information about these fields.
So when you need detailed payment information, call the PaymentProduct object. This object contains several instances of PaymentProductField. Each PaymentProductField carries a piece of information required to process the payment (e.g. bank account number, credit card number).
Retrieve the instance of the PaymentProduct as shown in the code snippet below.
try {
const paymentProduct = await sdk.getPaymentProduct(1, paymentContext);
paymentProduct.getField('expiryDate'); // returns a single PaymentProductField by id, or undefined if not found
paymentProduct.getRequiredFields(); // array of all the required fields the user needs to fill out.
paymentProduct.getFields(); // array of all fields available in the payment product.
} catch (error) {
// handle error state
}
PaymentProductField
PaymentProductField instances represent individual payment product fields (e.g. bank account number, credit card number). Each field has the following:
- An identifier
- A type
- A definition of restrictions that apply to the field's value
- Built-in validation for input values
- Information on how the field should be displayed to the customer
In the code example below, the system retrieves the field with the identifier "expiryDate" from a payment product. The system then checks the data restrictions to identify if it is a required field or an optional field. Finally, the system inspects whether the values the customer provided should be visible or hidden in the user interface.
const field = paymentProduct.getField('expiryDate');
field.isRequired(); // true if value is required.
field.shouldObfuscate(); // true if needs to be obfuscated.
field.applyMask('0628'); // returns 06/28
field.removeMask('06/28'); // returns 0628
field.validate('06/28'); // returns a list of validation errors (empty list if the value is valid)
- paymentProduct.getField(id) returns undefined if no field with the given id exists on the payment product. Always check for undefined before using the result.
- paymentRequest.getField(id) throws an InvalidArgumentError if the id is not found in the payment product. Only request fields that are defined in the selected PaymentProduct.
PaymentRequest
Once the customer selects a payment product and the system retrieves an instance of PaymentProduct, a payment request can be constructed. You must use the PaymentRequest class as a container for all the values the customer provides.
import { PaymentRequest } from 'onlinepayments-sdk-client-reactnative';
// paymentProduct is an instance of the PaymentProduct class (not BasicPaymentProduct).
const paymentRequest = new PaymentRequest(paymentProduct);
When the payment product is instantiated, methods like masking and unmasking values, validation, and encryption will work. You can set values through the instances of the PaymentRequestField class.
Tokenise payment request
A PaymentRequest has a property tokenize. You can use it to indicate whether a payment request should be stored as an account on file for future payments. You can control tokenisation via setTokenize(boolean) and read back with getTokenize(). The code snippet below shows how to construct a payment request when you want to store it as an account on file.
import { PaymentRequest } from 'onlinepayments-sdk-client-reactnative';
// create payment request; if tokenize is not provided its default value is false.
const paymentRequest = new PaymentRequest(paymentProduct);
// to mark the payment request for tokenization:
paymentRequest.setTokenize(true);
// to read the current tokenization setting:
const isTokenized = paymentRequest.getTokenize(); // false by default
By default, tokenize is set to false.
If the customer selects an account on file, you must supply both the account on file and the corresponding payment product when constructing the payment request. You can retrieve the instances of AccountOnFile from instances of BasicPaymentProduct and PaymentProduct.
import { PaymentRequest } from 'onlinepayments-sdk-client-reactnative';
// providing paymentProduct and accountOnFile via constructor.
const paymentRequest = new PaymentRequest(paymentProduct, accountOnFile);
// or using setAccountOnFile method:
paymentRequest.setAccountOnFile(accountOnFile);
Set field values for the payment request
Once you create a payment request, you can supply the values for the payment request fields as follows:
paymentRequest.getField('cardNumber').setValue('1245 1254 4575 45');
paymentRequest.getField('cvv').setValue('123');
The identifiers of the fields, such as "cardNumber" and "cvv", are used to set the field values using the payment request. In general, you can retrieve all available fields from the PaymentProduct instance.
Validate field values
Once the values are set, you can validate them. The system will validate the value using predefined data restrictions set on each field. That ensures only valid values are encrypted for the payment request.
const field = paymentRequest.getField('cardNumber');
field.setValue('1245 1254 4575 45');
if (field.validate().isValid) {
// the value is in the correct format.
}
// or use chained methods
paymentRequest.getField('cvv').setValue('123').validate();
Validate payment request
Once the server receives all the values, it can validate the payment request. The PaymentRequest calls validation on each of its PaymentRequestField instances, which use their internal DataRestrictions and validation logic to verify that the field values meet all requirements. The server will also provide a list of errors that occurred during validation.
If there are no errors, you can encrypt the payment request and send it to our platform via your server. If there are validation errors, you should provide the customer with feedback on these errors. Each ValidationErrorMessage contains the error message and error type for each field to help display appropriate feedback.
const validationResult = paymentRequest.validate();
if (!validationResult.isValid) {
console.log('the following fields are invalid', validationResult.errors);
}
The validations are defined in the PaymentProductField. The server returns them as a ValidationErrorMessage.
paymentRequest.setValue('cardNumber', '456735000042797');
paymentRequest.validate();
/*
* {
* errorMessage: "Card number is in invalid format.",
* paymentProductFieldId: "cardNumber",
* type: "luhn"
* }
*/
AccountOnFile with READ_ONLY fields
When no AccountOnFile is selected for the specific PaymentRequest, all payment request fields (such as cardNumber) are writable and can be set normally. When you set an AccountOnFile on the PaymentRequest, the SDK enforces the following behaviour:
- All previously set unwritable field values are cleared from the PaymentRequest.
- You cannot manually set read-only fields anymore. Calling setter will throw InvalidArgumentError.
- Calling paymentRequest.getField(readOnlyFieldId).getValue() will return undefined.
- You can use the AccountOnFile instance to retrieve a value.
This ensures only values that can be changed are submitted.
Encrypt payment request
The PaymentRequest is ready for encryption only after the following conditions have been met:
- The PaymentProduct is set
- The PaymentProductField values have been provided and validated
- The selected AccountOnFile or tokenize properties have been set (optional)
Then, encrypt the PaymentRequest by calling the sdk.encryptPaymentRequest(request). When the sdk.encryptPaymentRequest runs, the system will first validate the PaymentRequest for potential issues with data. That ensures no time is spent encrypting invalid data that our platform won’t be able to process in the Server API.
Although you can use your own encryption algorithms to encrypt a payment request, we advise you to use the encryption functionality offered by the SDK.
PaymentRequestField
Payment request fields are represented by instances of PaymentRequestField. Each field provides methods for the following:
- Setting and retrieving values
- Getting the field labels
- Obtaining masked values for display
- Validating user input against field restrictions
const field = paymentRequest.getField('cardNumber');
field.setValue('4242 4242 4242 4242'); // sets the value (mask is automatically removed)
field.getValue(); // returns the raw unmasked value
field.getMaskedValue(); // returns the value with mask applied
field.getId(); // returns the field identifier
field.getLabel(); // returns the display label
field.getPlaceholder(); // returns the placeholder text, if defined
field.getType(); // returns the field type (e.g. 'string', 'numericstring', 'expirydate')
field.isRequired(); // true if the field is required
field.shouldObfuscate(); // true if the value should be hidden (e.g. CVV)
field.clearValue(); // clears the current value
field.validate(); // returns ValidationResult with isValid and errors
CreditCardTokenRequest
This class is used to create a CardTokenization request. It contains the essential credit card fields: card number, cardholder name, expiry date, cvv, and payment product id.
import { CreditCardTokenRequest } from 'onlinepayments-sdk-client-reactnative';
const tokenRequest = new CreditCardTokenRequest();
tokenRequest.setCardholderName('test');
tokenRequest.setExpiryDate('122026');
tokenRequest.setCardNumber('12451254457545');
tokenRequest.setSecurityCode('123');
tokenRequest.setProductPaymentId(1);
Note that no validation rules are applied for values set in the token request since it is detached from the instance of the PaymentProduct. You should use this class as a helper for encrypting data required to create a token using the Server SDK. However, if invalid data is provided, the CreateToken request will fail.
You should provide raw values, not masked ones (e.g. "1226" instead of "12/26"). You can still use an instance of a PaymentProduct to format and validate values.
Encrypt token request
try {
const encryptedRequest = await sdk.encryptTokenRequest(tokenRequest);
/*
* encryptedRequest is the encrypted token request which can safely be sent to your server.
* It consists of two parts: encryptedCustomerInput and encodedClientMetaInfo.
*/
} catch (err) {
// token request can not be encrypted, handle error state
}
Masking
The SDK offers a masking functionality on the PaymentProductField class. It allows you to format field values and apply and unapply masks on a string.
const field = paymentProduct.getField('cardNumber');
// applying mask on a field.
field.applyMask('1234123412341234');
// removing mask from a field.
field.removeMask('1234 1234 1234 1234');
// getting masked value from PaymentRequestField
const maskedValue = paymentRequest.getField('cardNumber').getMaskedValue();
Additional features
The SDK has a lot more to offer. Have a look at the following features, as they will help you build the perfect solution.
Encrypt sensitive data
One of the biggest assets of the SDK is its encryption tool. It offers great security when transferring sensitive data (i.e. card numbers, expiry date, CVC code). An entire encryption/transfer flow looks like this:
You can encrypt all the provided payment information with sdk.encryptPaymentRequest. When sending the request, your application forwards the encrypted result to your e-commerce server, which sends it to the Server API.
Do not store the encrypted data. Transfer it via the Server API directly to our platform right after the encryption.
import { PaymentRequest } from 'onlinepayments-sdk-client-reactnative';
const paymentRequest = new PaymentRequest(paymentProduct);
// get field value from your input component
paymentRequest.getField('cardholderName').setValue('John Doe');
// set other fields...
const validationResult = paymentRequest.validate();
if (!validationResult.isValid) {
// display errors to the user.
} else {
try {
const encryptedRequest = await sdk.encryptPaymentRequest(paymentRequest);
// encryptedRequest.encryptedCustomerInput can be used to send the encrypted input data
// to the Server SDK to create a payment
} catch (error) {
console.error(error);
}
}
The SDK does all the heavy lifting, including:
- Requesting a public key from the Client API
- Performing the encryption
- BASE-64 encoding the result into one string
You only need to ensure that the PaymentRequest object contains all the information entered by the user. You need to send the encrypted payload to your e-commerce server, where it can be forwarded to the Server API.
Validate data
Each PaymentProductField has appropriate DataRestrictions. The DataRestrictions object contains information about all mandatory fields and validates whether the values entered meet the correctness condition. Together with a list of abstract validators, it also has a property isRequired. This property informs whether given restrictions are required or not.
You can validate a particular input just as easily as through the PaymentRequest validation. In case of any errors, the Errors field will display a list of errors.
It contains the following validators:
- Expiration Date: Checks whether the entered card expiration date is not earlier than the current date and whether it is not beyond the range of twenty-five years ahead.
- Email Address: Checks the format of the email address the customer has provided.
- Fixed List: Checks whether the entered value is on the list of possibilities.
- IBAN: Validates the IBAN the customer has provided.
- Length: Checks if the entered value is longer than the minimum value and if it is not longer than the maximum value.
- Luhn: The checksum formula used to validate a variety of identification numbers, such as credit card numbers.
- Range: Checks if the value is greater than the minimum value and if it is not greater than the maximum value.
- Regex: Validates that the entered value matches the regular expression.
- TermsAndConditions: The boolean validator for the terms and conditions accept field.
Each validator returns an appropriate error, indicating a field that does not meet the conditions, and a message you can easily translate.
Apply IIN check
The first six digits of a payment card number are known as the Issuer Identification Number (IIN). You can check the payment product and network associated with the entered IIN as soon as the customer enters the first six digits of their card number. Use the sdk.getIinDetails call to retrieve that information and verify if you can accept that card type.
You can use an instance of OnlinePaymentSdk to check which payment product is associated with an IIN. You do that with the session.getIinDetails function. The result of this check is an instance of IinDetailsResponse. This class has the following:
- A property status indicating the result of the check.
- Property paymentProductId indicating which payment product is associated with the IIN.
You can use the returned paymentProductId to fetch the PaymentProduct and show the appropriate logo to the customer.
The IinDetailsResponse has a status property represented through the IinStatus enum. The IinStatus enum values are:
- SUPPORTED indicates that the IIN is associated with a payment product supported by our platform.
- UNKNOWN indicates that the IIN is not recognised.
- NOT_ENOUGH_DIGITS indicates that fewer than six digits were provided, and that it is impossible to perform the IIN check.
- EXISTING_BUT_NOT_ALLOWED indicates that the provided IIN is recognised, but that the corresponding product is not allowed for the current payment or merchant.
- UNSUPPORTED indicates that the IIN is not supported.
import {
IinDetailStatus,
type PaymentContextWithAmount,
} from 'onlinepayments-sdk-client-reactnative';
const partialCreditCardNumber = '456735';
const paymentContext: PaymentContextWithAmount = {
countryCode: 'NZ',
amountOfMoney: { amount: 1000, currencyCode: 'AUD' },
isRecurring: false,
};
try {
const response = await sdk.getIinDetails(partialCreditCardNumber, paymentContext);
// response is an instance of `IinDetailsResponse`
const isSupported = response.status === IinDetailStatus.SUPPORTED;
// the list of co-brands, if available:
const coBrands = response.coBrands;
} catch (error) {
// handle error state
}
Some cards are co-branded and can be processed as either a local card (with a local brand) or an international card (with an international brand). If you are not set up to process these local cards, the API call will not return that card type in its response.
Testing
This library contains unit and integration tests written with Vitest. Vitest starts in watch mode by default in the development environment and run mode in the CI environment (when process.env.CI is present).
Unit tests
Testing input and output of small isolated functions (units) can be found in ./__tests__/unit. You do not need to expose any environment variables to execute unit tests. You can run them by using:
yarn test:unit
Tests d'intégration
You can find integration tests in ./__tests__/integration. These tests make real API calls to the Worldline sandbox and require a .env file in the project root with valid credentials. See .env.example for the required variables. You can run them by using:
yarn test:integration
Use the following to run all tests (unit and integration) at once:
yarn test