• France
lyra.com
Search
Categories
Tags
Europe (English)
France
Spain
Europe (English)
India
Home
Implementation
Embedded form (cards)
REST payment API
REST PCI-DSS payment API
REST SEPA API
Hosted payment
Data collection form
File exchange
Mobile payment
Snippets
Plugins
Marketplace
Back Office
Merchant Back Office
Expert Back Office
Guides
Help
FAQ
Video tutorials
Support

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
  • 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 integration codes of our SDK in different languages in the Github repository.

Add the the payment SDK to your application

Our SDK is compatible with iOS 11.0 and above.

There are different ways of integrating the SDK into an Xcode project:

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

From now, as the command line warning indicates, you should always open the project with the.xcworkspace file and not the.xcodeproj file. Otherwise, you will encounter compilation errors.

  1. 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 dependencies specified in your Cartfile.

Regadless of how you choose to integrate our SDK, once it is integrated in your project, you must select the " Embed & Sign " option.

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 BO marchand : Paramètres->Boutique->Clés de l'API REST, cf. la page Prérequis).
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 BO marchand : Paramètres > Boutique > Clés de l'API REST), cf. la page Prérequis). Required
cardScanningEnabled Bool Enables/Disables the map scan feature, see Enable card scan feature. Optional

Cette méthode peut renvoyer une erreur si l'initialisation a échoué. Merci de consulter la page sur la " Gestion des erreurs " pour résoudre la situation.

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"];

    }];

Do not call the Charge/CreatePayment web service from your mobile application!

  • 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 app, you need to pass 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

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.

It is also possible to customize the text of the payment button. To do this, you will need to send the text to be displayed as the key value when calling the Lyra.process()

        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: "MyCustomLabel"])

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:

  1. Integrating the LyraCardsRecognizer library into your Xcode project

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

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

  2. 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];
  1. In the Info.plist file of your application, add the NSCameraUsageDescription key and describe the reason for using the camera.

Copyrights

Recruitment

Head Office :

LYRA NETWORK
109, rue de l’innovation
31670 Labège
FRANCE

2.17.0-doc-1.8