maibao-bond

  1. 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');
  1. Require config, util, database
var Config = require('./global/config.js');
var Util = require('./global/util.js');
var Mongo = require('./global/db.js');
  1. 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);
  1. Init and open Mongodb
Mongo.init();
Mongo.open().then(function(db){ 
  ...
}
  1. 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'
}));
  1. Config server port and listen
app.set('port', Config.PORT );
app.listen(app.get('port'), function(){
    console.log('listen port' + app.get('port'));
})
  1. 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.

  1. 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);
})
  1. 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;
    },
  1. 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);
        });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末碘耳,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子镣陕,更是在濱河造成了極大的恐慌,老刑警劉巖劫狠,帶你破解...
    沈念sama閱讀 206,126評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡缠借,警方通過(guò)查閱死者的電腦和手機(jī)拆火,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門跳夭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人们镜,你說(shuō)我怎么就攤上這事币叹。” “怎么了模狭?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,445評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵颈抚,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我嚼鹉,道長(zhǎng)邪意,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,185評(píng)論 1 278
  • 正文 為了忘掉前任反砌,我火速辦了婚禮雾鬼,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘宴树。我一直安慰自己策菜,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評(píng)論 5 371
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著又憨,像睡著了一般翠霍。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上蠢莺,一...
    開(kāi)封第一講書(shū)人閱讀 48,970評(píng)論 1 284
  • 那天寒匙,我揣著相機(jī)與錄音,去河邊找鬼躏将。 笑死锄弱,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的祸憋。 我是一名探鬼主播会宪,決...
    沈念sama閱讀 38,276評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼蚯窥!你這毒婦竟也來(lái)了掸鹅?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 36,927評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤拦赠,失蹤者是張志新(化名)和其女友劉穎巍沙,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體荷鼠,經(jīng)...
    沈念sama閱讀 43,400評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡赎瞎,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了颊咬。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 37,997評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡牡辽,死狀恐怖喳篇,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情态辛,我是刑警寧澤麸澜,帶...
    沈念sama閱讀 33,646評(píng)論 4 322
  • 正文 年R本政府宣布,位于F島的核電站奏黑,受9級(jí)特大地震影響炊邦,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜熟史,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評(píng)論 3 307
  • 文/蒙蒙 一馁害、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蹂匹,春花似錦碘菜、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,204評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)仰坦。三九已至,卻和暖如春计雌,著一層夾襖步出監(jiān)牢的瞬間悄晃,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,423評(píng)論 1 260
  • 我被黑心中介騙來(lái)泰國(guó)打工凿滤, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留妈橄,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,423評(píng)論 2 352
  • 正文 我出身青樓鸭巴,卻偏偏與公主長(zhǎng)得像眷细,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子鹃祖,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容