-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
98 lines (92 loc) · 2.91 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*!
* promptpay-emvco-parser
* JavaScript library to parse the promptpay qrcode into emvco object
* <https://github.com/apemon/promptpay-emv-parser>
*
* Refs:
* - https://www.blognone.com/node/95133
* - https://www.emvco.com/emv-technologies/qrcodes/
* - https://github.com/dtinth/promptpay-qr
* - https://github.com/mhdnamvar/node-emv.git
*
* @license MIT
*/
var crc = require('crc');
var emv_tags = require('./tags.js');
function parse(emvdata) {
// tokenize the string first
var tags = _parseTag(emvdata);
// read from each tag
var result = {};
var keys = Object.keys(tags);
for(var i=0;i<keys.length;i++) {
var key = keys[i];
var value = tags[key];
var tag = emv_tags[key];
var temp = tag;
temp.data = value.data;
result[tag.name] = temp;
// check merchant info
if(key == "29") temp.merchantInfo = _parsePromptPayInfo(temp);
// check crc
if(key == "63") temp.valid = _checkCRC(emvdata);
}
return result;
}
function _parsePromptPayInfo(merchantTag) {
// 29 - promptpay
var merchantData = _parseTag(merchantTag.data);
var applicationId = merchantData["00"];
// find promptpay id type
var promptpayIdType;
if(merchantData["01"]) promptpayIdType = "MobileNumber";
else if(merchantData["02"]) promptpayIdType = "TaxId";
else if(merchantData["03"]) promptpayIdType = "EWalletId";
else promptpayIdType = "Unknown";
// formatting
var promptpayNumber;
switch(promptpayIdType) {
case "MobileNumber": promptpayNumber = _formatMobileNumber(merchantData["01"].data); break;
case "TaxId": promptpayNumber = merchantData["02"].data; break;
case "EWalletId": promptpayNumber = merchantData["03"].data; break;
}
// construct merchant info
var merchantInfo = {
"promptpayIdType": promptpayIdType,
"promptpayNumber": promptpayNumber
}
return merchantInfo;
}
function _formatMobileNumber(input) {
return "0" + input.substr(4);
}
function _checkCRC(input) {
var inputCRC = input.substr(-4).toUpperCase();
var content = input.substr(0, input.length - 4);
var crcValue = crc.crc16xmodem(content, 0xffff);
crcValue = ("0000" + crcValue.toString(16).toUpperCase()).slice(-4);
return crcValue == inputCRC;
}
function _parseTag(emvdata) {
var tags = {};
var index = 0;
var data = emvdata;
while (index < emvdata.length) {
var data = emvdata.substring(index);
// get ID tag
var tagId = data.substr(0, 2);
// get tag length
var tagLength = parseInt(data.substr(2, 2));
// get tag information
var tagInformation = data.substr(4, tagLength);
var tag = {
"id": tagId,
"length": tagLength,
"data": tagInformation
}
tags[tagId] = tag;
index += tagLength + 4;
}
return tags;
}
module.exports = parse