1.引入maven依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
2.編寫freemark文件。(freemarker在springboot2.20后的版本后綴是ftlh)
<script> function onBridgeReady(){ WeixinJSBridge.invoke( 'getBrandWCPayRequest', { "appId":"${payResponse.appId}", //公眾號名稱,由商戶傳入 "timeStamp":"${payResponse.timeStamp}", //時間戳,自1970年以來的秒數 "nonceStr":"${payResponse.nonceStr}", //隨機串 "package":"${payResponse.packAge}", "signType":"${payResponse.signType}", //微信簽名方式: "paySign":"${payResponse.paySign}" //微信簽名 }, function(res){ if(res.err_msg == "get_brand_wcpay_request:ok" ){ // 使用以上方式判斷前端返回,微信團隊鄭重提示: //res.err_msg將在用戶支付成功后返回ok,但並不保證它絕對可靠。 } }); } if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', onBridgeReady); document.attachEvent('onWeixinJSBridgeReady', onBridgeReady); } }else{ onBridgeReady(); } </script>
3.編寫相應的controller將數據傳輸至剛剛編寫的freemark文件
@GetMapping("/create") public ModelAndView create(@RequestParam("orderId") String orderId, @RequestParam("returnUrl") String returnUrl) { //1. 查詢訂單 OrderDTO orderDTO = orderService.findOne(orderId); if (orderDTO == null) { throw new SellException(ResultEnum.ORDER_NOT_EXIST); } //發起支付 PayResponse payResponse = payService.create(orderDTO); log.info("payResponse={}", JsonUtil.toJson(payResponse)); Map<String,Object> result=new HashMap<>(); result.put("payResponse",payResponse); result.put("returnUrl",returnUrl); return new ModelAndView("pay/create",result); //將數據傳輸至freemark文件 }