React Native integration guide
To integrate the Payment SDK into your React Native application and make a payment, 4 steps are required :
- Add the the payment SDK to your application
- Initialize the SDK
- Make a payment
- Check the transaction status
On this page you can also find:
- See our integration example
- Customize the SDK
- Enable the card scan feature
- Enable NFC feature
- Limitations
- Using our sdk in an Expo React Native application
In order to optimize the efficiency of our support, our SDK can send Sentry messages to our servers when an unusual situation or problem occurs. In this case, no sensitive data is transferred nor any data from your application.
See our integration example
You'll find sample code for integrating our SDK into a React Native application in the Github repository.
Add the the payment SDK to your application
To add the payment sdk to your native react application :
- Add our [Native Module] (https://www.npmjs.com/package/@lyracom/react-native-sdk-payment-module ) dependency to your package.json file.
{
"dependencies": {
"@lyracom/react-native-sdk-payment-module": "^1.0.0",
},
}
- Add a reference to pod-install in the development dependencies:
"devDependencies": {
"pod-install": "^0.1.0"
},
- Edit the Podfile in your iOS folder:
Add
use_frameworks!
following the "require_relative" instructions.Disable Flipper: comment out the line
:flipper_configuration => FlipperConfiguration.enabled
.Mettez à false les parametres suivantes: ,
:hermes_enabled => false
, et:fabric_enabled => false
.
Run
yarn
.Run
yarn pod-install --quiet
.
Initialize the SDK
As mentioned in the chapter on how the solution works , it's necessary to initialize the SDK.
Pour cela, il suffit d'appeler la méthode initialize
avec les paramètres suivants :
PARAMETER | FORMAT | Description |
---|---|---|
publicKey | string | Your public key (available in the |
options | Object | Object that lets you configure the SDK's behavior. |
Example of a call:
// Initialize Payment SDK initialize( config.publicKey, { cardScanningEnabled: true, apiServerName: "MY_API_SERVER_NAME", }, async (result) => { // onError Alert.alert(result.error.errorMessage); } );
Possible keys for the options object are :
Keys | Value format | Description | required |
---|---|---|---|
apiServerName | string | REST API server name (available in the | required |
cardScanningEnabled | boolean | Enables/Disables the map scan feature, see Enable card scan feature. | Optional |
It should also be noted that the SDK does not allow multiple processes in parallel. During the processing of the first call, the other calls will be ignored.
Make a payment
Making a payment is a 2-step process: initializing the display of the payment form, and processing the payment itself.
Initialize the display of the payment form
When the user decides to pay, you must initialize the display of the payment form.
Pour cela, vous devez appeler votre serveur marchand, pour y vérifier les achats de l'utilisateur, puis générer un identifiant de formulaire (appelé formToken
) en appelant le Web Service Charge/CreatePayment (toujours depuis votre serveur marchand). Dans cette requête, vous devez passer un paramètre formTokenVersion
qui correspond au résultat de la méthode getFormTokenVersion
du SDK. La réponse du Web Service ou cet identifiant de formulaire doit ensuite être renvoyé à votre application.
const getProcessPaymentContext = async () => { var formTokenVersion = getFormTokenVersion(); return fetch(config.merchantServerUrl + "/createPayment", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: paymentParams, }) .then((result) => result.json()) .then((json) => json.answer.formToken) .catch((error) => { console.error(error); }); };
- The step of validating the cart is crucial. Before you transmit it to us, you must check on your servers that the amount corresponds to the one in the cart.
- Calling the web service from the mobile application is amounts to making your call keys available to it (and to potential hackers), which is contrary to the security rules.
Displaying the payment screen
Once the formToken is received in the mobile application, you must transmit it to our payment SDK by calling the process
method with the following parameters:
PARAMETER | FORMAT | Description |
---|---|---|
formToken | string | The formToken, extracted from the previously called createPayment response. |
options | Object | Object that allows you to customize the payment form. |
onSuccess | (result: any) => void, | Callback function called if the payment was successful. |
onError | (result: any) => void, | Callback function called if the payment failed or could not be initiated. This can occur if the payment was declined or if a functional or technical error occurred during the payment. For more information see: Error handling. |
The SDK then checks the formToken consistency and displays the available payment methods.
Example of a call:
process( formToken!, options, async (result) => { // onSuccess // Verify the payment using your server verifyPayment(result.response) .then(() => { Alert.alert(`Payment success`); }) .catch(() => { Alert.alert(`Payment verification fail`); }); }, async (result) => { // onError Alert.alert(result.error.errorMessage); } );
Object descriptionLyraResponse
L'objet LyraResponse
est retourné dans les deux cas : onSuccess
et onError
. C'est un objet de type JSON Object. En cas de succès, il est nécessaire de vérifier son intégrité avant d'afficher le résultat du paiement.
In case the transaction was initiated on the server side, it will be possible to simply retrieve the payment details.
Example: .
{ "kr-hash":"80f5188e757c1828e8d4ccab87467eb50c4299e4057fa03b3f3185342f6d509c", "kr-hash-algorithm":"sha256_hmac", "kr-answer-type":"V4\/Payment", "kr-answer": "{ "shopId":"65512466", "orderCycle":"CLOSED", "orderStatus":"PAID", "serverDate":"2019-03-01T10:54:45+00:00", "orderDetails":{ "orderTotalAmount":1100, "orderEffectiveAmount":1100, "orderCurrency":"EUR", "mode":"TEST", "orderId":null, "_type":"V4\/OrderDetails" }, "customer":{ "billingDetails":{ "address":null, "category":null, "cellPhoneNumber":null, ... }, "email":null, "reference":null, "shippingDetails":{ "address":null, "address2":null, "category":null, ... }, "extraDetails":{ "browserAccept":null, "fingerPrintId":null, "ipAddress":"77.136.84.251", "browserUserAgent":"{\"deviceName\":\"Xiaomi Mi MIX 2S\",\"os\":\"Android\",\"osVersion\":\"[9]\",\"sdkVersion\":28,\"isMobile\":true}", "_type":"V4\/Customer\/ExtraDetails" }, "shoppingCart":{ "insuranceAmount":null, "shippingAmount":null, "taxAmount":null, "cartItemInfo":null, "_type":"V4\/Customer\/ShoppingCart" }, "_type":"V4\/Customer\/Customer" }, "transactions":[ { "shopId":"65512466", "uuid":"64d704a9bb664898954c3ef537982f99", "amount":1100, "currency":"EUR", "paymentMethodType":"CARD", "status":"PAID", "detailedStatus":"AUTHORISED", "operationType":"DEBIT", "creationDate":"2019-03-01T10:54:44+00:00", ... } ], "_type":"V4\/Payment" }" }
The response contains the same elements as the ones sent in the IPN:
PARAMETER | Description |
---|---|
kr-hash | Hash of the JSON object stored in kr-answer. It allows to verify the authenticity of the response. |
kr-hash-algorithm | Algorithm used to calculate the hash. |
kr-hash-key | Key used for signing kr-answer. |
kr-answer-type | Type the JSON object stored in kr-answer. |
kr-answer | Object containing complete transaction objects encoded in JSON. |
L'objet kr-answer
contient les éléments décrits ici.
In some cases, it may be that the transaction could not be initiated on the server side. It will be possible to find the error returned by the API in the json (you can find the format here: Error codes ).
Check the transaction status
Once the payment has been finalized, regardless of whether was accepted or rejected, you will be notified in two 2 ways:
- Via a call (IPN) to your merchant server, if the Merchant is registered on our payment gateway.
- by calling callbacks
onSuccess
oronError
on mobile application side.
It is necessary to check the integrity of the message (go here for more details), and to launch business processing on the server side (when the IPN is received).
Nos exemples de code fournissent un exemple de contrôle d'intégrité du message via votre serveur marchand. Il s'agit du endPoint verifyResult
appelé dans la méthode verifyResult
de l'application.
Here's an example code based on the merchant server provided.
const verifyPayment = async (paymentResult: any) => { return fetch(config.merchantServerUrl + "/verifyResult", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: paymentResult, }); };
Customize the SDK
Theme
It is possible to customize the SDK so that the views generated via the SDK (payment form) are displayed with the same colors and font as those used in your application.
You can define:
- One main color,
- A secondary color,
- the font to be used for all the texts that appear in the SDK.
The main color allows to modify:
- the header background color,
- The background color of the “Pay” button,
- the color of the word for closing the CVV tooltip pop-up,
- the color of the word for closing the brand selection pop-up,
- the color for highlighting the field and of its label when it is being edited,
- the color of the text in the payment in progress message,
- the color of the spinner in the current payment message.
The secondary color allows to change:
- the color of the arrow image for going back in the SDK header,
- the color of the texts in the SDK header,
- the text color of the “Pay” button.
For the customization to be taken into account, the following modifications must be made in the native part of the project: iOS and Android :
iOS
Add a PaymentSdkTheme.plist
file to your project's iOS folder and specify the colors to use in hexadecimal in this file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PaymentSDKColor</key>
<dict>
<key>PaymentSDK_PrimaryColor</key>
<string>#293C7A</string>
<key>PaymentSDK_SecondaryColor</key>
<string>#FFFFFF</string>
</dict>
</dict>
</plist>
It is also possible to change the font with the key PaymentSDKFont
.
Puis, ajouter le fichier PaymentSdkTheme.plist et celui de la police à votre projet iOS (depuis Xcode ouvrir le fichier .xcworkspace)
Android
Define the colors in your colors.xml file:
<color name="payment_sdk_PrimaryColor">#293C7A</color>
<color name="payment_sdk_SecondaryColor">#FFFFFF</color>
Pour personnaliser la police vous devez juste surcharger le style nécessaire dans le fichier styles.xml :
<style name="PaymentSDK_Theme">
<item name="android:fontFamily"></i>casual</item></style>
Texts
It is also possible to customize the text of the payment button. To do so, specify the optional "options" parameter when calling the process.
PAY button
- The text of the PAY button can be customized.
Specify the key customPayButtonLabel
.
Header
- If the text is forced and there is noorderId, it will replace the default text which is "Payment" or "Card Registration".
- On the other hand, if anorderIdest précisé alors, on continuera à afficher "CommandeOrderId".
Specify the key customHeaderLabel
.
Payment popup
- The popup text that opens when clicked PAY button can also be customized.
Specify the key customPopupLabel
.
Enable the card scan feature
The card scan feature allows a user to avoid entering their card information manually and, instead, use the camera on their mobile device to scan it and fill out the payment form automatically.
Pour activer cette fonctionnalité, vous devez lors de l'initialisation du SDK, envoyez true comme valeur à la clé cardScanningEnabled
dans le dictionnaire des options de configuration (Voir Initialiser le SDK).
Dans le fichier Info.plist
de votre application (dans le dossier iOS), ajoutez la clé NSCameraUsageDescription
et décrivez la raison de l'utilisation de la caméra.
Enable NFC feature
NFC feature allows a user not to enter their card information manually and, instead, to use NFC to scan the card and fill out the payment form automatically.
Pour activer cette fonctionnalité, vous devez lors de l'initialisation du SDK, envoyer true comme valeur pour la clé nfcEnabled
dans les options de configuration (Voir Initialiser le SDK).
Ajouter la permission suivante dans le fichier AndroidManifest.xml
de votre application :
<uses-permission android:name="android.permission.NFC" />
Limitations
The following SDK functions are not available in the Native Module:
- The method
cancelProcess()
. - Card scanning on Android devices.
Using our sdk in an Expo React Native application
If you have an Expo project (managed workflow) to add the payment sdk to your application:
- Add our [Native Module] (https://www.npmjs.com/package/@lyracom/react-native-sdk-payment-module ) dependency to your package.json file.
{
"dependencies": {
"@lyracom/react-native-sdk-payment-module": "^1.0.0",
},
}
- Add the following dependencies to your package.json file:
{
"dependencies": {
"expo-build-properties": "~0.4.1",
"expo-dev-client": "^2.0.1",
},
}
- In your app.json file add :
{
"expo": {
"plugins": [
[
"expo-build-properties",
{
"ios": {
"useFrameworks": "dynamic"
}
}
]
]
}}
- Run
yarn
.
- Run
eas build --profile development --platform ios
. - Run
eas build --profile development --platform android
. - Install the generated application on the corresponding device.
- Run
expo start --dev-client
.
You'll find sample code for integrating our SDK into a Expo React Native application in the Github repository.