Skip to main content
Version: v2.0.4 latest

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:

  1. Multilingual Support: The Initialization Factory supports English, Arabic, and Kurdish out of the box. Through the PaymentSDKLocalization object you define the list of languages the user can pick from inside the SDK UI, and which one is selected initially.

  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.

Configure the SDK (initialization)

The v2.x SDK is distributed as payment_sdk.xcframework (plus TdsSdkIos.xcframework for 3DS). Both are linked and embedded directly in your Xcode project — no CocoaPods required.

The old PaymentSDKLanguage enum (.english, .arabic, .kurdish, .auto) is gone in v2.x. Languages are now plain ISO 639-1 string codes wrapped in SdkLanguage(code:name:), and a code of nil means "follow the system language".

Example in Swift:

// The list of languages available in the SDK's language picker
let english = SdkLanguage(code: "en", name: "English")
let arabic = SdkLanguage(code: "ar", name: "العربية")
let kurdish = SdkLanguage(code: "ku", name: "کوردی") // Kurdish — new in v2.x
let system = SdkLanguage(code: nil, name: "System")

let localization = PaymentSDKLocalization(
availableLanguages: [english, arabic, kurdish, system],
selectedLanguageCode: "en", // UI language to apply first (nil = system)
writingDirection: .leftToRight
)

// Merchant display settings (optional on iOS, unlike Android)
let merchant = Merchant(
name: "Merchant Name",
logoUrlLight: "https://example.com/logo-light.png", // logo for light theme
logoUrlDark: "https://example.com/logo-dark.png", // logo for dark theme
finishPaymentUri: "finon://payment" // URI to return the payer after a SuperQi deep-link payment
)

// Settings for the "Pay with SuperQi" (ALIPAY) payment screen
let aliPaySettings = AliPaySettings(
showFirst: .QR, // show the QR option first (or .LINK)
qrToDeepLinkFallback: true, // offer an "open the app" button next to the QR
deepLinkToQrFallback: true // offer a QR next to the "open the app" button
)

// 3DS authentication flow settings
// (replaces the old authenticationFlow + tdssUICustomization parameters)
let tdsSettings = TDSSettings(
authFirst: .SDK, // try the embedded 3DS SDK flow first (or .BROWSER)
authFallback: true, // fall back to the other flow on failure
tdssUICustomization: UiCustomization() // EMVCo UI customization
)

let paymentSDKConfiguration = PaymentSDKConfiguration(
localization: localization, // replaces language + writingDirection
theme: .system, // .light, .dark, or .system
skipResultScreen: false,
connectionSettings: connectionSettings, // Payment Gateway URL, certificates, keys
tdsSettings: tdsSettings,
paymentMethodChoice: .onSdk, // SDK draws the method chooser (.onApp = your app does)
availablePaymentMethods: [.CARD, .ALIPAY, .PAYMENT_TOKEN], // .ALIPAY = "Pay with SuperQi"
merchant: merchant,
aliPaySettings: aliPaySettings
)

// Create the SDK instance with the custom configuration
let paymentSDK = PaymentSDK(with: paymentSDKConfiguration)
Enum casing on iOS

PaymentMethodChoice uses camelCase cases (.onSdk, .onApp) while AvailablePaymentMethods and PaymentTypeAliPay keep SCREAMING_CASE (.CARD, .ALIPAY, .QR, .LINK).

Deprecated attributes

The old top-level language:, writingDirection:, and tdssUICustomization: parameters still compile in v2.x for backward compatibility, but they are deprecated and will be removed in a future release. The new localization and tdsSettings values take priority — new integrations should only use the API shown above.

Enabling "Pay with SuperQi"

Adding .ALIPAY to availablePaymentMethods is all it takes to offer Pay with SuperQiALIPAY is the SDK's internal identifier for it. The full guide (flows, fallbacks, presets) is in the Pay with SuperQi section.

Register the finishPaymentUri URL scheme

For the SuperQi deep-link flow, the external wallet app returns the payer to your app through the custom URL scheme in Merchant.finishPaymentUri (e.g. finon://payment). The scheme must be registered in your app, either through the Xcode interface:

  • Select: Project → Target → Info
  • Scroll to the "URL Types" section and press "+"
  • Fill in the fields:
    • Identifier: $(PRODUCT_BUNDLE_IDENTIFIER) or a unique bundle ID
    • URL Schemes: your application scheme (e.g., finon)

or directly in Info.plist:

<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>None</string>
<key>CFBundleURLName</key>
<string>your.bundle.identifier</string>
<key>CFBundleURLSchemes</key>
<array>
<string>finon</string>
</array>
</dict>
</array>

finishPaymentUri is an iOS-only setting — on Android the equivalent scheme is declared in AndroidManifest.xml instead of the configuration.

Call setCustomerInfo before processing payments

On iOS the SDK's local storage is initialized per customer: call setCustomerInfo (with a non-null accountId) before processPayment, otherwise token storage and payments can fail.

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

Native color-settings in Xcode (color assets per light/dark appearance) are fully supported with themes. The color keys are identical on both platforms — the full v2.x key table (including the SuperQi and Aqsati screen colors) is on the Android SDK page.

SDK Text & Labels

Tailor text labels, button texts, error messages, and other textual content to resonate with your target audience. The string keys are identical on both platforms and are grouped by screen (common elements, method chooser, card screen, Pay with SuperQi screen, result screen) — see the full v2.x key tables on the Android SDK page.

On iOS, provide the values through a string catalog:

{
"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:

  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.

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:

  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.

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:

  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.

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.

On iOS these are instance methods on your PaymentSDK object, overloaded with one labeled parameter per configuration value:

Example in Swift:

// Examples of dynamically changing payment configuration in an iOS application

// Update theme to dark
paymentSDK.updatePaymentSDKConfiguration(theme: .dark)

// Update language to Kurdish
paymentSDK.updatePaymentSDKConfiguration(selectedLanguage: SdkLanguage(code: "ku", name: "کوردی"))

// Update writing direction to RTL
paymentSDK.updatePaymentSDKConfiguration(writingDirection: .rightToLeft)

// Update the available payment methods
paymentSDK.updatePaymentSDKConfiguration(availablePaymentMethods: [.CARD, .ALIPAY])

// Move the method-selection screen to the app side
paymentSDK.updatePaymentSDKConfiguration(paymentMethodChoice: .onApp)

// Change the SuperQi presentation to deep-link first
paymentSDK.updatePaymentSDKConfiguration(
aliPaySettings: AliPaySettings(showFirst: .LINK, qrToDeepLinkFallback: true, deepLinkToQrFallback: true)
)

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 data

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

  • currency - payment currency

  • paymentMethod - representation of method for the payment

    • paymentType - PAYMENT_TOKEN, CARD, ALIPAY (Pay with SuperQi), or AQSATI

    • 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