Accept a Payment using an Android Device
Connect a mobile card reader and accept a payment with the Stax Android SDK.
Prepare your Android app
- Install and initialize the SDK using the Android SDK setup instructions.
- Connect your Stax card reader before starting a reader transaction.
Run the Kotlin examples in your Android app after SDK initialization completes. The examples check whether Omni.shared() is available rather than silently skipping an operation when it is unavailable. Use the linked SDK sample project for application-level initialization and integration.
Connecting to Mobile Reader
- Search for available readers.
- Select a reader and connect to it.
Call connectToReader(this) from your Activity. The Activity supplies the context for the reader-selection dialog.
import android.app.Activity
import android.app.AlertDialog
import com.fattmerchant.android.Omni
fun connectToReader(activity: Activity) {
val omni = Omni.shared()
if (omni == null) {
println("Initialize the Stax SDK before connecting a reader.")
return
}
omni.getAvailableReaders { found ->
activity.runOnUiThread {
if (found.isEmpty()) {
println("No readers found. Check that your reader is available and search again.")
} else {
val readers = found.map { it.getName() }.toTypedArray()
AlertDialog.Builder(activity)
.setTitle("Select a reader")
.setItems(readers) { _, which ->
omni.connectReader(
mobileReader = found[which],
onConnected = { _ ->
println("Reader connected.")
},
onFail = { _ ->
println("Reader connection failed. Check the reader and try again.")
}
)
}
.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss()
println("Reader selection canceled.")
}
.show()
}
}
}
}When the connection succeeds, the example prints Reader connected. If the search returns no readers, it prints No readers found. Check that your reader is available and search again.
See the Stax Android SDK sample project for an example of connecting to a reader with the SDK.
Optional: USB VP3350 Support
Starting with Android SDK 2.7, you can use a VP3350 reader. For the USB variant, add these declarations inside the root <manifest> element of AndroidManifest.xml:
<uses-feature android:name="android.hardware.usb.host" android:required="false" />
<uses-feature android:name="android.hardware.usb.accessory" android:required="false" />These declarations add the USB features to your app manifest. Use the connection example to confirm that you can connect to your reader.
Optional: Listen to Connection Events
Your reader may update its firmware or fetch configuration from your merchant account while connecting. Register a MobileReaderConnectionStatusListener before connecting to observe these updates.
import com.fattmerchant.android.Omni
import com.fattmerchant.omni.MobileReaderConnectionStatusListener
import com.fattmerchant.omni.data.models.MobileReaderConnectionStatus
class MyStatusListener : MobileReaderConnectionStatusListener {
override fun mobileReaderConnectionStatusUpdate(status: MobileReaderConnectionStatus) {
println("Reader connection status: $status")
}
}
fun registerConnectionStatusListener() {
val omni = Omni.shared()
if (omni == null) {
println("Initialize the Stax SDK before registering a listener.")
return
}
omni.mobileReaderConnectionStatusListener = MyStatusListener()
println("Reader connection status listener registered.")
}Call registerConnectionStatusListener() before connectToReader(this). After registration, each update prints a line beginning with Reader connection status:.
Taking a Payment
Create a TransactionRequest (an object describing the payment you want to collect), then pass it to takeMobileReaderTransaction. By default, the request enables tokenization (replacing card details with a reusable payment-method token so you can charge the saved payment method later).
- Connect your reader using the connection example.
- Call
takePayment()to collect a one-cent payment. - Check
transaction.successin the completion callback before treating the payment as approved.
import com.fattmerchant.android.Omni
import com.fattmerchant.omni.data.Amount
import com.fattmerchant.omni.data.TransactionRequest
fun takePayment() {
val omni = Omni.shared()
if (omni == null) {
println("Initialize the Stax SDK before taking a payment.")
return
}
// The Int constructor uses cents: Amount(1) charges $0.01.
val request = TransactionRequest(amount = Amount(1))
omni.takeMobileReaderTransaction(
request = request,
completion = { transaction ->
if (transaction.success == true) {
println("Payment approved.")
// Keep this returned ID for later API operations; do not invent an ID.
println("Transaction ID: ${transaction.id}")
} else {
println("Payment was not approved.")
}
},
error = { _ ->
println("Payment could not be completed. Check the connection and transaction status before retrying.")
}
)
}An approved payment prints Payment approved. followed by the actual transaction ID. A response without success == true prints Payment was not approved.; the error callback reports that the operation could not be completed.
See the Stax Android SDK sample project for an example of paying with a reader with the SDK.
Optional: Configure the TransactionRequest
The following example shows the optional request fields from this guide with valid Kotlin named arguments. tokenize defaults to true, and preauth defaults to false. Set preauth to true only when you want to authorize a payment (hold funds) without capturing it (collecting the funds) until later.
import com.fattmerchant.omni.data.Amount
import com.fattmerchant.omni.data.TransactionRequest
fun buildPaymentRequest(): TransactionRequest {
return TransactionRequest(
amount = Amount(1), // The Int constructor uses cents.
tokenize = true,
invoiceId = null, // Supply an existing invoice ID only when linking to an invoice.
customerId = null, // Supply an existing customer ID only when linking to a customer.
lineItems = listOf(),
subtotal = null,
tax = null,
tip = null,
shippingAmount = null,
poNumber = null,
memo = null,
reference = null,
preauth = false,
meta = null
)
}Calling buildPaymentRequest() returns a request for one cent with tokenization enabled. Pass the returned request to takeMobileReaderTransaction using the same completion and error handling as the payment example.
Optional: Listen to transaction events via UserNotificationListener
Register a UserNotificationListener to receive prompts that you need to display to the customer during a transaction. For example, if a customer swipes a chip card that must be inserted, the reader can prompt the customer to insert it instead.
Implement both callbacks and register the listener before taking a payment. This example prints the prompts; display the typed notification's userFriendlyMessage in your payment screen so the customer can follow the reader's instructions.
import com.fattmerchant.android.Omni
import com.fattmerchant.omni.UserNotificationListener
import com.fattmerchant.omni.data.UserNotification
class MyNotificationListener : UserNotificationListener {
override fun onUserNotification(userNotification: UserNotification) {
println(userNotification.userFriendlyMessage)
}
override fun onRawUserNotification(userNotification: String) {
println("Reader prompt: $userNotification")
}
}
fun registerUserNotificationListener() {
val omni = Omni.shared()
if (omni == null) {
println("Initialize the Stax SDK before registering a listener.")
return
}
omni.userNotificationListener = MyNotificationListener()
println("User notification listener registered.")
}Call registerUserNotificationListener() before takePayment(). After registration, the example prints the reader's prompts as notifications arrive.
Tokenize a Payment
Pass a CreditCard object to tokenize to create a reusable payment method without taking a payment. Handle both the returned payment method and the error callback.
The following example uses SDK test cards rather than real card details. Run it in your test environment.
import com.fattmerchant.android.Omni
import com.fattmerchant.omni.data.models.CreditCard
fun tokenizeTestCard(testFailure: Boolean = false) {
val omni = Omni.shared()
if (omni == null) {
println("Initialize the Stax SDK before tokenizing a card.")
return
}
val card = if (testFailure) {
CreditCard.failingTestCreditCard()
} else {
CreditCard.testCreditCard()
}
omni.tokenize(
card,
completion = { _ ->
// Do not print the returned payment-method object or card details.
println("Payment method tokenized.")
},
error = { _ ->
println("Card tokenization failed.")
}
)
}Testing
- Call
tokenizeTestCard()to useCreditCard.testCreditCard(). Successful tokenization printsPayment method tokenized. - Call
tokenizeTestCard(testFailure = true)to useCreditCard.failingTestCreditCard(). A failed attempt printsCard tokenization failed.
Refund a Payment
Get the actual Transaction you want to refund from the Stax API or your payment completion callback, then pass it to refundPayment(transaction). The argument is the SDK transaction object, not a dummy ID or an invented API client.
import com.fattmerchant.android.Omni
import com.fattmerchant.omni.data.models.Transaction
fun refundPayment(transaction: Transaction) {
val omni = Omni.shared()
if (omni == null) {
println("Initialize the Stax SDK before refunding a payment.")
return
}
omni.refundMobileReaderTransaction(
transaction = transaction,
completion = { _ ->
println("Refund operation completed. Check the returned transaction status before confirming the refund to the customer.")
},
error = { _ ->
println("Refund could not be completed. Check the transaction status before retrying.")
}
)
}The completion callback reports that the operation completed; inspect the returned transaction before confirming the refund. If the error callback runs, check the transaction status before attempting the refund again.
Voiding a Payment
Use voidTransaction to cancel a payment or return its funds. This method handles both voids (canceling a payment before the funds are collected) and refunds (returning funds after collection), so prefer it over refundMobileReaderTransaction.
Pass the actual transaction you want to cancel to voidPayment(transaction). The example reads the ID from that transaction, as returned by the Stax API or your payment completion callback, rather than using a fabricated ID. It does not depend on a Dashboard URL or navigation path.
import com.fattmerchant.android.Omni
import com.fattmerchant.omni.data.models.Transaction
fun voidPayment(transaction: Transaction) {
// Use the ID returned with the transaction you intend to void or refund.
val id = transaction.id
if (id.isNullOrBlank()) {
println("The transaction has no ID. Retrieve the original transaction before continuing.")
return
}
val omni = Omni.shared()
if (omni == null) {
println("Initialize the Stax SDK before voiding a payment.")
return
}
omni.voidTransaction(
transactionId = id,
completion = { result ->
if (result.success == true) {
println("Payment voided or refunded.")
} else {
println("Payment was not voided or refunded.")
}
},
error = { _ ->
println("Void or refund could not be completed. Check the transaction status before retrying.")
}
)
}A successful result prints Payment voided or refunded. A result without success == true prints Payment was not voided or refunded. If an error occurs, check the original transaction's status before retrying.
Updated 5 days ago
