OrderService.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. if (!collection.isCanResale()) {
  79. throw new BusinessException("该藏品当前不可购买");
  80. }
  81. if (collection.getType() == CollectionType.BLIND_BOX) {
  82. if (collection.getStartTime().isAfter(LocalDateTime.now())) {
  83. throw new BusinessException("盲盒未开售");
  84. }
  85. }
  86. UserAddress userAddress = null;
  87. if (addressId != null) {
  88. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  89. }
  90. collection.setStock(collection.getStock() - qty);
  91. collection.setSale(collection.getSale() + qty);
  92. collectionRepo.save(collection);
  93. minter.setSales(minter.getSales() + 1);
  94. BigDecimal gasFee = sysConfigService.getBigDecimal("gas_fee");
  95. Order order = Order.builder()
  96. .userId(userId)
  97. .collectionId(collectionId)
  98. .name(collection.getName())
  99. .pic(collection.getPics())
  100. .detail(collection.getDetail())
  101. .properties(collection.getProperties())
  102. .category(collection.getCategory())
  103. .canResale(collection.isCanResale())
  104. .royalties(collection.getRoyalties())
  105. .serviceCharge(collection.getServiceCharge())
  106. .type(collection.getType())
  107. .minterId(collection.getMinterId())
  108. .minter(minter.getNickname())
  109. .minterAvatar(minter.getAvatar())
  110. .qty(qty)
  111. .price(collection.getPrice())
  112. .gasPrice(gasFee)
  113. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(gasFee))
  114. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  115. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  116. .address(Optional.ofNullable(userAddress).map(u ->
  117. u.getProvinceId() + " " + u.getCityId() + " " + u.getDistrictId() + " " + u.getAddress())
  118. .orElse(null))
  119. .status(OrderStatus.NOT_PAID)
  120. .build();
  121. return orderRepo.save(order);
  122. }
  123. public void payOrderAlipay(Long id, Model model) {
  124. try {
  125. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  126. if (order.getStatus() != OrderStatus.NOT_PAID) {
  127. throw new BusinessException("订单状态错误");
  128. }
  129. JSONObject bizContent = new JSONObject();
  130. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  131. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  132. bizContent.put("out_trade_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
  133. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  134. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  135. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  136. // 测试环境设为1分
  137. bizContent.put("total_amount", "0.01");
  138. }
  139. bizContent.put("subject", order.getName());
  140. bizContent.put("product_code", "QUICK_WAP_PAY");
  141. JSONObject body = new JSONObject();
  142. body.put("action", "payOrder");
  143. body.put("userId", order.getUserId());
  144. body.put("orderId", order.getId());
  145. bizContent.put("body", body.toJSONString());
  146. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  147. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  148. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  149. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  150. String form = alipayClient.pageExecute(alipayRequest).getBody();
  151. model.addAttribute("form", form);
  152. } catch (BusinessException err) {
  153. model.addAttribute("errMsg", err.getError());
  154. } catch (Exception e) {
  155. model.addAttribute("errMsg", e.getMessage());
  156. }
  157. }
  158. public String payOrderWeixinH5(Long id) throws WxPayException, EncoderException {
  159. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  160. if (order.getStatus() != OrderStatus.NOT_PAID) {
  161. throw new BusinessException("订单状态错误");
  162. }
  163. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  164. request.setBody(order.getName());
  165. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  166. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  167. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  168. // 测试环境设为1分
  169. // request.setTotalFee(1);
  170. }
  171. request.setSpbillCreateIp("180.102.110.170");
  172. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  173. request.setTradeType(WxPayConstants.TradeType.MWEB);
  174. request.setSignType("MD5");
  175. JSONObject body = new JSONObject();
  176. body.put("action", "payOrder");
  177. body.put("userId", order.getUserId());
  178. body.put("orderId", order.getId());
  179. request.setAttach(body.toJSONString());
  180. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  181. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  182. }
  183. public Object payOrderWeixin(Long id, String openId) throws WxPayException {
  184. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  185. if (order.getStatus() != OrderStatus.NOT_PAID) {
  186. throw new BusinessException("订单状态错误");
  187. }
  188. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  189. request.setBody(order.getName());
  190. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  191. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  192. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  193. // 测试环境设为1分
  194. // request.setTotalFee(1);
  195. }
  196. request.setSpbillCreateIp("180.102.110.170");
  197. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  198. request.setTradeType(WxPayConstants.TradeType.JSAPI);
  199. request.setOpenid(openId);
  200. request.setSignType("MD5");
  201. JSONObject body = new JSONObject();
  202. body.put("action", "payOrder");
  203. body.put("userId", order.getUserId());
  204. body.put("orderId", order.getId());
  205. request.setAttach(body.toJSONString());
  206. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  207. }
  208. public void notifyAlipay(Long orderId, PayMethod payMethod, String transactionId) {
  209. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  210. if (order.getStatus() == OrderStatus.NOT_PAID) {
  211. if (order.getType() == CollectionType.BLIND_BOX) {
  212. List<BlindBoxItem> items = blindBoxItemRepo.findByBlindBoxId(order.getCollectionId());
  213. Map<BlindBoxItem, Range<Integer>> randomRange = new HashMap<>();
  214. int c = 0, sum = 0;
  215. for (BlindBoxItem item : items) {
  216. randomRange.put(item, Range.between(c, c + item.getStock()));
  217. c += item.getStock();
  218. sum += item.getStock();
  219. }
  220. int retry = 0;
  221. BlindBoxItem winItem = null;
  222. while (winItem == null) {
  223. retry++;
  224. int rand = RandomUtils.nextInt(0, sum + 1);
  225. for (Map.Entry<BlindBoxItem, Range<Integer>> entry : randomRange.entrySet()) {
  226. BlindBoxItem item = entry.getKey();
  227. Range<Integer> range = entry.getValue();
  228. if (rand >= range.getMinimum() && rand < range.getMaximum()) {
  229. int total = items.stream().filter(i -> !i.isRare())
  230. .mapToInt(BlindBoxItem::getTotal).sum();
  231. int stock = items.stream().filter(i -> !i.isRare())
  232. .mapToInt(BlindBoxItem::getStock).sum();
  233. if (item.isRare()) {
  234. double nRate = stock / (double) total;
  235. double rRate = (item.getStock() - 1) / (double) item.getTotal();
  236. if (Math.abs(nRate - rRate) < (1 / (double) item.getTotal()) || retry > 1 || rRate == 0) {
  237. if (!(nRate > 0.1 && item.getStock() == 1)) {
  238. winItem = item;
  239. }
  240. }
  241. } else {
  242. double nRate = (stock - 1) / (double) total;
  243. double rRate = item.getStock() / (double) item.getTotal();
  244. if (Math.abs(nRate - rRate) < 0.2 || retry > 1 || nRate == 0) {
  245. winItem = item;
  246. }
  247. }
  248. }
  249. }
  250. if (retry > 100 && winItem == null) {
  251. throw new BusinessException("盲盒抽卡失败");
  252. }
  253. }
  254. winItem.setStock(winItem.getStock() - 1);
  255. winItem.setSale(winItem.getSale() + 1);
  256. order.setStatus(OrderStatus.PROCESSING);
  257. order.setPayTime(LocalDateTime.now());
  258. order.setTransactionId(transactionId);
  259. order.setPayMethod(payMethod);
  260. orderRepo.save(order);
  261. assetService.createAsset(order, winItem);
  262. } else {
  263. order.setStatus(OrderStatus.PROCESSING);
  264. order.setPayTime(LocalDateTime.now());
  265. order.setTransactionId(transactionId);
  266. order.setPayMethod(payMethod);
  267. orderRepo.save(order);
  268. assetService.createAsset(order);
  269. }
  270. } else if (order.getStatus() == OrderStatus.CANCELLED) {
  271. }
  272. }
  273. @EventListener
  274. public void onCreateAsset(CreateAssetEvent event) {
  275. Order order = event.getOrder();
  276. Asset asset = event.getAsset();
  277. if (event.isSuccess()) {
  278. order.setTxHash(asset.getTxHash());
  279. order.setGasUsed(asset.getGasUsed());
  280. order.setBlockNumber(asset.getBlockNumber());
  281. order.setStatus(OrderStatus.FINISH);
  282. orderRepo.save(order);
  283. } else {
  284. log.error("创建asset失败");
  285. }
  286. }
  287. public void cancel(Long id) {
  288. Order order = orderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  289. cancel(order);
  290. }
  291. public void cancel(Order order) {
  292. if (order.getStatus() != OrderStatus.NOT_PAID) {
  293. throw new BusinessException("已支付订单无法取消");
  294. }
  295. Collection collection = collectionRepo.findById(order.getCollectionId())
  296. .orElseThrow(new BusinessException("藏品不存在"));
  297. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  298. collection.setSale(collection.getSale() - 1);
  299. collection.setStock(collection.getStock() + 1);
  300. collectionRepo.save(collection);
  301. minter.setSales(minter.getSales() - 1);
  302. userRepo.save(minter);
  303. order.setStatus(OrderStatus.CANCELLED);
  304. order.setCancelTime(LocalDateTime.now());
  305. orderRepo.save(order);
  306. }
  307. @Scheduled(fixedRate = 60000)
  308. public void batchCancel() {
  309. List<Order> orders = orderRepo.findByStatusAndCreatedAtBeforeAndDelFalse(OrderStatus.NOT_PAID,
  310. LocalDateTime.now().minusMinutes(5));
  311. orders.stream().parallel().forEach(this::cancel);
  312. }
  313. public void refundCancelled(Order order) {
  314. }
  315. }