FrontECardController.java 18 KB

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