OrderController.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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.cyksj.common.EnvCommonService;
  6. import com.cyksj.common.exception.BusinessRuntimeException;
  7. import com.cyksj.common.util.IoKit;
  8. import com.cyksj.common.util.Xmls;
  9. import com.cyksj.config.zfb.ZfbProductCode;
  10. import com.cyksj.dto.Result;
  11. import com.cyksj.enums.GatewayResponse;
  12. import com.cyksj.mapper.OrderDonMapper;
  13. import com.cyksj.model.dto.AliPayParams;
  14. import com.cyksj.model.dto.H5JsPayParams;
  15. import com.cyksj.model.entity.OrderDon;
  16. import com.cyksj.model.manage.views.OrderDonView;
  17. import com.cyksj.model.request.OrderPayRequest;
  18. import com.cyksj.model.request.WxOrderRefundReq;
  19. import com.cyksj.model.request.ZfbOrderRefundReq;
  20. import com.cyksj.model.response.AliPayTradeStatus;
  21. import com.cyksj.service.order.OrderDonService;
  22. import com.cyksj.web.util.StpUserUtil;
  23. import com.ejlchina.searcher.BeanSearcher;
  24. import com.ejlchina.searcher.SearchResult;
  25. import com.ejlchina.searcher.param.Operator;
  26. import com.ejlchina.searcher.util.MapUtils;
  27. import lombok.extern.slf4j.Slf4j;
  28. import org.apache.commons.lang3.StringUtils;
  29. import org.springframework.beans.factory.annotation.Autowired;
  30. import org.springframework.validation.annotation.Validated;
  31. import org.springframework.web.bind.annotation.*;
  32. import javax.annotation.Resource;
  33. import javax.servlet.http.HttpServletRequest;
  34. import javax.servlet.http.HttpServletResponse;
  35. import java.io.OutputStream;
  36. import java.util.HashMap;
  37. import java.util.List;
  38. import java.util.Map;
  39. import java.util.Set;
  40. /**
  41. * @author chan
  42. * @date 2021/10/11 下午3:50
  43. */
  44. @Slf4j
  45. @RequestMapping("/applets/order")
  46. @RestController
  47. public class OrderController {
  48. @Autowired
  49. private OrderDonService orderDonService;
  50. @Resource
  51. private BeanSearcher beanSearcher;
  52. @Resource
  53. private HttpServletRequest request;
  54. @Autowired
  55. private EnvCommonService envCommonService;
  56. @Autowired
  57. private OrderDonMapper orderDonMapper;
  58. /**
  59. * 支付
  60. * @author chan
  61. * @date 2021-10-11 下午4:56
  62. */
  63. @PostMapping("/post/submit")
  64. public Result<OrderDon> submit(@Validated @RequestBody OrderPayRequest payRequest) throws Exception {
  65. final String methodName = "吊起微信支付";
  66. if (payRequest.getIsNoLogin() == null || !payRequest.getIsNoLogin()) {
  67. payRequest.setUserId(StpUserUtil.getLoginIdAsLong());
  68. }
  69. log.info("{}[start] params:{}",methodName,payRequest);
  70. OrderDon orderDon = orderDonService.submit(payRequest);
  71. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  72. }
  73. /**
  74. * 支付
  75. * @author chan
  76. * @date 2021-10-11 下午4:56
  77. */
  78. @PostMapping("/post/pay/{orderId}")
  79. public Result<H5JsPayParams> pay(@PathVariable Long orderId) throws Exception {
  80. final String methodName = "吊起微信支付";
  81. log.info("{}[start] orderId:{}",methodName,orderId);
  82. H5JsPayParams payParams = orderDonService.pay(orderId, "JSAPI");
  83. return GatewayResponse.SUCCESS.newBuilder().toResult(payParams);
  84. }
  85. /**
  86. * 调用生成订单之后
  87. * 微信网页预下单获取交易链接生成二维码
  88. */
  89. @PostMapping("/get/wx/orderQrCode/{orderId}")
  90. public Result<String> createUnifiedOrderQr(@PathVariable Long orderId) throws Exception {
  91. //预下单
  92. H5JsPayParams payParams = orderDonService.wxPcWebPay(orderId, "NATIVE");
  93. //获取二维码链接code_url
  94. String codeUrl = payParams.getCodeUrl();
  95. QrConfig qrConfig = new QrConfig(300, 300);
  96. return GatewayResponse.SUCCESS.newBuilder().toResult(QrCodeUtil.generateAsBase64(codeUrl, qrConfig, "png"));
  97. }
  98. /**
  99. * 微信订单退款
  100. */
  101. @PostMapping("/wx/refund")
  102. private Result<String> wxRefund(@RequestBody @Validated WxOrderRefundReq wxOrderRefundReq) throws Exception {
  103. return orderDonService.wxRefund(wxOrderRefundReq);
  104. }
  105. /**
  106. * 微信退款回调
  107. */
  108. @PostMapping("/wx/refund/notify")
  109. public void wxRefundNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  110. String xml = IoKit.toString(request.getInputStream());
  111. log.info("=== 退款成功的回调: \n {}", xml);
  112. // 解析xml
  113. Map<String, String> map = Xmls.toMap(xml);
  114. // 退款失败
  115. if (!StrUtil.equals("SUCCESS", map.get("return_code"))) {
  116. throw BusinessRuntimeException.getInstance("退款失败.");
  117. }
  118. orderDonService.wxRefundNotify(map);
  119. String toWechatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  120. OutputStream out = null;
  121. try {
  122. out = response.getOutputStream();
  123. IoKit.write(toWechatXmlResponse, out);
  124. } catch (Throwable e) {
  125. throw BusinessRuntimeException.getInstance(e == null ? null : e.getMessage());
  126. } finally {
  127. IoKit.close(out);
  128. }
  129. }
  130. /**
  131. * 微信支付回调
  132. * @author chan
  133. * @date 2021-10-11 下午5:42
  134. */
  135. @PostMapping("/prepay/notify")
  136. public void prepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  137. String xml = IoKit.toString(request.getInputStream());
  138. log.info("=== 基金会分发支付成功的回调: \n {}", xml);
  139. // 解析xml
  140. Map<String, String> map = Xmls.toMap(xml);
  141. // 支付失败
  142. if (!StringUtils.equals("SUCCESS", map.get("return_code")) || !StringUtils.equals("SUCCESS", map.get("result_code"))) {
  143. throw BusinessRuntimeException.getInstance("支付失败.");
  144. }
  145. orderDonService.prepayNotify(map);
  146. String toWeChatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  147. OutputStream out = null;
  148. try {
  149. out = response.getOutputStream();
  150. IoKit.write(toWeChatXmlResponse, out);
  151. } catch (Exception e) {
  152. throw BusinessRuntimeException.getInstance(e,e.getMessage());
  153. } finally {
  154. IoKit.close(out);
  155. }
  156. }
  157. /**
  158. * pc端微信支付回调
  159. * @author chan
  160. * @date 2021-10-11 下午5:42
  161. */
  162. @PostMapping("/pc/prepay/notify")
  163. public void pcPrepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  164. String xml = IoKit.toString(request.getInputStream());
  165. log.info("=== 微信pc端分发支付成功的回调: \n {}", xml);
  166. // 解析xml
  167. Map<String, String> map = Xmls.toMap(xml);
  168. // 支付失败
  169. if (!StringUtils.equals("SUCCESS", map.get("return_code")) || !StringUtils.equals("SUCCESS", map.get("result_code"))) {
  170. throw BusinessRuntimeException.getInstance("支付失败.");
  171. }
  172. orderDonService.prepayNotify(map);
  173. log.info("pc端微信支付回调修改订单状态成功");
  174. String toWeChatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  175. OutputStream out = null;
  176. try {
  177. out = response.getOutputStream();
  178. IoKit.write(toWeChatXmlResponse, out);
  179. } catch (Exception e) {
  180. throw BusinessRuntimeException.getInstance(e,e.getMessage());
  181. } finally {
  182. IoKit.close(out);
  183. }
  184. }
  185. /**
  186. * 支付宝表单支付
  187. * 支付宝调起支付宝表单
  188. */
  189. @PostMapping("/post/pay/zfb/{orderId}")
  190. @Deprecated
  191. public Result<String> aliPay(@PathVariable Long orderId,HttpServletResponse response) throws Exception {
  192. AliPayParams aliPayParams = orderDonService.aliPay(orderId, ZfbProductCode.MOBILE_WEB.getProductCode());
  193. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  194. //直接将完整的表单html输出到页面
  195. // response.getWriter().write(aliPayParams.getBody());
  196. // response.getWriter().flush();
  197. // response.getWriter().close();
  198. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  199. }
  200. /**
  201. * 支付宝web支付
  202. * pc网页二维码
  203. */
  204. @PostMapping("/get/zfb/orderQrCode/{orderId}")
  205. public Result<String> zfbWebQrCode(@PathVariable Long orderId, HttpServletResponse response) throws Exception {
  206. AliPayParams aliPayParams = orderDonService.aliPay(orderId, ZfbProductCode.PC_WEB.getProductCode());
  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. * 支付宝退款
  216. */
  217. @PostMapping("/zfb/refund")
  218. public Result<String> zfbOrderRefund(@RequestBody @Validated ZfbOrderRefundReq zfbOrderRefundReq) throws Exception {
  219. return orderDonService.zfbRefund(zfbOrderRefundReq);
  220. }
  221. /**
  222. * 支付宝回调
  223. */
  224. @PostMapping("/prepay/zfb/notify")
  225. public String aliPayNotify(HttpServletRequest request) throws Exception {
  226. ////将异步通知中收到的所有参数都存放到map中
  227. Map<String, String> params = convertRequestParamsToMap(request);
  228. String tradeStatus = params.get("trade_status");
  229. if (AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus) || AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  230. orderDonService.aliPayNotify(params);
  231. } else {
  232. log.error("支付宝回调 error 状态不符合 成功或完成 status:{} ,orderNo:{}", tradeStatus, params.get("out_trade_no"));
  233. return "fail";
  234. }
  235. return "success";
  236. }
  237. /**
  238. * 获取订单列表
  239. */
  240. @GetMapping("/get")
  241. public Result<SearchResult<OrderDonView>> list(){
  242. long userId = StpUserUtil.getLoginIdAsLong();
  243. SearchResult<OrderDonView> search = beanSearcher.search(OrderDonView.class, MapUtils.flatBuilder(request.getParameterMap())
  244. .field(OrderDonView::getUserId,userId)
  245. .orderBy(OrderDonView::getId).desc()
  246. .build());
  247. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  248. }
  249. /**
  250. * 获取订单列表
  251. */
  252. @GetMapping("/get/{orderId}")
  253. public Result<OrderDonView> list(@PathVariable Long orderId, Boolean isNoLogin) {
  254. Long userId = null;
  255. if (isNoLogin == null || !isNoLogin) {
  256. userId = StpUserUtil.getLoginIdAsLong();
  257. }
  258. OrderDonView detail = orderDonService.getDetail(orderId, userId);
  259. return GatewayResponse.SUCCESS.newBuilder().toResult(detail);
  260. }
  261. /**
  262. * 取消订单
  263. */
  264. @GetMapping("/get/close/{orderId}")
  265. public Result<String> closeOrder(@PathVariable Long orderId){
  266. orderDonService.closeOrder(orderId);
  267. return GatewayResponse.SUCCESS.newBuilder().toResult();
  268. }
  269. @GetMapping("/get/order/status/{orderId}")
  270. public Result<OrderDonView> getOrderStatusById(@PathVariable Long orderId) {
  271. if (orderId < 1) {
  272. throw BusinessRuntimeException.getInstance("订单不存在");
  273. }
  274. OrderDonView orderDonView = orderDonMapper.getOrderDetail(orderId);
  275. if (orderDonView == null) {
  276. throw BusinessRuntimeException.getInstance("订单不存在");
  277. }
  278. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonView);
  279. }
  280. @PostMapping("/get/noLogin/order")
  281. public Result<List<OrderDonView>> getSearchResult(@RequestBody List<Long> orderIds) {
  282. List<OrderDonView> orderDonViews = beanSearcher.searchAll(OrderDonView.class, MapUtils.builder()
  283. .field(OrderDonView::getId, orderIds).op(Operator.InList)
  284. .orderBy(OrderDonView::getId).desc().build());
  285. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonViews);
  286. }
  287. /**
  288. * 获取支付宝回调参数
  289. */
  290. private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
  291. Map<String, String> retMap = new HashMap<>();
  292. Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
  293. for (Map.Entry<String, String[]> entry : entrySet) {
  294. String name = entry.getKey();
  295. String[] values = entry.getValue();
  296. int valLen = values.length;
  297. if (valLen == 1) {
  298. retMap.put(name, values[0]);
  299. } else if (valLen > 1) {
  300. StringBuilder sb = new StringBuilder();
  301. for (String val : values) {
  302. sb.append(",").append(val);
  303. }
  304. retMap.put(name, sb.substring(1));
  305. } else {
  306. retMap.put(name, "");
  307. }
  308. }
  309. return retMap;
  310. }
  311. }