iOS SDK (Swift)
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:
-
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.
-
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.
-
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.
-
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.
-
Optional Parameters: All customization parameters provided by the Initialization Factory are optional, allowing developers to selectively implement features based on their application Requirements.
Configure connection settings
Example in Swift:
// Initialize the Payment SDK with custom configuration
let paymentSDKConfiguration = PaymentSDKConfiguration(
language: .arabic, // Set language to Arabic
writingDirection: .rightToLeft, // Set writing direction to RTL (If using right constraints, the direction will be automatic)
theme: .dark, // Set theme to dark
connectionSettings: connectionSettings, // Set connection settings for Payment Gateway, certificates, and keys
tdssUICustomization: tdssUICustomization // Set 3DS SDK UI customization according to EMVCo requirements,
// can be 'null' if Facial Recognition Authentication is allowed for the Merchant
)
// Initialize Payment SDK with custom configuration
PaymentSDK.initialize(with: 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:
-
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.
-
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 colorfinon_pay_sdk_text_bold- bold text colorfinon_pay_sdk_text_error- error text colorfinon_pay_sdk_input_frame_normal- input colorfinon_pay_sdk_input_frame_error- input color when there is validation errorfinon_pay_sdk_button_active_primary- primary button colorfinon_pay_sdk_button_active_secondary- secondary button colorfinon_pay_sdk_ripple_primary- ripple effect primary colorfinon_pay_sdk_ripple_secondary- ripple effect secondary colorfinon_pay_sdk_button_text_color_primary- primary button text colorfinon_pay_sdk_button_text_color_secondary- secondary button text colorfinon_pay_sdk_bg_bottom_sheet- background sheet colorfinon_pay_sdk_bg_card- background color for card frame
Below is an example for resources colors.xml for a particular theme:
Native color-settings in Xcode are fully supported with themes.
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 namefinon_pay_sdk_add_card- Add card labelfinon_pay_sdk_token_cvv- Label for requesting CVV when paying with a tokenfinon_pay_sdk_next- Next button labelfinon_pay_sdk_card_number- Card number labelfinon_pay_sdk_card_number_hint- Card number hintfinon_pay_sdk_card_number_error- Card number error messagefinon_pay_sdk_card_holder_name- Cardholder name labelfinon_pay_sdk_card_holder_name_hint- Cardholder name hintfinon_pay_sdk_card_holder_name_error- Cardholder name error messagefinon_pay_sdk_expiration_date- Card expiry labelfinon_pay_sdk_expiration_date_hint- Card expiry hintfinon_pay_sdk_expiration_date_error- Card expiry error messagefinon_pay_sdk_cvv- Card verification value labelfinon_pay_sdk_cvv_hint- Card verification value hintfinon_pay_sdk_cvv_error- Card verification value error messagefinon_pay_sdk_purchase_amount- Purchase amount labelfinon_pay_sdk_purchase_amount_hint- Purchase amount hintfinon_pay_sdk_continue_shopping- Finish payment labelfinon_pay_sdk_result_success- Successful transaction headerfinon_pay_sdk_result_success_description- Successful transaction descriptionfinon_pay_sdk_result_failure- Failed transaction headerfinon_pay_sdk_result_failure_description- Failed transaction description
{
"sourceLanguage": "en",
"strings": {
"finon_pay_sdk_add_card": {
"extractionState": "manual",
"localizations": {
"ar": {
"stringUnit": {
"state": "translated",
"value": "إضافة بطاقة"
}
},
"en": {
"stringUnit": {
"state": "translated",
"value": "Add card"
}
}
}
}
},
"version": "1.0"
}
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:
-
Secure Token Retrieval: The
Get Payment Tokensmethod retrieves payment tokens securely from local storage, ensuring the confidentiality and integrity of sensitive payment information. -
Association with account ID: Developers can specify an
accountIdas a parameter to retrieve payment tokens associated with that particular user, enabling personalized payment experiences and streamlined transaction management. -
UUID Format: Payment tokens are returned in the form of Universally Unique Identifiers (UUIDs), ensuring uniqueness and compatibility across different platforms and systems.
-
Card Hash: Returns also associated card hashes, so tokens can be migrated to a new device for same account Id.
Example in Swift:
private func getPaymentTokens(for accountId: String) -> [PaymentToken] {
// Call Payment SDK to retrieve payment tokens associated with the
// specified account Id
return PaymentSDK.getPaymentTokens(for: 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.
Example in Swift:
private func getLatestTokenTransactions(for paymentToken: PaymentToken) -> [TokenTransaction] {
// Call Payment SDK to retrieve the latest token transactions associated with
// the specified payment token
return PaymentSDK.getLatestTokenTransactions(for: 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:
-
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.
-
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.
-
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.
-
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.
Example in Swift:
private func blockPaymentTokens(for paymentToken: PaymentToken) -> BlockPaymentTokenResult {
// CCall Payment SDK to block payment token
return PaymentSDK.blockPaymentToken(for: 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:
-
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.
-
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.
-
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.
-
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.
-
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.
Example in Swift:
private func transferPaymentTokens(accountId: String, tokens: [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.
Example in Swift:
// Example of dynamically changing payment configuration in an iOS application
func updatePaymentSDKConfiguration(language: Language, theme: Theme) {
// Create a new PaymentSDkConfiguration instance with updated settings
let updatedConfiguration = PaymentSDKConfiguration(
language: language, // Set new language
theme: theme, // Set new theme
// 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.
Example in Swift:
// Example of setting connection settings in an iOS application
func 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(for: scheme, with: certificate,
algorithm: .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.
Example in Swift:
// Example of adding a listener to a closure event in an iOS application
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(sdkOnBackClick),
name: NSNotification.Name("finon_pay_sdk_on_back_click"),
object: nil
)
}
@objc private func sdkOnBackClick() {
let titleAlert = "Warning"
let textAlert = "Are you sure you want to close the window without saving the card?"
let alert = UIAlertController(
title: titleAlert,
message: textAlert,
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "NO", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "YES", style: .default) { _ in
self.payment.cancel()
})
self.getTopController()?.present(alert, animated: true)
}
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.
Example in Swift:
// Example of handling SDKNotInitializedException in an iOS application
do {
// Attempt to perform operations requiring SDK initialization
try PaymentSDK.processPayment()
} catch SDKError.sdkNotInitialized(let message) {
// Handle SDKNotInitializedException
print("SDK not initialized: \(message)")
// Notify user or initiate retry logic
let alertController = UIAlertController(
title: "Error",
message: "Payment SDK not initialized. Please try again later.",
preferredStyle: .alert
)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
} catch {
// Handle other types of exceptions
print("An unexpected error occurred: \(error)")
}
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.
Example in Swift:
// Example of handling SDKAlreadyInitialized exception in an iOS application
do {
// Attempt to initialize Payment SDK
try PaymentSDK.initialize(with: paymentSDKConfiguration)
} catch SDKError.sdkAlreadyInitialized(let message) {
// Handle SDKAlreadyInitializedException
print("Payment SDK already initialized: \(message)")
// Notify user or log the error
let alertController = UIAlertController(
title: "Error",
message: "Payment SDK already initialized.",
preferredStyle: .alert
)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
} catch {
// Handle other types of exceptions
print("An unexpected error occurred: \(error)")
}
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.
Example in Swift:
// Example of handling SDKRuntimeException in an iOS application
do {
// Attempt to perform Payment SDK operation
try PaymentSDK.processPayment()
} catch SDKError.sdkRuntimeException(let message) {
// Handle SDKRuntimeException
print("Runtime error occurred: \(message)")
// Notify user or log the error
let alertController = UIAlertController(
title: "Error",
message: "An unexpected error occurred. Please try again later.",
preferredStyle: .alert
)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
} catch {
// Handle other types of exceptions
print("An unexpected error occurred: \(error)")
}
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 dataaccountId- 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.
Example in Swift:
// Example of calling the "Process Payment" method with paymentDetails, onSuccess, and onError callbacks in an iOS application
func processPayment(
paymentDetails: PaymentDetails,
onSuccess: @escaping () -> Void,
onError: @escaping (String) -> Void
) {
do {
// Attempt to process payment using the provided payment details
try PaymentSDK.processPayment(
paymentDetails,
onSuccess: onSuccess,
onError: onError
)
} catch PaymentError.paymentProcessingError(let message) {
// Handle PaymentError and invoke error callback
onError("Payment processing error: \(message)")
} catch {
// Handle other types of exceptions
onError("An unexpected error occurred")
}
}
// Usage:
processPayment(
paymentDetails: paymentDetails,
onSuccess: { showPaymentSuccessMessage() },
onError: { errorMessage in
showErrorAlert(title: "Payment Error", message: errorMessage)
}
)
private func showPaymentSuccessMessage() {
// Display payment success message to the user
}
private func showErrorAlert(title: String, message: String) {
// Display error alert 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