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
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.
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 it in your Podfile:
target 'MyApp' do use_frameworks! pod 'LyraPaymentSDK' end
Then install it with
pod update
.
Via Carthage
To integrate the SDK into your Xcode project using Carthage, specify in your
Cartfile
the necessary dependencies for our SDK:# Payment SDK Mobile & dependencies github "CosmicMind/Material" == 3.1.8 github "SnapKit/SnapKit" == 5.0.1 github "getsentry/sentry-cocoa" "7.13.0" binary "https://raw.githubusercontent.com/lyra/ios-sdk/2.0.0/LyraPaymentSDK.json" == 2.0.0 binary "https://raw.githubusercontent.com/lyra/sentry-client-cocoa/2.0.0/sentry_client_cocoa.json" == 2.0.0 # Your dependencies ...
Add the ,
LyraPaymentSDK.xcframework
, to your iOS project along with the other dependencies specified in yourCartfile
.
We recommend to regularly update the payment SDK in order to guarantee optimal security of your payments.
You can regularly check our GitHub repository to follow new SDK releases.
Initialize the SDK
As mentioned in the chapter describing the solution operation , it is necessary to initialize the SDK when you launch your application , normally in the "didFinishLaunchingWithOptions" method of your AppDelegate.
To do this, simply call the initialize method with the following parameters and after importing the framework import LyraPaymentSDK
, :
PARAMETER | FORMAT | Description |
---|---|---|
publicKey | String | Votre clé publique (disponible dans le |
options | [String: Any] | Dictionary that allows you to configure the behavior of the SDK. |
Example of a call:
//Configure SDK options var configurationOptions = [String : Any]() configurationOptions[Lyra.apiServerName] = apiServerName //Initialize Payment SDK do { try Lyra.initialize(publicKey, configurationOptions) } catch { }
//Configure SDK options NSMutableDictionary *configurationOptions = [[NSMutableDictionary alloc] init]; [configurationOptions setValue:apiServerName forKey:Lyra.apiServerName]; //Initialize Payment SDK [Lyra initialize:publicKey :configurationOptions error:&error];
The possible keys in this dictionary are:
Keys | Value format | Description | required |
---|---|---|---|
apiServerName | String | Votre nom du serveur de l'API REST (disponible dans le | 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.
To do this, you need to call your merchant server, to verify the user's purchases there, and then generate a form identifier (called formToken) by calling the Web Service Charge/CreatePayment (again from your merchant server). In this request, you need to pass a formTokenVersion parameter that matches the result of the SDK's getFormTokenVersion method. The Web Service response or this form token should then be returned to your mobile application.
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 has been received in the mobile application, you must transmit 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 used with the PaymentSDKFont
key. Caution : For the font to be used to be taken into account, it must be added to your application, in your iOS project.
Texts
It is also possible to customize the text of the payment button. To do so, specify the optional "options" parameter when calling the Lyra.process().
PAY button
- The text of the PAY button can be customized.
Specify the key Lyra.customPayButtonLabel
.
Header
- If the text is forced and there is no orderId, it will replace the default text, which is "Payment" or "Card registration".
- On the other hand, if an orderId is specified, we will continue to display the "OrderId" value.
Specify the key Lyra.customHeaderLabel
.
Payment popup
- The popup text that opens when clicked PAY button can also be customized.
Specify the key Lyra.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)") }, [Lyra.customPayButtonLabel: "MyPayButtonLabel", Lyra.customHeaderLabel: "MyHeaderLabel", Lyra.customPopupLabel: "MyPopupLabel"])
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 onError handler passed to Lyra.process() is called with the "MOB_009 - Payment cancelled" error, indicating that the payment process has been cancelled.
- The payment process cannot be cancelled. If the Lyra.cancelProcess() is invoked while the SDK is communicating with the payment platform (the user has just clicked on the pay button) :
- the payment form remains displayed.
- the onError handler passed to Lyra.process() is called with the "MOB_013 - Payment cannot be cancelled" error, indicating that the payment process has been cancelled.
- normal SDK behavior continues:
- if the payment ends successfully, the onSuccess handler will be called.
- if the payment is failed. Depending on the error, the payment form remains displayed or the onError handler will be called.
- If there is no payment processing, the Lyra.cancelProcess() call will have no effect.
Enable the card scan feature
It is possible, in the SDK, to activate the card scanning functionality. This feature allows a user not to enter his card information manually but to use the camera of his mobile device to scan it and automatically fill in the payment form.
To enable this feature, you need to:
Integrating the LyraCardsRecognizer library into your Xcode project.
- Via CocoaPods
To integrate the library into your Xcode project using CocoaPods, specify it in your Podfile:
target 'MyApp' do pod 'LyraCardsRecognizer' end
The install it with
pod update
.- Via Carthage
To integrate the library , LyraCardsRecognizer , 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.When initializing the SDK, send true as a value to the cardScanningEnabled key in the configuration options dictionary (see Initializing the SDK ).
//Active card scan configurationOptions[Lyra.cardScanningEnabled] = true
//Active card scan [configurationOptions setValue:[NSNumber numberWithBool:true] forKey:Lyra.cardScanningEnabled];
- In the Info.plist file of your application, add the NSCameraUsageDescription key and describe the reason for using the camera.
