OrderController.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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());
  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/orderRedirect")
  299. public Result<String> zfbWebRedirectQrCode(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  300. AliPayParams aliPayParams = orderDonService.aliPay(re, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_redirect);
  301. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  302. }
  303. /**
  304. * 支付宝回调
  305. */
  306. @PostMapping("/prepay/zfb/notify")
  307. public String aliPayNotify(HttpServletRequest request) throws Exception {
  308. ////将异步通知中收到的所有参数都存放到map中
  309. Map<String, String> params = convertRequestParamsToMap(request);
  310. String tradeStatus = params.get("trade_status");
  311. String orderNo = params.get("out_trade_no");
  312. if (AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus) || AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  313. log.info("支付宝商家订单号orderNo:{},status:{}开始回调", orderNo, tradeStatus);
  314. orderDonService.aliPayNotify(params);
  315. } else {
  316. log.error("支付宝回调 error 状态不符合 成功或完成 status:{} ,orderNo:{}", tradeStatus, orderNo);
  317. return "fail";
  318. }
  319. return "success";
  320. }
  321. /**
  322. * 支付宝套餐包回调
  323. */
  324. @PostMapping("/prepay/zfb/upgrade/notify")
  325. public String aliPayUpgradeNotify(HttpServletRequest request) throws Exception {
  326. ////将异步通知中收到的所有参数都存放到map中
  327. Map<String, String> params = convertRequestParamsToMap(request);
  328. String tradeStatus = params.get("trade_status");
  329. String orderNo = params.get("out_trade_no");
  330. if (AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus) || AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  331. log.info("支付宝商家订单号orderNo:{},status:{}开始回调", orderNo, tradeStatus);
  332. orderDonService.aliPayUpgradeNotify(params);
  333. } else {
  334. log.error("支付宝回调 error 状态不符合 成功或完成 status:{} ,orderNo:{}", tradeStatus, orderNo);
  335. return "fail";
  336. }
  337. return "success";
  338. }
  339. /**
  340. * 支付宝转账
  341. */
  342. // @PostMapping("/zfb/transfer/accounts")
  343. // @NoSubmit
  344. // public Result<String> zfbTransferAccounts(@RequestBody @Validated TransferAccountsReq transferAccountsReq) throws Exception {
  345. // long userId = StpUserUtil.getLoginIdAsLong();
  346. // transferAccountsReq.setUserId(userId);
  347. // orderDonService.transferAccounts(transferAccountsReq);
  348. // return GatewayResponse.SUCCESS.newBuilder().toResult("转账成功");
  349. // }
  350. /**
  351. * 查询支付宝转账状态
  352. */
  353. @GetMapping("/zfb/transfer/status")
  354. public Result<String> getTransFerStatusByTid(String translationId) throws Exception {
  355. AlipayFundTransCommonQueryResponse response = orderDonService.getTransFerStatusByTid(translationId);
  356. if (response.isSuccess()) {
  357. if (!Constant.SUCCESS.equals(response.getStatus())) {
  358. return GatewayResponse.SUCCESS.newBuilder().toResult(response.getFailReason());
  359. }
  360. return GatewayResponse.SUCCESS.newBuilder().toResult("该红包已转账成功");
  361. }
  362. return GatewayResponse.SUCCESS.newBuilder().toResult(response.getSubMsg());
  363. }
  364. /**
  365. * 获取订单列表
  366. */
  367. @GetMapping("/get")
  368. public Result<SearchResult<OrderDonView>> list(String customId){
  369. long userId = StpUserUtil.getLoginIdAsLong();
  370. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  371. //Long yhsId = yhShopFrontService.getYhsIdByCustomId(customId);
  372. List<Long> userIds = UserBindRelationService.getRelationUserIdList(userId, null);
  373. SearchResult<OrderDonView> search = beanSearcher.search(OrderDonView.class, builder
  374. //.field(OrderDonView::getYhsId, yhsId)
  375. .field(OrderDonView::getUserId, userIds).op(Operator.InList)
  376. .orderBy(OrderDonView::getId).desc()
  377. .build());
  378. search.getDataList().forEach(data->{
  379. Integer count = availableBenefitsMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentAvailableBenefits.class)
  380. .eq(UserPayEquipmentAvailableBenefits::getRealOrderId, data.getId())
  381. .eq(UserPayEquipmentAvailableBenefits::getDeleted, true));
  382. data.setIsHasBenefits(count > 0 ? true : false);
  383. if (data.getIsBenefits() != null && data.getIsBenefits()) {
  384. String benefitsList = data.getBenefitsList();
  385. if (StrUtil.isNotBlank(benefitsList)) {
  386. try {
  387. List<Long> skuIds = Jsons.parseList(benefitsList, GoodsDonSku.class).stream().map(GoodsDonSku::getId).collect(Collectors.toList());
  388. data.setBenefitsViews(beanSearcher.searchAll(GoodsDonSkuView.class, MapUtils.builder().field(GoodsDonSkuView::getSkuId, skuIds).op(Operator.InList).build()));
  389. } catch (Exception e) {
  390. }
  391. }
  392. }
  393. data.setWaybill(waybillMapper.selectOne(Wrappers.lambdaQuery(OrderDonWaybill.class).eq(OrderDonWaybill::getOrderId, data.getId()).last("limit 1")));
  394. });
  395. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  396. }
  397. /**
  398. * 获取订单详情
  399. */
  400. @GetMapping("/get/{orderId}")
  401. public Result<OrderDetailView> detail(@PathVariable Long orderId, Boolean isNoLogin) {
  402. Long userId = StpUserUtil.getUserIdAfterLogin();
  403. OrderDetailView detail = orderDonService.getDetail(orderId, userId);
  404. return GatewayResponse.SUCCESS.newBuilder().toResult(detail);
  405. }
  406. /**
  407. * 取消订单
  408. */
  409. @GetMapping("/get/close/{orderId}")
  410. public Result<String> closeOrder(@PathVariable Long orderId) {
  411. long userId = StpUserUtil.getLoginIdAsLong();
  412. orderDonService.closeOrder(orderId, userId);
  413. return GatewayResponse.SUCCESS.newBuilder().toResult();
  414. }
  415. @GetMapping("/get/order/status/{orderId}")
  416. public Result<OrderDonSearchView> getOrderStatusById(@PathVariable Long orderId) {
  417. if (orderId < 1) {
  418. throw BusinessRuntimeException.getInstance("订单不存在");
  419. }
  420. OrderDonSearchView orderDonView = beanSearcher.searchFirst(OrderDonSearchView.class, MapUtils.builder()
  421. .put("orderId", String.format("where id = %s", orderId))
  422. .build());
  423. if (orderDonView == null) {
  424. throw BusinessRuntimeException.getInstance("订单不存在");
  425. }
  426. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonView);
  427. }
  428. /**
  429. * 查询套餐订单支付状态
  430. */
  431. @GetMapping("/get/upgrade/order/status/{orderId}")
  432. public Result<UpgradeOrderDonSearchView> getUpgradeOrderStatusById(@PathVariable Long orderId) {
  433. if (orderId < 1) {
  434. throw BusinessRuntimeException.getInstance("订单不存在");
  435. }
  436. UpgradeOrderDonSearchView orderDonView = beanSearcher.searchFirst(UpgradeOrderDonSearchView.class, MapUtils.builder()
  437. .put("orderId", String.format("where id = %s", orderId))
  438. .build());
  439. if (orderDonView == null) {
  440. throw BusinessRuntimeException.getInstance("订单不存在");
  441. }
  442. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonView);
  443. }
  444. @PostMapping("/get/noLogin/order")
  445. public Result<List<OrderDonView>> getSearchResult(@RequestBody List<Long> orderIds) {
  446. List<OrderDonView> orderDonViews = beanSearcher.searchAll(OrderDonView.class, MapUtils.builder()
  447. .field(OrderDonView::getId, orderIds).op(Operator.InList)
  448. .orderBy(OrderDonView::getId).desc().build());
  449. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonViews);
  450. }
  451. /**
  452. * 平台评论列表
  453. */
  454. @GetMapping("/get/orderComment")
  455. public Result<SearchResult<OrderCommentView>> getOrderCommentView() {
  456. SearchResult<OrderCommentView> search = beanSearcher.search(OrderCommentView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
  457. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  458. }
  459. /**
  460. * 电脑端手机号注册 购买车票是否绑定了微信用户
  461. */
  462. @GetMapping("/isBindWx")
  463. public Result<Boolean> isBindWx() {
  464. Long userId = StpUserUtil.getLoginIdAsLong();
  465. User user = userMapper.selectById(userId);
  466. if (user == null) {
  467. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  468. }
  469. if (StrUtil.isEmpty(user.getLoginPhone())) {
  470. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  471. }
  472. UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  473. .eq(UserBindDetail::getPhone, user.getLoginPhone()));
  474. if (userBindDetail == null || userBindDetail.getUserId() == null) {
  475. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  476. }
  477. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  478. }
  479. /**
  480. * 是否绑定了邮箱或手机号
  481. */
  482. @GetMapping("/isBind")
  483. public Result<Boolean> isBindPhoneOrEmail() {
  484. Long userId = StpUserUtil.getLoginIdAsLong();
  485. User user = userMapper.selectById(userId);
  486. if (user == null) {
  487. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  488. }
  489. //手机号注册 无需绑定
  490. if (StrUtil.isNotEmpty(user.getLoginPhone())) {
  491. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  492. }
  493. //是否绑定了手机号
  494. UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  495. .eq(StrUtil.isNotEmpty(user.getOpenId()), UserBindDetail::getUserId, userId)
  496. .eq(StrUtil.isNotEmpty(user.getEmail()), UserBindDetail::getEmailUserId, userId).last("limit 1"));
  497. //台湾ip
  498. String address = StringUtil.getNewInternalAddressByIp(ServletUtil.getClientIP(request));
  499. if (address.contains("台湾") || !address.contains("中国")) {
  500. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  501. }
  502. if (userBindDetail == null || StrUtil.isEmpty(userBindDetail.getPhone())) {
  503. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  504. }
  505. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  506. }
  507. /**
  508. * 获取支付宝回调参数
  509. */
  510. private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
  511. Map<String, String> retMap = new HashMap<>();
  512. Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
  513. for (Map.Entry<String, String[]> entry : entrySet) {
  514. String name = entry.getKey();
  515. String[] values = entry.getValue();
  516. int valLen = values.length;
  517. if (valLen == 1) {
  518. retMap.put(name, values[0]);
  519. } else if (valLen > 1) {
  520. StringBuilder sb = new StringBuilder();
  521. for (String val : values) {
  522. sb.append(",").append(val);
  523. }
  524. retMap.put(name, sb.substring(1));
  525. } else {
  526. retMap.put(name, "");
  527. }
  528. }
  529. return retMap;
  530. }
  531. /**
  532. * paypal支付
  533. */
  534. @PostMapping("/paypal/pay/{orderId}")
  535. public Result<String> paypalPay(@PathVariable Long orderId,String successUrl) throws Exception {
  536. final String methodName = "paypal支付";
  537. log.info("{}[start] orderId:{}",methodName,orderId);
  538. Payment payment = payPalService.createPayment(orderId,successUrl);
  539. String payUrl = "/";
  540. log.info("paypal links:{}",payment.getLinks());
  541. for(Links links : payment.getLinks()){
  542. if("approval_url".equals(links.getRel())){
  543. // 客户付款登陆地址
  544. String payPalUrl = links.getHref();
  545. log.info("PayPal调起支付成功[end]:{}", orderId);
  546. payUrl = payPalUrl;
  547. }
  548. }
  549. log.info("paypal支付成功[end]");
  550. return GatewayResponse.SUCCESS.newBuilder().toResult(payUrl);
  551. }
  552. /**
  553. * stripe支付
  554. */
  555. @PostMapping("/stripe/pay/{orderId}")
  556. public Result<String> stripePay(@PathVariable Long orderId,String successUrl) throws Exception {
  557. final String methodName = "stripe支付";
  558. log.info("{}[start] orderId:{}",methodName,orderId);
  559. String payUrl = stripeService.checkOutStripe(orderId,successUrl);
  560. log.info("Stripe支付成功 result:{}[end]",payUrl);
  561. return GatewayResponse.SUCCESS.newBuilder().toResult(payUrl);
  562. }
  563. /**
  564. * paypal支付回调
  565. */
  566. @RequestMapping(value = "/paypal/notify")
  567. public void successPay(@RequestParam(value = "paymentId") String paymentId, @RequestParam(value = "PayerID") String PayerID) throws Exception {
  568. PaypalPayConfig paypalPayConfig = paypalPayConfigService.getById(1);
  569. response.sendRedirect(payPalService.successPayment(paymentId,PayerID,paypalPayConfig));
  570. }
  571. /**
  572. * stripe支付回调
  573. */
  574. @PostMapping("/stripe/notify")
  575. @ResponseBody
  576. public String webhooks() throws Exception {
  577. InputStream inputStream = request.getInputStream();
  578. byte[] bytes = IoKit.toBytes(inputStream);
  579. String payload = new String(bytes, StandardCharsets.UTF_8);
  580. String sigHeader = request.getHeader("Stripe-Signature");
  581. StripePayConfig stripePayConfig = stripePayConfigService.getById(1);
  582. Event event = null;
  583. try {
  584. event = Webhook.constructEvent(
  585. payload, sigHeader, stripePayConfig.getWebhookSecret()
  586. );
  587. } catch (JsonSyntaxException | SignatureVerificationException e) {
  588. response.setStatus(400);
  589. return "";
  590. }
  591. // Deserialize the nested object inside the event
  592. EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer();
  593. StripeObject stripeObject = null;
  594. if (dataObjectDeserializer.getObject().isPresent()) {
  595. stripeObject = dataObjectDeserializer.getObject().orElse(null);
  596. } else {
  597. // Deserialization failed, probably due to an API version mismatch.
  598. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for
  599. // instructions on how to handle this case, or return an error here.
  600. }
  601. // Handle the event
  602. switch (event.getType()) {
  603. case "payment_intent.succeeded":
  604. PaymentIntent paymentIntent = (PaymentIntent) stripeObject;
  605. response.setStatus(200);
  606. break;
  607. case "charge.succeeded":
  608. //使用token支付成功回调
  609. Charge charge = (Charge) stripeObject;
  610. //TODO 此时根据charge ID 查询出关联的订单并处理支付成功业务代码
  611. response.setStatus(200);
  612. break;
  613. case "checkout.session.completed":
  614. //使用checkout支付成功回调
  615. Session session = (Session) stripeObject;
  616. stripeService.fulfillOrder(session);
  617. response.setStatus(200);
  618. break;
  619. default:
  620. response.setStatus(400);
  621. return "";
  622. }
  623. response.setStatus(200);
  624. return "";
  625. }
  626. /**
  627. * 余额明细
  628. */
  629. @GetMapping("/get/balance/detail")
  630. public Result<SearchResult<UserBalanceSourceRecord>> getUserBalanceSourceRecord() {
  631. long userId = StpUserUtil.getLoginIdAsLong();
  632. SearchResult<UserBalanceSourceRecord> search = beanSearcher.search(UserBalanceSourceRecord.class, MapUtils.flatBuilder(request.getParameterMap())
  633. .field(UserBalanceSourceRecord::getUserId, userId)
  634. .field(UserBalanceSourceRecord::getDetail).op(Operator.NotNull)
  635. .orderBy(UserBalanceSourceRecord::getId).desc()
  636. .onlySelect(UserBalanceSourceRecord::getBalance, UserBalanceSourceRecord::getDetail, UserBalanceSourceRecord::getCreatedTime)
  637. .build());
  638. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  639. }
  640. /**
  641. * 获取套餐订单列表
  642. */
  643. @GetMapping("/upgrade/get")
  644. public Result<SearchResult<UpgradeOrderDonView>> listUpgradeOrder(){
  645. long userId = StpUserUtil.getLoginIdAsLong();
  646. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  647. List<Long> userIds = UserBindRelationService.getRelationUserIdList(userId, null);
  648. SearchResult<UpgradeOrderDonView> search = beanSearcher.search(UpgradeOrderDonView.class, builder
  649. .field(UpgradeOrderDonView::getUserId, userIds).op(Operator.InList)
  650. .orderBy(UpgradeOrderDonView::getId).desc()
  651. .build());
  652. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  653. }
  654. /**
  655. * 获取套餐订单详情
  656. */
  657. @GetMapping("/get/upgrade/{orderId}")
  658. public Result<UpgradeOrderDetailView> upgradeOrderDetail(@PathVariable Long orderId) {
  659. Long userId = StpUserUtil.getUserIdAfterLogin();
  660. UpgradeOrderDetailView detail = orderDonService.getUpgradeOrderDetail(orderId, userId);
  661. return GatewayResponse.SUCCESS.newBuilder().toResult(detail);
  662. }
  663. /**
  664. * 取消套餐订单
  665. */
  666. @GetMapping("/get/close/upgrade/{orderId}")
  667. public Result<String> closeUpgradeOrder(@PathVariable Long orderId) {
  668. long userId = StpUserUtil.getLoginIdAsLong();
  669. orderDonService.closeUpgradeOrder(orderId, userId);
  670. return GatewayResponse.SUCCESS.newBuilder().toResult();
  671. }
  672. /**
  673. * midjourney查询订单用户账号剩余次数
  674. */
  675. @GetMapping("/get/midjourney/user")
  676. public Result<MidjourneyUserView> getMidjourneyUser(Long relationId) {
  677. long userId = StpUserUtil.getLoginIdAsLong();
  678. MidjourneyUserView search = beanSearcher.searchFirst(MidjourneyUserView.class, MapUtils.flatBuilder(request.getParameterMap())
  679. .field(MidjourneyUserView::getUserId, userId).field(MidjourneyUserView::getRelationId, relationId).build());
  680. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  681. }
  682. }