pay.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const Transaction = require('mongoose-transactions');
  7. const moment = require('moment');
  8. //
  9. class PayService extends CrudService {
  10. constructor(ctx) {
  11. super(ctx, 'pay');
  12. this.httpUtil = this.ctx.service.util.httpUtil;
  13. this.appConfig = this.app.config.wxPayConfig;
  14. this.goodsModel = this.ctx.model.Shop.Goods;
  15. this.orderModel = this.ctx.model.Trade.Order;
  16. this.dictDataModel = this.ctx.model.Dev.DictData;
  17. this.payOrderReturnUrl = this.app.config.payReturn.order;
  18. this.wxDomain = _.get(this.app, 'config.httpPrefix.wechat');
  19. this.tran = new Transaction();
  20. }
  21. /**
  22. * 去支付订单
  23. * 1.有支付方式之分; 微信/支付宝
  24. * 2.根据不同方式去请求
  25. * @param {Object} body 请求体
  26. * @param body.order_id 订单id
  27. * @param body.type 支付方式
  28. */
  29. async toPayOrder({ order_id, type = '0' }) {
  30. const payWay = await this.dictDataModel.findOne({ value: type, status: '0' });
  31. if (!payWay) throw new BusinessError(ErrorCode.DATA_INVALID, '该支付方式暂时无法使用');
  32. const order = await this.orderModel.findById(order_id);
  33. if (!order) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单数据');
  34. const { no, pay, stauts } = order;
  35. let rePayTimes = 0;
  36. if (stauts === '1') throw new BusinessError(ErrorCode.DATA_EXISTED, '订单已支付,无需重复支付');
  37. // 检查是否有支付信息如果有的话,支付方式是否一致
  38. if (_.isObject(pay) && Object.keys(pay).length > 0) {
  39. const pay_no = _.get(pay, 'pay_no');
  40. if (pay_no) {
  41. // 有支付订单.则先查支付订单是否可以继续支付
  42. // 1.如果有支付信息及支付单号,直接关闭.重开
  43. const arr = pay_no.split('-');
  44. // 获取重支付的次数,重支付次数+1
  45. const last = _.last(arr);
  46. rePayTimes = this.ctx.plus(last, 1);
  47. }
  48. await this.closeOrder(pay);
  49. }
  50. // 没有支付信息(要是有支付信息,上面直接return了.漏下来的都是没有的处理方案)
  51. const str = this.ctx.service.util.trade.createNonceStr();
  52. const arr = no.split('-');
  53. // 订单中pay的信息
  54. const payObject = { pay_type: type, pay_no: `${_.last(arr)}-${str}-${rePayTimes}` };
  55. const totalMoney = this.ctx.service.util.order.payOrder_RealPay(order);
  56. payObject.pay_money = totalMoney;
  57. let payData;
  58. let res;
  59. // 找到当前用户的openid:这里涉及问题是: 如果自己下单,自己付款.那没有问题;
  60. // 如果是自己下单.如果使用账号密码登录再付款.还用下单的人找到的openid就不能在这个微信号上进行支付了;
  61. // 所以此处是需要用当前用户的openid进行支付,如果之前生成单子.还需要检查当前用户的openid和之前的openid是否一致
  62. // 如果不一致.则需要将之前的订单关闭,重新生成
  63. // 请求微信支付接口的数据
  64. if (type === '0') {
  65. payData = this.getWxPayData(order_id, totalMoney, payObject.pay_no);
  66. payObject.openid = payData.openid;
  67. }
  68. try {
  69. this.tran.update('Order', order_id, { pay: payObject });
  70. await this.tran.run();
  71. } catch (error) {
  72. await this.tran.rollback();
  73. console.error(error);
  74. }
  75. if (totalMoney <= 0) {
  76. // 小于等于0的支付金额,不需要付款
  77. return { needPay: false };
  78. }
  79. if (type === '0') {
  80. res = await this.create(payData);
  81. res = this.preparToUniAppWxPay(res);
  82. }
  83. return res;
  84. }
  85. async withoutPay({ order_id }) {
  86. try {
  87. const orderData = await this.orderModel.findById(order_id);
  88. this.tran.update('Order', order_id, { status: '1' });
  89. await this.tran.run();
  90. // 拆订单
  91. await this.ctx.service.trade.orderDetail.create({ order_id }, this.tran);
  92. // 加销量
  93. await this.addSell(orderData, this.tran);
  94. await this.tran.run();
  95. } catch (error) {
  96. console.error(error);
  97. await this.tran.rollback();
  98. throw new BusinessError(ErrorCode.SERVICE_FAULT, '支付回调:修改失败');
  99. } finally {
  100. // 清空事务
  101. this.tran.clean();
  102. }
  103. }
  104. /**
  105. * 支付订单回调函数
  106. * @param {Object} body 请求地址参数
  107. * @param body.result 支付回调结果
  108. */
  109. async callBackPayOrder({ result }) {
  110. const { out_trade_no, payer } = result;
  111. // 没有需要报警,没有订单号就出问题了
  112. if (!out_trade_no) {
  113. console.error('没有支付订单号');
  114. return;
  115. }
  116. const openid = _.get(payer, 'openid');
  117. const query = { 'pay.pay_no': new RegExp(`${out_trade_no}`), 'pay.openid': openid };
  118. let orderData = await this.orderModel.findOne(query);
  119. // 没找到订单也是有问题的,需要报警
  120. if (!orderData) {
  121. console.error('没有找到订单');
  122. return;
  123. }
  124. orderData = JSON.parse(JSON.stringify(orderData));
  125. const payData = _.get(orderData, 'pay', {});
  126. let odIds = [];
  127. // 支付结果全都存起来
  128. payData.result = result;
  129. // 支付时间
  130. payData.pay_time = moment().format('YYYY-MM-DD HH:mm:ss');
  131. // 修改状态
  132. try {
  133. this.tran.update('Order', orderData._id, { pay: payData, status: '1' });
  134. await this.tran.run();
  135. // 拆订单
  136. odIds = await this.ctx.service.trade.orderDetail.create({ order_id: orderData._id }, this.tran);
  137. // 加销量
  138. await this.addSell(orderData, this.tran);
  139. await this.tran.run();
  140. // TODO: 将该订单的数据在mq队列中释放掉,不要让信息进入死信队列
  141. } catch (error) {
  142. console.error(error);
  143. await this.tran.rollback();
  144. const reason = '服务处理发生错误,原路退款!';
  145. // 先退款,所有回调发生错误的单子都需要退掉
  146. const str = this.ctx.service.util.trade.createNonceStr();
  147. const obj = {
  148. order_no: _.get(orderData, 'pay.pay_no'),
  149. out_refund_no: `${_.get(orderData, 'pay.pay_no')}-service_error-${str}`,
  150. money: _.get(orderData, 'pay.pay_money'),
  151. reason,
  152. };
  153. await this.refund(obj);
  154. throw new BusinessError(ErrorCode.SERVICE_FAULT, '支付回调:修改失败');
  155. } finally {
  156. // 清空事务
  157. this.tran.clean();
  158. }
  159. // 发送系统消息,让对应的店铺接收消息
  160. const msgData = { source_id: odIds, type: '0' };
  161. await this.ctx.service.shop.shopNotice.remindToSend(msgData);
  162. }
  163. /**
  164. * 加销量
  165. * @param {Object} order 支付订单数据
  166. * @param {Transaction} tran 数据库事务
  167. */
  168. async addSell(order, tran) {
  169. const goods = _.get(order, 'goods', []);
  170. for (const sg of goods) {
  171. const { is_set = '1' } = sg;
  172. if (is_set === '1') {
  173. const sgList = _.get(sg, 'goods', []);
  174. for (const g of sgList) {
  175. const buy_num = _.get(g, 'buy_num', 0);
  176. const goods_id = _.get(goods, '_id');
  177. if (!goods_id) return;
  178. const goodsInfo = await this.goodsModel.findById(goods_id, { sell_num: 1 });
  179. const newSell_num = this.ctx.plus(buy_num, _.get(goodsInfo, 'sell_num'));
  180. tran.update('Goods', goods_id, { sell_num: newSell_num });
  181. }
  182. } else {
  183. const { buy_num } = sg;
  184. const sgList = _.get(sg, 'goods', []);
  185. for (const g of sgList) {
  186. const goods_id = _.get(g, 'goods._id');
  187. const set_num = _.get(g, 'set_num');
  188. const goodsInfo = await this.goodsModel.findById(goods_id, { sell_num: 1 });
  189. const newNum = this.ctx.plus(_.get(goodsInfo, 'sell_num'), this.ctx.multiply(buy_num, set_num));
  190. tran.update('Goods', goods_id, { sell_num: newNum });
  191. }
  192. }
  193. }
  194. }
  195. /**
  196. * 关闭订单
  197. * @param {Object} pay 支付信息
  198. */
  199. async closeOrder(pay) {
  200. const { pay_type, pay_no } = pay;
  201. if (pay_type === '0') {
  202. // 微信支付方式
  203. const params = { config: this.appConfig, order_no: pay_no };
  204. const url = `${this.wxDomain}/pay/closeOrder`;
  205. const res = await this.httpUtil.cpost(url, params);
  206. return res || 'ok';
  207. }
  208. }
  209. /**
  210. * 微信支付:整理出uniapp需要的数据
  211. * @param {Object} data 微信接口的数据
  212. */
  213. preparToUniAppWxPay(data) {
  214. const obj = {
  215. // appid: _.get(data, 'appid'),
  216. // prepayid: _.get(data, 'prepay_id'),
  217. nonceStr: _.get(data, 'nonceStr'),
  218. package: `prepay_id=${_.get(data, 'prepay_id')}`,
  219. signType: _.get(data, 'signType'),
  220. timeStamp: _.get(data, 'timestamp'),
  221. paySign: _.get(data, 'paySign'),
  222. };
  223. return obj;
  224. }
  225. /**
  226. * 组织微信支付数据
  227. * @param {String} order_id 订单号
  228. * @param {Number} money 支付金额
  229. * @param {String} no 支付订单号
  230. */
  231. getWxPayData(order_id, money, no) {
  232. const openid = _.get(this.ctx, 'user.openid');
  233. const data = { config: this.appConfig, money, openid, order_no: no, desc: '购物', notice_url: this.payOrderReturnUrl };
  234. return data;
  235. }
  236. /**
  237. * 查询订单
  238. * @param {String} order_no 订单号
  239. */
  240. async search(order_no) {
  241. assert(order_no, '缺少订单号,无法查询订单信息');
  242. const params = { config: this.appConfig, order_no };
  243. const url = `${this.wxDomain}/pay/searchOrderByOrderNo`;
  244. const wxOrderReq = await this.httpUtil.cpost(url, params);
  245. return wxOrderReq;
  246. }
  247. /**
  248. * 创建订单,获取微信支付签名
  249. * @param {Object} data 数据
  250. */
  251. async create(data) {
  252. const { money, openid, order_no, desc, notice_url } = data;
  253. const wxOrderData = { config: this.appConfig, money, openid, order_no, desc, notice_url };
  254. const url = `${this.wxDomain}/pay/payOrder`;
  255. const res = await this.httpUtil.cpost(url, wxOrderData);
  256. if (res) return res;
  257. throw new BusinessError(ErrorCode.SERVICE_FAULT, '微信下单失败!');
  258. }
  259. /**
  260. * 关闭订单
  261. * @param {String} order_no 订单号
  262. */
  263. async close(order_no) {
  264. assert(order_no, '缺少订单号,无法查询订单信息');
  265. const params = { config: this.appConfig, order_no };
  266. const url = `${this.wxDomain}/pay/closeOrder`;
  267. const res = await this.httpUtil.cpost(url, params);
  268. return res || 'ok';
  269. }
  270. /**
  271. * TODO 退款,金额需要指定.可能是部分退款,也可能是全额退款
  272. * @param {String} order_no 支付订单号
  273. * @param {String} out_refund_no 退款单号
  274. * @param {String} money 退款金额
  275. * @param {String} reason 原因
  276. */
  277. async refund({ order_no, out_refund_no, money, reason }) {
  278. assert(order_no, '缺少订单号,无法查询订单信息');
  279. assert(out_refund_no, '缺少退款单号,无法退款');
  280. const url = `${this.wxDomain}/pay/refundOrder`;
  281. const params = { config: this.appConfig, order_no, out_refund_no, money, reason };
  282. const wxRefundReq = await this.httpUtil.cpost(url, params);
  283. return wxRefundReq || 'ok';
  284. }
  285. }
  286. module.exports = PayService;