OrderController.java 18 KB

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