OrderService.java 37 KB

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