WxPayController.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. package com.charging.chargingparking.modules.pay.wechat;
  2. import cn.hutool.core.date.DateUtil;
  3. import cn.hutool.core.util.StrUtil;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  6. import com.charging.chargingparking.dto.AccessToken;
  7. import com.charging.chargingparking.dto.MessageResult;
  8. import com.charging.chargingparking.dto.ParkingCostDTO;
  9. import com.charging.chargingparking.dto.UserInfo;
  10. import com.charging.chargingparking.entity.ParkingPay;
  11. import com.charging.chargingparking.entity.ParkingRecord;
  12. import com.charging.chargingparking.modules.pay.properties.WxPayProperties;
  13. import com.charging.chargingparking.service.ParkingFeeService;
  14. import com.charging.chargingparking.service.ParkingPayService;
  15. import com.charging.chargingparking.service.ParkingRecordService;
  16. import com.charging.chargingparking.utils.Sign;
  17. import com.charging.chargingparking.utils.StringUtils;
  18. import com.charging.chargingparking.utils.WeixinUtil;
  19. import com.ijpay.core.enums.SignType;
  20. import com.ijpay.core.enums.TradeType;
  21. import com.ijpay.core.kit.HttpKit;
  22. import com.ijpay.core.kit.WxPayKit;
  23. import com.ijpay.wxpay.WxPayApi;
  24. import com.ijpay.wxpay.model.UnifiedOrderModel;
  25. import lombok.extern.slf4j.Slf4j;
  26. import org.springframework.beans.factory.annotation.Autowired;
  27. import org.springframework.web.bind.annotation.*;
  28. import javax.servlet.http.HttpServletRequest;
  29. import java.math.BigDecimal;
  30. import java.util.Date;
  31. import java.util.HashMap;
  32. import java.util.Map;
  33. /**
  34. * @author 墨鱼_mo
  35. * @date 2022/1/18 0018 上午 9:53
  36. */
  37. @RequestMapping("/wxPay")
  38. @RestController
  39. @Slf4j
  40. public class WxPayController {
  41. @Autowired
  42. private ParkingRecordService parkingRecordService;
  43. @Autowired
  44. private ParkingFeeService parkingFeeService;
  45. @Autowired
  46. private WxPayProperties wxPayProperties;
  47. @Autowired
  48. private ParkingPayService parkingPayService;
  49. /**
  50. * 停车微信JSAPI支付
  51. *
  52. * @param id
  53. * @param openId
  54. * @return
  55. */
  56. @PostMapping("/parkingWxPay")
  57. public MessageResult parkingWxPay(String id, String openId,String codePayType) {
  58. MessageResult msgResult = new MessageResult<>();
  59. try {
  60. if (StrUtil.isBlank(openId)) {
  61. throw new Exception("openId不存在");
  62. }
  63. if (StrUtil.isBlank(id)) {
  64. throw new Exception("订单不存在");
  65. }
  66. ParkingRecord parkingRecord = parkingRecordService.getById(id);
  67. if (parkingRecord == null) {
  68. throw new Exception("记录不存在");
  69. }
  70. //记录总应缴
  71. ParkingCostDTO parkingCostDTO = parkingFeeService.parkingCost(parkingRecord);
  72. BigDecimal parkCost = parkingCostDTO.getNeedAmount();
  73. parkingRecord.setTotalAmount(parkCost);
  74. parkingRecord.setUpdateTime(new Date());
  75. parkingRecordService.updateById(parkingRecord);
  76. if (parkCost.subtract(parkingRecord.getPayAmount()).compareTo(BigDecimal.ZERO) <= 0) {
  77. throw new Exception("请直接离场");
  78. }
  79. //金额处理
  80. int wxTotalTee = parkCost.subtract(parkingRecord.getPayAmount()).multiply(new BigDecimal(100)).intValue();
  81. //创建支付记录
  82. ParkingPay parkingPay = new ParkingPay();
  83. parkingPay.setParkingRecordId(parkingRecord.getId());
  84. parkingPay.setOutOrderNo(wxPayProperties.getUrlKey() + StringUtils.getOutTradeNo());
  85. parkingPay.setCreateTime(new Date());
  86. parkingPay.setOpenId(openId);
  87. parkingPay.setCodePayType(codePayType);
  88. parkingPayService.save(parkingPay);
  89. Map<String, String> params = UnifiedOrderModel
  90. .builder()
  91. .appid(wxPayProperties.getAppId())
  92. // .appid(companyPaymentInfo.getSubAppId())
  93. // .mch_id(companyPaymentInfo.getSubMchId())
  94. .mch_id(wxPayProperties.getMchId())
  95. .sub_mch_id(wxPayProperties.getSubMchId())
  96. // .sub_appid(companyPaymentInfo.getSubAppId())
  97. .nonce_str(WxPayKit.generateStr())
  98. .body(parkingRecord.getProductTheme())
  99. .out_trade_no(parkingPay.getOutOrderNo())
  100. .total_fee(String.valueOf(wxTotalTee))
  101. .spbill_create_ip(wxPayProperties.getIp())
  102. .notify_url(wxPayProperties.getNotifyUrl())
  103. .trade_type(TradeType.JSAPI.getTradeType())
  104. .sub_openid(parkingPay.getOpenId())
  105. .build()
  106. .createSign(wxPayProperties.getMchKey(), SignType.HMACSHA256);
  107. String xmlResult = WxPayApi.pushOrder(false, params);
  108. Map<String, String> resultMap = WxPayKit.xmlToMap(xmlResult);
  109. String returnCode = resultMap.get("return_code");
  110. String returnMsg = resultMap.get("return_msg");
  111. if (!WxPayKit.codeIsOk(returnCode)) {
  112. log.error(returnCode);
  113. throw new Exception(returnMsg);
  114. }
  115. String resultCode = resultMap.get("result_code");
  116. if (!WxPayKit.codeIsOk(resultCode)) {
  117. String errCode = resultMap.get("err_code_des");
  118. log.error(errCode);
  119. throw new Exception(errCode);
  120. }
  121. // 以下字段在 return_code 和 result_code 都为 SUCCESS 的时候有返回
  122. String prepayId = resultMap.get("prepay_id");
  123. Map<String, String> packageParams = WxPayKit.prepayIdCreateSign(prepayId, wxPayProperties.getAppId(),
  124. wxPayProperties.getMchKey(), SignType.HMACSHA256);
  125. msgResult.setData(packageParams);
  126. msgResult.setResult(true);
  127. } catch (Exception e) {
  128. e.printStackTrace();
  129. log.error(e.getMessage(), e);
  130. msgResult.setResult(false);
  131. msgResult.setCode(400);
  132. msgResult.setMessage(e.getMessage());
  133. }
  134. return msgResult;
  135. }
  136. @RequestMapping(value = "/parkingWxPayNotify", method = {RequestMethod.POST, RequestMethod.GET})
  137. @ResponseBody
  138. public String parkingWxPayNotify(HttpServletRequest request) {
  139. String xmlMsg = HttpKit.readData(request);
  140. log.warn("支付通知=" + xmlMsg);
  141. Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
  142. String returnCode = params.get("return_code");
  143. String outTradeNo = params.get("out_trade_no");
  144. String payTimeStr = params.get("time_end");
  145. String openId = params.get("openid");
  146. String transactionNo = params.get("transaction_id");
  147. BigDecimal buyerPayAmount = new BigDecimal(params.get("total_fee")).divide(new BigDecimal(100));
  148. Date payTime = DateUtil.parse(payTimeStr);
  149. // 注意此处签名方式需与统一下单的签名类型一致 WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey()
  150. if (WxPayKit.verifyNotify(params, wxPayProperties.getMchKey(), SignType.HMACSHA256)) {
  151. if (WxPayKit.codeIsOk(returnCode)) {
  152. try {
  153. parkingPayService.saveAndUpdateRecord(outTradeNo,payTime,buyerPayAmount,openId,transactionNo,"wechat");
  154. // 发送通知等
  155. Map<String, String> xml = new HashMap<String, String>(2);
  156. xml.put("return_code", "SUCCESS");
  157. xml.put("return_msg", "OK");
  158. return WxPayKit.toXml(xml);
  159. } catch (Exception e) {
  160. log.error(e.getMessage(), e);
  161. e.printStackTrace();
  162. }
  163. }
  164. }
  165. return null;
  166. }
  167. /**
  168. * 获取微信配置
  169. *
  170. * @param url
  171. * @return
  172. */
  173. @GetMapping(value = "/getConfig")
  174. public MessageResult getConfig(String url) {
  175. int code = 200;
  176. String message = "获取成功";
  177. Object data = "";
  178. boolean result = true;
  179. try {
  180. AccessToken token = WeixinUtil.getAccessToken(wxPayProperties.getAppId(), wxPayProperties.getAppSecret());
  181. Map<String, String> wxMap = Sign.sign(WeixinUtil.getJsAPI(token.getToken()), url);
  182. wxMap.put("appId", wxPayProperties.getAppId());
  183. log.warn(JSONObject.toJSONString(wxMap));
  184. HashMap<String, Object> dataMap = new HashMap<String, Object>();
  185. dataMap.put("wxConfig", wxMap);
  186. data = dataMap;
  187. } catch (Exception ex) {
  188. log.error(ex.getMessage(), ex);
  189. code = 500;
  190. result = false;
  191. message = "系统错误";
  192. }
  193. return new MessageResult(result, message, data, code);
  194. }
  195. /**
  196. * 获取微信code
  197. *
  198. * @param url
  199. * @return
  200. */
  201. @PostMapping(value = "findWechatUrl")
  202. public MessageResult findWechatUrl(@RequestBody String url) {
  203. String newpath = WeixinUtil.getCodeRequest(wxPayProperties.getSubAppId(), url, "snsapi_userinfo");
  204. HashMap<String, Object> dataMap = new HashMap<String, Object>();
  205. dataMap.put("wechatUrl", newpath);
  206. return new MessageResult(true, "获取成功", dataMap, 200);
  207. }
  208. /**
  209. * 获取公众号用户信息
  210. *
  211. * @param code
  212. * @return
  213. */
  214. @GetMapping(value = "findUserInfo/{code}")
  215. public MessageResult findUserInfo(@PathVariable String code) {
  216. try {
  217. log.warn("code=" + code);
  218. log.warn("appId=" + wxPayProperties.getSubAppId());
  219. log.warn("appSecret=" + wxPayProperties.getSubAppSecret());
  220. AccessToken at = WeixinUtil.getAccessToken(wxPayProperties.getSubAppId(), wxPayProperties.getSubAppSecret(), code);
  221. if (at != null && org.apache.commons.lang3.StringUtils.isNotBlank(at.getOpenid())) {
  222. String openId = at.getOpenid();
  223. System.out.println("openId:" + openId);
  224. UserInfo userInfo = WeixinUtil.getUserInfo(openId, at.getToken());
  225. HashMap<String, Object> dataMap = new HashMap<String, Object>();
  226. dataMap.put("userInfo", userInfo);
  227. return new MessageResult(true, "获取微信信息成功", userInfo, 200);
  228. } else {
  229. return new MessageResult(false, "获取微信信息失败", "", 400);
  230. }
  231. } catch (Exception ex) {
  232. ex.printStackTrace();
  233. return new MessageResult(false, "系统错误", "", 500);
  234. }
  235. }
  236. }