NFC Tags
AndroidRead and write NFC tags from your Android app, on phones and on Sunmi payment terminals.
Before you start
Read and write NFC tags, such as loyalty cards, access badges, stickers, and smart cards, from your Android app. The Accept SDK opens a session on the tapped tag through the device's own contactless reader, and your app sends commands to it one at a time.
- A supported device.
- The Accept SDK installed and initialized.
Tag sessions don't need an authenticated merchant, the Tapaya Terminal plugin, or location permission. They ship in optional artifacts:
add them only if you need them; card payments work the same with or without them. The artifacts declare the
permissions they use: android.permission.NFC for phones, and com.sunmi.perm.CONTACTLESS_CARD for Sunmi
terminals. Android NFC is declared as optional, so Google Play still offers your app on devices without it. accept-nfc-sunmi also adds a <queries> entry for Sunmi's pay service and embeds Sunmi PayLib.
Supported devices and tags
| Device | Reader | Artifacts |
|---|---|---|
| Android phones and tablets with NFC | Android NFC | com.tapaya:accept-nfc |
| Sunmi P-series terminals | The payment module's contactless reader, through Sunmi's pay service | com.tapaya:accept-nfc and com.tapaya:accept-nfc-sunmi |
Sunmi P-series terminals have no Android NFC; their antenna sits behind the payment module, so they need the
Sunmi artifact as well. On a device with neither reader, isSupported() returns false and openSession() fails
with NOT_SUPPORTED.
| Tag type | Examples |
|---|---|
| NFC Type 2 | NTAG, MIFARE Ultralight, Ultralight EV1, Ultralight C |
| MIFARE Classic | MIFARE Classic Mini, 1K, 4K |
| ISO-DEP smart cards | MIFARE DESFire |
Some phones' NFC controllers can't talk to MIFARE Classic. On those phones, Classic operations fail with
NOT_SUPPORTED.
Check support, not the device model
Call isSupported() to decide whether to show the tag feature, instead of matching device
models. It returns true on a phone whose NFC is switched off; openSession() then fails with
NFC_DISABLED, so you can ask the user to turn NFC on.
How it works
- Your app calls
Accept.nfc.openSession(activity). - The SDK turns on the reader and waits for a tap.
- The customer taps a tag, and
openSession()returns aTagSessioncarrying the tag's UID and family. - Your app reads and writes through the session, one command at a time.
- Your app calls
close(), which frees the reader for payments and other sessions.
Payments always take priority
The device has one contactless reader. Starting a payment with Accept.payments.pay() takes it back: an open
session ends with PAYMENT, and openSession() fails with READER_BUSY until the payment is over. Be ready
for a session to end at any point; see End a session.
Integrate
Install
Add accept-nfc next to the core SDK. Add accept-nfc-sunmi too if your app runs on Sunmi P-series terminals.
Keep all Accept artifacts on the same version.
dependencies {
implementation("com.tapaya:accept:$acceptVersion")
implementation("com.tapaya:accept-nfc:$acceptVersion")
// Sunmi P-series terminals only
implementation("com.tapaya:accept-nfc-sunmi:$acceptVersion")
}The artifacts register themselves at app startup, so there is nothing to set up in code. Accept.nfc is an
extension property; import it before use:
import com.tapaya.accept.nfc.nfcCheck support
Call isSupported() to decide whether to show the tag feature at all:
if (Accept.nfc.isSupported()) {
showScanTagButton()
}isSupported() needs no tap and doesn't touch the reader, so it's safe to call while a payment is running. It
throws NotInitialized if Accept.initialize hasn't been called yet.
Open a session
Pass the activity that is in the foreground. It must be resumed, or openSession() throws
IllegalStateException.
val session = try {
Accept.nfc.openSession(activity)
} catch (e: TagSessionException) {
when (e.reason) {
TagErrorReason.TIMEOUT -> showMessage("No tag detected. Try again.")
TagErrorReason.READER_BUSY -> showMessage("The reader is busy. Try again soon.")
TagErrorReason.NFC_DISABLED -> showMessage("Turn on NFC in your phone's settings.")
else -> showMessage("Can't read tags on this device.")
}
return
}
try {
showTag(session.info.uidHex, session.info.family)
// read and write...
} finally {
session.close()
}openSession() suspends until a tag is tapped or tapWait runs out (30 seconds by default). Show a "Tap your
card" prompt while it waits. It throws IllegalStateException if activity isn't resumed.
On a phone, the activity matters: Android reads tags only for it, and leaving the foreground stops the wait or ends
the session with ACTIVITY_PAUSED. Sunmi terminals read tags whatever is in the foreground, but you still pass an
activity.
To stop waiting, for example when the customer taps Cancel, cancel the coroutine that called openSession().
On phones, Android reads tags only for the app in the foreground. If the activity you passed leaves the
foreground, the session ends with ACTIVITY_PAUSED. On Sunmi terminals, the reader works whatever is in the
foreground.
Read and write a tag
Branch on session.info.family, then use the operations for that tag type:
when (session.info.family) {
TagFamily.NTAG, TagFamily.ULTRALIGHT, TagFamily.ULTRALIGHT_EV1,
TagFamily.ULTRALIGHT_C, TagFamily.TYPE2_OTHER -> readType2Tag(session)
TagFamily.MIFARE_CLASSIC_MINI, TagFamily.MIFARE_CLASSIC_1K,
TagFamily.MIFARE_CLASSIC_4K -> readClassicCard(session)
TagFamily.ISO_DEP -> readSmartCard(session)
TagFamily.UNKNOWN -> showMessage("This tag isn't supported.")
}A command that doesn't fit the tapped tag fails with NOT_SUPPORTED, and the session stays open.
End a session
Call close() as soon as you're done, ideally from a finally block. Until you do, no other session can use the
reader. Closing a session that has already ended does nothing.
A session can also end on its own. session.ended is a StateFlow that stays null while the session is live,
then emits the reason it ended:
session.ended.filterNotNull().first().let { reason ->
when (reason) {
TagSessionEndReason.CARD_REMOVED -> showMessage("Card removed")
TagSessionEndReason.PAYMENT -> showMessage("A payment took over the reader")
TagSessionEndReason.ACTIVITY_PAUSED -> showMessage("Keep the app in the foreground")
else -> Unit
}
}TagSessionEndReason | When it happens |
|---|---|
CLOSED | Your app called close(). |
CARD_REMOVED | The tag left the field and wasn't selected again within the reselect timeout, or a different tag came back. |
IDLE_TIMEOUT | No command arrived within the idle timeout (10 seconds by default). |
PAYMENT | A payment started through Accept.payments.pay(). Payments always take priority. |
ACTIVITY_PAUSED | Phones only: the activity the session was opened with left the foreground. |
READER_LOST | The reader went away. On Sunmi terminals, the connection to the pay service dropped. |
Once a session has ended, every further command fails with SESSION_ENDED. Call openSession() again for a new
tap.
Good to know
- One session at a time. The device has one reader. A second
openSession()while a session is open or waiting fails withREADER_BUSY. - Commands run in order. Session methods can be called from any coroutine; they reach the tag one at a time, in the order you call them.
- Permanent writes aren't guarded. Lock bits, OTP pages, MIFARE Classic sector trailers, and passwords are written exactly as you send them. Double-check these writes; a mistake can lock the tag for good.
Test the integration
On each kind of device you ship to:
- Check that
isSupported()returnstrueon a phone with NFC and on a Sunmi terminal withaccept-nfc-sunmi. - On a phone, switch NFC off and confirm
openSession()fails withNFC_DISABLED. - Tap an NTAG or Ultralight tag and verify the session reports the right UID and
readPages(0)returns 16 bytes. ThenwritePageand read the page back. - On MIFARE Classic, authenticate with a wrong key and confirm
AUTH_FAILED, then with the right one. - Cancel
openSession()during the tap wait and open a new session straight away. - Start a payment during a session: the session should end as
PAYMENTand the payment go through. Remove the tag during another session: it should end asCARD_REMOVED. - On a phone, send your app to the background during a session and confirm it ends as
ACTIVITY_PAUSED.
Handle errors
Tag failures throw TagSessionException, whose reason tells you what to do next. TagSessionException is
not an AcceptException. The only Accept SDK exception tag sessions throw is NotInitialized, when
Accept.initialize hasn't been called yet.
try {
val session = Accept.nfc.openSession(activity)
// ...
} catch (e: TagSessionException) {
// reason-specific handling, see the tables below
}Re-authenticate when authLost is set
After a failure from the tag or reader (NAK, NO_RESPONSE, TIMEOUT, VENDOR_ERROR, or AUTH_FAILED), the
SDK selects the tag again before the next command, which drops authentication. When that happens, the
exception's authLost flag is set: authenticate again before sending another command to protected memory. On
ISO-DEP cards such as DESFire, re-select the application as well. Until you authenticate again, MIFARE Classic
block commands fail with AUTH_FAILED without reaching the tag.
A key, block, or page argument of the wrong length or sign, or a value below zero, throws
IllegalArgumentException before anything reaches the tag.