OrderController.java 31 KB

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