Skip to main content
Version: v1.4.x Legacy

Android SDK (Kotlin)

Initialization factory

The Initialization Factory is a component of the Payment SDK, designed to provide developers with extensive customization options for the visual aspects of payment integration in their applications. With support for multilingualism, bidirectional writing, light/dark themes, and color customization, the Initialization Factory empowers developers to create tailored payment experiences that meet the diverse needs of their users.

Key Features:

  1. Multilingual Support: The Initialization Factory supports both Arabic and English languages out of the box, allowing developers to seamlessly localize payment interfaces for global Audiences.

  2. Bidirectional Writing (LTR and RTL): Developers can configure the Initialization Factory to support both left-to-right (LTR) and right-to-left (RTL) writing directions, ensuring optimal layout and readability for languages like Arabic.

  3. Light and Dark Themes: The Initialization Factory offers options for both light and dark themes, enabling developers to adapt payment interfaces to different environments and user Preferences.

  4. Connection Settings: The Initialization Factory allows to configure technical and Security related values, such as base URLs, payment scheme certificates and public keys for data Encryption.

  5. Optional Parameters: All customization parameters provided by the Initialization Factory are optional, allowing developers to selectively implement features based on their application Requirements.

Code Example:

Configure connection settings

val connectionSettings: ConnectionSettings

// Initialize the Payment SDK with custom configuration
val paymentSDKConfiguration = PaymentSDKConfiguration.Builder()
// Set language to Arabic
.setLanguage(Language.ARABIC)
// Set writing direction to RTL
.setWritingDirection(WritingDirection.RIGHT_TO_LEFT)
// Set theme to dark
.setTheme(Theme.DARK)
// Set connection settings for Payment Gateway, certificates and keys
.setConnectionSettings(connectionSettings)
// Set 3DS SDK UI customisation according to EMVCo requirements,
// can be ‘null’ if Facial Recognition Authentication is allowed to be used for the Merchant
.setTdssUICustomization(tdssUICustomization)
.build()

// Initialize Payment SDK with custom configuration
PaymentSDK.initialize(context, paymentSDKConfiguration)

Custom Forms Configurations

Forms configuration settings allow to personalize various visual and textual elements of the application to align with business requirements and branding. Payment SDK uses platform native approaches for colors, labels and localisation, while embedded 3DS SDK strictly follows EMVCo requirements using UICustomization class.

Key Features:

  1. Color Transfer: Developers can customize font, background, and input colors for each theme, with the option to transfer colors between themes for consistent branding and user experience.

  2. Custom Labels: The Initialization Factory allows developers to set custom labels as a map of key-value pairs, providing the flexibility to customize text elements within the payment interface according to specific application requirements.

Color Palette

Define the primary, secondary, accent colors, and more to establish the visual identity of your application:

  • finon_pay_sdk_text_regular - regular text color
  • finon_pay_sdk_text_bold - bold text color
  • finon_pay_sdk_text_error - error text color
  • finon_pay_sdk_input_frame_normal - input color
  • finon_pay_sdk_input_frame_error - input color when there is validation error
  • finon_pay_sdk_button_active_primary - primary button color
  • finon_pay_sdk_button_active_secondary - secondary button color
  • finon_pay_sdk_ripple_primary - ripple effect primary color
  • finon_pay_sdk_ripple_secondary - ripple effect secondary color
  • finon_pay_sdk_button_text_color_primary - primary button text color
  • finon_pay_sdk_button_text_color_secondary - secondary button text color
  • finon_pay_sdk_bg_bottom_sheet - background sheet color
  • finon_pay_sdk_bg_card - background color for card frame

XML Example:

Below is an example for resources colors.xml for a particular theme:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="finon_pay_sdk_text_bold">#0A1F41</color>
<color name="finon_pay_sdk_text_regular">#43536D</color>
<color name="finon_pay_sdk_text_error">#F23B37</color>
<color name="finon_pay_sdk_input_frame_normal">#C1C7D0</color>
<color name="finon_pay_sdk_input_frame_error">#F23B37</color>
<color name="finon_pay_sdk_button_active_primary">#7742F4</color>
<color name="finon_pay_sdk_ripple_primary">#C4A7F8</color>
<color name="finon_pay_sdk_button_active_secondary">#39A156</color>
<color name="finon_pay_sdk_ripple_secondary">#91FB95</color>
<color name="finon_pay_sdk_button_text_color_primary">#FFFFFFFF</color>
<color name="finon_pay_sdk_button_text_color_secondary">#39A156</color>
<color name="finon_pay_sdk_bg_bottom_sheet">#FFFFFFFF</color>
<color name="finon_pay_sdk_bg_card">#000000</color>
</resources>

SDK Text & Labels

Tailor text labels, button texts, error messages, and other textual content to resonate with your target audience:

  • finon_pay_sdk_app_name - Application name
  • finon_pay_sdk_add_card - Add card label
  • finon_pay_sdk_token_cvv - Label for requesting CVV when paying with a token
  • finon_pay_sdk_next - Next button label
  • finon_pay_sdk_card_number - Card number label
  • finon_pay_sdk_card_number_hint - Card number hint
  • finon_pay_sdk_card_number_error - Card number error message
  • finon_pay_sdk_card_holder_name - Cardholder name label
  • finon_pay_sdk_card_holder_name_hint - Cardholder name hint
  • finon_pay_sdk_card_holder_name_error - Cardholder name error message
  • finon_pay_sdk_expiration_date - Card expiry label
  • finon_pay_sdk_expiration_date_hint - Card expiry hint
  • finon_pay_sdk_expiration_date_error - Card expiry error message
  • finon_pay_sdk_cvv - Card verification value label
  • finon_pay_sdk_cvv_hint - Card verification value hint
  • finon_pay_sdk_cvv_error - Card verification value error message
  • finon_pay_sdk_purchase_amount - Purchase amount label
  • finon_pay_sdk_purchase_amount_hint - Purchase amount hint
  • finon_pay_sdk_continue_shopping - Finish payment label
  • finon_pay_sdk_result_success - Successful transaction header
  • finon_pay_sdk_result_success_description - Successful transaction description
  • finon_pay_sdk_result_failure - Failed transaction header
  • finon_pay_sdk_result_failure_description - Failed transaction description
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="finon_pay_sdk_app_name">PaymentSdk</string>
<string name="finon_pay_sdk_add_card">Add card</string>
<string name="finon_pay_sdk_next">Next</string>
<string name="finon_pay_sdk_card_number">Card number</string>
<string name="finon_pay_sdk_card_number_hint">0000–0000–0000–0000</string>
<string name="finon_pay_sdk_card_number_error">Enter your card number</string>
</resources>

Support methods

Get Payment Tokens

The Get Payment Tokens method allows developers to retrieve payment tokens associated with an accountId from local storage. Payment tokens, represented in the form of UUIDs, serve as secure identifiers for cards and facilitate seamless payment processing within applications.

Key Features:

  1. Secure Token Retrieval: The Get Payment Tokens method retrieves payment tokens securely from local storage, ensuring the confidentiality and integrity of sensitive payment information.

  2. Association with account ID: Developers can specify an accountId as a parameter to retrieve payment tokens associated with that particular user, enabling personalized payment experiences and streamlined transaction management.

  3. UUID Format: Payment tokens are returned in the form of Universally Unique Identifiers (UUIDs), ensuring uniqueness and compatibility across different platforms and systems.

  4. Card Hash: Returns also associated card hashes, so tokens can be migrated to a new device for same account Id.

Code Example:

private fun getPaymentTokens(accountId: String): List<PaymentToken> {
// Call Payment SDK to retrieve payment tokens associated with the specified account Id
return PaymentSDK.getPaymentTokens(accountId)
}

Get latest token transactions

The Get latest Token Transactions method enables developers to retrieve the latest token transactions associated with a specific payment token.

Code Example:

private fun getLatestTokenTransactions(paymentToken: PaymentToken): List<TokenTransaction> {
// Call Payment SDK to retrieve the latest token transactions
// associated with the specified payment token
return PaymentSDK.getLatestTokenTransactions(paymentToken)
}

Block Payment Token

The Block Payment Token method allows developers to block the payment token, in the case when it is assumed that the payment token can no longer be used for payment. The card hashe associated with the blocked token will be removed. It allows to create new token for the card.

Key Features:

  1. Token Status Management: The method enables developers to change the status of payment tokens stored locally within the SDK. This status prevent their further use in payment transactions.

  2. Developer Control: Developers have full control over the token status, allowing them to block tokens programmatically based on various conditions or triggers. This flexibility enables proactive management of payment tokens to mitigate fraud or security risks.

  3. Real-Time Updates: Changes to token status are reflected in real-time within the local storage of the SDK. This ensures that any blocked tokens are immediately recognized and cannot be used for future payment transactions.

  4. Granular Blocking: Developers can block specific tokens individually, allowing for granular control over which tokens are invalidated. This precision is useful in scenarios where only certain tokens need to be blocked while others remain active.

Code Example:

private fun blockPaymentToken(paymentToken: PaymentToken): BlockPaymentTokenResult {
// Call Payment SDK to block payment token
return PaymentSDK.blockPaymentToken(paymentToken)
}

Transfer Payment Tokens

The "Transfer Payment Tokens" method allows developers to transfer payment tokens and card hashes associated with an account Id from local storage of one device to another. Payment tokens, represented in the form of UUIDs, serve as secure identifiers for cards and facilitate seamless device to device data migration.

Key Features:

  1. Cross-Device Transfer: The method enables developers to transfer payment tokens securely between devices. This facilitates seamless migration of payment data from one device to another, ensuring continuity of payment services for users across different platforms or devices.

  2. Account ID Association: Payment tokens are associated with a specific account ID, allowing developers to transfer tokens linked to a particular user or account from one device to another. This ensures that the transferred tokens remain tied to the same user’s account.

  3. Local Storage Synchronization: The SDK synchronizes the transfer of payment tokens between devices' local storage seamlessly. This ensures that transferred tokens are accurately replicated on the recipient device without loss or corruption of data.

  4. UUID Representation: Payment tokens are represented as universally unique identifiers (UUIDs), ensuring their uniqueness and preventing conflicts or duplication during transfer between devices. This standard format simplifies token management and interoperability across different systems.

  5. Secure Transfer Protocol: The method employs a secure transfer protocol to encrypt and protect payment token data during transmission between devices. This safeguards sensitive payment information from interception or unauthorized access by malicious actors.

Code Example:

private fun transferPaymentTokens(accountId: String, tokens: List<PaymentToken>)
: TransferPaymentTokensResult {
// Call Payment SDK to transfer payment tokens associated with the specified account Id
return PaymentSDK.transferPaymentTokens(accountId, tokens)
}

Payment SDK Configuration Change

The Payment SDK Configuration Change method allows developers to update the payment configuration settings dynamically within their applications. This functionality enables developers to modify payment-related parameters, such as language settings, theme colors, or custom labels, based on user preferences or application requirements, without the need for a full application restart.

Code Example:

// Example of dynamically changing payment configuration in an Android application
fun updatePaymentSDKConfiguration(language: Language, theme: Theme) {
// Create a new PaymentSDKConfiguration instance with updated settings
val updatedConfiguration = PaymentSDKConfiguration.Builder()
.setLanguage(language) // Set new language
.setTheme(theme) // Set new theme
.build() // Add other configuration settings as needed

// Update Payment SDK with the new configuration
PaymentSDK.updateConfiguration(updatedConfiguration)
}

Change connection settings

The Change Connection Settings method allows developers to configure connection settings for the payment gateway within their applications. This functionality enables developers to specify parameters such as the payment gateway base URL and payment schema certificates, ensuring secure and reliable communication with the payment gateway server.

Code Example:

// Example of setting connection settings in an Android application
fun setConnectionSettings(settings: ConnectionSettings) {
// Set the payment gateway base URL
PaymentSDK.setPaymentGatewayBaseUrl(settings.baseUrl)
// Set the payment gateway public key
PaymentSDK.setPaymentGatewayBaseUrl(settings.publicKey)
// Set the payment schema certificates
for ((scheme, certificate) in settings.certificates) {
PaymentSDK.setPaymentSchemaCertificate(scheme, certificate, CertAlgorithm.RSA)
}
}

Customize payment form closure actions

The "Subscribe to payment form closure" method allows developers to configure actions such as additional questions or behavioral changes on their application if event for the form closure was fired from Payment SDK side.

Code Example:

// Example of adding a listener to closure event in an Android application
override fun onReceive(context: Context, intent: Intent) {
BroadcastScope().launch {
PaymentSDK.exitSdk { requireContext, onExit ->
requireContext?.let {
val dialog = Dialog(requireContext)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(R.layout.dialog_sdk_exit)
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

val btnYes = dialog.findViewById<AppCompatButton>(R.id.bt_yes)
val btnNo = dialog.findViewById<AppCompatButton>(R.id.bt_no)

btnYes.text = SpannableStringBuilder()
.underline { append(context.getString(R.string.yes)) }
btnNo.text = SpannableStringBuilder()
.underline { append(context.getString(R.string.no)) }

btnYes.setOnClickListener {
dialog.dismiss()
onExit(true)
}

btnNo.setOnClickListener {
dialog.dismiss()
onExit(false)
}

dialog.show()
}
}
}
}

Exception Handling

SDKNotInitializedException

The SDKNotInitializedException is thrown when an attempt is made to use a feature or functionality of the Payment SDK without initializing it first. This exception serves as a signal to developers that the SDK initialization process has not been completed successfully, and subsequent operations cannot proceed until the SDK is properly initialized.

Code Example:

// Example of handling SDKNotInitializedException in an Android application
try {
// Attempt to perform operations requiring SDK initialization
PaymentSDK.processPayment()
} catch (e: SDKNotInitializedException) {
// Handle SDKNotInitializedException
Log.e("SDK Error", "SDK not initialized: ${e.message}")
// Notify user or initiate retry logic
// Example:
Toast.makeText(context, "Payment SDK not initialized. Please try again later.",
Toast.LENGTH_SHORT).show()
}

SDKAlreadyInitialized

The SDKAlreadyInitialized exception is thrown when an attempt is made to initialize the Payment SDK multiple times within the application lifecycle. This exception serves as a signal to developers that the SDK has already been initialized and subsequent initialization attempts are redundant.

Code Example:

// Example of handling SDKAlreadyInitialized exception in an Android application
try {
// Attempt to initialize Payment SDK
PaymentSDK.initialize(context, paymentSDKConfiguration)
} catch (e: SDKAlreadyInitializedException) {
// Handle SDKAlreadyInitializedException
Log.e("SDK Error", "Payment SDK already initialized: ${e.message}")
// Notify user or log the error
// Example:
Toast.makeText(context, "Payment SDK already initialized.", Toast.LENGTH_SHORT)
.show()
}

SDKRuntimeException

The SDKRuntimeException represents unexpected runtime errors that may occur during the execution of Payment SDK operations. These errors could be due to various factors such as network issues, server errors, or invalid input parameters. Handling this exception allows developers to gracefully manage such runtime errors and provide appropriate feedback to users.

Code Example:

// Example of handling SDKRuntimeException in an Android application
try {
// Attempt to perform Payment SDK operation
PaymentSDK.processPayment()
} catch (e: SDKRuntimeException) {
// Handle SDKRuntimeException
Log.e("SDK Error", "Runtime error occurred: ${e.message}")
// Notify user or log the error
// Example:
Toast.makeText(context, "An unexpected error occurred. Please try again later.",Toast.LENGTH_SHORT)
.show()
}

Payment method

Payment Details

The PaymentDetails object represents basic data for payment processing implementation.

Key values description:

  • paymentId - payment identifier returned from payment gateway

  • requestId - request identifier from the application

  • customerInfo - payer’s data

    • accountId - account identifier (user identifier)
  • amount - payment amount

  • currency - payment currency

  • paymentMethod - representation of method for the payment

    • paymentType - PaymentType.PAYMENT_TOKEN or PaymentType.CARD

    • paymentToken - PaymentToken.id if paymentType is PaymentType.PAYMENT_TOKEN

  • nonPaymentOperation - A sign of a non-payment operation. Amount must be null for nonpayment transactions.

  • withoutAuthenticate - The indication of the operation without authentication of the payer.

  • needPaymentToken - A sign of the need to generate a paymentToken for making Payments,based on a successful Payment. For non-payment transactions, the value must be 'true'.

  • tokenType - The type of the requested token (in descending order of possibilities):

    • AUTH - authenticated token (for any operations)

    • NON_RECUR - authenticated token (you can perform any operations except recurrent)

    • UNAUTH - an unauthenticated token (only for authentication operations). If the capabilities of the requested token are lower than the result of the operation, a token of the requested type will be returned. Otherwise, the token that was obtained as a result of the operation will be returned.

  • aPlusWalletId - wallet identifier for Facial Recognition Authentication

Process payment method call

The Process Payment method facilitates payment transactions within the application using the Payment SDK. This functionality enables developers to securely process payments and handle transaction outcomes. The method includes callback functions to handle both successful and error scenarios, ensuring a seamless payment experience for users.

Code Example:

// Example of calling the "Process Payment" method with paymentDetails, onSuccess, and onError callbacks in an Android application
fun processPayment(
paymentDetails: PaymentDetails,
onSuccess: () -> Unit,
onError: (String) -> Unit
) {
try {
// Attempt to process payment using the provided payment details
PaymentSDK.processPayment(paymentDetails, onSuccess, onError)
} catch (e: PaymentException) {
// Handle PaymentException and invoke error callback
onError("Payment processing error: ${e.message}")
}
}

// Usage:
processPayment(
paymentDetails = paymentDetails,
onSuccess = { showPaymentSuccessMessage() },
onError = { errorMessage -> showErrorDialog("Payment Error", errorMessage) }
)

private fun showPaymentSuccessMessage() {
// Display payment success message to the user
}

private fun showErrorDialog(title: String, message: String) {
// Display error dialog with the provided title and message to the user
}

Integration Support

After reading this entire page, if you've faced any issues or any questions in mind regarding the integration with the Payment SDK then please contact the Payment Gateway Integration Support via Email Address