partner-simplepay.js
13.2 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
"use strict";
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const request = require('request');
const crypto = require('crypto');
const moment = require('moment');
const URL = require('url');
const http = require('http');
http.globalAgent.maxSockets = Infinity;
const seconds_to_wait_before_resend_on_pending = 4;
var config;
var aaa;
var logger;
function start(options) {
if (!options) {
console.log('Undefined options, terminating....');
process.exit(1);
}
if (options.config) {
config = options.config;
} else {
console.log('Undefined options.config, terminating....')
process.exit(1);
}
if (options.aaa) {
aaa = options.aaa;
} else {
console.log('Undefined options.aaa, terminating....')
process.exit(1);
}
if (options && options.logger) {
logger = options.logger;
} else {
console.log('Undefined options.logger, terminating....')
process.exit(1);
}
createReverseHttpServer();
}
function callbackReport(requestId, rc, message, options) {
aaa.callbackReportWithPushToMongoDb(requestId, rc, message);
//return;
// resend trx as status check if rc 68 and task is defined
if (config && config.h2h_out.auto_resend && Number(config.h2h_out.auto_resend) && options && options.task && (rc == '68')) {
logger.verbose('Got pending trx, requesting in ' + seconds_to_wait_before_resend_on_pending + ' secs');
setTimeout(function() {
checkStatus(options.task);
}, seconds_to_wait_before_resend_on_pending * 1000)
}
}
function calculateSign(dt, trx_ref_id, cust_num, username, password) {
const cryptoHashPassword = crypto.createHash('sha1');
const cryptoHashUsernamePassword = crypto.createHash('sha1');
const cryptoHashOutest = crypto.createHash('sha1');
cryptoHashPassword.update(password);
const hashPassword = cryptoHashPassword.digest('hex');
cryptoHashUsernamePassword.update(username + hashPassword);
const hashUsernamePassword = cryptoHashUsernamePassword.digest('hex');
cryptoHashOutest.update(dt + trx_ref_id + cust_num + hashUsernamePassword);
return cryptoHashOutest.digest('hex');
}
function _decodeResponseBody(responseBody) {
let response;
try {
response = JSON.parse(responseBody);
}
catch(e) {
logger.warn('Error parsing response body');
}
return response;
}
function _composeMessageFromResponseData(responseDataObj) {
const diag = _getPropertyFromObjectSafe(responseDataObj, 'diag');
const msg = _getPropertyFromObjectSafe(responseDataObj, 'message');
const balance = _getPropertyFromObjectSafe(responseDataObj, 'balance');
const timestamp = _getPropertyFromObjectSafe(responseDataObj, 'timestamp');
const price = _getPropertyFromObjectSafe(responseDataObj, 'harga');
let messages = [];
if (timestamp) {
messages.push(timestamp);
}
if (diag) {
messages.push(diag);
}
if (msg) {
messages.push(msg);
}
if (balance) {
messages.push('Balance: ' + balance);
}
if (price) {
messages.push('Price: ' + price);
}
return messages.join('. ') + '.';
}
function _composeCompleteSn(responseDataObj) {
let serial = _getPropertyFromObjectSafe(responseDataObj, 'serial');
const info = _getPropertyFromObjectSafe(responseDataObj, 'info');
if (serial) {
serial = serial.replace(/ /g, '-');
}
if (!info) {
//logger.warn('Undefined data.info on _composeCompleteSn');
return serial;
}
const cleanedData = {
token: serial,
cust_name: _getPropertyFromObjectSafe(info, 'cust_name'),
tariff: _getPropertyFromObjectSafe(info, 'kelas'),
total_kwh: _getPropertyFromObjectSafe(info, 'size')
}
if (cleanedData && cleanedData.tariff && typeof cleanedData === 'string' && (cleanedData.tariff.search(/VA$/) < 0) ) {
cleanedData.tariff += 'VA';
}
if (cleanedData.cust_name) {
cleanedData.cust_name = cleanedData.cust_name.replace(/\W+/g, '-').replace(/\W+/g, '-').replace(/-+$/, '').replace(/^-+/, '').toUpperCase();
}
if (cleanedData.total_kwh) {
cleanedData.total_kwh = cleanedData.total_kwh.replace(/kWh\s*/g, '');
}
logger.verbose('Detail token info extracted', {originalResponseInfo: info, cleanedData: cleanedData});
return [
cleanedData.token, cleanedData.cust_name, cleanedData.tariff, cleanedData.total_kwh
].join('/');
}
function _responseBodyHandler(responseBody, task) {
let rc = '68';
let response = _decodeResponseBody(responseBody);
logger.verbose('RESPONSE', {response: response});
const responseStatus = _getPropertyFromObjectSafe(response, 'status');
const responseInfo = _getPropertyFromObjectSafe(response, 'info');
if (responseStatus == 'Error') {
if (['insufficient balance', 'System Cut-Off'].indexOf(responseInfo) >= 0) {
rc = '91';
}
callbackReport(task.requestId, '91', [responseStatus, responseInfo].join(': '), {task: task});
return;
}
const requestId = _getPropertyFromObjectSafe(response.data, 'request_id');
const trxStatus = _getPropertyFromObjectSafe(response.data, 'trx_status');
const diag = _getPropertyFromObjectSafe(response.data, 'diag');
let balance = _getPropertyFromObjectSafe(response.data, 'balance');
if ((typeof balance === 'string') && balance && aaa.updateBalance) {
balance = balance.replace(/\D/g, '');
if (balance) {
aaa.updateBalance(balance);
}
}
let aaaMessage = _composeMessageFromResponseData(response.data);
if (!aaaMessage) {
aaaMessage = 'Transaksi sedang diproses';
}
if (trxStatus == 'P') {
logger.verbose('Got pending trx response', {response: response.data});
rc = '68';
}
else if (trxStatus == 'S') {
logger.verbose('Got succcess trx response', {response: response.data});
rc = '00';
aaaMessage = 'SN=' + _composeCompleteSn(response.data) + '; ' + aaaMessage;
}
else if (trxStatus == 'R') {
logger.verbose('Got rejected trx response', {response: response.data});
const partnerRC = getPartnerRCFromDiagMessage(diag);
if (partnerRC == '15') {
rc = '14';
}
else {
rc = '40';
}
}
callbackReport(requestId, rc, aaaMessage, {task: task});
}
function getPartnerRCFromDiagMessage(diag) {
let matches = diag.match(/^\s*\[(.*)\]/);
if (!matches || matches.length < 2) {
return;
}
return matches[1];
}
function _hitTopup(task, isCheckStatus) {
const dt = moment().format('YYYY-MM-DD HH:mm:ss');
const username = config.h2h_out.username || config.h2h_out.userid;
const password = config.h2h_out.password || config.h2h_out.pin;
const sign = calculateSign(dt, task.requestId, task.destination, username, password);
logger.verbose('Sign for ' + dt + ', ' + task.requestId + ', ' + task.destination + ', ' + username + ', ' + password + ' is ' + sign);
const requestOptions = {
url: config.h2h_out.partner,
form: {
username: username,
datetime: dt,
code: task.remoteProduct,
trx_ref_id: task.requestId,
cust_num: task.destination,
sign: sign
}
}
logger.verbose('Requesting to partner', {requestOptions: requestOptions});
request.post(requestOptions, function(error, response, body) {
if (error) {
let rc = '68';
if (!isCheckStatus && (error.syscall == 'connect')) {
rc = '91';
}
logger.warn('Error requesting to partner', {task: task, rc: rc, error: error, isCheckStatus: isCheckStatus});
callbackReport(task.requestId, rc, 'Error requesting to partner. ' + error, {task: task});
return;
}
if (response.statusCode != 200) {
let rc = '68';
logger.warn('HTTP status code is not 200', {task: task, http_status_code: response.statusCode, isCheckStatus: isCheckStatus});
callbackReport(task.requestId, rc, 'HTTP status code ' + response.statusCode, {task: task});
return;
}
logger.info('Transaksi sedang diproses', {task: task, response_body: body});
_responseBodyHandler(body, task);
})
}
function _getPropertyFromObjectSafe(obj, property) {
let retval;
if (!obj) {
logger.warn('Invalid object')
return;
}
try {
retval = obj[property];
}
catch(e) {
logger.warn('Error getting ' + property + ' from object');
}
return retval;
}
function topupRequest(task) {
aaa.insertTaskToMongoDb(task);
_hitTopup(task);
}
function checkStatus(task) {
_hitTopup(task, true);
}
function reverseReportHandler(data) {
//logger.info('Got reverse report', {body: body});
const qs = URL.parse(data, true).query;
if (!qs || !qs.request_id) {
return;
}
if ((typeof qs.balance === 'string') && qs.balance && aaa.updateBalance) {
const balance = qs.balance.replace(/\D/g, '');
if (balance) {
aaa.updateBalance(balance);
}
}
let rc = '68';
if (qs.trx_status === 'S') {
rc = '00';
}
else if (qs.trx_status === 'R') {
rc = '40';
}
if ((typeof qs.serial === 'string') && qs.serial) {
rc = '00';
}
if (rc === '40') {
const partnerRC = getPartnerRCFromDiagMessage(qs.diag);
if (['14', '15'].indexOf(partnerRC) >= 0) {
rc = '14';
}
logger.verbose('REVERSE-REPORT: parsing diag', {request_id: qs.request_id, diag: qs.diag, partnerRC: partnerRC, newRc: rc});
}
const sn = (rc === '00') ? _createSnFromReverseReport(qs) : null;
let msg = [
'REVERSE REPORT',
'Diag: ' + (qs.diag || '-'),
'Message: ' + (qs.message || '-'),
'Status: ' + (qs.trx_status || '-'),
'Balance: ' + (qs.balance || '-'),
'Harga: ' + (qs.harga || '-')
].join('. ');
if (sn) {
msg = 'SN=' + sn + '; ' + msg;
}
callbackReport(qs.request_id, rc, msg);
}
function _parseInfoFromReverseReport(info) {
let result;
try {
result = JSON.parse(info);
}
catch (e) {
logger.warn('Exception on parsing qs info as JSON', {info: info});
}
return result;
}
function _createSnFromReverseReport(qs) {
let token = qs.serial;
if (token && typeof token === 'string') {
token = token.replace(/\W+/g, '-');
}
let sn = token || '-';
const info = _parseInfoFromReverseReport(qs.info);
if (info) {
const cust_name = (typeof info.cust_name === 'string') ? info.cust_name.replace(/\W+/g, '-').replace(/^\W+/, '').replace(/\W+$/, '') : '-';
const kelas = (typeof info.kelas === 'string') ? info.kelas.trim() : '-';
const kwh = (typeof info.size === 'string') ? info.size.trim() : '-';
sn = [
token || '-',
cust_name || '-',
kelas || '-',
kwh || '-'
].join('/');
}
return sn;
}
function createReverseHttpServer() {
var httpServer = http.createServer(function(req, res) {
logger.info('Got request from partner (reverse report)', {remote_address: req.connection.remoteAddress, url: req.url});
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
res.writeHead(200);
res.end('OK');
logger.info('Got reverse report with POST method', {body: body});
reverseReportHandler('?' + body);
});
return;
const qs = URL.parse(req.url, true).query;
if (!qs || !qs.request_id) {
return;
}
let rc = '68';
if (qs.trx_status === 'S') {
rc = '00';
}
else if (qs.trx_status === 'R') {
rc = '40';
}
if (rc === '40') {
const partnerRC = getPartnerRCFromDiagMessage(diag);
if (['14', '15'].indexOf(partnerRC) >= 0) {
rc = '14';
}
logger.verbose('REVERSE-REPORT: parsing diag', {request_id: qs.request_id, diag: diag, partnerRC: partnerRC, newRc: rc});
}
if ((typeof qs.balance === 'string') && qs.balance && aaa.updateBalance) {
const balance = qs.balance.replace(/\D/g, '');
if (balance) {
aaa.updateBalance(balance);
}
}
const sn = (rc === '00') ? _createSnFromReverseReport(qs) : null;
let msg = [
'REVERSE REPORT',
qs.diag,
'Status: ' + (qs.trx_status || '-'),
'Balance: ' + (qs.balance || '-'),
'Harga: ' + (qs.harga || '-')
].join('. ');
if (sn) {
msg = 'SN=' + sn + '; ' + msg;
}
callbackReport(qs.request_id, rc, msg);
});
httpServer.listen(config.h2h_out.listen_port, function() {
logger.info('HTTP Reverse/Report server listen on port ' + config.h2h_out.listen_port);
});
}
exports.calculateSign = calculateSign;
exports.start = start;
exports.topupRequest = topupRequest;
exports.checkStatus = checkStatus;