OrderService.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package com.izouma.nineth.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alipay.api.AlipayClient;
  5. import com.alipay.api.request.AlipayTradeWapPayRequest;
  6. import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
  7. import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
  8. import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
  9. import com.github.binarywang.wxpay.constant.WxPayConstants;
  10. import com.github.binarywang.wxpay.exception.WxPayException;
  11. import com.github.binarywang.wxpay.service.WxPayService;
  12. import com.izouma.nineth.config.AlipayProperties;
  13. import com.izouma.nineth.config.WxPayProperties;
  14. import com.izouma.nineth.domain.Collection;
  15. import com.izouma.nineth.domain.*;
  16. import com.izouma.nineth.dto.PageQuery;
  17. import com.izouma.nineth.enums.*;
  18. import com.izouma.nineth.event.CreateAssetEvent;
  19. import com.izouma.nineth.event.TransferAssetEvent;
  20. import com.izouma.nineth.exception.BusinessException;
  21. import com.izouma.nineth.repo.*;
  22. import com.izouma.nineth.utils.JpaUtils;
  23. import com.izouma.nineth.utils.SnowflakeIdWorker;
  24. import lombok.AllArgsConstructor;
  25. import lombok.extern.slf4j.Slf4j;
  26. import org.apache.commons.codec.EncoderException;
  27. import org.apache.commons.codec.net.URLCodec;
  28. import org.apache.commons.lang3.RandomUtils;
  29. import org.apache.commons.lang3.Range;
  30. import org.springframework.context.event.EventListener;
  31. import org.springframework.core.env.Environment;
  32. import org.springframework.data.domain.Page;
  33. import org.springframework.data.redis.core.RedisTemplate;
  34. import org.springframework.scheduling.annotation.Scheduled;
  35. import org.springframework.stereotype.Service;
  36. import org.springframework.ui.Model;
  37. import javax.transaction.Transactional;
  38. import java.math.BigDecimal;
  39. import java.time.LocalDateTime;
  40. import java.util.*;
  41. @Service
  42. @AllArgsConstructor
  43. @Slf4j
  44. public class OrderService {
  45. private OrderRepo orderRepo;
  46. private CollectionRepo collectionRepo;
  47. private UserAddressRepo userAddressRepo;
  48. private UserRepo userRepo;
  49. private Environment env;
  50. private AlipayClient alipayClient;
  51. private AlipayProperties alipayProperties;
  52. private WxPayService wxPayService;
  53. private WxPayProperties wxPayProperties;
  54. private AssetService assetService;
  55. private SysConfigService sysConfigService;
  56. private BlindBoxItemRepo blindBoxItemRepo;
  57. private AssetRepo assetRepo;
  58. private UserCouponRepo userCouponRepo;
  59. private CollectionService collectionService;
  60. private RedisTemplate<String, Object> redisTemplate;
  61. public Page<Order> all(PageQuery pageQuery) {
  62. return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
  63. }
  64. @Transactional
  65. public Order create(Long userId, Long collectionId, int qty, Long addressId, Long userCouponId) {
  66. if (qty <= 0) throw new BusinessException("数量必须大于0");
  67. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  68. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  69. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  70. UserCoupon coupon = null;
  71. if (userCouponId != null) {
  72. coupon = userCouponRepo.findById(userCouponId).orElseThrow(new BusinessException("兑换券不存在"));
  73. if (coupon.isUsed()) {
  74. throw new BusinessException("该兑换券已使用");
  75. }
  76. if (coupon.isLimited() && !coupon.getCollectionIds().contains(collectionId)) {
  77. throw new BusinessException("该兑换券不可用");
  78. }
  79. }
  80. if (!collection.isOnShelf()) {
  81. throw new BusinessException("藏品已下架");
  82. }
  83. if (qty > collection.getStock()) {
  84. throw new BusinessException("库存不足");
  85. }
  86. if (!collection.isSalable()) {
  87. throw new BusinessException("该藏品当前不可购买");
  88. }
  89. if (collection.getType() == CollectionType.BLIND_BOX) {
  90. if (collection.getStartTime().isAfter(LocalDateTime.now())) {
  91. throw new BusinessException("盲盒未开售");
  92. }
  93. }
  94. UserAddress userAddress = null;
  95. if (addressId != null) {
  96. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  97. }
  98. collection.setStock(collection.getStock() - qty);
  99. collection.setSale(collection.getSale() + qty);
  100. collectionRepo.save(collection);
  101. minter.setSales(minter.getSales() + 1);
  102. BigDecimal gasFee = sysConfigService.getBigDecimal("gas_fee");
  103. Order order = Order.builder()
  104. .userId(userId)
  105. .collectionId(collectionId)
  106. .name(collection.getName())
  107. .pic(collection.getPic())
  108. .detail(collection.getDetail())
  109. .properties(collection.getProperties())
  110. .category(collection.getCategory())
  111. .canResale(collection.isCanResale())
  112. .royalties(collection.getRoyalties())
  113. .serviceCharge(collection.getServiceCharge())
  114. .type(collection.getType())
  115. .minterId(collection.getMinterId())
  116. .minter(minter.getNickname())
  117. .minterAvatar(minter.getAvatar())
  118. .qty(qty)
  119. .price(collection.getPrice())
  120. .gasPrice(gasFee)
  121. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(gasFee))
  122. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  123. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  124. .address(Optional.ofNullable(userAddress).map(u ->
  125. u.getProvinceId() + " " + u.getCityId() + " " + u.getDistrictId() + " " + u.getAddress())
  126. .orElse(null))
  127. .status(OrderStatus.NOT_PAID)
  128. .assetId(collection.getAssetId())
  129. .couponId(userCouponId)
  130. .build();
  131. if (coupon != null) {
  132. coupon.setUsed(true);
  133. coupon.setUseTime(LocalDateTime.now());
  134. if (coupon.isNeedGas()) {
  135. order.setTotalPrice(order.getGasPrice());
  136. } else {
  137. order.setTotalPrice(BigDecimal.ZERO);
  138. }
  139. }
  140. if (collection.getSource() == CollectionSource.TRANSFER) {
  141. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("资产不存在"));
  142. asset.setStatus(AssetStatus.TRADING);
  143. assetRepo.save(asset);
  144. collection.setOnShelf(false);
  145. collectionRepo.save(collection);
  146. }
  147. order = orderRepo.save(order);
  148. if (order.getTotalPrice().equals(BigDecimal.ZERO)) {
  149. notifyOrder(order.getId(), PayMethod.WEIXIN, null);
  150. }
  151. return order;
  152. }
  153. public void payOrderAlipay(Long id, Model model) {
  154. try {
  155. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  156. if (order.getStatus() != OrderStatus.NOT_PAID) {
  157. throw new BusinessException("订单状态错误");
  158. }
  159. JSONObject bizContent = new JSONObject();
  160. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  161. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  162. bizContent.put("out_trade_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
  163. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  164. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  165. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  166. // 测试环境设为1分
  167. bizContent.put("total_amount", "0.01");
  168. }
  169. bizContent.put("subject", order.getName());
  170. bizContent.put("product_code", "QUICK_WAP_PAY");
  171. JSONObject body = new JSONObject();
  172. body.put("action", "payOrder");
  173. body.put("userId", order.getUserId());
  174. body.put("orderId", order.getId());
  175. bizContent.put("body", body.toJSONString());
  176. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  177. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  178. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  179. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  180. String form = alipayClient.pageExecute(alipayRequest).getBody();
  181. model.addAttribute("form", form);
  182. } catch (BusinessException err) {
  183. model.addAttribute("errMsg", err.getError());
  184. } catch (Exception e) {
  185. model.addAttribute("errMsg", e.getMessage());
  186. }
  187. }
  188. public Object payOrderWeixin(Long id, String tradeType, String openId) throws WxPayException, EncoderException {
  189. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  190. if (order.getStatus() != OrderStatus.NOT_PAID) {
  191. throw new BusinessException("订单状态错误");
  192. }
  193. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  194. request.setBody(order.getName());
  195. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  196. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  197. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  198. // 测试环境设为1分
  199. // request.setTotalFee(1);
  200. }
  201. request.setSpbillCreateIp("180.102.110.170");
  202. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  203. request.setTradeType(tradeType);
  204. request.setOpenid(openId);
  205. request.setSignType("MD5");
  206. JSONObject body = new JSONObject();
  207. body.put("action", "payOrder");
  208. body.put("userId", order.getUserId());
  209. body.put("orderId", order.getId());
  210. request.setAttach(body.toJSONString());
  211. if (WxPayConstants.TradeType.MWEB.equals(tradeType)) {
  212. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  213. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  214. } else if (WxPayConstants.TradeType.JSAPI.equals(tradeType)) {
  215. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  216. }
  217. throw new BusinessException("不支持此付款方式");
  218. }
  219. @Transactional
  220. public void notifyOrder(Long orderId, PayMethod payMethod, String transactionId) {
  221. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  222. Collection collection = collectionRepo.findById(order.getCollectionId())
  223. .orElseThrow(new BusinessException("藏品不存在"));
  224. User user = userRepo.findById(order.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  225. if (order.getStatus() == OrderStatus.NOT_PAID) {
  226. order.setStatus(OrderStatus.PROCESSING);
  227. order.setPayTime(LocalDateTime.now());
  228. order.setTransactionId(transactionId);
  229. order.setPayMethod(payMethod);
  230. if (order.getType() == CollectionType.BLIND_BOX) {
  231. BlindBoxItem winItem = collectionService.draw(collection.getId());
  232. orderRepo.save(order);
  233. assetService.createAsset(winItem, user, order.getId(), order.getPrice(), "出售",
  234. collectionService.getNextNumber(winItem.getCollectionId()));
  235. } else {
  236. if (collection.getSource() == CollectionSource.TRANSFER) {
  237. Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
  238. assetService.transfer(asset, order.getPrice(), user, "转让", order.getId());
  239. collectionRepo.delete(collection);
  240. } else {
  241. orderRepo.save(order);
  242. assetService.createAsset(collection, user, order.getId(), order.getPrice(), "出售",
  243. collectionService.getNextNumber(order.getCollectionId()));
  244. }
  245. }
  246. } else if (order.getStatus() == OrderStatus.CANCELLED) {
  247. }
  248. }
  249. @EventListener
  250. public void onCreateAsset(CreateAssetEvent event) {
  251. Asset asset = event.getAsset();
  252. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException("订单不存在"));
  253. if (event.isSuccess()) {
  254. order.setTxHash(asset.getTxHash());
  255. order.setGasUsed(asset.getGasUsed());
  256. order.setBlockNumber(asset.getBlockNumber());
  257. order.setStatus(OrderStatus.FINISH);
  258. orderRepo.save(order);
  259. } else {
  260. log.error("创建asset失败");
  261. }
  262. }
  263. @EventListener
  264. public void onTransferAsset(TransferAssetEvent event) {
  265. Asset asset = event.getAsset();
  266. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException("订单不存在"));
  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. if (collection.getSource() == CollectionSource.TRANSFER) {
  289. Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
  290. if (asset != null) {
  291. asset.setStatus(AssetStatus.NORMAL);
  292. }
  293. collection.setOnShelf(true);
  294. }
  295. collection.setSale(collection.getSale() - 1);
  296. collection.setStock(collection.getStock() + 1);
  297. collectionRepo.save(collection);
  298. minter.setSales(minter.getSales() - 1);
  299. userRepo.save(minter);
  300. order.setStatus(OrderStatus.CANCELLED);
  301. order.setCancelTime(LocalDateTime.now());
  302. orderRepo.save(order);
  303. if (order.getCouponId() != null) {
  304. userCouponRepo.findById(order.getCouponId()).ifPresent(coupon -> {
  305. coupon.setUsed(false);
  306. coupon.setUseTime(null);
  307. userCouponRepo.save(coupon);
  308. });
  309. }
  310. }
  311. @Scheduled(fixedRate = 60000)
  312. public void batchCancel() {
  313. List<Order> orders = orderRepo.findByStatusAndCreatedAtBeforeAndDelFalse(OrderStatus.NOT_PAID,
  314. LocalDateTime.now().minusMinutes(5));
  315. orders.forEach(this::cancel);
  316. }
  317. public void refundCancelled(Order order) {
  318. }
  319. public void setNumber() {
  320. for (Collection collection : collectionRepo.findAll()) {
  321. if (collection.getSource() != CollectionSource.OFFICIAL) continue;
  322. String key = "collectionNumber::" + collection.getId();
  323. redisTemplate.opsForValue().set(key, 0);
  324. for (Asset asset : assetRepo.findByCollectionId(collection.getId())) {
  325. redisTemplate.opsForValue().increment(key);
  326. asset.setNumber((Integer) redisTemplate.opsForValue().get(key));
  327. assetRepo.save(asset);
  328. }
  329. }
  330. }
  331. }