Skip to content

iOS (Swift)

The WajubMobile Swift package and its ready-made payment sheet.

The iOS SDK lets you take Mobile Money, card and wallet payments in your app, with a ready-made payment sheet.

WajubMobileUI

Stable · GA

Swift Package Manager

Version
1.0.0
Runtime
iOS 15+, Swift 5.9+ (Xcode 15+)
Frameworks
SwiftUI sheet, UIKit presenter

Covers

  • Payments
  • Mobile Money
  • Cards

Install

The package is added with Swift Package Manager. In Xcode, File › Add Package Dependencies… with https://github.com/wajubhq/wajub-ios, or in your own Package.swift:

Package.swift
dependencies: [
    .package(url: "https://github.com/wajubhq/wajub-ios.git", from: "1.0.0"),
],
targets: [
    .target(name: "App", dependencies: [
        .product(name: "WajubMobileUI", package: "wajub-ios"),
    ]),
]
RequirementValue
iOS15.0 or later
Swift5.9 or later, so Xcode 15 or later
DependenciesNone. Stripe is optional and lives in your app, see Cards
TargetAn app, not an app extension

The package has two products, and WajubMobileUI brings WajubMobile with it.

ProductWhat it holds
WajubMobileThe models, the errors, the Mobile Money helpers, and what you need to draw your own payment screens. No UI
WajubMobileUIThe SwiftUI sheet and WajubCheckout.present(_:from:)

Quick start

Your server creates the payment, the app presents the sheet with its token, and your server confirms the outcome. The app never holds your secret key.

1. Create the payment on your server with POST /payments and your secret key, then hand its authorization_token to the app through your own endpoint.

Your own endpoint, your own client
struct CheckoutResponse: Decodable {
    let authorizationToken: String
}

func fetchToken(cartId: String) async throws -> String {
    var request = URLRequest(url: URL(string: "https://api.yourshop.com/checkout")!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try JSONEncoder().encode(["cart_id": cartId])

    let (data, _) = try await URLSession.shared.data(for: request)
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    return try decoder.decode(CheckoutResponse.self, from: data).authorizationToken
}

2. Present the sheet from a view controller. present resolves once, when the sheet is gone, with the same value onComplete receives. It throws sheet_already_presented only when another sheet is still open.

The whole integration
import UIKit
import WajubMobile
import WajubMobileUI

@MainActor
func pay(token: String, from viewController: UIViewController) async {
    var options = PresentOptions(sessionToken: token)
    options.returnURL = "https://shop.example.com/app/return" // optional, a universal link into your app
    options.callbacks.onStateChange = { event in print("checkout:", event.state.rawValue) }

    do {
        switch try await WajubCheckout.present(options, from: viewController) {
        case .complete(let payment, _):
            // Paid. Confirm on your server before delivering.
            await confirmOnServer(paymentId: payment.id)
        case .processing:
            // Closed while a payment was running: money may still move.
            showPending()
        case .failed(let error, _):
            showError(error.message)
        case .cancelled(let reason, _):
            print("cancelled:", reason.rawValue)
        }
    } catch let error as WajubError {
        // Only sheet_already_presented: a sheet is already open.
        print(error.code)
    } catch {}
}

from: is optional. Without it the sheet presents from the top-most view controller of the key window. There is no SwiftUI view or modifier for the sheet: from a SwiftUI screen, call WajubCheckout.present without from:, or with the view controller that hosts your view.

3. Confirm on your server before you deliver anything, with GET /payments/{id} or the payment.succeeded webhook. The result in the app is what the payer saw, not a proof of payment: a Mobile Money approval can land after the payer closed the sheet.

Options

PresentOptions is a struct of var properties. Its initializer takes every one of them as a labelled argument with the default below, so set them there or on the value afterwards.

OptionTypeDefaultWhat it does
sessionTokenStringRequiredThe payment's authorization_token
localeString?nil"fr" or "en". Without it, the payment's language, else the device's
appearanceAppearance?nilThe sheet's look, see Appearance
loaderLoaderStyle.skeleton.skeleton, pulsing placeholder blocks, or .spinner
readyTimeoutInt, milliseconds15000Past it, a sheet still loading shows "We couldn't load the payment" with Retry and reports ready_timeout to onLoadError. 0 disables it
returnURLString?nilAn https universal link that brings the payer back to your app from a provider's page. Without it the payer comes back to the app by hand
mobileMoneyMobileMoneyOptionsMobileMoneyOptions()See Mobile Money
cancelOnDismissBooltrueClosing the sheet before any attempt cancels the payment. false leaves it open so you can present it again
autoCloseSuccessInt, milliseconds3000Before the success screen closes itself. 0 keeps it
callbacksCheckoutCallbacksCheckoutCallbacks()See Callbacks and states
cardCollectorCardCollector?nilYour Stripe card collector, see Cards. Without one, Stripe card payments are not offered
Options in the initializer
let options = PresentOptions(
    sessionToken: token,
    locale: "fr",
    loader: .spinner,
    returnURL: "https://shop.example.com/app/return",
    mobileMoney: MobileMoneyOptions(country: "CI", countryLocked: true, operatorMode: .detect),
    cancelOnDismiss: false
)

Callbacks and states

Every callback is optional and runs on the main thread, in this order: onReady, then onStateChange as the sheet moves, onPaymentStarted and onRedirect, then onSuccess, onError or onCancel, and onComplete exactly once. A callback that throws does not stop the sheet.

CallbackPayloadWhen
onReadyReadyEvent: sessionId, environment ("sandbox" or "live"), amount, currency, methods (the channel slugs shown)The first screen is drawn, also for a payment already paid or ended
onStateChangeStateChangeEvent: state, method (mobile_money, card, wallet or unknown)After onReady, then on every state change
onLoadErrorWajubErrorThe sheet cannot offer a payment
onPaymentStartedPaymentStartedEvent: method, channelThe payment request is accepted. From now on, closing the sheet resolves .processing
onRedirectRedirectEvent: url, methodRight before a provider page opens
onSuccessPaymentSuccessThe payment succeeded, with method "unknown" when it was already paid when the sheet opened
onErrorWajubErrorEvery failure the payer sees, retryable ones included. Field validation is not reported
onCancelCancelEvent: reason, redirectURLThe sheet closes as .cancelled
onCompleteCheckoutResultThe sheet closes, with what present resolves with
Callbacks in the initializer
options.callbacks = CheckoutCallbacks(
    onReady: { event in print("ready:", event.environment, event.methods) },
    onPaymentStarted: { event in print("paying with", event.channel) },
    onError: { error in print(error.code, error.correlationId ?? "-") }
)

CheckoutState is a String enum whose raw values are the state names: .initiated (INITIATED), .collectingDetails, .processing, .approvalRequired, .ussdRequired, .otpRequired, .pinRequired, .phoneRequired, .birthdayRequired, .addressRequired, .threeDSRequired (3DS_REQUIRED), .verifying, .pending, .success, .failed, .expired and .cancelled. Compare on the case, log rawValue. What each state shows is on Mobile SDKs.

Results

CheckoutResult is an enum with four cases, and status gives its name as a string, complete, processing, failed or cancelled.

CaseWhen
.complete(payment:transaction:)The sheet closed after the success screen, also for a payment already paid when it opened
.processing(transaction:)The sheet closed while a payment was under way: money may still move, confirm it on your server
.failed(error:transaction:)The sheet closed on a failure, an expiry, a load error, or a payment cancelled elsewhere (payment_cancelled)
.cancelled(reason:redirectURL:)Cancel payment (.payerCancelled), a close before any attempt (.dismissed), or the presenting screen going away first (.hostGone)

PaymentSuccess holds id (Wajub's payment id, what GET /payments/{id} takes), reference (yours), amount (what the payer paid, fee included, in major units), currency, method, status (always "success"), timestamp (ISO 8601) and receiptURL.

When the screen you presented from is dismissed while the sheet is open, the sheet resolves .cancelled with .hostGone before any attempt, .processing once one started and .complete after a success, and it never cancels the payment. With no window to present from, it resolves .hostGone at once.

If the app's process dies, nothing can resolve. At the next launch, read the outcome on your server, or with WajubSession(sessionToken:).status().

Cancelling and closing

The payer closes the sheet with its close button or a swipe down.

The payer closesResult
While the payment is still loading.cancelled, .dismissed. The payment stays open
Before any attempt.cancelled, .dismissed, and the payment is cancelled, unless cancelOnDismiss is false
While a payment is under way: approving, dialling a code, confirming a step or waiting.processing. The payment carries on: confirm it on your server
On the failure screen.failed with the error shown. The payment is cancelled too when it still can be, unless cancelOnDismiss is false
After the success screen.complete

Cancel payment, offered on the method list, on a form and on a failure the payer can retry, cancels the payment for good and resolves .cancelled with .payerCancelled.

The sheet never shows a failure when the outcome is unknown: it shows "Payment in progress" and keeps waiting, and closing it then resolves .processing. More on Mobile SDKs.

Appearance

PresentOptions.appearance sets the sheet's look. The keys, presets and variables are on Appearance.

A preset, a scheme and a few variables
options.appearance = Appearance(
    theme: .stripe,              // presets: .stripe, .night, .flat, .noPreset
    colorScheme: .auto,          // .light, .dark, .auto (follows the phone, live)
    variables: AppearanceVariables(
        colorPrimary: "#0F766E",
        fontFamily: "Poppins",   // used when your app ships it
        borderRadius: "12px"
    ),
    buttonTextColor: "#FFFFFF"
)
  • Arguments follow the declaration order of the initializers, as Swift requires: in AppearanceVariables, fontFamily comes before borderRadius.
  • The "none" preset is .noPreset for theme, and no shadow is .noShadow for shadow.
  • inherit: true takes the presenting screen's tint, colours and light or dark style.
  • What you set wins. The merchant's branding from the Dashboard fills what you leave unset: logo, business name, colours, radius and font. A white-label merchant hides "Secured by Wajub".
  • disableAnimations: true, or Reduce Motion on the phone, stops the animations.

Mobile Money

The payer picks the country and the operator and types the number. The sheet then asks them to approve the payment on their phone.

MobileMoneyOptionsDefaultWhat it does
countrynilThe country to start on, ISO-2. Without it, the payer's country when it is offered
countryLockedfalseHides the country selector, when country is offered
operatorMode.choose.choose lists the operators. .detect shows the operator found from the number, and the list only when the number does not tell or the payer opens it

For your own screens, MobileMoneyData.shared checks, formats and reads numbers: isValid(_:country:), nationalDigits(_:country:), e164(_:country:), formatAsYouType(_:), detectOperator(_:country:), and badge(operatorId:fallbackName:) for an operator's badge.

Cards

The card is paidWhat you do
With StripePass a CardCollector. Without one, Stripe card payments are not offered
On the payment provider's secure pageNothing. The sheet asks for the contact details the provider needs, then opens its page in Safari
In sandboxNothing. The sheet shows a test card form

A one-tap wallet opens the wallet's own app. While a page is open, Continue payment reopens it.

Stripe through your own collector

The package does not depend on Stripe's SDK. Implement CardCollector in your app with stripe-ios: the sheet calls it when the payer taps Pay by card, and sends the pm_… id it returns.

A CardCollector built on Stripe
import StripePaymentsUI
import WajubMobile

final class StripeCardCollector: CardCollector {
    @MainActor
    func collectPaymentMethod(_ request: CardCollectionRequest) async throws -> String? {
        STPAPIClient.shared.publishableKey = request.publishableKey
        // CardEntryScreen is your own screen with an STPPaymentCardTextField, presented over the sheet.
        guard let card = await CardEntryScreen.present(amount: request.amount, currency: request.currency) else {
            return nil // the payer backed out
        }
        let paymentMethod = try await STPAPIClient.shared.createPaymentMethod(with: card.paymentMethodParams)
        return paymentMethod.stripeId
    }
}

options.cardCollector = StripeCardCollector()

CardCollectionRequest carries publishableKey, the Stripe key to use, amount, currency, customerEmail, customerName and language, the sheet's. Return nil when the payer backs out: the sheet stays on the card form and nothing is charged. An error you throw is shown on the card form.

Confirmation steps

Some card payments ask the payer for one more thing after Pay. Each step has its own screen.

StateScreen
OTP_REQUIREDThe code the payer received
PIN_REQUIREDThe card PIN
PHONE_REQUIREDA phone number to confirm
BIRTHDAY_REQUIREDA date of birth
ADDRESS_REQUIREDA billing address
3DS_REQUIREDIn sandbox, a 3-D Secure code sent by email. In live, 3-D Secure in Safari

A wrong code keeps the screen and shows the attempts left. A step that expires or runs out of attempts ends on the failure screen, and Try again goes back to choosing a method.

Errors

Every failure is a WajubError, a struct conforming to Error and LocalizedError, whose errorDescription is message.

FieldWhat it is for
typeWajubErrorType: .apiError, .authenticationError, .invalidRequestError, .paymentError or .rateLimitError
codeWhat to branch on. The codes are constants in WajubError.Code
messageFor the payer, in the sheet's language
declineCodeOn a decline, the reason given for it
retryableWhether Try again can work
paramThe field at fault
correlationIdThe request id to quote to Wajub support
retryAfterSecondsOn rate_limited, the seconds to wait before trying again
blockReferenceOn shield_blocked, the reference to quote to Wajub support
Reading a failed result
case .failed(let error, _):
    switch error.code {
    case WajubError.Code.insufficientFunds:
        showError(error.message) // retryable: another number or method
    case WajubError.Code.shieldBlocked:
        showError(error.message) // carries error.blockReference
    default:
        showError(error.message)
    }

Codes you will meet: insufficient_funds, payment_declined, payment_attempt_ended (refused, nothing was charged), payment_failed, shield_blocked, merchant_restricted, rate_limited, session_terminal_expired, unsupported_action, redirect_unavailable. The full list is on Mobile SDKs.

Your own UI

Import WajubMobile alone to draw your own payment screens: CheckoutController keeps the sheet's logic, and you draw only its screens.

Checkout.present(_:presenter:browser:) runs the whole checkout under your own UI, with the same rules as WajubCheckout.present: one sheet at a time, and the CheckoutResult once your sheet is gone.

  • Your CheckoutPresenting draws the controller's screen, redraws on onChange, and wires your buttons to the controller's actions, selectMethod, setPhone, submitMobileMoney, submitCard, submitStep, tryAgain, cancelPayment and the others. Call dismiss's completion once your sheet is gone, and controller.hostGone() if your sheet cannot be shown.
  • Your BrowserOpening opens provider pages: .inApp in an SFSafariViewController, calling onClose once it is closed, and .external with UIApplication.open. It returns false when nothing can open the page.
  • completion and onClose are @MainActor @Sendable.
Your own sheet and browser
import Foundation
import WajubMobile

@MainActor
final class MySheet: CheckoutPresenting {
    private var controller: CheckoutController?

    func present(_ controller: CheckoutController) {
        self.controller = controller
        controller.onChange = { [weak self] in self?.render() }
        // Show your sheet; its buttons call the controller's actions.
    }

    func dismiss(_ controller: CheckoutController, completion: @escaping @MainActor @Sendable () -> Void) {
        // Hide your sheet, then:
        self.controller = nil
        completion()
    }

    private func render() {
        guard let controller else { return }
        print(controller.state?.rawValue ?? "loading") // draw controller.screen
    }
}

@MainActor
final class MyBrowser: BrowserOpening {
    func open(_ url: URL, mode: BrowserMode, onClose: @escaping @MainActor @Sendable () -> Void) async -> Bool {
        // .inApp: present an SFSafariViewController and call onClose() once it is closed.
        // .external: return await UIApplication.shared.open(url).
        false // nothing could open the page
    }
}

@MainActor
func payWithMySheet(_ options: PresentOptions) async throws -> CheckoutResult {
    try await Checkout.present(options, presenter: MySheet(), browser: MyBrowser())
}

WajubSession, the lower-level client of one payment, is documented in the package's README.

Privacy

To make the payment, the SDK sends Wajub what the payer types. For fraud prevention, it also sends basic device information and a random install identifier, which is not the advertising identifier.

WajubMobile ships a privacy manifest, which Xcode adds to your app's privacy report. It declares no tracking. It does not fill in App Store Connect for you: under App Privacy, declare what the SDK sends together with what your app collects on its own. What to declare, category by category, is on Mobile SDKs.

Testing

A payment your server creates with a sandbox key puts the whole flow in sandbox, sheet included, and the sheet shows a "Test mode" badge. The test numbers and cards are on Test scenarios.

What did you think of this content?