OrderService.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. package com.izouma.nineth.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alipay.api.AlipayApiException;
  5. import com.alipay.api.AlipayClient;
  6. import com.alipay.api.request.AlipayTradeWapPayRequest;
  7. import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
  8. import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
  9. import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
  10. import com.github.binarywang.wxpay.constant.WxPayConstants;
  11. import com.github.binarywang.wxpay.exception.WxPayException;
  12. import com.github.binarywang.wxpay.service.WxPayService;
  13. import com.izouma.nineth.config.AlipayProperties;
  14. import com.izouma.nineth.config.WxPayProperties;
  15. import com.izouma.nineth.domain.*;
  16. import com.izouma.nineth.domain.Collection;
  17. import com.izouma.nineth.dto.NFTAccount;
  18. import com.izouma.nineth.dto.PageQuery;
  19. import com.izouma.nineth.enums.CollectionType;
  20. import com.izouma.nineth.enums.OrderStatus;
  21. import com.izouma.nineth.enums.PayMethod;
  22. import com.izouma.nineth.event.CreateAssetEvent;
  23. import com.izouma.nineth.exception.BusinessException;
  24. import com.izouma.nineth.repo.*;
  25. import com.izouma.nineth.utils.JpaUtils;
  26. import com.izouma.nineth.utils.JsonUtils;
  27. import com.izouma.nineth.utils.SecurityUtils;
  28. import com.izouma.nineth.utils.SnowflakeIdWorker;
  29. import lombok.AllArgsConstructor;
  30. import lombok.extern.slf4j.Slf4j;
  31. import org.apache.commons.codec.EncoderException;
  32. import org.apache.commons.codec.net.URLCodec;
  33. import org.apache.commons.collections.MapUtils;
  34. import org.apache.commons.lang3.RandomUtils;
  35. import org.apache.commons.lang3.Range;
  36. import org.apache.http.client.utils.URLEncodedUtils;
  37. import org.springframework.context.event.EventListener;
  38. import org.springframework.core.env.Environment;
  39. import org.springframework.data.domain.Page;
  40. import org.springframework.scheduling.annotation.Scheduled;
  41. import org.springframework.stereotype.Service;
  42. import org.springframework.ui.Model;
  43. import javax.transaction.Transactional;
  44. import java.math.BigDecimal;
  45. import java.time.LocalDateTime;
  46. import java.util.*;
  47. @Service
  48. @AllArgsConstructor
  49. @Slf4j
  50. public class OrderService {
  51. private OrderRepo orderRepo;
  52. private CollectionRepo collectionRepo;
  53. private UserAddressRepo userAddressRepo;
  54. private UserRepo userRepo;
  55. private Environment env;
  56. private AlipayClient alipayClient;
  57. private AlipayProperties alipayProperties;
  58. private WxPayService wxPayService;
  59. private WxPayProperties wxPayProperties;
  60. private AssetService assetService;
  61. private SysConfigService sysConfigService;
  62. private BlindBoxItemRepo blindBoxItemRepo;
  63. public Page<Order> all(PageQuery pageQuery) {
  64. return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
  65. }
  66. @Transactional
  67. public Order create(Long userId, Long collectionId, int qty, Long addressId) {
  68. if (qty <= 0) throw new BusinessException("数量必须大于0");
  69. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  70. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  71. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  72. if (!collection.isOnShelf()) {
  73. throw new BusinessException("藏品已下架");
  74. }
  75. if (qty > collection.getStock()) {
  76. throw new BusinessException("库存不足");
  77. }
  78. UserAddress userAddress = null;
  79. if (addressId != null) {
  80. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  81. }
  82. collection.setStock(collection.getStock() - qty);
  83. collection.setSale(collection.getSale() + qty);
  84. collectionRepo.save(collection);
  85. minter.setSales(minter.getSales() + 1);
  86. BigDecimal gasFee = sysConfigService.getBigDecimal("gas_fee");
  87. Order order = Order.builder()
  88. .userId(userId)
  89. .collectionId(collectionId)
  90. .name(collection.getName())
  91. .pic(collection.getPics())
  92. .detail(collection.getDetail())
  93. .properties(collection.getProperties())
  94. .canResale(collection.isCanResale())
  95. .royalties(collection.getRoyalties())
  96. .serviceCharge(collection.getServiceCharge())
  97. .type(collection.getType())
  98. .minter(minter.getNickname())
  99. .minterAvatar(minter.getAvatar())
  100. .qty(qty)
  101. .price(collection.getPrice())
  102. .gasPrice(gasFee)
  103. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(gasFee))
  104. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  105. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  106. .address(Optional.ofNullable(userAddress).map(u ->
  107. u.getProvinceId() + " " + u.getCityId() + " " + u.getDistrictId() + " " + u.getAddress())
  108. .orElse(null))
  109. .status(OrderStatus.NOT_PAID)
  110. .build();
  111. return orderRepo.save(order);
  112. }
  113. public void payOrderAlipay(Long id, Model model) {
  114. try {
  115. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  116. if (order.getStatus() != OrderStatus.NOT_PAID) {
  117. throw new BusinessException("订单状态错误");
  118. }
  119. JSONObject bizContent = new JSONObject();
  120. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  121. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  122. bizContent.put("out_trade_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
  123. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  124. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  125. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  126. // 测试环境设为1分
  127. bizContent.put("total_amount", "0.01");
  128. }
  129. bizContent.put("subject", order.getName());
  130. bizContent.put("product_code", "QUICK_WAP_PAY");
  131. JSONObject body = new JSONObject();
  132. body.put("action", "payOrder");
  133. body.put("userId", order.getUserId());
  134. body.put("orderId", order.getId());
  135. bizContent.put("body", body.toJSONString());
  136. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  137. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  138. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  139. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  140. String form = alipayClient.pageExecute(alipayRequest).getBody();
  141. model.addAttribute("form", form);
  142. } catch (BusinessException err) {
  143. model.addAttribute("errMsg", err.getError());
  144. } catch (Exception e) {
  145. model.addAttribute("errMsg", e.getMessage());
  146. }
  147. }
  148. public String payOrderWeixinH5(Long id) throws WxPayException, EncoderException {
  149. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  150. if (order.getStatus() != OrderStatus.NOT_PAID) {
  151. throw new BusinessException("订单状态错误");
  152. }
  153. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  154. request.setBody(order.getName());
  155. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  156. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  157. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  158. // 测试环境设为1分
  159. // request.setTotalFee(1);
  160. }
  161. request.setSpbillCreateIp("180.102.110.170");
  162. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  163. request.setTradeType(WxPayConstants.TradeType.MWEB);
  164. request.setSignType("MD5");
  165. JSONObject body = new JSONObject();
  166. body.put("action", "payOrder");
  167. body.put("userId", order.getUserId());
  168. body.put("orderId", order.getId());
  169. request.setAttach(body.toJSONString());
  170. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  171. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  172. }
  173. public Object payOrderWeixin(Long id) throws WxPayException {
  174. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  175. if (order.getStatus() != OrderStatus.NOT_PAID) {
  176. throw new BusinessException("订单状态错误");
  177. }
  178. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  179. request.setBody(order.getName());
  180. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  181. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  182. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  183. // 测试环境设为1分
  184. // request.setTotalFee(1);
  185. }
  186. request.setSpbillCreateIp("180.102.110.170");
  187. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  188. request.setTradeType(WxPayConstants.TradeType.JSAPI);
  189. request.setOpenid(SecurityUtils.getAuthenticatedUser().getOpenId());
  190. request.setSignType("MD5");
  191. JSONObject body = new JSONObject();
  192. body.put("action", "payOrder");
  193. body.put("userId", order.getUserId());
  194. body.put("orderId", order.getId());
  195. request.setAttach(body.toJSONString());
  196. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  197. }
  198. public void notifyAlipay(Long orderId, Map<String, String> params) {
  199. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  200. if (order.getStatus() == OrderStatus.NOT_PAID) {
  201. if (order.getType() == CollectionType.BLIND_BOX) {
  202. List<BlindBoxItem> items = blindBoxItemRepo.findByBlindBoxId(order.getCollectionId());
  203. Map<BlindBoxItem, Range<Integer>> randomRange = new HashMap<>();
  204. int c = 0, sum = 0;
  205. for (BlindBoxItem item : items) {
  206. randomRange.put(item, Range.between(c, c + item.getStock()));
  207. c += item.getStock();
  208. sum += item.getStock();
  209. }
  210. int retry = 0;
  211. BlindBoxItem winItem = null;
  212. while (winItem == null) {
  213. retry++;
  214. int rand = RandomUtils.nextInt(0, sum + 1);
  215. for (Map.Entry<BlindBoxItem, Range<Integer>> entry : randomRange.entrySet()) {
  216. BlindBoxItem item = entry.getKey();
  217. Range<Integer> range = entry.getValue();
  218. if (rand >= range.getMinimum() && rand < range.getMaximum()) {
  219. int total = items.stream().filter(i -> !i.isRare())
  220. .mapToInt(BlindBoxItem::getTotal).sum();
  221. int stock = items.stream().filter(i -> !i.isRare())
  222. .mapToInt(BlindBoxItem::getStock).sum();
  223. if (item.isRare()) {
  224. double nRate = stock / (double) total;
  225. double rRate = (item.getStock() - 1) / (double) item.getTotal();
  226. if (Math.abs(nRate - rRate) < (1 / (double) item.getTotal()) || retry > 1 || rRate == 0) {
  227. if (!(nRate > 0.1 && item.getStock() == 1)) {
  228. winItem = item;
  229. }
  230. }
  231. } else {
  232. double nRate = (stock - 1) / (double) total;
  233. double rRate = item.getStock() / (double) item.getTotal();
  234. if (Math.abs(nRate - rRate) < 0.2 || retry > 1 || nRate == 0) {
  235. winItem = item;
  236. }
  237. }
  238. }
  239. }
  240. if (retry > 100 && winItem == null) {
  241. throw new BusinessException("盲盒抽卡失败");
  242. }
  243. }
  244. winItem.setStock(winItem.getStock() - 1);
  245. winItem.setSale(winItem.getSale() + 1);
  246. order.setStatus(OrderStatus.PROCESSING);
  247. order.setPayTime(LocalDateTime.now());
  248. order.setTransactionId(MapUtils.getString(params, "trade_no"));
  249. order.setPayMethod(PayMethod.ALIPAY);
  250. orderRepo.save(order);
  251. assetService.createAsset(order, winItem);
  252. } else {
  253. order.setStatus(OrderStatus.PROCESSING);
  254. order.setPayTime(LocalDateTime.now());
  255. order.setTransactionId(MapUtils.getString(params, "trade_no"));
  256. order.setPayMethod(PayMethod.ALIPAY);
  257. orderRepo.save(order);
  258. assetService.createAsset(order);
  259. }
  260. } else if (order.getStatus() == OrderStatus.CANCELLED) {
  261. }
  262. }
  263. @EventListener
  264. public void onCreateAsset(CreateAssetEvent event) {
  265. Order order = event.getOrder();
  266. Asset asset = event.getAsset();
  267. if (event.isSuccess()) {
  268. order.setTxHash(asset.getTxHash());
  269. order.setGasUsed(asset.getGasUsed());
  270. order.setBlockNumber(asset.getBlockNumber());
  271. order.setStatus(OrderStatus.FINISH);
  272. orderRepo.save(order);
  273. } else {
  274. log.error("创建asset失败");
  275. }
  276. }
  277. public void cancel(Long id) {
  278. Order order = orderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  279. cancel(order);
  280. }
  281. public void cancel(Order order) {
  282. if (order.getStatus() != OrderStatus.NOT_PAID) {
  283. throw new BusinessException("已支付订单无法取消");
  284. }
  285. Collection collection = collectionRepo.findById(order.getCollectionId())
  286. .orElseThrow(new BusinessException("藏品不存在"));
  287. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  288. collection.setSale(collection.getSale() - 1);
  289. collection.setStock(collection.getStock() + 1);
  290. collectionRepo.save(collection);
  291. minter.setSales(minter.getSales() - 1);
  292. userRepo.save(minter);
  293. order.setStatus(OrderStatus.CANCELLED);
  294. order.setCancelTime(LocalDateTime.now());
  295. orderRepo.save(order);
  296. }
  297. @Scheduled(fixedRate = 60000)
  298. public void batchCancel() {
  299. List<Order> orders = orderRepo.findByStatusAndCreatedAtBeforeAndDelFalse(OrderStatus.NOT_PAID,
  300. LocalDateTime.now().minusMinutes(5));
  301. orders.stream().parallel().forEach(this::cancel);
  302. }
  303. public void refundCancelled(Order order) {
  304. }
  305. }