Prerequisites: Authentication · Run a sale
You can use your app to capture a customer's signature through Mobile Sync. A signature capture is a separate instruction from a sale, and it doesn't move any money. Your app sends the instruction to our gateway, and then Mobile Sync shows a signature pad to the customer. Our gateway returns the signature as an image that your app can show or store.
Before you begin
Important: If your app sends a signature instruction while a sale is open in Mobile Sync, our gateway rejects it and ends it as a failure. Capture signatures between sales.
Make sure that you've integrated with Run a sale. You use the same type of gateway client, switch to Mobile Sync in the same way, and get the result from our gateway in the same way.
The code on this page uses the following values, variables, and functions:
- The
pairing,MobileSync, andCallbackvalues that you define in Connect your app to Mobile Sync. - The
makeGatewayClientfunction from Step 1 of Run a sale, and theactiveClient,activeInstructionId,activeInstructionType,isWaitingForSaleReturn, andsaleGenerationvariables from Step 3 of Run a sale. - The
terminalIdandapiKeyvalues, which are your processing terminal ID and your Payroc API key. - The
handleStartError(_:)andhandleUnconfirmedSale(_:)functions, which you define in Handle errors. - The
showSignature(_:),showCheckStatusButton(), andshowMessage(_:)functions, which are placeholders for your own code.
Integration steps
- Build the signature request.
- Switch to Mobile Sync and send the request.
- Read the result.
- Show the signature.
Step 1. Build the signature request
Build the request that triggers Mobile Sync to capture the customer's signature. The request contains only your processing terminal ID and the API type of your gateway client. It doesn't contain an amount or an order ID.
In the following code, client is the new gateway client that you create for the signature capture in Step 2.
import AppSwitchGatewayReference
let payload = Payloads.signature(dialect: client.apiType, terminalId: terminalId)
Step 2. Switch to Mobile Sync and send the request
Switch to Mobile Sync and send the request in the same way that you do for a sale in Step 3 of Run a sale. The differences are:
- You send the request as a
.signatureinstruction instead of a.paymentinstruction. - You store the task in
pendingSignatureinstead ofpendingSale.
As for a sale, create a new gateway client for every signature capture, so that each request has a new idempotency key.
import AppSwitchContract
import AppSwitchGatewayReference
import AppSwitchOrchestration
import UIKit
// You use this in Step 3 to get the result.
var pendingSignature: Task<InstructionStart, Error>?
func startSignature(terminalId: String, apiKey: String, openURL: @escaping (URL) -> Void) {
// The reader identifier that the kit stored when you paired.
guard let readerIdentifier = pairing.pairedReaderIdentifier else {
showMessage("Pair with Mobile Sync first.")
return
}
// 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
}
// A new client for every signature capture, and the request from Step 1.
let client = makeGatewayClient(readerIdentifier: readerIdentifier,
terminalId: terminalId, apiKey: apiKey)
let payload = Payloads.signature(dialect: client.apiType, terminalId: terminalId)
let transaction = AppSwitchTransaction(assertion: PostBackgroundTaskAssertion())
// Store the client and the task. In Step 3, you use them to get the result.
activeClient = client
activeInstructionId = nil
activeInstructionType = .signature // so that checkForMissingReturn checks a signature instruction
requestStarted = false
isWaitingForSaleReturn = true
saleGeneration += 1 // a signature capture replaces any earlier sale that hasn't started
let generation = saleGeneration
let task = Task {
let started = try await transaction.run(
switchURL: switchURL,
openURL: openURL,
post: {
// A newer sale or signature capture replaced this one. 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: .signature, payload: payload)
}
)
if generation == saleGeneration {
activeInstructionId = started.instructionId
}
return started
}
pendingSignature = task
// If the request never starts, show the error. See Handle errors.
Task {
if case .failure(let error) = await task.result, generation == saleGeneration {
pendingSignature = nil
handleStartError(error)
}
}
}
Step 3. Read the result
When Mobile Sync opens your result URL, handle the return in the same way as in Step 4 of Run a sale, and then call completeInstruction with type: .signature to get the result from our gateway.
Mobile Sync uses the same result URL for a sale and for a signature capture. To send each return to the right function, replace the last else branch of the .onOpenURL handler from Step 4 of Run a sale with the following code. The code uses activeInstructionType, which startSale sets to .payment and startSignature sets to .signature.
} else {
guard requestStarted else { return } // a late return from an earlier sale or signature capture
if activeInstructionType == .signature {
handleSignatureReturn(status: AppSwitchURL.returnStatus(from: url)) // a signature capture response
} else {
handleSaleReturn(status: AppSwitchURL.returnStatus(from: url)) // a sale response
}
}
Because Mobile Sync captures the signature, there's no need to check for an approval or a decline. The result is either a signature image, or a failure because the merchant canceled the signature capture, the customer didn't use the signature pad in time, or Mobile Sync couldn't send the signature.
The status value in the URL indicates what happened. The following table shows the possible values for status, and what they mean:
| Status | What happened |
|---|---|
completed | Mobile Sync delivered the signature, and our gateway confirmed it. |
cancelled | The merchant canceled the signature capture or left Mobile Sync. |
failed | Mobile Sync couldn't send the signature, for example because the connection dropped. The failure might not be permanent, so offer to check the status again. |
timeout | The customer didn't use the signature pad for 60 seconds. |
The following code shows how to get the result from our gateway and handle the signature:
import AppSwitchContract
import AppSwitchGatewayReference
func handleSignatureReturn(status: AppSwitchURL.ReturnStatus?) {
guard let client = activeClient, let signatureTask = pendingSignature else { return }
pendingSignature = nil // the next return is for a sale, unless you start another signature capture
isWaitingForSaleReturn = false
Task {
// The instruction ID from Step 2. If the task failed, handleStartError has already shown the error.
guard let started = try? await signatureTask.value else { return }
// A late return for a signature capture whose result your app has already shown.
guard !handledInstructionIds.contains(started.instructionId) else { return }
do {
let outcome = try await client.completeInstruction(type: .signature,
instructionId: started.instructionId)
if outcome.succeeded {
handledInstructionIds.insert(started.instructionId) // show each result only once
// One of the rows contains the signature image.
showSignature(ReceiptParser.rows(fromJSON: outcome.body))
} else if outcome.stillInProgress || status == .failed {
showCheckStatusButton() // Mobile Sync might still send the signature
} else {
handledInstructionIds.insert(started.instructionId)
showMessage(outcome.body) // canceled or timed out
}
} catch {
handleUnconfirmedSale(error) // see Handle errors
}
}
}
Step 4. Show the signature
Our gateway returns the signature as a Base64-encoded image. The kit's ReceiptParser decodes the image into the imageData value of a ReceiptRow. To show the signature, display that image in your app.
Note: The kit uses the name ReceiptParser for all responses, including responses that aren't for a sale.
The following code displays an image, and shows any other field in the response as text:
import AppSwitchGatewayReference
import SwiftUI
import UIKit
/// Displays an image, and shows every other field as text.
struct ReceiptRowView: View {
let row: ReceiptRow
var body: some View {
if let data = row.imageData, let image = UIImage(data: data) {
VStack(alignment: .leading) {
Text(row.label)
Image(uiImage: image)
.resizable()
.scaledToFit()
}
} else {
LabeledContent(row.label, value: row.value)
}
}
}
The Base64 string is large and isn't useful in a log. If you log a signature capture, log only the size of the image in bytes. Never log the response in full.