payOrder.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 moment = require('moment');
  7. //
  8. class PayOrderService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'payorder');
  11. this.model = this.ctx.model.Business.PayOrder;
  12. this.payService = this.ctx.service.wxpay;
  13. this.lessonStudentModel = this.ctx.model.Business.LessonStudent;
  14. this.tempLessonApplyModel = this.ctx.model.Apply.TempLessonApply;
  15. this.userModel = this.ctx.model.User.User;
  16. this.studentModel = this.ctx.model.User.Student;
  17. this.coachModel = this.ctx.model.User.Coach;
  18. }
  19. async beforeCreate(data) {
  20. if (!_.get(data, 'order_no')) data.order_no = this.getOrderNo();
  21. return data;
  22. }
  23. async afterCreate(body, data) {
  24. await this.syncData(data);
  25. const wxSign = await this.payService.create(data);
  26. return { data, wxSign };
  27. }
  28. async afterUpdate(filter, body, data) {
  29. await this.syncData(data);
  30. return data;
  31. }
  32. /**
  33. * 支付同步
  34. * @param {Object} data 支付单数据
  35. */
  36. async syncData(data) {
  37. const pay_for = _.get(data, 'pay_for');
  38. if (!pay_for) {
  39. // 不知道该去同步哪个表的支付状态,不处理
  40. return;
  41. }
  42. const { from_id: _id, status: is_pay } = data;
  43. if (pay_for === 'lessonStudent') {
  44. // 因为上课产生的支付,去找lessonStudent,修改指定学生的支付状态
  45. console.log(is_pay, _id);
  46. const r = await this.lessonStudentModel.updateOne({ _id }, { is_pay });
  47. console.log(r);
  48. } else if (pay_for === 'tempLessonApply') {
  49. // 私教课临时上课,需要到临时申请那找到相关数据,再修改lessonStudent
  50. const tempApply = await this.tempLessonApplyModel.findById(_id);
  51. if (!tempApply) return;
  52. const { lesson_id, student_id } = tempApply;
  53. await this.lessonStudentModel.updateOne({ lesson_id, student_id }, { is_pay });
  54. }
  55. }
  56. /**
  57. * 重新支付
  58. * @param {String} body 参数体
  59. * @property {String} id 数据id
  60. */
  61. async toRePay({ id }) {
  62. const data = await this.model.findById(id);
  63. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到支付的信息');
  64. // 找到这个订单,然后获取到订单号
  65. const { order_no } = data;
  66. // 利用订单号去查询微信那边,该订单是否还存在
  67. const wxOrder = await this.payService.search(order_no);
  68. let wxSign;
  69. if (_.get(wxOrder, 'trade_state') === 'NOTPAY') {
  70. // 未支付就用原数据,去支付
  71. wxSign = await this.payService.create(data);
  72. } else if (_.get(wxOrder, 'trade_state') === 'SUCCESS') {
  73. throw new BusinessError(ErrorCode.SERVICE_FAULT, '订单已支付,无需重复支付');
  74. } else if (_.get(wxOrder, 'trade_state') === 'USERPAYING') {
  75. throw new BusinessError(ErrorCode.SERVICE_FAULT, '订单支付中');
  76. } else {
  77. // 其他情况就当订单被关闭了.直接新订单
  78. const order_no = this.getOrderNo();
  79. data.order_no = order_no;
  80. await data.save();
  81. wxSign = await this.payService.create(data);
  82. }
  83. return { data, wxSign };
  84. }
  85. /**
  86. * 申请退款
  87. * @param {Object} body 参数体
  88. * @property {String} id 支付单的数据id
  89. */
  90. async toRefund({ id }) {
  91. // 查询支付
  92. const data = await this.model.findById(id);
  93. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到要退款的支付数据');
  94. const wxOrderReq = await this.payService.search(data.order_no);
  95. if (wxOrderReq) {
  96. if (!wxOrderReq) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未查询到微信支付订单');
  97. const wxRefundReq = await this.payService.refund(data.order_no, '退赛');
  98. if (wxRefundReq) {
  99. if (wxRefundReq.status !== 'REFUND') throw new BusinessError(ErrorCode.SERVICE_FAULT, '退款失败');
  100. // 退款成功
  101. data.status = '-3';
  102. await data.save();
  103. await this.syncData(data);
  104. return 'ok';
  105. }
  106. }
  107. throw new BusinessError(ErrorCode.SERVICE_FAULT, '查询微信支付订单失败');
  108. }
  109. /**
  110. * 关闭订单
  111. * @param {String} id 支付id
  112. * @return {Object} 关闭订单结果
  113. */
  114. async closeOrder(id) {
  115. const data = await this.model.findById(id);
  116. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到要退款的支付数据');
  117. const res = await this.payService.close(data.order_no);
  118. return res;
  119. }
  120. getOrderNo() {
  121. return `ONCAPP${moment().format('YYYYMMDDHHmmss')}-${_.random(1, 999999)}`;
  122. }
  123. // 二维码扫码
  124. async toPayNative(body) {
  125. body = await this.beforeCreate(body);
  126. const data = await this.model.create(body);
  127. const qrcode = await this.payService.createNative({ ...body });
  128. return qrcode;
  129. }
  130. // 二维码扫码回调
  131. async nativeReturn(body) {
  132. const result = _.get(body, 'result');
  133. console.log(result);
  134. if (!result) throw new BusinessError(ErrorCode.BADPARAM, '参数错误');
  135. const { out_trade_no: order_no, trade_state, payer } = body;
  136. const obj = {};
  137. if (trade_state === 'SUCCESS') obj.status = '1';
  138. else if (trade_state === 'REFUND') obj.status = '-3';
  139. const openid = _.get(payer, 'openid');
  140. if (openid) {
  141. obj.openid = openid;
  142. // 找payer_id的信息,学员,教练
  143. const user = await this.userModel.findOne({ openid });
  144. if (user) {
  145. const { _id: user_id } = user;
  146. let roleUser = await this.studentModel.findOne({ user_id });
  147. if (!roleUser) {
  148. roleUser = await this.coachModel.findOne({ user_id });
  149. if (roleUser) {
  150. obj.payer_role = 'Coach';
  151. obj.payer_id = roleUser._id;
  152. }
  153. } else {
  154. obj.payer_role = 'Student';
  155. obj.payer_id = roleUser._id;
  156. }
  157. }
  158. }
  159. console.log(order_no);
  160. console.log(obj);
  161. await this.model.updateOne({ order_no }, obj);
  162. }
  163. }
  164. module.exports = PayOrderService;