OrderController.java 10 KB

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