OrderService.java 40 KB

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