# 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`**: version 1.0.0, GA, Swift Package Manager, iOS 15+, Swift 5.9+ (Xcode 15+)

## Install

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

```swift title="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"),
    ]),
]
```

| Requirement  | Value                                                               |
| ------------ | ------------------------------------------------------------------- |
| iOS          | 15.0 or later                                                       |
| Swift        | 5.9 or later, so Xcode 15 or later                                  |
| Dependencies | None. Stripe is optional and lives in your app, see [Cards](#cards) |
| Target       | An app, not an app extension                                        |

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

| Product         | What it holds                                                                                                               |
| --------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `WajubMobile`   | The models, the errors, the Mobile Money helpers, and what you need to draw [your own payment screens](#your-own-ui). No UI |
| `WajubMobileUI` | The 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`](https://docs.wajub.com/api/payments/create) and your
secret key, then hand its `authorization_token` to the app through your own endpoint.

```swift title="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.

```swift title="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](https://docs.wajub.com/developer-tools/webhooks/quickstart). 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.

| Option             | Type                 | Default                | What it does                                                                                                                                     |
| ------------------ | -------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `sessionToken`     | `String`             | Required               | The payment's `authorization_token`                                                                                                              |
| `locale`           | `String?`            | `nil`                  | `"fr"` or `"en"`. Without it, the payment's language, else the device's                                                                          |
| `appearance`       | `Appearance?`        | `nil`                  | The sheet's look, see [Appearance](#appearance)                                                                                                  |
| `loader`           | `LoaderStyle`        | `.skeleton`            | `.skeleton`, pulsing placeholder blocks, or `.spinner`                                                                                           |
| `readyTimeout`     | `Int`, milliseconds  | `15000`                | Past it, a sheet still loading shows "We couldn't load the payment" with **Retry** and reports `ready_timeout` to `onLoadError`. `0` disables it |
| `returnURL`        | `String?`            | `nil`                  | An `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      |
| `mobileMoney`      | `MobileMoneyOptions` | `MobileMoneyOptions()` | See [Mobile Money](#mobile-money)                                                                                                                |
| `cancelOnDismiss`  | `Bool`               | `true`                 | Closing the sheet before any attempt cancels the payment. `false` leaves it open so you can present it again                                     |
| `autoCloseSuccess` | `Int`, milliseconds  | `3000`                 | Before the success screen closes itself. `0` keeps it                                                                                            |
| `callbacks`        | `CheckoutCallbacks`  | `CheckoutCallbacks()`  | See [Callbacks and states](#callbacks-and-states)                                                                                                |
| `cardCollector`    | `CardCollector?`     | `nil`                  | Your Stripe card collector, see [Cards](#cards). Without one, Stripe card payments are not offered                                               |

```swift title="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.

| Callback           | Payload                                                                                                                       | When                                                                                            |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `onReady`          | `ReadyEvent`: `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                             |
| `onStateChange`    | `StateChangeEvent`: `state`, `method` (`mobile_money`, `card`, `wallet` or `unknown`)                                         | After `onReady`, then on every state change                                                     |
| `onLoadError`      | `WajubError`                                                                                                                  | The sheet cannot offer a payment                                                                |
| `onPaymentStarted` | `PaymentStartedEvent`: `method`, `channel`                                                                                    | The payment request is accepted. From now on, closing the sheet resolves `.processing`          |
| `onRedirect`       | `RedirectEvent`: `url`, `method`                                                                                              | Right before a provider page opens                                                              |
| `onSuccess`        | `PaymentSuccess`                                                                                                              | The payment succeeded, with `method` `"unknown"` when it was already paid when the sheet opened |
| `onError`          | `WajubError`                                                                                                                  | Every failure the payer sees, retryable ones included. Field validation is not reported         |
| `onCancel`         | `CancelEvent`: `reason`, `redirectURL`                                                                                        | The sheet closes as `.cancelled`                                                                |
| `onComplete`       | `CheckoutResult`                                                                                                              | The sheet closes, with what `present` resolves with                                             |

```swift title="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](https://docs.wajub.com/libraries/sdks/mobile#states).

## Results

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

| Case                              | When                                                                                                                                       |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `.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 closes                                                                       | Result                                                                                                                 |
| -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| 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](https://docs.wajub.com/libraries/sdks/mobile#cancelling-and-closing).

## Appearance

`PresentOptions.appearance` sets the sheet's look. The keys, presets and variables are on
[Appearance](https://docs.wajub.com/libraries/components/appearance).

```swift title="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.

| `MobileMoneyOptions` | Default   | What it does                                                                                                                                             |
| -------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `country`            | `nil`     | The country to start on, ISO-2. Without it, the payer's country when it is offered                                                                       |
| `countryLocked`      | `false`   | Hides 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 paid                      | What you do                                                                                                     |
| ------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| With Stripe                           | Pass a [`CardCollector`](#stripe-through-your-own-collector). Without one, Stripe card payments are not offered |
| On the payment provider's secure page | Nothing. The sheet asks for the contact details the provider needs, then opens its page in Safari               |
| In sandbox                            | Nothing. 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.

```swift title="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.

| State               | Screen                                                                     |
| ------------------- | -------------------------------------------------------------------------- |
| `OTP_REQUIRED`      | The code the payer received                                                |
| `PIN_REQUIRED`      | The card PIN                                                               |
| `PHONE_REQUIRED`    | A phone number to confirm                                                  |
| `BIRTHDAY_REQUIRED` | A date of birth                                                            |
| `ADDRESS_REQUIRED`  | A billing address                                                          |
| `3DS_REQUIRED`      | In 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`.

| Field               | What it is for                                                                                                      |
| ------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `type`              | `WajubErrorType`: `.apiError`, `.authenticationError`, `.invalidRequestError`, `.paymentError` or `.rateLimitError` |
| `code`              | What to branch on. The codes are constants in `WajubError.Code`                                                     |
| `message`           | For the payer, in the sheet's language                                                                              |
| `declineCode`       | On a decline, the reason given for it                                                                               |
| `retryable`         | Whether **Try again** can work                                                                                      |
| `param`             | The field at fault                                                                                                  |
| `correlationId`     | The request id to quote to Wajub support                                                                            |
| `retryAfterSeconds` | On `rate_limited`, the seconds to wait before trying again                                                          |
| `blockReference`    | On `shield_blocked`, the reference to quote to Wajub support                                                        |

```swift title="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](https://docs.wajub.com/libraries/sdks/mobile#errors).

## 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`.

```swift title="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](https://github.com/wajubhq/wajub-ios).

## 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](https://docs.wajub.com/libraries/sdks/mobile#privacy).

## 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](https://docs.wajub.com/developer-tools/testing/test-scenarios).

- [Mobile SDKs](https://docs.wajub.com/libraries/sdks/mobile): States, results and error codes.
- [Create a payment](https://docs.wajub.com/api/payments/create): The server call that produces the token.
- [Webhooks](https://docs.wajub.com/developer-tools/webhooks/quickstart): The confirmation that ships the order.
- [Appearance](https://docs.wajub.com/libraries/components/appearance): The appearance keys and presets.
- [Flutter](https://docs.wajub.com/libraries/sdks/flutter): The SDK for Flutter apps.
- [React Native](https://docs.wajub.com/libraries/sdks/react-native): The SDK for React Native apps.
- [Android](https://docs.wajub.com/libraries/sdks/kotlin): The SDK for Android apps, in Kotlin and Compose.
