OrderNotifyController.java 13 KB

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