Tap to Pay on Pocket
Initiate and accept contactless payments from your POS application via the SDK.
The code samples in this guide use Kotlin and Kotlin Coroutines.
How the SDK works
The Tap to Pay on Pocket SDK (DojoTapToPayOnPocket) lets your Point of Sale (POS) application accept in-person contactless payments and process unlinked refunds on a Dojo Pocket device. Rather than manually constructing Android Intents, managing PendingIntent callbacks, and orchestrating Dojo REST API calls yourself, the SDK coordinates both the Dojo API and the on-device Dojo Pay App (TaP) through a single, type-safe Kotlin interface.
Every interaction with the SDK follows a two-phase asynchronous lifecycle:
- Request setup and dispatch (
DojoResult): When your POS invokes an operation—such asinitDojo(),sale(),refund(), orlastTx()—the SDK validates the parameters, creates any required backend resources (PaymentIntentandTerminalSession) via the Dojo API, and launches the TaP UI on the Pocket device. The function returns aDojoResult<Value, Error>immediately to confirm whether the request was accepted and dispatched to TaP (or failed pre-dispatch validation, API creation, or intent resolution). - Outcome delivery (
DojoTapToPayOnPocket.responses): While TaP is in the foreground, the customer taps their card or mobile wallet (or splits the bill / adds a gratuity). When the interaction completes, TaP delivers the outcome back to the SDK's internal broadcast receiver, and the SDK emits a strongly typedResponseon the process-wideDojoTapToPayOnPocket.responsesFlow. If focus returns to your POS without a callback from TaP, the SDK automatically polls the Dojo API to reconstruct the outcome or emitsResponse.MissingResponseso you can reconcile manually.
Flow diagram: End-to-end SDK architecture and lifecycle
sequenceDiagram
autonumber
participant POS as POS App
participant SDK as DojoTapToPayOnPocket SDK
participant API as Dojo API
participant TaP as Dojo Pay App (TaP)
Note over POS,SDK: 1. Application Startup
POS->>SDK: initSdk(context, config)
SDK-->>POS: DojoResult.Success(Unit)
POS->>SDK: Collect DojoTapToPayOnPocket.responses
Note over POS,TaP: 2. Terminal Initialization & Provisioning
POS->>SDK: initDojo()
SDK->>TaP: Dispatch com.dojo.action.INIT
SDK-->>POS: DojoResult.Success(Unit)
TaP-->>SDK: INIT_COMPLETE (INIT_RESULT, TERMINAL_ID)
SDK->>API: Prefetch & cache terminal UUID for TID
SDK-->>POS: Emit Response.DojoInit on responses
Note over POS,TaP: 3. Sale or Refund Transaction
POS->>SDK: sale(amountInPennies, reference, currencyCode)
SDK->>API: Create PaymentIntent & TerminalSession
API-->>SDK: paymentIntentId, terminalSessionId
SDK->>TaP: Dispatch com.dojo.action.SALE
SDK-->>POS: DojoResult.Success(SaleMetadata)
Note over POS: Persist SaleMetadata to local storage
TaP-->>SDK: TX_COMPLETE (or fallback API reconciliation)
SDK-->>POS: Emit Response.Sale / Response.SplitSale on responses
Note over POS: Process result & clear persisted metadata
Operations overview
| Step | SDK Method | Immediate Return Type | Emitted on responses | Purpose |
|---|---|---|---|---|
| 1. Configure SDK | initSdk(context, config) | DojoResult<Unit, InitSdkError> | None | Registers your API credentials, environment settings, and lifecycle observers in Application.onCreate(). |
| 2. Observe responses | responses | Flow<Response> | All Response subtypes | Process-wide stream delivering all asynchronous outcomes from TaP and automatic foreground reconciliation. |
| 3. Provision & link terminal | initDojo() | DojoResult<Unit, InitDojoError> | Response.DojoInit | Provisions the TaP payment engine (if needed) and caches the device's Terminal ID (TID) in the SDK for API session creation. |
| 4. Take a payment | sale(...) | DojoResult<SaleMetadata, SaleError> | Response.Sale or Response.SplitSale | Creates a Dojo PaymentIntent and TerminalSession, then launches TaP to accept a contactless payment (or split bill). |
| 5. Issue a refund | refund(...) | DojoResult<RefundMetadata, RefundError> | Response.Refund | Creates an unlinked refund TerminalSession, then launches TaP to process a contactless card refund. |
| 6. Recover an interrupted transaction | reconcileSale(...) / reconcileRefund(...) | DojoResult<ManualReconciliationResult<T>, E> | None (returned directly) | Stateless, read-only Dojo API lookup to recover the outcome of a sale or refund after Response.MissingResponse or process death. |
| 7. Query last on-device transaction | lastTx() | DojoResult<Unit, LastTxError> | Response.LastTx | Queries TaP locally for the most recent completed single or split sale on the device (for parity with Intent integrations). |
Setting up the SDK
1. Generate an API key
Generate a Dojo API key in the Developer Portal by following the API keys guide. Secret keys for the sandbox test environment use the prefix sk_sandbox_, and production keys use the prefix sk_prod_.
2. Add the Gradle dependency
The SDK is published to Maven Central and requires minSdk = 29 (Android 10) or higher. Add the dependency to your module's build.gradle.kts (or build.gradle):
repositories {
mavenCentral()
}
dependencies {
implementation("tech.dojo.pos:tap-to-pay-on-pocket:1.0.0")
}
3. Initialize the SDK in Application.onCreate()
Initialize the SDK once per process inside your custom Application.onCreate() before collecting DojoTapToPayOnPocket.responses or invoking any other operation. Pass your Application context, your Dojo API key, and the softwareHouseId assigned to you by Dojo.
fun initSdk(
context: Context,
config: Config,
): DojoResult<Unit, InitSdkError>
DojoTapToPayOnPocket.initSdk validates the host context and merged manifest components synchronously and returns DojoResult<Unit, InitSdkError>:
import android.app.Application
import android.util.Log
import tech.dojo.pos.Config
import tech.dojo.pos.DojoResult
import tech.dojo.pos.InitSdkError
import tech.dojo.pos.InvalidSdkContext
import tech.dojo.pos.SdkIntegrationError
import tech.dojo.pos.pocket.DojoTapToPayOnPocket
class ExamplePosApp : Application() {
override fun onCreate() {
super.onCreate()
initDojoSdk()
}
private fun initDojoSdk() {
val result: DojoResult<Unit, InitSdkError> = DojoTapToPayOnPocket.initSdk(
context = this,
config = Config(
apiKey = "[YOUR API KEY]",
softwareHouseId = "[YOUR SOFTWARE HOUSE ID]",
),
)
when (result) {
is DojoResult.Success -> {
// SDK is initialized; start your process-level responses collector here
}
is DojoResult.Failure -> {
when (val error = result.error) {
is InvalidSdkContext -> {
Log.e("ExamplePosApp", "Invalid Context (${error.contextClassName}); pass an Application or Activity context.")
}
is SdkIntegrationError -> {
Log.e("ExamplePosApp", "SDK integration check failed: ${error.message}")
}
}
}
}
}
}
Handling InitSdkError
If initSdk returns DojoResult.Failure, it does not retain partial state or overwrite an existing valid initialization:
| Error Type | Properties | Cause & Recommended POS Action |
|---|---|---|
InvalidSdkContext | contextClassName: String | The supplied Context could not resolve a valid android.app.Application via context.applicationContext. Always pass your Application instance (this inside Application.onCreate()) or an Activity context. |
SdkIntegrationError | message: String | The SDK's required manifest components (DojoProxyActivity or DojoResponseReceiver) were disabled in your merged AndroidManifest.xml, or initSdk was called from a process other than the one hosting DojoResponseReceiver. Ensure manifest merging is enabled and guard multi-process initialization. |
Customising the SDK
Config provides sensible defaults for production and sandbox testing while allowing you to customise reseller attribution, target environments, and reconciliation timings when needed:
data class Config(
val apiKey: String,
val softwareHouseId: String,
val resellerId: String = softwareHouseId,
val apiEnvironment: DojoApiEnvironment = DojoApiEnvironment.PRODUCTION,
val appEnvironment: AppEnvironment = AppEnvironment.PRODUCTION,
val foregroundReconciliation: ForegroundReconciliationConfig = ForegroundReconciliationConfig(),
val processLifecycle: ProcessLifecycle = ..., // Uses AndroidX ProcessLifecycleOwner by default
)
data class ForegroundReconciliationConfig(
val enabled: Boolean = true,
val windowMs: Long = 5_000,
val pollIntervalMs: Long = 1_000,
val networkConfig: ApiCallConfig = ApiCallConfig(),
)
data class ApiCallConfig(
val connectTimeoutMs: Int = 10_000,
val readTimeoutMs: Int = 10_000,
val maxAttempts: Int = 3,
val firstRetryDelayMs: Long = 500,
val secondRetryDelayMs: Long = 1_000,
)
Reseller IDs
softwareHouseId identifies the EPOS company whose software generates the request and remains constant across all merchants using your EPOS software. resellerId identifies the reseller who distributes the software on behalf of the EPOS company and defaults to softwareHouseId when omitted.
In sandbox, use your assigned softwareHouseId and resellerId if you have them; otherwise use the literal values "softwareHouse1" and "reseller1". Production integrations must always use the identifiers assigned by Dojo.
Environments
By default, the SDK targets AppEnvironment.PRODUCTION (com.dojo.tap) and DojoApiEnvironment.PRODUCTION (https://api.dojo.tech).
appEnvironment: Controls which on-device TaP package the SDK targets via explicitIntents. Only change this toAppEnvironment.STAGING(com.dojo.tap.staging) if Dojo has provisioned your test device with a staging build of the TaP app.apiEnvironment: Controls the Dojo API base URL and should remain set toDojoApiEnvironment.PRODUCTION, as the production API endpoint supports both sandbox (sk_sandbox_...) and production (sk_prod_...) API keys.
Foreground reconciliation
By default (ForegroundReconciliationConfig.enabled = true), the SDK automatically queries the Dojo API as a fallback if focus returns to your POS app while a sale or refund is still awaiting a response from TaP. It polls every pollIntervalMs (1_000 ms by default, must be > 0) for up to windowMs (5_000 ms by default, must be >= pollIntervalMs). You can adjust these timings or set enabled = false if you prefer to handle all recovery manually via reconcileSale and reconcileRefund.
Process lifecycle observation
The SDK uses AndroidX ProcessLifecycleOwner (initialized via the AndroidX Startup library) to verify that your POS app is in the foreground before dispatching Intents and to detect when your app returns to the foreground after a transaction. We recommend keeping AndroidX Startup enabled; if your app disables it in the manifest, you must supply a custom ProcessLifecycle implementation in Config.
Multi-process considerations
SDK state is strictly process-local. By default, the SDK's merged manifest components (DojoProxyActivity and DojoResponseReceiver) run in your application's default process. If your application spawns multiple processes (or customises android:process on the SDK components), you must guard Application.onCreate() so initSdk(), responses collection, and all SDK operations run exclusively inside the process that hosts DojoResponseReceiver.
Manifest merging and R8 / ProGuard
The SDK automatically merges its required <uses-permission android:name="android.permission.INTERNET" />, <queries> declarations for the TaP package, internal DojoProxyActivity, and DojoResponseReceiver into your app's AndroidManifest.xml, and bundles its own consumer R8/ProGuard keep rules—no manual manifest entries or ProGuard rules are required.
Responses
Because payment interactions happen in the TaP application, transaction outcomes are delivered asynchronously through DojoTapToPayOnPocket.responses:
val responses: Flow<Response>
How response delivery works
- Process-level collection: Responses can arrive while your Activity or Composable UI is in the background or undergoing configuration changes. Subscribe to
DojoTapToPayOnPocket.responsesonce at theApplication/ process level (for example, in an application-scoped coroutine or repository initialized right afterinitSdksucceeds) and persist or forward state updates to your UI layer. - FIFO buffering before subscription: If TaP delivers a response before your collector starts, the SDK retains accepted responses in an in-memory FIFO queue and delivers them in order as soon as the first collector subscribes.
- Multicast without replay: Every collector that is active at the moment a response is emitted receives that emission. Once delivered, responses are not replayed to collectors that subscribe later.
- Typed properties and backwards-compatible
Bundles: EveryResponsesubtype exposes strongly typed Kotlin properties (recommended) alongside a rawbundle: Bundleproperty containing the underlyingcom.dojo.extra.*extras for seamless migration from rawIntentintegrations.
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import tech.dojo.pos.Response
import tech.dojo.pos.pocket.DojoTapToPayOnPocket
class PosResponseCoordinator {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
fun startObserving() {
scope.launch {
DojoTapToPayOnPocket.responses.collect { response ->
when (response) {
is Response.DojoInit -> handleInitResponse(response)
is Response.Sale -> handleSaleResponse(response)
is Response.SplitSale -> handleSplitSaleResponse(response)
is Response.Refund -> handleRefundResponse(response)
is Response.LastTx.Sale -> handleLastTxSaleResponse(response)
is Response.LastTx.SplitSale -> handleLastTxSplitResponse(response)
is Response.MissingResponse -> handleMissingResponse(response)
}
}
}
}
}
Initialize
Before your POS can start a sale(), refund(), or lastTx(), you must initialize the on-device TaP application using DojoTapToPayOnPocket.initDojo().
Calling initDojo() performs two critical jobs:
- Device provisioning: If the Pocket device has never been activated, TaP guides the operator through entering their activation code and provisions the contactless payment engine (which can take up to two minutes on first run). If the device is already provisioned, TaP completes immediately.
- Terminal ID (
TID) resolution and caching: When TaP finishes initializing, it returns the Pocket device's uniqueterminalId(TID, returned from TaP26.07.15onwards). The SDK automatically caches thisTIDin memory and prefetches the corresponding terminal UUID from the Dojo API so subsequentsale()andrefund()calls can create terminal sessions.
initDojo() in each new app process before sale() or refund()Because the device's TID is cached in memory within your POS process, calling sale() or refund() before initDojo() has completed in the current process will fail with SdkNotInitialised. On already-provisioned devices, calling initDojo() completes quickly and emits Response.DojoInit with isSuccess = true, detail = "COMPLETED", and the device's terminalId.
(Note: reconcileSale and reconcileRefund query session IDs directly and only require initSdk(), not initDojo()).

Flow diagram: Tap Init Flow
flowchart TD
Start["POS calls DojoTapToPayOnPocket.initDojo()"] --> DispatchCheck{"Pre-dispatch validation passes?"}
DispatchCheck -->|"No"| DispatchFail["Returns DojoResult.Failure(InitDojoError)"]
DispatchCheck -->|"Yes"| Provisions["Returns DojoResult.Success(Unit) & launches TaP"]
Provisions -->|"Device not yet activated"| Activation["Operator completes Device Activation Flow in TaP"]
Provisions -->|"Device already activated"| Complete
Activation --> Complete["SDK emits Response.DojoInit on DojoTapToPayOnPocket.responses"]
Complete --> ResultTrue["isSuccess == true (detail = 'OK' or 'COMPLETED', terminalId cached by SDK)"]
Complete --> ResultFalse["isSuccess == false (detail = error code, e.g. 'NO_TID', 'A5', 'E1')"]
style DispatchFail fill:#f96,stroke:#333
style ResultFalse fill:#f96,stroke:#333
style ResultTrue fill:#3f3,stroke:#333
style Provisions fill:#d1f2eb,stroke:#333
style Complete fill:#b8c2f2,stroke:#333
Device security prerequisites
To pass payment-scheme security attestation during provisioning, the Pocket device must meet the following hardware and OS requirements:
- Developer options disabled: The device must not be in developer mode or connected to a host via Android Debug Bridge (ADB) (which triggers provisioning error
"A5"). - Unmodified system image: The device system images must not be modified (no custom bootloader, root access, or
subinary). - Locked bootloader: The bootloader must be locked.
- NFC enabled: The device must have NFC enabled.
If any of these checks fail, TaP will reject provisioning and return Response.DojoInit with isSuccess = false and a diagnostic error code in detail.
Dispatching an initialization request
Call DojoTapToPayOnPocket.initDojo() while your POS app is in the foreground:
fun initDojo(): DojoResult<Unit, InitDojoError>
DojoResult.Success(Unit) confirms that the INIT intent was dispatched to TaP. Handle DojoResult.Failure to catch pre-dispatch errors:
import tech.dojo.pos.AppInBackground
import tech.dojo.pos.DojoResult
import tech.dojo.pos.DpaNotInstalled
import tech.dojo.pos.DpaSecurityFailure
import tech.dojo.pos.DpaVersionUnsupported
import tech.dojo.pos.InitDojoError
import tech.dojo.pos.SdkNotInitialised
import tech.dojo.pos.pocket.DojoTapToPayOnPocket
fun startTerminalInitialization() {
when (val result: DojoResult<Unit, InitDojoError> = DojoTapToPayOnPocket.initDojo()) {
is DojoResult.Success -> {
// Request dispatched to TaP. Await Response.DojoInit on DojoTapToPayOnPocket.responses.
}
is DojoResult.Failure -> {
when (val error = result.error) {
is SdkNotInitialised -> {
// DojoTapToPayOnPocket.initSdk() has not succeeded in this process
}
is AppInBackground -> {
// Host POS app is in the background; bring to foreground and retry
}
is DpaNotInstalled -> {
// TaP app is not installed on the device for error.action
}
is DpaVersionUnsupported -> {
// Installed TaP version (error.installedVersionCode) is below error.minimumVersionCode
}
is DpaSecurityFailure -> {
// Android OS blocked the intent with error.cause (SecurityException)
}
}
}
}
}
InitDojoError reference
| Error Type | Properties | Cause & Recommended POS Action |
|---|---|---|
SdkNotInitialised | None (data object) | DojoTapToPayOnPocket.initSdk(...) was not called or failed before calling initDojo(). Ensure initSdk runs in Application.onCreate(). |
AppInBackground | None (data object) | Your POS process is not in the started/foreground state (ProcessLifecycle.isStarted == false), so Android blocks activity launches. Wait until your Activity is visible and retry. |
DpaNotInstalled | action: String | The target TaP application package (com.dojo.tap in production) is not installed or cannot resolve com.dojo.action.INIT. Prompt the operator to install or enable the Dojo Pay App. |
DpaVersionUnsupported | installedVersionCode: Long, minimumVersionCode: Long | The installed TaP app version is older than the minimum version required by this SDK (100918). Prompt the operator to update the Dojo Pay App. |
DpaSecurityFailure | action: String, cause: SecurityException | Android rejected launching the TaP activity with a SecurityException. Log error.cause and notify support if persistent. |
Handling the initialization response
When TaP finishes provisioning (or confirms the device is already initialized), the SDK emits Response.DojoInit on DojoTapToPayOnPocket.responses.
- Properties
- Bundle
Check response.isSuccess == true to confirm initialization succeeded. When false, inspect response.detail for the failure code:
DojoTapToPayOnPocket.responses.collect { response ->
when (response) {
is Response.DojoInit -> {
val isSuccess: Boolean? = response.isSuccess
val detail: String? = response.detail
val terminalId: String? = response.terminalId
if (isSuccess == true) {
// Terminal is ready to accept sales and refunds (TID: terminalId)
} else {
// Initialization failed with error code in `detail`
}
}
else -> Unit
}
}
| Property | Value | Type |
|---|---|---|
isSuccess | true if initialization succeeded; false if it failed. | Boolean? |
detail | "OK" when initialized for the first time, "COMPLETED" if already initialized prior to the call, or an error code string on failure. | String? |
terminalId | Unique Terminal ID (TID) of the Pocket device (populated on success from TaP 26.07.15 onwards). | String? |
If you are migrating from an Intent-based integration, you can read the underlying extras from response.bundle:
DojoTapToPayOnPocket.responses.collect { response ->
when (response) {
is Response.DojoInit -> {
val initResult = response.bundle.getBoolean("com.dojo.extra.INIT_RESULT", false)
val initResultDetail = response.bundle.getString("com.dojo.extra.INIT_RESULT_DETAIL")
val terminalId = response.bundle.getString("com.dojo.extra.TERMINAL_ID")
}
else -> Unit
}
}
| Key (literal string) | Value | Type |
|---|---|---|
com.dojo.extra.INIT_RESULT | true if initialization succeeded; false if it failed. | Boolean |
com.dojo.extra.INIT_RESULT_DETAIL | "OK" (newly initialized), "COMPLETED" (already initialized), or an error code string on failure. | String |
com.dojo.extra.TERMINAL_ID | Unique Terminal ID (TID) of the Pocket device (returned from TaP 26.07.15 onwards). | String |
Initialization detail status and error codes
detail (INIT_RESULT_DETAIL) | isSuccess | Meaning & Recommended POS Action |
|---|---|---|
"OK" | true | Provisioning completed just now. No further action required; the terminal is ready for transactions. |
"COMPLETED" | true | The terminal was already provisioned prior to this initDojo() call, and its terminalId is now cached by the SDK. No further action required. |
"NO_TID" | false | Terminal ID was not found after initialization completed. Recommended action: Retry initDojo(). |
"E1" | false | A payment session failed to start during initialization. Recommended action: Retry initDojo(). |
"T1" | false | A timeout caused provisioning to be cancelled. Recommended action: Verify network connectivity and retry initDojo(). |
"A5" | false | Android Debug Bridge (ADB) or Developer Options is enabled on the device. Disable USB debugging / Developer Options in Android Settings and retry. |
"A6", "B2" | false | Network connectivity was disrupted during provisioning. Check Wi-Fi/mobile data connectivity and retry. |
"A1"–"A4", "A7"–"A12", "B1", "B3", "B4" | false | Payment kernel or attestation provisioning error (for example, "A10" unknown provisioning error, "A11" restricted app installed, "A12" attestation error). Retry initialization; if persistent, surface the code to support. |
"D99", "D<status>" | false | Terminal session linking failed with the Dojo backend. Verify network connectivity and retry. |
"R1" / "R2" / "R3" | false | Recovery required: "R1" (restart the TaP app), "R2" (restart the Pocket device), or "R3" (re-provision / disaster recovery). Prompt the operator accordingly. |
If the operator navigates back to your POS app before TaP finishes the initialization flow, DojoTapToPayOnPocket.responses emits Response.MissingResponse(requestType = RequestType.INIT). Because INIT does not create a backend transaction session, you can simply call initDojo() again when ready.
Sale
When a customer is ready to pay, call DojoTapToPayOnPocket.sale(...). Under the hood, the SDK:
- Validates that the SDK and terminal (
TID) are initialized,amountInPennies > 0, andcurrencyCodeis a valid ISO 4217 alpha-3 currency code. - Resolves the Pocket device's terminal UUID on the Dojo API.
- Creates a Dojo
PaymentIntent(withcaptureMode = "Auto") and prepares aSaleTerminalSessionon the Dojo API. - Dispatches
com.dojo.action.SALEto TaP on the device and returnsDojoResult.Success(SaleMetadata(paymentIntentId, terminalSessionId))to your caller. - Waits for the customer to present their contactless card or mobile wallet in TaP, then emits
Response.Sale(orResponse.SplitSaleif the operator splits the bill inside TaP) ontoDojoTapToPayOnPocket.responses.
Starting a sale
Method signature
suspend fun sale(
amountInPennies: Int,
reference: String = UUID.randomUUID().toString(),
currencyCode: String = "GBP",
): DojoResult<SaleMetadata, SaleError>
| Parameter | Default | Description & Constraints | Type |
|---|---|---|---|
amountInPennies | Required | Sale amount in the currency's minor units (for example, 1500 represents £15.00 in GBP). Must be strictly greater than 0 (> 0), otherwise fails immediately with InvalidAmount. | Int |
reference | UUID.randomUUID().toString() | Merchant reference attached to the Dojo PaymentIntent (for example, "Order #1234"). | String |
currencyCode | "GBP" | ISO 4217 3-letter currency code. Validated via java.util.Currency.getInstance; invalid codes fail immediately with InvalidCurrencyCode. | String |
Dispatching and persisting SaleMetadata
DojoResult.Success means the payment intent and terminal session were created and TaP was launched—not that the customer has paid yet. Always persist the returned SaleMetadata (paymentIntentId and terminalSessionId) to local storage before awaiting the final Response.Sale on DojoTapToPayOnPocket.responses so you can reconcile the sale if your POS process is killed while TaP is in the foreground:
import kotlinx.coroutines.launch
import tech.dojo.pos.ApiError
import tech.dojo.pos.AppInBackground
import tech.dojo.pos.DojoResult
import tech.dojo.pos.DpaNotInstalled
import tech.dojo.pos.DpaSecurityFailure
import tech.dojo.pos.DpaVersionUnsupported
import tech.dojo.pos.InvalidAmount
import tech.dojo.pos.InvalidCurrencyCode
import tech.dojo.pos.NetworkError
import tech.dojo.pos.SaleError
import tech.dojo.pos.SaleMetadata
import tech.dojo.pos.SdkNotInitialised
import tech.dojo.pos.TerminalNotFound
import tech.dojo.pos.UnexpectedError
import tech.dojo.pos.pocket.DojoTapToPayOnPocket
fun checkoutOrder(amountInPennies: Int, orderReference: String) {
scope.launch {
val result: DojoResult<SaleMetadata, SaleError> = DojoTapToPayOnPocket.sale(
amountInPennies = amountInPennies,
reference = orderReference,
currencyCode = "GBP",
)
when (result) {
is DojoResult.Success -> {
val metadata: SaleMetadata = result.value
// Persist metadata.paymentIntentId.value and metadata.terminalSessionId.value
// to durable storage until Response.Sale / Response.SplitSale is received
pendingTransactionStore.savePendingSale(
paymentIntentId = metadata.paymentIntentId.value,
terminalSessionId = metadata.terminalSessionId.value,
)
}
is DojoResult.Failure -> {
handleSaleDispatchError(result.error)
}
}
}
}
Handling sale dispatch errors
If sale() returns DojoResult.Failure(error), no transaction was started in TaP. The SaleError sealed interface allows exhaustive when handling across validation, terminal resolution, API transport, and intent dispatch failures:
fun handleSaleDispatchError(error: SaleError) {
when (error) {
is SdkNotInitialised -> {
// Either initSdk() has not been called, or initDojo() has not completed
// with a valid terminalId in this process yet.
}
is InvalidAmount -> {
// error.amountInPennies <= 0
}
is InvalidCurrencyCode -> {
// error.currencyCode is not a recognized ISO 4217 alpha-3 code
}
is TerminalNotFound -> {
// No Dojo terminal matched error.tid on the Dojo API for this API key / account
}
is ApiError -> {
// Dojo API returned non-2xx HTTP status (error.statusCode, error.body)
}
is NetworkError -> {
// Network failure reaching Dojo API (error.cause)
}
is UnexpectedError -> {
// Unexpected runtime or JSON parsing failure (error.cause)
}
is AppInBackground -> {
// POS app is not in the foreground; bring to foreground and retry
}
is DpaNotInstalled -> {
// TaP app is not installed on the device (error.action)
}
is DpaVersionUnsupported -> {
// Installed TaP version (error.installedVersionCode) < error.minimumVersionCode
}
is DpaSecurityFailure -> {
// Android blocked launching TaP (error.action, error.cause)
}
}
}
| Error Type | Category | Properties | Cause & Recommended POS Action |
|---|---|---|---|
SdkNotInitialised | SdkStateError | None (data object) | Either initSdk() was not called, or initDojo() has not yet completed with a valid terminalId in the current process. Call initDojo() and wait for Response.DojoInit(isSuccess = true) before retrying. |
InvalidAmount | TransactionValidationError | amountInPennies: Int | amountInPennies was <= 0. Pass a positive integer in minor currency units. |
InvalidCurrencyCode | TransactionValidationError | currencyCode: String | currencyCode is not a valid 3-letter ISO 4217 currency code. |
TerminalNotFound | TerminalResolutionError | tid: String | The TID reported by TaP during initDojo() was not found in the terminals list (GET /terminals) for your Dojo API key, softwareHouseId, and resellerId. Verify your API key and reseller credentials match the merchant account provisioned on the Pocket device. |
ApiError | TransportError | statusCode: Int, body: String | The Dojo API returned a non-2xx HTTP response while resolving the terminal or creating the PaymentIntent / TerminalSession. Check statusCode (401 invalid API key, 4xx bad request, 5xx server error). |
NetworkError | TransportError | cause: Throwable | A network connectivity error or timeout occurred before the transaction was dispatched to TaP. Safe to retry when back online. |
UnexpectedError | TransportError | cause: Throwable | An unexpected runtime failure occurred. Log error.cause for diagnostics. |
AppInBackground | DispatchError | None (data object) | Your POS app was not in the foreground when sale() was called or when API setup completed. Retry while your Activity is visible. |
DpaNotInstalled | DispatchError | action: String | The TaP app is not installed or cannot handle com.dojo.action.SALE. |
DpaVersionUnsupported | DispatchError | installedVersionCode: Long, minimumVersionCode: Long | The installed TaP app is older than the minimum version required by the SDK. Update TaP on the device. |
DpaSecurityFailure | DispatchError | action: String, cause: SecurityException | Android threw a SecurityException while starting the TaP activity. |
Expected POS Action
When the customer completes or cancels the payment in TaP (or when automatic foreground reconciliation resolves an interrupted callback), the SDK emits Response.Sale on DojoTapToPayOnPocket.responses (or Response.SplitSale if the bill was split in TaP).
responses, not returned as SaleErrorOnce sale() returns DojoResult.Success(SaleMetadata), any card decline, customer cancellation, or terminal expiration is delivered as a Response.Sale on DojoTapToPayOnPocket.responses with response.transactionResult set to DECLINED, CANCELLED, or FAILED. Always inspect response.transactionResult to determine whether the payment was authorised.
- Properties
- Bundle
Inspect response.transactionResult to determine whether the sale was authorised, declined, cancelled, or failed:
import tech.dojo.pos.Response
import tech.dojo.pos.TransactionResult
import tech.dojo.pos.pocket.DojoTapToPayOnPocket
DojoTapToPayOnPocket.responses.collect { response ->
when (response) {
is Response.Sale -> {
val saleStatus = response.saleStatus
val transactionResult = response.transactionResult
val baseAmount = response.baseAmount
val gratuityAmount = response.gratuityAmount
val transactionId = response.transactionId
val authCode = response.authCode
val paymentMethod = response.paymentMethod
val cvm = response.cardholderVerificationMethod
val cardScheme = response.cardScheme
val cardApplicationLabel = response.cardApplicationLabel
val cardApplicationId = response.cardApplicationId
val cardPan = response.cardPan
val dateTime = response.dateTime
val paymentIntentId = response.paymentIntentId
val terminalSessionId = response.terminalSessionId
when (transactionResult) {
TransactionResult.AUTHORISED -> {
// Mark order as paid, store receipt details, and clear persisted SaleMetadata
pendingTransactionStore.clearPendingSale()
}
TransactionResult.DECLINED,
TransactionResult.CANCELLED,
TransactionResult.FAILED,
TransactionResult.UNKNOWN,
null -> {
// Payment was not taken; clear persisted SaleMetadata and allow retry with a new sale() call
pendingTransactionStore.clearPendingSale()
}
}
}
else -> Unit
}
}
| Property | Value | Type |
|---|---|---|
saleStatus | Status of the sale request ("OK"). | String? |
transactionResult | AUTHORISED / DECLINED / CANCELLED / FAILED / UNKNOWN | TransactionResult? |
baseAmount | Base transaction amount in pennies (minor units). | Int? |
gratuityAmount | Tip / gratuity amount in pennies (if a tip was added in TaP). | Int? |
transactionId | Unique TaP terminal transaction identifier. | String? |
authCode | Card issuer authorization code. | String? |
paymentMethod | CONTACTLESS / CHIP / SWIPE / MANUAL_ENTRY / KEYED / UNKNOWN | PaymentMethod? |
cardholderVerificationMethod | PIN / SIGNATURE / DEVICE / NONE / UNKNOWN | CardholderVerificationMethod? |
cardScheme | Card brand string (for example, "VISA", "MASTERCARD", "MAESTRO", "AMERICAN_EXPRESS", "DISCOVER", "DINERS", "JCB", "UNION_PAY", "ALIPAY", "BANCOMAT", "CONECS", "UNKNOWN"). | String? |
cardApplicationLabel | EMV card application label (for example, "VISA DEBIT"). | String? |
cardApplicationId | EMV card application identifier (for example, "A0000000031010"). Note: null on API-reconciled responses. | String? |
cardPan | Masked card Primary Account Number (for example, "************0226"). | String? |
dateTime | ISO 8601 UTC timestamp string of the transaction (for example, "2026-11-10T14:32:10Z"). | String? |
paymentIntentId | Dojo API payment intent identifier (paymentIntentId.value). | PaymentIntentId? |
terminalSessionId | Dojo API terminal session identifier (terminalSessionId.value). | TerminalSessionId? |
You can also read the raw Intent extras from response.bundle:
DojoTapToPayOnPocket.responses.collect { response ->
when (response) {
is Response.Sale -> {
val saleStatus = response.bundle.getString("com.dojo.extra.SALE_STATUS")
val transactionResult = response.bundle.getString("com.dojo.extra.TRANSACTION_RESULT")
val baseAmount = response.bundle.getInt("com.dojo.extra.BASE_AMOUNT")
val gratuityAmount = response.bundle.getInt("com.dojo.extra.GRATUITY_AMOUNT")
val transactionId = response.bundle.getString("com.dojo.extra.TRANSACTION_ID")
val authCode = response.bundle.getString("com.dojo.extra.AUTH_CODE")
val paymentMethod = response.bundle.getString("com.dojo.extra.PAYMENT_METHOD")
val cvm = response.bundle.getString("com.dojo.extra.CARDHOLDER_VERIFICATION_METHOD")
val cardScheme = response.bundle.getString("com.dojo.extra.CARD_SCHEME")
val cardApplicationLabel = response.bundle.getString("com.dojo.extra.CARD_APPLICATION_LABEL")
val cardApplicationId = response.bundle.getString("com.dojo.extra.CARD_APPLICATION_ID")
val cardPan = response.bundle.getString("com.dojo.extra.CARD_PAN")
val dateTime = response.bundle.getString("com.dojo.extra.DATE_TIME")
val paymentIntentId = response.bundle.getString("com.dojo.extra.PAYMENT_INTENT_ID")
val terminalSessionId = response.bundle.getString("com.dojo.extra.TERMINAL_SESSION_ID")
}
else -> Unit
}
}
| Key (literal string) | Value | Type |
|---|---|---|
com.dojo.extra.SALE_STATUS | "OK" | String |
com.dojo.extra.TRANSACTION_RESULT | "AUTHORISED" / "DECLINED" / "CANCELLED" / "FAILED" / "UNKNOWN" | String |
com.dojo.extra.BASE_AMOUNT | Base transaction amount in pennies. | Int |
com.dojo.extra.GRATUITY_AMOUNT | Gratuity transaction amount in pennies. | Int |
com.dojo.extra.TRANSACTION_ID | Unique TaP transaction identifier. | String |
com.dojo.extra.AUTH_CODE | Card issuer authorization code. | String |
com.dojo.extra.PAYMENT_METHOD | "CONTACTLESS" / "CHIP" / "ICC_CHIP" / "SWIPE" / "MANUAL_ENTRY" / "KEYED" / "UNKNOWN" (Note: response.paymentMethod normalizes both "CHIP" and "ICC_CHIP" to PaymentMethod.CHIP). | String |
com.dojo.extra.CARDHOLDER_VERIFICATION_METHOD | "PIN" / "SIGNATURE" / "DEVICE" / "NONE" / "UNKNOWN" | String |
com.dojo.extra.CARD_SCHEME | "VISA" / "MASTERCARD" / "MAESTRO" / "AMERICAN_EXPRESS" / "DISCOVER" / "DINERS" / "JCB" / "UNION_PAY" / "ALIPAY" / "BANCOMAT" / "CONECS" / "UNKNOWN" | String |
com.dojo.extra.CARD_APPLICATION_LABEL | EMV application label. | String |
com.dojo.extra.CARD_APPLICATION_ID | EMV application ID (null when reconstructed via API reconciliation). | String |
com.dojo.extra.CARD_PAN | Masked card Primary Account Number (for example, "************0226"). | String |
com.dojo.extra.DATE_TIME | ISO 8601 UTC timestamp string of the transaction. | String |
com.dojo.extra.PAYMENT_INTENT_ID | Dojo API payment intent ID. | String |
com.dojo.extra.TERMINAL_SESSION_ID | Dojo API terminal session ID. | String |
Interpreting TransactionResult
TransactionResult | Meaning | Recommended POS Action |
|---|---|---|
AUTHORISED | The acquiring bank authorised the transaction and funds will be captured automatically. | Mark the order as paid, record the receipt fields (transactionId, authCode, cardPan, cardScheme, dateTime), and clear persisted SaleMetadata. |
DECLINED | The card issuer declined the payment (or signature verification was rejected). | Inform the operator/customer that the card was declined, clear persisted SaleMetadata, and allow starting a new sale() with an alternative payment method. |
CANCELLED | The customer or operator cancelled the payment in TaP before completion. | Keep the order unpaid, clear persisted SaleMetadata, and allow starting a new sale() when ready. |
FAILED | A technical error or session expiration prevented the transaction from completing. | Clear persisted SaleMetadata and prompt the operator to retry with a new sale(). |
UNKNOWN | An unrecognized result string was returned. | Reconcile the transaction using reconcileSale with its SaleMetadata to verify the authoritative status on the Dojo API. |
Refund
To issue an unlinked contactless refund to a customer's card, call DojoTapToPayOnPocket.refund(...). Unlike a sale—which creates both a PaymentIntent and a TerminalSession—an unlinked refund creates a standalone UnlinkedRefund TerminalSession on the Dojo API and launches TaP so the customer can tap their card to receive the refund.
Starting a refund
Method signature
suspend fun refund(
amountInPennies: Int,
currencyCode: String = "GBP",
): DojoResult<RefundMetadata, RefundError>
| Parameter | Default | Description & Constraints | Type |
|---|---|---|---|
amountInPennies | Required | Refund amount in the currency's minor units (for example, 1500 represents £15.00 in GBP). Must be strictly greater than 0 (> 0), otherwise fails immediately with InvalidAmount. | Int |
currencyCode | "GBP" | ISO 4217 3-letter currency code. Validated via java.util.Currency.getInstance; invalid codes fail immediately with InvalidCurrencyCode. | String |
Dispatching and persisting RefundMetadata
When refund() succeeds, it returns DojoResult.Success(RefundMetadata(terminalSessionId)). Persist terminalSessionId to local storage immediately so you can call reconcileRefund if the response from TaP is interrupted:
import kotlinx.coroutines.launch
import tech.dojo.pos.DojoResult
import tech.dojo.pos.RefundError
import tech.dojo.pos.RefundMetadata
import tech.dojo.pos.pocket.DojoTapToPayOnPocket
fun issueRefund(amountInPennies: Int) {
scope.launch {
val result: DojoResult<RefundMetadata, RefundError> = DojoTapToPayOnPocket.refund(
amountInPennies = amountInPennies,
currencyCode = "GBP",
)
when (result) {
is DojoResult.Success -> {
val metadata: RefundMetadata = result.value
// Persist metadata.terminalSessionId.value to durable storage
// until Response.Refund is received
pendingTransactionStore.savePendingRefund(
terminalSessionId = metadata.terminalSessionId.value,
)
}
is DojoResult.Failure -> {
val error: RefundError = result.error
// Handle SdkNotInitialised, InvalidAmount, InvalidCurrencyCode,
// TerminalNotFound, ApiError, NetworkError, UnexpectedError,
// AppInBackground, DpaVersionUnsupported, DpaNotInstalled, or DpaSecurityFailure
}
}
}
}
Handling refund dispatch errors
RefundError shares the exact same 11 error subtypes as SaleError:
- State & validation:
SdkNotInitialised(eitherinitSdk()was not called orinitDojo()has not cached aterminalIdin this process),InvalidAmount,InvalidCurrencyCode. - Terminal resolution & API transport:
TerminalNotFound,ApiError,NetworkError,UnexpectedError. - Intent dispatch:
AppInBackground,DpaNotInstalled,DpaVersionUnsupported,DpaSecurityFailure.
Expected POS Action
Once the customer presents their card in TaP and the acquiring bank responds (or when automatic foreground reconciliation resolves an interrupted callback), the SDK emits Response.Refund on DojoTapToPayOnPocket.responses.
- Properties
- Bundle
Check response.transactionResult == TransactionResult.AUTHORISED to verify whether the refund was authorised:
import tech.dojo.pos.Response
import tech.dojo.pos.TransactionResult
import tech.dojo.pos.pocket.DojoTapToPayOnPocket
DojoTapToPayOnPocket.responses.collect { response ->
when (response) {
is Response.Refund -> {
val refundStatus = response.refundStatus
val transactionResult = response.transactionResult
val baseAmount = response.baseAmount
val transactionId = response.transactionId
val authCode = response.authCode
val paymentMethod = response.paymentMethod
val cvm = response.cardholderVerificationMethod
val cardScheme = response.cardScheme
val cardApplicationLabel = response.cardApplicationLabel
val cardApplicationId = response.cardApplicationId
val cardPan = response.cardPan
val dateTime = response.dateTime
val terminalSessionId = response.terminalSessionId
when (transactionResult) {
TransactionResult.AUTHORISED -> {
// Record completed refund and clear persisted RefundMetadata
pendingTransactionStore.clearPendingRefund()
}
TransactionResult.DECLINED,
TransactionResult.CANCELLED,
TransactionResult.FAILED,
TransactionResult.UNKNOWN,
null -> {
// Refund was not processed; clear persisted RefundMetadata
pendingTransactionStore.clearPendingRefund()
}
}
}
else -> Unit
}
}
| Property | Value | Type |
|---|---|---|
refundStatus | Status of the refund request ("OK"). | String? |
transactionResult | AUTHORISED / DECLINED / CANCELLED / FAILED / UNKNOWN | TransactionResult? |
baseAmount | Refund amount in pennies (minor units). | Int? |
transactionId | Unique TaP terminal transaction identifier. | String? |
authCode | Card issuer authorization code. | String? |
paymentMethod | CONTACTLESS / CHIP / SWIPE / MANUAL_ENTRY / KEYED / UNKNOWN | PaymentMethod? |
cardholderVerificationMethod | PIN / SIGNATURE / DEVICE / NONE / UNKNOWN | CardholderVerificationMethod? |
cardScheme | Card brand string (for example, "VISA", "MASTERCARD", "MAESTRO", "AMERICAN_EXPRESS" or "AMEX", "DISCOVER", "DINERS", "JCB", "UNION_PAY", "UNKNOWN"). | String? |
cardApplicationLabel | EMV card application label. | String? |
cardApplicationId | EMV card application ID (null on API-reconciled responses). | String? |
cardPan | Masked card Primary Account Number (for example, "************0226"). | String? |
dateTime | ISO 8601 UTC timestamp string of the refund transaction. | String? |
terminalSessionId | Dojo API terminal session identifier (terminalSessionId.value). | TerminalSessionId? |
You can also read the raw Intent extras from response.bundle (note that TaP uses "com.dojo.extra.SALE_STATUS" for both sales and refunds):
DojoTapToPayOnPocket.responses.collect { response ->
when (response) {
is Response.Refund -> {
val refundStatus = response.bundle.getString("com.dojo.extra.SALE_STATUS")
val transactionResult = response.bundle.getString("com.dojo.extra.TRANSACTION_RESULT")
val baseAmount = response.bundle.getInt("com.dojo.extra.BASE_AMOUNT")
val transactionId = response.bundle.getString("com.dojo.extra.TRANSACTION_ID")
val authCode = response.bundle.getString("com.dojo.extra.AUTH_CODE")
val paymentMethod = response.bundle.getString("com.dojo.extra.PAYMENT_METHOD")
val cvm = response.bundle.getString("com.dojo.extra.CARDHOLDER_VERIFICATION_METHOD")
val cardScheme = response.bundle.getString("com.dojo.extra.CARD_SCHEME")
val cardApplicationLabel = response.bundle.getString("com.dojo.extra.CARD_APPLICATION_LABEL")
val cardApplicationId = response.bundle.getString("com.dojo.extra.CARD_APPLICATION_ID")
val cardPan = response.bundle.getString("com.dojo.extra.CARD_PAN")
val dateTime = response.bundle.getString("com.dojo.extra.DATE_TIME")
val terminalSessionId = response.bundle.getString("com.dojo.extra.TERMINAL_SESSION_ID")
}
else -> Unit
}
}
| Key (literal string) | Value | Type |
|---|---|---|
com.dojo.extra.SALE_STATUS | "OK" | String |
com.dojo.extra.TRANSACTION_RESULT | "AUTHORISED" / "DECLINED" / "CANCELLED" / "FAILED" / "UNKNOWN" | String |
com.dojo.extra.BASE_AMOUNT | Refund transaction amount in pennies. | Int |
com.dojo.extra.TRANSACTION_ID | Unique TaP transaction identifier. | String |
com.dojo.extra.AUTH_CODE | Card issuer authorization code. | String |
com.dojo.extra.PAYMENT_METHOD | "CONTACTLESS" / "CHIP" / "ICC_CHIP" / "SWIPE" / "MANUAL_ENTRY" / "KEYED" / "UNKNOWN" | String |
com.dojo.extra.CARDHOLDER_VERIFICATION_METHOD | "PIN" / "SIGNATURE" / "DEVICE" / "NONE" / "UNKNOWN" | String |
com.dojo.extra.CARD_SCHEME | "VISA" / "MASTERCARD" / "MAESTRO" / "AMERICAN_EXPRESS" / "AMEX" / "DISCOVER" / "DINERS" / "JCB" / "UNION_PAY" / "UNKNOWN" | String |
com.dojo.extra.CARD_APPLICATION_LABEL | EMV application label. | String |
com.dojo.extra.CARD_APPLICATION_ID | EMV application ID (null when reconstructed via API reconciliation). | String |
com.dojo.extra.CARD_PAN | Masked card Primary Account Number. | String |
com.dojo.extra.DATE_TIME | ISO 8601 UTC timestamp string of the transaction. | String |
com.dojo.extra.TERMINAL_SESSION_ID | Dojo API terminal session ID. | String |
Reconciling transactions
When your POS application dispatches a sale or refund, the SDK creates resources in the Dojo API and hands control over to the TaP application on the device. Under normal conditions, once the customer completes or cancels the interaction, TaP returns the outcome via an Android PendingIntent and the SDK emits Response.Sale, Response.SplitSale, or Response.Refund on DojoTapToPayOnPocket.responses.
However, an Intent response from TaP may not reach your POS application if:
- The user switches apps or returns to the POS app before TaP finishes sending the result.
- The Android operating system reclaims your POS app's process while TaP is in the foreground (process death).
- Automatic foreground reconciliation is disabled or its polling window expires before the transaction reaches a terminal state.
To guarantee that no transaction outcome is lost—and prevent double-charging or orphaned refunds—the SDK provides two complementary layers of reconciliation:
- Automatic foreground reconciliation: Enabled by default (
ForegroundReconciliationConfig.enabled = true). When focus returns to your POS app while asaleorrefundis still awaiting a response from TaP, the SDK automatically polls the Dojo API (by default every1,000ms for up to5,000ms). If the transaction reaches a terminal status during this window, the SDK reconstructs and emitsResponse.SaleorResponse.Refunddirectly ontoDojoTapToPayOnPocket.responses. If the polling window expires while the transaction is still non-terminal (or if automatic reconciliation is disabled), the SDK emitsResponse.MissingResponse. - Manual reconciliation (
reconcileSaleandreconcileRefund): Stateless, read-only, single-shot suspend functions that query the Dojo API directly for the current status of a specific sale or refund using its metadata identifiers. CallingreconcileSaleorreconcileRefunddoes not launch the TaP UI, dispatch a new transaction, modify pending-request tracking, or emit ontoDojoTapToPayOnPocket.responses. Furthermore,reconcileSaleandreconcileRefundonly requireinitSdk()to have succeeded in the current process—they do not requireinitDojo()to have run first, allowing you to recover persisted transactions immediately on app startup after process death.
API-based reconciliation queries the single TerminalSession and PaymentIntent created when sale() was called and always reconstructs a single-transaction Response.Sale. Neither mechanism emits or returns Response.SplitSale. Split bill transactions (Response.SplitSale) are currently only returned via the direct PendingIntent response from TaP or recovered on-device via lastTx().
Flow diagram: Transaction and reconciliation lifecycle
flowchart TD
Dispatch["POS calls sale() or refund()"] --> Created["DojoResult.Success(SaleMetadata / RefundMetadata) - POS persists metadata & TaP opens"]
Created --> Outcome{"How does POS regain control?"}
Outcome -->|"TaP sends TX_COMPLETE Intent"| DirectResponse["SDK emits Response.Sale / Response.SplitSale / Response.Refund on responses"]
Outcome -->|"POS returns to foreground without TaP response"| AutoCheck{"Foreground reconciliation enabled?"}
Outcome -->|"POS process recreated after OS process death"| LoadPersisted["POS loads persisted SaleMetadata / RefundMetadata after initSdk()"]
AutoCheck -->|"Yes (polls up to windowMs)"| AutoOutcome{"Terminal status reached in window?"}
AutoCheck -->|"No"| Missing["SDK emits Response.MissingResponse on responses"]
AutoOutcome -->|"Yes"| ReconstructedResponse["SDK emits reconstructed Response.Sale / Response.Refund on responses"]
AutoOutcome -->|"No (timeout / network error)"| Missing
Missing --> ManualCall["POS calls reconcileSale(metadata) or reconcileRefund(metadata)"]
LoadPersisted --> ManualCall
ManualCall --> ManualResult{"ManualReconciliationResult"}
ManualResult -->|"Resolved(response)"| TerminalHandled["POS processes reconstructed Response.Sale or Response.Refund & clears persisted metadata"]
ManualResult -->|"Unresolved(status)"| NonTerminal["Transaction still non-terminal (e.g. Created, Initiated) - wait & retry or handle status"]
DirectResponse --> ClearPersisted["POS processes response & clears persisted metadata"]
ReconstructedResponse --> ClearPersisted
Capturing and persisting metadata
To call reconcileSale or reconcileRefund, you must pass the identifiers created for that specific request:
SaleMetadata: ContainspaymentIntentId: PaymentIntentIdandterminalSessionId: TerminalSessionId(both@JvmInline value classwrappers around avalue: String).RefundMetadata: ContainsterminalSessionId: TerminalSessionId.
You can obtain these metadata objects in two ways:
1. When dispatching sale or refund (recommended)
DojoTapToPayOnPocket.sale(...) and DojoTapToPayOnPocket.refund(...) return DojoResult.Success(SaleMetadata) and DojoResult.Success(RefundMetadata) as soon as the Dojo API session is created and the TaP Intent is dispatched.
If Android terminates your POS process while TaP is in the foreground, in-memory state is lost and Response.MissingResponse will not be emitted when your app restarts. Always persist SaleMetadata or RefundMetadata to durable local storage (such as Room, DataStore, or SharedPreferences) immediately upon DojoResult.Success, check for any persisted metadata on startup right after initSdk(), and clear it once a terminal outcome is recorded.
scope.launch {
when (val result = DojoTapToPayOnPocket.sale(amountInPennies = 1500, reference = "Order #1234")) {
is DojoResult.Success -> {
val metadata: SaleMetadata = result.value
// Persist metadata.paymentIntentId.value and metadata.terminalSessionId.value
// to local storage so you can call reconcileSale(metadata) if the process is recreated
pendingTransactionStore.savePendingSale(
paymentIntentId = metadata.paymentIntentId.value,
terminalSessionId = metadata.terminalSessionId.value,
)
}
is DojoResult.Failure -> {
val error: SaleError = result.error
// Handle dispatch failure (no transaction was started in TaP)
}
}
}
Similarly, for an unlinked refund:
scope.launch {
when (val result = DojoTapToPayOnPocket.refund(amountInPennies = 1500)) {
is DojoResult.Success -> {
val metadata: RefundMetadata = result.value
// Persist metadata.terminalSessionId.value to local storage
pendingTransactionStore.savePendingRefund(
terminalSessionId = metadata.terminalSessionId.value,
)
}
is DojoResult.Failure -> {
val error: RefundError = result.error
// Handle dispatch failure
}
}
}
If your POS process is recreated by the OS while TaP was in the foreground, reconstruct SaleMetadata or RefundMetadata from your persisted strings and reconcile immediately after initSdk():
fun recoverPendingTransactionsOnStartup() {
pendingTransactionStore.loadPendingSale()?.let { saved ->
val metadata = SaleMetadata(
paymentIntentId = PaymentIntentId(saved.paymentIntentId),
terminalSessionId = TerminalSessionId(saved.terminalSessionId),
)
scope.launch { reconcileMissingSale(metadata) }
}
pendingTransactionStore.loadPendingRefund()?.let { saved ->
val metadata = RefundMetadata(
terminalSessionId = TerminalSessionId(saved.terminalSessionId),
)
scope.launch { reconcileMissingRefund(metadata) }
}
}
2. When receiving Response.MissingResponse
If your POS process remains alive and returns to the foreground without receiving a terminal response from TaP (and automatic foreground reconciliation does not resolve the transaction within its polling window), DojoTapToPayOnPocket.responses emits Response.MissingResponse:
data class MissingResponse(
val requestType: RequestType,
val paymentIntentId: PaymentIntentId? = null,
val terminalSessionId: TerminalSessionId? = null,
) : Response
You can construct SaleMetadata or RefundMetadata directly from the identifiers attached to Response.MissingResponse:
DojoTapToPayOnPocket.responses.collect { response ->
when (response) {
is Response.MissingResponse -> {
when (response.requestType) {
RequestType.SALE -> {
val paymentIntentId = response.paymentIntentId
val terminalSessionId = response.terminalSessionId
if (paymentIntentId != null && terminalSessionId != null) {
val metadata = SaleMetadata(
paymentIntentId = paymentIntentId,
terminalSessionId = terminalSessionId,
)
reconcileMissingSale(metadata)
}
}
RequestType.REFUND -> {
val terminalSessionId = response.terminalSessionId
if (terminalSessionId != null) {
val metadata = RefundMetadata(
terminalSessionId = terminalSessionId,
)
reconcileMissingRefund(metadata)
}
}
RequestType.INIT,
RequestType.LAST_TX -> {
// INIT and LAST_TX do not create backend terminal sessions; retry directly if needed
}
}
}
// Handle Response.DojoInit, Response.Sale, Response.SplitSale, Response.Refund, Response.LastTx...
else -> Unit
}
}
Reconciling a sale (reconcileSale)
reconcileSale queries the Dojo API for the current status of the sale's terminal session (GET /terminal-sessions/{terminalSessionId}). If the terminal session has reached a terminal status, the SDK fetches the corresponding payment intent (GET /payment-intents/{paymentIntentId}) to populate baseAmount and gratuityAmount, and reconstructs a Response.Sale. If the terminal session is still in a non-terminal status, the SDK returns ManualReconciliationResult.Unresolved immediately without making a second request for the payment intent.
Method signature
suspend fun reconcileSale(
metadata: SaleMetadata,
apiCallConfig: ApiCallConfig = ApiCallConfig(maxAttempts = 1),
): DojoResult<ManualReconciliationResult<Response.Sale>, SaleReconciliationError>
Handling the result
When reconcileSale returns DojoResult.Success(ManualReconciliationResult.Resolved(response)), response is a standard Response.Sale instance exposing the same typed properties and Bundle extras documented in the Sale section.
- Properties
- Bundle
suspend fun reconcileMissingSale(metadata: SaleMetadata) {
when (val result = DojoTapToPayOnPocket.reconcileSale(metadata)) {
is DojoResult.Success -> {
when (val outcome = result.value) {
is ManualReconciliationResult.Resolved -> {
val saleResponse: Response.Sale = outcome.response
val saleStatus = saleResponse.saleStatus
val transactionResult = saleResponse.transactionResult
val baseAmount = saleResponse.baseAmount
val gratuityAmount = saleResponse.gratuityAmount
val transactionId = saleResponse.transactionId
val authCode = saleResponse.authCode
val paymentMethod = saleResponse.paymentMethod
val cvm = saleResponse.cardholderVerificationMethod
val cardScheme = saleResponse.cardScheme
val cardApplicationLabel = saleResponse.cardApplicationLabel
val cardPan = saleResponse.cardPan
val dateTime = saleResponse.dateTime
val paymentIntentId = saleResponse.paymentIntentId
val terminalSessionId = saleResponse.terminalSessionId
pendingTransactionStore.clearPendingSale()
}
is ManualReconciliationResult.Unresolved -> {
val backendStatus: String = outcome.status
// Transaction is still non-terminal (e.g. "Created" or "Initiated")
}
}
}
is DojoResult.Failure -> {
val error: SaleReconciliationError = result.error
// Handle SdkNotInitialised, ApiError, NetworkError, or UnexpectedError
}
}
}
suspend fun reconcileMissingSale(metadata: SaleMetadata) {
when (val result = DojoTapToPayOnPocket.reconcileSale(metadata)) {
is DojoResult.Success -> {
when (val outcome = result.value) {
is ManualReconciliationResult.Resolved -> {
val bundle = outcome.response.bundle
val saleStatus = bundle.getString("com.dojo.extra.SALE_STATUS")
val transactionResult = bundle.getString("com.dojo.extra.TRANSACTION_RESULT")
val baseAmount = bundle.getInt("com.dojo.extra.BASE_AMOUNT")
val gratuityAmount = bundle.getInt("com.dojo.extra.GRATUITY_AMOUNT")
val transactionId = bundle.getString("com.dojo.extra.TRANSACTION_ID")
val authCode = bundle.getString("com.dojo.extra.AUTH_CODE")
val paymentMethod = bundle.getString("com.dojo.extra.PAYMENT_METHOD")
val cvm = bundle.getString("com.dojo.extra.CARDHOLDER_VERIFICATION_METHOD")
val cardScheme = bundle.getString("com.dojo.extra.CARD_SCHEME")
val cardApplicationLabel = bundle.getString("com.dojo.extra.CARD_APPLICATION_LABEL")
val cardPan = bundle.getString("com.dojo.extra.CARD_PAN")
val dateTime = bundle.getString("com.dojo.extra.DATE_TIME")
val paymentIntentId = bundle.getString("com.dojo.extra.PAYMENT_INTENT_ID")
val terminalSessionId = bundle.getString("com.dojo.extra.TERMINAL_SESSION_ID")
pendingTransactionStore.clearPendingSale()
}
is ManualReconciliationResult.Unresolved -> {
val backendStatus: String = outcome.status
// Transaction is still non-terminal (e.g. "Created" or "Initiated")
}
}
}
is DojoResult.Failure -> {
val error: SaleReconciliationError = result.error
// Handle SdkNotInitialised, ApiError, NetworkError, or UnexpectedError
}
}
}
Reconciling a refund (reconcileRefund)
reconcileRefund queries the Dojo API for the current status of an unlinked refund's terminal session (GET /terminal-sessions/{terminalSessionId}). If the terminal session has reached a terminal status, the SDK reconstructs a Response.Refund from the session details.
Method signature
suspend fun reconcileRefund(
metadata: RefundMetadata,
apiCallConfig: ApiCallConfig = ApiCallConfig(maxAttempts = 1),
): DojoResult<ManualReconciliationResult<Response.Refund>, RefundReconciliationError>
Handling the result
When reconcileRefund returns DojoResult.Success(ManualReconciliationResult.Resolved(response)), response is a standard Response.Refund instance exposing the same typed properties and Bundle extras documented in the Refund section.
- Properties
- Bundle
suspend fun reconcileMissingRefund(metadata: RefundMetadata) {
when (val result = DojoTapToPayOnPocket.reconcileRefund(metadata)) {
is DojoResult.Success -> {
when (val outcome = result.value) {
is ManualReconciliationResult.Resolved -> {
val refundResponse: Response.Refund = outcome.response
val refundStatus = refundResponse.refundStatus
val transactionResult = refundResponse.transactionResult
val baseAmount = refundResponse.baseAmount
val transactionId = refundResponse.transactionId
val authCode = refundResponse.authCode
val paymentMethod = refundResponse.paymentMethod
val cvm = refundResponse.cardholderVerificationMethod
val cardScheme = refundResponse.cardScheme
val cardApplicationLabel = refundResponse.cardApplicationLabel
val cardPan = refundResponse.cardPan
val dateTime = refundResponse.dateTime
val terminalSessionId = refundResponse.terminalSessionId
pendingTransactionStore.clearPendingRefund()
}
is ManualReconciliationResult.Unresolved -> {
val backendStatus: String = outcome.status
// Refund is still non-terminal (e.g. "Created" or "Initiated")
}
}
}
is DojoResult.Failure -> {
val error: RefundReconciliationError = result.error
// Handle SdkNotInitialised, ApiError, NetworkError, or UnexpectedError
}
}
}
suspend fun reconcileMissingRefund(metadata: RefundMetadata) {
when (val result = DojoTapToPayOnPocket.reconcileRefund(metadata)) {
is DojoResult.Success -> {
when (val outcome = result.value) {
is ManualReconciliationResult.Resolved -> {
val bundle = outcome.response.bundle
val refundStatus = bundle.getString("com.dojo.extra.SALE_STATUS")
val transactionResult = bundle.getString("com.dojo.extra.TRANSACTION_RESULT")
val baseAmount = bundle.getInt("com.dojo.extra.BASE_AMOUNT")
val transactionId = bundle.getString("com.dojo.extra.TRANSACTION_ID")
val authCode = bundle.getString("com.dojo.extra.AUTH_CODE")
val paymentMethod = bundle.getString("com.dojo.extra.PAYMENT_METHOD")
val cvm = bundle.getString("com.dojo.extra.CARDHOLDER_VERIFICATION_METHOD")
val cardScheme = bundle.getString("com.dojo.extra.CARD_SCHEME")
val cardApplicationLabel = bundle.getString("com.dojo.extra.CARD_APPLICATION_LABEL")
val cardPan = bundle.getString("com.dojo.extra.CARD_PAN")
val dateTime = bundle.getString("com.dojo.extra.DATE_TIME")
val terminalSessionId = bundle.getString("com.dojo.extra.TERMINAL_SESSION_ID")
pendingTransactionStore.clearPendingRefund()
}
is ManualReconciliationResult.Unresolved -> {
val backendStatus: String = outcome.status
// Refund is still non-terminal (e.g. "Created" or "Initiated")
}
}
}
is DojoResult.Failure -> {
val error: RefundReconciliationError = result.error
// Handle SdkNotInitialised, ApiError, NetworkError, or UnexpectedError
}
}
}
Understanding ManualReconciliationResult and backend statuses
A successful API lookup returns DojoResult.Success containing a ManualReconciliationResult, which is a sealed interface with two variants:
ManualReconciliationResult.Resolved(val response: T): The Dojo backend reported a terminal status for the terminal session, and the SDK reconstructed the correspondingResponse.SaleorResponse.Refund.ManualReconciliationResult.Unresolved(val status: String): The API request succeeded, but the terminal session is still in a non-terminal state on the backend. This is modelled asDojoResult.Successrather thanDojoResult.Failurebecause the lookup itself succeeded.
The table below shows how the SDK maps Dojo API TerminalSession statuses to ManualReconciliationResult and TransactionResult:
Backend TerminalSession.status | Terminal? | ManualReconciliationResult | response.transactionResult (com.dojo.extra.TRANSACTION_RESULT) | Recommended POS Action |
|---|---|---|---|---|
"Authorized" | Yes | Resolved | TransactionResult.AUTHORISED ("AUTHORISED") | Mark transaction as paid/refunded and clear persisted metadata. |
"Captured" | Yes | Resolved | TransactionResult.AUTHORISED ("AUTHORISED") | Mark transaction as paid/refunded and clear persisted metadata. |
"SignatureVerificationAccepted" | Yes | Resolved | TransactionResult.AUTHORISED ("AUTHORISED") | Mark transaction as paid/refunded and clear persisted metadata. |
"Declined" | Yes | Resolved | TransactionResult.DECLINED ("DECLINED") | Mark transaction as declined; safe to start a new transaction. |
"SignatureVerificationRejected" | Yes | Resolved | TransactionResult.DECLINED ("DECLINED") | Mark transaction as declined; safe to start a new transaction. |
"Canceled" | Yes | Resolved | TransactionResult.CANCELLED ("CANCELLED") | Mark transaction as cancelled; safe to start a new transaction. |
"CancelRequested" | Yes | Resolved | TransactionResult.CANCELLED ("CANCELLED") | Mark transaction as cancelled; safe to start a new transaction. |
"Expired" | Yes | Resolved | TransactionResult.FAILED ("FAILED") | Mark transaction as failed; safe to start a new transaction. |
"Created" | No | Unresolved("Created") | N/A | Session was created on the backend but never started on TaP. If focus has already returned to your POS app, you can safely clear the pending metadata and start a new transaction. |
"InitiateRequested" / "Initiated" / "SignatureVerificationRequired" (or any other status) | No | Unresolved(status) | N/A | Transaction is still in progress. Wait and call reconcileSale / reconcileRefund again before starting a new payment. |
- Single-transaction reconstruction only (no
SplitSale): Reconstructed sale responses never setcom.dojo.extra.SPLIT_BILL(Response.SplitSale), as the Dojo REST API endpoints queried during reconciliation represent a singleTerminalSessionandPaymentIntent. - EMV Application ID (
cardApplicationId): In responses reconstructed viareconcileSaleorreconcileRefund(as well as automatic foreground reconciliation),cardApplicationId(com.dojo.extra.CARD_APPLICATION_ID) isnullbecause the EMV application ID is not returned by the Dojo REST API.cardApplicationLabelis synthesized from the API'scardTypeandcardFundingType(for example,"VISA DEBIT"), and American ExpresscardSchemeis mapped to"AMERICAN_EXPRESS"for sales and"AMEX"for refunds. All other properties onResponse.SaleandResponse.Refundare populated from the API response. - Idempotency with automatic foreground reconciliation: If you invoke
reconcileSaleorreconcileRefundwhile automatic foreground reconciliation is concurrently polling for the same request, both your manual call andDojoTapToPayOnPocket.responsesmay emit the resolved response. Deduplicate transaction updates in your POS usingterminalSessionId(orpaymentIntentId).
Customising network timeouts and retries (ApiCallConfig)
Unlike automatic foreground reconciliation, which polls repeatedly across a time window and defaults to maxAttempts = 3 per HTTP call, reconcileSale and reconcileRefund default to a single attempt (ApiCallConfig(maxAttempts = 1)) so your application has explicit control over retry behaviour.
You can pass a custom ApiCallConfig to configure connection/read timeouts and automatic transport-level retries for transient network or 5xx errors:
val result = DojoTapToPayOnPocket.reconcileSale(
metadata = saleMetadata,
apiCallConfig = ApiCallConfig(
connectTimeoutMs = 10_000,
readTimeoutMs = 10_000,
maxAttempts = 3,
firstRetryDelayMs = 500,
secondRetryDelayMs = 1_000,
),
)
| Property | Default in reconcileSale / reconcileRefund | Description | Type |
|---|---|---|---|
connectTimeoutMs | 10_000 | HTTP connection timeout in milliseconds (must be > 0). | Int |
readTimeoutMs | 10_000 | HTTP read timeout in milliseconds (must be > 0). | Int |
maxAttempts | 1 | Total number of attempts per API request (must be > 0). | Int |
firstRetryDelayMs | 500 | Delay in milliseconds before the second attempt when maxAttempts >= 2 (must be >= 0). | Long |
secondRetryDelayMs | 1_000 | Delay in milliseconds before the third and subsequent attempts when maxAttempts >= 3 (must be >= 0). | Long |
Error handling
When reconcileSale or reconcileRefund cannot complete the API lookup, it returns DojoResult.Failure(error), where error is typed as SaleReconciliationError or RefundReconciliationError. Both sealed interfaces share the same four subtypes, enabling exhaustive when handling:
when (val result = DojoTapToPayOnPocket.reconcileSale(saleMetadata)) {
is DojoResult.Success -> { /* Handle Resolved or Unresolved */ }
is DojoResult.Failure -> {
when (val error = result.error) {
is SdkNotInitialised -> {
// DojoTapToPayOnPocket.initSdk() has not been called
}
is ApiError -> {
val statusCode: Int = error.statusCode
val responseBody: String = error.body
// Non-2xx HTTP status from Dojo API (e.g. 401, 404, 500)
}
is NetworkError -> {
val cause: Throwable = error.cause
// Connectivity failure or socket timeout (e.g. device offline); retry when back online
}
is UnexpectedError -> {
val cause: Throwable = error.cause
// Unexpected runtime or response-parsing error
}
}
}
}
| Error Type | Properties | Cause & Recommended POS Action |
|---|---|---|
SdkNotInitialised | None (data object) | DojoTapToPayOnPocket.initSdk(...) was not called (or failed) prior to invoking reconciliation. Ensure initSdk completes in Application.onCreate() before reconciling. |
ApiError | statusCode: Int, body: String | The Dojo API responded with a non-2xx HTTP status code. A 404 indicates the terminalSessionId or paymentIntentId was not found; 401 indicates an invalid API key; 5xx indicates a transient server error (retry with backoff). |
NetworkError | cause: Throwable | A network transport error (IOException, DNS failure, or socket timeout) prevented reaching the Dojo API. Keep the persisted metadata and retry once network connectivity is restored. |
UnexpectedError | cause: Throwable | An unexpected runtime or payload-deserialization error occurred. Log error.cause for diagnostics. |
If the calling coroutine is cancelled while reconcileSale or reconcileRefund is in flight, CancellationException is rethrown normally to preserve Kotlin structured concurrency rather than returned as DojoResult.Failure.
Split bills
When a sale is in progress in TaP, the operator or customer can choose to split the total bill across two or more constituent payments (and optionally add gratuity to individual shares). Once all constituent payments are completed in TaP, the SDK emits a single Response.SplitSale on DojoTapToPayOnPocket.responses (instead of Response.Sale) containing both the aggregated totals and a list of individual SplitTransaction records.
- Properties
- Bundle
Handle Response.SplitSale in your responses collector to inspect the overall bill summary and iterate over response.splitTransactions:
DojoTapToPayOnPocket.responses.collect { response ->
when (response) {
is Response.SplitSale -> {
val paymentsMade: Int? = response.paymentsMade
val totalBaseAmount: Int? = response.totalBaseAmount
val totalPaidAmount: Int? = response.totalPaidAmount
val totalGratuityAmount: Int? = response.totalGratuityAmount
val splitTransactions = response.splitTransactions
splitTransactions.forEach { tx ->
val status = tx.status
val baseAmount = tx.baseAmount
val gratuityAmount = tx.gratuityAmount
val transactionResult = tx.transactionResult
val transactionId = tx.transactionId
val authCode = tx.authCode
val paymentMethod = tx.paymentMethod
val cvm = tx.cardholderVerificationMethod
val cardScheme = tx.cardScheme
val cardApplicationLabel = tx.cardApplicationLabel
val cardApplicationId = tx.cardApplicationId
val cardPan = tx.cardPan
val dateTime = tx.dateTime
}
pendingTransactionStore.clearPendingSale()
}
else -> Unit
}
}
Response.SplitSale summary properties
| Property | Value | Type |
|---|---|---|
paymentsMade | Total number of constituent payments completed across the split bill. | Int? |
totalBaseAmount | Total base amount of the entire bill in pennies. | Int? |
totalPaidAmount | Total base amount paid in pennies across all constituent splits. | Int? |
totalGratuityAmount | Total gratuity amount paid in pennies across all constituent splits. | Int? |
splitTransactions | List of constituent payment records making up the split bill. | List<SplitTransaction> |
SplitTransaction properties
| Property | Value | Type |
|---|---|---|
status | Status of the constituent transaction ("OK"). | String? |
baseAmount | Base transaction amount for this split in pennies. | Int? |
gratuityAmount | Tip / gratuity amount for this split in pennies. | Int? |
transactionResult | AUTHORISED / DECLINED / CANCELLED / FAILED / UNKNOWN | TransactionResult? |
authCode | Card issuer authorization code. | String? |
paymentMethod | CONTACTLESS / CHIP / SWIPE / MANUAL_ENTRY / KEYED / UNKNOWN | PaymentMethod? |
cardholderVerificationMethod | PIN / SIGNATURE / DEVICE / NONE / UNKNOWN | CardholderVerificationMethod? |
cardScheme | Card brand string (for example, "VISA", "MASTERCARD", "MAESTRO", "AMERICAN_EXPRESS", "DISCOVER", "DINERS", "JCB", "UNION_PAY", "ALIPAY", "BANCOMAT", "CONECS", "UNKNOWN"). | String? |
cardApplicationLabel | EMV card application label. | String? |
cardApplicationId | EMV card application ID. | String? |
cardPan | Masked card Primary Account Number (for example, "************0226"). | String? |
dateTime | ISO 8601 UTC timestamp string of the constituent transaction. | String? |
transactionId | Unique TaP transaction identifier for this constituent payment. | String? |
In response.bundle, the top-level bundle holds the aggregated totals and a "com.dojo.extra.PAYMENT_KEYS" ArrayList<String> (such as ["KEY_0", "KEY_1", ...]). Each key maps to a nested Bundle on response.bundle containing that constituent payment's fields:
DojoTapToPayOnPocket.responses.collect { response ->
when (response) {
is Response.SplitSale -> {
val paymentsMade = response.bundle.getInt("com.dojo.extra.PAYMENTS_MADE")
val totalBaseAmount = response.bundle.getInt("com.dojo.extra.TOTAL_BASE_AMOUNT")
val totalPaidAmount = response.bundle.getInt("com.dojo.extra.TOTAL_PAID_AMOUNT")
val totalGratuityAmount = response.bundle.getInt("com.dojo.extra.TOTAL_GRATUITY_AMOUNT")
val splitTransactionKeys = response.bundle.getStringArrayList("com.dojo.extra.PAYMENT_KEYS")
splitTransactionKeys?.forEach { key ->
val txBundle = response.bundle.getBundle(key) ?: return@forEach
val status = txBundle.getString("com.dojo.extra.TX_STATUS")
val baseAmount = txBundle.getInt("com.dojo.extra.BASE_AMOUNT")
val gratuityAmount = txBundle.getInt("com.dojo.extra.GRATUITY_AMOUNT")
val transactionResult = txBundle.getString("com.dojo.extra.TRANSACTION_RESULT")
val transactionId = txBundle.getString("com.dojo.extra.TRANSACTION_ID")
val authCode = txBundle.getString("com.dojo.extra.AUTH_CODE")
val paymentMethod = txBundle.getString("com.dojo.extra.PAYMENT_METHOD")
val cvm = txBundle.getString("com.dojo.extra.CARDHOLDER_VERIFICATION_METHOD")
val cardScheme = txBundle.getString("com.dojo.extra.CARD_SCHEME")
val cardApplicationLabel = txBundle.getString("com.dojo.extra.CARD_APPLICATION_LABEL")
val cardApplicationId = txBundle.getString("com.dojo.extra.CARD_APPLICATION_ID")
val cardPan = txBundle.getString("com.dojo.extra.CARD_PAN")
val dateTime = txBundle.getString("com.dojo.extra.DATE_TIME")
}
}
else -> Unit
}
}
Top-level split bill bundle keys
| Key (literal string) | Value | Type |
|---|---|---|
com.dojo.extra.SPLIT_BILL | true | Boolean |
com.dojo.extra.PAYMENTS_MADE | Number of constituent payments made. | Int |
com.dojo.extra.TOTAL_BASE_AMOUNT | Total base amount to be paid in pennies. | Int |
com.dojo.extra.TOTAL_PAID_AMOUNT | Total base amount paid in pennies. | Int |
com.dojo.extra.TOTAL_GRATUITY_AMOUNT | Total gratuity amount paid in pennies. | Int |
com.dojo.extra.PAYMENT_KEYS | List of nested bundle keys (for example, ["KEY_0", "KEY_1"]). | ArrayList<String> |
Nested per-split bundle keys (response.bundle.getBundle(key))
| Key (literal string) | Value | Type |
|---|---|---|
com.dojo.extra.TX_STATUS | "OK" | String |
com.dojo.extra.BASE_AMOUNT | Base transaction amount in pennies. | Int |
com.dojo.extra.GRATUITY_AMOUNT | Gratuity transaction amount in pennies. | Int |
com.dojo.extra.TRANSACTION_RESULT | "AUTHORISED" / "DECLINED" / "CANCELLED" / "FAILED" / "UNKNOWN" | String |
com.dojo.extra.AUTH_CODE | Card issuer authorization code. | String |
com.dojo.extra.PAYMENT_METHOD | "CONTACTLESS" / "CHIP" / "ICC_CHIP" / "SWIPE" / "MANUAL_ENTRY" / "KEYED" / "UNKNOWN" | String |
com.dojo.extra.CARDHOLDER_VERIFICATION_METHOD | "PIN" / "SIGNATURE" / "DEVICE" / "NONE" / "UNKNOWN" | String |
com.dojo.extra.CARD_SCHEME | "VISA" / "MASTERCARD" / "MAESTRO" / "AMERICAN_EXPRESS" / "DISCOVER" / "DINERS" / "JCB" / "UNION_PAY" / "ALIPAY" / "BANCOMAT" / "CONECS" / "UNKNOWN" | String |
com.dojo.extra.CARD_APPLICATION_LABEL | EMV application label. | String |
com.dojo.extra.CARD_APPLICATION_ID | EMV application ID. | String |
com.dojo.extra.CARD_PAN | Masked card Primary Account Number. | String |
com.dojo.extra.DATE_TIME | ISO 8601 UTC timestamp string of the transaction. | String |
com.dojo.extra.TRANSACTION_ID | Unique TaP transaction identifier. | String |
Last transaction details
For standard sales and refunds, we strongly recommend recovering outcomes via reconcileSale and reconcileRefund, which query the authoritative status of a specific PaymentIntent and TerminalSession on the Dojo API without launching the TaP UI.
lastTx() is provided for parity with Intent-based integrations and for recovering on-device Response.SplitSale details when the last transaction on the device was a split bill.
DojoTapToPayOnPocket.lastTx() dispatches com.dojo.action.LAST_TX to the on-device TaP application to request the cached details of the most recent local POS transaction executed on the device, regardless of whether it was authorised, declined, or failed. It cannot query a specific historical transaction by ID.
Requesting the last transaction
Method signature
fun lastTx(): DojoResult<Unit, LastTxError>
Call lastTx() while your POS app is in the foreground. DojoResult.Success(Unit) confirms that the lookup intent was dispatched to TaP, and the result will be emitted as Response.LastTx on DojoTapToPayOnPocket.responses:
import tech.dojo.pos.DojoResult
import tech.dojo.pos.LastTxError
import tech.dojo.pos.pocket.DojoTapToPayOnPocket
fun queryLastOnDeviceTransaction() {
when (val result: DojoResult<Unit, LastTxError> = DojoTapToPayOnPocket.lastTx()) {
is DojoResult.Success -> {
// Request dispatched to TaP; await Response.LastTx on DojoTapToPayOnPocket.responses
}
is DojoResult.Failure -> {
val error: LastTxError = result.error
// Handle SdkNotInitialised, AppInBackground, DpaNotInstalled,
// DpaVersionUnsupported, or DpaSecurityFailure
}
}
}
LastTxError shares the same five pre-dispatch error subtypes as InitDojoError: SdkNotInitialised, AppInBackground, DpaNotInstalled, DpaVersionUnsupported, and DpaSecurityFailure.
Expected POS action
When TaP responds, the SDK emits Response.LastTx on DojoTapToPayOnPocket.responses. Response.LastTx is a sealed interface with two subtypes:
Response.LastTx.Sale: Returned when the last transaction was a single transaction (or when no previous transaction was found on the device). Exposesresponse.txStatus("OK"when a completed transaction was found,"NO_TX_FOUND"if no prior local POS transaction exists on the device, ornullif the last transaction was incomplete) andresponse.sale: Response.Sale.Response.LastTx.SplitSale: Returned when the last transaction on the device was a split bill (com.dojo.extra.SPLIT_BILL == true). Exposesresponse.splitSale: Response.SplitSale.
- Properties
- Bundle
import tech.dojo.pos.Response
import tech.dojo.pos.pocket.DojoTapToPayOnPocket
DojoTapToPayOnPocket.responses.collect { response ->
when (response) {
is Response.LastTx.Sale -> {
when (val txStatus = response.txStatus) {
"OK" -> {
// Inspect the underlying single-transaction details via response.sale
val sale: Response.Sale = response.sale
val transactionResult = sale.transactionResult
val baseAmount = sale.baseAmount
val gratuityAmount = sale.gratuityAmount
val transactionId = sale.transactionId
val authCode = sale.authCode
}
"NO_TX_FOUND" -> {
// No prior local POS transaction is stored on this Pocket device
}
null -> {
// The last transaction did not reach a terminal outcome on-device;
// use reconcileSale() or reconcileRefund() with your persisted metadata
}
}
}
is Response.LastTx.SplitSale -> {
// Inspect the underlying split bill details via response.splitSale
val splitSale: Response.SplitSale = response.splitSale
val paymentsMade = splitSale.paymentsMade
val totalPaidAmount = splitSale.totalPaidAmount
val splitTransactions = splitSale.splitTransactions
}
else -> Unit
}
}
| Subtype | Property | Value | Type |
|---|---|---|---|
Response.LastTx.Sale | txStatus | "OK" when a completed transaction was found, "NO_TX_FOUND" when no prior transaction exists on the device, or null if the transaction was incomplete. | String? |
Response.LastTx.Sale | sale | Underlying Response.Sale instance containing all transaction and card properties. | Response.Sale |
Response.LastTx.SplitSale | splitSale | Underlying Response.SplitSale instance containing split summary totals and splitTransactions. | Response.SplitSale |
In response.bundle, "com.dojo.extra.SPLIT_BILL" indicates whether the last transaction was split between two or more payments:
DojoTapToPayOnPocket.responses.collect { response ->
when (response) {
is Response.LastTx -> {
val isSplitBill = response.bundle.getBoolean("com.dojo.extra.SPLIT_BILL", false)
if (isSplitBill) {
// Handle just like a SplitSale bundle (see Split bills section)
val paymentsMade = response.bundle.getInt("com.dojo.extra.PAYMENTS_MADE")
val totalPaidAmount = response.bundle.getInt("com.dojo.extra.TOTAL_PAID_AMOUNT")
} else {
// Check TX_STATUS ("OK" or "NO_TX_FOUND") and read single transaction extras
val txStatus = response.bundle.getString("com.dojo.extra.TX_STATUS")
val transactionResult = response.bundle.getString("com.dojo.extra.TRANSACTION_RESULT")
val transactionId = response.bundle.getString("com.dojo.extra.TRANSACTION_ID")
}
}
else -> Unit
}
}