OrderController.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. package com.cyksj.web.controller.payment;
  2. import cn.hutool.core.util.StrUtil;
  3. import cn.hutool.extra.qrcode.QrCodeUtil;
  4. import cn.hutool.extra.qrcode.QrConfig;
  5. import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
  6. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  7. import com.cyksj.common.annotation.Log;
  8. import com.cyksj.common.constant.Constant;
  9. import com.cyksj.common.exception.BusinessRuntimeException;
  10. import com.cyksj.common.util.IoKit;
  11. import com.cyksj.common.util.Jsons;
  12. import com.cyksj.common.util.Xmls;
  13. import com.cyksj.config.zfb.BaseZfbConfig;
  14. import com.cyksj.config.zfb.ZfbProductCode;
  15. import com.cyksj.dto.Result;
  16. import com.cyksj.enums.BusinessType;
  17. import com.cyksj.enums.GatewayResponse;
  18. import com.cyksj.mapper.OrderDonMapper;
  19. import com.cyksj.mapper.OrderDonWaybillMapper;
  20. import com.cyksj.mapper.UserMapper;
  21. import com.cyksj.mapper.channel.UserPayEquipmentAvailableBenefitsMapper;
  22. import com.cyksj.mapper.market.task.UserBindPhoneMapper;
  23. import com.cyksj.model.dto.AliPayParams;
  24. import com.cyksj.model.dto.H5JsPayParams;
  25. import com.cyksj.model.entity.*;
  26. import com.cyksj.model.manage.views.OrderDonView;
  27. import com.cyksj.model.request.AlipayOrderDonReq;
  28. import com.cyksj.model.request.OrderPayRequest;
  29. import com.cyksj.model.request.WxOrderRefundReq;
  30. import com.cyksj.model.request.ZfbOrderRefundReq;
  31. import com.cyksj.model.response.AliPayTradeStatus;
  32. import com.cyksj.model.views.GoodsDonSkuView;
  33. import com.cyksj.model.views.OrderCommentView;
  34. import com.cyksj.service.order.OrderDonService;
  35. import com.cyksj.service.sys.SysConfigService;
  36. import com.cyksj.web.util.StpUserUtil;
  37. import com.ejlchina.searcher.BeanSearcher;
  38. import com.ejlchina.searcher.SearchResult;
  39. import com.ejlchina.searcher.param.Operator;
  40. import com.ejlchina.searcher.util.MapUtils;
  41. import lombok.extern.slf4j.Slf4j;
  42. import org.apache.commons.lang3.StringUtils;
  43. import org.springframework.beans.factory.annotation.Autowired;
  44. import org.springframework.validation.annotation.Validated;
  45. import org.springframework.web.bind.annotation.*;
  46. import javax.annotation.Resource;
  47. import javax.servlet.http.HttpServletRequest;
  48. import javax.servlet.http.HttpServletResponse;
  49. import java.io.OutputStream;
  50. import java.util.HashMap;
  51. import java.util.List;
  52. import java.util.Map;
  53. import java.util.Set;
  54. import java.util.stream.Collectors;
  55. /**
  56. * @author chan
  57. * @date 2021/10/11 下午3:50
  58. */
  59. @Slf4j
  60. @RequestMapping("/applets/order")
  61. @RestController
  62. public class OrderController {
  63. @Autowired
  64. private OrderDonService orderDonService;
  65. @Resource
  66. private BeanSearcher beanSearcher;
  67. @Resource
  68. private HttpServletRequest request;
  69. @Autowired
  70. private OrderDonMapper orderDonMapper;
  71. @Autowired
  72. private UserBindPhoneMapper userBindPhoneMapper;
  73. @Autowired
  74. private UserMapper userMapper;
  75. @Autowired
  76. private UserPayEquipmentAvailableBenefitsMapper availableBenefitsMapper;
  77. @Autowired
  78. private OrderDonWaybillMapper waybillMapper;
  79. @Autowired
  80. private SysConfigService sysConfigService;
  81. /**
  82. * 支付
  83. * @author chan
  84. * @date 2021-10-11 下午4:56
  85. */
  86. @PostMapping("/post/submit")
  87. public Result<OrderDon> submit(@Validated @RequestBody OrderPayRequest payRequest) throws Exception {
  88. final String methodName = "吊起微信支付";
  89. if (payRequest.getIsNoLogin() == null || !payRequest.getIsNoLogin()) {
  90. payRequest.setUserId(StpUserUtil.getLoginIdAsLong());
  91. }
  92. log.info("{}[start] params:{}",methodName,payRequest);
  93. OrderDon orderDon = orderDonService.submit(payRequest);
  94. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  95. }
  96. /**
  97. * 支付
  98. * @author chan
  99. * @date 2021-10-11 下午4:56
  100. */
  101. @PostMapping("/post/pay/{orderId}")
  102. public Result<H5JsPayParams> pay(@PathVariable Long orderId) throws Exception {
  103. final String methodName = "吊起微信支付";
  104. log.info("{}[start] orderId:{}",methodName,orderId);
  105. H5JsPayParams payParams = orderDonService.pay(orderId, "JSAPI");
  106. return GatewayResponse.SUCCESS.newBuilder().toResult(payParams);
  107. }
  108. /**
  109. * 调用生成订单之后
  110. * 微信网页预下单获取交易链接生成二维码
  111. */
  112. @PostMapping("/get/wx/orderQrCode/{orderId}")
  113. public Result<String> createUnifiedOrderQr(@PathVariable Long orderId) throws Exception {
  114. //预下单
  115. H5JsPayParams payParams = orderDonService.wxPcWebPay(orderId, "NATIVE");
  116. //获取二维码链接code_url
  117. String codeUrl = payParams.getCodeUrl();
  118. QrConfig qrConfig = new QrConfig(300, 300);
  119. return GatewayResponse.SUCCESS.newBuilder().toResult(QrCodeUtil.generateAsBase64(codeUrl, qrConfig, "png"));
  120. }
  121. /**
  122. * 微信订单退款
  123. */
  124. @PostMapping("/wx/refund")
  125. @Log(module = "订单管理/微信退款", businessType = BusinessType.PUT, isSaveRequestData = true)
  126. public Result<String> wxRefund(@RequestBody @Validated WxOrderRefundReq wxOrderRefundReq) throws Exception {
  127. return orderDonService.wxRefund(wxOrderRefundReq);
  128. }
  129. /**
  130. * 微信退款回调
  131. */
  132. @PostMapping("/wx/refund/notify")
  133. public void wxRefundNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  134. String xml = IoKit.toString(request.getInputStream());
  135. log.info("=== 退款成功的回调: \n {}", xml);
  136. // 解析xml
  137. Map<String, String> map = Xmls.toMap(xml);
  138. // 退款失败
  139. if (!StrUtil.equals("SUCCESS", map.get("return_code"))) {
  140. throw BusinessRuntimeException.getInstance("退款失败.");
  141. }
  142. orderDonService.wxRefundNotify(map);
  143. String toWechatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  144. OutputStream out = null;
  145. try {
  146. out = response.getOutputStream();
  147. IoKit.write(toWechatXmlResponse, out);
  148. } catch (Throwable e) {
  149. throw BusinessRuntimeException.getInstance(e == null ? null : e.getMessage());
  150. } finally {
  151. IoKit.close(out);
  152. }
  153. }
  154. /**
  155. * 微信支付回调
  156. * @author chan
  157. * @date 2021-10-11 下午5:42
  158. */
  159. @PostMapping("/prepay/notify")
  160. public void prepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  161. String xml = IoKit.toString(request.getInputStream());
  162. log.info("=== 基金会分发支付成功的回调: \n {}", xml);
  163. // 解析xml
  164. Map<String, String> map = Xmls.toMap(xml);
  165. // 支付失败
  166. if (!StringUtils.equals("SUCCESS", map.get("return_code")) || !StringUtils.equals("SUCCESS", map.get("result_code"))) {
  167. throw BusinessRuntimeException.getInstance("支付失败.");
  168. }
  169. orderDonService.prepayNotify(map);
  170. String toWeChatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  171. OutputStream out = null;
  172. try {
  173. out = response.getOutputStream();
  174. IoKit.write(toWeChatXmlResponse, out);
  175. } catch (Exception e) {
  176. throw BusinessRuntimeException.getInstance(e,e.getMessage());
  177. } finally {
  178. IoKit.close(out);
  179. }
  180. }
  181. /**
  182. * pc端微信支付回调
  183. * @author chan
  184. * @date 2021-10-11 下午5:42
  185. */
  186. @PostMapping("/pc/prepay/notify")
  187. public void pcPrepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  188. String xml = IoKit.toString(request.getInputStream());
  189. log.info("=== 微信pc端分发支付成功的回调: \n {}", xml);
  190. // 解析xml
  191. Map<String, String> map = Xmls.toMap(xml);
  192. // 支付失败
  193. if (!StringUtils.equals("SUCCESS", map.get("return_code")) || !StringUtils.equals("SUCCESS", map.get("result_code"))) {
  194. throw BusinessRuntimeException.getInstance("支付失败.");
  195. }
  196. orderDonService.prepayNotify(map);
  197. log.info("pc端微信支付回调修改订单状态成功");
  198. String toWeChatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  199. OutputStream out = null;
  200. try {
  201. out = response.getOutputStream();
  202. IoKit.write(toWeChatXmlResponse, out);
  203. } catch (Exception e) {
  204. throw BusinessRuntimeException.getInstance(e,e.getMessage());
  205. } finally {
  206. IoKit.close(out);
  207. }
  208. }
  209. /**
  210. * 支付宝表单支付
  211. * 支付宝调起支付宝表单
  212. */
  213. @PostMapping("/post/pay/zfb")
  214. @Deprecated
  215. public Result<String> aliPay(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  216. Long orderId = re.getOrderId();
  217. String returnUrl = re.getReturnUrl();
  218. AliPayParams aliPayParams = orderDonService.aliPay(orderId, returnUrl, ZfbProductCode.MOBILE_WEB.getProductCode(), null);
  219. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  220. //直接将完整的表单html输出到页面
  221. // response.getWriter().write(aliPayParams.getBody());
  222. // response.getWriter().flush();
  223. // response.getWriter().close();
  224. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  225. }
  226. /**
  227. * 支付宝web支付
  228. * pc网页内嵌二维码
  229. */
  230. @PostMapping("/get/zfb/orderQrCode")
  231. public Result<String> zfbWebQrCode(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  232. Long orderId = re.getOrderId();
  233. String returnUrl = re.getReturnUrl();
  234. AliPayParams aliPayParams = orderDonService.aliPay(orderId, returnUrl, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_orderCode);
  235. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  236. //直接将完整的表单html输出到页面
  237. // response.getWriter().write(aliPayParams.getBody());
  238. // response.getWriter().flush();
  239. // response.getWriter().close();
  240. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  241. }
  242. /**
  243. * 支付宝web支付
  244. * pc网页跳转二维码
  245. */
  246. @PostMapping("/get/zfb/orderRedirect")
  247. public Result<String> zfbWebRedirectQrCode(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  248. Long orderId = re.getOrderId();
  249. String returnUrl = re.getReturnUrl();
  250. AliPayParams aliPayParams = orderDonService.aliPay(orderId, returnUrl, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_redirect);
  251. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  252. }
  253. /**
  254. * 支付宝退款
  255. */
  256. @PostMapping("/zfb/refund")
  257. @Log(module = "订单管理/支付宝退款", businessType = BusinessType.PUT, isSaveRequestData = true)
  258. public Result<String> zfbOrderRefund(@RequestBody @Validated ZfbOrderRefundReq zfbOrderRefundReq) throws Exception {
  259. return orderDonService.zfbRefund(zfbOrderRefundReq);
  260. }
  261. /**
  262. * 支付宝回调
  263. */
  264. @PostMapping("/prepay/zfb/notify")
  265. public String aliPayNotify(HttpServletRequest request) throws Exception {
  266. ////将异步通知中收到的所有参数都存放到map中
  267. Map<String, String> params = convertRequestParamsToMap(request);
  268. String tradeStatus = params.get("trade_status");
  269. String orderNo = params.get("out_trade_no");
  270. if (AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus) || AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  271. log.info("支付宝商家订单号orderNo:{},status:{}开始回调", orderNo, tradeStatus);
  272. orderDonService.aliPayNotify(params);
  273. } else {
  274. log.error("支付宝回调 error 状态不符合 成功或完成 status:{} ,orderNo:{}", tradeStatus, orderNo);
  275. return "fail";
  276. }
  277. return "success";
  278. }
  279. /**
  280. * 支付宝转账
  281. */
  282. // @PostMapping("/zfb/transfer/accounts")
  283. // @NoSubmit
  284. // public Result<String> zfbTransferAccounts(@RequestBody @Validated TransferAccountsReq transferAccountsReq) throws Exception {
  285. // long userId = StpUserUtil.getLoginIdAsLong();
  286. // transferAccountsReq.setUserId(userId);
  287. // orderDonService.transferAccounts(transferAccountsReq);
  288. // return GatewayResponse.SUCCESS.newBuilder().toResult("转账成功");
  289. // }
  290. /**
  291. * 查询支付宝转账状态
  292. */
  293. @GetMapping("/zfb/transfer/status")
  294. public Result<String> getTransFerStatusByTid(String translationId) throws Exception {
  295. AlipayFundTransCommonQueryResponse response = orderDonService.getTransFerStatusByTid(translationId);
  296. if (response.isSuccess()) {
  297. if (!Constant.SUCCESS.equals(response.getStatus())) {
  298. return GatewayResponse.SUCCESS.newBuilder().toResult(response.getFailReason());
  299. }
  300. return GatewayResponse.SUCCESS.newBuilder().toResult("该红包已转账成功");
  301. }
  302. return GatewayResponse.SUCCESS.newBuilder().toResult(response.getSubMsg());
  303. }
  304. /**
  305. * 获取订单列表
  306. */
  307. @GetMapping("/get")
  308. public Result<SearchResult<OrderDonView>> list(){
  309. long userId = StpUserUtil.getLoginIdAsLong();
  310. SearchResult<OrderDonView> search = beanSearcher.search(OrderDonView.class, MapUtils.flatBuilder(request.getParameterMap())
  311. .field(OrderDonView::getUserId,userId)
  312. .orderBy(OrderDonView::getId).desc()
  313. .build());
  314. search.getDataList().forEach(data->{
  315. Integer count = availableBenefitsMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentAvailableBenefits.class)
  316. .eq(UserPayEquipmentAvailableBenefits::getRealOrderId, data.getId())
  317. .eq(UserPayEquipmentAvailableBenefits::getDeleted, true));
  318. data.setIsHasBenefits(count > 0 ? true : false);
  319. if (data.getIsBenefits()) {
  320. String benefitsList = data.getBenefitsList();
  321. if (StrUtil.isNotBlank(benefitsList)) {
  322. try {
  323. List<Long> skuIds = Jsons.parseList(benefitsList, GoodsDonSku.class).stream().map(GoodsDonSku::getId).collect(Collectors.toList());
  324. data.setBenefitsViews(beanSearcher.searchAll(GoodsDonSkuView.class, MapUtils.builder().field(GoodsDonSkuView::getSkuId, skuIds).op(Operator.InList).build()));
  325. } catch (Exception e) {
  326. }
  327. }
  328. }
  329. data.setWaybill(waybillMapper.selectOne(Wrappers.lambdaQuery(OrderDonWaybill.class).eq(OrderDonWaybill::getOrderId, data.getId()).last("limit 1")));
  330. });
  331. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  332. }
  333. /**
  334. * 获取订单详情
  335. */
  336. @GetMapping("/get/{orderId}")
  337. public Result<OrderDonView> detail(@PathVariable Long orderId, Boolean isNoLogin) {
  338. Long userId = null;
  339. if (isNoLogin == null || !isNoLogin) {
  340. userId = StpUserUtil.getLoginIdAsLong();
  341. }
  342. OrderDonView detail = orderDonService.getDetail(orderId, userId);
  343. return GatewayResponse.SUCCESS.newBuilder().toResult(detail);
  344. }
  345. /**
  346. * 取消订单
  347. */
  348. @GetMapping("/get/close/{orderId}")
  349. public Result<String> closeOrder(@PathVariable Long orderId){
  350. orderDonService.closeOrder(orderId);
  351. return GatewayResponse.SUCCESS.newBuilder().toResult();
  352. }
  353. @GetMapping("/get/order/status/{orderId}")
  354. public Result<OrderDonView> getOrderStatusById(@PathVariable Long orderId) {
  355. if (orderId < 1) {
  356. throw BusinessRuntimeException.getInstance("订单不存在");
  357. }
  358. OrderDonView orderDonView = orderDonMapper.getOrderDetail(orderId);
  359. if (orderDonView == null) {
  360. throw BusinessRuntimeException.getInstance("订单不存在");
  361. }
  362. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonView);
  363. }
  364. @PostMapping("/get/noLogin/order")
  365. public Result<List<OrderDonView>> getSearchResult(@RequestBody List<Long> orderIds) {
  366. List<OrderDonView> orderDonViews = beanSearcher.searchAll(OrderDonView.class, MapUtils.builder()
  367. .field(OrderDonView::getId, orderIds).op(Operator.InList)
  368. .orderBy(OrderDonView::getId).desc().build());
  369. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonViews);
  370. }
  371. /**
  372. * 平台评论列表
  373. */
  374. @GetMapping("/get/orderComment")
  375. public Result<SearchResult<OrderCommentView>> getOrderCommentView() {
  376. SearchResult<OrderCommentView> search = beanSearcher.search(OrderCommentView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
  377. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  378. }
  379. /**
  380. * 是否绑定了邮箱或手机号
  381. */
  382. @GetMapping("/isBind")
  383. public Result<Boolean> isBindPhoneOrEmail() {
  384. Long userId = StpUserUtil.getLoginIdAsLong();
  385. User user = userMapper.selectById(userId);
  386. if (StrUtil.isEmpty(user.getOpenId())) {
  387. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  388. }
  389. UserBindPhone userBindPhone = userBindPhoneMapper.selectOne(Wrappers.lambdaQuery(UserBindPhone.class)
  390. .eq(UserBindPhone::getUserId, userId));
  391. if (userBindPhone == null) {
  392. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  393. }
  394. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  395. }
  396. /**
  397. * 获取支付宝回调参数
  398. */
  399. private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
  400. Map<String, String> retMap = new HashMap<>();
  401. Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
  402. for (Map.Entry<String, String[]> entry : entrySet) {
  403. String name = entry.getKey();
  404. String[] values = entry.getValue();
  405. int valLen = values.length;
  406. if (valLen == 1) {
  407. retMap.put(name, values[0]);
  408. } else if (valLen > 1) {
  409. StringBuilder sb = new StringBuilder();
  410. for (String val : values) {
  411. sb.append(",").append(val);
  412. }
  413. retMap.put(name, sb.substring(1));
  414. } else {
  415. retMap.put(name, "");
  416. }
  417. }
  418. return retMap;
  419. }
  420. }