diff --git a/application/helpers/HMAC.js b/application/helpers/HMAC.js deleted file mode 100644 index 9e531f5..0000000 --- a/application/helpers/HMAC.js +++ /dev/null @@ -1,13 +0,0 @@ -const CryptoJS = require('crypto-js'); - -const createHMAC = async (payload) => { - let hash = await CryptoJS.HmacSHA256( - payload, - process.env.SECRET_KEY - ).toString(); - return hash; -}; - -module.exports = { - createHMAC, -}; diff --git a/application/helpers/helper.js b/application/helpers/helper.js index e84dc23..6150b1b 100644 --- a/application/helpers/helper.js +++ b/application/helpers/helper.js @@ -1,4 +1,4 @@ -const CryptoJS = require("crypto-js"); +const CryptoJS = require('crypto-js'); // ENCRYPT TEXT const encryptText = (text) => { @@ -20,6 +20,15 @@ const decryptText = (cipherText) => { } }; +// CREATE HMAC +const createHMAC = async (payload) => { + let hash = await CryptoJS.HmacSHA256( + payload, + process.env.SECRET_KEY + ).toString(); + return hash; +}; + // RANDOM UNIQUE CODE function getUniqueCode() { const maxDate = Date.now(); @@ -36,48 +45,64 @@ function randomNumberInt() { while (result.length !== 3) { let random = getRandomArbitrary(0, 9); if (!result.includes(random)) result.push(random); - + // To check if the first no is not zero if (result.length === 1 && random === 0) result.pop(); } - return parseInt( result.join("") ); + return parseInt(result.join('')); } // GENERATE XML REQUEST function generateXMLRequest(urn, headers, items) { - let xmlRequest = '' - + let xmlRequest = ''; + switch (urn.toUpperCase()) { case 'ZFMCMS_FI_001': - - let xmlItem = '' + let xmlItem = ''; items.map((item, index) => { xmlItem += ` - ${String(index+1).padStart(10, '0')} + ${String(index + 1).padStart( + 10, + '0' + )} - ${item.c_account_code_topup ? item.c_account_code_topup : ""} + ${ + item.c_account_code_topup + ? item.c_account_code_topup + : '' + } - ${item.c_account_topup ? item.c_account_topup : ""} + ${ + item.c_account_topup ? item.c_account_topup : '' + } - ${item.ba ? item.ba : ""} + ${item.ba ? item.ba : ''} - ${item.amount ? item.amount : ""} + ${ + item.amount ? item.amount : '' + } - ${item.posting_date ? item.posting_date : ""} + ${ + item.posting_date ? item.posting_date : '' + } - ${item.c_invoice_no ? item.c_invoice_no : ""} + ${ + item.c_invoice_no ? item.c_invoice_no : '' + } - ${item.item_text ? item.item_text : ""} + ${ + item.item_text ? item.item_text : '' + } ${item.de_cre} - ` - }) + `; + }); xmlRequest = ` @@ -144,144 +169,157 @@ function generateXMLRequest(urn, headers, items) { - ` + `; break; default: console.log('Sorry, we are out of ' + urn + '.'); } - - return xmlRequest + return xmlRequest; } // POSTING SAP -async function postingSAP(url, body, credential){ +async function postingSAP(url, body, credential) { try { + const axios = require('axios'); - const axios = require("axios"); - - const config = { - headers : { + const config = { + headers: { 'Content-Type': 'text/xml', - 'responseType': 'text', + responseType: 'text', }, auth: { username: credential.username, - password: credential.password - } - } + password: credential.password, + }, + }; - const resp = await axios.post(url, body, config) + const resp = await axios.post(url, body, config); return { - status : resp.status, - message: "Success", - data : resp.data - } - + status: resp.status, + message: 'Success', + data: resp.data, + }; } catch (error) { - // Error 😨 + // Error 😨 - if (error.response) { - /* - * The request was made and the server responded with a - * status code that falls out of the range of 2xx - */ - return { - status : error.response.status, - message: error.message, - data : [] - } - } else if (error.request) { - /* - * The request was made but no response was received, `error.request` - * is an instance of XMLHttpRequest in the browser and an instance - * of http.ClientRequest in Node.js - */ - return { - status : 500, - message: "can't connect to sap network".toUpperCase(), - data : [] - } - } else { - // Something happened in setting up the request and triggered an Error - return { - status : 500, - message: error.message, - data : [] - } - } + if (error.response) { + /* + * The request was made and the server responded with a + * status code that falls out of the range of 2xx + */ + return { + status: error.response.status, + message: error.message, + data: [], + }; + } else if (error.request) { + /* + * The request was made but no response was received, `error.request` + * is an instance of XMLHttpRequest in the browser and an instance + * of http.ClientRequest in Node.js + */ + return { + status: 500, + message: "can't connect to sap network".toUpperCase(), + data: [], + }; + } else { + // Something happened in setting up the request and triggered an Error + return { + status: 500, + message: error.message, + data: [], + }; + } } } // GET SOAP RESPONSE DATA function getXMLData(response) { const xml2js = require('xml2js'); -// console.log(xmlString) + // console.log(xmlString) let resSAP = { type: '', - message : '', - data : { + message: '', + data: { E_DOCUMENTYEAR: '', E_DOCUMENTNUMBER: '', // ITEM: [], - } - } + }, + }; - if(response.status == 200){ - + if (response.status == 200) { const options = { explicitArray: false, - tagNameProcessors: [xml2js.processors.stripPrefix] - } + tagNameProcessors: [xml2js.processors.stripPrefix], + }; xml2js.parseString(response.data, options, (err, result) => { - - if (err) throw err + if (err) throw err; let soapBody = result.Envelope.Body; - if (soapBody.$) delete soapBody.$ + if (soapBody.$) delete soapBody.$; - resSAP.data.E_DOCUMENTYEAR = soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTYEAR'] ? soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTYEAR'] : "0000" - resSAP.data.E_DOCUMENTNUMBER = soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTNUMBER'] ? soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTNUMBER'] : "" + resSAP.data.E_DOCUMENTYEAR = soapBody['ZFMCMS_FI_001.Response'][ + 'E_DOCUMENTYEAR' + ] + ? soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTYEAR'] + : '0000'; + resSAP.data.E_DOCUMENTNUMBER = soapBody['ZFMCMS_FI_001.Response'][ + 'E_DOCUMENTNUMBER' + ] + ? soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTNUMBER'] + : ''; - if(soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']){ - if (!Array.isArray(soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'])) { + if (soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']) { + if ( + !Array.isArray( + soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'] + ) + ) { // resSAP.data.ITEM.push(soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']) - resSAP.type = soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']['TYPE'] - resSAP.message = "[SAP] " + soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']['MESSAGE_1'] + resSAP.type = + soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']['TYPE']; + resSAP.message = + '[SAP] ' + + soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][ + 'MESSAGE_1' + ]; } else { // resSAP.data.ITEM = soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'] - resSAP.type = soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][0]['TYPE'] - - const indexMessage = soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'].length - 1 - let message = "[SAP] "+ soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][indexMessage]['MESSAGE_1'] + resSAP.type = + soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][0]['TYPE']; - resSAP.message = message + const indexMessage = + soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'].length - 1; + let message = + '[SAP] ' + + soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][ + indexMessage + ]['MESSAGE_1']; + + resSAP.message = message; } } - }); - - }else { - - resSAP.type = 'E' - resSAP.message = response.message ? response.message : "aa" - + } else { + resSAP.type = 'E'; + resSAP.message = response.message ? response.message : 'aa'; } - - return resSAP - + return resSAP; } module.exports = { encryptText, decryptText, + createHMAC, getUniqueCode, randomNumberInt, generateXMLRequest, postingSAP, - getXMLData + getXMLData, }; diff --git a/application/modules/reservebalance/reservebalance.controller.js b/application/modules/reservebalance/reservebalance.controller.js index 2a85c37..586710c 100644 --- a/application/modules/reservebalance/reservebalance.controller.js +++ b/application/modules/reservebalance/reservebalance.controller.js @@ -1,6 +1,5 @@ const { param, body, validationResult } = require('express-validator'); const helper = require('../../helpers/helper'); -const hmac = require('../../helpers/HMAC'); const winston = require('../../helpers/winston.logger'); const model = require('./reservebalance.model'); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); @@ -54,6 +53,14 @@ const validate = (method) => { .isNumeric() .withMessage('Amount is invalid format'), ]; + case 'reservationV2': + return [ + body('reservation_data') + .not() + .isEmpty() + .withMessage('Reservation data is required'), + body('ref_no').not().isEmpty().withMessage('Ref No is required'), + ]; case 'cancelReservation': return [ body('mid').not().isEmpty().withMessage('MID is required'), @@ -639,7 +646,7 @@ const reservationValidate = async (req, res) => { // *Created By: Mohamad Ihsan* // *Description:* // proses yang digunakan untuk melakukan validasi reservasi saldo. Proses ini seharusnya dilakukan terlebih dahulu sebelum melakukan insert data reservasi ke sistem CMS -// pada proses reservation validate version 2 ini, akan di generate berupa security code yang nanti nya akan digunakan sebagai keamanan data saat melakukan insert data reservasi +// pada proses reservation validate version 2 ini, data reservasi akan di encrypt dan data enkripan tersebut digunakan untuk end point reservation const reservationValidateV2 = async (req, res) => { try { @@ -1007,24 +1014,30 @@ const reservationValidateV2 = async (req, res) => { // }); // } + let reservationData = { + mid: mid, + tid: tid, + card_number: card_number, + amount: amount, + transaction_date: now, + }; + // log debug - // process mendapatkan persentase issuer fee dan channel free berdasarkan settingan dari sistem CMS + // process enkripsi data reservasi yang nanti nya akan di kirim ke end point reservation api untuk menyimpan data reservasi winston.logger.debug( - `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] generating security code...` + `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] encrypting data reservation: ${JSON.stringify( + reservationData + )}` ); - let hash = card_number + amount + moment().format('YYYYMMDDHHmm'); - let securityCode = await hmac.createHMAC(hash); + // enkripsi data reservasi sebelum melakukan transaksi reservasi + let hash = helper.encryptText(JSON.stringify(reservationData)); result = { code: '00', message: 'validation successfully.', data: { - reservation: { - card_number: card_number, - amount: amount, - }, - security_code: securityCode, + reservation_data: hash, }, }; @@ -1667,8 +1680,7 @@ const reservationV2 = async (req, res) => { let result = {}; // param - let { mid, tid, card_number, amount, ref_no } = req.body; - const security_code = req.header('Reservation-Security-Code'); + let { reservation_data, ref_no } = req.body; // log info winston.logger.info( @@ -1692,45 +1704,18 @@ const reservationV2 = async (req, res) => { return res.status(200).json(result); } - // cek security code di header request - if (!security_code) { - result = { - code: '400', - message: 'reservation security code is required', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - // log debug - // pengecekkan konten data yang dikirim dengan security code yang dikirim + // pengecekkan reservation data yang di request winston.logger.debug( - `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking content data request and security code...` + `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking reservation data...` ); - let hash = card_number + amount + moment().format('YYYYMMDDHHmm'); - let hash1 = - card_number + - amount + - moment().subtract(1, 'minutes').format('YYYYMMDDHHmm'); - let hash2 = - card_number + amount + moment().add(1, 'minutes').format('YYYYMMDDHHmm'); + let reservationData = helper.decryptText(reservation_data); - let securityCode = []; - securityCode.push(await hmac.createHMAC(hash)); - securityCode.push(await hmac.createHMAC(hash1)); - securityCode.push(await hmac.createHMAC(hash2)); - - if (!securityCode.includes(security_code)) { + if (!reservationData) { result = { code: '435', - message: 'bad request. content data is invalid.', + message: 'bad request. reservation data is invalid.', data: {}, }; @@ -1742,6 +1727,29 @@ const reservationV2 = async (req, res) => { return res.status(200).json(result); } + reservationData = JSON.parse(reservationData); + + // extract reseravtion data + let mid = reservationData.mid; + let tid = reservationData.tid; + let card_number = reservationData.card_number; + let amount = reservationData.amount; + let transactionDate = reservationData.transaction_date; + + // log debug + // pengecekkan reservation data yang di request + winston.logger.debug( + `${uniqueCode} [ PROCESSING RESERVATION-V2 ] extracting reservation data : ${JSON.stringify( + { + mid: mid, + tid: tid, + card_number: card_number, + amount: amount, + transaction_date: transactionDate, + } + )}` + ); + // log debug // pengecekkan nomor kartu yang di request adalah kartu production atau bukan berdasarkan settingan di .ENV dengan constanta SERVER_FOR. // Jika settingan .ENV SERVER_FOR adalah production dan nomor kartu KMT yang di request adalah kartu development maka sistem online topup akan menolaknya. Begitupun sebaliknya diff --git a/application/routes/reservebalance.routes.js b/application/routes/reservebalance.routes.js index c17252d..f991879 100644 --- a/application/routes/reservebalance.routes.js +++ b/application/routes/reservebalance.routes.js @@ -68,7 +68,7 @@ router.post( router.post( '/reservation/v2', auth.authenticateToken, - controller.validate('reservation'), + controller.validate('reservationV2'), controller.reservationV2 ); diff --git a/server/index.js b/server/index.js index 2257799..6720644 100644 --- a/server/index.js +++ b/server/index.js @@ -2,7 +2,6 @@ const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const helper = require('../application/helpers/helper'); -const hmac = require('../application/helpers/HMAC.js'); const winston = require('../application/helpers/winston.logger'); const authRoute = require('../application/routes/auth.routes'); const dongleOrderRoute = require('../application/routes/dongleorder.routes'); @@ -38,13 +37,20 @@ app.use(bodyParser.urlencoded({ extended: true })); // ============================== ROUTES API ============================== app.get('/', async (req, res) => { - let hash = await hmac.createHMAC('hallo'); + let data = { + card_number: '1234567890', + amount: 10000, + }; + + let chipperData = helper.encryptText(JSON.stringify(data)); + let decrypData = JSON.parse(helper.decryptText(chipperData)); res.json({ message: 'Welcome to Topup Online Service.', data: { text: '0nlinet0pupkci', chiper_text: helper.encryptText('0nlinet0pupkci'), - hmac: hash, + chipper_data: chipperData, + decrypt_data: decrypData, date: moment().format('YYYYMMDDHHmm'), }, }); @@ -158,7 +164,6 @@ cron.schedule('0 17 * * *', async () => { const { _generateCashIn, } = require('../application/modules/cashin/cahsin.controller'); -const { createHMAC } = require('../application/helpers/HMAC.js'); cron.schedule('30 7 * * *', async () => { try {