OrderPayService.java 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. package com.izouma.nineth.service;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.alipay.api.AlipayApiException;
  4. import com.alipay.api.AlipayClient;
  5. import com.alipay.api.request.AlipayTradePrecreateRequest;
  6. import com.alipay.api.response.AlipayTradePrecreateResponse;
  7. import com.izouma.nineth.config.AlipayProperties;
  8. import com.izouma.nineth.config.Constants;
  9. import com.izouma.nineth.config.GeneralProperties;
  10. import com.izouma.nineth.domain.*;
  11. import com.izouma.nineth.dto.PayQuery;
  12. import com.izouma.nineth.dto.UserBankCard;
  13. import com.izouma.nineth.enums.*;
  14. import com.izouma.nineth.event.OrderNotifyEvent;
  15. import com.izouma.nineth.exception.BusinessException;
  16. import com.izouma.nineth.repo.*;
  17. import com.izouma.nineth.utils.SnowflakeIdWorker;
  18. import lombok.AllArgsConstructor;
  19. import lombok.extern.slf4j.Slf4j;
  20. import org.apache.commons.lang3.StringUtils;
  21. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  22. import org.springframework.cache.annotation.Cacheable;
  23. import org.springframework.security.crypto.password.PasswordEncoder;
  24. import org.springframework.stereotype.Service;
  25. import org.springframework.web.context.request.RequestContextHolder;
  26. import org.springframework.web.context.request.ServletRequestAttributes;
  27. import java.math.BigDecimal;
  28. import java.net.URLEncoder;
  29. import java.nio.charset.StandardCharsets;
  30. import java.time.LocalDateTime;
  31. import java.util.Map;
  32. import java.util.Objects;
  33. import java.util.Optional;
  34. import java.util.stream.Stream;
  35. @Service
  36. @Slf4j
  37. @AllArgsConstructor
  38. public class OrderPayService {
  39. private static String PAY_CHANNEL = Constants.PayChannel.SAND;
  40. private final OrderService orderService;
  41. private final OrderRepo orderRepo;
  42. private final MintOrderRepo mintOrderRepo;
  43. private final GiftOrderRepo giftOrderRepo;
  44. private final SandPayService sandPayService;
  45. private final HMPayService hmPayService;
  46. private final GeneralProperties generalProperties;
  47. private final UserBalanceService userBalanceService;
  48. private final RocketMQTemplate rocketMQTemplate;
  49. private final GiftOrderService giftOrderService;
  50. private final MintOrderService mintOrderService;
  51. private final UserRepo userRepo;
  52. private final SnowflakeIdWorker snowflakeIdWorker;
  53. private final RechargeOrderRepo rechargeOrderRepo;
  54. private final SysConfigService sysConfigService;
  55. private final PasswordEncoder passwordEncoder;
  56. private final PayEaseService payEaseService;
  57. private final UserBankCardRepo userBankCardRepo;
  58. private final AuctionOrderRepo auctionOrderRepo;
  59. private final AuctionOrderService auctionOrderService;
  60. private final IdentityAuthRepo identityAuthRepo;
  61. private final AlipayClient alipayClient;
  62. private final AlipayProperties alipayProperties;
  63. private final AlipayService alipayService;
  64. private final PhotoAssetRepo photoAssetRepo;
  65. private final PhotoAssetService photoAssetService;
  66. public static void setPayChannel(String payChannel) {
  67. log.info("set pay channel {}", payChannel);
  68. if (Constants.PayChannel.HM.equals(payChannel) || Constants.PayChannel.SAND.equals(payChannel)) {
  69. PAY_CHANNEL = payChannel;
  70. }
  71. }
  72. @Cacheable(value = "payOrder", key = "'order#'+#orderId")
  73. public String payOrder(Long orderId) {
  74. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  75. if (order.getStatus() != OrderStatus.NOT_PAID) {
  76. throw new BusinessException("订单状态错误");
  77. }
  78. switch (PAY_CHANNEL) {
  79. case Constants.PayChannel.SAND:
  80. return sandPayService.pay(orderId + "", order.getName(), order.getTotalPrice(),
  81. order.getCreatedAt().plusMinutes(3), "order");
  82. case Constants.PayChannel.HM:
  83. return hmPayService.requestAlipay(orderId + "", order.getTotalPrice(), order.getName(),
  84. HMPayService.getTimeout(order.getCreatedAt(), 180), Constants.OrderNotifyType.ORDER,
  85. generalProperties.resolveFrontUrl(order.getCompanyId(), "/orderDetail?id=" + orderId));
  86. }
  87. throw new BusinessException(Constants.PAY_ERR_MSG);
  88. }
  89. private String aliRequest(Long orderId, BigDecimal amount, String subject, String type) {
  90. AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
  91. request.setNotifyUrl(alipayProperties.getNotifyUrl());
  92. JSONObject bizContent = new JSONObject();
  93. bizContent.put("out_trade_no", orderId + "");
  94. bizContent.put("total_amount", amount);
  95. bizContent.put("subject", subject);
  96. JSONObject body = new JSONObject();
  97. body.put("type", type);
  98. body.put("orderId", orderId);
  99. bizContent.put("body", body.toString());
  100. request.setBizContent(bizContent.toString());
  101. AlipayTradePrecreateResponse response = null;
  102. try {
  103. response = alipayClient.execute(request);
  104. } catch (AlipayApiException e) {
  105. e.printStackTrace();
  106. throw new BusinessException(Constants.PAY_ERR_MSG, e.getErrMsg());
  107. }
  108. if (response.isSuccess()) {
  109. return response.getQrCode();
  110. } else {
  111. throw new BusinessException(response.getSubMsg());
  112. }
  113. }
  114. @Cacheable(value = "payOrder", key = "'order#'+#orderId")
  115. public String payOrderAli(Long orderId) {
  116. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  117. if (order.getStatus() != OrderStatus.NOT_PAID) {
  118. throw new BusinessException("订单状态错误");
  119. }
  120. String qrCode = aliRequest(orderId, order.getTotalPrice(), order.getName(), Constants.OrderNotifyType.ORDER);
  121. String ua = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
  122. .getHeader("User-Agent");
  123. if (ua.toLowerCase().contains("micromessenger")) {
  124. return "/static/wx_alipay_bridge.html?payUrl=" + URLEncoder
  125. .encode(Constants.ALIPAY_URL_SCHEME + qrCode, StandardCharsets.UTF_8)
  126. + "&orderId=" + orderId + "&type=order&returnUrl="
  127. + URLEncoder
  128. .encode(generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"), StandardCharsets.UTF_8);
  129. } else {
  130. return Constants.ALIPAY_URL_SCHEME + qrCode;
  131. }
  132. }
  133. @Cacheable(value = "payOrder", key = "'order#'+#orderId")
  134. public String payOrderQuick(Long orderId) {
  135. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  136. if (order.getStatus() != OrderStatus.NOT_PAID) {
  137. throw new BusinessException("订单状态错误");
  138. }
  139. return sandPayService.payQuick(orderId + "", order.getName(), order.getTotalPrice(),
  140. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.ORDER,
  141. generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"));
  142. }
  143. @Cacheable(value = "payOrder", key = "'order#'+#orderId")
  144. public String payOrderQuickBind(Long orderId) {
  145. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  146. if (order.getStatus() != OrderStatus.NOT_PAID) {
  147. throw new BusinessException("订单状态错误");
  148. }
  149. IdentityAuth identityAuth = identityAuthRepo
  150. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(order.getUserId(), AuthStatus.SUCCESS)
  151. .orElseThrow(new BusinessException("请先完成实名认证"));
  152. return sandPayService.payQuickBind(orderId + "", order.getName(), order.getTotalPrice(),
  153. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.ORDER,
  154. generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"),
  155. order.getUserId(), identityAuth.getRealName(), identityAuth.getIdNo());
  156. }
  157. public void payOrderBalance(Long orderId, Long userId, String tradeCode) {
  158. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  159. if (order.getStatus() != OrderStatus.NOT_PAID) {
  160. throw new BusinessException("订单状态错误");
  161. }
  162. checkTradeCode(userId, tradeCode, order.getUserId());
  163. BalanceRecord record = userBalanceService
  164. .balancePay(order.getUserId(), order.getTotalPrice(), orderId, order.getName());
  165. rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
  166. new OrderNotifyEvent(orderId, PayMethod.BALANCE, record.getId().toString(),
  167. System.currentTimeMillis()));
  168. }
  169. @Cacheable(value = "payOrder", key = "'order#'+#orderId")
  170. public Map<String, Object> payOrderAgreement(Long orderId, String bindCardId) {
  171. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  172. if (order.getStatus() != OrderStatus.NOT_PAID) {
  173. throw new BusinessException("订单状态错误");
  174. }
  175. if (StringUtils.isEmpty(bindCardId)) {
  176. bindCardId = userBankCardRepo.findByUserId(order.getUserId())
  177. .stream().map(UserBankCard::getBindCardId).findFirst().orElse(null);
  178. }
  179. if (StringUtils.isEmpty(bindCardId)) {
  180. throw new BusinessException("请先绑定银行卡");
  181. }
  182. return payEaseService.pay(order.getName(), orderId.toString(), order.getTotalPrice(),
  183. order.getUserId().toString(), bindCardId, Constants.OrderNotifyType.ORDER);
  184. }
  185. public void confirmOrderAgreement(String requestId, String paymentOrderId, String code) {
  186. try {
  187. payEaseService.payConfirm(requestId, paymentOrderId, code);
  188. } catch (BusinessException e) {
  189. try {
  190. new Thread(() -> {
  191. orderService.cancel(Long.parseLong(requestId));
  192. }).start();
  193. } catch (Exception ee) {
  194. }
  195. throw e;
  196. }
  197. }
  198. @Cacheable(value = "payOrder", key = "'gift#'+#orderId")
  199. public String payGiftOrder(Long orderId) {
  200. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  201. if (order.getStatus() != OrderStatus.NOT_PAID) {
  202. throw new BusinessException("订单状态错误");
  203. }
  204. switch (PAY_CHANNEL) {
  205. case Constants.PayChannel.SAND:
  206. return sandPayService.pay(orderId + "", "转赠" + order.getAssetId(), order.getGasPrice(),
  207. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.GIFT);
  208. case Constants.PayChannel.HM:
  209. return hmPayService.requestAlipay(orderId + "", order.getGasPrice(),
  210. "转赠" + order.getAssetId(),
  211. HMPayService.getTimeout(order.getCreatedAt(), 180),
  212. Constants.OrderNotifyType.GIFT, generalProperties
  213. .resolveFrontUrl(order.getCompanyId(), "/store"));
  214. }
  215. throw new BusinessException(Constants.PAY_ERR_MSG);
  216. }
  217. @Cacheable(value = "payOrder", key = "'gift#'+#orderId")
  218. public String payGiftAli(Long orderId) {
  219. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  220. if (order.getStatus() != OrderStatus.NOT_PAID) {
  221. throw new BusinessException("订单状态错误");
  222. }
  223. String qrCode = aliRequest(orderId, order.getGasPrice(), "转赠", Constants.OrderNotifyType.GIFT);
  224. String ua = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
  225. .getHeader("User-Agent");
  226. if (ua.toLowerCase().contains("micromessenger")) {
  227. return "/static/wx_alipay_bridge.html?payUrl=" + URLEncoder
  228. .encode(Constants.ALIPAY_URL_SCHEME + qrCode, StandardCharsets.UTF_8)
  229. + "&orderId=" + orderId + "&type=gift&returnUrl="
  230. + URLEncoder
  231. .encode(generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"), StandardCharsets.UTF_8);
  232. } else {
  233. return Constants.ALIPAY_URL_SCHEME + qrCode;
  234. }
  235. }
  236. @Cacheable(value = "payOrder", key = "'gift#'+#orderId")
  237. public String payGiftQuick(Long orderId) {
  238. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  239. if (order.getStatus() != OrderStatus.NOT_PAID) {
  240. throw new BusinessException("订单状态错误");
  241. }
  242. return sandPayService.payQuick(orderId + "", "转赠" + order.getAssetId(), order.getGasPrice(),
  243. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.GIFT,
  244. generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"));
  245. }
  246. @Cacheable(value = "payOrder", key = "'gift#'+#orderId")
  247. public String payGiftQuickBind(Long orderId) {
  248. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  249. if (order.getStatus() != OrderStatus.NOT_PAID) {
  250. throw new BusinessException("订单状态错误");
  251. }
  252. IdentityAuth identityAuth = identityAuthRepo
  253. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(order.getUserId(), AuthStatus.SUCCESS)
  254. .orElseThrow(new BusinessException("请先完成实名认证"));
  255. return sandPayService.payQuickBind(orderId + "", "转赠" + order.getAssetId(), order.getGasPrice(),
  256. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.GIFT,
  257. generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"),
  258. order.getUserId(), identityAuth.getRealName(), identityAuth.getIdNo());
  259. }
  260. public void payGiftBalance(Long orderId, Long userId, String tradeCode) {
  261. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  262. if (order.getStatus() != OrderStatus.NOT_PAID) {
  263. throw new BusinessException("订单状态错误");
  264. }
  265. checkTradeCode(userId, tradeCode, order.getUserId());
  266. BalanceRecord record = userBalanceService.balancePay(order.getUserId(), order.getGasPrice(), orderId, "转赠");
  267. giftOrderService.giftNotify(orderId, PayMethod.BALANCE, record.getId().toString());
  268. }
  269. @Cacheable(value = "payOrder", key = "'gift#'+#orderId")
  270. public Map<String, Object> payGiftOrderAgreement(Long orderId, String bindCardId) {
  271. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  272. if (order.getStatus() != OrderStatus.NOT_PAID) {
  273. throw new BusinessException("订单状态错误");
  274. }
  275. if (StringUtils.isEmpty(bindCardId)) {
  276. bindCardId = userBankCardRepo.findByUserId(order.getUserId())
  277. .stream().map(UserBankCard::getBindCardId).findFirst().orElse(null);
  278. }
  279. if (StringUtils.isEmpty(bindCardId)) {
  280. throw new BusinessException("请先绑定银行卡");
  281. }
  282. return payEaseService.pay("转赠" + order.getAssetId(), orderId.toString(), order.getGasPrice(),
  283. order.getUserId().toString(), bindCardId, Constants.OrderNotifyType.GIFT);
  284. }
  285. @Cacheable(value = "payOrder", key = "'mintOrder#'+#orderId")
  286. public String payMintOrder(Long orderId) {
  287. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  288. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  289. throw new BusinessException("订单状态错误");
  290. }
  291. switch (PAY_CHANNEL) {
  292. case Constants.PayChannel.SAND:
  293. return sandPayService.pay(orderId + "", "铸造活动:" + order.getMintActivityId(),
  294. order.getGasPrice(), order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.MINT);
  295. case Constants.PayChannel.HM:
  296. return hmPayService.requestAlipay(orderId + "", order.getGasPrice(),
  297. "铸造活动:" + order.getMintActivityId(),
  298. HMPayService.getTimeout(order.getCreatedAt(), 180),
  299. Constants.OrderNotifyType.MINT, generalProperties
  300. .resolveFrontUrl(order.getCompanyId(), "/home"));
  301. }
  302. throw new BusinessException("绿洲宇宙冷却系统已启动,请稍后支付");
  303. }
  304. @Cacheable(value = "payOrder", key = "'mintOrder#'+#orderId")
  305. public String payMintAli(Long orderId) {
  306. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  307. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  308. throw new BusinessException("订单状态错误");
  309. }
  310. String qrCode = aliRequest(orderId, order.getGasPrice(), "铸造活动:" + order
  311. .getMintActivityId(), Constants.OrderNotifyType.MINT);
  312. String ua = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
  313. .getHeader("User-Agent");
  314. if (ua.toLowerCase().contains("micromessenger")) {
  315. return "/static/wx_alipay_bridge.html?payUrl=" + URLEncoder
  316. .encode(Constants.ALIPAY_URL_SCHEME + qrCode, StandardCharsets.UTF_8)
  317. + "&orderId=" + orderId + "&type=mintOrder&returnUrl="
  318. + URLEncoder
  319. .encode(generalProperties.resolveFrontUrl(order.getCompanyId(), "/home"), StandardCharsets.UTF_8);
  320. } else {
  321. return Constants.ALIPAY_URL_SCHEME + qrCode;
  322. }
  323. }
  324. @Cacheable(value = "payOrder", key = "'mintOrder#'+#orderId")
  325. public String payMintQuick(Long orderId) {
  326. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  327. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  328. throw new BusinessException("订单状态错误");
  329. }
  330. return sandPayService.payQuick(orderId + "", "铸造活动:" + order.getMintActivityId(),
  331. order.getGasPrice(), order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.MINT,
  332. generalProperties.resolveFrontUrl(order.getCompanyId(), "/home"));
  333. }
  334. @Cacheable(value = "payOrder", key = "'mintOrder#'+#orderId")
  335. public String payMintQuickBind(Long orderId) {
  336. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  337. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  338. throw new BusinessException("订单状态错误");
  339. }
  340. IdentityAuth identityAuth = identityAuthRepo
  341. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(order.getUserId(), AuthStatus.SUCCESS)
  342. .orElseThrow(new BusinessException("请先完成实名认证"));
  343. return sandPayService.payQuickBind(orderId + "", "铸造活动:" + order.getMintActivityId(),
  344. order.getGasPrice(), order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.MINT,
  345. generalProperties.resolveFrontUrl(order.getCompanyId(), "/home"),
  346. order.getUserId(), identityAuth.getRealName(), identityAuth.getIdNo());
  347. }
  348. public void payMintOrderBalance(Long orderId, Long userId, String tradeCode) {
  349. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  350. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  351. throw new BusinessException("订单状态错误");
  352. }
  353. checkTradeCode(userId, tradeCode, order.getUserId());
  354. BalanceRecord record = userBalanceService.balancePay(order.getUserId(), order.getGasPrice(), orderId, "铸造活动");
  355. mintOrderService.mintNotify(orderId, PayMethod.BALANCE, record.getId().toString());
  356. }
  357. private void checkTradeCode(Long userId, String tradeCode, Long orderUserId) {
  358. if (!Objects.equals(orderUserId, userId)) {
  359. throw new BusinessException("订单不属于该用户");
  360. }
  361. String encodedPwd = userRepo.findTradeCode(userId);
  362. if (StringUtils.isEmpty(encodedPwd)) {
  363. throw new BusinessException("请先设置交易密码");
  364. }
  365. if (!passwordEncoder.matches(tradeCode, encodedPwd)) {
  366. throw new BusinessException("交易码错误");
  367. }
  368. }
  369. @Cacheable(value = "payOrder", key = "'mint#'+#orderId")
  370. public Map<String, Object> payMintOrderAgreement(Long orderId, String bindCardId) {
  371. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  372. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  373. throw new BusinessException("订单状态错误");
  374. }
  375. if (StringUtils.isEmpty(bindCardId)) {
  376. bindCardId = userBankCardRepo.findByUserId(order.getUserId())
  377. .stream().map(UserBankCard::getBindCardId).findFirst().orElse(null);
  378. }
  379. if (StringUtils.isEmpty(bindCardId)) {
  380. throw new BusinessException("请先绑定银行卡");
  381. }
  382. return payEaseService.pay("铸造活动:" + order.getMintActivityId(), orderId.toString(), order.getGasPrice(),
  383. order.getUserId().toString(), bindCardId, Constants.OrderNotifyType.MINT);
  384. }
  385. private Long getCompanyId() {
  386. Long companyId = 1L;
  387. try {
  388. String hCompanyId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
  389. .getHeader("companyId");
  390. if (StringUtils.isNotBlank(hCompanyId)) {
  391. companyId = Long.parseLong(hCompanyId);
  392. }
  393. } catch (Exception ignored) {
  394. }
  395. return companyId;
  396. }
  397. public String recharge(Long userId, BigDecimal amount) {
  398. BigDecimal minAmount = sysConfigService.getBigDecimal("min_recharge_amount");
  399. if (amount.compareTo(minAmount) < 0) {
  400. throw new BusinessException("充值金额不能小于" + minAmount);
  401. }
  402. if (amount.compareTo(new BigDecimal("50000")) > 0) {
  403. throw new BusinessException("充值金额不能大于50000");
  404. }
  405. RechargeOrder order = RechargeOrder.builder()
  406. .id(snowflakeIdWorker.nextId())
  407. .userId(userId)
  408. .amount(amount)
  409. .status(OrderStatus.NOT_PAID)
  410. .build();
  411. rechargeOrderRepo.save(order);
  412. switch (PAY_CHANNEL) {
  413. case Constants.PayChannel.SAND:
  414. return sandPayService.pay(order.getId() + "", "余额充值", order.getAmount(),
  415. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.RECHARGE);
  416. case Constants.PayChannel.HM:
  417. return hmPayService.requestAlipay(order.getId() + "", order.getAmount(),
  418. "余额充值",
  419. HMPayService.getTimeout(order.getCreatedAt(), 180),
  420. Constants.OrderNotifyType.RECHARGE, generalProperties.resolveFrontUrl(getCompanyId(), "/home"));
  421. }
  422. throw new BusinessException("绿洲宇宙冷却系统已启动,请稍后支付");
  423. }
  424. public String payRechargeAli(Long userId, BigDecimal amount) {
  425. BigDecimal minAmount = sysConfigService.getBigDecimal("min_recharge_amount");
  426. if (amount.compareTo(minAmount) < 0) {
  427. throw new BusinessException("充值金额不能小于" + minAmount);
  428. }
  429. if (amount.compareTo(new BigDecimal("50000")) > 0) {
  430. throw new BusinessException("充值金额不能大于50000");
  431. }
  432. RechargeOrder order = RechargeOrder.builder()
  433. .id(snowflakeIdWorker.nextId())
  434. .userId(userId)
  435. .amount(amount)
  436. .status(OrderStatus.NOT_PAID)
  437. .build();
  438. rechargeOrderRepo.save(order);
  439. String qrCode = aliRequest(order.getId(), order.getAmount(), "余额充值", Constants.OrderNotifyType.RECHARGE);
  440. String ua = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
  441. .getHeader("User-Agent");
  442. if (ua.toLowerCase().contains("micromessenger")) {
  443. return "/static/wx_alipay_bridge.html?payUrl=" + URLEncoder
  444. .encode(Constants.ALIPAY_URL_SCHEME + qrCode, StandardCharsets.UTF_8)
  445. + "&orderId=" + order.getId() + "&type=recharge&returnUrl="
  446. + URLEncoder
  447. .encode(generalProperties.resolveFrontUrl(getCompanyId(), "/home"), StandardCharsets.UTF_8);
  448. } else {
  449. return Constants.ALIPAY_URL_SCHEME + qrCode;
  450. }
  451. }
  452. public Map<String, Object> rechargeAgreement(Long userId, BigDecimal amount, String bindCardId) {
  453. BigDecimal minAmount = sysConfigService.getBigDecimal("min_recharge_amount");
  454. if (amount.compareTo(minAmount) < 0) {
  455. throw new BusinessException("充值金额不能小于" + minAmount);
  456. }
  457. if (amount.compareTo(new BigDecimal("50000")) > 0) {
  458. throw new BusinessException("充值金额不能大于50000");
  459. }
  460. RechargeOrder order = RechargeOrder.builder()
  461. .id(snowflakeIdWorker.nextId())
  462. .userId(userId)
  463. .amount(amount)
  464. .status(OrderStatus.NOT_PAID)
  465. .build();
  466. rechargeOrderRepo.save(order);
  467. if (StringUtils.isEmpty(bindCardId)) {
  468. bindCardId = userBankCardRepo.findByUserId(order.getUserId())
  469. .stream().map(UserBankCard::getBindCardId).findFirst().orElse(null);
  470. }
  471. if (StringUtils.isEmpty(bindCardId)) {
  472. throw new BusinessException("请先绑定银行卡");
  473. }
  474. return payEaseService.pay("余额充值", order.getId().toString(), order.getAmount(),
  475. order.getUserId().toString(), bindCardId, Constants.OrderNotifyType.RECHARGE);
  476. }
  477. public String rechargeQuick(Long userId, BigDecimal amount, Long companyId) {
  478. BigDecimal minAmount = sysConfigService.getBigDecimal("min_recharge_amount");
  479. if (amount.compareTo(minAmount) < 0) {
  480. throw new BusinessException("充值金额不能小于" + minAmount);
  481. }
  482. if (amount.compareTo(new BigDecimal("50000")) > 0) {
  483. throw new BusinessException("充值金额不能大于50000");
  484. }
  485. RechargeOrder order = RechargeOrder.builder()
  486. .id(snowflakeIdWorker.nextId())
  487. .userId(userId)
  488. .amount(amount)
  489. .status(OrderStatus.NOT_PAID)
  490. .build();
  491. rechargeOrderRepo.save(order);
  492. return sandPayService.payQuick(order.getId() + "", "余额充值",
  493. order.getAmount(), LocalDateTime.now().plusMinutes(3), Constants.OrderNotifyType.RECHARGE,
  494. generalProperties.resolveFrontUrl(companyId, "/home"));
  495. }
  496. public String rechargeQuickBind(Long userId, BigDecimal amount, Long companyId) {
  497. BigDecimal minAmount = sysConfigService.getBigDecimal("min_recharge_amount");
  498. if (amount.compareTo(minAmount) < 0) {
  499. throw new BusinessException("充值金额不能小于" + minAmount);
  500. }
  501. if (amount.compareTo(new BigDecimal("50000")) > 0) {
  502. throw new BusinessException("充值金额不能大于50000");
  503. }
  504. IdentityAuth identityAuth = identityAuthRepo
  505. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
  506. .orElseThrow(new BusinessException("请先完成实名认证"));
  507. RechargeOrder order = RechargeOrder.builder()
  508. .id(snowflakeIdWorker.nextId())
  509. .userId(userId)
  510. .amount(amount)
  511. .status(OrderStatus.NOT_PAID)
  512. .build();
  513. rechargeOrderRepo.save(order);
  514. return sandPayService.payQuickBind(order.getId() + "", "余额充值",
  515. order.getAmount(), LocalDateTime.now().plusMinutes(3), Constants.OrderNotifyType.RECHARGE,
  516. generalProperties.resolveFrontUrl(companyId, "/home"),
  517. userId, identityAuth.getRealName(), identityAuth.getIdNo());
  518. }
  519. public JSONObject refund(String orderId, String transactionId, BigDecimal amount, String channel) {
  520. switch (channel) {
  521. case Constants.PayChannel.SAND: {
  522. JSONObject res = sandPayService.refund(orderId, amount);
  523. if (!"000000".equals(res.getJSONObject("head").getString("respCode"))) {
  524. String msg = res.getJSONObject("head").getString("respMsg");
  525. throw new BusinessException("退款失败:" + msg);
  526. }
  527. return res;
  528. }
  529. case Constants.PayChannel.HM: {
  530. JSONObject res = hmPayService.refund(orderId, amount);
  531. if (!"REFUND_SUCCESS".equals(res.getString("sub_code"))) {
  532. String msg = res.getString("msg");
  533. throw new BusinessException("退款失败:" + msg);
  534. }
  535. return res;
  536. }
  537. case Constants.PayChannel.PE: {
  538. JSONObject res = payEaseService.refund(orderId, transactionId, amount);
  539. String status = res.getString("status");
  540. if (!"SUCCESS".equals(status)) {
  541. String error = res.getString("error");
  542. String cause = res.getString("cause");
  543. throw new BusinessException("退款失败:" + error + ";" + cause);
  544. }
  545. return res;
  546. }
  547. case Constants.PayChannel.ALI: {
  548. alipayService.refund(orderId, amount);
  549. return null;
  550. }
  551. }
  552. throw new BusinessException("退款失败");
  553. }
  554. public PayQuery query(String orderId) {
  555. return query(orderId, null);
  556. }
  557. public PayQuery query(String orderId, String channel) {
  558. if (StringUtils.isNotEmpty(channel)) {
  559. switch (channel) {
  560. case Constants.PayChannel.SAND:
  561. return sandPayService.payQuery(orderId);
  562. case Constants.PayChannel.HM:
  563. return hmPayService.payQuery(orderId);
  564. case Constants.PayChannel.PE:
  565. return payEaseService.payQuery(orderId);
  566. }
  567. }
  568. PayQuery query = sandPayService.payQuery(orderId);
  569. if (query == null || !query.isExist()) {
  570. query = hmPayService.payQuery(orderId);
  571. }
  572. if (query == null || !query.isExist()) {
  573. query = payEaseService.payQuery(orderId);
  574. }
  575. if (query == null || !query.isExist()) {
  576. query = alipayService.payQuery(orderId);
  577. }
  578. return Optional.ofNullable(query).orElse(PayQuery.builder().exist(false).build());
  579. }
  580. @Cacheable(value = "payOrder", key = "'auctionOrder#'+#orderId")
  581. public String payAuctionOrder(Long orderId) {
  582. AuctionOrder order = auctionOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  583. if (order.getStatus() != AuctionOrderStatus.NOT_PAID) {
  584. throw new BusinessException("订单状态错误");
  585. }
  586. switch (PAY_CHANNEL) {
  587. case Constants.PayChannel.SAND:
  588. return sandPayService.pay(orderId + "", "拍卖:" + order.getName(), order.getTotalPrice(),
  589. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.AUCTION);
  590. case Constants.PayChannel.HM:
  591. return hmPayService.requestAlipay(orderId + "", order.getTotalPrice(),
  592. "拍卖:" + order.getName(), HMPayService.getTimeout(order.getCreatedAt(), 180),
  593. Constants.OrderNotifyType.AUCTION, generalProperties.resolveFrontUrl(getCompanyId(), "/home"));
  594. }
  595. throw new BusinessException("绿洲宇宙冷却系统已启动,请稍后支付");
  596. }
  597. @Cacheable(value = "payOrder", key = "'auctionOrder#'+#orderId")
  598. public String payAuctionAli(Long orderId) {
  599. AuctionOrder order = auctionOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  600. if (order.getStatus() != AuctionOrderStatus.NOT_PAID) {
  601. throw new BusinessException("订单状态错误");
  602. }
  603. String qrCode = aliRequest(orderId, order.getTotalPrice(), "拍卖:" + order
  604. .getName(), Constants.OrderNotifyType.AUCTION);
  605. String ua = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
  606. .getHeader("User-Agent");
  607. if (ua.toLowerCase().contains("micromessenger")) {
  608. return "/static/wx_alipay_bridge.html?payUrl=" + URLEncoder
  609. .encode(Constants.ALIPAY_URL_SCHEME + qrCode, StandardCharsets.UTF_8)
  610. + "&orderId=" + orderId + "&type=auctionOrder&returnUrl="
  611. + URLEncoder
  612. .encode(generalProperties.resolveFrontUrl(getCompanyId(), "/home"), StandardCharsets.UTF_8);
  613. } else {
  614. return Constants.ALIPAY_URL_SCHEME + qrCode;
  615. }
  616. }
  617. @Cacheable(value = "payOrder", key = "'auctionOrder#'+#orderId")
  618. public String payAuctionQuick(Long orderId) {
  619. AuctionOrder order = auctionOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  620. if (order.getStatus() != AuctionOrderStatus.NOT_PAID) {
  621. throw new BusinessException("订单状态错误");
  622. }
  623. IdentityAuth identityAuth = identityAuthRepo
  624. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(order.getUserId(), AuthStatus.SUCCESS)
  625. .orElseThrow(new BusinessException("请先完成实名认证"));
  626. return sandPayService.payQuick(orderId + "", "拍卖:" + order.getName(),
  627. order.getTotalPrice(), order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.AUCTION,
  628. generalProperties.resolveFrontUrl(getCompanyId(), "/home"));
  629. }
  630. @Cacheable(value = "payOrder", key = "'auctionOrder#'+#orderId")
  631. public String payAuctionQuickBind(Long orderId) {
  632. AuctionOrder order = auctionOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  633. if (order.getStatus() != AuctionOrderStatus.NOT_PAID) {
  634. throw new BusinessException("订单状态错误");
  635. }
  636. IdentityAuth identityAuth = identityAuthRepo
  637. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(order.getUserId(), AuthStatus.SUCCESS)
  638. .orElseThrow(new BusinessException("请先完成实名认证"));
  639. return sandPayService.payQuickBind(orderId + "", "拍卖:" + order.getName(),
  640. order.getTotalPrice(), order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.AUCTION,
  641. generalProperties.resolveFrontUrl(getCompanyId(), "/home"),
  642. order.getUserId(), identityAuth.getRealName(), identityAuth.getIdNo());
  643. }
  644. public void payAuctionOrderBalance(Long orderId, Long userId, String tradeCode) {
  645. AuctionOrder order = auctionOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  646. if (order.getStatus() != AuctionOrderStatus.NOT_PAID) {
  647. throw new BusinessException("订单状态错误");
  648. }
  649. checkTradeCode(userId, tradeCode, order.getUserId());
  650. BalanceRecord record = userBalanceService.balancePay(order.getUserId(), order.getTotalPrice(), orderId, "拍卖");
  651. auctionOrderService.notify(orderId, PayMethod.BALANCE, record.getId().toString());
  652. }
  653. @Cacheable(value = "payOrder", key = "'auctionOrder#'+#orderId")
  654. public Map<String, Object> payAuctionOrderAgreement(Long orderId, String bindCardId) {
  655. AuctionOrder order = auctionOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  656. if (order.getStatus() != AuctionOrderStatus.NOT_PAID) {
  657. throw new BusinessException("订单状态错误");
  658. }
  659. if (StringUtils.isEmpty(bindCardId)) {
  660. bindCardId = userBankCardRepo.findByUserId(order.getUserId())
  661. .stream().map(UserBankCard::getBindCardId).findFirst().orElse(null);
  662. }
  663. if (StringUtils.isEmpty(bindCardId)) {
  664. throw new BusinessException("请先绑定银行卡");
  665. }
  666. return payEaseService.pay("拍卖:" + order.getAuctionId(), orderId.toString(), order.getTotalPrice(),
  667. order.getUserId().toString(), bindCardId, Constants.OrderNotifyType.AUCTION);
  668. }
  669. @Cacheable(value = "payOrder", key = "'picOrder#'+#orderId")
  670. public String payPicOrder(Long orderId) {
  671. PhotoAsset order = photoAssetRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  672. if (order.getOrderStatus() != OrderStatus.NOT_PAID) {
  673. throw new BusinessException("订单状态错误");
  674. }
  675. switch (PAY_CHANNEL) {
  676. case Constants.PayChannel.SAND:
  677. return sandPayService.pay(orderId + "", "星图:" + order.getPicName(), order.getPrice(),
  678. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.PIC);
  679. case Constants.PayChannel.HM:
  680. return hmPayService.requestAlipay(orderId + "", order.getPrice(),
  681. "星图:" + order.getPicName(), HMPayService.getTimeout(order.getCreatedAt(), 180),
  682. Constants.OrderNotifyType.PIC, generalProperties.resolveFrontUrl(getCompanyId(), "/orderDetail?id=" + orderId));
  683. }
  684. throw new BusinessException("绿洲宇宙冷却系统已启动,请稍后支付");
  685. }
  686. @Cacheable(value = "payOrder", key = "'picOrder#'+#orderId")
  687. public String payPicAli(Long orderId) {
  688. PhotoAsset order = photoAssetRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  689. if (order.getOrderStatus() != OrderStatus.NOT_PAID) {
  690. throw new BusinessException("订单状态错误");
  691. }
  692. String qrCode = aliRequest(orderId, order.getPrice(), "星图:" + order
  693. .getPicName(), Constants.OrderNotifyType.PIC);
  694. String ua = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
  695. .getHeader("User-Agent");
  696. if (ua.toLowerCase().contains("micromessenger")) {
  697. return "/static/wx_alipay_bridge.html?payUrl=" + URLEncoder
  698. .encode(Constants.ALIPAY_URL_SCHEME + qrCode, StandardCharsets.UTF_8)
  699. + "&orderId=" + orderId + "&type=pic&returnUrl="
  700. + URLEncoder
  701. .encode(generalProperties.resolveFrontUrl(getCompanyId(), "/orderDetail?id=" + orderId), StandardCharsets.UTF_8);
  702. } else {
  703. return Constants.ALIPAY_URL_SCHEME + qrCode;
  704. }
  705. }
  706. @Cacheable(value = "payOrder", key = "'picOrder#'+#orderId")
  707. public String payPicQuick(Long orderId) {
  708. PhotoAsset order = photoAssetRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  709. if (order.getOrderStatus() != OrderStatus.NOT_PAID) {
  710. throw new BusinessException("订单状态错误");
  711. }
  712. IdentityAuth identityAuth = identityAuthRepo
  713. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(order.getUserId(), AuthStatus.SUCCESS)
  714. .orElseThrow(new BusinessException("请先完成实名认证"));
  715. return sandPayService.payQuick(orderId + "", "星图:" + order.getPicName(),
  716. order.getPrice(), order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.PIC,
  717. generalProperties.resolveFrontUrl(getCompanyId(), "/orderDetail?id=" + orderId));
  718. }
  719. @Cacheable(value = "payOrder", key = "'picOrder#'+#orderId")
  720. public String payPicQuickBind(Long orderId) {
  721. PhotoAsset order = photoAssetRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  722. if (order.getOrderStatus() != OrderStatus.NOT_PAID) {
  723. throw new BusinessException("订单状态错误");
  724. }
  725. IdentityAuth identityAuth = identityAuthRepo
  726. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(order.getUserId(), AuthStatus.SUCCESS)
  727. .orElseThrow(new BusinessException("请先完成实名认证"));
  728. return sandPayService.payQuickBind(orderId + "", "星图:" + order.getPicName(),
  729. order.getPrice(), order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.PIC,
  730. generalProperties.resolveFrontUrl(getCompanyId(), "/orderDetail?id=" + orderId),
  731. order.getUserId(), identityAuth.getRealName(), identityAuth.getIdNo());
  732. }
  733. public void payPicOrderBalance(Long orderId, Long userId, String tradeCode) {
  734. PhotoAsset order = photoAssetRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  735. if (order.getOrderStatus() != OrderStatus.NOT_PAID) {
  736. throw new BusinessException("订单状态错误");
  737. }
  738. checkTradeCode(userId, tradeCode, order.getUserId());
  739. BalanceRecord record = userBalanceService.balancePay(order.getUserId(), order.getPrice(), orderId, "星图");
  740. photoAssetService.notify(orderId, PayMethod.BALANCE, record.getId().toString());
  741. }
  742. @Cacheable(value = "payOrder", key = "'picOrder#'+#orderId")
  743. public Map<String, Object> payPicOrderAgreement(Long orderId, String bindCardId) {
  744. PhotoAsset order = photoAssetRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  745. if (order.getOrderStatus() != OrderStatus.NOT_PAID) {
  746. throw new BusinessException("订单状态错误");
  747. }
  748. if (StringUtils.isEmpty(bindCardId)) {
  749. bindCardId = userBankCardRepo.findByUserId(order.getUserId())
  750. .stream().map(UserBankCard::getBindCardId).findFirst().orElse(null);
  751. }
  752. if (StringUtils.isEmpty(bindCardId)) {
  753. throw new BusinessException("请先绑定银行卡");
  754. }
  755. return payEaseService.pay("星图:" + order.getPicName(), orderId.toString(), order.getPrice(),
  756. order.getUserId().toString(), bindCardId, Constants.OrderNotifyType.PIC);
  757. }
  758. }