Key Takeaways:
- On an unattended EV charging terminal, a session can end in three ways: a stop in the app, an unplugged connector, or a timeout. We built a payment path for each one.
- A card check at stop keeps strangers from ending someone else's session. In our app, the check compares the masked card numbers from the start and the stop.
- The card hold placed at the start is a fixed amount, and a long session can cost more. We top the hold up before the price reaches it, so the full amount can still be collected, and we cancel the hold if a session times out with no energy used.
- On an unattended terminal, logs are the only way to establish what happened. We log a missing payment response separately from a decline, and we log every step with terminal, session and payment references.
- We used Worldline's WPI, and the patterns we describe apply to terminals with pre-authorization and capture. Only the API calls differ by vendor and version.
Self-service EV chargers have no staff on site, so every charging session must end with a correct payment. Usually, a driver taps a card, starts charging and later stops the session in the terminal app. Some drivers unplug without touching the app. And some sessions never get a stop signal at all: the driver doesn't return to the app and the connector status never changes. Still, the app has to take the right amount, from the right card, exactly once.
This article describes how Stormotion handled that in an Android app for the payment terminals of a European EV charging operator. It covers when to take the payment, who may stop a session, how to keep a card hold large enough, how to show payment screens in the driver's language, and what to log.
Our project: the Android app we built for EV charging terminals
Our team built the Android application that runs on the payment terminal of a self-service charging station. The terminal's payment app, supplied by the terminal vendor, performs the card operations. The operator's backend owns the charging sessions. Our app sits between them: it starts and stops sessions through the backend and asks the payment application to authorize, update and complete payments.
The code in this article is ours, and it calls Worldline's WPI (Worldline Payment Interface), an Android intent-based interface. The version we describe is WPI 2.0, the current version when we built the app. Worldline has since released newer revisions (2.1, 2.2, 2.3).
Payment modes: three ways a charging session ends
In our app, a session can end in three ways, so we built a payment path for each one. When a session starts, the terminal places a hold on the driver's card (a pre-authorization) for a fixed amount per connector. Money moves only when our app completes the payment for the energy that was actually used.
1. The driver stops the session in the app
When the driver stops the session in the app, we complete the payment right away for the energy used.
private fun completePayment() {
val paymentCompletionRequest = PaymentCompletionRequest(
currency = sessionSharedViewModel.uiState.value.preAuth!!.currency!!,
paymentSolutionReference = sessionSharedViewModel.uiState.value.preAuth!!.reference!!,
requestedAmount = sessionSharedViewModel.uiState.value.stopSessionStatus!!.price,
sessionId = sessionSharedViewModel.uiState.value.sessionId ?: "Unknown"
)
Log.v(TAG, "PaymentCompletionRequest: $paymentCompletionRequest")
completePayment.launch(paymentCompletionRequest)
} The payment completion request in our code takes its data from two earlier steps. The currency and the payment reference come from the pre-authorization made at the start. The amount comes from the stop-session response, so the driver pays the final price of the session, not the hold.
The non-null assertions (!!) encode a rule: this screen is reachable only after a successful pre-authorization, and a missing value fails immediately instead of sending a malformed request. On an unattended terminal a crash is a problem of its own, which is why logging matters. We show how to log such failures later in this article. The "Unknown" fallback for sessionId keeps the request buildable and visible in the logs even when the session identifier is missing.
2. The driver unplugs without using the app
When a driver disconnects the connector and leaves, nobody presses a button, so we detect it ourselves. Our app keeps checking the status of every connector and starts the payment when a connector moves into the "Available", "Unavailable" or "Stopped" state after a charging session:
// ConnectorsSharedViewModel.kt
private fun findUnpaidSessions(): Boolean {
var findUnpaidSessions = false
_uiState.value.connectors.forEachIndexed { index, connector ->
if (index < copyUiState.connectors.size) {
val correspondingCopiedItem = copyUiState.connectors[index]
// Detect status change indicating session ended
if ((connector.status == ConnectorStatus.Available && correspondingCopiedItem.status != ConnectorStatus.Available) ||
(connector.status == ConnectorStatus.Unavailable && correspondingCopiedItem.status != ConnectorStatus.Unavailable) ||
(connector.status == ConnectorStatus.Stopped && correspondingCopiedItem.status != ConnectorStatus.Stopped)) {
Log.d(TAG, "Connector status mismatch. Checking session for unfinished payment.")
val uniqueStationId = copyUiState.connectors[index].uniqueStationId
val stationIdToSessionMap = sessionSharedViewModel.uiState.value.stationIdToSessionMap
val session = stationIdToSessionMap[uniqueStationId]
if (!sessionSharedViewModel.isUserPaid(uniqueStationId)) {
val stationId = session?.stationId ?: connector.stationId
val transactionId = session?.transactionId
val sessionId = session?.sessionId
if (stationId != null && transactionId != null && sessionId != null) {
Log.d(TAG, "Stopping charging and initializing payment")
sessionSharedViewModel.markUserAsPaid(uniqueStationId)
stopCharge(
stationId = stationId,
transactionId = transactionId,
sessionId = sessionId,
connector = connector
)
findUnpaidSessions = true
}
}
}
}
}
copyUiState = _uiState.value
return findUnpaidSessions
} The polling interval is configured in MainActivity, and the hold top-up section shows that connector polls run about every 10 seconds. On each poll the function compares the current state of every connector with the snapshot from the previous poll (copyUiState).
Only a transition counts: a connector that is already "Available" doesn't trigger anything. When a transition is found, the function looks up the session for that station and checks whether payment has been processed. If not, it marks the session as paid, stops the charge and starts the payment sequence.
Two details of our implementation are worth knowing before you reuse this pattern:
- The "paid" flag is set before the payment result is known. markUserAsPaid runs before stopCharge, which stops the next poll from starting a second payment for the same session. The flip side is that this path does not retry a payment that fails afterwards, so the failure has to be visible in telemetry (see the logging section).
- Connectors are compared by list position. Our code assumes that the connector list keeps the same order between polls.
3. The session stays open for 48 hours
To keep card holds from staying open indefinitely and to protect both drivers and the operator, we built a 48-hour timeout that closes open sessions and settles the payment. It covers sessions that nobody ends. The driver doesn't return to the app and the connector status never triggers the unplug path. Here is how it works:
// ConnectorsSharedViewModel.kt
private fun closeOpenReservations(chargingStations: Result.Success<List<EVChargingStation>>) {
val stationIdToSessionMap = sessionSharedViewModel.uiState.value.stationIdToSessionMap
val connectors = _uiState.value.connectors
viewModelScope.launch {
connectors.forEachIndexed { index, connector ->
val session = stationIdToSessionMap[connector.uniqueStationId] ?: return@forEachIndexed
session.sessionStartTime?.let { sessionStartTime ->
if (hasSessionExceededLimit(sessionStartTime)) {
processSession(session, connector)
}
}
}
}
}
private fun hasSessionExceededLimit(sessionStartTime: Long): Boolean {
val hoursPassed = (System.currentTimeMillis() - sessionStartTime) / (1000 * 60 * 60)
return hoursPassed >= 48
}
private suspend fun processSession(session: Session, connector: ConnectorWithReference) {
val sessionId = session.sessionId ?: return
when (val sessionStatus = chargingRepository.getSessionStatus(sessionId)) {
is Result.Success -> handleSessionSuccess(session, connector, sessionStatus.data)
is Result.Error -> handleSessionError()
Result.Loading -> handleSessionLoading()
}
}
private fun handleSessionSuccess(session: Session, connector: ConnectorWithReference, sessionStatusData: SessionStatus) {
if (sessionStatusData.price == 0.0) {
// No energy consumed - cancel pre-authorization
initiatePreAuthCancellation(session, connector)
} else if (session.stopSessionStatus == null) {
// Energy consumed - charge the user
stopChargingSession(session, connector)
}
} This check runs inside the regular connector polling loop. When a session passes 48 hours, our app:
- Reads the session status from the backend.
- Cancels the pre-authorization if no energy was consumed (the price is 0).
- Processes the payment for the actual amount if energy was consumed and the session has not been stopped yet.
The 48 hours is a constant in our code, so treat it as a business rule rather than a rule of the card networks. A hold cannot stay open forever, though: how long an authorization remains valid depends on the card scheme. The timeout protects drivers from holds that never release, and it protects the operator from sessions that are never paid.
Payment card verification at session stop
On a public charging terminal, anyone standing at the screen can press "End session". Without verification, a stranger could stop another driver's session before they return, which disrupts charging and creates disputes. We therefore ask the driver to tap the card again at stop and compare it with the card used at the start.
This is an identity check, not a second charge. In our WPI implementation the check uses WPI_SVC_PAYMENT_INSTRUMENT_RECOGNITION. The driver taps the card, and our app compares the returned masked card number with the one stored when the session started. The actual debit still happens later, through payment completion.
Our developer Artem Manakov came up with this comparison. The interface had no dedicated command for "are these two taps the same card", so he used what the interface already returns: the masked number saved at pre-authorization and the one returned at stop.
Reading the masked card number
For PCI reasons, WPI always returns the card number masked, with only the last four digits visible, so we never store or compare full card numbers. At pre-authorization, our app takes the masked number from the receipt text and saves it for the check at stop. The receipt format varies, so we accept five patterns, such as 1234, XXXX XXXX 1234 or a plain digit group:
private fun extractPan(input: String): String? {
// Regex to match a variety of card number formats with flexible lengths and optional spaces
val firstRegex = "\\*{4}( \\*{4}){0,2} \\d{4}"
val secondRegex = "X{4}( X{4}){0,2} \\d{4}"
val thirdRegex = "\\*{8,15}\\d{4}"
val fourthRegex = "X{8,15}\\d{4}"
val fifthRegex = "\\d{4}( \\d{4}){2,3}"
val regex = Regex("($firstRegex)|($secondRegex)|($thirdRegex)|($fourthRegex)|($fifthRegex)")
return regex.find(input)?.value
} The five expressions are joined into one alternation, and the function returns the first match found in the text, or null if the receipt contains none.
Comparing at stop
At stop, our app compares the masked card number from the recognition response with the stored one as a whole string. In practice that means matching the visible last four digits within the same mask format:
private val recognizePaymentInstrument =
registerForActivityResult(GetPaymentInstrumentRecognition()) { response: PaymentInstrumentRecognitionResponse? ->
if (response?.result == TransactionResponseResult.WPI_RESULT_SUCCESS.name) {
val pan = response.pan
if (pan == sessionSharedViewModel?.uiState?.value?.preAuth?.pan) {
val navController = findNavController()
navController.navigate(
ConfirmStopChargeFragmentDirections
.actionConfirmStopChargeFragmentToStopChargeFragment()
)
} else {
showErrorReAuthScreen()
}
}
} The call goes through Android's Activity Result API: registerForActivityResult registers the callback, and the payment application's answer arrives in it. On a match, our app opens the stop screen. On a mismatch or a failed recognition, our app shows a re-authentication error screen and doesn't call the backend stop API, so the session keeps running until the correct card is presented.
Keeping the card hold ahead of the session
Our app tops up the card hold before the price reaches it, because a fixed hold is too small for a long or high-power session. In user-facing product we call the held amount a "reservation amount". It's the card pre-authorization, and in WPI the top-up is WPI_SVC_UPDATE_PRE_AUTHORIZATION.
We place an initial hold of a fixed amount per connector (€50 in our configuration). If the app tries to capture more than the authorized amount, the payment may fail and the operator cannot collect revenue.
When the app triggers an update
On each connector poll (about every 10 seconds), our app fetches the live price of active sessions and compares it with the current hold:
private fun handleSuccessfulSession(
session: Session,
connector: ConnectorWithReference,
price: Double?
) {
if (session.preAuth?.currentAmount == null) {
session.preAuth?.currentAmount = session.preAuth?.amount
}
val preAuthCurrent = session.preAuth?.currentAmount ?: return
if (price == null || price < preAuthCurrent - 20) return
val uiState = sessionSharedViewModel.uiState.value
if (uiState.sessionUpdatingId != null || uiState.updatePreAuthRequest != null) return
session.preAuth.currentAmount = preAuthCurrent + connector.preAuth.amount
val reference = session.preAuth.reference ?: return
val updateRequestExtra = WpiUpdatePreAuthorizationRequestExtra(
currency = connector.preAuth.currency,
requestedAmount = connector.preAuth.amount,
paymentSolutionReference = reference
)
sessionSharedViewModel.uiState.value.updatePreAuthRequest =
updateRequestExtra
sessionSharedViewModel.uiState.value.sessionUpdatingId =
connector.uniqueStationId
} The rules in our code:
- We start a top-up when price >= currentAmount - 20. We use a €20 buffer so the top-up starts before the hold is used up. With a €50 hold, the first update fires when the price reaches €30.
- We add one full preAuth.amount increment. The hold then becomes €100, the next update fires at €80, and so on.
- We skip the top-up if an update is already in progress (sessionUpdatingId or updatePreAuthRequest is set). This keeps repeated polls from stacking several update prompts on the same terminal.
The amounts (€50, €20) are configuration values in our project, not general recommendations.
One more detail matters if you reuse this code: currentAmount is increased when the request is created, not when the terminal confirms it. If the card refuses the top-up, the app's idea of the hold and the real hold would differ, and the code shown does not cover that case.
The screen and the terminal call
In our app, a pending update is picked up by the welcome screen, which polls every 30 seconds. If an update is pending and the session is not being stopped, it opens the update screen:
// WelcomeFragment.updatePreAuth()
if (sessionSharedViewModel.uiState.value.updatePreAuthRequest != null) {
val shouldUpdatePreAuth = session != null && session.stopSessionStatus == null
if (shouldUpdatePreAuth) {
findNavController().navigate(
WelcomeFragmentDirections.actionWelcomeFragmentToUpdatePreAuth()
)
}
} Our update screen informs the driver, waits 7 seconds so the terminal prompt doesn't come as a surprise, and then launches the payment application:
viewLifecycleOwner.lifecycleScope.launch {
delay(7_000)
sessionSharedViewModel.uiState.value.sessionUpdatingId = null
val paymentRequest = sessionSharedViewModel.uiState.value.updatePreAuthRequest
updatePreAuthLauncher.launch(paymentRequest)
} The intent for the update looks like this:
// GetPaymentUpdate.kt
Intent(WPI_ACTION_PROCESS_TRANSACTION).apply {
putExtra(WPI_SERVICE_TYPE, "WPI_SVC_UPDATE_PRE_AUTHORIZATION")
putExtra(WPI_REQUEST_EXTRA, Json.encodeToString(
input.copy(requestedAmount = input.requestedAmount * 100)
))
} The multiplication by 100 is a WPI rule: amounts are sent in minor units, so €50.00 becomes 5000. According to the specification, the amount in an update is the increment, not the new total. Each update also returns a new payment reference, and the final purchase has to use the reference of the latest update.
Showing payment screens in the driver's language
We also made each location open in its own language. The terminals are deployed in several European countries, and the card hold only works if the driver understands what is asked of them. The tariff text, the "tap your card" prompt, the stop confirmation and the payment error messages are all steps where a driver who cannot read the screen hesitates, taps the wrong thing or walks away.
On a busy site, that means abandoned sessions, support calls and mistakes in the stop flow. The payment application has its own customerLanguage on WPI responses, but the app's interface language is separate and is controlled through the Android locale and translated resources.
Each charging location returns a default_language value from the API. When connectors load, our app stores it:
// ChargingAPI.kt
data class LocationApiModel(
val evses: List<EVChargingStationApiModel>,
@SerialName("default_language")
val defaultLanguage: String = DEFAULT_COUNTRY_CODE
)
// DefaultChargingRepository — on locations fetch
sessionSharedViewModel?.updateDefaultLanguage(locationsResult.data.defaultLanguage) Despite the field name, the values are country keys such as gb. Our app maps them to language codes for the language picker, and falls back to gb when the API sends nothing:
const val DEFAULT_COUNTRY_CODE: String = "gb"
val COUNTRY_CODE_TO_LANGUAGE_CODE: Map<String, String> =
mapOf(
Pair("gb", "en"),
Pair("fr", "fr"),
Pair("de", "de"),
Pair("nl", "nl"),
Pair("ro", "ro"),
Pair("pl", "pl"),
Pair("es", "es"),
Pair("it", "it"),
Pair("ru", "ru")
) Keeping the default on the backend means a new site can open in the right language without a new app release, while the driver can still switch language on the terminal.
Building an app for EV charging payment terminals?
Talk to Stormotion
Logging as part of the payment design
Every flow described above, from the three ways a session ends to the hold top-up and the card check, runs with nobody watching the terminal. When one of them goes wrong, logs are the only way to reconstruct the session, often days later.
We treat logs as operational infrastructure and keep them in two layers:
- Local log (Logcat) for fast debugging during development and on-device investigation.
- Cloud telemetry (Application Insights) for production monitoring across remote terminals: payment success and failure, API errors, heartbeats and unpaid-session recovery. These are custom events in Application Insights.
Payment outcomes must be traceable
Payment completion is the only moment money moves, so we log every completion with the terminal ID, the session ID, Worldline's error condition and the transaction reference. If it fails, support needs these, not a screenshot from the driver. On success, our app sends a structured event that includes the transaction reference number read from the receipt:
fun logPaymentSuccess(sessionId: String, response: PaymentCompletionTransactionResponse) {
Log.d("TelemetryService", "logPaymentSuccess called: response=$response")
terminalId?.let {
val formattedReceiptText = response.receipt?.formatted?.client.toString()
val trxRefNoRegex = Regex("Trx\\. Ref-No:\\s*\\n*\\s*(\\d+)", RegexOption.MULTILINE)
val match = trxRefNoRegex.find(formattedReceiptText)
val trxRefNo = match?.groupValues?.getOrNull(1) ?: "Unknown"
logEvent(
"Payment Completed Successfully", mapOf(
"terminalId" to it,
"transactionReferenceNumber" to trxRefNo,
"paymentReference" to response.paymentSolutionReference.toString(),
"sessionId" to sessionId,
// ...
)
)
}
} The function reads the client receipt text, extracts the "Trx. Ref-No" with a regular expression, and falls back to "Unknown" so the event is still sent if the receipt format changes. The event is sent only when a terminal ID is known, so make sure it is set before the first payment. Keep sensitive data out of logs: log identifiers and references, not card data.
A missing response is not a decline
We log a missing response separately from a decline, because the two mean different things for support: after a decline the outcome is known, and after silence it is not. According to Artem, a decline from Worldline arrives in the same way as any other result: as a normal WPI response with a failure result, which the app logs together with the information it has, including the specific error. A null intent is different. It is no answer at all, as if the payment application crashed, so the app logs it separately.
override fun parseResult(
resultCode: Int,
intent: Intent?
): PaymentCompletionTransactionResponse? {
return intent?.let {
it.getStringExtra(WPI_RESPONSE_EXTRA)?.let { wpiResponse ->
try {
AppJson.decodeFromString<PaymentCompletionTransactionResponse>(wpiResponse)
} catch (e: Exception) {
TelemetryService.logPaymentFailure(e)
null
}
}
}
} The function has three outcomes:
- A valid response becomes a typed object.
- A response that cannot be parsed is logged as a parse failure and returns null.
- A missing intent or a missing response extra also returns null, which the caller treats as "no answer". In our setup this happened after repeated card-read errors.
The third case is behavior we observed in our integration, not something the WPI specification describes for payment responses. The specification does describe a recovery route: the app stores the WPI session ID before sending the intent, and a later WPI_SVC_LAST_TRANSACTION request returns the last transaction for that session.
Background flows are invisible without telemetry
Our app logs the moment an unpaid session is detected and the moment the stop and payment requests are created, because an automatic payment, for example after the driver unplugged and the connector went to "Stopped", has no user on the screen:
TelemetryService.terminalId?.let { terminalId ->
TelemetryService.logEvent(
"Connector status mismatch - Unpaid Session Found",
mapOf(
"terminalId" to terminalId,
"stationId" to stationId,
"sessionId" to (sessionId ?: ""),
"transactionId" to (transactionId ?: ""),
"uniqueStationId" to uniqueStationId,
"connectorId" to connector.id,
"connectorStatus" to connector.status.name,
"device-type" to "payment-terminal"
)
)
} Pre-authorization, hold updates, background completion and the card check at stop are asynchronous, distributed steps. Without correlated events (terminal ID, session ID and the payment references), you cannot tell a payment provider issue from a network blip or a logic bug, and you cannot show finance or support what happened to a specific charge.
Lessons for EV charging operators adding payment terminals
If you're choosing or integrating a payment terminal for an unattended product, these are the lessons we took from this project, and they carry over:
- Design for the person who is not there. Every session needs a payment path that works without a driver: stop, unplug and timeout. A timeout is also where a hold that was never used gets canceled.
- Treat the card hold as a resource. Track how much is authorized and how much the session costs, and top up with a buffer.
- Verify with what the terminal gives you, and state the limit. A masked number is better than nothing, but a vendor token or a PIN is stronger. Choose based on the risk of a wrong stop at your sites.
- Read the documentation for your version. Each terminal vendor and payment platform handles holds, references and capture differently, and the details decide whether a final payment succeeds.
- Log steps with shared identifiers, and keep decline and silence apart. Without that, support cannot say what happened to a charge.
If you are extending an EV charging app with payment terminals, we can help with the terminal integration, the payment flows and the logging your product needs. Tell us about your project in the form below.


