OrderNotifyController.java 13 KB

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