Browse Source

Add wechat code2session

HonorLee 4 years ago
parent
commit
7061456dcd
2 changed files with 30 additions and 5 deletions
  1. 8 1
      system/lib/extra/wechat/handler/wechat.js
  2. 22 4
      system/lib/extra/wechat/wechat.js

+ 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');
-}
+}