lrf 2 лет назад
Родитель
Сommit
c28805fcdc

+ 23 - 0
app/controller/trade/pay.js

@@ -0,0 +1,23 @@
+'use strict';
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+
+//
+class PayController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.service = this.ctx.service.trade.pay;
+    this.body = this.ctx.request.body;
+    this.query = this.ctx.query;
+  }
+
+  async toPayOrder() {
+    const data = await this.service.toPayOrder(this.body);
+    this.ctx.ok({ data });
+  }
+
+  async callBackPayOrder() {
+    await this.service.callBackPayOrder(this.body);
+  }
+}
+module.exports = CrudController(PayController, {});

+ 1 - 1
app/public/routerRegister.js

@@ -11,7 +11,7 @@ const _ = require('lodash');
 module.exports = (app, routes, keyZh, rkey, ckey) => {
   const { router, config } = app;
   const mwares = app.middleware;
-  // if (process.env.NODE_ENV === 'development') console.log(`${keyZh}:  ${rkey}`);
+  if (process.env.NODE_ENV === 'development') console.log(`${keyZh}:  ${rkey}`);
   for (const route of routes) {
     const { method, path, controller: ctl, zh } = route;
     let { middleware = [] } = route;

+ 1 - 0
app/router.js

@@ -14,4 +14,5 @@ module.exports = app => {
 
   require('./z_router/view/index')(app); // 视图部分
   require('./z_router/util')(app); // 工具接口
+  require('./z_router/trade/pay')(app); // 支付接口
 };

+ 2 - 2
app/service/trade/order.js

@@ -83,11 +83,12 @@ class OrderService extends CrudService {
       orderData.status = '0';
       // 生成数据
       // const order = await this.model.create(orderData);
-      this.tran.insert('Order', orderData);
+      const order_id = this.tran.insert('Order', orderData);
       // 处理库存问题
       // 处理库存,删除购物车
       await this.dealGoodsNum(goodsData);
       await this.tran.run();
+      return order_id;
     } catch (error) {
       await this.tran.rollback();
       console.error(error);
@@ -170,7 +171,6 @@ class OrderService extends CrudService {
         i.goods.reduce((p, n) => p + (n.freight || 0) * (n.num || 0), 0),
         2
       );
-      console.log(i);
     }
     return list;
   }

+ 15 - 1
app/service/trade/orderDetail.js

@@ -4,11 +4,25 @@ const { BusinessError, ErrorCode } = require('naf-core').Error;
 const _ = require('lodash');
 const assert = require('assert');
 
-// 
+//
 class OrderDetailService extends CrudService {
   constructor(ctx) {
     super(ctx, 'orderdetail');
     this.model = this.ctx.model.Trade.OrderDetail;
+    this.orderModel = this.ctx.model.Trade.Order;
+  }
+
+  /**
+   * 创建用户支付完成后的订单
+   * @param {Object} body 请求参数体
+   * @param body.order_id 下单的id
+   */
+  async create({ order_id }) {
+    const order = await this.orderModel.findById(order_id);
+    if (!order) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到支付订单的数据');
+    const { customer, address, goods, no, status, buy_time } = order;
+    if (status === '0') throw new BusinessError(ErrorCode.DATA_INVALID, '订单未支付');
+    const orderDetailData = { customer, address, order: order_id };
   }
 }
 

+ 66 - 8
app/service/pay.js

@@ -24,30 +24,42 @@ class PayService extends CrudService {
    * @param body.order_id 订单id
    * @param body.type 支付方式
    */
-  async toPayOrder({ order_id, type }) {
+  async toPayOrder({ order_id, type = '0' }) {
     const payWay = await this.dictDataModel.findOne({ value: type, status: '0' });
     if (!payWay) throw new BusinessError(ErrorCode.DATA_INVALID, '该支付方式暂时无法使用');
     const order = await this.orderModel.findById(order_id);
     if (!order) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单数据');
     const { no, pay } = order;
     // 检查是否有支付信息如果有的话,支付方式是否一致
-    if (Object.keys(pay).length > 0) {
+    if (_.isObject(pay) && Object.keys(pay).length > 0) {
       const pay_type = _.get(pay, 'pay_type');
-      // 支付方式不同,则将支付内容刷掉,重新进行数据生成
+      // 支付方式不同,则将支付内容刷掉,重新进行数据生成 => 关闭之前的订单
       if (pay_type === type) {
         // 支付方式相同,则再找有没有支付订单
         const pay_no = _.get(pay, 'pay_no');
         if (pay_no) {
           // 有支付订单.则先查支付订单是否可以继续支付
           // TODO:
-          // 1.当前用户和之前下单支付的用户的openid是不是一个人.是一个人=>2;不是一个人=>3
+          // 1.当前用户和之前下单支付的用户的openid是不是一个人.是一个人=>3;不是一个人=>2
           // 2.需要关闭之前的支付订单并且重新进行支付: 关闭订单.再放到下面
           // 3.查询订单是否过期 没过期=>4; 过期=>5
           // 4.继续支付:取出数据,return;
           // 5.放到下面.重新支付
+          const openid = _.get(this.ctx, 'user.openid');
+          const pay_openid = _.get(pay, 'openid');
+          if (pay_openid === openid) {
+            // 检查订单是否可以支付
+            const canPay = await this.search(pay.pay_no);
+            console.log(canPay);
+            // if (canPay) {
+            //   // 继续支付
+            //   return;
+            // }
+            await this.closeOrder(pay);
+          } else await this.closeOrder(pay);
         }
         // 没有的话,就说明数据有问题.按照没有支付信息处理即可
-      }
+      } else await this.closeOrder(pay);
     }
     // 没有支付信息(要是有支付信息,上面直接return了.漏下来的都是没有的处理方案)
     const str = this.ctx.service.util.trade.createNonceStr();
@@ -55,6 +67,9 @@ class PayService extends CrudService {
     // 订单中pay的信息
     const payObject = { pay_type: type, pay_no: `${_.last(arr)}-${str}` };
     const totalMoney = this.getOrderNeedPay(order);
+    payObject.pay_money = totalMoney;
+    let payData;
+    let res;
     // 找到当前用户的openid:这里涉及问题是: 如果自己下单,自己付款.那没有问题;
     // 如果是自己下单.如果使用账号密码登录再付款.还用下单的人找到的openid就不能在这个微信号上进行支付了;
     // 所以此处是需要用当前用户的openid进行支付,如果之前生成单子.还需要检查当前用户的openid和之前的openid是否一致
@@ -62,8 +77,11 @@ class PayService extends CrudService {
 
     // 请求微信支付接口的数据
     if (type === '0') {
-      const toPayData = { config: this.appConfig, money: totalMoney, openid: '', order_no: payObject.pay_no, desc: '购物', notice_url: this.payOrderReturnUrl('order_id') };
+      payData = this.getWxPayData(order_id, totalMoney, payObject.pay_no);
+      res = await this.create(payData);
+      res = this.preparToUniAppWxPay(res);
     }
+    return res;
   }
 
   /**
@@ -71,8 +89,48 @@ class PayService extends CrudService {
    * @param {Object} param 请求地址参数
    * @param param.order 订单id
    */
-  async callBackPayOrder({ order }) {}
+  async callBackPayOrder({ order }) {
+    console.log(order);
+  }
 
+  /**
+   * 关闭订单
+   * @param {Object} pay 支付信息
+   */
+  async closeOrder(pay) {
+    const { pay_type } = pay;
+    if (pay_type === '0') {
+      // 微信支付方式
+    }
+  }
+  /**
+   * 微信支付:整理出uniapp需要的数据
+   * @param {Object} data 微信接口的数据
+   */
+  preparToUniAppWxPay(data) {
+    const obj = {
+      // appid: _.get(data, 'appid'),
+      // prepayid: _.get(data, 'prepay_id'),
+      nonceStr: _.get(data, 'nonceStr'),
+      package: `prepay_id=${_.get(data, 'prepay_id')}`,
+      signType: _.get(data, 'signType'),
+      timeStamp: _.get(data, 'timestamp'),
+      paySign: _.get(data, 'paySign'),
+    };
+    return obj;
+  }
+
+  /**
+   * 组织微信支付数据
+   * @param {String} order_id 订单号
+   * @param {Number} money 支付金额
+   * @param {String} no 支付订单号
+   */
+  getWxPayData(order_id, money, no) {
+    const openid = _.get(this.ctx, 'user.openid');
+    const data = { config: this.appConfig, money, openid, order_no: no, desc: '购物', notice_url: this.payOrderReturnUrl(order_id) };
+    return data;
+  }
 
   /**
    * 计算订单需支付的金额
@@ -82,7 +140,7 @@ class PayService extends CrudService {
     let total = 0;
     const { total_detail = {} } = order;
     for (const key in total_detail) {
-      total = _.floor(total_detail[key] + total);
+      total = _.floor(total_detail[key] + total, 2);
     }
     return total;
   }

+ 0 - 1
app/service/util/token.js

@@ -72,7 +72,6 @@ class TokenService extends CrudService {
       await this.redis.del(`token:${oid}`);
       // 该token用完了,换下一个
       const newToken = await this.initToken(uid);
-      console.log(newToken);
       return { token: newToken, check: true, fresh: true };
     }
     // token使用次数-1

+ 1 - 1
app/service/util/trade.js

@@ -66,7 +66,7 @@ class TradeService extends CrudService {
     if (shopRes.result !== true) return goodsRes;
     // 3.检验该规格是否可以购买
     const goodsSpecData = await this.goodsSpecModel.findById(goodsSpec);
-    const gsRes = this.checkGoodsSpec(goodsSpecData);
+    const gsRes = this.checkGoodsSpec(goodsSpecData, num);
     if (gsRes.result !== true) return gsRes;
     if (makeCache) {
       const key = await this.makeOrderKey({ shop, goods, goodsSpec, num });

+ 16 - 0
app/z_router/trade/pay.js

@@ -0,0 +1,16 @@
+'use strict';
+// 路由配置
+const path = require('path');
+const regPath = path.resolve('app', 'public', 'routerRegister');
+const routerRegister = require(regPath);
+const rkey = 'pay';
+const ckey = 'trade.pay';
+const keyZh = '支付接口';
+const routes = [
+  { method: 'post', path: `${rkey}/order/:id`, controller: `${ckey}.callBackPayOrder`, zh: `${keyZh}-支付回调函数` },
+  { method: 'post', path: `${rkey}/toPayOrder`, controller: `${ckey}.toPayOrder`, zh: `${keyZh}-去支付订单` },
+];
+
+module.exports = app => {
+  routerRegister(app, routes, keyZh, rkey, ckey);
+};

+ 2 - 2
config/config.default.js

@@ -70,8 +70,8 @@ module.exports = appInfo => {
 
   // http请求前缀
   config.httpPrefix = {
-    // wechat: 'http://127.0.0.1:14001/wechat/api',
-    wechat: 'https://broadcast.waityou24.cn/wechat/api',
+    wechat: 'http://127.0.0.1:14001/wechat/api',
+    // wechat: 'https://broadcast.waityou24.cn/wechat/api',
   };
   // 中间件
   config.requestLog = {