Skip to content
developers

Handle errors

Show the merchant a clear message for every way an app switch can fail, including error responses, voided sales, and missing returns.

Prerequisites: Authentication · Run a sale

Errors can occur from when you pair your app to when you get the result of a sale. Mobile Sync doesn't show the merchant a message when an error occurs, so your app must show one. To help merchants, program your app to recognize each type of error and show a message that tells the merchant what to do next.

The following types of error can occur:

Note: The code snippets on this page use placeholder functions for your app's own interface. Replace them with your own code:

  • showMessage(_:) shows a message to the merchant.
  • askToPairAgain() asks the merchant to pair again.
  • showCheckStatusButton() shows a Check status button. When the merchant selects the button, call the checkStatus() function.

The code also uses the variables that you set in Run a sale, such as isWaitingForSaleReturn and pendingSale, and the pair and unpair functions from Connect your app to Mobile Sync.

The reader identifier is out of date

If the reader identifier is out of date, your app must pair with Mobile Sync again. The reader identifier becomes out of date when:

  • Our gateway doesn't recognize the reader identifier, for example, the merchant reinstalled Mobile Sync.
  • Mobile Sync returns notProvisioned because it was reset.
  • Mobile Sync is no longer installed, so canOpenURL returns false.

Tell the merchant that they need to pair again, and never delete the stored reader identifier without telling them. When the merchant agrees, use the following code to delete the old reader identifier and send a new pairing request.

swift
/// Call when the merchant agrees to pair again.
func pairAgain(openURL: (URL) -> Void) {
    unpair()              // forget the old reader identifier, and disable the Pay button
    pair(openURL: openURL)
}

The sale doesn't start on Mobile Sync

A sale doesn't start if Mobile Sync isn't ready, or if our gateway rejects your request. If our gateway rejects your request, Mobile Sync waits for a request that isn't coming.

Mobile Sync isn't ready

When Mobile Sync isn't ready, AppSwitchTransaction.run stops and throws an AppSwitchError. The App Switch Kit doesn't send your request.

ErrorCauseWhat to show the merchant
wsUnavailableMobile Sync couldn't connect to our gateway, for example, because the iPhone is offline.Check the internet connection, and then try again.
readerUnavailableThe card reader in Mobile Sync couldn't start.Open Mobile Sync to see the details.
readyTimeoutMobile Sync didn't send its ready signal within 30 seconds.Try again.

Our gateway rejects your request

If our gateway rejects your request, run also throws the error. For example, our gateway might reject the request because the amount isn't valid, or because it doesn't recognize the reader identifier.

Program your app to handle the errors that run throws and shows the merchant a message. The code in Step 3 of Run a sale calls it when the task throws an error.

If our gateway rejected your request, Mobile Sync is already open and waiting. The code tells Mobile Sync that no request is coming, so that Mobile Sync returns to your app immediately. For more information, go to Tell Mobile Sync that your request failed.

Example code

swift
import AppSwitchGatewayReference
import AppSwitchOrchestration
import Foundation

/// True when our gateway doesn't recognize the reader identifier that your app stored.
func isUnknownDevice(_ error: Error) -> Bool {
    if case GatewayError.http(let status, _) = error { return status == 404 }
    return false
}

/// Called by Run a sale, Step 3 when the task throws an error.
func handleStartError(_ error: Error) {
    // Your app canceled the sale. See Cancel a sale.
    if error is CancellationError || (error as? URLError)?.code == .cancelled { return }

    isWaitingForSaleReturn = false

    // Mobile Sync wasn't ready, so the kit didn't send your request.
    if let switchError = error as? AppSwitchError {
        switch switchError {
        case .wsUnavailable:
            showMessage("Check the internet connection, and then try again.")
        case .readerUnavailable:
            showMessage("Open Mobile Sync to see the details.")
        case .readyTimeout:
            showMessage("Mobile Sync didn't respond. Try again.")
        }
        return
    }

    // Our gateway rejected your request. Tell Mobile Sync that no request is coming.
    reportPostFailure()

    if isUnknownDevice(error) {
        askToPairAgain()                       // pair with Mobile Sync again
    } else {
        showMessage(error.localizedDescription)
    }
}

Mobile Sync waits for a request that isn't coming

Our App Switch Kit and our gateway can accept the switch and bring Mobile Sync online, and then our gateway rejects your request. If this happens, Mobile Sync waits for the sale and the iPhone stays on the Mobile Sync screen until the instruction timeout ends. To shorten the wait, you can:

Change the instruction timeout

After Mobile Sync is ready, it waits 30 seconds for your request. If no request arrives, Mobile Sync returns to your app with status=timeout.

If you want to change the timeout for a sale, for example, if you encounter slow network conditions, add instructionTimeoutInSeconds to the switch URL. Mobile Sync accepts only values between 1 and 300 seconds.

swift
import AppSwitchContract
import Foundation

func switchURL(timeoutSeconds: Int) -> URL? {
    guard let base = AppSwitchURL.switchURL(targetScheme: MobileSync.scheme, callback: Callback.sale),
          var components = URLComponents(url: base, resolvingAgainstBaseURL: false)
    else { return nil }

    var items = components.percentEncodedQueryItems ?? []
    items.append(URLQueryItem(name: AppSwitchURL.instructionTimeoutQueryItem, value: String(timeoutSeconds)))
    components.percentEncodedQueryItems = items
    return components.url
}

Tell Mobile Sync that your request failed

If your request fails, send the com.payroc.appswitch.instruction.failed signal. Mobile Sync then returns to your app immediately with status=failed. The signal has no payload, and Mobile Sync doesn't confirm that it received it. The handleStartError function in Our gateway rejects your request calls the following code.

swift
import AppSwitchContract

/// Tell Mobile Sync that no request is coming.
func reportPostFailure() {
    AppSwitchInstructionSignalName.post(AppSwitchInstructionSignalName.instructionFailed)
}

Mobile Sync returns an error

If there is an error with Mobile Sync, Mobile Sync can switch back to your app with an error query item in the return URL. This can happen in the response to a pairing request and in the response to a sale or a signature capture.

Mobile Sync can return the following errors in the response to a pairing request or a sale request:

ErrorWhat it meansWhat your app does
unsupportedSchemeYour app opened a Mobile Sync scheme that isn't one of the switch schemes that you configured in your app.Correct the scheme in your app. This is a problem with your integration, so you shouldn't see it in production.
notProvisionedA sale reached a version of the Mobile Sync app that is new or was reset, so the reader identifier that your app stored is out of date.Pair your app with Mobile Sync again.
standaloneModeMobile Sync is set up, but it's in Standalone mode, so it can't receive requests from Payroc Cloud. Mobile Sync returns this for a sale, a signature capture, and a pairing request.Keep the pairing, because the reader identifier doesn't change when the merchant switches mode. Ask the merchant to switch Mobile Sync back to Payroc Cloud in its App settings.
modeSwitchInProgressA pairing request reached Mobile Sync while the merchant is changing Mobile Sync's mode.Keep the pairing. Ask the merchant to finish the mode switch in Mobile Sync, and then pair again.
tapToPayDisabledA pairing request reached a terminal that has Tap to Pay turned off, so the terminal can't take sales.Show a message that tells the merchant to contact support.

A pairing response contains an error

If the response to a pairing request contains an error, your app doesn't store a reader identifier. Show the merchant a message for the error. For example, the code in Step 3 of Connect your app to Mobile Sync calls the errorMessage(for:) function.

A sale response contains an error

For a sale or a signature capture, only notProvisioned and standaloneMode mean that Mobile Sync didn't run the request. There's no result to get from our gateway, so show the merchant a message.

For any other error, get the result from our gateway as you normally do.

The following code creates a message for each error and handles the two errors that mean the sale didn't run. If the error is notProvisioned, the code also unpairs the old reader identifier and asks the merchant to pair again.

swift
import AppSwitchContract

/// A message for the merchant for an `error` code in a response from Mobile Sync.
func errorMessage(for code: String?) -> String {
    switch code {
    case AppSwitchURL.unsupportedSchemeError:
        "This app opened Mobile Sync in the wrong way."
    case AppSwitchURL.notProvisionedError:
        "Mobile Sync was reset. Pair again to continue."
    case AppSwitchURL.standaloneModeError:
        "Mobile Sync is in Standalone mode. Switch it back to Payroc Cloud in its App settings."
    case AppSwitchURL.modeSwitchInProgressError:
        "Mobile Sync is switching modes. Finish the switch there, and then pair again."
    case AppSwitchURL.tapToPayDisabledError:
        "Tap to Pay is turned off for this terminal. Contact support."
    case .some(let other):
        "Mobile Sync couldn't run the request (\(other))."
    case .none:
        "Mobile Sync didn't return a result."
    }
}

/// Call for a sale response that contains notProvisioned or standaloneMode. See Run a sale, Step 4.
func handleSaleError(_ code: String) {
    saleGeneration += 1                        // the sale is no longer current; see Cancel a sale
    pendingSale?.cancel()                      // the sale never ran
    isWaitingForSaleReturn = false
    showMessage(errorMessage(for: code))

    if code == AppSwitchURL.notProvisionedError {
        unpair()                               // the reader identifier is out of date
        askToPairAgain()                       // pair with Mobile Sync again
    }
    // For standaloneMode, keep the pairing.
}

The sale is voided or doesn't complete

When a sale ends, Mobile Sync returns to your app with a status that tells you what Mobile Sync encountered. The status is only an indication of the outcome. Use it to decide what to show the merchant while you retrieve the instruction from our gateway.

StatusWhat happenedWas the customer charged?
completedMobile Sync got a response to the sale.Yes, if our gateway approved the sale.
cancelledThe merchant or our gateway canceled the sale.No
failedA terminal error occurred before authorization, or your request failed.No
voidedA network failure occurred during authorization or surcharge reversal. Mobile Sync saves the pending reversal and sends it again when it's online.Maybe, until the reversal is processed.
timeoutThe sale was idle for too long, or no request arrived.No
unavailableMobile Sync couldn't connect to our gateway.No
readerUnavailableThe card reader in Mobile Sync couldn't start.No

The instruction contains more information about the issue and the true status of the sale. Use the following table to decide what to show the merchant after you get the instruction from our gateway. If the sale is still in progress, you can offer an option to check the status again.

Our gateway saysStatusWhat to showOffer Check status?
The sale is completedAny, including voidedThe receipt, as in Step 5 of Run a sale. For voided, also read Mobile Sync voids the sale.No
The sale is still in progressvoidedThe payment is voided and a reversal is pending.Yes
The sale is still in progressAny other statusThe sale is still processing.Yes
The sale ended but isn't completedvoidedMobile Sync voided the payment. Include the status from our gateway.No
The sale ended but isn't completedAny other statusThe status and text from our gateway.No

The following code handles the cases where the sale isn't completed. If our gateway is still processing the sale, the code keeps isWaitingForSaleReturn as true, so that your app can check again.

Important: Don't write the full response from our gateway to a log. It can contain card data.

swift
import AppSwitchContract
import AppSwitchGatewayReference

/// Call when our gateway doesn't report the sale as completed.
func handleIncompleteSale(_ outcome: InstructionOutcome, hint: AppSwitchURL.ReturnStatus?) {
    if outcome.stillInProgress {
        showMessage(hint == .voided
            ? "The payment is voided and a reversal is pending."
            : "The sale is still processing.")
        showCheckStatusButton()                // the button calls checkStatus()
        return
    }

    isWaitingForSaleReturn = false
    if hint == .voided {
        showMessage("Mobile Sync voided the payment. Status: \(outcome.status)")
    } else {
        // Don't show outcome.body for a completed sale. It's the full payment, which can contain card data.
        showMessage(outcome.succeeded
            ? "The sale completed, but your app couldn't read the payment details. Check the status again."
            : outcome.body)                    // for example, "cancelled: <the error from our gateway>"
    }
}

Mobile Sync voids the sale

A voided status from Mobile Sync means that Mobile Sync can't confirm whether our gateway received the result. Mobile Sync saves the pending reversal and sends it when Mobile Sync is back online.

If you retrieve the instruction and our gateway reports the sale as completed, your app can show the receipt. However, our gateway might have approved the sale while a reversal is still in progress.

Important: Before the merchant hands over goods for a sale that returned voided, retrieve the sale and check if our gateway reversed it.

To retrieve the sale, send a GET request to /payments with the orderId that you stored in Run a sale. If our gateway reversed the sale, it returns a response that contains a status of reversal.

swift
import AppSwitchGatewayReference

/// True when our gateway shows that the sale was reversed.
func isReversed(orderId: String, terminalId: String, using client: PayrocGatewayClient) async -> Bool {
    let payments = (try? await client.listPayments(orderId: orderId, processingTerminalId: terminalId)) ?? []
    return payments.first?.isReversed ?? false
}

You can't confirm the result

Sometimes your app can't get the result from our gateway. Don't tell the merchant that the sale succeeded or failed. Keep the instruction ID, tell the merchant that you can't confirm the result, and offer a Check status button.

You can't confirm the result in the following scenarios:

The response never arrives

If the merchant switches back to your app or closes Mobile Sync during a sale, Mobile Sync cancels the sale and your app gets no response. When your app becomes active, wait 1.5 seconds for a response, and then check with our gateway up to three times, three seconds apart.

Mobile Sync can send a late cancelled response the next time the merchant opens it, for up to five minutes. For more information about how to handle this scenario, go to The merchant leaves Mobile Sync.

Your app can't reach our gateway

If the iPhone's network connection is down after a sale, the first check can fail. Our gateway reports the sale as in progress until Mobile Sync reconnects and sends its result.

Our gateway returns a 404

Our gateway doesn't recognize the reader identifier that your app stored. You need to program your app to pair with Mobile Sync again to get a new reader identifier. For more information, go to The reader identifier is out of date.

The following code handles an error when your app tries to get the result. Step 5 of Run a sale calls it.

swift
/// Call when your app can't get the result from our gateway.
func handleUnconfirmedSale(_ error: Error) {
    if isUnknownDevice(error) {
        isWaitingForSaleReturn = false
        askToPairAgain()                       // pair with Mobile Sync again
        return
    }

    // Keep the instruction ID, and check again when your app becomes active. See Cancel a sale.
    isWaitingForSaleReturn = true
    showMessage("We couldn't confirm the result. Check your internet connection, and then check the status again.")
    showCheckStatusButton()
}

Check the status again

When the merchant selects Check status, call the following checkStatus() function. It checks the instruction with our gateway once, and works for a sale and for a signature capture. It uses the activeClient, activeInstructionId, activeInstructionType, and handledInstructionIds variables from Step 3 of Run a sale, which stay set after Mobile Sync returns.

If your app doesn't capture signatures, remove the .signature branch.

swift
import AppSwitchGatewayReference

/// Call when the merchant selects Check status. Works for a sale and for a signature capture.
func checkStatus() {
    guard let client = activeClient, let instructionId = activeInstructionId else { return }
    let type = activeInstructionType
    Task {
        do {
            let outcome = try await client.completeInstruction(type: type,
                                                               instructionId: instructionId,
                                                               maxAttempts: 1)
            if outcome.stillInProgress {
                showCheckStatusButton()               // still processing, so the merchant can check again
                return
            }
            isWaitingForSaleReturn = false
            handledInstructionIds.insert(instructionId)
            if type == .signature {
                pendingSignature = nil                // the signature capture is finished
                if outcome.succeeded {
                    showSignature(ReceiptParser.rows(fromJSON: outcome.body))   // see Capture a signature
                } else {
                    showMessage(outcome.status)
                }
            } else {
                showResult(outcome, hint: nil)        // from Run a sale, Step 5
            }
        } catch {
            handleUnconfirmedSale(error)
        }
    }
}

Next step

After you handle errors, you can submit your app to the App Store.

Browse guides

Search documentation

API reference169
Guides131
Knowledge38
legal1
Solutions32
Workflows74
↑↓highlight↵openView all search results

Menu

Theme

Sign out

Your saved plans remain in your organization. This browser’s private draft and account view will be cleared.

Talk to an engineer