OrderService.java 42 KB

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