FrontECardController.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. package com.ruoyi.web.controller.front;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
  4. import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryV3Result;
  5. import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
  6. import com.github.binarywang.wxpay.exception.WxPayException;
  7. import com.github.binarywang.wxpay.service.WxPayService;
  8. import com.ruoyi.common.core.controller.BaseController;
  9. import com.ruoyi.common.core.domain.AjaxResult;
  10. import com.ruoyi.common.core.domain.entity.SysUser;
  11. import com.ruoyi.common.enums.ECardPayStatus;
  12. import com.ruoyi.common.utils.DateUtils;
  13. import com.ruoyi.common.utils.SecurityUtils;
  14. import com.ruoyi.common.utils.StringUtils;
  15. import com.ruoyi.common.utils.ip.IpUtils;
  16. import com.ruoyi.common.utils.uuid.IdUtils;
  17. import com.ruoyi.system.service.ISysConfigService;
  18. import com.ruoyi.system.service.ShortMessageService;
  19. import com.ruoyi.voluntary.domain.BBusiEcardPrice;
  20. import com.ruoyi.voluntary.domain.BBusiPaymentOrders;
  21. import com.ruoyi.voluntary.service.IBBusiEcardPriceService;
  22. import com.ruoyi.voluntary.service.IBBusiPaymentOrdersService;
  23. import com.ruoyi.web.service.WeixinPayService;
  24. import com.ruoyi.web.util.IosVerifyUtil;
  25. import eu.bitwalker.useragentutils.UserAgent;
  26. import io.swagger.annotations.Api;
  27. import io.swagger.annotations.ApiOperation;
  28. import io.swagger.v3.oas.annotations.Operation;
  29. import lombok.extern.slf4j.Slf4j;
  30. import org.apache.commons.collections4.CollectionUtils;
  31. import org.apache.commons.lang3.math.NumberUtils;
  32. import org.apache.commons.lang3.tuple.Pair;
  33. import org.springframework.beans.factory.annotation.Autowired;
  34. import org.springframework.beans.factory.annotation.Value;
  35. import org.springframework.web.bind.annotation.*;
  36. import javax.servlet.http.HttpServletRequest;
  37. import java.util.*;
  38. @Api(tags = "前端 电子卡业务")
  39. @RestController
  40. @RequestMapping("front/ecard")
  41. @Slf4j
  42. public class FrontECardController extends BaseController {
  43. @Autowired
  44. private IBBusiEcardPriceService ecardPriceService;
  45. @Autowired
  46. private IBBusiPaymentOrdersService paymentOrdersService;
  47. @Autowired
  48. private ShortMessageService shortMessageService;
  49. @Autowired
  50. private WeixinPayService weixinPayService;
  51. @Autowired
  52. private WxPayService wxService;
  53. @Autowired
  54. private ISysConfigService sysConfigService;
  55. private static final String SUCCESS = "SUCCESS";
  56. private static final String cardDesc = "在线购卡";
  57. public static final String description = "VIP会员";
  58. // @Value("${wxpay.pay.callback}")
  59. // private String payCallback;
  60. @Value("${wxpay.mchid}")
  61. private String mchId;
  62. @Value("${wxpay.key}")
  63. private String mchKey;
  64. // @Value("${wxpay.appid}")
  65. // private String appId = WxMaConfiguration.getAppId();
  66. public String getMchKey() {
  67. return this.mchKey;
  68. }
  69. /**
  70. * {
  71. "amount": {
  72. "currency": "CNY",
  73. "payer_currency": "CNY",
  74. "payer_total": 1,
  75. "total": 1
  76. },
  77. "appid": "wx7b9ff116a897456a",
  78. "attach": "",
  79. "bank_type": "OTHERS",
  80. "mchid": "1629698256",
  81. "out_trade_no": "test_order_t1",
  82. "payer": {
  83. "openid": "o8uY95w2o4T-xq6e8tjKTDRr2tFg"
  84. },
  85. "promotion_detail": [],
  86. "success_time": "2022-08-23T23:55:35+08:00",
  87. "trade_state": "SUCCESS",
  88. "trade_state_desc": "支付成功",
  89. "trade_type": "NATIVE",
  90. "transaction_id": "4200001565202208236598567532"
  91. }
  92. * @return
  93. */
  94. @ApiOperation(value = "5 重新生成二维码")
  95. @GetMapping("/regenerateQrCode")
  96. public AjaxResult regenerateQrCode(@RequestParam Long orderId) {
  97. BBusiPaymentOrders order = paymentOrdersService.selectBBusiPaymentOrdersById(orderId);
  98. String codeUrl = StringUtils.EMPTY;
  99. if(StringUtils.isBlank(order.getQrcodeId())){
  100. try {
  101. codeUrl = weixinPayService.createOrderPayUrl(order.getPhonenumber()+"_"+orderId, order.getPayFee(), "单招"+cardDesc, null);
  102. order.setQrcodeId(codeUrl);
  103. paymentOrdersService.updateBBusiPaymentOrders(order);
  104. } catch (Exception e) {
  105. weixinPayService.processWxPayFail(orderId, null, e.getMessage());
  106. logger.error("QrCodeId: ", e);
  107. }
  108. }else {
  109. codeUrl = order.getQrcodeId();
  110. }
  111. String qrCode = weixinPayService.encodeQrCode(codeUrl);
  112. JSONObject result = new JSONObject();
  113. result.put("qrCode",qrCode);
  114. result.put("orderId",orderId);
  115. result.put("isPaySuccess",ECardPayStatus.isSuccess(order.getStatus()));
  116. return AjaxResult.success(result);
  117. }
  118. @ApiOperation(value = "4 获取订单状态")
  119. @GetMapping("/getOrderPayStatus")
  120. public AjaxResult getOrderPayStatus(@RequestParam Long orderId) {
  121. BBusiPaymentOrders order = paymentOrdersService.selectBBusiPaymentOrdersById(orderId);
  122. JSONObject result = new JSONObject();
  123. result.put("isPaySuccess",ECardPayStatus.isSuccess(order.getStatus()));
  124. result.put("isPayFailed",ECardPayStatus.isFaild(order.getStatus()));
  125. result.put("isUnPaid",ECardPayStatus.isUnPaid(order.getStatus()));
  126. return AjaxResult.success(result);
  127. }
  128. @Operation(summary = "查询订单")
  129. @GetMapping("/queryOrder")
  130. public WxPayOrderQueryV3Result queryOrder(@RequestParam(required = false) String transactionId,
  131. @RequestParam(required = false) String outTradeNo) throws Exception {
  132. WxPayOrderQueryV3Result result = wxService.queryOrderV3(transactionId, outTradeNo);
  133. if("NOTPAY".equals(result.getTradeState())) {
  134. Integer timeout = NumberUtils.toInt(sysConfigService.selectConfigByKey("pay.order.timeout"), 60);
  135. Date timeoutDate = DateUtils.addSeconds(new Date(), -timeout);
  136. BBusiPaymentOrders poCond = new BBusiPaymentOrders();
  137. poCond.setOutTradeNo(outTradeNo);
  138. poCond.setTransactionId(transactionId);
  139. List<BBusiPaymentOrders> orders = paymentOrdersService.selectBBusiPaymentOrdersList(poCond);
  140. if(CollectionUtils.isEmpty(orders) || orders.get(0).getCreateTime().before(timeoutDate)) {
  141. result.setTradeState("CLOSED");
  142. result.setTradeStateDesc("超时关闭");
  143. }
  144. }
  145. return result;
  146. }
  147. @ApiOperation(value = "3 支付通知(回调)")
  148. @PostMapping("/payResult")
  149. public AjaxResult wxPayResult(HttpServletRequest request,
  150. @RequestHeader("wechatpay-serial") String serial, @RequestHeader("wechatpay-signature-type") String signatureType,
  151. @RequestHeader("wechatpay-timestamp") String timestamp, @RequestHeader("wechatpay-nonce") String nonce,
  152. @RequestHeader("wechatpay-signature") String signature, @RequestBody String json) {
  153. logger.error("----------------------开始处理微信支付回调--------------");
  154. // String json = readBody(req);
  155. try {
  156. weixinPayService.processWxPayResult(serial, signatureType, timestamp, nonce, signature, json);
  157. } catch (Exception e) {
  158. logger.error("处理微信回调失败: " + signature + "\n" + json, e);
  159. return AjaxResult.error("解析异常");
  160. }
  161. return AjaxResult.success();
  162. }
  163. @ApiOperation("02 测试支付")
  164. @GetMapping(value = "checktest")
  165. public AjaxResult checkTest() {
  166. weixinPayService.checkWxPay();
  167. return AjaxResult.success();
  168. }
  169. @ApiOperation("02 测试支付")
  170. @GetMapping(value = "paytest")
  171. public AjaxResult paytest(String id, Integer amount, @RequestParam(defaultValue = "false") boolean h5, HttpServletRequest request) {
  172. try {
  173. String os = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getOperatingSystem().getName();
  174. String ip = IpUtils.getIpAddr(request);
  175. WeixinPayService.PayOrderSceneInfo sceneInfo = h5 ? new WeixinPayService.PayOrderSceneInfo(ip, os) : null;
  176. String codeUrl = weixinPayService.createOrderPayUrl("test_pay_" + id, amount, "Test" + id, sceneInfo);
  177. return AjaxResult.success(weixinPayService.encodeQrCode(codeUrl));
  178. } catch (Exception e) {
  179. logger.error("QrCodeId: ", e);
  180. return AjaxResult.error(e.getMessage());
  181. }
  182. }
  183. @ApiOperation("02 下单生成地址")
  184. @PostMapping(value = "createOrder")
  185. public AjaxResult createOrder(HttpServletRequest request, Double totalFee, @RequestParam(required = false) String type) throws WxPayException {
  186. if (null==totalFee){
  187. AjaxResult.error("金额不能为空");
  188. }
  189. if(StringUtils.isBlank(type)) {
  190. type = "h5";
  191. }
  192. SysUser u = SecurityUtils.getLoginUser().getUser();
  193. Integer totalFee2 = (int)(totalFee * 100D);
  194. BBusiPaymentOrders insertOrder = new BBusiPaymentOrders();
  195. insertOrder.setCode(IdUtils.simpleUUID());
  196. insertOrder.setType(cardDesc);
  197. // insertOrder.setOutTime(ecardPrice.getOutTime());
  198. int num = 1;
  199. insertOrder.setNum(num);
  200. insertOrder.setPrice(totalFee2);
  201. insertOrder.setFee(totalFee2);
  202. insertOrder.setTotalFee(totalFee2*num);
  203. insertOrder.setPayFee(totalFee2*num);
  204. insertOrder.setBody(cardDesc+"_"+description+"_" + type);
  205. insertOrder.setPhonenumber(u.getPhonenumber());
  206. insertOrder.setCustomerCode(String.valueOf(u.getUserId()));
  207. insertOrder.setYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
  208. //状态(-2:已退费,-1:支付失败,0:无效,1:未支付,2:已支付)
  209. insertOrder.setStatus(ECardPayStatus.unpaid.getValue());
  210. insertOrder.setCreateTime(new Date());
  211. paymentOrdersService.insertBBusiPaymentOrders(insertOrder);
  212. Long orderId = insertOrder.getId();
  213. if("ios".equals(type)) {
  214. Map data = new HashMap<>();
  215. data.put("orderId", String.valueOf(orderId));
  216. return AjaxResult.success(data);
  217. }
  218. WxPayUnifiedOrderV3Request order = new WxPayUnifiedOrderV3Request();
  219. // Integer totalFee = 1;
  220. String notifyUrl = sysConfigService.selectConfigByKey("pay.callback.url") + "/front/ecard/payResult";
  221. String outTradeNo = u.getPhonenumber() + "_" + orderId + "_" + u.getUserId() +"_"+System.currentTimeMillis();
  222. if(outTradeNo.length() > 30) {
  223. outTradeNo = outTradeNo.substring(0,20) + outTradeNo.substring(outTradeNo.length() - 10);
  224. }
  225. order.setDescription(description).setOutTradeNo(outTradeNo);
  226. order.setNotifyUrl(notifyUrl).setAmount(new WxPayUnifiedOrderV3Request.Amount().setTotal(totalFee2));
  227. WxPayUnifiedOrderV3Request.SceneInfo sceneInfo = new WxPayUnifiedOrderV3Request.SceneInfo();
  228. sceneInfo.setPayerClientIp(IpUtils.getIpAddr(request));
  229. WxPayUnifiedOrderV3Request.H5Info h5Info = new WxPayUnifiedOrderV3Request.H5Info();
  230. String os = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getOperatingSystem().getName();
  231. h5Info.setType(os);
  232. sceneInfo.setH5Info(h5Info);
  233. order.setSceneInfo(sceneInfo);
  234. String h5Url = wxService.createOrderV3(TradeTypeEnum.H5, order);
  235. String prepayId = StringUtils.substringBetween(h5Url, "prepay_id=", "&package=");
  236. BBusiPaymentOrders upOrder = new BBusiPaymentOrders();
  237. upOrder.setPrepayId(prepayId);
  238. upOrder.setDetail(h5Url);
  239. upOrder.setOutTradeNo(outTradeNo);
  240. upOrder.setId(orderId);
  241. paymentOrdersService.updateBBusiPaymentOrders(upOrder);
  242. Map data = new HashMap<>();
  243. data.put("h5url", h5Url);
  244. data.put("outTradeNo", outTradeNo);
  245. return AjaxResult.success(data);
  246. }
  247. @ApiOperation("02 下单生成二维码")
  248. @GetMapping(value = "prepayCard")
  249. public AjaxResult prepayCard(Long ecardPayId, String mobile, String code) {
  250. Pair<Long, String> pair = prepayCard(ecardPayId, mobile, code, null);
  251. if(null == pair) {
  252. return AjaxResult.error("验证码校验失败");
  253. }
  254. String qrCode = weixinPayService.encodeQrCode(pair.getRight());
  255. JSONObject result = new JSONObject();
  256. result.put("qrCode",qrCode);
  257. result.put("orderId",pair.getLeft());
  258. return AjaxResult.success(result);
  259. }
  260. private Pair<Long, String> prepayCard(Long ecardPayId, String mobile, String code, WeixinPayService.PayOrderSceneInfo sceneInfo) {
  261. boolean isSuccess = shortMessageService.checkCode(mobile, code);
  262. if(!isSuccess){
  263. return null;
  264. }
  265. //生成订单
  266. BBusiEcardPrice ecardPrice = ecardPriceService.selectBBusiEcardPriceById(ecardPayId);
  267. //未支付订单,不要多次生成
  268. BBusiPaymentOrders order= paymentOrdersService.selectBBusiPaymentOrdersNoPaid(mobile);
  269. Boolean isInsert = false;
  270. if(null==order){
  271. order=new BBusiPaymentOrders();
  272. isInsert = true;
  273. }
  274. order.setCode(IdUtils.simpleUUID());
  275. order.setType(cardDesc);
  276. //cardId在回调中处理
  277. // order.setCardId(1L);
  278. // order.setCardNo("");
  279. order.setOutTime(ecardPrice.getOutTime());
  280. int num = 1;
  281. order.setNum(num);
  282. order.setFee(ecardPrice.getPrice());
  283. order.setTotalFee(ecardPrice.getPrice()*num);
  284. order.setPayFee(ecardPrice.getPrice()*num);
  285. order.setBody(cardDesc);
  286. order.setPhonenumber(mobile);
  287. order.setYear(String.valueOf(ecardPrice.getYear()));
  288. //状态(-2:已退费,-1:支付失败,0:无效,1:未支付,2:已支付)
  289. order.setStatus(ECardPayStatus.unpaid.getValue());
  290. if(isInsert){
  291. paymentOrdersService.insertBBusiPaymentOrders(order);
  292. }else {
  293. paymentOrdersService.updateBBusiPaymentOrders(order);
  294. }
  295. Long orderId = order.getId();
  296. // TODO 调用微信支付生成二维码返回给前端
  297. try {
  298. String codeUrl = weixinPayService.createOrderPayUrl(mobile+"_"+orderId+"_"+System.currentTimeMillis(), order.getPayFee(), "金鲤志愿"+cardDesc, sceneInfo);
  299. order.setQrcodeId(codeUrl);
  300. } catch (Exception e) {
  301. weixinPayService.processWxPayFail(orderId, null, e.getMessage());
  302. logger.error("QrCodeId: ", e);
  303. }
  304. order.setPrepayId("");//预支付ID
  305. order.setTransactionId("");//交易ID
  306. paymentOrdersService.updateBBusiPaymentOrders(order);
  307. return Pair.of(orderId, order.getQrcodeId());
  308. }
  309. @ApiOperation("01 获取电子卡价格")
  310. @GetMapping(value = "getEcardPrices")
  311. public AjaxResult getEcardPrices() {
  312. BBusiEcardPrice cond = new BBusiEcardPrice();
  313. SysUser sysUser = SecurityUtils.getLoginUser().getUser();
  314. cond.setLocation(sysUser.getLocation());
  315. cond.setExamType(sysUser.getExamType().name());
  316. return AjaxResult.success(ecardPriceService.selectBBusiEcardPriceList(cond));
  317. }
  318. @PostMapping("/iosVerifyResult")
  319. public AjaxResult iosPay(@RequestBody String payload) {
  320. log.info("苹果内购校验开始,base64校验体:{}", payload);
  321. JSONObject reqData = JSONObject.parseObject(payload);
  322. String receiptData;
  323. if(null == reqData || StringUtils.isBlank(receiptData = reqData.getString("receipt"))) {
  324. return error("苹果验证失败,返回数据为空");
  325. }
  326. Long orderId = reqData.getLong("orderId");
  327. String transactionId = reqData.getString("transId");
  328. //线上环境验证
  329. String verifyResult = IosVerifyUtil.buyAppVerify(receiptData, 1);
  330. if (verifyResult == null) {
  331. return error("苹果验证失败,返回数据为空");
  332. } else {
  333. log.info("线上,{}苹果平台返回JSON:{}", orderId, verifyResult);
  334. JSONObject appleReturn = JSONObject.parseObject(verifyResult);
  335. String states = appleReturn.getString("status");
  336. //无数据则沙箱环境验证
  337. if ("21007".equals(states)) {
  338. verifyResult = IosVerifyUtil.buyAppVerify(receiptData, 0);
  339. log.info("沙盒环境,{}苹果平台返回JSON:{}", orderId, verifyResult);
  340. appleReturn = JSONObject.parseObject(verifyResult);
  341. states = appleReturn.getString("status");
  342. }
  343. log.info("苹果平台返回值:appleReturn" + appleReturn);
  344. // 前端所提供的收据是有效的 验证成功
  345. if (states.equals("0")) {
  346. String receipt = appleReturn.getString("receipt");
  347. JSONObject returnJson = JSONObject.parseObject(receipt);
  348. String inApp = returnJson.getString("in_app");
  349. List<HashMap> inApps = JSONObject.parseArray(inApp, HashMap.class);
  350. if (!org.apache.commons.collections.CollectionUtils.isEmpty(inApps)) {
  351. ArrayList<String> transactionIds = new ArrayList<String>();
  352. for (HashMap app : inApps) {
  353. transactionIds.add((String) app.get("transaction_id"));
  354. }
  355. //交易列表包含当前交易,则认为交易成功
  356. if (transactionIds.contains(transactionId)) {
  357. //处理业务逻辑
  358. weixinPayService.processPaySuccess(orderId, transactionId, "SUCCESS", "ios", "");
  359. log.info("交易成功,处理订单:{}",orderId);
  360. return success("交易成功");
  361. }
  362. return error("当前交易不在交易列表中");
  363. }
  364. return error("未能获取获取到交易列表");
  365. } else {
  366. weixinPayService.processPaySuccess(orderId, transactionId, "FAILURE", "ios", states);
  367. return error("支付失败,错误码:" + states);
  368. }
  369. }
  370. }
  371. // https://blog.csdn.net/Arhhhhhhh/article/details/130082795?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-130082795-blog-121291537.235^v43^pc_blog_bottom_relevance_base6&spm=1001.2101.3001.4242.1&utm_relevant_index=2
  372. // https://developer.apple.com/documentation/appstoreserverapi/get-v2-refund-lookup-_transactionid_
  373. }