OrderService.java 41 KB

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