Tapaya

NFC Tags

Android

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

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

DeviceReaderArtifacts
Android phones and tablets with NFCAndroid NFCcom.tapaya:accept-nfc
Sunmi P-series terminalsThe payment module's contactless reader, through Sunmi's pay servicecom.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 typeExamples
NFC Type 2NTAG, MIFARE Ultralight, Ultralight EV1, Ultralight C
MIFARE ClassicMIFARE Classic Mini, 1K, 4K
ISO-DEP smart cardsMIFARE 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

  1. Your app calls Accept.nfc.openSession(activity).
  2. The SDK turns on the reader and waits for a tap.
  3. The customer taps a tag, and openSession() returns a TagSession carrying the tag's UID and family.
  4. Your app reads and writes through the session, one command at a time.
  5. 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.

build.gradle.kts
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.nfc

Check 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
    }
}
TagSessionEndReasonWhen it happens
CLOSEDYour app called close().
CARD_REMOVEDThe tag left the field and wasn't selected again within the reselect timeout, or a different tag came back.
IDLE_TIMEOUTNo command arrived within the idle timeout (10 seconds by default).
PAYMENTA payment started through Accept.payments.pay(). Payments always take priority.
ACTIVITY_PAUSEDPhones only: the activity the session was opened with left the foreground.
READER_LOSTThe 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 with READER_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:

  1. Check that isSupported() returns true on a phone with NFC and on a Sunmi terminal with accept-nfc-sunmi.
  2. On a phone, switch NFC off and confirm openSession() fails with NFC_DISABLED.
  3. Tap an NTAG or Ultralight tag and verify the session reports the right UID and readPages(0) returns 16 bytes. Then writePage and read the page back.
  4. On MIFARE Classic, authenticate with a wrong key and confirm AUTH_FAILED, then with the right one.
  5. Cancel openSession() during the tap wait and open a new session straight away.
  6. Start a payment during a session: the session should end as PAYMENT and the payment go through. Remove the tag during another session: it should end as CARD_REMOVED.
  7. 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.

Missing something on this page?Request a feature. We attach this page so the team sees the context.