OrderNotifyController.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package com.izouma.nineth.web;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alipay.api.AlipayApiException;
  5. import com.alipay.api.internal.util.AlipaySignature;
  6. import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
  7. import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
  8. import com.github.binarywang.wxpay.exception.WxPayException;
  9. import com.github.binarywang.wxpay.service.WxPayService;
  10. import com.github.kevinsawicki.http.HttpRequest;
  11. import com.huifu.adapay.core.AdapayCore;
  12. import com.huifu.adapay.core.util.AdapaySign;
  13. import com.izouma.nineth.config.AlipayProperties;
  14. import com.izouma.nineth.config.GeneralProperties;
  15. import com.izouma.nineth.enums.PayMethod;
  16. import com.izouma.nineth.event.OrderNotifyEvent;
  17. import com.izouma.nineth.repo.ErrorOrder;
  18. import com.izouma.nineth.repo.ErrorOrderRepo;
  19. import com.izouma.nineth.service.AssetService;
  20. import com.izouma.nineth.service.GiftOrderService;
  21. import com.izouma.nineth.service.MintOrderService;
  22. import com.izouma.nineth.service.OrderService;
  23. import com.izouma.nineth.utils.SnowflakeIdWorker;
  24. import lombok.AllArgsConstructor;
  25. import lombok.extern.slf4j.Slf4j;
  26. import org.apache.commons.collections.MapUtils;
  27. import org.apache.rocketmq.client.producer.SendResult;
  28. import org.apache.rocketmq.client.producer.SendStatus;
  29. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  30. import org.springframework.stereotype.Controller;
  31. import org.springframework.web.bind.annotation.*;
  32. import javax.servlet.http.HttpServletRequest;
  33. import java.util.HashMap;
  34. import java.util.Map;
  35. import java.util.Set;
  36. import static com.alibaba.fastjson.serializer.SerializerFeature.PrettyFormat;
  37. @Slf4j
  38. @Controller
  39. @RequestMapping("/notify")
  40. @AllArgsConstructor
  41. public class OrderNotifyController {
  42. private final AlipayProperties alipayProperties;
  43. private final OrderService orderService;
  44. private final WxPayService wxPayService;
  45. private final AssetService assetService;
  46. private final GiftOrderService giftOrderService;
  47. private final SnowflakeIdWorker snowflakeIdWorker;
  48. private final RocketMQTemplate rocketMQTemplate;
  49. private final GeneralProperties generalProperties;
  50. private final MintOrderService mintOrderService;
  51. private final ErrorOrderRepo errorOrderRepo;
  52. @PostMapping("/order/alipay")
  53. @ResponseBody
  54. public String notify(HttpServletRequest request) throws AlipayApiException {
  55. Map<String, String> params = new HashMap<>();
  56. Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
  57. for (Map.Entry<String, String[]> entry : entrySet) {
  58. String name = entry.getKey();
  59. String[] values = entry.getValue();
  60. int valLen = values.length;
  61. if (valLen == 1) {
  62. params.put(name, values[0]);
  63. } else if (valLen > 1) {
  64. StringBuilder sb = new StringBuilder();
  65. for (String val : values) {
  66. sb.append(",").append(val);
  67. }
  68. params.put(name, sb.substring(1));
  69. } else {
  70. params.put(name, "");
  71. }
  72. }
  73. log.info("支付宝回调 {}", JSON.toJSONString(params, PrettyFormat));
  74. AlipaySignature.rsaCheckV1(params, alipayProperties.getAliPublicKey(), "UTF-8", "RSA2");
  75. if (MapUtils.getString(params, "trade_status").equals("TRADE_SUCCESS")) {
  76. JSONObject body = JSON.parseObject(params.get("body"));
  77. String action = body.getString("action");
  78. switch (action) {
  79. case "payOrder": {
  80. Long orderId = body.getLong("orderId");
  81. orderService.notifyOrder(orderId, PayMethod.ALIPAY, MapUtils.getString(params, "trade_no"));
  82. break;
  83. }
  84. case "payGiftOrder": {
  85. Long orderId = body.getLong("orderId");
  86. giftOrderService.giftNotify(orderId, PayMethod.ALIPAY, MapUtils.getString(params, "trade_no"));
  87. break;
  88. }
  89. case "payMintOrder": {
  90. Long orderId = body.getLong("orderId");
  91. mintOrderService.mintNotify(orderId, PayMethod.ALIPAY, MapUtils.getString(params, "trade_no"));
  92. break;
  93. }
  94. }
  95. return "success";
  96. }
  97. return "error";
  98. }
  99. @PostMapping(value = "/order/weixin", produces = "application/xml")
  100. @ResponseBody
  101. public String wxNotify(@RequestBody String xmlData) throws WxPayException {
  102. log.info("微信支付回调: {}", xmlData);
  103. final WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
  104. notifyResult.checkResult(wxPayService, "MD5", true);
  105. JSONObject attach = JSONObject.parseObject(notifyResult.getAttach());
  106. String action = attach.getString("action");
  107. switch (action) {
  108. case "payOrder": {
  109. Long orderId = attach.getLong("orderId");
  110. orderService.notifyOrder(orderId, PayMethod.WEIXIN, notifyResult.getTransactionId());
  111. break;
  112. }
  113. case "payGiftOrder": {
  114. Long orderId = attach.getLong("orderId");
  115. giftOrderService.giftNotify(orderId, PayMethod.WEIXIN, notifyResult.getTransactionId());
  116. break;
  117. }
  118. }
  119. return WxPayNotifyResponse.success("OK");
  120. }
  121. @PostMapping(value = "/order/iap")
  122. @ResponseBody
  123. public String iap(@RequestParam String receiptData, @RequestParam Long orderId) {
  124. String data = "{\"receipt-data\":\"" + receiptData + "\"}";
  125. String body = HttpRequest.post("https://buy.itunes.apple.com/verifyReceipt")
  126. .contentType("application/json")
  127. .send(data)
  128. .body();
  129. JSONObject jsonObject = JSON.parseObject(body);
  130. int status = jsonObject.getInteger("status");
  131. if (status == 21007) {
  132. jsonObject = JSON.parseObject(HttpRequest.post("https://sandbox.itunes.apple.com/verifyReceipt")
  133. .contentType("application/json")
  134. .send(data)
  135. .body());
  136. status = jsonObject.getInteger("status");
  137. }
  138. if (status == 0) {
  139. orderService.notifyOrder(orderId, PayMethod.WEIXIN, snowflakeIdWorker.nextId() + "");
  140. }
  141. return "ok";
  142. }
  143. // @PostMapping("/adapay/order/{orderId}")
  144. // @ResponseBody
  145. // public void adapayNotify(@PathVariable Long orderId, HttpServletRequest request) {
  146. // log.info("adapay notify: \n{}", JSON.toJSONString(request.getParameterMap(), PrettyFormat));
  147. // try {
  148. // String data = request.getParameter("data");
  149. // String sign = request.getParameter("sign");
  150. // String type = request.getParameter("type");
  151. // if ("payment.succeeded".equals(type)) {
  152. // boolean checkSign = AdapaySign.verifySign(data, sign, AdapayCore.PUBLIC_KEY);
  153. // log.info("checkSign {}", checkSign);
  154. // if (checkSign) {
  155. // JSONObject jsonObject = JSON.parseObject(data);
  156. // String channel = jsonObject.getString("pay_channel");
  157. // String id = jsonObject.getString("id");
  158. //
  159. // rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
  160. // new OrderNotifyEvent(orderId, channel.startsWith("wx") ? PayMethod.WEIXIN : PayMethod.ALIPAY, id, LocalDateTime.now()));
  161. //
  162. // orderService.notifyOrder(orderId, channel.startsWith("wx") ? PayMethod.WEIXIN : PayMethod.ALIPAY, id);
  163. // }
  164. // }
  165. // } catch (Exception e) {
  166. // e.printStackTrace();
  167. // }
  168. // }
  169. @PostMapping("/adapay/order/{orderId}")
  170. @ResponseBody
  171. public void adapayNotify(@PathVariable Long orderId, HttpServletRequest request) throws Exception {
  172. log.info("adapay notify: \n{}", JSON.toJSONString(request.getParameterMap(), PrettyFormat));
  173. String data = request.getParameter("data");
  174. String sign = request.getParameter("sign");
  175. String type = request.getParameter("type");
  176. if ("payment.succeeded".equals(type)) {
  177. boolean checkSign = AdapaySign.verifySign(data, sign, AdapayCore.PUBLIC_KEY);
  178. log.info("checkSign {}", checkSign);
  179. if (checkSign) {
  180. JSONObject jsonObject = JSON.parseObject(data);
  181. String channel = jsonObject.getString("pay_channel");
  182. String id = jsonObject.getString("id");
  183. PayMethod payMethod = channel.startsWith("wx") ? PayMethod.WEIXIN : PayMethod.ALIPAY;
  184. SendResult result = null;
  185. int count = 0;
  186. do {
  187. if (++count > 10) {
  188. log.error("发送订单通知失败,订单id:{}", orderId);
  189. errorOrderRepo.save(ErrorOrder.builder()
  190. .orderId(orderId)
  191. .transactionId(id)
  192. .payMethod(payMethod)
  193. .errorMessage("发送到回调队列失败")
  194. .build());
  195. break;
  196. }
  197. result = rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
  198. new OrderNotifyEvent(orderId, payMethod, id, System.currentTimeMillis()));
  199. } while (result != null && result.getSendStatus() == SendStatus.SEND_OK);
  200. }
  201. }
  202. }
  203. @PostMapping("/adapay/ordertest/{orderId}")
  204. @ResponseBody
  205. public void adapayNotifyTest(@PathVariable Long orderId, @RequestParam String transactionId) throws Exception {
  206. rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
  207. new OrderNotifyEvent(orderId, PayMethod.ALIPAY, transactionId, System.currentTimeMillis()));
  208. }
  209. @PostMapping("/adapay/giftOrder/{orderId}")
  210. @ResponseBody
  211. public void adapayGiftNotify(@PathVariable Long orderId, HttpServletRequest request) {
  212. log.info("adapay gift notify: \n{}", JSON.toJSONString(request.getParameterMap(), PrettyFormat));
  213. try {
  214. String data = request.getParameter("data");
  215. String sign = request.getParameter("sign");
  216. String type = request.getParameter("type");
  217. if ("payment.succeeded".equals(type)) {
  218. boolean checkSign = AdapaySign.verifySign(data, sign, AdapayCore.PUBLIC_KEY);
  219. log.info("checkSign {}", checkSign);
  220. if (checkSign) {
  221. JSONObject jsonObject = JSON.parseObject(data);
  222. String channel = jsonObject.getString("pay_channel");
  223. String id = jsonObject.getString("id");
  224. giftOrderService.giftNotify(orderId, channel.startsWith("wx") ? PayMethod.WEIXIN : PayMethod.ALIPAY, id);
  225. }
  226. }
  227. } catch (Exception e) {
  228. e.printStackTrace();
  229. }
  230. }
  231. @PostMapping("/adapay/mintOrder/{orderId}")
  232. @ResponseBody
  233. public void adapayMintNotify(@PathVariable Long orderId, HttpServletRequest request) {
  234. log.info("adapay mint notify: \n{}", JSON.toJSONString(request.getParameterMap(), PrettyFormat));
  235. try {
  236. String data = request.getParameter("data");
  237. String sign = request.getParameter("sign");
  238. String type = request.getParameter("type");
  239. if ("payment.succeeded".equals(type)) {
  240. boolean checkSign = AdapaySign.verifySign(data, sign, AdapayCore.PUBLIC_KEY);
  241. log.info("checkSign {}", checkSign);
  242. if (checkSign) {
  243. JSONObject jsonObject = JSON.parseObject(data);
  244. String channel = jsonObject.getString("pay_channel");
  245. String id = jsonObject.getString("id");
  246. mintOrderService.mintNotify(orderId, channel.startsWith("wx") ? PayMethod.WEIXIN : PayMethod.ALIPAY, id);
  247. }
  248. }
  249. } catch (Exception e) {
  250. e.printStackTrace();
  251. }
  252. }
  253. }