Getting started with Android SDK

  Last updated: 

  Before proceeding, please ensure you have met all requirements
Click here to open this information in a new tab

  Our GitLab repository includes an example app that demonstrates how to integrate our payment SDK into your application. Our examples are predominantly written in Kotlin, but examples in Java are also provided. Click here to view.

Features

The Trust Payments Android SDK allows you to seamlessly integrate a prebuilt or custom UI in your app to accept card payments & comply with the Strong Customer Authentication (SCA) mandate.

Use this integration if you need a pre-built “Drop-In” UI that supports the following features:

  • Card payments
  • Tokenization payments
  • Customisation of UI components to fit with your business branding
  • Locale and custom translations
  • Google Pay

Alternatively our SDK can empower you to process payments to the Trust Payments gateway, whilst using your own payment checkout view.

 

             

 

1. Install the SDK in your app

To embed the Mobile SDK into your project, you will need to use Gradle, a build automation tool that offers dependency management features:

 

Integrating SDK Artefacts as a Dependency from Maven

In your app-level build.gradle file, add the following dependencies:

// Trust Payments SDK core dependency
implementation 'com.trustpayments.mobile:core:<latest_version>' // Optional UI module providing ready-to-use "drop-in" view
implementation 'com.trustpayments.mobile:ui:<latest_version>'

To integrate the Mobile SDK, add the following dependencies to your app-level build.gradle file:

You will need to refer to the following resources and include the latest package version numbers in the placeholders above:

In your root-level build.gradle file, add the following dependency to get the Cardinal SDK.

allprojects {
repositories {
google()
...
maven {
url "https://gitlab.com/api/v4/projects/56100229/packages/maven"
name "GitLab"
credentials(HttpHeaderCredentials) {
name = "Private-Token"
value = <gitlab_token>
}
authentication {
header(HttpHeaderAuthentication)
}
}
}
}
  As of release 2.8.3, you will be required to contact our Support Team to request a gitlab_token for the Android SDK project.

 

             

 

2. Initialise the Android SDK in your app

Configure the instance

Before you can begin accepting payments, you'll first need to create an instance of our SDK PaymentTransactionManager class.

PaymentTransactionManager(
context = context,
gatewayType = TrustPaymentsGatewayType.EU,
isCardinalLive = false,
merchantUsername = usernameFromTrustPayments,
cardinalStyleManager = null,
isLocationDataConsentGiven = false
)
  Parameter Description
  Required context Provides the Android context
  Required gatewayType

Specifies the gateway processing region. Set this to be: TrustPaymentsGatewayType.EU

  Required isCardinalLive When set to true, all 3-D Secure-related operations will be targeted to the 3D-Secure live environment, otherwise the staging environment will be used. Set this to true when processing live payments.
  Required merchantUsername Username provided by our Support Team i.e. your JWT Username
 Optional cardinalStyleManager 3D-Secure UI customisation.
  Required isLocationDataConsentGiven When set to true you are confirming that your app received consent from the customer to capture their device location as part of your app privacy policy.

 

Location Consent

As of v2.7.10.1 of the Android SDK, we have introduced an additional parameter to the SDKs PaymentTransactionManager class called isLocationDataConsentGiven. By default, isLocationDataConsentGiven is set to false, meaning the customer has not agreed to your app privacy policy that requests consent to capture the device location data. The information required for the privacy policy to be displayed to the customer can be found here.

To reduce the likelihood of your customers being challenged by the card issuer for further authentication, complete the following:

  1. Once your customer has agreed to your app privacy policy, which includes location data, the consent to your app privacy policy must be passed to the Trust Payments SDK PaymentTransactionManager instance by setting isLocationDataConsentGiven as true. 

  2. Request that GPS can be enabled if currently disabled by the customer device.
  3. Create a location consent prompt when your app is creating an instance of the PaymentTransactionManager class. You will need to include permissions in the manifest file:
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    If permission to access the device location is granted to your app by the customer, then the SDK will attempt to capture the device location. For best practices to generate the device location consent prompt, please refer to Google's official best practices.

For an example of how to present the privacy policy to customers in your app for customer acceptance, you can reference our sample application class PrivacyPolicyActivity.kt 

 

Custom Payment View

For integrators who have already or plan to build their own payment view capable of capturing the customer card details, you can skip ahead to section 'Process a payment' where we explain how to create a payment session and execute the payment request to our payment processing gateway.

 

Drop-In Payment View

The SDK comes with its own Drop-In Payment View which allows you to quickly add the card detail inputs into your checkout. To inflate our default Drop-In Payment View, you start by adding it to an appropriate XML file:

<com.trustpayments.mobile.ui.dropin.DropInPaymentView
android:id="@+id/dropInPaymentView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp" />

Next, an activity related to this layout has to implement the required listener interface and override the methods of the Drop-In Payment View. This ensures that the card detail variables are updated when the customer card details are successfully validated.

class SimpleActivity : AppCompatActivity(), DropInPaymentView.DropInPaymentViewListener {

    // Payment card details.
    private var pan = ""
    private var expiryDate = ""
    private var cvv = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_simple)
        // Set the drop-in payment view listener
        findViewById(R.id.dropInPaymentView).dropInPaymentViewListener = this
    }

    /**
     * Captures user input from payment view and update variables if input is valid.
     * */
    override fun onInputValid(paymentInputType: PaymentInputType, input: String) {
        when (paymentInputType) {
            PaymentInputType.PAN - pan = input
            PaymentInputType.ExpiryDate - expiryDate = input
            PaymentInputType.CVV - cvv = input
        }
    }

    /**
     * Get called once card details is provided in payment view and pay button is clicked.
     * */
    override fun onPayButtonClicked() {
        processTransaction(pan = pan, expiryDate = expiryDate, cvv = cvv)
    }
}
  

 

 Process a Payment

  The following solution involves the transmission of sensitive payment credentials. When developing your solution, you must ensure that your system does NOT store or log the card number, expiry date or security code. Failure to do so will invalidate your PCI compliance.

To request a payment, start by creating a payment session by calling the createSession method, which takes the following arguments:

  Parameter Description
  Required jwt A JSON Web Token(JWT) signed on your secure merchant server and passed back to your app, which contains details about the payment transaction amount, customer billing, shipping, order reference information, etc. To learn how to construct the JWT and its payload contents, click here to open more info in a new tab.
  Optional cardPan

The customer's card number

  Optional cardExpiryDate The customer's card expiry date
  Optional cardSecurityCode The customer's security code

 

Once you have your payment session, call the executeSession method, which takes the following arguments:

  Parameter Description
  Required session The payment session details, including the signed JWT & customer card details
 Conditional activityProvider

When calling executeSession method and also specifying THREEDQUERY in the JWT payload requesttypedescriptions field list, you must provide an activityProvider. The activityProvider is a callback to an Activity. The Activity would be the window in your Android app and this needs to be known to our payment SDK to successfully display the 3-D Secure version 2 challenge window to your customers.

  As of v2.8.0.0 - activityResultProvider should not be passed as the 3rd parameter to the executeSession method, as this was only required for 3-D Secure version 1, which has since been deprecated.

 private fun processTransaction(pan: String, expiryDate: String, cvv: String) {
  lifecycleScope.launch(Dispatchers.IO) {
	// Obtain generated JWT from client server, This contains payment order information that you are planning to pay.
	val jwt: String = fetchJwtFromServer()
	// Create payment session which contains order and payment information.
	val session: PaymentSession = paymentTransactionManager.createSession(
		jwtProvider = { jwt },
		cardPan = pan,
		cardExpiryDate = expiryDate,
		cardSecurityCode = cvv,
	)
	// Executes payment request using PaymentTransactionManager. Once completed response will be presented.
	val response: Response = paymentTransactionManager.executeSession(
		session = session,
		activityProvider = {
			this@SimpleActivity
		},
	)
	// Validate payment result and update screen with the transaction details.
	processResponse(response)
  }
}

 

Verify Payment Response

The payment response comes back as a JSON Web Token (JWT). It's imperative that the JWT response signature is validated before trusting its content. As with the payment request JWT, the signature verification should take place on your secure server.

To learn more on how to validate the response JWT, please take a moment to review heading 'Verify the response JWT signature' in our JWT guidance.

Once the signature has been successfully verified and you've confirmed that the AUTH request has been processed successfully, you can proceed to update the app screen to notify the customer.

/**
* Validates executed payment result and update screen with the transaction details.
* */
private suspend fun processResponse(response: Response) {
  // Verify JWT signature from response on your server
  if (verifyJwtSignatureUsingYourServer(response.responseJwtList)) {
    val parsedResult = ResponseParser.parse(response.responseJwtList)
    val transactionReference =
parsedResult?.firstOrNull() ?.customerOutput?.transactionReference withContext(Dispatchers.Main) { Toast.makeText( this@SimpleActivity, "Transaction Successful: $transactionReference", Toast.LENGTH_LONG ).show() } } }

 

Full Example

package com.trustpayments.mobile.exampleapp

import JwtProvider.fetchJwtFromServer
import JwtProvider.verifyJwtSignatureUsingYourServer
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.trustpayments.mobile.core.PaymentSession
import com.trustpayments.mobile.core.services.api.TrustPaymentsGatewayType
import com.trustpayments.mobile.core.services.transaction.PaymentTransactionManager
import com.trustpayments.mobile.core.services.transaction.PaymentTransactionManager.Response
import com.trustpayments.mobile.core.util.ResponseParser
import com.trustpayments.mobile.ui.dropin.DropInPaymentView
import com.trustpayments.mobile.ui.model.PaymentInputType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SimpleActivity : AppCompatActivity(), DropInPaymentView.DropInPaymentViewListener {

    // PaymentTransactionManager responsible for executing the transaction.
    private val paymentTransactionManager by lazy {
        PaymentTransactionManager(
            context = applicationContext,
            gatewayType = TrustPaymentsGatewayType.EU,
            isCardinalLive = false, // Mark this true for production mode.
            merchantUsername = BuildConfig.MERCHANT_USERNAME, // MERCHANT_USERNAME obtained through account manager
            isLocationDataConsentGiven = true,
        )
    }

    // Payment card details.
    private var pan = ""
    private var expiryDate = ""
    private var cvv = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_simple)
        // Set the drop-in payment view listener
        findViewById(R.id.dropInPaymentView).dropInPaymentViewListener = this
    }

    /**
     * Captures user input from payment view and update variables if inputs are valid.
     * */
    override fun onInputValid(paymentInputType: PaymentInputType, input: String) {
        when (paymentInputType) {
            PaymentInputType.PAN - pan = input
            PaymentInputType.ExpiryDate - expiryDate = input
            PaymentInputType.CVV - cvv = input
        }
    }

    /**
     * Gets called once card details are provided in payment view and pay button is clicked.
     * */
    override fun onPayButtonClicked() {
        processTransaction(pan = pan, expiryDate = expiryDate, cvv = cvv)
    }

    private fun processTransaction(pan: String, expiryDate: String, cvv: String) {
        lifecycleScope.launch(Dispatchers.IO) {
            // Obtain generated JWT from client server, This contains payment order information that you are planning to pay.
            val jwt: String = fetchJwtFromServer()
            // Create payment session which contains order and payment information.
            val session: PaymentSession = paymentTransactionManager.createSession(
                jwtProvider = { jwt },
                cardPan = pan,
                cardExpiryDate = expiryDate,
                cardSecurityCode = cvv,
            )
            // Executes payment request using PaymentTransactionManager. Once completed response will be presented.
            val response: Response = paymentTransactionManager.executeSession(
                session = session,
                activityProvider = {
                    this@SimpleActivity
                },
            )
            // Validate payment result and update screen with the transaction details.
            processResponse(response)
        }
    }

    /**
     * Validates executed payment result and update screen with the transaction details.
     * */
    private suspend fun processResponse(response: Response) {
        // Verify JWT signature from response
        if (verifyJwtSignatureUsingYourServer(response.responseJwtList)) {
            val parsedResult = ResponseParser.parse(response.responseJwtList)
            val transactionReference =
                parsedResult?.firstOrNull()
                    ?.customerOutput?.transactionReference
            withContext(Dispatchers.Main) {
                Toast.makeText(
                    this@SimpleActivity,
                    "Transaction Successful: $transactionReference",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
    }
}

 

             

 

3. Configure webhooks

It is strongly recommended that you configure webhooks on your Mobile SDK solution. When configured, URL notifications are sent to your system when payments are processed on your account.

  If you do not configure webhooks as explained below, you may not be notified of payments processed on your account, e.g. in cases of client-side errors that occur prior to the response being returned.

  1. Sign in to Portal.

  2. Search for your sitereference using the search box found at the top of the page.

  3. When viewing your site details, click “Rule manager“.



  4. Select the action type “URL notification” from the drop-down and your browser will be redirected.



  5. Create a new URL notification rule:
      • (A) Click “Add new condition” and specify the circumstances in which the URL notification is to be triggered following a transaction. In the Requests box displayed, ensure “AUTH” is ticked (meaning the notification is triggered following payment authorisations).
        Click here to learn more about configuring conditions.
      • (B) Click “Add new action” and specify the endpoint for the URL notification.
        Click here to learn more about URL notification actions.
      • (C) Using the drop-down boxes, assign the condition to the action and click “Create rule“.



  6. Ensure the rule is active (this is shown with a tick under the Active column). Once enabled, the rule will be applied to all payment sessions for the given sitereference, and the URL notification will be triggered whenever the condition specified is met.

    Note: All new rules should be created on your test sitereference and tested to ensure they work as expected before being added to your live sitereference.

  7. You must configure your system to respond to all URL notifications received from Trust Payments with an HTTP 200 OK response.
    For example: “HTTP/1.0 200 OK”.
    Your system must reply within 8 seconds of receiving a notification.

  Once you have completed the steps above, we recommend returning to the Getting started page to learn more about enabling add-ons, testing your solution and going live.

Click here to open the Getting started page.

 

Was this article helpful?
0 out of 0 found this helpful