OrderService.java 41 KB

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