API¶
This section covers the native Android API: how to start the flow, configure the SDK, implement the available listeners, and read the results, errors and events it returns.
Listener interfaces¶
Use these interfaces to receive lifecycle callbacks and events:
interface NfcReadListener {
fun onNfcReadStarted()
fun onNfcReadResults(results: NfcReadResult)
fun onNfcReadFinished(error: NfcReadError?)
}
interface NfcReadEventsListener {
fun onNfcReadEvent(event: NfcReadEvent)
}
The callbacks are received on the main thread, in this order:
onNfcReadStarted()when the SDK has been launched and the flow begins.onNfcReadResults(results)only when the chip was read and verified successfully.onNfcReadFinished(error)when the SDK has been dismissed, always as the last callback.errorisnullafter a successful read.
Invalid configuration
If the configuration is not valid, the SDK does not start: onNfcReadFinished(error) is called right away with the configuration error, and onNfcReadStarted() is never called.
Entry point¶
NfcRead is the entry point of the SDK:
| Method | Description |
|---|---|
NfcRead.start(listener, configuration, context) |
Validates the configuration and starts the flow. |
NfcRead.setEventsListener(listener) |
Sets the listener that receives the events of the flow. |
NfcRead.stop() |
Closes the flow from the host app. The SDK finishes with the integratorClose error. |
NfcRead.getVersion() |
Returns the version of the SDK. |
Starting a flow¶
1) Create an NfcReadConfiguration (build it in code or decode it from JSON).
2) Set the events listener (optional but recommended).
3) Start the SDK with your listener and configuration.
import android.util.Log
import androidx.activity.ComponentActivity
import com.veridas.sdk.nfc.entrypoint.NfcRead
import com.veridas.sdk.nfc.entrypoint.NfcReadEventsListener
import com.veridas.sdk.nfc.entrypoint.NfcReadListener
import com.veridas.sdk.nfc.entrypoint.NfcReadResult
import com.veridas.sdk.nfc.error.NfcReadError
import com.veridas.sdk.nfc.event.NfcReadEvent
class NfcIntegratorActivity :
ComponentActivity(),
NfcReadListener,
NfcReadEventsListener
{
private companion object {
private val TAG = NfcIntegratorActivity::class.simpleName
}
fun startNfcRead() {
NfcRead.start(
listener = this,
configuration = getConfigurationFromAsset("nfcRead.json"),
context = this
)
NfcRead.setEventsListener(this)
}
// NfcReadListener
override fun onNfcReadResults(results: NfcReadResult) {
Log.i(TAG, "NFC SDK -- onNfcReadResults $results")
}
override fun onNfcReadStarted() {
Log.i(TAG, "NFC SDK -- Started")
}
override fun onNfcReadFinished(error: NfcReadError?) {
Log.i(TAG, "NFC SDK -- onNfcReadFinished $error")
}
// NfcReadEventsListener
override fun onNfcReadEvent(event: NfcReadEvent) {
Log.i(TAG, "NFC SDK -- onNfcReadEvent $event")
}
}
Example helper for loading JSON configs (shared by all SDKs):
import com.veridas.sdk.nfc.configuration.NfcReadConfiguration
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
@OptIn(ExperimentalSerializationApi::class)
private val json = Json {
ignoreUnknownKeys = true
explicitNulls = false
}
fun getConfigurationFromAsset(fileName: String): NfcReadConfiguration {
val jsonString = applicationContext
.assets
.open(fileName)
.bufferedReader()
.use { it.readText() }
return json.decodeFromString<NfcReadConfiguration>(jsonString)
}
Providing the document data at runtime¶
The data that opens the chip usually comes from a previous step of your flow (for example, the OCR of a document capture) rather than from a static JSON file. Set it on the configuration before starting the SDK. When it is complete and valid, the form is skipped and the reading starts right away:
import com.veridas.sdk.nfc.configuration.NfcPrefill
import com.veridas.sdk.nfc.configuration.NfcSetup
val base = getConfigurationFromAsset("nfcRead.json")
val config = base.copy(
setup = (base.setup ?: NfcSetup()).copy(
prefill = NfcPrefill(
documentNumber = "BAA000589",
dateOfBirth = "860816", // MRZ format: yyMMdd
dateOfExpiry = "281127" // MRZ format: yyMMdd
),
keys = listOf("DG1_NAME", "DG1_SURNAME", "DG1_DOC_NUMBER", "DG1_DOB")
)
)
NfcRead.start(listener = this, configuration = config, context = this)
The keys to return usually come at runtime too: when your flow uses the Veridas services, pass the nfcKeys they return for the document.
See prefill for the validation rules.
ViewModel example¶
The listeners do not need to be an Activity. This example implements them in a ViewModel, and receives the Context that launches the SDK from the screen that calls it, so the ViewModel does not keep a reference to it:
import android.content.Context
import android.util.Log
import androidx.lifecycle.ViewModel
import com.veridas.sdk.nfc.configuration.NfcReadConfiguration
import com.veridas.sdk.nfc.entrypoint.NfcRead
import com.veridas.sdk.nfc.entrypoint.NfcReadEventsListener
import com.veridas.sdk.nfc.entrypoint.NfcReadListener
import com.veridas.sdk.nfc.entrypoint.NfcReadResult
import com.veridas.sdk.nfc.error.NfcReadError
import com.veridas.sdk.nfc.event.NfcReadEvent
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
class MainSdkViewModel : ViewModel(), NfcReadListener, NfcReadEventsListener {
private companion object {
private val TAG = MainSdkViewModel::class.simpleName
}
@OptIn(ExperimentalSerializationApi::class)
private val json = Json {
ignoreUnknownKeys = true
explicitNulls = false
}
fun startNfcRead(context: Context) {
val config = loadConfigFromJson(context, "nfcRead.json")
NfcRead.start(listener = this, configuration = config, context = context)
NfcRead.setEventsListener(this)
}
private fun loadConfigFromJson(context: Context, fileName: String): NfcReadConfiguration {
val jsonString = context.assets.open(fileName).bufferedReader().use { it.readText() }
return json.decodeFromString<NfcReadConfiguration>(jsonString)
}
// NfcReadListener
override fun onNfcReadResults(results: NfcReadResult) { Log.i(TAG, "onNfcReadResults $results") }
override fun onNfcReadStarted() { Log.i(TAG, "onNfcReadStarted") }
override fun onNfcReadFinished(error: NfcReadError?) { Log.i(TAG, "onNfcReadFinished $error") }
// NfcReadEventsListener
override fun onNfcReadEvent(event: NfcReadEvent) { Log.i(TAG, "onNfcReadEvent $event") }
}
Results¶
onNfcReadResults(results) receives an NfcReadResult:
data class NfcReadResult(
val keysData: Map<String, String>,
val certificate: NfcCertificate,
val authentication: NfcAuthentication,
val dataGroupHashes: List<NfcDataGroupHash>
)
The results are only delivered when the document passed every authenticity check that was performed. A document whose checks fail is not delivered: the SDK finishes with one of the authentication errors described in Errors.
Printing the results
The toString() of NfcReadResult (what logging results shows) lists the keys received, a summary of the certificate and of the authentication outcomes, and whether each data group hash is valid, but not the values: they are the holder's personal data. Read them from keysData.
keysData¶
The data read from the chip, keyed by field.
Only the requested keys are returned
keysData only contains the text keys listed in keys. If keys is not set or is empty, it contains no text key. The photos (cut_photo and signature) are the exception: they are always returned when the chip carries them, whether they are listed or not.
A requested key is absent when the chip does not carry that value (the data group was not read, the element is not in it, or it has no such part, such as an address with no region). A value the chip carries empty is "".
Text values are cleaned: the < filler characters of the MRZ are replaced by spaces, repeated spaces are collapsed and the result is trimmed. Dates use the dd MM yyyy format.
Key |
Value |
|---|---|
DG1_NAME |
Given names of the holder. Taken from DG11 when it was read, since DG1 truncates the name to the MRZ width; from DG1 otherwise. |
DG1_SURNAME |
Surnames of the holder, with the same source as DG1_NAME. A name with a single part is the surname, and DG1_NAME is absent. |
DG1_DOC_NUMBER |
Document number. |
DG1_DOC_TYPE |
Document type, as in the MRZ (for example ID, or P for passports). |
DG1_DOB |
Date of birth. Taken from DG11 when it carries a full date, from DG1 otherwise. |
DG1_DOE |
Date of expiry. |
DG1_ISSUER |
Issuing state or organization (for example ESP). |
DG1_NATIONALITY |
Nationality of the holder. |
DG1_SEX |
F or M. Absent for any other value. |
DG1_OPT_DATA |
Optional data of the MRZ. |
DG11_PERS_NUM |
Personal number from DG11. When DG11 does not carry it, the optional data of the MRZ. |
DG1_ADDR_LINE, DG1_ADDR_CITY, DG1_ADDR_REGION |
Permanent address from DG11: street, city and region. |
DG11_BIRTH_PLACE, DG11_BIRTH_STATE |
Place of birth from DG11: city and state or province. |
DG11_TITLE |
Title of the holder from DG11. |
cut_photo |
Face image of the holder (DG2), as a base64-encoded PNG. |
signature |
Signature image of the holder (DG7), as a base64-encoded PNG. |
Available data depends on the document
Not every document carries every data group. DG1 (MRZ data) and DG2 (face image) are always present on an eMRTD, while DG7 and DG11 are optional and depend on the issuer.
certificate¶
NfcCertificate, the Document Signer certificate that signed the chip's Document Security Object (SOD).
| Property | Description |
|---|---|
issuer |
Issuer of the certificate. |
notBefore |
Start of the validity period in UTC, as OpenSSL prints it, e.g. "Feb 9 00:00:00 2021 GMT". The iOS SDK delivers the same string. |
notAfter |
End of the validity period, in the same format. |
encoded |
The certificate in ASN.1 DER. Parse it with CertificateFactory.getInstance("X.509") to get an X509Certificate. |
A result is only delivered when the certificate is inside its validity period, chains to a trusted CSCA and verifies the signature of the SOD, so there is no validity flag.
authentication¶
NfcAuthentication, the result of every authentication protocol run against the chip. Each one is an NfcProtocolResult: SUCCESS, FAILED or NOT_PERFORMED.
Property |
Description |
|---|---|
pace |
PACE, the access protocol tried first. |
bac |
BAC, the access protocol used when PACE is not available or fails. |
chipAuthentication |
Chip Authentication (anti-cloning), performed when the chip has DG14. |
activeAuthentication |
Active Authentication (anti-cloning), performed when the chip has DG15. |
paceProtocol |
The PACE variant the chip was opened with, e.g. "id-PACE-ECDH-GM-AES-CBC-CMAC-256 / brainpoolP384r1". null when PACE did not succeed. |
A document usually implements only one of the two anti-cloning mechanisms. The Spanish DNIe, for example, uses Chip Authentication, so activeAuthentication == NOT_PERFORMED is expected. If both are NOT_PERFORMED, no anti-cloning check could be run on that document.
dataGroupHashes¶
One NfcDataGroupHash per data group read, with the result of Passive Authentication for it. The list is empty when the chip has no SOD.
Property |
Description |
|---|---|
dgNumber |
The data group number (1 for DG1, 2 for DG2...). |
readHash |
The hash stored in the SOD, as a ByteArray. null when the SOD has none for this group. |
calculatedHash |
The hash of the bytes read from the chip, as a ByteArray. null when it could not be calculated. |
isValid |
true when both hashes exist and are equal. |
Errors¶
onNfcReadFinished(error) receives an NfcReadError, or null when the flow ended after a successful read. It has two properties: error, a String with the error code, and info, an optional text with extra details (for example, the invalid configuration value, or the reason why Passive Authentication failed). info is null for every other error.
Error |
Description |
|---|---|
nfcUnavailable |
The device has no NFC reader. The SDK closes before showing any screen. |
configuration |
The configuration is not valid. info describes the problem. See Validation. |
passiveAuthenticationFailed |
The document could not be verified: its signer does not chain to a trusted CSCA, the SOD signature is not valid, or a data group does not match its hash in the SOD. info says why. |
chipAuthenticationFailed |
The chip failed Chip Authentication: it may be a clone. |
activeAuthenticationFailed |
The chip failed Active Authentication: it may be a clone. |
maxRetriesReached |
A reading failed after the user had used all the retries set in maxRetries, whatever the failure. |
userClose |
The user left the process. |
integratorClose |
The host app closed the SDK with NfcRead.stop(). |
authenticationFailed, timeout, readingFailed, unsupportedDocument |
Recoverable reading failures. The SDK lets the user retry them, so they are only returned if the user leaves the process while the failure is pending: the failure is returned instead of userClose. After a focus loss, leaving returns userClose. |
generic |
An unexpected error. |
The authentication errors do not consume a reading attempt: they end the flow at once, because reading the same document again would give the same result.
override fun onNfcReadFinished(error: NfcReadError?) {
when (error?.error) {
null -> Log.i(TAG, "The flow finished successfully")
"userClose", "integratorClose" -> Log.i(TAG, "The flow was closed")
"passiveAuthenticationFailed" -> Log.w(TAG, "The document is not valid: ${error.info}")
else -> Log.e(TAG, "The flow ended with ${error.error}")
}
}
Dispatched events¶
The SDK dispatches a set of events to communicate that the corresponding actions have been taken. Each event is sent to fun onNfcReadEvent(event: NfcReadEvent), which receives a data class:
data class NfcReadEvent
This object contains the following attributes: type with the event identifier, sdkDefinition and flowDefinition, whose name is always "VD-NFC" and "nfc" respectively, and detail, with all the information specific to the event. detail has the same fields as the events of the Selfie, Document and Video SDKs (type and errorType), except stage, size, flow and code, which NFC events never set, followed by the NFC ones listed below. The fields of detail are optional and only the ones listed for each event are set, so make sure your code handles missing values.
Event Name |
Event Detail | Event Trigger |
|---|---|---|
VD_started |
— | When the SDK has started. |
VD_nfcFlowStarted |
— | When the reading flow starts. |
VD_instructions |
— | When the instructions are displayed. |
VD_nfcMrzEntered |
— | When the user submits valid data in the document data form. |
VD_nfcPermissionsRequested |
— | When the user is asked to turn NFC on, because the device has it but it is switched off. It is not sent when NFC is already on. |
VD_nfcReadStarted |
"retries": 0 |
When a chip reading attempt starts: the reading screen is shown, with no need to tap the document, and again each time the user retries or restarts from it. retries is the number of attempts that have already failed (0 on the first one). |
VD_nfcWrongKey |
"errorType": "wrongKey" |
When the chip could not be opened with the document data provided (followed by VD_nfcReadFailed, since it uses a retry). |
VD_nfcReadFailed |
"retries": 1 |
When a reading attempt fails because the document was not detected, the reading was interrupted, the document is not supported or the chip could not be opened with the document data. retries is the number of failed attempts so far: the SDK ends with maxRetriesReached when it goes over maxRetries. |
VD_nfcCancelled |
— | When the user confirms leaving the process from the exit confirmation modal. |
VD_loseFocus |
— | When the app goes to the background while the reading screen waits for a document or reads it. The reading is interrupted and the focus loss feedback screen is shown, so the user can restart the process. |
VD_nfcPassiveAuthChecked |
"accessProtocol": "PACE", "correctlySigned": true, "dataIntegrityVerified": true, "chipAuthentication": "SUCCESS", "activeAuthentication": "NOT_PERFORMED", "trustworthy": true, "paceProtocol": "id-PACE-ECDH-GM-AES-CBC-CMAC-256 / brainpoolP384r1", "readBlockSize": 223 |
When the chip has been read and its authenticity has been verified. |
VD_nfcReadSucceeded |
— | When the reading finishes successfully. |
VD_restartClicked |
"type": "restarted" |
When the retry or restart button is clicked in a feedback screen. |
VD_closeClicked |
"type": "exit" |
When the user confirms leaving the process in the exit confirmation modal. |
VD_processFinished |
— | When the process finishes successfully. |
The fields of VD_nfcPassiveAuthChecked:
Field |
Description |
|---|---|
accessProtocol |
The protocol that opened the chip: PACE or BAC. |
correctlySigned |
Whether the Document Signer chains to a trusted CSCA and the SOD signature is valid. |
dataIntegrityVerified |
Whether every data group read matches its hash in the SOD. |
chipAuthentication, activeAuthentication |
SUCCESS, FAILED or NOT_PERFORMED. |
trustworthy |
Whether the document passed every check that was performed. |
paceProtocol |
The PACE variant the chip was opened with. Absent when PACE did not succeed. |
readBlockSize |
Bytes read per command: 223. |
Events shared with the iOS SDK
The NFC event identifiers and the NFC fields of detail are the ones of the iOS SDK, so the same analytics can be used on both platforms. The structure of the event follows the other Android SDKs instead: the SDK and flow names are the sdkDefinition and flowDefinition objects, and there is no detail.type of info or error. Two things differ: VD_nfcPermissionsRequested and the retries of VD_nfcReadStarted are only sent by the Android SDK, and the initialSelectedAID field of VD_nfcPassiveAuthChecked only exists on iOS.