OrderService.java 43 KB

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