- Require nodejs package, and init express framework
var express = require('express');
var app = express();
var ejs = require('ejs');
var path = require('path');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var url = require('url');
- Require config, util, database
var Config = require('./global/config.js');
var Util = require('./global/util.js');
var Mongo = require('./global/db.js');
- Require controllers and init
var Comman = require('./controller/comman.js');
var Guest = require('./controller/guest.js').init(Config.KEY, Config.SECRET);
var Order = require('./controller/order.js');
var Payment = require('./controller/payment.js').init(Config.REQUESTURL);
var Notifi = require('./controller/notification.js').init(Config.NOTIFICATIONURL);
- Init and open Mongodb
Mongo.init();
Mongo.open().then(function(db){
...
}
- Set file engine and static path, config session to cache customer data
app.set('views', __dirname + '/');
app.engine('.html', ejs.__express);
app.use(express.static(path.join(__dirname, '/views/')));
app.set('view engine', 'html');
app.use(cookieParser());
app.use(session({
resave: true, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
secret: 'love'
}));
- Config server port and listen
app.set('port', Config.PORT );
app.listen(app.get('port'), function(){
console.log('listen port' + app.get('port'));
})
- Set router
app.get('/', attachDB, guestCome, function(req, res, next){
res.render('/views/index')
})
Now we have all our settings in one place and they are easily manageable.
- Customer open app in unochat
(a). Run attachDB -- Set req.db so that use in controller
var attachDB = function(req, res, next){
req.db = db;
next();
};
(b). Run guestCome -- sava and cache customer
if(!req.headers.referer){
next();
return;
}
var url_parts = url.parse(req.headers.referer, true); // get auth
var query = url_parts.query; //
if(req.session.guest){
next();
}else{
console.log(" add query");
Guest.add(req, query.auth).then(function(data){ // decode and sava auth
req.session.guest = data; // cache user data in session to pretvent multiple access
next();
}, function(){
console.error("add guest error");
next();
})
}
(c). Guest controller -- decode auth
var guest = Util.uno_decrypt(auth, this.KEY+':'+this.SECRET);
in util.js decode auth and return JSON
uno_decrypt : function (data, key) {
...
return this.string2json(str)
}
(d). Guest controller -- save auth
model.insert("guests", guest).then(function(items){
deferred.resolve(guest);
})
- Customer select bond and buy it.
(a). set router, and get data from http post
app.post('/trading/pay', attachDB, guestCome, reqParams, function(req, res, next){
var body = Util.string2json(req.body)
var uid = Number(req.session.guest.id) // user unochat id
var no = "Z"+new Date().getTime(); // set order number
var amount = body.amount; // buy bond amount
var time = Util.getNow(); // buy time
var remark = body.remark; // remark
var code = body.code; // user dynamic code
var account = req.session.guest.kingmic_account
if(body.key){
req.ukey = body.key;
req.usecret = body.secret;
}
...
})
(b). Call payment api
payment controller should extend base controller
module.exports = BaseController.extend({
...
})
pay method
unoPaySubmit : function(key, secret, unochatUid, unochatAccount, dynamicCode, orderNo, amount, orderTime, remark){
var deferred = Q.defer();
var params = {
unochat_uid : unochatUid,
unochat_account : unochatAccount,
dynamic_code : dynamicCode,
order_no : orderNo,
amount : amount,
order_time : orderTime,
remark : remark
};
var url = this.URL.PaySubmit;
// set http request header
// Special attention set HTTP Authorization Header
var req = this.createPayRequest(url, params, key, secret);
// console.log(req);
request(req, function(err, response, body){
var bd = Util.string2json(body);
// success return
// {code : 200, message : "success" }
// failed return
// {code : 101, message : fail reason }
/**
* return mixed Status Description
* 101 Authorization Failed
* 102 order number cannot be empty
* 103 Invalid Amount
* 104 failed to create order
* 105 Invalid Unochat ID
* 106 merchant balance is insufficient
* 107-invalid authentication code format
* 108-exceeded number of attempts, account suspended for 10 mins
* 109 Invalid Authentication Code
* 110 Unable to Deduct Amount
*/
if(response.statusCode == 200 && 200 == bd.code){
deferred.resolve(body);
}else{
deferred.reject(body);
}
});
return deferred.promise;
},
- Call payment API response
Payment.unoPaySubmit(...).then(function(data){
// call api success
// will save order into mongodb
Order.add(req, {
pay_unochat_uid : uid,
accept_unochat_uid : body.id,
accept_unochat_name : body.name,
order_no : no,
amount : amount,
order_time : time,
remark : remark,
type : 'pay'
}).then(function(result){
//save sueecss and response json data
console.log('add order in mongodb success');
res.send(result)
}, function(err){
res.send(err);
})
}, function(err){
res.send(err);
});