asd123a20 3 年之前
父節點
當前提交
1dc78116c1

+ 1 - 1
app/controller/order.js

@@ -10,7 +10,7 @@ class ItemsController extends Controller {
     this.service = this.ctx.service.order;
   }
   async updatestatus() {
-    const { out_trade_no } = this.ctx.query;
+    const { out_trade_no } = this.ctx.request.body;
     const res = await this.service.updatestatus({ out_trade_no });
     this.ctx.ok(res);
   }

+ 21 - 26
app/controller/weixin.js

@@ -2,6 +2,7 @@
 
 const Controller = require('egg').Controller;
 const uuid = require('uuid');
+const jwt = require('jsonwebtoken');
 class LoginController extends Controller {
   constructor(ctx) {
     super(ctx);
@@ -9,12 +10,6 @@ class LoginController extends Controller {
     this.model = this.ctx.model.Admin;
   }
 
-  // GET 通过微信号获得用户信息
-  async fetch() {
-    const { openid } = this.ctx.requestparam;
-    const res = await this.service.fetchByWeixin(openid);
-    this.ctx.ok({ userinfo: res });
-  }
   // 获取openid
   async auth() {
     try {
@@ -27,13 +22,13 @@ class LoginController extends Controller {
       }
       // TODO: 生成回调地址
       const { wxapi, authUrl = this.ctx.path } = this.app.config;
-      // windos环境
-      // const host = this.ctx.header.referer.split('/')[2];
-      // linux环境
-      const host = this.ctx.header.host;
-      const backUrl = encodeURI(`${this.ctx.protocol}://${host}${authUrl}`);
-      const to_uri = `${wxapi.baseUrl}/api/auth?appid=${wxapi.appid}&response_type=code&redirect_uri=${backUrl}#wechat`;
-      this.ctx.redirect(to_uri);
+      const referer = this.ctx.header.referer;
+      if (referer) {
+        const host = referer.split('/')[2];
+        const backUrl = encodeURI(`${this.ctx.protocol}://${host}${authUrl}`);
+        const to_uri = `${wxapi.baseUrl}/api/auth?appid=${wxapi.appid}&response_type=code&redirect_uri=${backUrl}#wechat`;
+        this.ctx.redirect(to_uri);
+      }
     } catch (error) {
       console.log(error);
     }
@@ -44,28 +39,24 @@ class LoginController extends Controller {
     const val = await this.app.redis.get('redirect_uri');
     const res = await weixin.fetch(code);
     const openid = res.openid;
+    const { secret, expiresIn = '1h' } = this.config.jwt;
+    const subject = openid;
+    const token = await jwt.sign({ openid }, secret, { expiresIn, issuer: 'user', subject });
     // TODO: 重定性到跳转页面
-    await this.ctx.render('redirect.njk', { openid, redirect_uri: val });
+    await this.ctx.render('redirect.njk', { openid, redirect_uri: val, token });
   }
 
   // POST 绑定用户微信号
   async bind() {
     try {
-      const { userName, code } = this.ctx.query;
-      if (userName) {
-        const userinfo = await this.model.findOne({ userName });
-        await this.app.redis.set('key', userinfo._id, 'EX', 600);
-      }
+      const { code } = this.ctx.query;
       if (code) {
         return await this.Back({ code });
       }
 
       // TODO: 生成回调地址
       const { wxapi, authUrl = this.ctx.path } = this.app.config;
-      // windos环境
-      // const host = this.ctx.header.referer.split('/')[2];
-      // linux环境
-      const host = this.ctx.header.host;
+      const host = this.ctx.header['x-forwarded-host'];
       const backUrl = encodeURI(`${this.ctx.protocol}://${host}${authUrl}`);
       const to_uri = `${wxapi.baseUrl}/api/auth?appid=${wxapi.appid}&response_type=code&redirect_uri=${backUrl}#wechat`;
 
@@ -86,10 +77,13 @@ class LoginController extends Controller {
   // mp
   async mqtt() {
     const key = this.ctx.params.key;
+    let msg = 'success';
+    if (key === 'bind') msg = JSON.stringify({ openid: this.ctx.query.openid });
+    if (key === 'pay') msg = JSON.stringify(this.ctx.query);
     // TODO: 发布扫码成功消息
     const { mq } = this.ctx;
     if (mq) {
-      await mq.topic('qrcode.topic', key, 'success', { durable: true });
+      await mq.topic('qrcode.topic', key, msg, { durable: true });
     } else {
       this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
     }
@@ -142,14 +136,15 @@ class LoginController extends Controller {
   }
   // 关闭订单
   async orderClose() {
-    const { out_trade_no } = this.ctx.query;
+    const { out_trade_no } = this.ctx.request.body;
     const res = await this.ctx.service.weixin.orderClose({ out_trade_no });
     this.ctx.ok(res);
   }
   // 消息模板下发
   async pushMould() {
-    const { out_trade_no, openid } = this.ctx.query;
+    const { out_trade_no, openid } = this.ctx.request.body;
     await this.ctx.service.weixin.pushMould({ out_trade_no, openid });
+    this.ctx.ok('ok');
   }
 }
 

+ 9 - 10
app/router.js

@@ -6,22 +6,21 @@
 module.exports = app => {
   const { router, controller } = app;
 
-  // 开放接口
+  // 开放接口 (get请求为开放接口)
   router.post('/api/power/login', controller.login.adminlogin); // 管理员帐号密码登录
-  router.get('/api/qrcodeToken', controller.weixin.qrcodeToken); // 获取公众号token
+  router.get('/api/qrcodeToken', controller.weixin.qrcodeToken); // uuid 换 token
   router.get('/api/getuuid', controller.weixin.getuuid); // 获取uuid
   router.get('/api/qrcodelogin/:uuid', controller.weixin.qrcodelogin); // 二维码登录
   router.get('/api/check', controller.weixin.check); // 查询二维码状态
+  router.get('/api/weixin/getopenid', controller.weixin.auth); // 获取openid token
   router.get('/api/mqtt/:key', controller.weixin.mqtt); // 发送mq消息
-  // 支付相关
+
+  // 以下接口不开放
   router.post('/api/weixin/orderPay', controller.weixin.orderPay); // 预支付交易单
   router.get('/api/weixin/pay', controller.weixin.pay); // 发起支付接口
-  router.get('/api/weixin/orderClose', controller.weixin.orderClose); // 关闭订单
-  router.get('/api/weixin/pushMould', controller.weixin.pushMould); // 模板下发
-  // 微信登录相关接口
-  router.get('/api/weixin/getopenid', controller.weixin.auth); // 获取openid
+  router.post('/api/weixin/orderClose', controller.weixin.orderClose); // 关闭订单
+  router.post('/api/weixin/pushMould', controller.weixin.pushMould); // 模板下发
   router.get('/api/weixin/bind', controller.weixin.bind); // 管理员绑定微信
-  router.get('/api/weixin/fetch', controller.weixin.fetch);
 
   // 日志接口
   // router.post('/api/log/create', controller.log.create);
@@ -79,12 +78,12 @@ module.exports = app => {
   router.get('/api/specialist/fetch/:_id', controller.specialist.fetch);
 
   // 订单接口
-  router.post('/api/order/create', controller.order.create); // 开放
+  router.post('/api/order/create', controller.order.create);
   router.post('/api/order/update', controller.order.update);
   router.delete('/api/order/delete/:_id', controller.order.delete);
   router.get('/api/order/query', controller.order.query);
   router.get('/api/order/fetch/:_id', controller.order.fetch);
-  router.get('/api/order/updatestatus', controller.order.updatestatus);
+  router.post('/api/order/updatestatus', controller.order.updatestatus); // 修改订单状态
 
   // TODO: 自动配置路由,将所有以‘Action’结尾的方法自动进行路由注册
   Object.keys(app.controller).forEach(key => {

+ 2 - 1
app/service/login.js

@@ -59,7 +59,8 @@ class JwtLoginService extends NafService {
     }
     // TODO: 生成回调地址
     const { wxapi, authUrl = this.ctx.path } = this.app.config;
-    const backUrl = encodeURI(`${this.ctx.protocol}://${this.ctx.host}${authUrl}`);
+    const host = this.ctx.header['x-forwarded-host'];
+    const backUrl = encodeURI(`${this.ctx.protocol}://${host}${authUrl}`);
     const to_uri = `${wxapi.baseUrl}/api/auth?appid=${wxapi.appid}&response_type=code&redirect_uri=${backUrl}#wechat`;
     this.ctx.redirect(to_uri);
   }

+ 4 - 2
app/service/weixin.js

@@ -31,6 +31,7 @@ class WeixinAuthService extends AxiosService {
   }
   // 下发模板消息
   async pushMould({ openid, out_trade_no }) {
+    console.log();
     await this.userMould({ openid, out_trade_no });
     await this.adminMould({ out_trade_no });
   }
@@ -150,7 +151,7 @@ class WeixinAuthService extends AxiosService {
       serial_no: wxapi.certid,
       apiv3_private_key: wxapi.v3key,
     });
-    const host = this.ctx.header.host;
+    const host = this.ctx.header.referer.split('/')[2];
     const backUrl = encodeURI(`${this.ctx.protocol}://${host}${authUrl}`);
     // jsapi 支付下单
     const result = await paymnet.jsapi({
@@ -196,7 +197,8 @@ class WeixinAuthService extends AxiosService {
     const data = `${appid}\n${payTimestamp}\n${payNonceStr}\nprepay_id=${prepay_id}\n`;
     const createSign = payment.rsaSign(data, privateKey);
     const pay_uri = this.ctx.header.referer;
-    const redirect_uri = `${this.ctx.protocol}://${this.ctx.header.host}/yl-web/reserve`;
+    const host = this.ctx.header.referer.split('/')[2];
+    const redirect_uri = `${this.ctx.protocol}://${host}/yl-web/reserve`;
     // TODO: 重定向到支付页面
     await this.ctx.render('pay.njk', { openid, appid, prepay_id, payNonceStr, payTimestamp, createSign, redirect_uri, out_trade_no, pay_uri });
   }

+ 15 - 3
app/view/pay.njk

@@ -74,10 +74,22 @@
       function(res) {
           if (res.err_msg == "get_brand_wcpay_request:ok") {
             showsuccess();
-            $.get('/api/weixin/pushMould', { out_trade_no, openid }) 
-            $.get('/api/order/updatestatus', { out_trade_no })
+            $.ajax({
+              type: 'POST',
+              url: '/api/weixin/pushMould',
+              data: { out_trade_no, openid }
+            })
+            $.ajax({
+              type: 'POST',
+              url: '/api/order/updatestatus',
+              data: { out_trade_no }
+            })
           } else {
-            $.get('/api/weixin/orderClose', { out_trade_no })
+            $.ajax({
+              type: 'POST',
+              url: '/api/weixin/orderClose',
+              data: { out_trade_no }
+            })
             .then(function(res) {
               if (res.status == 204) {
                 window.location.replace(redirect_uri);

+ 2 - 0
app/view/redirect.njk

@@ -19,8 +19,10 @@
   <script>
     var openid = '{{openid | safe}}';
     var redirect_uri = '{{redirect_uri}}';
+    var token = '{{token}}';
     window.onload = function() {
       sessionStorage.setItem('openid', openid);
+      sessionStorage.setItem('token', token);
       window.location.replace(redirect_uri);
     }
   </script>

+ 15 - 20
app/view/weixinbind.njk

@@ -21,9 +21,9 @@
 		</div>
 		<div class="weui-msg__text-area" v-if="view == 'success'">
 			<h2 class="weui-msg__title">
-				微信绑定成功
+				扫码确认成功
 			</h2>
-			<p class="weui-msg__desc">您已成功通过微信扫码绑定。</p>
+			<p class="weui-msg__desc">您已成功通过微信扫码确认。</p>
 		</div>
 		<div class="weui-msg__text-area" v-if="view == 'login'">
 			<h2 class="weui-msg__title">
@@ -33,14 +33,13 @@
 		<div class="weui-msg__opr-area" v-if="view == 'login'">
 			<p class="weui-btn-area">
 				<a href="javascript:;" class="weui-btn weui-btn_primary" v-bind:class="{ 'weui-btn_disabled': loading }"
-					v-on:click="login">${ loading ? '正在绑定...' : '确定' }</a> 
+					v-on:click="login">${ loading ? '正在确认...' : '确定' }</a> 
 				<a href="javascript:;" class="weui-btn weui-btn_default" v-show="!loading" v-on:click="close">取消</a>
 			</p>
 		</div>
 	</div>
 	<script type="text/javascript" th:inline="javascript">
     const openid = '{{ openid | safe }}'
-    const id = '{{ id | safe }}'
 		var app = new Vue({
 			delimiters: ['${', '}'],
 			el : '#app',
@@ -52,24 +51,20 @@
 				login : function() {
 					if(this.loading) return;
 					this.loading = true;
-					$.post('/api/admin/update', { _id: id, openid: openid })
-					.then(function(result) {
-						if (result.errcode == 0) {
-							$.get('/api/mqtt/bind').then(function(res) {
-								if (res.errcode == 0) {
-                  					app.view = 'success';
-								} else {
-								  return $.Deferred().reject(res.errmsg);
-								}
-							})
-						} else {
-							return $.Deferred().reject(result.errmsg); 
-						}
+          $.ajax({
+            type: 'GET',
+            url: '/api/mqtt/bind',
+            data: { openid }
+          })
+          .then(function(res) {
+            if (res.errcode == 0) {
+              app.view = 'success';
+            } else {
+              return $.Deferred().reject(res.errmsg);
+            }
 					}).fail(function( jqXHR, textStatus, errorThrown ) {
 						var msg = "处理失败,请稍后重试!";
-						if(typeof jqXHR == "string") msg = jqXHR;
-						showAlert(msg, '绑定失败');
-						app.message = msg;
+						return $.Deferred().reject(msg);
 					}).always(function(){
 						app.loading = false;
 					});

+ 6 - 7
config/config.default.js

@@ -18,6 +18,12 @@ module.exports = appInfo => {
       enable: false,
     },
   };
+  // server config
+  config.cluster = {
+    listen: {
+      port: 9001,
+    },
+  };
   config.wxapi = {
     // 微信公众号APPID
     appid: 'wx3ce04cdc39e157c7',
@@ -53,13 +59,6 @@ module.exports = appInfo => {
 
   config.onerror = ErrorConfig;
 
-  // server config
-  config.cluster = {
-    listen: {
-      port: 8001,
-    },
-  };
-
   // mongoose config
   config.mongoose = {
     url: 'mongodb://127.0.0.1:27018/jzyl',

+ 0 - 1
config/config.local.js

@@ -17,7 +17,6 @@ module.exports = () => {
       hostname: '192.168.0.45',
     },
   };
-
   // redis config
   // config.redis = {
   //   client: {

+ 0 - 1
config/config.prod.js

@@ -2,7 +2,6 @@
 
 module.exports = () => {
   const config = exports = {};
-
   // mq config
   config.amqp = {
     client: {