OrderService.java 42 KB

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