• 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

Android integration guide

  • Add the the payment SDK to your application
  • Initialize the SDK
  • Make a payment
  • Check the transaction status

This page provides information on how to:

  • View our integration examples
  • Customize the SDK
  • Enable NFC feature
  • Enable the card scanning feature

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

Our SDK is compatible with Android 19 and higher.

To add the payment SDK to your application, it is necessary to add the following dependency in your build.gradle :

implementation 'com.lyra:sdk:1.2.+'

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.

Optimize the efficiency of our support service

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.

Only if your minSdkVersion is <= 23, then it is necessary to follow the following procedure https://developer.android.com/studio/write/java8-support in order to allow Android devices <= 6 to benefit from sending sentry messages. When filtering sensitive data, our SDK uses Java8 code.

Here are the changes that need to be made to the build.gradle of your application:

// only if your minSdkVersion <= 23
android {
    compileOptions {
        // Flag to enable support for the new language APIs
        coreLibraryDesugaringEnabled = true
        // Sets Java compatibility to Java 8
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
}
dependencies {
    // Needed by coreLibraryDesugaringEnabled compileOptions
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:1.1.5")
}

Initialize the SDK

As mentioned in the chapter on the solution operation, it is necessary to perform the SDK initialization when launching your application, usually in the "onCreate" method of your core business.

To do this, simply call the Lyra.initialize method with the following parameters:

Parameter Format Description
publicKey String Your public key (available in the Expert Back Office : Settings -> Store -> REST API Keys, see the Requirements page).
options HashMap Map allowing to configure the SDK: NFC, card scan.

Example of a call:

val options = HashMap<String, Any>()
options[Lyra.OPTION_API_SERVER_NAME] = "MY_API_SERVER_NAME"
Lyra.initialize(applicationContext, PUBLIC_KEY, options)
HashMap options = new HashMap();
options.put(Lyra.OPTION_API_SERVER_NAME, "MY_API_SERVER_NAME");
Lyra.INSTANCE.initialize(getApplicationContext(), PUBLIC_KEY, options);

The possible keys in this dictionary are:

Keys Value format Description Required
apiServerName String REST API server name (available in the Expert Back Office : Settings -> Store-> REST API keys), see the Requirements page). Required
cardScanningEnabled Bool Enables/Disables the camera scan functionality of the map. If not set, the functionality will be disabled. Optional
nfcEnabled Bool Enables/Disables the NFC card scanning functionality. If not set, the functionality will be disabled. Optional

Warning: this method may return an error if the initialization failed. Please see the page on Error handling to resolve the 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

The payment process occurs in 2 steps: the initialization of the form display, and the processing of the payment itself.

Initialize the display of the payment form

When the user decides to pay, you can initialize the payment form display.

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 Charge/CreatePayment Web Service (again from your merchant server). In this request, you need to pass a formTokenVersion parameter that corresponds to 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 sample code based on the Android code examples and the provided merchant server.

    requestQueue.add(JsonObjectRequest(Request.Method.POST,
    "${SERVER_URL}/createPayment",
    paymentParams,
    Response.Listener { response ->
        //Extract the formToken from the serverResponse
        val answer = JSONObject(response).getJSONObject("answer")
        val formToken = answer.getString("formToken")
        //Now, call Lyra.process() with the formToken
    },
    Response.ErrorListener { error ->
        //Please manage your error behaviour here
        Toast.makeText(
            applicationContext,
            "Error Creating Payment",
            Toast.LENGTH_LONG
       ).show()
    }
   ))
    requestQueue.add(new JsonObjectRequest(Request.Method.POST, SERVER_URL + "/createPayment", getPaymentParams(), new Response.Listener<JSONObject>() {
        //Process merchant server response
        @Override
        public void onResponse(JSONObject response) {
            //Extract the formToken from the serverResponse
            JSONObject answer = new JSONObject(response).getJSONObject("answer");
            String formToken = answer.getString("formToken");
            //Now, call Lyra.process() with the formToken
        }
    }, new Response.ErrorListener() {
        //Error when calling merchant server
        @Override
        public void onErrorResponse(VolleyError error) {
            //Please manage your error behaviour here
            Toast.makeText(getApplicationContext(), "Error Creating Payment", Toast.LENGTH_LONG).show();
        }
    }));

Important: 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 application, you must transmit it to our payment SDK by calling the Lyra.process method with the following parameters:

Parameter Format Description
supportFragmentManager FragmentManager Reference to your UI so that the SDK can display the payment form.
formToken String The formToken, extracted from the previously called createPayment response.
paymentHandler LyraHandler Callback to process the payment result.

The SDK then checks the formToken consistency and displays the available payment methods.

Example of a call:

    Lyra.process(supportFragmentManager, formToken, object : LyraHandler {
        override fun onSuccess(lyraResponse: LyraResponse) {
            verifyPayment(lyraResponse)
        }

        override fun onError(lyraException: LyraException, lyraResponse: LyraResponse?) {
            Toast.makeText(
                applicationContext,
                "Payment fail: ${lyraException.errorMessage}",
                Toast.LENGTH_LONG
           ).show()
        }
    })
    Lyra.INSTANCE.process(getSupportFragmentManager(), formToken, new LyraHandler() {
        @Override
        public void onSuccess(LyraResponse lyraResponse) {
            verifyPayment(lyraResponse);
        }

        @Override
        public void onError(LyraException e, LyraResponse lyraResponse) {
            Toast.makeText(getApplicationContext(), "Payment fail: " + e.getErrorMessage(), Toast.LENGTH_LONG).show();
        }
    });

The paymentHandler is an interface that must be implemented. It contains 2 methods:

Callback Description
onSuccess Appelée si le paiement s'est déroulé correctement.
onError Cette méthode est appelée si le paiement est en échec ou n'a pu être initié. Cette situation peut se produire si une erreur fonctionnelle (le paiement a été refusé) ou technique est survenue pendant le paiement. Pour en savoir plus consulter: Gestion des erreurs.

Description of the LyraResponse object

The same 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 de l'objet JSON stocké dans kr-answer. Il permet de vérifier l'authenticité de la réponse
kr-hash-algorithm Algorithme utilisé pour calculer le hash
kr-hash-key Clé utilisée pour signer kr-answer.
kr-answer-type Type de l'objet JSON contenu dans kr-answer
kr-answer Objet contenant les objets transactions complets encodés en JSON

The kr-answer objet 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 you have correctly configured the notification rules,
  • By calling the paymentHandler 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 sample code based on the Android code examples and the provided merchant server.

    requestQueue.add(JsonObjectRequest(Request.Method.POST,
    "${SERVER_URL}/verifyResult",
    payload,
    Response.Listener { response ->
        //Check the response integrity by verifying the hash on your server
        Toast.makeText(
            applicationContext,
            "Payment success",
            Toast.LENGTH_LONG
       ).show()
    },
    Response.ErrorListener { error ->
        //Manage error here, please refer to the documentation for more information
        Toast.makeText(
            applicationContext,
            "Payment verification fail",
            Toast.LENGTH_LONG
       ).show()
    }
   ))
    requestQueue.add(new JsonObjectRequest(Request.Method.POST, SERVER_URL + "/verifyResult", response, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            //Check the response integrity by verifying the hash on your server
            Toast.makeText(getApplicationContext(), "Payment Success", Toast.LENGTH_LONG).show();
        }
    }, new Response.ErrorListener() {
        //Error when verifying payment
        @Override
        public void onErrorResponse(VolleyError error) {
            //Manage error here, please refer to the documentation for more information
            Toast.makeText(getApplicationContext(), "Payment verification fail", Toast.LENGTH_LONG).show();
        }
    }));

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 colors, just define them in your file colors.xml :

<color name="payment_sdk_PrimaryColor">#293C7A</color>
<color name="payment_sdk_SecondaryColor">#FFFFFF</color>

To customize the font you just need to override the necessary style in the file styles.xml :

<style name="PaymentSDK_Theme">
    <item name="android:fontFamily"></i>casual</item></style>

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().

The key to add is Lyra.CUSTOM_PAY_BUTTON_LABEL. Here is an example:

   Lyra.process(supportFragmentManager, formToken, LyraHandler, hashMapOf(Lyra.CUSTOM_PAY_BUTTON_LABEL to "MyCustomLabel"))

Enable NFC feature

It is possible, in the SDK, to activate the NFC functionality. This feature allows a user not to enter his card information manually but to use NFC to scan it and automatically fill in the payment form.

To enable this feature, you need to:

  1. When initializing the SDK, send true as a value for the nfcEnabled key in the configuration options (see Initializing the SDK).
    options[Lyra.OPTION_NFC_ENABLED] = true
    options.put(Lyra.OPTION_NFC_ENABLED, true);
  1. Add the following permission in the AndroidManifest.xml file of your application:
<uses-permission android:name="android.permission.NFC" />

Enable the card scanning feature

It is possible, in the SDK, to enable the card scanning functionality by camera. This feature allows a user to not enter his card information manually but 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. Integrate the CardsCameraRecognizer library into your Android project by adding the following dependency to your build.gradle:
    // Lyra Cards Camera Recognizer SDK
    implementation 'com.lyra:cards-camera-recognizer:1.0.+'
  1. When initializing the SDK, send true as a value for the cardScanningEnabled key in the configuration options (see Initializing the SDK).
    options[Lyra.OPTION_CARD_SCANNING_ENABLED] = true
    options.put(Lyra.OPTION_CARD_SCANNING_ENABLED, true);

Please note that the following permissions will be added directly in the AndroidManifest.xml file during the compilation of the project:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature android:name="android.hardware.CAMERA" android:required="false" />
<uses-feature android:name="android.hardware.camera.AUTOFOCUS" android:required="false" />

Copyrights

Recruitment

Head Office :

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

2.17.0-doc-1.8