OrderService.java 41 KB

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