OrderService.java 41 KB

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