OrderService.java 38 KB

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