# Run a sale

Switch to Mobile Sync, send a sale instruction to our gateway, and show the result when Mobile Sync returns to your app.

**Prerequisites:** [Authentication](/api/authentication) · [Connect your app to Mobile Sync](/guides/payments/tap-to-pay-on-iphone/mobile-sync/connect-your-app-to-mobile-sync)

To run a sale, your app opens Mobile Sync, and then sends a payment instruction to our gateway. Our gateway sends the instruction to Mobile Sync, which reads the customer's card. When the sale is finished, Mobile Sync returns the merchant to your app, and your app gets the result from our gateway.

**Note:** Your app opens Mobile Sync before it sends the instruction. The App Switch Kit handles this order for you.

Your app does the following:

- Uses a gateway client to send a payment instruction to our gateway.
- Switches to Mobile Sync.
- Gets updates on the sale.
- Shows the result of the sale to the merchant.

<a id="before-you-begin"></a>
## Before you begin

The code on this page uses the following items from other pages:

- `MobileSync`, `Callback`, `pairing`, and `handlePairingReturn`, which you define in [Connect your app to Mobile Sync](/guides/payments/tap-to-pay-on-iphone/mobile-sync/connect-your-app-to-mobile-sync).
- `handleStartError`, `handleSaleError`, `handleIncompleteSale`, and `handleUnconfirmedSale`, which you define in [Handle errors](/guides/payments/tap-to-pay-on-iphone/mobile-sync/handle-errors).
- `checkForMissingReturn`, which you define in [Cancel a sale](/guides/payments/tap-to-pay-on-iphone/mobile-sync/cancel-a-sale#the-merchant-leaves-mobile-sync).

The code also uses placeholder functions for your app's own interface. Replace them with your own code:

- `showMessage(_:)` shows a message to the merchant.
- `showApproved(_:)` shows the receipt for an approved sale.
- `showDeclined(_:)` shows a message for a declined sale.

<a id="integration-steps"></a>
## Integration steps

1. [Create a gateway client](#step-1-create-a-gateway-client)
2. [Build the sale request](#step-2-build-the-sale-request)
3. [Switch to Mobile Sync and send the request](#step-3-switch-to-mobile-sync-and-send-the-request)
4. [Return to your app](#step-4-return-to-your-app)
5. [Get the result and show the receipt](#step-5-get-the-result-and-show-the-receipt)

<a id="step-1-create-a-gateway-client"></a>
## Step 1. Create a gateway client

To start each sale, you need to create a gateway client. The gateway client handles the following actions:

- Authenticating requests to our gateway.
- Sending payment information.
- Retrieving updates about payments.
- Retrieving payment information.

We provide a gateway client, `PayrocGatewayClient`, that you can use. It handles your app's requests to our gateway. It authenticates with your Payroc API key, sends the sale instruction, checks its status, and gets the payment.

Create a `PayrocGatewayClient` with your sale's configuration, and then call `beginNewInstruction()`. This gives the sale a new idempotency key and bearer token.

To create a `PayrocGatewayClient`, you need your processing terminal ID and your Payroc API key. We sent you these when you signed up with us. Load them from your own secure configuration, and don't commit them to source control. The examples in this guide refer to them as `terminalId` and `apiKey`. You don't need your Mobile Sync API key, because you use that only to set up Mobile Sync.

```swift
import AppSwitchGatewayReference

/// Create a new client for every sale.
func makeGatewayClient(readerIdentifier: String, terminalId: String, apiKey: String) -> PayrocGatewayClient {
    let config = GatewayConfig(
        readerIdentifier: readerIdentifier,   // the reader identifier that the kit stored when you paired
        terminalId: terminalId,
        apiKey: apiKey,
        currency: "USD"
    )
    let client = PayrocGatewayClient(config: config)
    client.beginNewInstruction()              // new idempotency key for this sale
    return client
}
```

By default, our reference client sends requests to our test environment. To change to our production environment, edit the following values in the `PayrocGatewayClient.swift` file:

| **Value** | **Test** | **Production** |
| --- | --- | --- |
| `baseURL` | `https://api.uat.payroc.com/v1` | `https://api.payroc.com/v1` |
| `authURL` | `https://identity.uat.payroc.com/authorize` | `https://identity.payroc.com/authorize` |

<a id="step-2-build-the-sale-request"></a>
## Step 2. Build the sale request

To run a sale, you need to use `Payloads.sale` to pass the sale details to the gateway client. Pass the following parameters:

| **Parameter** | **Description** |
| --- | --- |
| `amountMinorUnits` | Amount of the sale in minor units, for example, cents. |
| `entryMethod` | How the card can be captured. Send `deviceRead`, `manualEntry`, or `deviceReadOrManualEntry`. |
| `dialect` | Format of the request body. Pass `client.apiType`. |
| `terminalId` | Your processing terminal ID. |
| `currency` | Currency code, for example, `USD`. |

We also recommend that you pass in `orderId` with a unique order ID for each sale. Create a new order ID for every sale, for example, with `Payloads.randomAlphanumeric()`, and store it so that you can use it to search for the payment later.

To add a tax or a tip to the sale, go to [Add a tax](/guides/payments/tap-to-pay-on-iphone/mobile-sync/add-a-tax) or [Add a tip](/guides/payments/tap-to-pay-on-iphone/mobile-sync/add-a-tip).

```swift
import AppSwitchGatewayReference

/// Builds the sale request. Store the order ID so that you can look up the payment later.
func makeSalePayload(client: PayrocGatewayClient, terminalId: String,
                     amountInCents: Int, orderId: String) -> String {
    Payloads.sale(
        amountMinorUnits: amountInCents,      // for example, 1000 for $10.00
        entryMethod: .deviceReadOrManualEntry,
        dialect: client.apiType,              // matches the gateway client from Step 1
        terminalId: terminalId,
        currency: "USD",
        orderId: orderId
    )
}
```

<a id="send-other-information-in-the-request"></a>
### Send other information in the request

If you want to send more information in the request, build the JSON body yourself with `makeCustomPayload` instead of using `makeSalePayload`. In Step 3, pass the result to `startSale` as `payload`. The body must match the format that the gateway client expects, which is `client.apiType`. For a list of the parameters that you can send, go to [Create a payment instruction](/api/send-payment-instruction).

**Note:** App switching doesn't support the `closedLoopOptions`, `ebtDetails`, or `healthcareExpenses` parameters.

Our gateway client handles the header parameters, such as the idempotency key and the content type.

```swift
import Foundation

/// Build the request body yourself, instead of using Payloads.sale.
func makeCustomPayload(terminalId: String, orderId: String, amountInCents: Int) throws -> String {
    // Build the body from the fields in the payment instruction request.
    let body: [String: Any] = [
        "processingTerminalId": terminalId,
        "operator": "Jane",
        "order": [
            "orderId": orderId,
            "amount": amountInCents,
            "currency": "USD",
            "description": "Large Pepperoni Pizza"
        ],
        "customizationOptions": ["entryMethod": "deviceReadOrManualEntry"],
        "autoCapture": true
    ]
    let data = try JSONSerialization.data(withJSONObject: body)
    return String(decoding: data, as: UTF8.self)
}
```

<a id="step-3-switch-to-mobile-sync-and-send-the-request"></a>
## Step 3. Switch to Mobile Sync and send the request

To prompt the gateway client to send the sale details, call `AppSwitchTransaction.run`.

When you call `AppSwitchTransaction.run`, the kit does the following for you:

1. Starts a background task, so that iOS doesn't suspend your app.
2. Starts listening for Mobile Sync's ready signal.
3. Opens Mobile Sync.
4. Waits up to 30 seconds for Mobile Sync to connect to our gateway.
5. Sends your request.

**Note:** If you don't import `AppSwitchOrchestration`, you need to program your app to do these steps.

When you call `run`, send the following parameters:

| **Parameter** | **Description** |
| --- | --- |
| `switchURL` | URL that opens Mobile Sync, from `AppSwitchURL.switchURL(targetScheme:callback:)`. |
| `openURL` | Function that your app uses to open a URL. In SwiftUI, get `openURL` from `@Environment(\.openURL)`, and then pass `{ url in openURL(url) }`. |
| `post` | Closure that sends your request. The `run` function calls it only when Mobile Sync is ready. |
| `readyTimeout` | (Optional) How long to wait for Mobile Sync. The default is 30 seconds. |

We also recommend that you use `canOpenURL` to check that Mobile Sync is installed. The `run` function doesn't check this.

If your request is successful, `run` returns an `InstructionStart` that contains the `instructionId` and a `status` of `inProgress`.

If Mobile Sync isn't ready or our gateway rejects your request, the task throws an error. Mobile Sync might not return to your app, so the following code watches the task and passes any error to `handleStartError`, which you define in [Handle errors](/guides/payments/tap-to-pay-on-iphone/mobile-sync/handle-errors#our-gateway-rejects-your-request).

The code also uses a `saleGeneration` value to identify the current sale. If your app cancels a sale or starts a new one before the kit sends the request, the kit can still be waiting for Mobile Sync's ready signal for the earlier sale. The `saleGeneration` value stops the earlier sale from sending its request or showing an error. For more information, go to [Cancel a sale](/guides/payments/tap-to-pay-on-iphone/mobile-sync/cancel-a-sale#before-the-request-is-sent).

**Note:** To keep the examples short, the following code stores its values in top-level variables. In your own app, you can keep them in a `@MainActor` class, such as a view model. The sample app keeps them in `PaymentViewModel`.

```swift
import AppSwitchContract
import AppSwitchGatewayReference
import AppSwitchOrchestration
import UIKit

// You use these in Step 5 to get the result.
var activeClient: PayrocGatewayClient?
var pendingSale: Task<InstructionStart, Error>?
var activeInstructionId: String?   // set when our gateway accepts the request
var requestStarted = false         // true once the kit starts to send the request
var activeInstructionType: InstructionType = .payment   // .signature during a signature capture
var handledInstructionIds: Set<String> = []             // instructions whose result your app has shown
var saleGeneration = 0             // goes up for every new sale, and when your app cancels a sale

// True from the moment that you start a sale or signature capture until your app handles the response.
var isWaitingForSaleReturn = false

func startSale(client: PayrocGatewayClient, payload: String, openURL: @escaping (URL) -> Void) {
    // Check that Mobile Sync is installed. run doesn't check this.
    guard let switchURL = AppSwitchURL.switchURL(targetScheme: MobileSync.scheme, callback: Callback.sale),
          UIApplication.shared.canOpenURL(switchURL) else {
        showMessage("Mobile Sync isn't installed. Install it, then pair again.")
        return
    }

    // Give the kit a background task. The kit starts and ends it.
    let transaction = AppSwitchTransaction(assertion: PostBackgroundTaskAssertion())

    // Store the client and the task. In Step 5, you use them to get the result.
    activeClient = client
    activeInstructionId = nil
    activeInstructionType = .payment
    requestStarted = false
    isWaitingForSaleReturn = true
    saleGeneration += 1
    let generation = saleGeneration    // identifies this sale
    let task = Task {
        let started = try await transaction.run(
            switchURL: switchURL,
            openURL: openURL,
            post: {
                // A newer sale, or a cancel, replaced this sale. Don't send the request.
                guard generation == saleGeneration else { throw CancellationError() }
                requestStarted = true   // the kit calls this only when Mobile Sync is ready
                return try await client.postInstruction(type: .payment, payload: payload)
            }
        )
        if generation == saleGeneration {
            activeInstructionId = started.instructionId   // available as soon as the request succeeds
        }
        return started
    }
    pendingSale = task

    // If the request never starts, show the error. See Handle errors.
    Task {
        if case .failure(let error) = await task.result, generation == saleGeneration {
            handleStartError(error)   // only if this is still the current sale
        }
    }
}
```

You can combine the code from Steps 1 to 3 into one function:

```swift
/// Returns the order ID. Store it with your own order record so that you can look up the payment later.
@discardableResult
func pay(amountInCents: Int, terminalId: String, apiKey: String,
         openURL: @escaping (URL) -> Void) -> String? {
    // The reader identifier that the kit stored when you paired.
    guard let readerIdentifier = pairing.pairedReaderIdentifier else {
        showMessage("Pair with Mobile Sync first.")
        return nil
    }

    // Step 1. Create the gateway client.
    let client = makeGatewayClient(readerIdentifier: readerIdentifier,
                                   terminalId: terminalId, apiKey: apiKey)

    // Step 2. Build the sale request.
    let orderId = Payloads.randomAlphanumeric()   // a new order ID for every sale
    let payload = makeSalePayload(client: client, terminalId: terminalId,
                                  amountInCents: amountInCents, orderId: orderId)

    // Step 3. Switch to Mobile Sync and send the request.
    startSale(client: client, payload: payload, openURL: openURL)
    return orderId
}
```

<a id="step-4-return-to-your-app"></a>
## Step 4. Return to your app

When the sale ends, Mobile Sync opens your `result` URL, which you defined in [Register your URL schemes](/guides/payments/tap-to-pay-on-iphone/mobile-sync/connect-your-app-to-mobile-sync#register-your-url-schemes) when you connected your app. The URL only brings your app to the front. It doesn't contain the result. In Step 5, you get the result from our gateway.

```swift
import AppSwitchContract
import SwiftUI

struct ContentView: View {
    @Environment(\.scenePhase) private var scenePhase

    var body: some View {
        Text("Your app")   // your app's views
            .onOpenURL { url in
                guard AppSwitchURL.isCallback(url, callbackScheme: Callback.scheme) else { return }

                if AppSwitchURL.isIdentityReturn(url) {
                    handlePairingReturn(url)                      // a pairing response
                } else if let code = AppSwitchURL.errorCode(from: url),
                          code == AppSwitchURL.notProvisionedError || code == AppSwitchURL.standaloneModeError {
                    handleSaleError(code)                         // the sale never ran; see Handle errors
                } else {
                    // A return that arrives before the kit sends your request is a late return from an earlier sale.
                    guard requestStarted else { return }
                    handleSaleReturn(status: AppSwitchURL.returnStatus(from: url))
                }
            }
            .onChange(of: scenePhase) { _, phase in
                if phase == .active { checkForMissingReturn() }   // see Cancel a sale
            }
    }
}
```

Attach these modifiers to your app's root view. This handler replaces the `.onOpenURL` handler that you added in [Connect your app to Mobile Sync](/guides/payments/tap-to-pay-on-iphone/mobile-sync/connect-your-app-to-mobile-sync), because it also handles sale responses.

The URL that Mobile Sync opens doesn't contain an instruction ID, so your app can't tell which sale a response is for. Mobile Sync can send a late `cancelled` response for an earlier sale the next time that the merchant opens it. If that response arrives before the kit sends the request for your new sale, the handler ignores it. For more information, go to [The merchant leaves Mobile Sync](/guides/payments/tap-to-pay-on-iphone/mobile-sync/cancel-a-sale#the-merchant-leaves-mobile-sync).

<a id="step-5-get-the-result-and-show-the-receipt"></a>
## Step 5. Get the result and show the receipt

After the gateway client sends the instruction, you need to use the App Switch Kit to check the status of the sale.

Our gateway returns a status of `inProgress` while the customer enters their payment details and our gateway runs the sale. After our gateway runs the sale, the status of the instruction changes to `completed` and the response includes a link to the sale. The kit uses the link to [retrieve the payment details](/api/get-payment), which include a response code that indicates whether the sale was successful. You can then build the receipt from the payment information.

**Note:** The code in this step uses `activeClient` and `pendingSale`, which you stored in Step 3.

To get the result, program your app to complete the following steps:

1. Wait for the instruction ID from Step 3. If that task failed, there's no result to get, and the code from Step 3 has already passed the error to `handleStartError`.
2. Call `completeInstruction`.- The kit sends `GET /payment-instructions/{id}` up to 12 times until the status isn't `inProgress`. The gateway can hold each request for up to a minute, so show a "Getting the result…" message.
   - When the status is `completed`, the kit follows `link.href` to `GET /payments/{paymentId}` and returns the payment JSON in `outcome.body`.
3. Check whether the sale was approved. The `outcome.succeeded` value means only that our gateway ran the sale and a payment exists. It's also `true` for a declined card. To find out whether the sale was successful, read `transactionResult.responseCode` and `transactionResult.responseMessage` in the payment. For a full list of response codes, go to [Retrieve payment](/api/get-payment).
4. Show the result and the receipt. Build your result page and receipt from the transaction result.

The following code puts steps 3 and 4 in a `showResult` function, because [Cancel a sale](/guides/payments/tap-to-pay-on-iphone/mobile-sync/cancel-a-sale#the-merchant-leaves-mobile-sync) also uses it.

```swift
import AppSwitchContract
import AppSwitchGatewayReference
import Foundation

/// The payment fields your app needs. Add others from the payment object as required.
struct PaymentDetails: Decodable {
    struct TransactionResult: Decodable {
        let status: String            // for example, "ready" or "declined"
        let responseCode: String      // "A" = approved
        let responseMessage: String?
        let approvalCode: String?
    }
    let paymentId: String
    let transactionResult: TransactionResult
}

func handleSaleReturn(status: AppSwitchURL.ReturnStatus?) {
    guard let client = activeClient, let pendingSale else { return }
    isWaitingForSaleReturn = false   // Mobile Sync returned, so checkForMissingReturn doesn't also check
    Task {
        // 1. The instruction ID from Step 3. If the task failed, handleStartError has already shown the error.
        guard let started = try? await pendingSale.value else { return }
        // A late return for a sale whose result your app has already shown.
        guard !handledInstructionIds.contains(started.instructionId) else { return }
        do {
            // 2. Check the instruction until it finishes, then get the payment.
            let outcome = try await client.completeInstruction(type: .payment,
                                                               instructionId: started.instructionId)
            if outcome.stillInProgress {
                isWaitingForSaleReturn = true    // not final yet, so check again when your app becomes active
            } else {
                handledInstructionIds.insert(started.instructionId)   // show each result only once
            }
            showResult(outcome, hint: status)                    // 3 and 4
        } catch {
            handleUnconfirmedSale(error)                         // see Handle errors
        }
    }
}

/// Shows the result of a sale from the outcome that our gateway returns.
func showResult(_ outcome: InstructionOutcome, hint: AppSwitchURL.ReturnStatus?) {
    guard outcome.succeeded,
          let payment = try? JSONDecoder().decode(PaymentDetails.self,
                                                  from: Data(outcome.body.utf8)) else {
        handleIncompleteSale(outcome, hint: hint)                // see Handle errors
        return
    }
    // 3. Check whether the processor approved the sale.
    if payment.transactionResult.responseCode == "A" {
        showApproved(payment)                                    // 4. show your receipt
    } else {
        showDeclined(payment.transactionResult.responseMessage)
    }
}
```

<a id="troubleshooting"></a>
## Troubleshooting

If your request is unsuccessful in Step 3, the cause is one of the following:

| **Cause** | **What happens** |
| --- | --- |
| Mobile Sync wasn't ready | The `run` function throws `wsUnavailable`, `readerUnavailable`, or `readyTimeout`, and your request isn't sent. |
| Your request failed | The `run` function throws the error from your request, for example, a gateway `404`. |

If the kit doesn't start a background task, iOS suspends your app while Mobile Sync is on screen, and your request fails with error `-1005`. The Xcode debugger hides this problem, so test your app with the debugger detached.

<a id="next-step"></a>
## Next step

To program your app to cancel a sale that's in progress, or to handle the result when a sale is canceled, go to [Cancel a sale](/guides/payments/tap-to-pay-on-iphone/mobile-sync/cancel-a-sale).
