OrderController.java 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. package com.cyksj.web.controller.payment;
  2. import cn.hutool.core.codec.Base64;
  3. import cn.hutool.core.util.StrUtil;
  4. import cn.hutool.extra.qrcode.QrCodeUtil;
  5. import cn.hutool.extra.qrcode.QrConfig;
  6. import cn.hutool.extra.servlet.ServletUtil;
  7. import cn.hutool.json.JSONObject;
  8. import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
  9. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  10. import com.cyksj.common.constant.Constant;
  11. import com.cyksj.common.exception.BusinessRuntimeException;
  12. import com.cyksj.common.util.IoKit;
  13. import com.cyksj.common.util.Jsons;
  14. import com.cyksj.common.util.StringUtil;
  15. import com.cyksj.common.util.Xmls;
  16. import com.cyksj.config.zfb.BaseZfbConfig;
  17. import com.cyksj.config.zfb.ZfbProductCode;
  18. import com.cyksj.dto.Result;
  19. import com.cyksj.enums.GatewayApiCode;
  20. import com.cyksj.enums.GatewayResponse;
  21. import com.cyksj.mapper.GoodsDonSkuMapper;
  22. import com.cyksj.mapper.OrderDonRenewRecordMapper;
  23. import com.cyksj.mapper.OrderDonWaybillMapper;
  24. import com.cyksj.mapper.UserMapper;
  25. import com.cyksj.mapper.channel.UserPayEquipmentAvailableBenefitsMapper;
  26. import com.cyksj.mapper.market.task.UserBindDetailMapper;
  27. import com.cyksj.model.dto.AliPayParams;
  28. import com.cyksj.model.dto.H5JsPayParams;
  29. import com.cyksj.model.entity.*;
  30. import com.cyksj.model.manage.views.*;
  31. import com.cyksj.model.request.AlipayOrderDonReq;
  32. import com.cyksj.model.request.OrderPayRequest;
  33. import com.cyksj.model.response.AliPayTradeStatus;
  34. import com.cyksj.model.views.GoodsDonSkuView;
  35. import com.cyksj.model.views.MidjourneyUserView;
  36. import com.cyksj.model.views.OrderCommentView;
  37. import com.cyksj.service.midjourney.MidjourneyAccountService;
  38. import com.cyksj.service.order.OrderDonService;
  39. import com.cyksj.service.paypal.PayPalService;
  40. import com.cyksj.service.paypal.PaypalPayConfigService;
  41. import com.cyksj.service.stripe.StripePayConfigService;
  42. import com.cyksj.service.stripe.StripeService;
  43. import com.cyksj.service.user.UserBindRelationService;
  44. import com.cyksj.web.util.StpUserUtil;
  45. import com.ejlchina.searcher.BeanSearcher;
  46. import com.ejlchina.searcher.SearchResult;
  47. import com.ejlchina.searcher.param.Operator;
  48. import com.ejlchina.searcher.util.MapBuilder;
  49. import com.ejlchina.searcher.util.MapUtils;
  50. import com.google.gson.JsonSyntaxException;
  51. import com.paypal.api.payments.Links;
  52. import com.paypal.api.payments.Payment;
  53. import com.stripe.exception.SignatureVerificationException;
  54. import com.stripe.model.*;
  55. import com.stripe.model.checkout.Session;
  56. import com.stripe.net.Webhook;
  57. import lombok.extern.slf4j.Slf4j;
  58. import org.apache.commons.lang3.StringUtils;
  59. import org.springframework.beans.BeanUtils;
  60. import org.springframework.beans.factory.annotation.Autowired;
  61. import org.springframework.validation.annotation.Validated;
  62. import org.springframework.web.bind.annotation.*;
  63. import javax.annotation.Resource;
  64. import javax.servlet.http.Cookie;
  65. import javax.servlet.http.HttpServletRequest;
  66. import javax.servlet.http.HttpServletResponse;
  67. import java.io.InputStream;
  68. import java.io.OutputStream;
  69. import java.nio.charset.StandardCharsets;
  70. import java.util.*;
  71. import java.util.stream.Collectors;
  72. /**
  73. * @author chan
  74. * @date 2021/10/11 下午3:50
  75. */
  76. @Slf4j
  77. @RequestMapping("/applets/order")
  78. @RestController
  79. public class OrderController {
  80. @Autowired
  81. private OrderDonService orderDonService;
  82. @Resource
  83. private BeanSearcher beanSearcher;
  84. @Resource
  85. private HttpServletRequest request;
  86. @Resource
  87. private HttpServletResponse response;
  88. @Autowired
  89. private UserBindDetailMapper userBindDetailMapper;
  90. @Autowired
  91. private UserMapper userMapper;
  92. @Autowired
  93. private UserPayEquipmentAvailableBenefitsMapper availableBenefitsMapper;
  94. @Autowired
  95. private OrderDonWaybillMapper waybillMapper;
  96. @Autowired
  97. private UserBindRelationService UserBindRelationService;
  98. @Autowired
  99. private PaypalPayConfigService paypalPayConfigService;
  100. @Autowired
  101. private PayPalService payPalService;
  102. @Autowired
  103. private StripePayConfigService stripePayConfigService;
  104. @Autowired
  105. private StripeService stripeService;
  106. @Autowired
  107. private MidjourneyAccountService midjourneyAccountService;
  108. @Autowired
  109. private GoodsDonSkuMapper skuMapper;
  110. @Autowired
  111. private OrderDonRenewRecordMapper orderDonRenewRecordMapper;
  112. /**
  113. * 支付
  114. * @author chan
  115. * @date 2021-10-11 下午4:56
  116. */
  117. @PostMapping("/post/submit")
  118. public Result<OrderDon> submit(@Validated @RequestBody OrderPayRequest payRequest, HttpServletResponse response) throws Exception {
  119. final String methodName = "吊起微信支付";
  120. Long userId = StpUserUtil.getUserIdAfterLogin();
  121. payRequest.setUserId(userId);
  122. log.info("{}[start] params:{}", methodName, payRequest);
  123. String ip = ServletUtil.getClientIP(request);
  124. String address = StringUtil.getNewInternalAddressByIp(ip);
  125. //address.contains("柬埔寨") ||
  126. if (address.contains("缅甸")) {
  127. throw BusinessRuntimeException.getInstance("用户系统异常");
  128. }
  129. payRequest.setIp(ip);
  130. OrderDon orderDon = orderDonService.submit(payRequest);
  131. //无登录订单 预留手机号免登录
  132. if (userId == null && payRequest.getPopularizeId() != null && StrUtil.isNotBlank(payRequest.getPhone())) {
  133. User user = userMapper.selectById(orderDon.getUserId());
  134. //写回登陆信息
  135. StpUserUtil.login(user.getId());
  136. response.addHeader("satoken-user", StpUserUtil.getTokenValue());
  137. Cookie cookie = new Cookie("satoken-user", StpUserUtil.getTokenValue());
  138. cookie.setMaxAge(31536000);
  139. cookie.setPath("/");
  140. response.addCookie(cookie);
  141. JSONObject jsonObject = new JSONObject();
  142. jsonObject.putOpt("showId", user.getShowId());
  143. jsonObject.putOpt("nickName", user.getNickname());
  144. Cookie userInfo = new Cookie("info", Base64.encode(jsonObject.toString()));
  145. cookie.setMaxAge(31536000);
  146. cookie.setPath("/");
  147. response.addCookie(userInfo);
  148. }
  149. if (orderDon.getGoodsId() != null && orderDon.getGoodsId() == 26l) {
  150. GoodsDonSku sku = skuMapper.selectById(orderDon.getSkuId());
  151. orderDon.setIsMirror(sku.getIsMirror());
  152. }
  153. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  154. }
  155. /**
  156. * 套餐提交支付
  157. */
  158. @PostMapping("/post/upgrade/submit")
  159. public Result<UpgradeOrderDon> submitUpgrade(@Validated @RequestBody OrderPayRequest payRequest) throws Exception {
  160. final String methodName = "套餐吊起支付";
  161. //无需免登录
  162. Long userId = StpUserUtil.getLoginIdAsLong();
  163. payRequest.setUserId(userId);
  164. log.info("{}[start] params:{}", methodName, payRequest);
  165. String ip = ServletUtil.getClientIP(request);
  166. payRequest.setIp(ip);
  167. UpgradeOrderDon orderDon = orderDonService.submitUpgrade(payRequest);
  168. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  169. }
  170. /**
  171. * 0元订单确认
  172. */
  173. @PostMapping("/post/order/status/{orderId}")
  174. public Result<String> zeroOrderConfirm(@PathVariable Long orderId) {
  175. orderDonService.zeroOrderConfirm(orderId);
  176. return GatewayResponse.SUCCESS.newBuilder().toResult();
  177. }
  178. /**
  179. * 套餐0元订单确认
  180. */
  181. @PostMapping("/post/upgrade/order/status/{orderId}")
  182. public Result<String> zeroUpgradeOrderConfirm(@PathVariable Long orderId) {
  183. orderDonService.zeroUpgradeOrderConfirm(orderId);
  184. return GatewayResponse.SUCCESS.newBuilder().toResult();
  185. }
  186. /**
  187. * 支付
  188. * @author chan
  189. * @date 2021-10-11 下午4:56
  190. */
  191. @PostMapping("/post/pay/{orderId}")
  192. public Result<H5JsPayParams> pay(@PathVariable Long orderId) throws Exception {
  193. final String methodName = "吊起微信支付";
  194. log.info("{}[start] orderId:{}",methodName,orderId);
  195. H5JsPayParams payParams = orderDonService.pay(orderId, "JSAPI");
  196. return GatewayResponse.SUCCESS.newBuilder().toResult(payParams);
  197. }
  198. /**
  199. * 调用生成订单之后
  200. * 微信网页预下单获取交易链接生成二维码
  201. */
  202. @PostMapping("/get/wx/orderQrCode/{orderId}")
  203. public Result<String> createUnifiedOrderQr(@PathVariable Long orderId) throws Exception {
  204. //预下单
  205. H5JsPayParams payParams = orderDonService.wxPcWebPay(orderId, "NATIVE");
  206. //获取二维码链接code_url
  207. String codeUrl = payParams.getCodeUrl();
  208. QrConfig qrConfig = new QrConfig(300, 300);
  209. return GatewayResponse.SUCCESS.newBuilder().toResult(QrCodeUtil.generateAsBase64(codeUrl, qrConfig, "png"));
  210. }
  211. /**
  212. * 微信支付回调
  213. * @author chan
  214. * @date 2021-10-11 下午5:42
  215. */
  216. @PostMapping("/prepay/notify")
  217. public void prepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  218. String xml = IoKit.toString(request.getInputStream());
  219. log.info("=== 微信支付成功的回调: \n {}", xml);
  220. // 解析xml
  221. Map<String, String> map = Xmls.toMap(xml);
  222. // 支付失败
  223. if (!StringUtils.equals("SUCCESS", map.get("return_code")) || !StringUtils.equals("SUCCESS", map.get("result_code"))) {
  224. throw BusinessRuntimeException.getInstance("支付失败.");
  225. }
  226. orderDonService.prepayNotify(map);
  227. String toWeChatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  228. OutputStream out = null;
  229. try {
  230. out = response.getOutputStream();
  231. IoKit.write(toWeChatXmlResponse, out);
  232. } catch (Exception e) {
  233. throw BusinessRuntimeException.getInstance(e,e.getMessage());
  234. } finally {
  235. IoKit.close(out);
  236. }
  237. }
  238. /**
  239. * pc端微信支付回调
  240. * @author chan
  241. * @date 2021-10-11 下午5:42
  242. */
  243. @PostMapping("/pc/prepay/notify")
  244. public void pcPrepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  245. String xml = IoKit.toString(request.getInputStream());
  246. log.info("=== 微信pc端分发支付成功的回调: \n {}", xml);
  247. // 解析xml
  248. Map<String, String> map = Xmls.toMap(xml);
  249. // 支付失败
  250. if (!StringUtils.equals("SUCCESS", map.get("return_code")) || !StringUtils.equals("SUCCESS", map.get("result_code"))) {
  251. throw BusinessRuntimeException.getInstance("支付失败.");
  252. }
  253. orderDonService.prepayNotify(map);
  254. log.info("pc端微信支付回调修改订单状态成功");
  255. String toWeChatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  256. OutputStream out = null;
  257. try {
  258. out = response.getOutputStream();
  259. IoKit.write(toWeChatXmlResponse, out);
  260. } catch (Exception e) {
  261. throw BusinessRuntimeException.getInstance(e,e.getMessage());
  262. } finally {
  263. IoKit.close(out);
  264. }
  265. }
  266. /**
  267. * 支付宝表单支付
  268. * 支付宝调起支付宝表单
  269. * 手机支付
  270. */
  271. @PostMapping("/post/pay/zfb")
  272. @Deprecated
  273. public Result<String> aliPay(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  274. AliPayParams aliPayParams = orderDonService.aliPay(re, ZfbProductCode.MOBILE_WEB.getProductCode(), null);
  275. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  276. //直接将完整的表单html输出到页面
  277. // response.getWriter().write(aliPayParams.getBody());
  278. // response.getWriter().flush();
  279. // response.getWriter().close();
  280. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  281. }
  282. /**
  283. * 套餐支付宝支付
  284. */
  285. @PostMapping("/post/pay/upgrade/zfb")
  286. @Deprecated
  287. public Result<String> aliPayUpgrade(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  288. AliPayParams aliPayParams = orderDonService.aliPayUpgrade(re, ZfbProductCode.MOBILE_WEB.getProductCode(),null);
  289. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  290. }
  291. /**
  292. * 支付宝web支付
  293. * pc网页内嵌二维码
  294. */
  295. @PostMapping("/get/zfb/orderQrCode")
  296. public Result<String> zfbWebQrCode(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  297. AliPayParams aliPayParams = orderDonService.aliPay(re, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_orderCode);
  298. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  299. //直接将完整的表单html输出到页面
  300. // response.getWriter().write(aliPayParams.getBody());
  301. // response.getWriter().flush();
  302. // response.getWriter().close();
  303. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  304. }
  305. /**
  306. * 支付宝web支付
  307. * pc网页内嵌二维码
  308. */
  309. @PostMapping("/get/zfb/upgrade/orderQrCode")
  310. public Result<String> zfbWebQrCodeUpgrade(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  311. AliPayParams aliPayParams = orderDonService.aliPayUpgrade(re, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_orderCode);
  312. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  313. //直接将完整的表单html输出到页面
  314. // response.getWriter().write(aliPayParams.getBody());
  315. // response.getWriter().flush();
  316. // response.getWriter().close();
  317. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  318. }
  319. /**
  320. * 支付宝web支付
  321. * pc网页跳转二维码
  322. */
  323. @PostMapping("/get/zfb/orderRedirect")
  324. public Result<String> zfbWebRedirectQrCode(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  325. AliPayParams aliPayParams = orderDonService.aliPay(re, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_redirect);
  326. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  327. }
  328. /**
  329. * 支付宝回调
  330. */
  331. @PostMapping("/prepay/zfb/notify")
  332. public String aliPayNotify(HttpServletRequest request) throws Exception {
  333. ////将异步通知中收到的所有参数都存放到map中
  334. Map<String, String> params = convertRequestParamsToMap(request);
  335. String tradeStatus = params.get("trade_status");
  336. String orderNo = params.get("out_trade_no");
  337. if (AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus) || AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  338. log.info("支付宝商家订单号orderNo:{},status:{}开始回调", orderNo, tradeStatus);
  339. orderDonService.aliPayNotify(params);
  340. } else {
  341. log.error("支付宝回调 error 状态不符合 成功或完成 status:{} ,orderNo:{}", tradeStatus, orderNo);
  342. return "fail";
  343. }
  344. return "success";
  345. }
  346. /**
  347. * 支付宝套餐包回调
  348. */
  349. @PostMapping("/prepay/zfb/upgrade/notify")
  350. public String aliPayUpgradeNotify(HttpServletRequest request) throws Exception {
  351. ////将异步通知中收到的所有参数都存放到map中
  352. Map<String, String> params = convertRequestParamsToMap(request);
  353. String tradeStatus = params.get("trade_status");
  354. String orderNo = params.get("out_trade_no");
  355. if (AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus) || AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  356. log.info("支付宝商家订单号orderNo:{},status:{}开始回调", orderNo, tradeStatus);
  357. orderDonService.aliPayUpgradeNotify(params);
  358. } else {
  359. log.error("支付宝回调 error 状态不符合 成功或完成 status:{} ,orderNo:{}", tradeStatus, orderNo);
  360. return "fail";
  361. }
  362. return "success";
  363. }
  364. /**
  365. * 支付宝转账
  366. */
  367. // @PostMapping("/zfb/transfer/accounts")
  368. // @NoSubmit
  369. // public Result<String> zfbTransferAccounts(@RequestBody @Validated TransferAccountsReq transferAccountsReq) throws Exception {
  370. // long userId = StpUserUtil.getLoginIdAsLong();
  371. // transferAccountsReq.setUserId(userId);
  372. // orderDonService.transferAccounts(transferAccountsReq);
  373. // return GatewayResponse.SUCCESS.newBuilder().toResult("转账成功");
  374. // }
  375. /**
  376. * 查询支付宝转账状态
  377. */
  378. @GetMapping("/zfb/transfer/status")
  379. public Result<String> getTransFerStatusByTid(String translationId) throws Exception {
  380. AlipayFundTransCommonQueryResponse response = orderDonService.getTransFerStatusByTid(translationId);
  381. if (response.isSuccess()) {
  382. if (!Constant.SUCCESS.equals(response.getStatus())) {
  383. return GatewayResponse.SUCCESS.newBuilder().toResult(response.getFailReason());
  384. }
  385. return GatewayResponse.SUCCESS.newBuilder().toResult("该红包已转账成功");
  386. }
  387. return GatewayResponse.SUCCESS.newBuilder().toResult(response.getSubMsg());
  388. }
  389. /**
  390. * 获取订单列表
  391. */
  392. @GetMapping("/get")
  393. public Result<SearchResult<OrderDonView>> list(String customId){
  394. long userId = StpUserUtil.getLoginIdAsLong();
  395. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  396. //Long yhsId = yhShopFrontService.getYhsIdByCustomId(customId);
  397. List<Long> userIds = UserBindRelationService.getRelationUserIdList(userId, null);
  398. SearchResult<OrderDonView> search = beanSearcher.search(OrderDonView.class, builder
  399. //.field(OrderDonView::getYhsId, yhsId)
  400. .field(OrderDonView::getUserId, userIds).op(Operator.InList)
  401. .orderBy(OrderDonView::getId).desc()
  402. .build());
  403. search.getDataList().forEach(data->{
  404. Integer count = availableBenefitsMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentAvailableBenefits.class)
  405. .eq(UserPayEquipmentAvailableBenefits::getRealOrderId, data.getId())
  406. .eq(UserPayEquipmentAvailableBenefits::getDeleted, true));
  407. data.setIsHasBenefits(count > 0 ? true : false);
  408. if (data.getIsBenefits() != null && data.getIsBenefits()) {
  409. String benefitsList = data.getBenefitsList();
  410. if (StrUtil.isNotBlank(benefitsList)) {
  411. try {
  412. List<Long> skuIds = Jsons.parseList(benefitsList, GoodsDonSku.class).stream().map(GoodsDonSku::getId).collect(Collectors.toList());
  413. data.setBenefitsViews(beanSearcher.searchAll(GoodsDonSkuView.class, MapUtils.builder().field(GoodsDonSkuView::getSkuId, skuIds).op(Operator.InList).build()));
  414. } catch (Exception e) {
  415. }
  416. }
  417. }
  418. if (data.getRelationId() == 0) {
  419. data.setWaybill(waybillMapper.selectOne(Wrappers.lambdaQuery(OrderDonWaybill.class).eq(OrderDonWaybill::getOrderId, data.getId()).last("limit 1")));
  420. }
  421. if (data.getOrderType() == 2) {
  422. OrderDonRenewRecord orderDonRenewRecord = orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  423. .eq(OrderDonRenewRecord::getOrderId, data.getId())
  424. .last("limit 1"));
  425. data.setIsRenewPackage(orderDonRenewRecord != null ? true : false);
  426. }
  427. });
  428. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  429. }
  430. /**
  431. * 获取订单详情
  432. */
  433. @GetMapping("/get/{orderId}")
  434. public Result<OrderDetailView> detail(@PathVariable Long orderId, Boolean isNoLogin) {
  435. Long userId = StpUserUtil.getUserIdAfterLogin();
  436. OrderDetailView detail = orderDonService.getDetail(orderId, userId);
  437. return GatewayResponse.SUCCESS.newBuilder().toResult(detail);
  438. }
  439. /**
  440. * 取消订单
  441. */
  442. @GetMapping("/get/close/{orderId}")
  443. public Result<String> closeOrder(@PathVariable Long orderId) {
  444. long userId = StpUserUtil.getLoginIdAsLong();
  445. orderDonService.closeOrder(orderId, userId);
  446. return GatewayResponse.SUCCESS.newBuilder().toResult();
  447. }
  448. @GetMapping("/get/order/status/{orderId}")
  449. public Result<OrderDonSearchView> getOrderStatusById(@PathVariable Long orderId) {
  450. if (orderId < 1) {
  451. throw BusinessRuntimeException.getInstance("订单不存在");
  452. }
  453. OrderDonSearchView orderDonView = beanSearcher.searchFirst(OrderDonSearchView.class, MapUtils.builder()
  454. .put("orderId", String.format("where id = %s", orderId))
  455. .build());
  456. if (orderDonView == null) {
  457. throw BusinessRuntimeException.getInstance("订单不存在");
  458. }
  459. if (orderDonView.getIsMirror() && orderDonView.getOrderType() == 2) {
  460. Optional.ofNullable(orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  461. .eq(OrderDonRenewRecord::getOrderId, orderId)
  462. .last("limit 1")))
  463. .ifPresent(renew -> {
  464. GoodsDonSku sku = skuMapper.selectById(renew.getOriSkuId());
  465. orderDonView.setOriSpecVal(sku.getSpecVal());
  466. });
  467. }
  468. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonView);
  469. }
  470. /**
  471. * 查询套餐订单支付状态
  472. */
  473. @GetMapping("/get/upgrade/order/status/{orderId}")
  474. public Result<UpgradeOrderDonSearchView> getUpgradeOrderStatusById(@PathVariable Long orderId) {
  475. if (orderId < 1) {
  476. throw BusinessRuntimeException.getInstance("订单不存在");
  477. }
  478. UpgradeOrderDonSearchView orderDonView = beanSearcher.searchFirst(UpgradeOrderDonSearchView.class, MapUtils.builder()
  479. .put("orderId", String.format("where id = %s", orderId))
  480. .build());
  481. if (orderDonView == null) {
  482. throw BusinessRuntimeException.getInstance("订单不存在");
  483. }
  484. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonView);
  485. }
  486. @PostMapping("/get/noLogin/order")
  487. public Result<List<OrderDonView>> getSearchResult(@RequestBody List<Long> orderIds) {
  488. List<OrderDonView> orderDonViews = beanSearcher.searchAll(OrderDonView.class, MapUtils.builder()
  489. .field(OrderDonView::getId, orderIds).op(Operator.InList)
  490. .orderBy(OrderDonView::getId).desc().build());
  491. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonViews);
  492. }
  493. /**
  494. * 平台评论列表
  495. */
  496. @GetMapping("/get/orderComment")
  497. public Result<SearchResult<OrderCommentView>> getOrderCommentView() {
  498. SearchResult<OrderCommentView> search = beanSearcher.search(OrderCommentView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
  499. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  500. }
  501. /**
  502. * 电脑端手机号注册 购买车票是否绑定了微信用户
  503. */
  504. @GetMapping("/isBindWx")
  505. public Result<Boolean> isBindWx() {
  506. Long userId = StpUserUtil.getLoginIdAsLong();
  507. User user = userMapper.selectById(userId);
  508. if (user == null) {
  509. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  510. }
  511. if (StrUtil.isEmpty(user.getLoginPhone())) {
  512. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  513. }
  514. UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  515. .eq(UserBindDetail::getPhone, user.getLoginPhone()));
  516. if (userBindDetail == null || userBindDetail.getUserId() == null) {
  517. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  518. }
  519. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  520. }
  521. /**
  522. * 是否绑定了邮箱或手机号
  523. */
  524. @GetMapping("/isBind")
  525. public Result<Boolean> isBindPhoneOrEmail(@RequestParam(defaultValue = "1") Boolean fip) {
  526. Long userId = StpUserUtil.getLoginIdAsLong();
  527. User user = userMapper.selectById(userId);
  528. if (user == null) {
  529. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  530. }
  531. //手机号注册 无需绑定
  532. if (StrUtil.isNotEmpty(user.getLoginPhone())) {
  533. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  534. }
  535. //是否绑定了手机号
  536. UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  537. .eq(StrUtil.isNotEmpty(user.getOpenId()), UserBindDetail::getUserId, userId)
  538. .eq(StrUtil.isNotEmpty(user.getEmail()), UserBindDetail::getEmailUserId, userId).last("limit 1"));
  539. if (fip) {
  540. //台湾ip
  541. String address = StringUtil.getNewInternalAddressByIp(ServletUtil.getClientIP(request));
  542. if (address.contains("台湾") || !address.contains("中国")) {
  543. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  544. }
  545. }
  546. if (userBindDetail == null || StrUtil.isEmpty(userBindDetail.getPhone())) {
  547. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  548. }
  549. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  550. }
  551. /**
  552. * 获取支付宝回调参数
  553. */
  554. private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
  555. Map<String, String> retMap = new HashMap<>();
  556. Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
  557. for (Map.Entry<String, String[]> entry : entrySet) {
  558. String name = entry.getKey();
  559. String[] values = entry.getValue();
  560. int valLen = values.length;
  561. if (valLen == 1) {
  562. retMap.put(name, values[0]);
  563. } else if (valLen > 1) {
  564. StringBuilder sb = new StringBuilder();
  565. for (String val : values) {
  566. sb.append(",").append(val);
  567. }
  568. retMap.put(name, sb.substring(1));
  569. } else {
  570. retMap.put(name, "");
  571. }
  572. }
  573. return retMap;
  574. }
  575. /**
  576. * paypal支付
  577. */
  578. @PostMapping("/paypal/pay/{orderId}")
  579. public Result<String> paypalPay(@PathVariable Long orderId,String successUrl) throws Exception {
  580. final String methodName = "paypal支付";
  581. log.info("{}[start] orderId:{}",methodName,orderId);
  582. Payment payment = payPalService.createPayment(orderId,successUrl);
  583. String payUrl = "/";
  584. log.info("paypal links:{}",payment.getLinks());
  585. for(Links links : payment.getLinks()){
  586. if("approval_url".equals(links.getRel())){
  587. // 客户付款登陆地址
  588. String payPalUrl = links.getHref();
  589. log.info("PayPal调起支付成功[end]:{}", orderId);
  590. payUrl = payPalUrl;
  591. }
  592. }
  593. log.info("paypal支付成功[end]");
  594. return GatewayResponse.SUCCESS.newBuilder().toResult(payUrl);
  595. }
  596. /**
  597. * stripe支付
  598. */
  599. @PostMapping("/stripe/pay/{orderId}")
  600. public Result<String> stripePay(@PathVariable Long orderId,String successUrl) throws Exception {
  601. final String methodName = "stripe支付";
  602. log.info("{}[start] orderId:{}",methodName,orderId);
  603. String payUrl = stripeService.checkOutStripe(orderId,successUrl);
  604. log.info("Stripe支付成功 result:{}[end]",payUrl);
  605. return GatewayResponse.SUCCESS.newBuilder().toResult(payUrl);
  606. }
  607. /**
  608. * paypal支付回调
  609. */
  610. @RequestMapping(value = "/paypal/notify")
  611. public void successPay(@RequestParam(value = "paymentId") String paymentId, @RequestParam(value = "PayerID") String PayerID) throws Exception {
  612. PaypalPayConfig paypalPayConfig = paypalPayConfigService.getById(1);
  613. response.sendRedirect(payPalService.successPayment(paymentId,PayerID,paypalPayConfig));
  614. }
  615. /**
  616. * stripe支付回调
  617. */
  618. @PostMapping("/stripe/notify")
  619. @ResponseBody
  620. public String webhooks() throws Exception {
  621. InputStream inputStream = request.getInputStream();
  622. byte[] bytes = IoKit.toBytes(inputStream);
  623. String payload = new String(bytes, StandardCharsets.UTF_8);
  624. String sigHeader = request.getHeader("Stripe-Signature");
  625. StripePayConfig stripePayConfig = stripePayConfigService.getById(1);
  626. Event event = null;
  627. try {
  628. event = Webhook.constructEvent(
  629. payload, sigHeader, stripePayConfig.getWebhookSecret()
  630. );
  631. } catch (JsonSyntaxException | SignatureVerificationException e) {
  632. response.setStatus(400);
  633. return "";
  634. }
  635. // Deserialize the nested object inside the event
  636. EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer();
  637. StripeObject stripeObject = null;
  638. if (dataObjectDeserializer.getObject().isPresent()) {
  639. stripeObject = dataObjectDeserializer.getObject().orElse(null);
  640. } else {
  641. // Deserialization failed, probably due to an API version mismatch.
  642. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for
  643. // instructions on how to handle this case, or return an error here.
  644. }
  645. // Handle the event
  646. switch (event.getType()) {
  647. case "payment_intent.succeeded":
  648. PaymentIntent paymentIntent = (PaymentIntent) stripeObject;
  649. response.setStatus(200);
  650. break;
  651. case "charge.succeeded":
  652. //使用token支付成功回调
  653. Charge charge = (Charge) stripeObject;
  654. //TODO 此时根据charge ID 查询出关联的订单并处理支付成功业务代码
  655. response.setStatus(200);
  656. break;
  657. case "checkout.session.completed":
  658. //使用checkout支付成功回调
  659. Session session = (Session) stripeObject;
  660. stripeService.fulfillOrder(session);
  661. response.setStatus(200);
  662. break;
  663. default:
  664. response.setStatus(400);
  665. return "";
  666. }
  667. response.setStatus(200);
  668. return "";
  669. }
  670. /**
  671. * 余额明细
  672. */
  673. @GetMapping("/get/balance/detail")
  674. public Result<SearchResult<UserBalanceSourceRecord>> getUserBalanceSourceRecord() {
  675. long userId = StpUserUtil.getLoginIdAsLong();
  676. SearchResult<UserBalanceSourceRecord> search = beanSearcher.search(UserBalanceSourceRecord.class, MapUtils.flatBuilder(request.getParameterMap())
  677. .field(UserBalanceSourceRecord::getUserId, userId)
  678. .field(UserBalanceSourceRecord::getDetail).op(Operator.NotNull)
  679. .orderBy(UserBalanceSourceRecord::getId).desc()
  680. .onlySelect(UserBalanceSourceRecord::getBalance, UserBalanceSourceRecord::getDetail, UserBalanceSourceRecord::getCreatedTime)
  681. .build());
  682. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  683. }
  684. /**
  685. * 获取套餐订单列表
  686. */
  687. @GetMapping("/upgrade/get")
  688. public Result<SearchResult<UpgradeOrderDonView>> listUpgradeOrder(){
  689. long userId = StpUserUtil.getLoginIdAsLong();
  690. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  691. List<Long> userIds = UserBindRelationService.getRelationUserIdList(userId, null);
  692. SearchResult<UpgradeOrderDonView> search = beanSearcher.search(UpgradeOrderDonView.class, builder
  693. .field(UpgradeOrderDonView::getUserId, userIds).op(Operator.InList)
  694. .orderBy(UpgradeOrderDonView::getId).desc()
  695. .build());
  696. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  697. }
  698. /**
  699. * 获取套餐订单详情
  700. */
  701. @GetMapping("/get/upgrade/{orderId}")
  702. public Result<UpgradeOrderDetailView> upgradeOrderDetail(@PathVariable Long orderId) {
  703. Long userId = StpUserUtil.getUserIdAfterLogin();
  704. UpgradeOrderDetailView detail = orderDonService.getUpgradeOrderDetail(orderId, userId);
  705. return GatewayResponse.SUCCESS.newBuilder().toResult(detail);
  706. }
  707. /**
  708. * 取消套餐订单
  709. */
  710. @GetMapping("/get/close/upgrade/{orderId}")
  711. public Result<String> closeUpgradeOrder(@PathVariable Long orderId) {
  712. long userId = StpUserUtil.getLoginIdAsLong();
  713. orderDonService.closeUpgradeOrder(orderId, userId);
  714. return GatewayResponse.SUCCESS.newBuilder().toResult();
  715. }
  716. /**
  717. * midjourney查询订单用户账号剩余次数
  718. */
  719. @GetMapping("/get/midjourney/user")
  720. public Result<MidjourneyUserView> getMidjourneyUser(Long relationId) {
  721. long userId = StpUserUtil.getLoginIdAsLong();
  722. MidjourneyUserView search = beanSearcher.searchFirst(MidjourneyUserView.class, MapUtils.flatBuilder(request.getParameterMap())
  723. .field(MidjourneyUserView::getUserId, userId).field(MidjourneyUserView::getRelationId, relationId).build());
  724. if (search == null) {
  725. MidjourneyUser midjourneyUser = midjourneyAccountService.getMidjourneyUserToken(userId, relationId);
  726. search = new MidjourneyUserView();
  727. BeanUtils.copyProperties(midjourneyUser, search);
  728. }
  729. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  730. }
  731. /**
  732. * 续费升级提交支付
  733. */
  734. @PostMapping("/post/renew/upgrade/submit")
  735. public Result<OrderDon> submitRenewUpgrade(@Validated @RequestBody OrderPayRequest payRequest) throws Exception {
  736. final String methodName = "续费升级吊起支付";
  737. //无需免登录
  738. Long userId = StpUserUtil.getLoginIdAsLong();
  739. payRequest.setUserId(userId);
  740. log.info("{}[start] params:{}", methodName, payRequest);
  741. String ip = ServletUtil.getClientIP(request);
  742. payRequest.setIp(ip);
  743. OrderDon orderDon = orderDonService.submitRenewUpgrade(payRequest);
  744. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  745. }
  746. /**
  747. * 获取续费套餐订单列表
  748. */
  749. @GetMapping("/renew/get")
  750. public Result<SearchResult<RenewUpgradeOrderDonView>> listRenewOrders(){
  751. long userId = StpUserUtil.getLoginIdAsLong();
  752. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  753. List<Long> userIds = UserBindRelationService.getRelationUserIdList(userId, null);
  754. SearchResult<RenewUpgradeOrderDonView> search = beanSearcher.search(RenewUpgradeOrderDonView.class, builder
  755. .field(UpgradeOrderDonView::getUserId, userIds).op(Operator.InList)
  756. .orderBy(UpgradeOrderDonView::getId).desc()
  757. .build());
  758. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  759. }
  760. }