HonorLee 4 years ago
parent
commit
9dc6382eb1
3 changed files with 143 additions and 92 deletions
  1. 113 87
      system/core.js
  2. 8 1
      system/lib/extra/wechat/handler/wechat.js
  3. 22 4
      system/lib/extra/wechat/wechat.js

+ 113 - 87
system/core.js

@@ -4,9 +4,10 @@
  * @License MIT
  */
 'use strict';
+const EventEmitter = require('events').EventEmitter;
 global.Core  = {};
 global.CACHE = {};
-
+global.System = new EventEmitter();
 //Global Path
 global.Core.Path = {
     System      : ROOTPATH + '/system',
@@ -69,92 +70,115 @@ CoreLibFiles = null;
 
 //Core Setting,just change it if necessary!
 global.Core.Setting = {};
-
-//If Mysql on,load Mysql Extension
-if(Config && Config.Database.Mysql.on){
-    let MysqlPool    = require(Core.Path.ExtraLib + '/mysql-pool.js').instance(Config.Database.Mysql);
-    let testMysqlCon = MysqlPool.getConnection(function(err,connection){
-        if(!err){
-            connection.release();
-            connection.query('SELECT VERSION() as version',function(err,result,fields){
-                if(err){
-                    LOGGER.error('Mysql Connect error,please recheck your config');
-                    LOGGER.error(err);
-                }else{
-                    LOGGER.info('Mysql Connect success');
-                    LOGGER.info('Mysql Version: ' + result[0]['version'] + ' | User: ' + Config.Database.Mysql.user + ' | Database: ' + Config.Database.Mysql.database);
-                    global.MysqlPool = MysqlPool;
-                    global.MysqlDB   = require(Core.Path.Helper + '/mysqldb.js');
-                }
-            });
-        }else{
-            LOGGER.error('Mysql Connect error,please recheck your config');
-            LOGGER.error(err);
-        }
-    });
-
-}
-
-//If Mongodb on,load Mongodb Extension
-if(Config && Config.Database.Mongodb.on && Config.Database.Mongodb.database){
-    let verify = Config.Database.Mongodb.user?Config.Database.Mongodb.user+':'+Config.Database.Mongodb.password+'@':'';
-    let mongoConnect = 'mongodb://' + verify + Config.Database.Mongodb.host+':'+Config.Database.Mongodb.port+'/'+Config.Database.Mongodb.database;
-    require('mongodb').MongoClient.connect(mongoConnect,function(err,db){
-        if(err) {
-            LOGGER.error('MongoDB connect error!',true);
-            LOGGER.error('Server start failed. Log has been saved!');
-            // Logger.out(err);
-            return;
-        }
-        LOGGER.info('Mongodb Connect success');
-        global.MongoDB = {db:db};
-        global.MG = function(collection){
-            if(!collection) return null;
-            return MongoDB.db.collection(Config.Database.Mongodb.prefix+collection);
-        };
-    });
-}
-
-//If Memcache on,load Memcache Extension
-if(Config && Config.Database.Memcache.on){
-    let Memclass  = require('memcached');
-    let Memcache  = new Memclass(Config.Database.Memcache.host+':'+Config.Database.Memcache.port);
-    Memcache.version(function(err,data){
-        if(err){
-            LOGGER.error('Memcache Connect error,please recheck your config');
-            LOGGER.error(err);
-        }else{
-            LOGGER.info('Memcache Connect success');
-            LOGGER.info('Memcache Version: ' + data[0]['version']);
-            global.Memcache = Memcache;
-        }
-    });
-}
-
-//If Redis on,Create Redis Client
-if(Config && Config.Database.Redis.on){
-    let redis = require('redis').createClient({port:Config.Database.Redis.port,host:Config.Database.Redis.host,retry_strategy: function (options) {
-        if (options.error && options.error.code === 'ECONNREFUSED') {
-            LOGGER.error('Redis connect has been refused,please recheck your config,and make sure redis server is running!');
-        }
-        if (options.total_retry_time > 1000 * 10) {
-            LOGGER.error('Redis retry connect time exhausted');
-        }
-        if (options.attempt > 10) {
-            LOGGER.error('Redis unknow error');
-        }
-        // reconnect after
-        return Math.min(options.attempt * 100, 3000);
-    },prefix:Config.Database.Redis.prefix});
-    redis.on('ready',function(e){
-        LOGGER.info('Redis Connect success');
-        LOGGER.info('Redis Version: ' + redis.server_info.redis_version);
-        global.Redis = redis;
-    });
-    redis.on('reconnecting',function(e){
-        LOGGER.warn('Redis lost connect,reconnecting!');
-    });
-}
+ASYNC.series([(callback)=>{
+    //If Mysql on,load Mysql Extension
+    if(Config && Config.Database.Mysql.on){
+        let MysqlPool    = require(Core.Path.ExtraLib + '/mysql-pool.js').instance(Config.Database.Mysql);
+        let testMysqlCon = MysqlPool.getConnection(function(err,connection){
+            if(!err){
+                connection.release();
+                connection.query('SELECT VERSION() as version',function(err,result,fields){
+                    if(err){
+                        LOGGER.error('Mysql Connect error,please recheck your config');
+                        LOGGER.error(err);
+                        callback(err);
+                    }else{
+                        LOGGER.info('Mysql Connect success');
+                        LOGGER.info('Mysql Version: ' + result[0]['version'] + ' | User: ' + Config.Database.Mysql.user + ' | Database: ' + Config.Database.Mysql.database);
+                        global.MysqlPool = MysqlPool;
+                        global.MysqlDB   = require(Core.Path.Helper + '/mysqldb.js');
+                        callback();
+                    }
+                });
+            }else{
+                LOGGER.error('Mysql Connect error,please recheck your config');
+                LOGGER.error(err);
+                callback(err);
+            }
+        });
+    }else{
+        callback();
+    }
+},(callback)=>{
+    //If Mongodb on,load Mongodb Extension
+    if(Config && Config.Database.Mongodb.on && Config.Database.Mongodb.database){
+        let verify = Config.Database.Mongodb.user?Config.Database.Mongodb.user+':'+Config.Database.Mongodb.password+'@':'';
+        let mongoConnect = 'mongodb://' + verify + Config.Database.Mongodb.host+':'+Config.Database.Mongodb.port+'/'+Config.Database.Mongodb.database;
+        require('mongodb').MongoClient.connect(mongoConnect,function(err,db){
+            if(err) {
+                LOGGER.error('MongoDB connect error!',true);
+                LOGGER.error('Server start failed. Log has been saved!');
+                // Logger.out(err);
+                callback(err);
+                return;
+            }
+            LOGGER.info('Mongodb Connect success');
+            global.MongoDB = {db:db};
+            global.MG = function(collection){
+                if(!collection) return null;
+                return MongoDB.db.collection(Config.Database.Mongodb.prefix+collection);
+            };
+            callback();
+        });
+    }else{
+        callback();
+    }
+},(callback)=>{
+    //If Memcache on,load Memcache Extension
+    if(Config && Config.Database.Memcache.on){
+        let Memclass  = require('memcached');
+        let Memcache  = new Memclass(Config.Database.Memcache.host+':'+Config.Database.Memcache.port);
+        Memcache.version(function(err,data){
+            if(err){
+                LOGGER.error('Memcache Connect error,please recheck your config');
+                LOGGER.error(err);
+                callback(err);
+            }else{
+                LOGGER.info('Memcache Connect success');
+                LOGGER.info('Memcache Version: ' + data[0]['version']);
+                global.Memcache = Memcache;
+                callback();
+            }
+        });
+    }else{
+        callback();
+    }
+},(callback)=>{
+    //If Redis on,Create Redis Client
+    if(Config && Config.Database.Redis.on){
+        let redis = require('redis').createClient({port:Config.Database.Redis.port,host:Config.Database.Redis.host,retry_strategy: function (options) {
+            if (options.error && options.error.code === 'ECONNREFUSED') {
+                LOGGER.error('Redis connect has been refused,please recheck your config,and make sure redis server is running!');
+            }
+            if (options.total_retry_time > 1000 * 10) {
+                LOGGER.error('Redis retry connect time exhausted');
+            }
+            if (options.attempt > 10) {
+                LOGGER.error('Redis unknow error');
+            }
+            if(options.error) callback(options.error);
+            // reconnect after
+            return Math.min(options.attempt * 100, 3000);
+        },prefix:Config.Database.Redis.prefix});
+        redis.on('ready',function(e){
+            LOGGER.info('Redis Connect success');
+            LOGGER.info('Redis Version: ' + redis.server_info.redis_version);
+            global.Redis = redis;
+            callback();
+        });
+        redis.on('reconnecting',function(e){
+            LOGGER.warn('Redis lost connect,reconnecting!');
+        });
+    }else{
+        callback();
+    }
+}],(err)=>{
+    if(err){
+        System.emit('error',err);
+    }else{
+        System.emit('ready');
+    }
+});
 
 //Check File Paths
 for(let path in global.Core.Path){
@@ -186,3 +210,5 @@ global.RouterRule = null;
 try{
     global.RouterRule = require(ROOTPATH+'/rule.js');
 }catch(e){}
+
+module.exports = System;

+ 8 - 1
system/lib/extra/wechat/handler/wechat.js

@@ -25,5 +25,12 @@ module.exports = {
             signatureObj.appId = Config.Wechat.appId;
             this.endAPI(0,signatureObj);
         });
+    },
+    getCode2Session:function(){
+        if(!this.GET['code']) return this.endAPI(-1,'JsCode Can Be Empty');
+        Wechat.getCode2Session.call(this,this.GET['code'],function(err,body){
+            if(err) return this.endAPI(-1,'getCode2Session error!');
+            this.endAPI(0,body);
+        });
     }
-}
+}

+ 22 - 4
system/lib/extra/wechat/wechat.js

@@ -14,7 +14,8 @@ const WechatApiURL = {
     getJsApiTicket:`${WechatDomain}/cgi-bin/ticket/getticket?type=jsapi&access_token=`,
     getJsOauthCode:`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${Config.Wechat.appId}`,
     getOauthToken:`${WechatDomain}/sns/oauth2/access_token?appid=${Config.Wechat.appId}&secret=${Config.Wechat.appSecret}&grant_type=authorization_code`,
-    getOauthUserinfo:`${WechatDomain}/sns/userinfo?lang=zh_CN`
+    getOauthUserinfo:`${WechatDomain}/sns/userinfo?lang=zh_CN`,
+    getCode2Session:`${WechatDomain}/sns/jscode2session?appid=${Config.Wechat.appId}&secret=${Config.Wechat.appSecret}&grant_type=authorization_code&js_code=`
 }
 
 let Wechat = {
@@ -154,6 +155,23 @@ let Wechat = {
                 callback.call(_this,null,result);
             });
         });
+    },
+    getCode2Session:function(code,callback){
+        let _this = this;
+        if(!code) return callback.call(this,new Error('jscode is empty'));
+        let url = WechatApiURL.getCode2Session + code;
+        Core.Request({url:url,encoding:'UTF-8',json:true},function(err,response,body){
+            if(err || !body){
+                Logger.error('Wechat getCode2Session error!');
+                Logger.error(err);
+                callback.call(_this,new Error('Wechat getCode2Session error!'),null);
+                return;
+            }
+            if(body.errcode){
+                return callback.call(_this,body.errcode,errMsg[body.errcode]);
+            }
+            callback.call(_this,null,body);
+        });
     }
 }
 
@@ -184,7 +202,7 @@ function getTokenFromCache(callback){
     }else{
         callback(null);
     }
-    
+
 }
 
 function setTokenToCahe(token,expires){
@@ -224,7 +242,7 @@ function getTicketFromCache(callback){
     }else{
         callback(null);
     }
-    
+
 }
 
 function setTicketToCahe(ticket,expires){
@@ -237,4 +255,4 @@ function setTicketToCahe(ticket,expires){
     }
     let expiresTime = Math.floor(Moment().valueOf()/1000) + expires;
     FILE.writeFileSync(tmpTicketFile,JSON.stringify({ticket:ticket,expires:expiresTime}),'UTF-8');
-}
+}