# iOS SDK

> Install and configure the Onerway iOS SDK, present native checkout, and handle client results, app returns, and Apple Pay.

The SDK provides the payment interface and handles payment interactions. Your server creates payments, confirms final results, and fulfills orders.

## Prerequisites and environment

The SDK requires iOS 13 or later. The Swift module name is `OnerwayPayments`.

Prepare a merchant account and server-side signing credentials for the same environment. Your server must provide endpoints to create payments and receive notifications. Obtain the SDK package. Keep credentials on your server only. Configure `returnUrl` when creating payments that require authentication or an external redirect. Complete the relevant wallet configuration before enabling a native wallet.

## Install the SDK

### Obtain the SDK package

Request the `onerway-ios.xcframework.zip` release package from Onerway. Refer to the Onerway release notes for the version.

### Add the SDK to your Xcode project

1. Extract the ZIP file to obtain `onerway-ios.xcframework`.
2. Drag the XCFramework into your Xcode project and select **Copy items if needed**.
3. Under **Add to targets**, select your App Target.
4. Open **Target > General > Frameworks, Libraries, and Embedded Content**.
5. Set `onerway-ios.xcframework` to **Embed & Sign**.
6. Confirm that the app's Deployment Target is iOS 13 or later.

### Verify installation

Add the following import to a Swift file in your App Target:

```swift
import OnerwayPayments
```

Build for both a simulator and a physical device. If you see `No such module 'OnerwayPayments'`, check that the XCFramework belongs to the current Target. If the app reports `Library not loaded` at launch, check that the framework is set to **Embed & Sign**.

## Initialization and configuration

### Runtime environment

The SDK environment must match the environment in which your server created the payment. Always setting `environment` explicitly is recommended; avoid relying on its default value.

`environment` selects the SDK runtime environment and has type `OnerwayEnvironment`.

| Value | Environment | Description |
| --- | --- | --- |
| `PRODUCTION` | Production | Uses production merchant configuration |
| `SANDBOX` | Sandbox | Uses sandbox accounts and payment sessions |

The default is `PRODUCTION`. For sandbox, pass `OnerwayEnvironment.SANDBOX`.

### Configure each presentation

You can configure `environment`, `locale`, `themeMode`, and `applePay` each time you call `OnerwayCheckout.present`. No separate global initialization is needed.

### Appearance modes

| `themeMode` | Description |
| --- | --- |
| `FOLLOW_HOST` | Follows the host app's light or dark appearance and subsequent changes; the default |
| `LIGHT` | Always light |
| `DARK` | Always dark |

### Languages

`locale` supports these language tags:

`ar`, `de`, `en`, `es`, `fi`, `fr`, `it`, `ja`, `ko`, `nl`, `no`, `pl`, `pt`, `ru`, `sv`, `th`, `vi`, `zh-Hans`, `zh-Hant`.

When omitted, the SDK reads the app or system language. Unsupported languages fall back to `en`.

## Obtain a payment session and present checkout

### Obtain a payment session from your server

1. Your app calls your own server's payment creation endpoint.
2. Your server uses `merchantNo` and its signing credentials to sign and submit a [Create SDK transaction](/payments/api-reference/endpoints/sdk-create-transaction) request. Set `paymentMode=APP` and `osType=IOS`. Follow that endpoint's requirements for all other parameters and conditionally required fields.
3. Your server stores the mapping between your order, `paymentId`, and any returned transaction identifiers, then sends `paymentId` to your app.
4. Your app calls the native SDK with a non-empty `paymentId`.

Keep signing keys, `secret`, request signing, and Webhook signature verification on your server.

Your session endpoint can return an object such as the following. You define the endpoint name and response format:

```json
{
  "merchantTxnId": "YOUR_ORDER_ID",
  "paymentId": "PAYMENT_ID_FROM_ONERWAY"
}
```

For payments that require authentication or an external redirect, configure your HTTPS `returnUrl` when creating the payment. Use `notifyUrl` to receive payment notifications on your server. The return URL restores the customer interaction; notifications confirm the order. Each serves a separate purpose.

### Call the SDK

Call the SDK from an existing, visible `UIViewController`. The controller below is an example; you can integrate the call into your existing payment entry point.

```swift
import OnerwayPayments
import UIKit

final class CheckoutViewController: UIViewController {
    private var isPresentingCheckout = false

    @MainActor
    func presentCheckout(paymentId: String) {
        guard !isPresentingCheckout else { return }
        guard !paymentId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
            showMessage("paymentId must not be empty")
            return
        }
        guard viewIfLoaded?.window != nil else {
            showMessage("The current page is not visible yet")
            return
        }

        isPresentingCheckout = true
        OnerwayCheckout.present(
            from: self,
            paymentId: paymentId,
            locale: nil,
            themeMode: OnerwayThemeMode.FOLLOW_HOST,
            environment: OnerwayEnvironment.PRODUCTION
        ) { [weak self] result in
            self?.isPresentingCheckout = false
            self?.handlePaymentResult(result)
        }
    }

    private func handlePaymentResult(_ result: PaymentResult) {
        if result.reason?.type == PaymentReasonType.canceled {
            showOrderPage()
            return
        }

        switch result.paymentStatus {
        case "S":
            verifyOnMerchantServer(paymentId: result.paymentId)
        case "P", "A":
            showPending(paymentId: result.paymentId)
        case "N":
            showNotCompleted(paymentId: result.paymentId)
        case nil:
            showCheckoutError(code: result.reason?.code)
        default:
            verifyOnMerchantServer(paymentId: result.paymentId)
        }
    }

    // Implement these methods in your app. Keep the current order and confirm it
    // with your server, including canceled, N, empty, or unknown results.
    // Do not automatically create another payment.
    private func showMessage(_ message: String) {}
    private func showOrderPage() {}
    private func verifyOnMerchantServer(paymentId: String) {}
    private func showPending(paymentId: String) {}
    private func showNotCompleted(paymentId: String) {}
    private func showCheckoutError(code: String?) {}
}
```

`from` must be a currently visible `UIViewController` attached to a Window. Do not pass a newly created controller that has not been displayed.

### Parameters

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `from` | `UIViewController` | Yes | — | The currently visible host view controller, already attached to a Window |
| `paymentId` | `String` | Yes | — | Non-empty payment session identifier created by your server |
| `locale` | `String?` | No | `nil` | Checkout language; see Languages for supported values |
| `themeMode` | `OnerwayThemeMode` | No | `FOLLOW_HOST` | Appearance mode: `FOLLOW_HOST`, `LIGHT`, or `DARK` |
| `environment` | `OnerwayEnvironment` | No | `PRODUCTION` | Runtime environment: `PRODUCTION` or `SANDBOX` |
| `applePay` | `ApplePayConfiguration?` | No | `nil` | Additional client configuration for Apple Pay; see Apple Pay configuration |
| `completion` | `(PaymentResult) -> Void` | Yes | — | Receives the client result for this checkout on the main thread |

The client and server must use the same environment. Call on the main thread, and prevent duplicate presentations in your app. After checkout closes normally, the SDK calls back once on the main thread. An empty `paymentId` returns `sdk_error / invalid_payment_id` without waiting for the page to appear.

## Handle client payment results

### PaymentResult

| Field | Type | Description |
| --- | --- | --- |
| `paymentId` | `String` | Payment session identifier |
| `transactionId` | `String?` | Server transaction identifier; `nil` until available |
| `paymentMethod` | `String?` | Payment method obtained by the SDK; `nil` until available |
| `paymentStatus` | `String?` | Non-empty values are `S`, `P`, `A`, or `N`; `nil` on cancellation or error, in which case read `reason` |
| `reason` | `PaymentReason?` | Cancellation or error reason |

### Payment statuses and merchant actions

When checkout closes, handle `paymentStatus` as follows:

| `paymentStatus` | Meaning | Merchant action |
| --- | --- | --- |
| `S` | The SDK has received a successful payment result | Display success and fulfill the order after your server confirms the result |
| `P` | The payment is processing or its result still needs confirmation | Display a confirmation-in-progress message and continue querying from your server |
| `A` | The SDK has received an authorized result | Follow your server's pre-authorization and capture results; do not treat this as a completed charge |
| `N` | The SDK has received a payment-not-completed result | Confirm the order status on your server; do not automatically create a new payment based only on this value |

When the customer cancels or the SDK exits with an error, `paymentStatus` is empty. Read `reason.type` and `reason.code` for the cause. Query your server to confirm the order status after cancellation, an error, or a network timeout.

Branch on `reason.type` and `reason.code`. Do not determine order status from error message text.

The SDK handles payment retries, authentication, and external redirects. If the customer only cancels wallet authorization or dismisses a recoverable error message, checkout remains open and no completion callback is triggered.

`PaymentResult`, the return URL, and the SDK interface are for client interactions. Base fulfillment, shipping, account top-ups, and accounting on a signature-verified Webhook or a result confirmed by a server-side query. Process each merchant order idempotently. Completion of the client flow does not mean the server-side order has reached a final state.

### Reason types

| `reason.type.rawValue` | Description |
| --- | --- |
| `canceled` | The customer closed the entire checkout |
| `validation_error` | Local parameter or form validation error; reserved, not returned in the current version |
| `api_error` | Payment API or backend business error |
| `sdk_error` | SDK configuration, invocation, network, or internal error |

Closing the Apple Pay authorization sheet only cancels that wallet operation. Checkout stays open, and the SDK does not immediately call back to your app.

### PaymentReason

| Field | Type | Description |
| --- | --- | --- |
| `type` | `PaymentReasonType` | Reason category; see Reason types |
| `code` | `String` | Reason code for application logic and troubleshooting |
| `message` | `String?` | Display or diagnostic information; do not use it to determine payment status |
| `param` | `String?` | Related parameter |
| `declineCode` | `String?` | Reserved; always `nil` in the current version |
| `errors` | `[PaymentFieldError]?` | Reserved; always `nil` in the current version |

Optional fields are `nil` when no corresponding information is available.

### Payment identifiers

| Identifier | Source | Purpose |
| --- | --- | --- |
| `merchantTxnId` | Generated by your server | Associates the payment with your order |
| `paymentId` | Create SDK transaction response | Opens checkout and identifies the payment session |
| `transactionId` | SDK result callback | Identifies the server transaction |

`transactionId` is the server transaction identifier obtained by the SDK and is `nil` until available. The same `paymentId` may have different transaction identifiers after payment attempts or retries. Associate the transaction using the value in the current callback, and confirm its final status on your server.

## Handle authentication, external redirects, and app returns

When authentication or an external payment is required, the SDK opens an in-app browser (`SFSafariViewController`; some payment methods open a third-party app). After payment, the platform redirects to the `returnUrl` configured when the payment was created, and the system opens your app. **The platform performs this redirect. The SDK does not need to participate, and you do not need to pass the return URL to the SDK.** Handling after return depends on whether the original SDK session is still active; see [After returning to the app](#after-returning-to-the-app).

### Configure the return URL

1. When creating a payment on your server, set `returnUrl` to a URL that opens your app. An HTTPS Universal Link is recommended; complete the Associated Domains and AASA configuration below. Confirm support with Onerway before using a custom scheme.
2. Receive the return through your app’s existing routing, then follow [After returning to the app](#after-returning-to-the-app). No additional page or Delegate logic is required for this purpose.

### Use an HTTPS Universal Link

#### Configure Associated Domains

Add **Associated Domains** under **Target > Signing & Capabilities**:

```text
applinks:pay.example.com
```

#### Publish apple-app-site-association

Publish a file without an extension at:

```text
https://pay.example.com/.well-known/apple-app-site-association
```

```json
{
  "applinks": {
    "details": [
      {
        "appIDs": ["TEAM_ID.com.example.app"],
        "components": [
          { "/": "/payment/return*" }
        ]
      }
    ]
  }
}
```

Replace the Team ID, Bundle ID, domain, and path. The server must return JSON directly over HTTPS, without redirecting to a login page or returning HTML.

### After returning to the app

- If the original SDK session is still active, the customer can close its in-app browser if it remains visible after returning to the app. The SDK automatically queries the payment status and displays the result after the browser closes; your app does not need to listen for browser closure or confirm the payment again. After checkout closes normally, the `present` completion returns the client result once on the main thread.
- If the app has restarted, the session has ended, or the query fails, confirm the result with your server from your order page.
- Do not determine payment results from return URL parameters such as `status` or amount. Use a server-side query or Webhook for the final status.

### Optional: pass a return link to the SDK

#### `OnerwayCheckout.handleReturnURL(_ url: URL) -> Bool`

To pass a valid return link to a payment session that is still active, call the following from your app's existing Universal Link handler. The SDK can then close the browser automatically and continue processing. This step is optional:

```swift
if OnerwayCheckout.handleReturnURL(url) {
    return
}
// If the SDK does not accept the URL, query your server from your order page.
```

A `true` return value from `handleReturnURL` only means that the SDK accepted the URL. It does not mean that payment succeeded. Returning to the app and querying the payment work without this call: the SDK queries automatically after the customer closes the browser. If the app restarts or the session ends, confirm the result from your order page.

#### Optional session restoration API

`OnerwayCheckout.resumeFromReturn(from:url:locale:themeMode:environment:applePay:completion:) -> Bool`

Use this when you need to rebuild a lost SDK session. It is not required for the standard flow. After an app restart, you can also confirm the result directly from your order page.

The types of `from`, `locale`, `themeMode`, `environment`, `applePay`, and `completion` match those of `present`. Replace `paymentId` with `url: URL` so the SDK can identify and restore the session.

`true` only means the SDK accepted the return link; it does not mean payment succeeded. `false` means the SDK did not handle it, and your app should return to its order page and query your server. Your app must first validate the HTTPS scheme, domain, and path. Do not trust a status carried in the return URL.

## Platform wallets

### Configure Apple Pay for your app

Before enabling Apple Pay, follow [Apple's configuration guide](https://developer.apple.com/help/account/capabilities/configure-apple-pay/) to configure the Merchant ID, payment processing certificate, and App Capability. Submit your app according to Apple's app release requirements.

1. Create a Merchant ID in your Apple Developer account.
2. Confirm the payment processing certificate and payment processor configuration process with Onerway. If the processor handles decryption, obtain the CSR and configure the certificate according to that process. Do not include merchant private keys or payment processing keys in your app.
3. Add **Apple Pay** under your App Target's **Signing & Capabilities**, select the correct Merchant ID, and confirm that Entitlements and signing settings match.
4. Confirm that the Merchant ID supplied by the server or supplemented by `ApplePayConfiguration.merchantIdentifier` matches the App Capability. Configure country codes and card networks according to your actual acceptance scope.
5. Verify payments using [Apple's sandbox testing guide](https://developer.apple.com/apple-pay/sandbox-testing/). Complete release verification using a release-signed app and a physical device.

Native Apple Pay requires a Merchant ID, a payment processing certificate, and the App Capability. If your app also provides web pages that accept Apple Pay, complete merchant domain verification for those pages.

### Apple Pay configuration

`applePay` provides optional additional client configuration. The SDK first uses the Apple Pay Merchant ID, order country, and card networks returned by the server, falling back to this configuration for missing values. If neither source provides card networks, it uses Visa and Mastercard.

When you pass `applePay`, the authorization sheet uses its required `merchantDisplayName`. Without `applePay`, the SDK uses the order's brand name or merchant name, or `Onerway` if neither is available.

When creating `ApplePayConfiguration`, you must provide these three string parameters. They belong to the Apple Pay configuration and are not the merchant number used by the Onerway order API.

| Field | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `merchantIdentifier` | `String` | Yes | — | Apple Pay Merchant ID; must match the Merchant ID enabled in your app's Capability |
| `countryCode` | `String` | Yes | — | Two-letter country code for the merchant's country of acceptance, such as 🇺🇸 `US` |
| `merchantDisplayName` | `String` | Yes | — | Merchant name displayed on the Apple Pay authorization sheet |
| `supportedNetworks` | `[String]` | No | `["visa", "mastercard"]` | Supported card networks; see the table below |

| `supportedNetworks` value | Card network |
| --- | --- |
| `visa`, `visacard` | Visa |
| `mastercard`, `mastercardcredit`, `mastercarddebit` | Mastercard |
| `amex`, `americanexpress` | American Express |
| `discover` | Discover |
| `maestro` | Maestro |
| `chinaunionpay`, `unionpay` | UnionPay |
| `mada` | mada |

```swift
let applePay = ApplePayConfiguration(
    merchantIdentifier: "merchant.com.example",
    countryCode: "US",
    merchantDisplayName: "Example Store",
    supportedNetworks: ["visa", "mastercard"]
)

OnerwayCheckout.present(
    from: self,
    paymentId: paymentId,
    environment: OnerwayEnvironment.PRODUCTION,
    applePay: applePay
) { [weak self] result in
    self?.handlePaymentResult(result)
}
```

The SDK displays the Apple Pay button when the server returns Apple Pay for the order and the SDK can obtain a complete wallet configuration. When the customer taps Apple Pay, the SDK first checks device and supported-card availability. If the check fails, it does not open the authorization sheet and closes checkout with `sdk_error` and code `apple_pay_unavailable`, `apple_pay_no_card`, or `apple_pay_invalid_networks`. Your app must still complete Apple Pay Capability and signing configuration.

## Optional integration examples

### SwiftUI (optional)

The SDK uses a `UIViewController` to present checkout. In a SwiftUI project, call it through an existing UIKit container or your project's Coordinator:

```swift
import OnerwayPayments
import UIKit

@MainActor
func startCheckout(from host: UIViewController, paymentId: String) {
    OnerwayCheckout.present(
        from: host,
        paymentId: paymentId,
        environment: OnerwayEnvironment.PRODUCTION
    ) { result in
        // Handle the result in your state management layer and query your server.
        handleMerchantPaymentResult(result)
    }
}
```

Implement `handleMerchantPaymentResult` to display the result and query your server. Do not create a temporary `UIViewController` that is not attached to a Window.

### Objective-C (optional)

Add a Swift Bridge to your Objective-C project:

```swift
import OnerwayPayments
import UIKit

@objc(OWCheckoutBridge)
final class OWCheckoutBridge: NSObject {
    @objc(presentFrom:paymentId:completion:)
    static func present(
        from controller: UIViewController,
        paymentId: String,
        completion: @escaping (NSDictionary) -> Void
    ) {
        OnerwayCheckout.present(
            from: controller,
            paymentId: paymentId,
            environment: OnerwayEnvironment.PRODUCTION
        ) { result in
            var value: [String: Any] = [
                "paymentId": result.paymentId,
                "transactionId": result.transactionId.map { $0 as Any } ?? NSNull(),
                "paymentMethod": result.paymentMethod.map { $0 as Any } ?? NSNull(),
                "paymentStatus": result.paymentStatus.map { $0 as Any } ?? NSNull(),
                "reason": NSNull()
            ]
            if let reason = result.reason {
                value["reason"] = [
                    "type": reason.type.rawValue,
                    "code": reason.code,
                    "message": reason.message.map { $0 as Any } ?? NSNull(),
                    "param": reason.param.map { $0 as Any } ?? NSNull(),
                    "declineCode": reason.declineCode.map { $0 as Any } ?? NSNull(),
                    "errors": reason.errors.map { errors in
                        errors.map { error in
                            [
                                "field": error.field,
                                "message": error.message,
                                "code": error.code.map { $0 as Any } ?? NSNull()
                            ] as [String: Any]
                        } as Any
                    } ?? NSNull()
                ] as [String: Any]
            }
            completion(value as NSDictionary)
        }
    }
}
```

Call this Bridge from Objective-C through the `<ProductModuleName>-Swift.h` header generated by Xcode.

## Troubleshooting, integration verification, and further reading

| Symptom | What to check |
| --- | --- |
| `No such module 'OnerwayPayments'` | Whether the XCFramework was extracted and added to the current App Target |
| `Library not loaded` | Whether the framework is set to **Embed & Sign** under **Frameworks, Libraries, and Embedded Content** |
| Simulator or device architecture error | Whether you are using the complete XCFramework and whether the package has been modified |
| Order fails to load | Whether `paymentId` is valid and was created in the environment selected by the SDK |
| Checkout does not appear | Whether `from` is a visible controller attached to a Window |
| No callback received | Whether the SDK result page is still open and whether the external flow returned to the app correctly |
| Empty `paymentStatus` | Inspect `reason.type` and `reason.code`; the status is empty for cancellation and error results |
| Universal Link does not open the app | Associated Domains, AASA, Team ID, Bundle ID, domain, and path |
| App opens on return but the order does not update | Query your server from your order page; do not rely on return URL parameters |
| Optional `handleReturnURL` call does not accept the URL | Whether `paymentId` matches and the original session still exists; this issue does not apply if you do not call the method |
| Apple Pay does not appear | Server-side configuration, Capability, Merchant ID, and wallet availability on a physical device |

When reporting an issue, provide the SDK version, app version, masked `paymentId`, occurrence time, iOS version, reproduction steps, and `reason.code`. Do not send card numbers, CVV, complete payment tokens, merchant keys, or unmasked user information.

### Integration verification

Test at least these scenarios: a normal payment; successful and canceled authentication; wallet cancellation; repeated taps; network interruption; `P/A/N` results; unknown or empty results; return to the original session after an external redirect; confirmation from your order page after an app restart; repeated return handling; and Webhooks arriving more than once or before the client result.

For each scenario, verify that app and server order mappings match and that processing is deduplicated by merchant order. Fulfill an `S` result only after server confirmation. Do not treat `A` as a successful charge, or closure or timeout as payment failure. Any `transactionId` returned to the host app's business module must come from the server-confirmed transaction ID. After testing, recheck Universal Links and native wallets using a release-signed app.

After an app interruption, restore the order and query the existing payment from your server before deciding how to continue. Do not automatically submit again while processing is in progress or the result is unknown. Do not create a new order just because the page disappeared.

### Further scenarios and references

- [Create SDK transaction](/payments/api-reference/endpoints/sdk-create-transaction): server-side fields and payment intent status definitions.
- [Webhook notifications](/payments/get-started/webhooks): signature verification, responses, retries, and idempotency rules.
- [Payment result notification](/payments/api-reference/webhooks/payment-result): results for regular payments.
- [Subscription scenarios](/payments/online-payments/scenarios/subscriptions): server-side subscription flows; do not trigger recurring charges from client success events.
