Sfoglia il codice sorgente

Merge remote-tracking branch 'origin/dev' into dev

hejq 8 anni fa
parent
commit
25299e1fed

+ 2 - 2
donate-service/pom.xml

@@ -188,13 +188,13 @@
         <dependency>
             <groupId>com.github.binarywang</groupId>
             <artifactId>weixin-java-pay</artifactId>
-            <version>2.8.6.BETA</version>
+            <version>2.8.9.BETA</version>
         </dependency>
 
         <dependency>
             <groupId>com.github.binarywang</groupId>
             <artifactId>weixin-java-mp</artifactId>
-            <version>2.8.6.BETA</version>
+            <version>2.8.9.BETA</version>
         </dependency>
         <!--        <dependency>
                     <groupId>org.apache.commons</groupId>

+ 2 - 0
donate-service/src/main/java/com/uas/service/donate/config/WxConfig.java

@@ -11,4 +11,6 @@ public class WxConfig {
 
     public static String Token = "huangchengtian";
 
+    public static String oauthUserScope = "snsapi_userinfo";
+
 }

+ 44 - 13
donate-service/src/main/java/com/uas/service/donate/controller/IndexController.java

@@ -1,12 +1,9 @@
 package com.uas.service.donate.controller;
 
 import com.alibaba.fastjson.JSONObject;
-import com.github.binarywang.wxpay.exception.WxPayException;
 import com.uas.service.donate.api.WxPayApi;
 import com.uas.service.donate.config.WxConfig;
 import com.uas.service.donate.model.Project;
-import com.uas.service.donate.model.SystemSession;
-import com.uas.service.donate.model.User;
 import com.uas.service.donate.model.WechatUserInfo;
 import com.uas.service.donate.service.CarouselService;
 import com.uas.service.donate.service.ProjectRecodeService;
@@ -46,17 +43,51 @@ public class IndexController {
 
     private Logger logger = LoggerFactory.getLogger(IndexController.class);
 
-    private String oauthUserScope = "snsapi_userinfo";
-
-
     @RequestMapping(value = "/", method = RequestMethod.GET)
     public String returnaDefault(HttpServletRequest request, HttpServletResponse response) throws IOException {
         String code = request.getParameter("code");
         String state = request.getParameter("state");
-        User user = SystemSession.getUser();
-
         String ua = request.getHeader("user-agent").toLowerCase();
         if (ua.indexOf("micromessenger") >= 0) {// 是微信浏览器
+            Object openId = request.getSession().getAttribute("openId");
+            if (openId != null) {
+                //有openid 已授权
+                logger.info("有openid 已授权");
+                return "forward:/index";
+            } else {
+                //需要授权
+                logger.info("公众号获取:--需要授权");
+                //String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxPayApi.getConfig().getAppId() + "&redirect_uri=" + URLEncoder.encode("http://lj.ubtob.com/", "UTF-8") + "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
+                String url = WechatConnector.createAuthorizeUrl(WxConfig.oauthUserScope, wxPayApi.getConfig().getAppId(), URLEncoder.encode("http://lj.ubtob.com", "UTF-8"));
+                response.sendRedirect(url);
+            }
+        }
+
+        if (code != null) {
+            //授权回调
+            logger.info("公众号获取,授权回调:authCode=" + code + ",state=" + state);
+
+            String openId = null;
+            try {
+                if ("snsapi_userinfo".equals(WxConfig.oauthUserScope)) {
+                    WechatUserInfo wechatUserInfo= WechatConnector.getOauthUser(code, wxPayApi.getConfig().getAppId(), WxConfig.APPSECRET); //TODO APPSECRET
+                    logger.info("微信用户授权信息:" + wechatUserInfo.toString());
+                    openId = wechatUserInfo.getOpenId();
+                } else if ("snsapi_base".equals(WxConfig.oauthUserScope)) {
+                    JSONObject tokenJson = WechatConnector.getAccessToken(code, wxPayApi.getConfig().getAppId(), WxConfig.APPSECRET);//TODO APPSECRET
+                    openId = tokenJson.getString("openid");
+                }
+
+                //openId = wxPayApi.authcode2Openid(code);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+            request.getSession().setAttribute("openId", openId);
+            logger.info("当前微信用户openId:" + openId);
+        }
+
+
+        /*if (ua.indexOf("micromessenger") >= 0) {// 是微信浏览器
 
             if (user != null && user.getWxOpenId() != null) {
                 //有用户 有openid 已授权
@@ -66,13 +97,13 @@ public class IndexController {
                 //有用户 无openid 需要授权
                 logger.info("公众号获取:--有用户 无openid 需要授权");
                 //String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxPayApi.getConfig().getAppId() + "&redirect_uri=" + URLEncoder.encode("http://lj.ubtob.com/", "UTF-8") + "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
-                String url = WechatConnector.createAuthorizeUrl(oauthUserScope, wxPayApi.getConfig().getAppId(), URLEncoder.encode("http://lj.ubtob.com", "UTF-8"));
+                String url = WechatConnector.createAuthorizeUrl(WxConfig.oauthUserScope, wxPayApi.getConfig().getAppId(), URLEncoder.encode("http://lj.ubtob.com", "UTF-8"));
                 response.sendRedirect(url);
             } else if (user == null && code == null) {
                 //需要授权
                 logger.info("公众号获取:--需要授权");
                 //String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxPayApi.getConfig().getAppId() + "&redirect_uri=" + URLEncoder.encode("http://lj.ubtob.com/", "UTF-8") + "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
-                String url = WechatConnector.createAuthorizeUrl(oauthUserScope, wxPayApi.getConfig().getAppId(), URLEncoder.encode("http://lj.ubtob.com", "UTF-8"));
+                String url = WechatConnector.createAuthorizeUrl(WxConfig.oauthUserScope, wxPayApi.getConfig().getAppId(), URLEncoder.encode("http://lj.ubtob.com", "UTF-8"));
                 response.sendRedirect(url);
             }
         }
@@ -86,11 +117,11 @@ public class IndexController {
             }
             String openId = null;
             try {
-                if ("snsapi_userinfo".equals(oauthUserScope)) {
+                if ("snsapi_userinfo".equals(WxConfig.oauthUserScope)) {
                     WechatUserInfo wechatUserInfo= WechatConnector.getOauthUser(code, wxPayApi.getConfig().getAppId(), WxConfig.APPSECRET); //TODO APPSECRET
                     logger.info("微信用户授权信息:" + wechatUserInfo.toString());
                     openId = wechatUserInfo.getOpenId();
-                } else if ("snsapi_base".equals(oauthUserScope)) {
+                } else if ("snsapi_base".equals(WxConfig.oauthUserScope)) {
                     JSONObject tokenJson = WechatConnector.getAccessToken(code, wxPayApi.getConfig().getAppId(), WxConfig.APPSECRET);//TODO APPSECRET
                     openId = tokenJson.getString("openid");
                 }
@@ -104,7 +135,7 @@ public class IndexController {
             user.setWxOpenId(openId);
             logger.info("当前用户信息:" + user.toString());
             SystemSession.setUser(user);
-        }
+        }*/
 
         return "forward:/index";
     }

+ 38 - 9
donate-service/src/main/java/com/uas/service/donate/controller/WxpayController.java

@@ -21,6 +21,7 @@ import com.uas.service.donate.service.ProjectRecodeService;
 import com.uas.service.donate.service.WechatOrderService;
 import com.uas.service.donate.util.IpUtils;
 import com.uas.service.donate.util.StringUtils;
+import com.uas.service.donate.util.WechatConnector;
 import com.uas.service.donate.util.WxCheckoutUtil;
 import org.apache.commons.io.IOUtils;
 import org.slf4j.Logger;
@@ -126,14 +127,27 @@ public class WxpayController {
         }
 
         WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = createWxPayUnifiedOrderRequest(request, projectRecode, WxPayConstants.TradeType.JSAPI);
-        User user =SystemSession.getUser();
+        //User user =SystemSession.getUser();
         String openId = null;
-        if (user != null) {
+        Object openIdObj = request.getSession().getAttribute("openId");
+        /*if (user != null && user.getWxOpenId() != null) {
+            logger.info("当前用户信息:" + user.toString());
             openId = user.getWxOpenId();
+        } else {
+            logger.info("公众号支付缺少openId:--需要用户授权");
+            String url = WechatConnector.createAuthorizeUrl(WxConfig.oauthUserScope, wxPayApi.getConfig().getAppId(), URLEncoder.encode("http://lj.ubtob.com", "UTF-8"));
+            response.sendRedirect(url);
+        }*/
+
+        if (openIdObj != null) {
+            openId = (String) openIdObj;
+            logger.info("当前微信用户信息:" + openId);
+        } else {
+            logger.info("公众号支付缺少openId:--需要用户授权");
+            String url = WechatConnector.createAuthorizeUrl(WxConfig.oauthUserScope, wxPayApi.getConfig().getAppId(), URLEncoder.encode("http://lj.ubtob.com", "UTF-8"));
+            response.sendRedirect(url);
         }
 
-        openId = "o8lZ9uPU0cQRhPIEejd8XIuD6Urc";
-
         logger.info("公众号支付处理:openId=" + openId);
         if (StringUtils.isEmpty(wxPayApi.getConfig().getSubAppId())) {
             wxPayUnifiedOrderRequest.setOpenid(openId);//否是 trade_type=JSAPI,此参数必传,用户在主商户appid下的唯一标识。openid和sub_openid可以选传其中之一,如果选择传sub_openid,则必须传sub_appid。
@@ -148,13 +162,28 @@ public class WxpayController {
         } else {
             //modelMap.put("outTradeNo", projectRecode.getId());
             //将prepayId返回给js
-            modelMap.put("appId", wxPayApi.getConfig().getAppId());
-            modelMap.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
-            modelMap.put("nonceStr", wxPayUnifiedOrderRequest.getNonceStr());//String.valueOf(System.currentTimeMillis()
-            modelMap.put("package", "prepay_id=" + map.get("prepayId"));
+            String nonceStr = String.valueOf(System.currentTimeMillis());
+            String timeStamp = String.valueOf(Long.parseLong(nonceStr) / 1000);
+            String appId = wxPayApi.getConfig().getAppId();
+            String packagePrepayId = "prepay_id=" + map.get("prepayId");
+            modelMap.put("appId", appId);
+            modelMap.put("timeStamp", timeStamp);
+            modelMap.put("nonceStr", nonceStr);
+            modelMap.put("package", packagePrepayId);
             modelMap.put("signType", "MD5");
+
+            logger.info("参数--" + appId + "," + timeStamp + "," + nonceStr + "," + packagePrepayId);
+            Map<String, String> signMap = new HashMap<>();
+            signMap.put("appId", appId);
+            signMap.put("timeStamp", timeStamp);
+            signMap.put("nonceStr", nonceStr);
+            signMap.put("package", packagePrepayId);
+            signMap.put("signType", "MD5");
+
             //预付订单再次签名
-            String packageSign = SignUtils.createSign(map, WxPayConstants.SignType.MD5, wxPayApi.getConfig().getMchKey(), false);
+            String packageSign = SignUtils.createSign(signMap, "MD5", wxPayApi.getConfig().getMchKey(), false);
+            logger.info("预付订单再次签名验签--" + SignUtils.checkSign(signMap, "MD5", wxPayApi.getConfig().getMchKey()));
+
             modelMap.put("paySign", packageSign);
         }
 

+ 21 - 1
donate-service/src/main/resources/templates/index.ftl

@@ -14,8 +14,8 @@
     <link rel="stylesheet" href="static/css/base.css">
     <link rel="stylesheet" type="text/css" href="static/css/kkpager_orange.css" />
 
-    <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
     <script type="text/javascript" src ="static/js/pay.js"></script>
+    <script type="text/javascript" src ="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
     <style>
         body{
             font-family: "Microsoft Yahei", "微软雅黑";
@@ -861,6 +861,26 @@
     $('.close').click(function(){
         $(this).parent().parent().css('display','none');
         $("#hover-background").css('display','none');
+
+        //重置弹出框条件
+//        var lis = $('#choose-money li');
+//        for (var i=0;i<lis.length; i++) {
+//            $(lis[i]).removeClass('active');
+//        }
+//        $(lis[0])..addClass('active');
+//
+//        var divs = $('#pay-way div.item');
+//        for (var i=0;i<divs.length; i++) {
+//            $(divs[i]).removeClass('active');
+//        }
+//        $(divs[0])..addClass('active');
+//
+//        var inputs = $(.write input);
+//        for (var i=0;i<inputs.length; i++) {
+//            $(inputs[i]).attr('value', '');
+//        }
+
+
     })
     function donate(e){
         $('.pop').css('display','none');

+ 74 - 12
donate-service/src/main/webapp/resources/js/pay.js

@@ -140,22 +140,65 @@ var unionPay  = function () {
 
 /*公众号支付*/
 var webPay = function (jsonStr) {
+    // var xmlHttpRequest;
+    //
+    // $(function(){
+    //     if(window.XMLHttpRequest){
+    //         xmlHttpRequest=new XMLHttpRequest();
+    //     }else{
+    //         xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
+    //     }
+    //     //xmlHttpRequest.responseType = 'json';
+    //     //xmlHttpRequest.setRequestHeader('Content-type','application/x-www-form-urlencoded');
+    //     xmlHttpRequest.onreadystatechange = back;
+    //     xmlHttpRequest.open('POST','/wxpay/webPay',true);
+    //     xmlHttpRequest.send('jsonStr=' + jsonStr);
+    //     function back() {
+    //         if(xmlHttpRequest.status == 200 || xmlHttpRequest.readyState == 4){
+    //             alert(xmlHttpRequest.responseText);
+    //             var resJsonObj=JSON.parse(xmlHttpRequest.responseText);
+    //             if (resJsonObj.error != null) {
+    //                 alert(resJsonObj.error);
+    //                 return;
+    //             }
+    //
+    //             alert("0");
+    //
+    //             if (typeof WeixinJSBridge == "undefined") {
+    //                 alert("1");
+    //                 if (document.addEventListener) {
+    //                     document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
+    //                 } else if (document.attachEvent) {
+    //                     document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
+    //                     document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
+    //                 }
+    //             } else {
+    //                 alert("2");
+    //                 onBridgeReady(resJsonObj);
+    //             }
+    //         }
+    //     }
+    //
+    // });
+
+
     $.ajax({
         url : '/wxpay/webPay',
-        type : 'POST',
+        method : 'post',
         dataType : 'json',
         async: false,
+        contentType: 'application/x-www-form-urlencoded',
         data: {
             jsonStr : jsonStr
         },
         success : function(res) {
-            var resJsonObj=JSON.parse(res);
-            if (resJsonObj.error != null) {
-                alert(resJsonObj.error);
+            if (res.error != null) {
+                alert(res.error);
                 return;
             }
 
             if (typeof WeixinJSBridge == "undefined") {
+                alert("2");
                 if (document.addEventListener) {
                     document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                 } else if (document.attachEvent) {
@@ -163,13 +206,30 @@ var webPay = function (jsonStr) {
                     document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                 }
             } else {
-                onBridgeReady(resJsonObj);
+                onBridgeReady(res);
             }
         },
         error : function() {
             alert('系统异常,请联系客服!');
         }
     });
+
+
+    // $http.post({
+    //     url : '/wxpay/webPay',
+    //     dataType : 'jsonp',
+    //     async: false,
+    //     contentType: 'application/x-www-form-urlencoded',
+    //     data: {
+    //         jsonStr : jsonStr
+    //     },
+    //     success: function() {
+    //         alert('系统异常!');
+    //     },
+    //     error : function() {
+    //         alert('系统异常,请联系客服!');
+    //     }
+    // }).success();
 }
 
 var getJson = function (proId, amount, payWay, uuid) {
@@ -198,15 +258,17 @@ function onBridgeReady(resJsonObj){
         "signType" : resJsonObj.signType, //微信签名方式:       
         "paySign" : resJsonObj.paySign
         //微信签名   
-    }, function(res) {
-        if (res.err_msg == "get_brand_wcpay_request:ok") {
+    },
+    function (res) {
+        // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回    ok,但并不保证它绝对可靠。
+        if (res.err_msg == 'get_brand_wcpay_request:ok') {
             alert("支付成功");
-            // 使用以上方式判断前端返回:res.err_msg将在用户支付成功后返回    ok,但并不保证它绝对可靠。
-        }
-        else{
+            //window.location.href = "${returnUrl}";
+        }else if(res.err_msg == 'get_brand_wcpay_request:cancel'){
+            alert("取消支付");
+        }else{
             alert("支付失败");
-            //res.err_msg;  
-        }
+        } // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回    ok,但并不保证它绝对可靠。
     });
 }