@walletfactory/emvqr
Version:
Decode emv qr code specification for payments
58 lines (43 loc) • 1.02 kB
JavaScript
const crc = require('./crc')
const { getTag, getSubTag } = require('./scheme')
const validate = (text) => {
const data = text.substring(0, text.length - 4)
const checksum = text.substring(text.length - 4)
const hash = crc.computeCRC(data)
return hash === checksum
}
const read = (text, tagId) => {
const id = text.substring(0, 2)
const len = parseInt(text.substring(2, 4))
const data = text.substring(4, len + 4)
const next = text.substring(len + 4)
if (!len || !data.length || len !== data.length) {
return {}
}
if (!tagId && !getTag(id)) {
return {}
}
if (tagId && !getSubTag(tagId, id)) {
return {}
}
if (next.length) {
let value = read(data, id)
if (!Object.keys(value).length) {
value = data
}
return {
[id]: value,
...read(next)
}
}
return { [id]: data }
}
const decode = (text) => {
if (!validate(text)) {
throw new Error('Checksum validation failed.')
}
return read(text)
}
module.exports = {
decode
}