〇、序
前期已经实现了对扫码盒子请求的监听,本章将研究如何将交易明细记录保存至mysql数据库。
一、开发实战
(一)导入mysql模块
使用如下命令为项目添加mysql依赖包
npm i mysql --save
(二)新建mysql数据库
新建交易明细表transactions
2019-04-17_001614.png
(三)编写mysql的操作类
初步的想法是在rules文件内,监听逻辑里面,当识别收款成功就新开一次mysql连接进行数据保存,为了更好节省数据库网络连接开销,将使用mysql数据连接池新开连接,新建lib文件夹并新建连接池类mysql.js:
var mysql=require("mysql");
var pool = mysql.createPool({
host: 'localhost',
user: 'user',
password: 'code',
database: 'eabcpay',
port: 3306
});
var query=function(sql,callback){
pool.getConnection(function(err,conn){
if(err){
callback(err,null,null);
}else{
conn.query(sql,function(qerr,vals,fields){
//释放连接
conn.release();
//事件驱动回调
callback(qerr,vals,fields);
});
}
});
};
module.exports=query;
(二)优化rules
myRuleModule示例
const dateUtil = require("./lib/dateFormat.js");
var query = require("./lib/mysql.js");
module.exports = {
replaceServerResDataAsync: function (req, res, serverResData, callback) {
// console.log(req.url);
// console.log(req.headers.host);
// console.log(req.url.indexOf("/site/CashCollect/DirectCashCollect"));
var flag = false;
var orderNo = "1";
var amount = 0.00;
var cashier = "default";
var createtime = dateUtil.formatTime(new Date());
var unusedamount = 0.00;
var queryStr;
if (req.headers.host == "e.abchina.com" && req.url.indexOf("/site/CashCollect/DirectCashCollect") > -1) {
var resData = serverResData.toString();
resData = JSON.parse(resData);
// 会有支付时候并不是马上支付完毕的情况,当IsWaiting为true时还在支付当中,稍后才会调用/site/BranchMarketOrder/PayQuery查询方支付结果
if (resData.Code == 0 && !resData.Value.IsWaiting) {
flag = true;
orderNo = resData.Value.OrderNo;
amount = 0.01;
cashier = "wang";
createtime = dateUtil.formatTime(new Date());
unusedamount = 100000.00;
}
} else if (req.headers.host == "e.abchina.com" && req.url.indexOf("/site/BranchMarketOrder/PayQuery") > -1) {
var billId;
var resData = serverResData.toString();
resData = JSON.parse(resData);
if (req.url.indexOf("?") > -1) {
var arrUrl = req.url.split("?");
var billIdStr = arrUrl[1];
var billIdSplit = billIdStr.split("=");
billId = billIdSplit[1];
}
var para = arrUrl[1];
console.log(resData.Code);
console.log(resData);
if (resData.Code == 0 && resData.Message == "成功") {
flag = true;
orderNo = billId;
amount = 0.01;
cashier = "wang";
createtime = dateUtil.formatTime(new Date());
unusedamount = 100000.00;
}
}
if (flag) {
queryStr = "INSERT INTO transactions(orderno,amount,cashier,createtime,unusedamount) VALUES ('" + orderNo + "', " + amount + ", '" + cashier + "', '" + createtime + "', " + unusedamount + ");";
console.log(queryStr);
query(queryStr, function (err, vals, fields) {
console.log(vals);
});
}
callback(serverResData);
}
}
四、下一步研究计划
1.对语音播报模块进行研究;
2.对利用订单号查找金额进行实验;
3.优化mysql数据库模块,研发交易记录功能和收银员交班功能。