OrderNotifyController.java 12 KB

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