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