Skip to main content

Tap to Pay on Pocket

Initiate and accept contactless payments from your POS application via the SDK.

note

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:

  1. Request setup and dispatch (DojoResult): When your POS invokes an operation—such as initDojo(), sale(), refund(), or lastTx()—the SDK validates the parameters, creates any required backend resources (PaymentIntent and TerminalSession) via the Dojo API, and launches the TaP UI on the Pocket device. The function returns a DojoResult<Value, Error> immediately to confirm whether the request was accepted and dispatched to TaP (or failed pre-dispatch validation, API creation, or intent resolution).
  2. 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 typed Response on the process-wide DojoTapToPayOnPocket.responses Flow. If focus returns to your POS without a callback from TaP, the SDK automatically polls the Dojo API to reconstruct the outcome or emits Response.MissingResponse so 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​

StepSDK MethodImmediate Return TypeEmitted on responsesPurpose
1. Configure SDKinitSdk(context, config)DojoResult<Unit, InitSdkError>NoneRegisters your API credentials, environment settings, and lifecycle observers in Application.onCreate().
2. Observe responsesresponsesFlow<Response>All Response subtypesProcess-wide stream delivering all asynchronous outcomes from TaP and automatic foreground reconciliation.
3. Provision & link terminalinitDojo()DojoResult<Unit, InitDojoError>Response.DojoInitProvisions the TaP payment engine (if needed) and caches the device's Terminal ID (TID) in the SDK for API session creation.
4. Take a paymentsale(...)DojoResult<SaleMetadata, SaleError>Response.Sale or Response.SplitSaleCreates a Dojo PaymentIntent and TerminalSession, then launches TaP to accept a contactless payment (or split bill).
5. Issue a refundrefund(...)DojoResult<RefundMetadata, RefundError>Response.RefundCreates an unlinked refund TerminalSession, then launches TaP to process a contactless card refund.
6. Recover an interrupted transactionreconcileSale(...) / 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 transactionlastTx()DojoResult<Unit, LastTxError>Response.LastTxQueries 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 TypePropertiesCause & Recommended POS Action
InvalidSdkContextcontextClassName: StringThe 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.
SdkIntegrationErrormessage: StringThe 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 explicit Intents. Only change this to AppEnvironment.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 to DojoApiEnvironment.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.responses once at the Application / process level (for example, in an application-scoped coroutine or repository initialized right after initSdk succeeds) 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: Every Response subtype exposes strongly typed Kotlin properties (recommended) alongside a raw bundle: Bundle property containing the underlying com.dojo.extra.* extras for seamless migration from raw Intent integrations.
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:

  1. 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.
  2. Terminal ID (TID) resolution and caching: When TaP finishes initializing, it returns the Pocket device's unique terminalId (TID, returned from TaP 26.07.15 onwards). The SDK automatically caches this TID in memory and prefetches the corresponding terminal UUID from the Dojo API so subsequent sale() and refund() calls can create terminal sessions.
warning
Call 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:

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 TypePropertiesCause & Recommended POS Action
SdkNotInitialisedNone (data object)DojoTapToPayOnPocket.initSdk(...) was not called or failed before calling initDojo(). Ensure initSdk runs in Application.onCreate().
AppInBackgroundNone (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.
DpaNotInstalledaction: StringThe 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.
DpaVersionUnsupportedinstalledVersionCode: Long, minimumVersionCode: LongThe installed TaP app version is older than the minimum version required by this SDK (100918). Prompt the operator to update the Dojo Pay App.
DpaSecurityFailureaction: String, cause: SecurityExceptionAndroid 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.

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
}
}
PropertyValueType
isSuccesstrue 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?
terminalIdUnique Terminal ID (TID) of the Pocket device (populated on success from TaP 26.07.15 onwards).String?

Initialization detail status and error codes​

detail (INIT_RESULT_DETAIL)isSuccessMeaning & Recommended POS Action
"OK"trueProvisioning completed just now. No further action required; the terminal is ready for transactions.
"COMPLETED"trueThe terminal was already provisioned prior to this initDojo() call, and its terminalId is now cached by the SDK. No further action required.
"NO_TID"falseTerminal ID was not found after initialization completed. Recommended action: Retry initDojo().
"E1"falseA payment session failed to start during initialization. Recommended action: Retry initDojo().
"T1"falseA timeout caused provisioning to be cancelled. Recommended action: Verify network connectivity and retry initDojo().
"A5"falseAndroid Debug Bridge (ADB) or Developer Options is enabled on the device. Disable USB debugging / Developer Options in Android Settings and retry.
"A6", "B2"falseNetwork connectivity was disrupted during provisioning. Check Wi-Fi/mobile data connectivity and retry.
"A1"–"A4", "A7"–"A12", "B1", "B3", "B4"falsePayment 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>"falseTerminal session linking failed with the Dojo backend. Verify network connectivity and retry.
"R1" / "R2" / "R3"falseRecovery required: "R1" (restart the TaP app), "R2" (restart the Pocket device), or "R3" (re-provision / disaster recovery). Prompt the operator accordingly.
Missing initialization callback

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:

  1. Validates that the SDK and terminal (TID) are initialized, amountInPennies > 0, and currencyCode is a valid ISO 4217 alpha-3 currency code.
  2. Resolves the Pocket device's terminal UUID on the Dojo API.
  3. Creates a Dojo PaymentIntent (with captureMode = "Auto") and prepares a Sale TerminalSession on the Dojo API.
  4. Dispatches com.dojo.action.SALE to TaP on the device and returns DojoResult.Success(SaleMetadata(paymentIntentId, terminalSessionId)) to your caller.
  5. Waits for the customer to present their contactless card or mobile wallet in TaP, then emits Response.Sale (or Response.SplitSale if the operator splits the bill inside TaP) onto DojoTapToPayOnPocket.responses.

Starting a sale​

Method signature​

suspend fun sale(
amountInPennies: Int,
reference: String = UUID.randomUUID().toString(),
currencyCode: String = "GBP",
): DojoResult<SaleMetadata, SaleError>
ParameterDefaultDescription & ConstraintsType
amountInPenniesRequiredSale 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
referenceUUID.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 TypeCategoryPropertiesCause & Recommended POS Action
SdkNotInitialisedSdkStateErrorNone (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.
InvalidAmountTransactionValidationErroramountInPennies: IntamountInPennies was <= 0. Pass a positive integer in minor currency units.
InvalidCurrencyCodeTransactionValidationErrorcurrencyCode: StringcurrencyCode is not a valid 3-letter ISO 4217 currency code.
TerminalNotFoundTerminalResolutionErrortid: StringThe 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.
ApiErrorTransportErrorstatusCode: Int, body: StringThe 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).
NetworkErrorTransportErrorcause: ThrowableA network connectivity error or timeout occurred before the transaction was dispatched to TaP. Safe to retry when back online.
UnexpectedErrorTransportErrorcause: ThrowableAn unexpected runtime failure occurred. Log error.cause for diagnostics.
AppInBackgroundDispatchErrorNone (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.
DpaNotInstalledDispatchErroraction: StringThe TaP app is not installed or cannot handle com.dojo.action.SALE.
DpaVersionUnsupportedDispatchErrorinstalledVersionCode: Long, minimumVersionCode: LongThe installed TaP app is older than the minimum version required by the SDK. Update TaP on the device.
DpaSecurityFailureDispatchErroraction: String, cause: SecurityExceptionAndroid 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).

info
Card declines and cancellations are emitted on responses, not returned as SaleError

Once 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.

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
}
}
PropertyValueType
saleStatusStatus of the sale request ("OK").String?
transactionResultAUTHORISED / DECLINED / CANCELLED / FAILED / UNKNOWNTransactionResult?
baseAmountBase transaction amount in pennies (minor units).Int?
gratuityAmountTip / gratuity amount in pennies (if a tip was added in TaP).Int?
transactionIdUnique TaP terminal transaction identifier.String?
authCodeCard issuer authorization code.String?
paymentMethodCONTACTLESS / CHIP / SWIPE / MANUAL_ENTRY / KEYED / UNKNOWNPaymentMethod?
cardholderVerificationMethodPIN / SIGNATURE / DEVICE / NONE / UNKNOWNCardholderVerificationMethod?
cardSchemeCard brand string (for example, "VISA", "MASTERCARD", "MAESTRO", "AMERICAN_EXPRESS", "DISCOVER", "DINERS", "JCB", "UNION_PAY", "ALIPAY", "BANCOMAT", "CONECS", "UNKNOWN").String?
cardApplicationLabelEMV card application label (for example, "VISA DEBIT").String?
cardApplicationIdEMV card application identifier (for example, "A0000000031010"). Note: null on API-reconciled responses.String?
cardPanMasked card Primary Account Number (for example, "************0226").String?
dateTimeISO 8601 UTC timestamp string of the transaction (for example, "2026-11-10T14:32:10Z").String?
paymentIntentIdDojo API payment intent identifier (paymentIntentId.value).PaymentIntentId?
terminalSessionIdDojo API terminal session identifier (terminalSessionId.value).TerminalSessionId?

Interpreting TransactionResult​

TransactionResultMeaningRecommended POS Action
AUTHORISEDThe 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.
DECLINEDThe 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.
CANCELLEDThe 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.
FAILEDA technical error or session expiration prevented the transaction from completing.Clear persisted SaleMetadata and prompt the operator to retry with a new sale().
UNKNOWNAn 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>
ParameterDefaultDescription & ConstraintsType
amountInPenniesRequiredRefund 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 (either initSdk() was not called or initDojo() has not cached a terminalId in 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.

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
}
}
PropertyValueType
refundStatusStatus of the refund request ("OK").String?
transactionResultAUTHORISED / DECLINED / CANCELLED / FAILED / UNKNOWNTransactionResult?
baseAmountRefund amount in pennies (minor units).Int?
transactionIdUnique TaP terminal transaction identifier.String?
authCodeCard issuer authorization code.String?
paymentMethodCONTACTLESS / CHIP / SWIPE / MANUAL_ENTRY / KEYED / UNKNOWNPaymentMethod?
cardholderVerificationMethodPIN / SIGNATURE / DEVICE / NONE / UNKNOWNCardholderVerificationMethod?
cardSchemeCard brand string (for example, "VISA", "MASTERCARD", "MAESTRO", "AMERICAN_EXPRESS" or "AMEX", "DISCOVER", "DINERS", "JCB", "UNION_PAY", "UNKNOWN").String?
cardApplicationLabelEMV card application label.String?
cardApplicationIdEMV card application ID (null on API-reconciled responses).String?
cardPanMasked card Primary Account Number (for example, "************0226").String?
dateTimeISO 8601 UTC timestamp string of the refund transaction.String?
terminalSessionIdDojo API terminal session identifier (terminalSessionId.value).TerminalSessionId?

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:

  1. Automatic foreground reconciliation: Enabled by default (ForegroundReconciliationConfig.enabled = true). When focus returns to your POS app while a sale or refund is still awaiting a response from TaP, the SDK automatically polls the Dojo API (by default every 1,000 ms for up to 5,000 ms). If the transaction reaches a terminal status during this window, the SDK reconstructs and emits Response.Sale or Response.Refund directly onto DojoTapToPayOnPocket.responses. If the polling window expires while the transaction is still non-terminal (or if automatic reconciliation is disabled), the SDK emits Response.MissingResponse.
  2. Manual reconciliation (reconcileSale and reconcileRefund): 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. Calling reconcileSale or reconcileRefund does not launch the TaP UI, dispatch a new transaction, modify pending-request tracking, or emit onto DojoTapToPayOnPocket.responses. Furthermore, reconcileSale and reconcileRefund only require initSdk() to have succeeded in the current process—they do not require initDojo() to have run first, allowing you to recover persisted transactions immediately on app startup after process death.
note

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: Contains paymentIntentId: PaymentIntentId and terminalSessionId: TerminalSessionId (both @JvmInline value class wrappers around a value: String).
  • RefundMetadata: Contains terminalSessionId: TerminalSessionId.

You can obtain these metadata objects in two ways:

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.

Persist metadata before TaP completes

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.

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
}
}
}

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.

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
}
}
}

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 corresponding Response.Sale or Response.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 as DojoResult.Success rather than DojoResult.Failure because the lookup itself succeeded.

The table below shows how the SDK maps Dojo API TerminalSession statuses to ManualReconciliationResult and TransactionResult:

Backend TerminalSession.statusTerminal?ManualReconciliationResultresponse.transactionResult (com.dojo.extra.TRANSACTION_RESULT)Recommended POS Action
"Authorized"YesResolvedTransactionResult.AUTHORISED ("AUTHORISED")Mark transaction as paid/refunded and clear persisted metadata.
"Captured"YesResolvedTransactionResult.AUTHORISED ("AUTHORISED")Mark transaction as paid/refunded and clear persisted metadata.
"SignatureVerificationAccepted"YesResolvedTransactionResult.AUTHORISED ("AUTHORISED")Mark transaction as paid/refunded and clear persisted metadata.
"Declined"YesResolvedTransactionResult.DECLINED ("DECLINED")Mark transaction as declined; safe to start a new transaction.
"SignatureVerificationRejected"YesResolvedTransactionResult.DECLINED ("DECLINED")Mark transaction as declined; safe to start a new transaction.
"Canceled"YesResolvedTransactionResult.CANCELLED ("CANCELLED")Mark transaction as cancelled; safe to start a new transaction.
"CancelRequested"YesResolvedTransactionResult.CANCELLED ("CANCELLED")Mark transaction as cancelled; safe to start a new transaction.
"Expired"YesResolvedTransactionResult.FAILED ("FAILED")Mark transaction as failed; safe to start a new transaction.
"Created"NoUnresolved("Created")N/ASession 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)NoUnresolved(status)N/ATransaction is still in progress. Wait and call reconcileSale / reconcileRefund again before starting a new payment.
Reconstructed response differences and concurrency
  • Single-transaction reconstruction only (no SplitSale): Reconstructed sale responses never set com.dojo.extra.SPLIT_BILL (Response.SplitSale), as the Dojo REST API endpoints queried during reconciliation represent a single TerminalSession and PaymentIntent.
  • EMV Application ID (cardApplicationId): In responses reconstructed via reconcileSale or reconcileRefund (as well as automatic foreground reconciliation), cardApplicationId (com.dojo.extra.CARD_APPLICATION_ID) is null because the EMV application ID is not returned by the Dojo REST API. cardApplicationLabel is synthesized from the API's cardType and cardFundingType (for example, "VISA DEBIT"), and American Express cardScheme is mapped to "AMERICAN_EXPRESS" for sales and "AMEX" for refunds. All other properties on Response.Sale and Response.Refund are populated from the API response.
  • Idempotency with automatic foreground reconciliation: If you invoke reconcileSale or reconcileRefund while automatic foreground reconciliation is concurrently polling for the same request, both your manual call and DojoTapToPayOnPocket.responses may emit the resolved response. Deduplicate transaction updates in your POS using terminalSessionId (or paymentIntentId).

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,
),
)
PropertyDefault in reconcileSale / reconcileRefundDescriptionType
connectTimeoutMs10_000HTTP connection timeout in milliseconds (must be > 0).Int
readTimeoutMs10_000HTTP read timeout in milliseconds (must be > 0).Int
maxAttempts1Total number of attempts per API request (must be > 0).Int
firstRetryDelayMs500Delay in milliseconds before the second attempt when maxAttempts >= 2 (must be >= 0).Long
secondRetryDelayMs1_000Delay 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 TypePropertiesCause & Recommended POS Action
SdkNotInitialisedNone (data object)DojoTapToPayOnPocket.initSdk(...) was not called (or failed) prior to invoking reconciliation. Ensure initSdk completes in Application.onCreate() before reconciling.
ApiErrorstatusCode: Int, body: StringThe 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).
NetworkErrorcause: ThrowableA 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.
UnexpectedErrorcause: ThrowableAn unexpected runtime or payload-deserialization error occurred. Log error.cause for diagnostics.
Coroutine cancellation

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.

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​

PropertyValueType
paymentsMadeTotal number of constituent payments completed across the split bill.Int?
totalBaseAmountTotal base amount of the entire bill in pennies.Int?
totalPaidAmountTotal base amount paid in pennies across all constituent splits.Int?
totalGratuityAmountTotal gratuity amount paid in pennies across all constituent splits.Int?
splitTransactionsList of constituent payment records making up the split bill.List<SplitTransaction>

SplitTransaction properties​

PropertyValueType
statusStatus of the constituent transaction ("OK").String?
baseAmountBase transaction amount for this split in pennies.Int?
gratuityAmountTip / gratuity amount for this split in pennies.Int?
transactionResultAUTHORISED / DECLINED / CANCELLED / FAILED / UNKNOWNTransactionResult?
authCodeCard issuer authorization code.String?
paymentMethodCONTACTLESS / CHIP / SWIPE / MANUAL_ENTRY / KEYED / UNKNOWNPaymentMethod?
cardholderVerificationMethodPIN / SIGNATURE / DEVICE / NONE / UNKNOWNCardholderVerificationMethod?
cardSchemeCard brand string (for example, "VISA", "MASTERCARD", "MAESTRO", "AMERICAN_EXPRESS", "DISCOVER", "DINERS", "JCB", "UNION_PAY", "ALIPAY", "BANCOMAT", "CONECS", "UNKNOWN").String?
cardApplicationLabelEMV card application label.String?
cardApplicationIdEMV card application ID.String?
cardPanMasked card Primary Account Number (for example, "************0226").String?
dateTimeISO 8601 UTC timestamp string of the constituent transaction.String?
transactionIdUnique TaP transaction identifier for this constituent payment.String?

Last transaction details​

Prefer API reconciliation for sales and refunds

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). Exposes response.txStatus ("OK" when a completed transaction was found, "NO_TX_FOUND" if no prior local POS transaction exists on the device, or null if the last transaction was incomplete) and response.sale: Response.Sale.
  • Response.LastTx.SplitSale: Returned when the last transaction on the device was a split bill (com.dojo.extra.SPLIT_BILL == true). Exposes response.splitSale: Response.SplitSale.
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
}
}
SubtypePropertyValueType
Response.LastTx.SaletxStatus"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.SalesaleUnderlying Response.Sale instance containing all transaction and card properties.Response.Sale
Response.LastTx.SplitSalesplitSaleUnderlying Response.SplitSale instance containing split summary totals and splitTransactions.Response.SplitSale