iOS Integration Guide
To integrate the payment SDK into your application and make a payment, follow these 4 steps:
- 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:
- View our integration examples
- Customize the SDK
- Cancel a payment in progress
- Enable the card scan feature
To optimize analysis when needed, our SDK can send Sentry messages to our servers when an unusual situation or problem occurs. In this case, no sensitive data or data from your application is transferred.
View our integration examples
You will find many examples of our SDK's integration codes in different languages in the Github repository.
Add the the payment SDK to your application
There are different ways of integrating the SDK into an Xcode project:
Via CocoaPods
To integrate the SDK into your Xcode project using CocoaPods:
- Indicate the SDK in your Podfile:
target 'MyApp' do use_frameworks! pod 'LyraPaymentSDK' end
- Then install the SDK with
pod update
.
Via Carthage
To integrate the SDK into your Xcode project using Carthage, specify in your
Cartfile
the dependencies necessary for our SDK:# Payment SDK Mobile & dependencies binary "https://raw.githubusercontent.com/lyra/Material/1.0.5/LyraMaterial.json" == 1.0.5 binary "https://raw.githubusercontent.com/lyra/Motion/4.0.1/LyraMotion.json" == 4.0.1 github "SnapKit/SnapKit" == 5.6.0 github "getsentry/sentry-cocoa" "8.13.0" binary "https://raw.githubusercontent.com/lyra/ios-sdk/2.6.7/LyraPaymentSDK.json>" == 2.6.7 binary "https://raw.githubusercontent.com/lyra/sentry-client-cocoa/4.0.0/sentry_client_cocoa.json" == 4.0.0 binary "https://raw.githubusercontent.com/lyra/ios-cards-camera-recognizer/2.0.1/LyraCardsRecognizer.json" == 2.0.1 # Your dependencies ...
Dans le Cartfile
assurez-vous de remplacer le numéro de la version de LyraPaymentSDK par le numéro de la dernière version publiée sur notre repository GitHub
Ajoutez le LyraPaymentSDK.xcframework
à votre projet iOS ainsi que les autres dépendances spécifiées dans votre Cartfile
.
Nous vous recommandons de mettre à jour régulièrement le SDK de paiement, afin de garantir une sécurité optimale de vos paiements.
Pour être informé des nouvelles versions du SDK, vous pouvez consulter régulièrement notre repository GitHub.
Initialize the SDK
Comme indiqué dans le chapitre sur le fonctionnement de la solution , il est nécessaire d'effectuer l'initialisation du SDK au lancement de votre application, typiquement dans la méthode didFinishLaunchingWithOptions de votre AppDelegate.
Pour cela, il suffit d'appeler la méthode ,initialize
, avec les paramètres suivants et après avoir importé le framework import LyraPaymentSDK
, :
PARAMETER | FORMAT | Description |
---|---|---|
publicKey | String | Your public key (available in the |
options | [String: Any] | Dictionary that allows you to configure the behavior of the SDK. |
{: .lita-excluded-col1 .lita-excluded-col2 } Exemple d'appel :
//Configure SDK options var configurationOptions = [String : Any]() configurationOptions[LyraInitOptions.apiServerName] = apiServerName //Initialize Payment SDK do { try Lyra.initialize(publicKey, configurationOptions) } catch { }
//Configure SDK options NSMutableDictionary *configurationOptions = [[NSMutableDictionary alloc] init]; [configurationOptions setValue:apiServerName forKey:LyraInitOptions.apiServerName]; //Initialize Payment SDK [Lyra initialize:publicKey :configurationOptions error:&error];
The possible keys in this dictionary are:
Keys | Value format | Description | required |
---|---|---|---|
apiServerName | String | REST API server name (available in the | required |
cardScanningEnabled | Bool | 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 (no callback, no exception).
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 mobile.
Here is a code sample based on the available iOS code examples and the merchant server.
// 1. Init server comunication class for get createPayment context let serverCommunication = ServerCommunication() // 2. Execute getProcessPaymentContext for get the formToken (required param in SDK process method) serverCommunication.getPaymentContext { (getContextSuccess, formToken, error) in ... let objectResponse = json as? [String: Any] let serverResponse = objectResponse["answer"] as? [String: Any] let formToken = serverReponse["formToken"] as? String }
// 1. Init server comunication class for get createPayment context ServerCommunication *serverComunication = [[ServerCommunication alloc] init]; // 2. Execute getProcessPaymentContext for get the formToken (required param in SDK process method) [_serverComunication getProcessPaymentContext:^(BOOL getContextSuccess, NSString *formToken, NSError* error) { ... NSDictionary *objectResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError]; NSDictionary *serverResponse = [objectResponse objectForKey:@"answer"]; NSString* formToken = (NSString*)[serverResponse objectForKey:@"formToken"]; }];
- 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 received in the mobile app, you need to send it to our payment SDK by calling the process
method with the following parameters and after importing the framework import LyraPaymentSDK
, :
PARAMETER | FORMAT | Description |
---|---|---|
contextViewController | UIViewController | Corresponds to the ViewController of the client application from which the payment process will be launched. |
formToken | String | The formToken, extracted from the previously called createPayment response. |
onSuccess | LyraHandlerOnSuccess | Callback function called if the payment was successful. |
onError | LyraHandlerOnError | 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:
Lyra.process(self, formToken, onSuccess: { ( _ lyraResponse: LyraResponse) -> Void //Verify the payment using your server: Check the response integrity by verifying the hash on your server self.verifyPayment(lyraResponse) }, onError: { (_ error: LyraError, _ lyraResponse: LyraResponse?) -> Void //TODO: Handle Payment SDK error in process payment request self.showMessage("Payment fail: \(error.errorMessage)") })
[Lyra processWithContextViewController:self formToken: formToken onSuccess:^(LyraResponse *lyraResponse //Verify the payment using your server: Check the response integrity by verifying the hash on your server [self verifyPayment:lyraResponse]; } onError:^(LyraError *lyraError, LyraResponse *lyraResponse) { //TODO: Handle Payment SDK error in process payment request [self showMessage: [NSString stringWithFormat:@"Payment fail: %@", lyraError.errorMessage]]; } error:&error];
Description of the LyraResponse object
The LyraResponse object is returned in both onSuccess and onError. It is an object of type JSONObject. In case of success, it is necessary to check its integrity before displaying the payment result.
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. |
The kr-answer object contains the elements described here.
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 the onSuccess or onError callback on the 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).
Our sample code provides an example of message integrity check via your merchant server, i.e. the verifyResult endPoint called in the verifyResult method of the application.
Here is a code sample based on the available iOS code examples and the merchant server.
func verifyPayment(_ lyraResponse: LyraResponse) { serverCommunication.verifyPayment(lyraResponse, onVerifyPaymentCompletion: { (paymentVerified, isConnectionError) in if paymentVerified { self.showMessage("Payment success") } else { self.showMessage("Payment verification fail") } }) }
- (void) verifyPayment:(LyraResponse*) lyraResponse { [_serverComunication verifyPayment:lyraResponse withCompletion:^(BOOL paymentVerified, BOOL isErrorConnection) { if(paymentVerified) [self showMessage: @"Payment success"]; else [self showMessage: @"Payment verification fail"]; }]; }
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.
To customize the payment SDK, you simply have to add a PaymentSdkTheme.plist file in your project and specify in this file the colors to use in hexadecimal values:
<?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
.
Texts
Il est aussi possible de personnaliser certains textes. Pour cela, spécifier le paramètre optionnel "options" lors de l'appel au Lyra.process()
.
PAY button
- The text of the PAY button can be customized.
Specify the key LyraPaymentOptions.customPayButtonLabel
.
Header
- If the text is forced and there is noorderId, il remplacera le texte par défaut qui est "Paiement" ou "Enregistrement de la carte".
- On the other hand, if anorderIdest précisé alors, on continuera à afficher sa valeur. Exemple : "Commande CM-12345".
Specify the key LyraPaymentOptions.customHeaderLabel
.
Payment popup
- The popup text that opens when clicked PAY button can also be customized.
Specify the key LyraPaymentOptions.customPopupLabel
.
Lyra.process(self, formToken, onSuccess: { ( _ lyraResponse: LyraResponse) -> Void //Verify the payment using your server: Check the response integrity by verifying the hash on your server self.verifyPayment(lyraResponse) }, onError: { (_ error: LyraError, _ lyraResponse: LyraResponse?) -> Void //TODO: Handle Payment SDK error in process payment request self.showMessage("Payment fail: \(error.errorMessage)") }, [LyraPaymentOptions.customPayButtonLabel: "MyPayButtonLabel", LyraPaymentOptions.customHeaderLabel: "MyHeaderLabel", LyraPaymentOptions.customPopupLabel: "MyPopupLabel"])
Payment methods offered
Par défaut, l'appel au Lyra.process()
propose tous les moyens de paiement disponibles. Cependant, il est possible de modifier ce comportement pour proposer un moyen de paiement spécifique en utilisant le paramètre optionnel "options". Pour cela :
- Specify the key
LyraPaymentOptions.paymentMethodType
. - Use the enum
LyraPaymentMethods
for the value:
- cardPayment: the card payment form is presented by the SDK.
- applePay: the payment via ApplePay is presented by the SDK.
- all: if there are several payment methods, the payment method selection page is displayed. Otherwise, the card payment form is displayed. This value corresponds to the same behavior as calling to
Lyra.process()
without the keyLyraPaymentOptions.paymentMethodType
dans le paramètre "options".
Cancel a payment in progress
It is possible to cancel a payment in progress using the Lyra.cancelProcess()
method. In general, this method correctly exits the payment form, but there are different scenarios:
The payment process can be cancelled:
- the payment form closes correctly.
- the
handler onError
passed toLyra.process()
is called with the errorMOB_009 - Payment cancelled, indicating that the payment process has been canceled.
Le processus de paiement ne peut pas être annulé. Si le
Lyra.cancelProcess()
est invoqué pendant que le SDK est en communication avec la plateforme de paiement (l'utilisateur vient de cliquer sur le bouton payer) :- the payment form remains displayed.
- the
handler onError
passed toLyra.process()
is called with the errorMOB_013 - Payment cannot be cancelled, indicating that the payment process cannot be canceled. - normal SDK behavior continues:
- if the payment ends successfully, the
handler onSuccess
will be called. - if the payment is failed. Depending on the error, the payment form remains displayed or the
handler onError
will be called.
- if the payment ends successfully, the
S'il n'y a pas de processus de paiement en cours, l'appel au
Lyra.cancelProcess()
n'aura aucun effet.
Enable the card scan feature
Il est possible, dans le SDK, d'activer la fonctionnalité de scan de la carte. Cette fonctionnalité permet à un utilisateur de ne pas saisir manuellement les informations de sa carte mais d'utiliser la caméra de son appareil mobile pour les scanner et remplir automatiquement le formulaire de paiement.
To enable this feature, you need to:
Intégrer la librairie LyraCardsRecognizer dans votre projet Xcode :
. Via CocoaPods
To integrate the library into your Xcode project using CocoaPods, specify it in your Podfile:
target 'MyApp' do pod 'LyraCardsRecognizer' end
Puis installez-la avec
pod update
.Via Carthage
To integrate the LyraCardsRecognizer library into your Xcode project using Carthage, specify it in your
Cartfile
, :binary "https://raw.githubusercontent.com/lyra/ios-cards-camera-recognizer/2.0.0/LyraCardsRecognizer.json" == 2.0.0
Add the
LyraCardsRecognizer.xcframework
file to your iOS project.
Lors de l'initialisation du SDK, envoyez true comme valeur à la clé
cardScanningEnabled
dans le dictionnaire des options de configuration (Voir Initialiser le SDK).
//Active card scan configurationOptions[LyraInitOptions.cardScanningEnabled] = true
//Active card scan [configurationOptions setValue:[NSNumber numberWithBool:true] forKey:LyraInitOptions.cardScanningEnabled];
- In the file
Info.plist
of your application, add the keyNSCameraUsageDescription
and describe the reason for using the camera.
![](/assets/doc/images/mobp/lyra/en-EN/ios_camera_permission.png)