OrderService.java 44 KB

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