The smarter way
  • Getting Started
  • USER GUIDE
    • Payment Gateway
    • Currencies
    • Apple Pay
      • Setup MPGS
      • Setup Cybersource
    • Payment Tracking
      • Payment Transactions Insights
      • Payment Transactions States
      • Notifications, URLs & Timing
    • Plugins
      • Payment Request
      • E-Commerce
      • Bulk payment request
    • Features
      • Refund & Void Access Control
      • Two-Step Refund & Void Authorization
    • Integration
    • Configuration
      • Global Configuration
      • Webhooks Configuration
      • Transaction Report Configuration
      • How to Get API Keys
      • URL Shortener Configuration
    • Notification Communication Channels
      • Email Notifications
      • SMS Notifications
      • WhatsApp Notifications
        • Integrated WhatsApp Channel
        • Manual WhatsApp Channel
      • Notification Templates
      • Notification Process: Automatic and Manual
    • Satellite
    • Real Estate
      • Regular Activities
        • Property management
        • Tenant and Contract Management
          • Tenant & Contract Dashboard
          • Tenant Management
          • Contract Management
            • Add New Contract
            • Contract Action
              • Renew Contract
              • Terminate Contract
              • Manual Payment
              • Suspend Contract
              • Resume Contract
              • Advance Payment
        • Generate Invoice
        • Invoices Management
        • Maintenance
        • Transactions
        • Auditing and Rolling Back Activities
      • Merchant First Journey
  • developer
    • Getting Started
    • Tokenization
    • Authentication
    • Payment Methods
    • Checkout API
    • Operations
    • User Cards
    • Payment Status-Inquiry
    • Auto-Debit
    • Invoice API
    • Message Notifications
    • Upload Attachment
    • Checkout SDK
      • Web
      • iOS
      • Android
      • Flutter
    • Webhooks
      • Payment Notification
      • Operation Notification
      • Signing Mechanism
      • Integration Guides
        • Laravel Webhook Receiver Guide
        • .NET Webhook Receiver Guide
    • Test Cards
Powered by GitBook
On this page
  • Installation
  • Minimum Requirements
  • Installation with CocoaPods
  • Installation with Swift Package Manager
  • Native UI
  • SDK Configuration
  • Language
  • Light and dark theme
  • Functions
  • Checkout.init
  • Properties
  • Callbacks
  • errorCallback
  • cancelCallback
  • successCallback
  • Example
  • Customization Theme
  • Properties description
  • Data types description
  • Example
  • Apple Pay
  • STC Pay
  • KNET - Apple Pay
  • Onsite Checkout
  • Error Reporting
  • Cyber Security Measures
  • Jailbreak Detection
  • FAQ
  1. developer
  2. Checkout SDK

iOS

PreviousWebNextAndroid

Last updated 1 month ago

The is a Swift framework (library) provided by Ottu, designed to facilitate the seamless integration of an Ottu-powered checkout process into iOS applications.

With the Checkout SDK, both the visual appearance and the forms of payment available during the can be fully customized.

To integrate the Checkout SDK, the library must be included in the iOS application and initialized with the following parameters:

Additionally, optional configurations such as the to accept and the styling for the checkout interface can be specified.

should never be used on the client side. Instead, should be used. This is essential to ensure the security of your application and the protection of sensitive data.

The SDK is supported on devices running iOS 14 or higher.

Ottu is available via . To install it, the following line must be added to the Podfile:

pod 'ottu_checkout_sdk', :git => 'https://github.com/ottuco/ottu-ios.git', :tag => '2.0.3'
  • When ottu_checkout_sdk is added to the Podfile, the GitHub repository must also be specified as follows:

  • If CocoaPods returns an error like "could not find compatible versions for pod", try running the pod repo update command to resolve it.

pod 'ottu_checkout_sdk', :git => 'https://github.com/ottuco/ottu-ios'

Once the Swift package has been set up, adding Alamofire as a dependency requires simply including it in the dependencies value of the Package.swift file.

dependencies: [
    .package(url: "https://github.com/ottuco/ottu-ios.git", from: "2.0.3")
]

The SDK UI is embedded as a View within any part of a ViewController in the merchant's application.

Example:

If only one payment option is available and it is a wallet, the UI is automatically minimized.

The SDK supports two languages: English and Arabic, with English set as the default.

The language applied in the device settings is automatically used by the SDK, requiring no manual adjustments within the application.

However, if the transaction is created in a different language and setup preload is enabled, texts retrieved from the backend (such as fee descriptions) will be displayed in the transaction language rather than the device's language.

The SDK also supports UI adjustments based on the device's theme settings (light or dark mode).

The appropriate theme is applied automatically during SDK initialization, aligning with the device's settings. Similar to language settings, no manual adjustments are required within the application.

The SDK currently provides a single function, serving as the entry point for the merchant's application.

The Checkout.init function is responsible for initializing the checkout process and configuring the necessary settings for the Checkout SDK.

It must be called once by the parent application and provided with a set of configuration fields that define all the required options for the checkout process.

When Checkout.init is invoked, the SDK automatically sets up the essential components, including:

  • Generating a form for the customer to enter their payment details.

  • Handling communication with Ottu's servers to process the payment.

This function returns a View object, which is a native iOS UI component. It can be embedded within any ViewController instance in the application.

The merchant_id specifies the Ottu merchant domain and must be set to the root domain of the Ottu account, excluding the "https://" or "http://" prefix.

For example, if the Ottu URL is https://example.ottu.com, then the corresponding merchant_id is example.ottu.com.

This parameter is used to link the checkout process to the appropriate Ottu merchant account.

Only the public key should be used. The private key must remain confidential at all times and must not be shared with any clients.

The session_id is a unique identifier assigned to the payment transaction associated with the checkout process.

This identifier is automatically generated when the payment transaction is created.

Available options for formsOfPayment:

  • applePay: Supports Apple Pay, allowing purchases to be made using Apple Pay-enabled devices.

  • stcPay: Requires customers to enter their mobile number and authenticate with an OTP sent to their device to complete the payment.

  • cardOnsite: Enables direct payments (onsite checkout), where Cardholder Data (CHD) is entered directly in the SDK. If 3DS authentication is required, a payment provider is involved in the process.

An ApiTransactionDetails struct object is used to store transaction details.

If provided, the SDK will not request transaction details from the backend, reducing processing time and improving efficiency.

An object is used to provide SDK callbacks to the application. Typically, this is the parent app’s class that conforms to OttuDelegate, aggregating the SDK object.

In the Checkout SDK, callback functions are essential for providing real-time updates on the status of payment transactions.

These callbacks improve the user experience by enabling seamless and efficient handling of different payment scenarios, including:

  • Successful payments

  • Transaction cancellations

  • Errors encountered during the payment process

All the callbacks described below can be triggered for any type of payment.

The errorCallback function is triggered when an issue occurs during the payment process. Proper error handling is essential to ensure a smooth user experience.

Best Practice for Handling Errors

Defining the errorCallback Function

The errorCallback function can be defined using the data-error attribute on the Checkout script tag. This attribute allows the specification of a global function to handle errors.

When an error occurs, the errorCallback function is invoked with a data JSON object, where data.status is set to error.

Params Available in data JSONObject for errorCallback

  • message mandatory

  • form_of_payment mandatory

  • status mandatory

  • challenge_occurred optional

  • session_id optional

  • order_no optional

  • reference_number optional

Defining the cancelCallback Function

The cancelCallback function can be defined using the data-cancel attribute on the Checkout script tag. This attribute allows the specification of a global function to handle cancellations.

Invocation of cancelCallback

If a customer cancels a payment, the cancelCallback function is invoked with a data JSON object, where data.status is set to canceled.

Params Available in data JSONObject for cancelCallback

  • message mandatory

  • form_of_payment mandatory

  • challenge_occurred optional

  • session_id optional

  • status mandatory

  • order_no optional

  • reference_number optional

  • payment_gateway_info optional

In both cancelCallback and errorCallback, the SDK must be reinitialized, either on the same session or on a new session.

Defining the successCallback Function

The successCallback function is defined and assigned as the value of the data-success attribute within the Checkout script tag.

Invocation of successCallback

When a payment is successfully processed, the successCallback function is invoked with a data JSON object, where data.status is set to success.

Params Available in data JSONObject for successCallback

  • message mandatory

  • form_of_paymentmandatory

  • challenge_occurred optional

  • session_id optional

  • status mandatory

  • order_no optional

  • reference_number optional

  • redirect_url optional

  • payment_gateway_info optional

There are both UIKit and SwiftUI samples available at the sample repo:

The SDK initialization process and the callback delegate remain identical for both implementations.

Code Sample:

self.checkout = Checkout(
    formsOfPayments: formsOfPayment,
    sessionId: sessionId,
    merchantId: merchantId,
    apiKey: apiKey,
    delegate: self
)
if let paymentView = self.checkout?.paymentView() {
    paymentView.translatesAutoresizingMaskIntoConstraints = false
    self.paymentContainerView.addSubview(paymentView)

    NSLayoutConstraint.activate([
        paymentView.leadingAnchor.constraint(equalTo: self.paymentContainerView.leadingAnchor),
        self.paymentContainerView.trailingAnchor.constraint(equalTo: paymentView.trailingAnchor),
        paymentView.topAnchor.constraint(equalTo: self.paymentContainerView.topAnchor),
        self.paymentContainerView.bottomAnchor.constraint(equalTo: paymentView.bottomAnchor)
      ])
}
extension OttuPaymentsViewController: OttuDelegate {
    func errorCallback(_ data: [String: Any] ? ) {
        paymentContainerView.isHidden = true

        let alert = UIAlertController(title: "Error", message: data?.debugDescription ?? "", preferredStyle:
            .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel))
        self.present(alert, animated: true)
    }

    func cancelCallback(_ data: [String: Any] ? ) {
        var message = ""

        if let paymentGatewayInfo = data ? ["payment_gateway_info"] as ? [String: Any],
            let pgName = paymentGatewayInfo["pg_name"] as ? String,
                pgName == "kpay" {
                    message = paymentGatewayInfo["pg_response"].debugDescription
                } else {
                    message = data?.debugDescription ?? ""
                }

        paymentContainerView.isHidden = true

        let alert = UIAlertController(title: "Canсel", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel))
        self.present(alert, animated: true)
    }

    func successCallback(_ data: [String: Any] ? ) {
        paymentContainerView.isHidden = true
        paymentSuccessfullLabel.isHidden = false

        let alert = UIAlertController(title: "Success", message: data?.debugDescription ?? "", preferredStyle:
            .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel))
        present(alert, animated: true)
    }
}

The main class describing theme is called CheckoutTheme.

It uses additional component classes like:

  • ButtonComponent

  • LabelComponent

  • TextFieldComponent

All properties in the CheckoutTheme class are optional, allowing users to customize any of them as needed.

General

Property Name
Description
Data Type

mainTitle

Font and color for all “Captions”

title

Font and color for payment options in the list

subtitle

Font and color for payment options details (like expiration date)

Fees

Property Name
Description
Data Type

feesTitle

Font and color of fees value in the payment options list

feesSubtitle

Font and color of fees description in the payment options list

Data

Property Name
Description
Data Type

dataLabel

Font and color of payment details fields (like “Amount”)

dataValue

Font and color of payment details values

Other

Property Name
Description
Data Type

errorMessageText

Font and color of error message text in pop-ups

Property Name
Description
Data Type

inputTextField

Font and color of text in any input field (including disabled state)

Property Name
Description
Data Type

backgroundColor

The main background of the SDK view component

UIColor

backgroundColorModal

The background of any modal window

UIColor

iconColor

The color of the icon of the payment

UIColor

Property Name
Description
Data Type

button

Background, text color and font for any button

selectorButton

Background, text color and font for payment item selection button

Property Name
Description
Data Type

switchOnTintColor

The color of switch (toggle) control

UIColor

Property Name
Description
Data Type

margins

Top, left, bottom and right margins between compone

Property Name
Description
Data Type

showPaymentDetails

Boolean variable determining whether the “Payment Details” section should be displayed or hidden.

Boolean

Property Name
Data Type

color

UIColor

font

UIFont

fontFamily

String

Property Name
Data Type

label

text

backgroundColor

UIColor

Property Name
Data Type

enabledTitleColor

UIColor

disabledTitleColor

UIColor

font

UIFont

enabledBackgroundColor

UIColor

disabledBackgroundColor

UIColor

fontFamily

String

Property Name
Data Type

left

Int

top

Int

right

Int

bottom

Int

To configure the theme, similar steps must be followed as described in the test app file.

Code Snippet:

func createTheme() - > CheckoutTheme {
    var theme = CheckoutTheme()
    theme.backgroundColor = .systemBackground
    theme.backgroundColorModal = .secondarySystemBackground
    theme.margins = UIEdgeInsets(top: 8, left: 2, bottom: 8, right: 2)
    theme.mainTitle.color = .label
    theme.mainTitle.fontFamily = "Arial"
    theme.button.enabledTitleColor = .payButtonTitle
    theme.button.disabledTitleColor = .payButtonDisabledTitle
    theme.button.fontFamily = "Arial"
    theme.button.enabledBackgroundColor = .payButtonBackground
    theme.button.disabledBackgroundColor = .payButtonDisabledBackground
    return theme
}

The theme object is passed to the SDK initialization as shown below:

Code Snippet:

self.checkout = Checkout(
    theme: theme,
    sessionId: sessionId,
    merchantId: merchantId,
    apiKey: apiKey,
    delegate: self
)
    • It is confirmed that a session_id and pg_codes associated with the Apple Pay Payment Service have been supplied.

    • It is ensured that the customer is using an Apple device that supports Apple Pay. If the device is not supported, the button will not be shown, and an error message stating This device doesn't support Apple Pay will be displayed to inform the user of the compatibility issue.

    • It is verified that the customer has a wallet configured on their Apple Pay device. if the wallet is not configured (i.e., no payment cards are added), the Setup button will appear. Clicking on this button will prompt the Apple Pay wallet on the user's device to open, allowing them to configure it by adding payment cards.

  1. Displaying the Apple Pay Button: If all these conditions are met, the Apple Pay button is displayed and made available for use in the checkout flow.

  2. Restricting Payment Options: To display only the Apple Pay button, applePay should be passed within the formsOfPayment parameter. The formsOfPayment property instructs the Checkout SDK to render only the Apple Pay button. If this property is not included, all available payment options are rendered by the SDK.

This setup ensures a seamless integration and user experience, allowing customers to easily set up and use Apple Pay during the checkout process.

  • It is confirmed that the session_id and pg_codes provided during SDK initialization are associated with the STC Pay Payment Service. This ensures that the STC Pay option is available for the customer to choose as a payment method.

  • It is ensured that the STC Pay button is displayed by the iOS SDK, regardless of whether the customer has provided a mobile number while creating the transaction.

This setup ensures a seamless integration and user experience, allowing customers to easily set up and use STC Pay during the checkout process.

Due to compliance requirements, KNET necessitates a popup displaying the payment result after each failed payment. This functionality is available only in the cancelCallback when there is a response from the payment gateway. As a result, the user must click on the Apple Pay button again to retry the payment.

The popup notification requirement is specific to the KNET payment gateway. Other payment gateways may have different requirements or notification mechanisms, so it is essential to follow the respective documentation for each payment gateway integration.

To properly handle the popup notification for KNET, the following code snippet should be implemented into your payment processing flow:

func cancelCallback(_ data: [String: Any] ? ) {
    var message = ""

    if let paymentGatewayInfo = data ? ["payment_gateway_info"] as ? [String: Any],
        let pgName = paymentGatewayInfo["pg_name"] as ? String,
            pgName == "kpay" {
                message = paymentGatewayInfo["pg_response"].debugDescription
            } else {
                message = data?.debugDescription ?? ""
            }

    navigationController?.popViewController(animated: true)
    let alert = UIAlertController(title: "Canсel", message: message, preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .cancel))
    self.present(alert, animated: true)
}
}

The above code performs the following checks and actions:

  1. Verification: It first checks if the cancel object contains information about the payment gateway payment_gateway_info.

  2. Payment Gateway Identification: It then verifies if the pg_name property in payment_gateway_info is equal to "kpay", confirming that the payment gateway used is KNET.

  3. Response Handling: If the conditions are met, it retrieves the payment gateway's response from the pg_response property. If not available, it uses a default "Payment was cancelled." error message.

  4. Popup Notification: Finally, it displays the error message in a popup using self.present(alert, animated: true) to notify the user about the failed payment.

This setup ensures compliance with KNET's requirements and provides a clear user experience for handling failed payments.

This payment option allows direct payments to be performed from the mobile SDK. A UI is provided by the SDK, where the CHD is entered by the user. If permitted by the backend, the card can be saved for future payments as a tokenized payment.

Here’s how the onsite checkout screen looks like:

The SDK utilizes Sentry for error logging and reporting, which is initialized based on the configuration from SDK Studio. However, since the SDK is integrated into the merchant's app, conflicts may arise if the app also uses Sentry. To avoid this, merchants can disable Sentry in the Checkout SDK by setting the is_enabled flag to false in the configuration.

To enable the detection of jailbroken devices, the following section must be added to the application's Info.plist file:

<key > LSApplicationQueriesSchemes < /key> 
    <array >
        <string > zbra < /string> 
        <string > cydia < /string> 
        <string > undecimus < /string> 
        <string > sileo < /string> 
        <string > filza < /string> 
        <string > activator < /string> 
    </array>

The SDK supports the following payment forms: tokenPay, ottuPG, redirect applePay and stcPay. Merchants can display specific methods according to their needs.

For example, if you want to only show the STC Pay button, you can do so using formsOfPayment = stcPay, and only the STC Pay button will be displayed. The same applies for applePay and other methods.

It is required to have a device running iOS 13 or higher.

The payment request for Apple Pay can be customized using its initialization methods. These methods allow the configuration of various properties, including:

  • API version

  • Supported card types

  • Accepted networks

  • Applicable countries

  • Merchant capabilities

The (SPM) is a tool designed for automating the distribution of Swift code and is integrated into the Swift compiler.

Therefore, the currently selected device language or the app's selected language should be considered when specifying a language code in the transaction creation request of the .

Additionally, callbacks are provided and must be handled by the parent application. These callbacks are described .

string required

string required

The apiKey is the Ottu API , used for authentication when communicating with Ottu's servers during the checkout process.

string required

For more details on how to use the session_id parameter in the Checkout API, refer to the .

array optional

The forms of payment displayed in the can be customized using formsOfPayment. By default, all forms of payment are enabled.

tokenPay: Uses to securely store and process customers' payment information.

redirect: Redirects customers to an external or a third-party payment processor to complete the transaction.

object optional

object optional

The theme struct object is used for UI customization, allowing modifications to background colors, text colors, and fonts for various components. It supports customization for both light and dark device modes. All fields in the theme struct are optional. If a theme is not provided, the default UI settings will be applied. For more details, refer to the section.

object required

To implement this delegate, the class must define three callback functions. More details are accessible next .

In the event of an error, the recommended approach is to restart the checkout process by generating a new session_id through the .

The cancelCallback function in the is triggered when a payment is canceled.

In the , the successCallback function is triggered upon the successful completion of the .

UIKit:

SwiftUI:

The CheckoutTheme class consists of objects that define various UI components. While the names of these components largely correspond to those listed , they also include platform-specific fields for further customization.

If a property is not specified, the default value (as defined in the Figma design ) will be automatically applied.

When the between Ottu and Apple for Apple Pay is completed, the necessary checks to display the Apple Pay button are handled automatically by the Checkout SDK.

Initialization: Upon initialization of the Checkout SDK with the provided and payment gateway codes (), several conditions are automatically verified:

When the between Ottu and STC Pay is completed, the necessary checks to display the STC Pay button are handled seamlessly by the Checkout SDK.

Initialization: Upon initialization of the Checkout SDK with the provided and payment gateway codes (), several conditions are automatically verified:

Yes, see the section.

For a complete list of supported properties, refer to the documentation.

Swift Package Manager
Checkout API
tokenization
Checkout API
Checkout SDK
here
Apple Pay
Installation with Swift Package Manager
Native UI
SDK Configuration
Language
Light and dark theme
Functions
here
Checkout.init
Properties
merchantId
apiKey
sessionId
formsOfPayment
setupPreload
theme
Customization Theme
delegate
secion
Callbacks
errorCallback
cancelCallback
successCallback
Example
Customization Theme
here
Properties description
Texts
Text Fields
Colors
Buttons
Switch
Margins
Payment Details
Data types description
LabelComponent
TextFieldComponent
ButtonComponent
UIEdgeInsets
Example
Apple Pay
STC Pay
KNET - Apple Pay
Onsite Checkout
Error Reporting
Cyber Security Measures
Jailbreak Detection
FAQ
1️
What forms of payments are supported by the SDK?
2️
What are the minimum system requirements for the SDK integration?
3️
Can I customize the appearance beyond the provided themes?
Customization Theme
4️
How do I customize the payment request for Apple Pay?
LabelComponent
LabelComponent
LabelComponent
LabelComponent
LabelComponent
LabelComponent
LabelComponent
LabelComponent
LabelComponent
TextFieldComponent
ButtonComponent
ButtonComponent
UIEdgeInsets
LabelComponent
Checkout SDK
CocoaPods
forms of payment
theme
Installation
Minimum Requirements
Installation with CocoaPods
Checkout SDK
ottu-ios/Example at main · ottuco/ottu-ios
ottu-ios/Example_SwiftUI at main · ottuco/ottu-ios
checkout process
payment process
public key
payment gateway
integration
integration
session_id
session_id
pg_codes
session_id
pg_codes
checkout process
API public key
API private key
API public key
session_id
merchant_id