OrderService.java 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. package com.izouma.nineth.service;
  2. import com.alibaba.excel.EasyExcel;
  3. import com.alibaba.fastjson.JSON;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.alibaba.fastjson.serializer.SerializerFeature;
  6. import com.alipay.api.AlipayClient;
  7. import com.alipay.api.request.AlipayTradeWapPayRequest;
  8. import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
  9. import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
  10. import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
  11. import com.github.binarywang.wxpay.constant.WxPayConstants;
  12. import com.github.binarywang.wxpay.exception.WxPayException;
  13. import com.github.binarywang.wxpay.service.WxPayService;
  14. import com.google.common.base.Splitter;
  15. import com.huifu.adapay.Adapay;
  16. import com.huifu.adapay.core.exception.BaseAdaPayException;
  17. import com.huifu.adapay.model.AdapayCommon;
  18. import com.huifu.adapay.model.Payment;
  19. import com.huifu.adapay.model.Refund;
  20. import com.izouma.nineth.config.*;
  21. import com.izouma.nineth.domain.Collection;
  22. import com.izouma.nineth.domain.*;
  23. import com.izouma.nineth.dto.MarketSettlement;
  24. import com.izouma.nineth.dto.PageQuery;
  25. import com.izouma.nineth.dto.UserBankCard;
  26. import com.izouma.nineth.enums.*;
  27. import com.izouma.nineth.event.CreateAssetEvent;
  28. import com.izouma.nineth.event.CreateOrderEvent;
  29. import com.izouma.nineth.event.OrderNotifyEvent;
  30. import com.izouma.nineth.event.TransferAssetEvent;
  31. import com.izouma.nineth.exception.BusinessException;
  32. import com.izouma.nineth.repo.*;
  33. import com.izouma.nineth.security.Authority;
  34. import com.izouma.nineth.service.sms.SmsService;
  35. import com.izouma.nineth.utils.AESEncryptUtil;
  36. import com.izouma.nineth.utils.JpaUtils;
  37. import com.izouma.nineth.utils.SecurityUtils;
  38. import com.izouma.nineth.utils.SnowflakeIdWorker;
  39. import com.izouma.nineth.utils.excel.ExcelUtils;
  40. import lombok.AllArgsConstructor;
  41. import lombok.extern.slf4j.Slf4j;
  42. import org.apache.commons.codec.EncoderException;
  43. import org.apache.commons.codec.net.URLCodec;
  44. import org.apache.commons.collections.MapUtils;
  45. import org.apache.commons.lang3.ObjectUtils;
  46. import org.apache.commons.lang3.StringUtils;
  47. import org.apache.rocketmq.client.producer.SendResult;
  48. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  49. import org.springframework.cache.annotation.Cacheable;
  50. import org.springframework.context.event.EventListener;
  51. import org.springframework.core.env.Environment;
  52. import org.springframework.data.domain.Page;
  53. import org.springframework.data.redis.core.BoundSetOperations;
  54. import org.springframework.data.redis.core.BoundValueOperations;
  55. import org.springframework.data.redis.core.RedisTemplate;
  56. import org.springframework.scheduling.annotation.Scheduled;
  57. import org.springframework.stereotype.Service;
  58. import org.springframework.ui.Model;
  59. import java.io.File;
  60. import java.io.OutputStream;
  61. import java.math.BigDecimal;
  62. import java.math.RoundingMode;
  63. import java.time.Duration;
  64. import java.time.LocalDateTime;
  65. import java.time.format.DateTimeFormatter;
  66. import java.time.temporal.ChronoUnit;
  67. import java.util.*;
  68. import java.util.concurrent.TimeUnit;
  69. import java.util.concurrent.atomic.AtomicInteger;
  70. import java.util.stream.Collectors;
  71. @Service
  72. @AllArgsConstructor
  73. @Slf4j
  74. public class OrderService {
  75. private OrderRepo orderRepo;
  76. private CollectionRepo collectionRepo;
  77. private UserAddressRepo userAddressRepo;
  78. private UserRepo userRepo;
  79. private Environment env;
  80. private AlipayClient alipayClient;
  81. private AlipayProperties alipayProperties;
  82. private WxPayService wxPayService;
  83. private WxPayProperties wxPayProperties;
  84. private AssetService assetService;
  85. private SysConfigService sysConfigService;
  86. private AssetRepo assetRepo;
  87. private UserCouponRepo userCouponRepo;
  88. private CollectionService collectionService;
  89. private CommissionRecordRepo commissionRecordRepo;
  90. private AdapayProperties adapayProperties;
  91. private GeneralProperties generalProperties;
  92. private RocketMQTemplate rocketMQTemplate;
  93. private RedisTemplate<String, Object> redisTemplate;
  94. private SnowflakeIdWorker snowflakeIdWorker;
  95. private SmsService smsService;
  96. private ErrorOrderRepo errorOrderRepo;
  97. private ShowCollectionRepo showCollectionRepo;
  98. private ShowroomService showroomService;
  99. private CollectionPrivilegeRepo collectionPrivilegeRepo;
  100. private UserBankCardRepo userBankCardRepo;
  101. private IdentityAuthRepo identityAuthRepo;
  102. public Page<Order> all(PageQuery pageQuery) {
  103. return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
  104. }
  105. public String mqCreate(Long userId, Long collectionId, int qty, Long addressId, Long userCouponId, Long invitor,
  106. String sign, boolean vip, int vipPurchase, int vipPoint) {
  107. String qs = null;
  108. try {
  109. qs = AESEncryptUtil.decrypt(sign);
  110. } catch (Exception e) {
  111. throw new BusinessException("签名错误");
  112. }
  113. final Map<String, String> map = Splitter.on('&').trimResults().withKeyValueSeparator('=').split(qs);
  114. if (Math.abs(MapUtils.getLong(map, "ts") - System.currentTimeMillis()) > 90000) {
  115. throw new BusinessException("签名已过期");
  116. }
  117. if (redisTemplate.opsForValue().get(RedisKeys.BLACK_LIST + userId) != null) {
  118. throw new BusinessException("频繁操作,请稍后再试");
  119. }
  120. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.LIMIT_USER + userId);
  121. ops.setIfAbsent(0, Duration.ofSeconds(10));
  122. long val = Optional.ofNullable(ops.increment()).orElse(0L);
  123. if (val > 5) {
  124. if (val > 10) {
  125. redisTemplate.opsForValue().set(RedisKeys.BLACK_LIST + userId, 1, Duration.ofSeconds(60 * 10));
  126. }
  127. throw new BusinessException("频繁操作,请稍后再试");
  128. }
  129. limitReq(collectionId);
  130. Integer stock = collectionService.getStock(collectionId);
  131. if (stock == null || stock <= 0) {
  132. throw new BusinessException("藏品已售罄", ErrorCode.SOLD_OUT);
  133. }
  134. Long id = snowflakeIdWorker.nextId();
  135. SendResult result = rocketMQTemplate.syncSend(generalProperties.getCreateOrderTopic(),
  136. new CreateOrderEvent(id, userId, collectionId, qty, addressId, userCouponId, invitor, vip), 100000);
  137. log.info("发送订单到队列: {}, userId={}, result={}", id, userId, result);
  138. return String.valueOf(id);
  139. }
  140. public void limitReq(Long collectionId) {
  141. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.LIMIT_REQ + collectionId);
  142. ops.setIfAbsent(3000, Duration.ofSeconds(30));
  143. Long val = ops.decrement();
  144. if (val == null || val < 0) {
  145. throw new BusinessException("前方拥堵,请稍后再试");
  146. }
  147. }
  148. public Order create(Long userId, Long collectionId, int qty, Long addressId, Long userCouponId, Long invitor,
  149. Long id, boolean vip) {
  150. long t = System.currentTimeMillis();
  151. qty = 1;
  152. int stock = Optional.ofNullable(collectionService.decreaseStock(collectionId, qty))
  153. .map(Math::toIntExact)
  154. .orElseThrow(new BusinessException("很遗憾,藏品已售罄", ErrorCode.SOLD_OUT));
  155. int usePoint = 0;
  156. // 创建订单出错后需要回滚库存,所以需要try-catch
  157. try {
  158. if (stock < 0) {
  159. throw new BusinessException("很遗憾,藏品已售罄", ErrorCode.SOLD_OUT);
  160. }
  161. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  162. if (collection.getAssetId() != null && collection.getAssetId().equals(778359L)) {
  163. throw new BusinessException("很遗憾,藏品已售罄", ErrorCode.SOLD_OUT);
  164. }
  165. if (collection.getAssetId() != null) {
  166. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("藏品不存在"));
  167. if (asset.getStatus() != AssetStatus.NORMAL) {
  168. throw new BusinessException("藏品已下架");
  169. }
  170. }
  171. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  172. UserCoupon coupon = null;
  173. if (collection.isCouponPayment()) {
  174. if (userCouponId == null) {
  175. throw new BusinessException("必须使用优惠券支付");
  176. }
  177. coupon = userCouponRepo.findById(userCouponId).orElseThrow(new BusinessException("兑换券不存在"));
  178. if (coupon.isUsed()) {
  179. throw new BusinessException("该兑换券已使用");
  180. }
  181. if (coupon.isLimited() && !coupon.getCollectionIds().contains(collectionId)) {
  182. throw new BusinessException("该兑换券不可用");
  183. }
  184. }
  185. if (collection.isScheduleSale()) {
  186. if (collection.getStartTime().isAfter(LocalDateTime.now())) {
  187. throw new BusinessException("当前还未开售");
  188. }
  189. }
  190. if (!collection.isOnShelf()) {
  191. if (!collection.isScanCode()) {
  192. throw new BusinessException("藏品已下架");
  193. }
  194. }
  195. if (!collection.isSalable()) {
  196. throw new BusinessException("该藏品当前不可购买");
  197. }
  198. if (collection.getMaxCount() > 0) {
  199. int count;
  200. if (StringUtils.isNotBlank(collection.getCountId())) {
  201. count = orderRepo.countByUserIdAndCountIdAndStatusIn(userId, collection.getCountId(), Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  202. } else {
  203. count = orderRepo.countByUserIdAndCollectionIdAndStatusIn(userId, collectionId, Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  204. }
  205. if (count >= collection.getMaxCount()) {
  206. throw new BusinessException("限购" + collection.getMaxCount() + "件");
  207. }
  208. }
  209. User user = null;
  210. if (ObjectUtils.isNotEmpty(collection.getMinimumCharge()) && collection.getMinimumCharge()
  211. .compareTo(BigDecimal.ZERO) > 0) {
  212. user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  213. if (!user.isCanSale()) {
  214. throw new BusinessException("绿洲石不足");
  215. }
  216. }
  217. //查询是否有拉新任务,只算官方购买
  218. if (collection.getSource() != CollectionSource.TRANSFER && collection.getAssignment() > 0) {
  219. //延迟销售
  220. if (!vip && collection.getTimeDelay()) {
  221. if (collection.getSaleTime().isAfter(LocalDateTime.now())) {
  222. throw new BusinessException("当前还未开售");
  223. }
  224. }
  225. if (user == null) {
  226. user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  227. }
  228. if (vip) {
  229. int purchase = orderRepo.countByUserIdAndCollectionIdAndVipTrueAndStatusIn(userId, collectionId, Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  230. if (user.getVipPurchase() - purchase <= 0) {
  231. throw new BusinessException("vip名额已使用完毕!");
  232. }
  233. // vip扣除额度
  234. if (ObjectUtils.isNotEmpty(collection.getVipQuota())) {
  235. collectionService.decreaseQuota(collectionId, 1);
  236. }
  237. } else {
  238. if (user.getVipPoint() < 1) {
  239. throw new BusinessException("没有购买名额");
  240. }
  241. usePoint = 1;
  242. }
  243. }
  244. UserAddress userAddress = null;
  245. if (addressId != null) {
  246. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  247. }
  248. BigDecimal gasFee = sysConfigService.getBigDecimal("gas_fee");
  249. Order order = Order.builder()
  250. .id(Optional.ofNullable(id).orElse(snowflakeIdWorker.nextId()))
  251. .userId(userId)
  252. .collectionId(collectionId)
  253. .name(collection.getName())
  254. .pic(collection.getPic())
  255. .detail(collection.getDetail())
  256. .properties(collection.getProperties())
  257. .category(collection.getCategory())
  258. .canResale(collection.isCanResale())
  259. .royalties(collection.getRoyalties())
  260. .serviceCharge(collection.getServiceCharge())
  261. .type(collection.getType())
  262. .source(collection.getSource())
  263. .minterId(collection.getMinterId())
  264. .minter(minter.getNickname())
  265. .minterAvatar(minter.getAvatar())
  266. .qty(qty)
  267. .price(collection.getPrice())
  268. .gasPrice(gasFee)
  269. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(gasFee))
  270. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  271. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  272. .address(Optional.ofNullable(userAddress).map(u ->
  273. u.getProvinceName() + " " + u.getCityName() + " " + u.getDistrictName() + " " + u.getAddress())
  274. .orElse(null))
  275. .status(OrderStatus.NOT_PAID)
  276. .assetId(collection.getAssetId())
  277. .couponId(userCouponId)
  278. .invitor(invitor)
  279. .countId(collection.getCountId())
  280. .vip(vip)
  281. .vipPoint(usePoint)
  282. .build();
  283. if (coupon != null) {
  284. coupon.setUsed(true);
  285. coupon.setUseTime(LocalDateTime.now());
  286. if (coupon.isNeedGas()) {
  287. order.setTotalPrice(order.getGasPrice());
  288. } else {
  289. order.setTotalPrice(BigDecimal.ZERO);
  290. }
  291. userCouponRepo.save(coupon);
  292. }
  293. if (collection.getSource() == CollectionSource.TRANSFER) {
  294. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("资产不存在"));
  295. asset.setStatus(AssetStatus.TRADING);
  296. assetRepo.save(asset);
  297. collectionRepo.setOnShelf(collectionId, false);
  298. }
  299. order = orderRepo.save(order);
  300. if (order.getTotalPrice().equals(BigDecimal.ZERO)) {
  301. notifyOrder(order.getId(), PayMethod.WEIXIN, null);
  302. }
  303. if (usePoint > 0) {
  304. // 扣除积分
  305. userRepo.addVipPoint(userId, -usePoint);
  306. }
  307. rocketMQTemplate.syncSend(generalProperties.getUpdateStockTopic(), collectionId, 10000);
  308. log.info("订单创建完成, id={}, {}ms", order.getId(), System.currentTimeMillis() - t);
  309. return order;
  310. } catch (Exception e) {
  311. collectionService.increaseStock(collectionId, qty);
  312. if (usePoint > 0) {
  313. // 扣除积分
  314. userRepo.addVipPoint(userId, usePoint);
  315. log.info("订单失败加积分用户ID:{}, 积分:{}", userId, usePoint);
  316. }
  317. if (vip) {
  318. collectionService.decreaseQuota(collectionId, 1);
  319. log.info("订单失败加藏品额度CollectionId:{}", collectionId);
  320. }
  321. throw e;
  322. }
  323. }
  324. public Object checkLimit(Long collectionId, Long userId) {
  325. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  326. int limit = collection.getMaxCount();
  327. int count = 0;
  328. if (collection.getMaxCount() > 0) {
  329. if (StringUtils.isNotBlank(collection.getCountId())) {
  330. count = orderRepo.countByUserIdAndCountIdAndStatusIn(userId, collection.getCountId(),
  331. Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  332. } else {
  333. count = orderRepo.countByUserIdAndCollectionIdAndStatusIn(userId, collectionId,
  334. Arrays.asList(OrderStatus.FINISH, OrderStatus.NOT_PAID, OrderStatus.PROCESSING));
  335. }
  336. }
  337. Map<String, Object> map = new HashMap<>();
  338. map.put("limit", limit);
  339. map.put("count", count);
  340. return map;
  341. }
  342. public void payOrderAlipay(Long id, Model model) {
  343. try {
  344. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  345. if (order.getStatus() != OrderStatus.NOT_PAID) {
  346. throw new BusinessException("订单状态错误");
  347. }
  348. JSONObject bizContent = new JSONObject();
  349. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  350. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  351. bizContent.put("out_trade_no", String.valueOf(snowflakeIdWorker.nextId()));
  352. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  353. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  354. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  355. // 测试环境设为1分
  356. bizContent.put("total_amount", "0.01");
  357. }
  358. bizContent.put("subject", order.getName());
  359. bizContent.put("product_code", "QUICK_WAP_PAY");
  360. JSONObject body = new JSONObject();
  361. body.put("action", "payOrder");
  362. body.put("userId", order.getUserId());
  363. body.put("orderId", order.getId());
  364. bizContent.put("body", body.toJSONString());
  365. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  366. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  367. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  368. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  369. String form = alipayClient.pageExecute(alipayRequest).getBody();
  370. model.addAttribute("form", form);
  371. } catch (BusinessException err) {
  372. model.addAttribute("errMsg", err.getError());
  373. } catch (Exception e) {
  374. model.addAttribute("errMsg", e.getMessage());
  375. }
  376. }
  377. public Object payOrderWeixin(Long id, String tradeType, String openId) throws WxPayException, EncoderException {
  378. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  379. if (order.getStatus() != OrderStatus.NOT_PAID) {
  380. throw new BusinessException("订单状态错误");
  381. }
  382. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  383. request.setBody(order.getName());
  384. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  385. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  386. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  387. // 测试环境设为1分
  388. // request.setTotalFee(1);
  389. }
  390. request.setSpbillCreateIp("180.102.110.170");
  391. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  392. request.setTradeType(tradeType);
  393. request.setOpenid(openId);
  394. request.setSignType("MD5");
  395. JSONObject body = new JSONObject();
  396. body.put("action", "payOrder");
  397. body.put("userId", order.getUserId());
  398. body.put("orderId", order.getId());
  399. request.setAttach(body.toJSONString());
  400. if (WxPayConstants.TradeType.MWEB.equals(tradeType)) {
  401. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  402. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  403. } else if (WxPayConstants.TradeType.JSAPI.equals(tradeType)) {
  404. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  405. }
  406. throw new BusinessException("不支持此付款方式");
  407. }
  408. @Cacheable(value = "adapay", key = "#id+'_'+#payChannel")
  409. public Object payAdapay(Long id, String payChannel, String openId) throws BaseAdaPayException {
  410. List<String> aliChannels = Arrays.asList("alipay", "alipay_qr", "alipay_wap");
  411. List<String> wxChannels = Arrays.asList("wx_pub", "wx_lite");
  412. if (!aliChannels.contains(payChannel) && !wxChannels.contains(payChannel)) {
  413. throw new BusinessException("不支持此渠道");
  414. }
  415. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  416. if (SecurityUtils.getAuthenticatedUser() != null
  417. && !SecurityUtils.getAuthenticatedUser().getId().equals(order.getUserId())) {
  418. log.error("payAdapay userId错误 requestUserId={} orderUserId={}",
  419. SecurityUtils.getAuthenticatedUser().getId(), order.getUserId());
  420. }
  421. Collection collection = collectionRepo.findById(order.getCollectionId())
  422. .orElseThrow(new BusinessException("藏品不存在"));
  423. User invitor = null;
  424. if (order.getInvitor() != null) {
  425. invitor = userRepo.findById(order.getInvitor()).orElse(null);
  426. }
  427. if (invitor != null && StringUtils.isBlank(invitor.getSettleAccountId())) {
  428. invitor = null;
  429. }
  430. if (order.getStatus() != OrderStatus.NOT_PAID) {
  431. throw new BusinessException("订单状态错误");
  432. }
  433. Map<String, Object> paymentParams = new HashMap<>();
  434. paymentParams.put("order_no", String.valueOf(snowflakeIdWorker.nextId()));
  435. paymentParams.put("pay_amt", order.getTotalPrice().setScale(2, RoundingMode.HALF_UP).toPlainString());
  436. paymentParams.put("app_id", adapayProperties.getAppId());
  437. paymentParams.put("pay_channel", payChannel);
  438. paymentParams.put("goods_title", collection.getName());
  439. paymentParams.put("goods_desc", collection.getName());
  440. paymentParams.put("time_expire", DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
  441. .format(LocalDateTime.now().plusMinutes(3)));
  442. paymentParams.put("notify_url", adapayProperties.getNotifyUrl() + "/order/" + adapayProperties.getMerchant() + "/" + order.getId());
  443. List<Map<String, Object>> divMembers = new ArrayList<>();
  444. BigDecimal totalAmount = order.getTotalPrice().subtract(order.getGasPrice());
  445. BigDecimal restAmount = order.getTotalPrice().multiply(BigDecimal.valueOf(1));
  446. if (collection.getSource().equals(CollectionSource.TRANSFER)) {
  447. Asset asset = assetRepo.findById(collection.getAssetId()).orElseThrow(new BusinessException("无记录"));
  448. User owner = userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("拥有者用户不存在"));
  449. if (collection.getServiceCharge() + collection.getRoyalties() > 0) {
  450. // 扣除手续费、服务费、GAS费
  451. restAmount = divMoney(totalAmount, restAmount, divMembers, owner.getMemberId(),
  452. 100 - (collection.getServiceCharge() + collection.getRoyalties()), false);
  453. }
  454. restAmount = divMoney(restAmount, divMembers, "0", restAmount, true);
  455. } else {
  456. if (invitor != null && invitor.getShareRatio() != null
  457. && invitor.getShareRatio().compareTo(BigDecimal.ZERO) > 0) {
  458. restAmount = divMoney(totalAmount, restAmount, divMembers, invitor.getMemberId(),
  459. invitor.getShareRatio().intValue(), false);
  460. }
  461. restAmount = divMoney(restAmount, divMembers, "0", restAmount, true);
  462. }
  463. if (restAmount.compareTo(BigDecimal.ZERO) != 0) {
  464. log.error("分账出错 {}", JSON.toJSONString(divMembers, SerializerFeature.PrettyFormat));
  465. throw new BusinessException("分账出错");
  466. }
  467. if (divMembers.size() > 1) {
  468. paymentParams.put("div_members", divMembers);
  469. }
  470. Map<String, Object> expend = new HashMap<>();
  471. paymentParams.put("expend", expend);
  472. if ("wx_pub".equals(payChannel)) {
  473. if (StringUtils.isBlank(openId)) {
  474. throw new BusinessException("缺少openId");
  475. }
  476. expend.put("open_id", openId);
  477. expend.put("limit_pay", "1");
  478. }
  479. Map<String, Object> response;
  480. if ("wx_lite".equals(payChannel)) {
  481. paymentParams.put("adapay_func_code", "wxpay.createOrder");
  482. paymentParams.put("callback_url", generalProperties.getHost() + "/9th/orders");
  483. response = AdapayCommon.requestAdapayUits(paymentParams);
  484. log.info("createOrderResponse {}", JSON.toJSONString(response, SerializerFeature.PrettyFormat));
  485. } else {
  486. response = Payment.create(paymentParams);
  487. log.info("createOrderResponse {}", JSON.toJSONString(response, SerializerFeature.PrettyFormat));
  488. AdapayService.checkSuccess(response);
  489. // 保存adapay的订单id,用于后续取消订单时的查询
  490. BoundSetOperations<String, Object> ops = redisTemplate.boundSetOps(RedisKeys.PAY_RECORD + order.getId());
  491. ops.add(adapayProperties.getMerchant() + "#" + MapUtils.getString(response, "id"));
  492. ops.expire(7, TimeUnit.DAYS);
  493. }
  494. switch (payChannel) {
  495. case "alipay_wap":
  496. case "alipay":
  497. return MapUtils.getString(MapUtils.getMap(response, "expend"), "pay_info");
  498. case "alipay_qr":
  499. return MapUtils.getString(MapUtils.getMap(response, "expend"), "qrcode_url");
  500. case "wx_pub":
  501. JSONObject payParams = JSON.parseObject(MapUtils.getString(MapUtils.getMap(response, "expend"), "pay_info"));
  502. payParams.put("timestamp", payParams.get("timeStamp"));
  503. payParams.remove("timeStamp");
  504. return payParams;
  505. default:
  506. return MapUtils.getMap(response, "expend");
  507. }
  508. }
  509. public static BigDecimal divMoney(BigDecimal totalAmount, BigDecimal restAmount, List<Map<String, Object>> divMembers,
  510. String memberId, int ratio, boolean feeFlag) {
  511. if (ratio == -1 || (ratio > 0 && ratio < 100)) {
  512. BigDecimal divAmount = ratio == -1 ? restAmount :
  513. totalAmount.multiply(BigDecimal.valueOf(ratio))
  514. .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
  515. Map<String, Object> divMem = new HashMap<>();
  516. divMem.put("member_id", memberId);
  517. divMem.put("amount", divAmount.toPlainString());
  518. divMem.put("fee_flag", feeFlag ? "Y" : "N");
  519. divMembers.add(divMem);
  520. return restAmount.subtract(divAmount);
  521. } else {
  522. throw new BusinessException("分账比例错误");
  523. }
  524. }
  525. public static BigDecimal divMoney(BigDecimal restAmount, List<Map<String, Object>> divMembers,
  526. String memberId, BigDecimal divAmount, boolean feeFlag) {
  527. if (divAmount.compareTo(BigDecimal.ZERO) > 0) {
  528. Map<String, Object> divMem = new HashMap<>();
  529. divMem.put("member_id", memberId);
  530. divMem.put("amount", divAmount.toPlainString());
  531. divMem.put("fee_flag", feeFlag ? "Y" : "N");
  532. divMembers.add(divMem);
  533. }
  534. return restAmount.subtract(divAmount);
  535. }
  536. public void notifyOrder(Long orderId, PayMethod payMethod, String transactionId) {
  537. log.info("订单回调 orderId: {}, payMethod: {}, transactionId: {}", orderId, payMethod, transactionId);
  538. // 取消订单与订单回调不能同时进行,需要抢锁
  539. if (!getOrderLock(orderId)) {
  540. log.info("订单回调失败 orderId: {} redis锁定, 重新发送到队列", orderId);
  541. rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
  542. new OrderNotifyEvent(orderId, payMethod, transactionId, System.currentTimeMillis()));
  543. return;
  544. }
  545. try {
  546. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  547. Collection collection = collectionRepo.findById(order.getCollectionId())
  548. .orElseThrow(new BusinessException("藏品不存在"));
  549. User user = userRepo.findById(order.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  550. if (order.getStatus() == OrderStatus.NOT_PAID) {
  551. order.setStatus(OrderStatus.PROCESSING);
  552. order.setPayTime(LocalDateTime.now());
  553. order.setTransactionId(transactionId);
  554. order.setPayMethod(payMethod);
  555. if (order.getType() == CollectionType.BLIND_BOX) {
  556. log.info("开始盲盒抽卡 orderId: {}, collectionId: {}", orderId, collection.getId());
  557. BlindBoxItem winItem = null;
  558. try {
  559. winItem = collectionService.draw(collection.getId());
  560. } catch (BusinessException ignored) {
  561. }
  562. if (winItem == null) {
  563. log.info("抽卡失败退款 orderId: {}", orderId);
  564. order.setStatus(OrderStatus.CANCELLED);
  565. order.setCancelTime(LocalDateTime.now());
  566. Map<String, Object> refundParams = new HashMap<>();
  567. refundParams.put("refund_amt", order.getTotalPrice().setScale(2, RoundingMode.HALF_UP)
  568. .toPlainString());
  569. refundParams.put("refund_order_no", String.valueOf(snowflakeIdWorker.nextId()));
  570. try {
  571. Map<String, Object> response = Refund.create(transactionId, refundParams);
  572. } catch (BaseAdaPayException e) {
  573. e.printStackTrace();
  574. }
  575. orderRepo.save(order);
  576. throw new BusinessException("抽卡失败, 已退款 " + orderId);
  577. }
  578. log.info("抽卡成功 orderId: {}, collectionId: {}, winCollectionId: {}", orderId, collection.getId(), winItem.getCollectionId());
  579. order.setWinCollectionId(winItem.getCollectionId());
  580. orderRepo.save(order);
  581. //藏品其他信息/是否vip
  582. // CollectionPrivilege collectionPrivilege = collectionPrivilegeRepo.findByCollectionId(order.getCollectionId());
  583. // if (ObjectUtils.isNotEmpty(collectionPrivilege)) {
  584. // if (collectionPrivilege.isVip()) {
  585. // //更新vip信息
  586. // userRepo.updateVipPurchase(order.getUserId(), 1);
  587. // }
  588. // }
  589. assetService.createAsset(winItem, user, order.getId(), order.getPrice(), "出售",
  590. winItem.getTotal() > 1 ? collectionService.getNextNumber(winItem.getCollectionId()) : null,
  591. collection.getHoldDays());
  592. } else {
  593. if (collection.getSource() == CollectionSource.TRANSFER) {
  594. orderRepo.save(order);
  595. Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
  596. assetService.transfer(asset, order.getPrice(), user, "转让", order.getId());
  597. collectionRepo.delete(collection);
  598. // 如果展厅有此藏品
  599. showCollectionRepo.deleteAllByCollectionId(order.getCollectionId());
  600. // 发送短信提醒用户转让成功
  601. if (asset != null && asset.getUserId() != null) {
  602. smsService.sellOut(userRepo.findPhoneById(asset.getUserId()));
  603. }
  604. } else {
  605. orderRepo.save(order);
  606. //藏品其他信息/是否vip
  607. // CollectionPrivilege collectionPrivilege = collectionPrivilegeRepo.findByCollectionId(order.getCollectionId());
  608. // if (ObjectUtils.isNotEmpty(collectionPrivilege)) {
  609. // if (collectionPrivilege.isVip()) {
  610. // //更新vip信息
  611. // userRepo.updateVipPurchase(order.getUserId(), 1);
  612. // }
  613. // }
  614. Asset asset = assetService.createAsset(collection, user, order.getId(), order.getPrice(), "出售",
  615. collection.getTotal() > 1 ? collectionService.getNextNumber(order.getCollectionId()) : null);
  616. if (collection.getType() == CollectionType.SHOWROOM) {
  617. showroomService.save(asset);
  618. }
  619. }
  620. }
  621. commission(order);
  622. if (collection.getAssetId() == null) {
  623. collectionService.increaseSale(order.getCollectionId(), order.getQty());
  624. }
  625. } else {
  626. throw new BusinessException("状态错误 " + order.getStatus());
  627. }
  628. } catch (Exception e) {
  629. ErrorOrder errorOrder = ErrorOrder.builder()
  630. .orderId(orderId)
  631. .transactionId(transactionId)
  632. .payMethod(payMethod)
  633. .build();
  634. if (e instanceof BusinessException) {
  635. log.error("订单回调出错 orderId: {} {}", orderId, e.getMessage());
  636. } else {
  637. log.error("订单回调出错 orderId: " + orderId, e);
  638. }
  639. errorOrder.setErrorMessage(e.getMessage());
  640. errorOrderRepo.save(errorOrder);
  641. }
  642. releaseOrderLock(orderId);
  643. }
  644. @EventListener
  645. public void onCreateAsset(CreateAssetEvent event) {
  646. Asset asset = event.getAsset();
  647. if (asset.getOrderId() != null) {
  648. Order order = orderRepo.findById(asset.getOrderId()).orElse(null);
  649. if (event.isSuccess() && order != null) {
  650. order.setTxHash(asset.getTxHash());
  651. order.setGasUsed(asset.getGasUsed());
  652. order.setBlockNumber(asset.getBlockNumber());
  653. order.setStatus(OrderStatus.FINISH);
  654. orderRepo.save(order);
  655. }
  656. }
  657. }
  658. @EventListener
  659. public void onTransferAsset(TransferAssetEvent event) {
  660. Asset asset = event.getAsset();
  661. Order order = orderRepo.findById(asset.getOrderId()).orElseThrow(new BusinessException("订单不存在"));
  662. if (event.isSuccess()) {
  663. order.setTxHash(asset.getTxHash());
  664. order.setGasUsed(asset.getGasUsed());
  665. order.setBlockNumber(asset.getBlockNumber());
  666. order.setStatus(OrderStatus.FINISH);
  667. orderRepo.save(order);
  668. } else {
  669. log.error("创建asset失败");
  670. }
  671. }
  672. public void cancel(Long id) {
  673. Order order = orderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  674. cancel(order);
  675. }
  676. public void cancel(Order order) {
  677. // 取消订单与订单回调不能同时进行,需要抢锁
  678. if (!getOrderLock(order.getId())) {
  679. log.error("订单取消失败 {}, redis锁了", order.getId());
  680. return;
  681. }
  682. try {
  683. if (order.getStatus() != OrderStatus.NOT_PAID) {
  684. throw new BusinessException("已支付订单无法取消");
  685. }
  686. // 查询adapay支付记录,如果已经支付,则不能取消
  687. Set<Object> transactionIds = redisTemplate.opsForSet().members(RedisKeys.PAY_RECORD + order.getId());
  688. if (transactionIds != null && transactionIds.size() > 0) {
  689. AtomicInteger succeeded = new AtomicInteger();
  690. AtomicInteger pending = new AtomicInteger();
  691. transactionIds.parallelStream().forEach(s -> {
  692. String transactionIdStr = Optional.ofNullable(s).map(Object::toString).orElse("");
  693. String transactionId = null;
  694. String merchant = null;
  695. if (transactionIdStr.contains("#")) {
  696. String[] arr = transactionIdStr.split("#");
  697. merchant = arr[0];
  698. transactionId = arr[1];
  699. } else {
  700. merchant = Adapay.defaultMerchantKey;
  701. transactionId = transactionIdStr;
  702. }
  703. try {
  704. Map<String, Object> map = Payment.query(transactionId, merchant);
  705. if ("succeeded".equalsIgnoreCase(MapUtils.getString(map, "status"))) {
  706. succeeded.getAndIncrement();
  707. }
  708. if ("pending".equalsIgnoreCase(MapUtils.getString(map, "status"))) {
  709. pending.getAndIncrement();
  710. // 未支付的订单调用关单接口
  711. Map<String, Object> closeParams = new HashMap<>();
  712. closeParams.put("payment_id", transactionId);
  713. Payment.close(closeParams, merchant);
  714. }
  715. } catch (BaseAdaPayException e) {
  716. log.error("adapay error", e);
  717. }
  718. });
  719. // if (succeeded.get() + pending.get() > 0) {
  720. if (succeeded.get() > 0) {
  721. if (ChronoUnit.MINUTES.between(order.getCreatedAt(), LocalDateTime.now()) < 10) {
  722. throw new BusinessException("订单已经支付成功或待支付,不能取消 " + order.getId());
  723. }
  724. }
  725. }
  726. CollectionSource source = Optional.ofNullable(order.getSource()).orElseGet(() ->
  727. collectionRepo.findById(order.getCollectionId()).map(Collection::getSource).orElse(null));
  728. if (source == CollectionSource.TRANSFER) {
  729. Asset asset = assetRepo.findById(order.getAssetId()).orElse(null);
  730. if (asset != null) {
  731. log.info("set normal cancelOrder {}", order.getId());
  732. asset.setStatus(AssetStatus.NORMAL);
  733. assetRepo.save(asset);
  734. }
  735. collectionRepo.setOnShelf(order.getCollectionId(), true);
  736. }
  737. collectionService.increaseStock(order.getCollectionId(), order.getQty());
  738. order.setStatus(OrderStatus.CANCELLED);
  739. order.setCancelTime(LocalDateTime.now());
  740. orderRepo.save(order);
  741. if (order.getCouponId() != null) {
  742. userCouponRepo.findById(order.getCouponId()).ifPresent(coupon -> {
  743. coupon.setUsed(false);
  744. coupon.setUseTime(null);
  745. userCouponRepo.save(coupon);
  746. });
  747. }
  748. //加上积分
  749. if (ObjectUtils.isNotEmpty(order.getVipPoint()) && order.getVipPoint() > 0) {
  750. userRepo.updateVipPoint(order.getUserId(), order.getVipPoint());
  751. log.info("取消加积分用户ID:{},订单ID:{},积分:{}", order.getUserId(), order.getId(), order.getVipPoint());
  752. }
  753. if (order.isVip()) {
  754. collectionService.decreaseQuota(order.getCollectionId(), 1);
  755. log.info("取消加藏品额度CollectionId:{}", order.getCollectionId());
  756. }
  757. rocketMQTemplate.syncSend(generalProperties.getUpdateQuotaTopic(), order.getCollectionId(), 10000);
  758. log.info("取消订单{}", order.getId());
  759. } catch (Exception e) {
  760. if (e instanceof BusinessException) {
  761. log.error(e.getMessage());
  762. } else {
  763. log.error("订单取消错误 orderId: " + order.getId(), e);
  764. }
  765. }
  766. releaseOrderLock(order.getId());
  767. }
  768. public void refundCancelled(Order order) {
  769. }
  770. public void setNumber() {
  771. for (Collection collection : collectionRepo.findAll()) {
  772. if (collection.getSource() != CollectionSource.OFFICIAL) continue;
  773. collection.setCurrentNumber(0);
  774. collectionRepo.save(collection);
  775. for (Asset asset : assetRepo.findByCollectionId(collection.getId())) {
  776. if (asset.getStatus() == AssetStatus.GIFTED || asset.getStatus() == AssetStatus.TRANSFERRED) {
  777. } else {
  778. asset.setNumber(collectionService.getNextNumber(collection.getId()));
  779. assetRepo.save(asset);
  780. }
  781. }
  782. }
  783. }
  784. public void setNumberRecursive(Asset asset) {
  785. }
  786. @Scheduled(cron = "0 0 4 * * ?")
  787. public void setSales() {
  788. if (generalProperties.isNotifyServer()) {
  789. return;
  790. }
  791. List<User> minters = userRepo.findByAuthoritiesContains(Authority.get(AuthorityName.ROLE_MINTER));
  792. for (User minter : minters) {
  793. userRepo.setSales(minter.getId(), (int) orderRepo.countSales(minter.getId()));
  794. }
  795. }
  796. public void commission(Order order) {
  797. if (order.getInvitor() != null) {
  798. userRepo.findById(order.getInvitor()).ifPresent(user -> {
  799. BigDecimal shareRatio = user.getShareRatio();
  800. if (StringUtils.isNotBlank(user.getSettleAccountId()) &&
  801. shareRatio != null && shareRatio.compareTo(BigDecimal.ZERO) > 0) {
  802. BigDecimal totalPrice = order.getTotalPrice().subtract(order.getGasPrice());
  803. commissionRecordRepo.save(CommissionRecord.builder()
  804. .orderId(order.getId())
  805. .collectionId(order.getCollectionId())
  806. .name(order.getName())
  807. .totalPrice(totalPrice)
  808. .nickname(user.getNickname())
  809. .userId(user.getId())
  810. .shareRatio(user.getShareRatio())
  811. .phone(user.getPhone())
  812. .shareAmount(totalPrice.multiply(shareRatio)
  813. .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP))
  814. .build());
  815. }
  816. });
  817. }
  818. }
  819. public Object queryCreateOrder(String id) {
  820. Object res = redisTemplate.opsForValue().get(RedisKeys.CREATE_ORDER + id);
  821. if (res != null) {
  822. if (res instanceof Map) {
  823. if (MapUtils.getBooleanValue((Map) res, "success", false)) {
  824. Order order = (Order) MapUtils.getObject((Map) res, "data");
  825. if (!SecurityUtils.getAuthenticatedUser().getId().equals(order.getUserId())) {
  826. log.error("queryCreateOrder userId错误 requestUserId={} orderUserId={}",
  827. SecurityUtils.getAuthenticatedUser().getId(), order.getUserId());
  828. return null;
  829. }
  830. }
  831. }
  832. }
  833. return res;
  834. }
  835. // 获取订单锁,有效时间1小时
  836. public boolean getOrderLock(Long orderId) {
  837. BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.ORDER_LOCK + orderId);
  838. Boolean flag = ops.setIfAbsent(1, 1, TimeUnit.HOURS);
  839. return Boolean.TRUE.equals(flag);
  840. }
  841. // 释放订单锁
  842. public void releaseOrderLock(Long orderId) {
  843. redisTemplate.delete(RedisKeys.ORDER_LOCK + orderId);
  844. }
  845. public void calcSettle(LocalDateTime start, LocalDateTime end, OutputStream outputStream) {
  846. List<Order> orders = orderRepo.findByCreatedAtBetweenAndSourceAndStatusIn(start, end, CollectionSource.TRANSFER, Arrays.asList(OrderStatus.PROCESSING, OrderStatus.FINISH));
  847. List<Asset> assets = assetRepo.findAllById(orders.stream().map(Order::getAssetId).collect(Collectors.toSet()));
  848. List<UserBankCard> bankCards = userBankCardRepo.findByUserIdIn(assets.stream().map(Asset::getUserId).collect(Collectors.toSet()));
  849. List<MarketSettlement> settlements = new ArrayList<>();
  850. for (Order order : orders) {
  851. BigDecimal amount = order.getTotalPrice()
  852. .subtract(order.getGasPrice())
  853. .multiply(new BigDecimal("100")
  854. .subtract(BigDecimal.valueOf(order.getServiceCharge()))
  855. .subtract(BigDecimal.valueOf(order.getRoyalties()))
  856. .divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP))
  857. .setScale(2, RoundingMode.HALF_UP);
  858. Long userId = assets.stream().filter(a -> a.getId().equals(order.getAssetId())).map(Asset::getUserId).findAny().orElse(null);
  859. if (userId != null) {
  860. UserBankCard userBankCard = bankCards.stream().filter(b -> b.getUserId().equals(userId)).findAny().orElse(null);
  861. MarketSettlement marketSettlement = settlements.stream().filter(s -> s.getUserId().equals(userId)).findAny().orElse(null);
  862. if (marketSettlement == null) {
  863. marketSettlement = new MarketSettlement(userId,
  864. Optional.ofNullable(userBankCard).map(UserBankCard::getRealName).orElse(null),
  865. Optional.ofNullable(userBankCard).map(UserBankCard::getBankNo).orElse(null),
  866. amount);
  867. settlements.add(marketSettlement);
  868. } else {
  869. marketSettlement.setAmount(marketSettlement.getAmount()
  870. .add(amount));
  871. }
  872. }
  873. }
  874. EasyExcel.write(outputStream, MarketSettlement.class).sheet("sheet").doWrite(settlements);
  875. }
  876. }