From 6159dc58f50d3e4680779b7989bbd4d49a76bad5 Mon Sep 17 00:00:00 2001
From: admin <weikou2014>
Date: 星期五, 09 五月 2025 19:13:35 +0800
Subject: [PATCH] 添加日志

---
 src/main/java/com/taoke/autopay/controller/WebApiController.java |  377 ++++++++++++++++++++++++++++++++++++++++++++++++++---
 1 files changed, 351 insertions(+), 26 deletions(-)

diff --git a/src/main/java/com/taoke/autopay/controller/WebApiController.java b/src/main/java/com/taoke/autopay/controller/WebApiController.java
index dafd7b6..c4fdc9a 100644
--- a/src/main/java/com/taoke/autopay/controller/WebApiController.java
+++ b/src/main/java/com/taoke/autopay/controller/WebApiController.java
@@ -1,58 +1,383 @@
 package com.taoke.autopay.controller;
 
+import com.google.gson.Gson;
+import com.taoke.autopay.dto.DYOrderDto;
+import com.taoke.autopay.dto.WXAppInfoDto;
 import com.taoke.autopay.entity.KeyOrder;
+import com.taoke.autopay.entity.SystemConfigKeyEnum;
+import com.taoke.autopay.entity.WxUserInfo;
+import com.taoke.autopay.entity.agent.ChannelAgent;
 import com.taoke.autopay.exception.KeyOrderException;
-import com.taoke.autopay.factory.OrderFactory;
+import com.taoke.autopay.exception.KeyVerifyException;
+import com.taoke.autopay.exception.WxOrderCountException;
+import com.taoke.autopay.manager.PayCountVerifyManager;
 import com.taoke.autopay.service.KeyOrderService;
-import com.taoke.autopay.utils.JsonUtil;
-import com.taoke.autopay.utils.StringUtil;
+import com.taoke.autopay.service.SystemConfigService;
+import com.taoke.autopay.service.WxUserService;
+import com.taoke.autopay.service.agent.ChannelAgentService;
+import com.taoke.autopay.utils.*;
+import com.taoke.autopay.vo.SubmitKeyInfo;
+import net.sf.json.JSONObject;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Controller;
+import org.springframework.util.AntPathMatcher;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.yeshi.utils.UrlUtils;
 
 import javax.annotation.Resource;
-import java.io.PrintWriter;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.IOException;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
 @Controller
 @RequestMapping("webapi")
 public class WebApiController {
     Logger logger = LoggerFactory.getLogger(WebApiController.class);
 
+    Logger wxLogger = LoggerFactory.getLogger("wxLogger");
+
+    Logger verifyLogger = LoggerFactory.getLogger("keyVerifyLogger");
+
+
     @Resource
     private KeyOrderService keyOrderService;
 
+    @Resource
+    private WxUserService wxUserService;
 
-    @ResponseBody
-    @RequestMapping(value = "submitKey")
-    public String submitKey(String  key) {
-        if(StringUtil.isNullOrEmpty(key)){
-           return JsonUtil.loadFalseResult(0,"璇蜂笂浼爇ey");
+    @Resource
+    private SystemConfigService systemConfigService;
+    @Resource
+    private PayCountVerifyManager payCountVerifyManager;
+
+    @Resource
+    private ChannelAgentService channelAgentService;
+
+
+    private KeyOrder addKey(SubmitKeyInfo keyInfo, Long wxUid) throws KeyVerifyException, KeyOrderException, WxOrderCountException {
+
+        // 鏌ヨ娌℃湁澶勭悊鐨勬暟閲�
+        long notProcessCount = keyOrderService.countUserNotDoOrder(wxUid, new Date(System.currentTimeMillis() - 1000 * 60 * 30));
+        if (notProcessCount > 0) {
+            throw new WxOrderCountException("涓婁竴涓彛浠ゅ皻鏈鐞嗗畬锛�");
         }
-       List<String> urllist =  UrlUtils.parseUrlsFromText(key);
-       if(urllist.isEmpty()||!urllist.get(0).contains("ur.alipay.com")){
-           return JsonUtil.loadFalseResult("鏀粯瀹濆彛浠や笉姝g‘");
-       }
-        try {
-            KeyOrder order =   keyOrderService.addKeyOrder(key);
 
-            Long uid =  keyOrderService.getCanDistributeUid();
-            if(uid!=null){
-                KeyOrder orderUpdate=new KeyOrder();
-                orderUpdate.setId(order.getId());
-                orderUpdate.setDistributeClientUid(uid);
-                orderUpdate.setDistributeTime(new Date());
-                keyOrderService.update(orderUpdate);
+        // 瑙f瀽閾炬帴
+        List<String> urllist = UrlUtils.parseUrlsFromText(keyInfo.getKey());
+        String verifyAlipayKey = systemConfigService.getValueCache(SystemConfigKeyEnum.ALIPAY_KEY_VERIFY);
+        DYOrderDto orderDto = null;
+        int orderType = Constant.ORDER_TYPE_UNKNOWN;
+        if (verifyAlipayKey != null && verifyAlipayKey.trim().equalsIgnoreCase("1")) {
+            try {
+                // 闇�瑕侀獙璇佹敮浠樺疂鍙d护
+                if (urllist.isEmpty()) {
+                    throw new Exception("鍙d护涓笉鍖呭惈閾炬帴");
+                }
+                AlipayOrderUtil.AlipayOrderTradeInfo tradeInfo = AlipayOrderUtil.getTradeInfo(urllist.get(0));
+                String orderStatus = "";
+                switch (tradeInfo.getStatus()) {
+                    case AlipayOrderUtil.AlipayOrderTradeInfo.STATUS_CANCELED:
+                        orderStatus = "璁㈠崟宸插彇娑�";
+                        break;
+                    case AlipayOrderUtil.AlipayOrderTradeInfo.STATUS_PAY:
+                        orderStatus = "璁㈠崟宸叉敮浠�";
+                        break;
+                    case AlipayOrderUtil.AlipayOrderTradeInfo.STATUS_NOT_PAY:
+                        orderStatus = "璁㈠崟鏈敮浠�";
+                        break;
+                }
+                if (tradeInfo == null) {
+                    throw new Exception("鍙d护鍐呭鑾峰彇澶辫触");
+                }
+                orderType = AlipayOrderUtil.getOrderType(tradeInfo.getGoodsTitle());
+                // 楠岃瘉鍐呭
+                orderDto = keyOrderService.verifyKey(tradeInfo.getGoodsTitle(), orderStatus, tradeInfo.getItemRealAmount(), wxUid, null);
+            } catch (KeyVerifyException ee) {
+                try {
+                    verifyLogger.warn("鏍¢獙涓嶉�氳繃锛氥�恵}銆�-{}", keyInfo.getKey(), ee.getMessage());
+                } catch (Exception e) {
+                }
+                throw ee;
+            } catch (Exception e) {
+                throw new KeyVerifyException(KeyVerifyException.CODE_COMMON, e.getMessage());
             }
-            return JsonUtil.loadTrueResult("");
-        } catch (KeyOrderException e) {
-            e.printStackTrace();
-           return JsonUtil.loadFalseResult(e.getMessage());
+        }
+        KeyOrder order = keyOrderService.addKeyOrder(keyInfo, wxUid, TimeUtil.getGernalTime(System.currentTimeMillis(), Constant.DB_DAY_FORMAT), orderType, orderDto);
+        Long uid = keyOrderService.getCanDistributeUid(Constant.MAX_PAY_ACCOUNT_QUEUE_SIZE);
+        if (uid != null) {
+            KeyOrder orderUpdate = new KeyOrder();
+            orderUpdate.setId(order.getId());
+            orderUpdate.setDistributeClientUid(uid);
+            orderUpdate.setDistributeTime(new Date());
+            keyOrderService.update(orderUpdate);
+        }
+        return order;
+    }
+
+    private void verifySubmitKey(String key) throws Exception {
+        List<String> urllist = UrlUtils.parseUrlsFromText(key);
+        if (urllist.isEmpty() || !urllist.get(0).contains("ur.alipay.com")) {
+            throw new Exception("涓嶅寘鍚敮浠樺疂閾炬帴");
+        }
+        if (!key.contains("鏀粯瀹�")) {
+            throw new Exception("娌″寘鍚敮浠樺疂姹夊瓧");
         }
     }
 
+    private Map<String, IPUtil.IPInfo> ipInfoMap = new HashMap<>();
+
+    @ResponseBody
+    @RequestMapping(value = "submitKeyV4")
+    public String submitKeyV4(SubmitKeyInfo keyInfo, HttpSession session, HttpServletRequest request) {
+        String referer = request.getHeader("Referer");
+        keyInfo.setReferer(referer);
+        WxUserInfo user = (WxUserInfo) session.getAttribute(Constant.SESSION_KEY_USER);
+        if (StringUtil.isNullOrEmpty(keyInfo.getKey())) {
+            return JsonUtil.loadFalseResult("璇蜂笂浼爇ey");
+        }
+        String ip = IPUtil.getRemotIP(request);
+        keyInfo.setIp(ip);
+        if (!ipInfoMap.containsKey(ip)) {
+            try {
+                IPUtil.IPInfo ipInfo = IPUtil.getLocalIPInfo(ip);
+                ipInfoMap.put(ip, ipInfo);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }
+        keyInfo.setIpInfo(ipInfoMap.get(ip));
+
+        AntPathMatcher pathMatcher = new AntPathMatcher();
+
+        Map<String, String> paramsMap = HttpUtil.getPramsFromUrl(keyInfo.getReferer());
+        if (paramsMap.containsKey("a") && ipInfoMap.get(ip) != null) {
+            String alias = paramsMap.get("a");
+            ChannelAgent agent = channelAgentService.selectByAlias(alias);
+            if (!StringUtil.isNullOrEmpty(agent.getShieldedAreas())) {
+                String[] res = agent.getShieldedAreas().split(",");
+                String ipInfoStr = ipInfoMap.get(ip).getProvince() + "/" + ipInfoMap.get(ip).getCity();
+                boolean shield = false;
+                for (String pattern : res) {
+                    if (pathMatcher.match(pattern, ipInfoStr)) {
+                        shield = true;
+                        break;
+                    }
+                }
+                if (shield) {
+                    // 鍒ゆ柇鐢ㄦ埛鏄惁涓虹櫧鍚嶅崟
+                    if (user.getStatus() != WxUserInfo.STATUS_WHITE) {
+                        // 涓嶆槸鐧藉悕鍗曟墠闄愬埗
+                        LogUtil.loggerDebug.warn("鍖哄煙灞忚斀锛歿}-{}", ip, new Gson().toJson(ipInfoMap.get(ip)));
+                        return JsonUtil.loadFalseResult("鏆傛椂鏃犳硶涓婁紶鍙d护");
+                    }
+                }
+            }
+        }
+
+        try {
+            verifySubmitKey(keyInfo.getKey());
+        } catch (Exception e) {
+            return JsonUtil.loadFalseResult("鏀粯瀹濆彛浠や笉姝g‘");
+        }
+        // 楠岃瘉鎻愪氦鏃堕棿
+        String timeStr = systemConfigService.getValueCache(SystemConfigKeyEnum.KEY_SUBMIT_TIME_RANGE);
+        if (StringUtil.isNullOrEmpty(timeStr)) {
+            return JsonUtil.loadFalseResult("灏氭湭閰嶇疆鐢熸晥鏃堕棿");
+        }
+        String startTime = timeStr.split(",")[0].trim().replace(":", "");
+        String endTime = timeStr.split(",")[1].trim().replace(":", "");
+        String now = TimeUtil.getGernalTime(System.currentTimeMillis(), "HHmmss");
+        if (Integer.parseInt(now) < Integer.parseInt(startTime) || Integer.parseInt(now) > Integer.parseInt(endTime)) {
+            return JsonUtil.loadFalseResult(String.format("鍙d护鎻愪氦鏃堕棿娈典负锛�%s-%s", timeStr.split(",")[0], timeStr.split(",")[1]));
+        }
+
+        if (user == null) {
+            // 鍏堜繚瀛楰EY
+            session.setAttribute(Constant.SESSION_KEY_TEMP_ALIPAY_KEY, keyInfo);
+            wxLogger.info("寰俊娌℃湁鎺堟潈:" + session.getId());
+            String redictLink = systemConfigService.getValueCache(SystemConfigKeyEnum.WX_REDIRECT_LINK);
+            if (StringUtil.isNullOrEmpty(redictLink)) {
+                return JsonUtil.loadFalseResult("鏃犳硶鑾峰彇鍒版巿鏉冮摼鎺�");
+            }
+
+            redictLink = redictLink.replace("snsapi_base", "snsapi_userinfo");
+            // 娌℃湁鐧诲綍锛岃繑鍥炵櫥褰曢摼鎺�
+            JSONObject root = new JSONObject();
+            root.put("link", redictLink);
+            return JsonUtil.loadTrueResult(Constant.RESULT_CODE_NEED_LOGIN, root);
+        }
+        wxLogger.info("寰俊鏈夋巿鏉�:" + session.getId());
+        LogUtil.loggerDebug.warn("GEO淇℃伅锛歿}-{}-{}", user.getId(), ip, new Gson().toJson(ipInfoMap.get(ip)));
+        try {
+            KeyOrder order = addKey(keyInfo, user.getId());
+            JSONObject data = new JSONObject();
+            data.put("id", order.getId());
+            return JsonUtil.loadTrueResult(data);
+        } catch (KeyOrderException e) {
+            e.printStackTrace();
+            return JsonUtil.loadFalseResult(e.getMessage());
+        } catch (WxOrderCountException e) {
+            return JsonUtil.loadFalseResult(e.getMessage());
+        } catch (KeyVerifyException e) {
+            LogUtil.loggerDebug.debug("鍙d护鏍¢獙澶辫触锛歿}-{}-{}", keyInfo.getKey(), e.getCode(), e.getMessage());
+            switch (e.getCode()) {
+                case KeyVerifyException.CODE_KEY_MONEY_NOT_MATCH:
+                    return JsonUtil.loadFalseResult("璇ョ瑪璁㈠崟鏈夎锛屼笉浜堟彁浜�");
+                case KeyVerifyException.CODE_ORDER_MONEY_NOT_MATCH:
+                    return JsonUtil.loadFalseResult("鎻愪氦閲戦涓嶅尮閰�");
+                case KeyVerifyException.CODE_ORDER_NO_REPEAT:
+                    return JsonUtil.loadFalseResult("閲嶅鎻愪氦璁㈠崟");
+            }
+            return JsonUtil.loadFalseResult(e.getMessage());
+        }
+    }
+
+
+    private WxUserInfo wxLogin(String code, HttpSession session) throws Exception {
+        WXAppInfoDto wxApp = systemConfigService.getWxAppInfoCache();
+        WxApiUtil.WXAccessTokenInfo tokenInfo = WxApiUtil.getAcessTokenInfo(code, wxApp);
+        if (tokenInfo != null && !StringUtil.isNullOrEmpty(tokenInfo.getOpenid())) {
+            WxApiUtil.WXUserInfo wxUserInfo = null;
+            if (tokenInfo.getScope() != null && tokenInfo.getScope().contains("snsapi_userinfo")) {
+                try {
+                    wxUserInfo = WxApiUtil.getUserInfo(tokenInfo.getAccess_token(), tokenInfo.getOpenid());
+                    wxLogger.info("瑙f瀽缁撴灉", new Gson().toJson(wxUserInfo));
+                } catch (Exception e) {
+                    wxLogger.error("瑙f瀽鍑洪敊", e);
+                }
+            }
+            if (wxUserInfo == null) {
+                wxUserInfo = new WxApiUtil.WXUserInfo();
+                wxUserInfo.setOpenid(tokenInfo.getOpenid());
+            }
+            WxUserInfo user = wxUserService.login(wxUserInfo);
+            session.setAttribute(Constant.SESSION_KEY_USER, user);
+            wxLogger.info("寰俊淇濆瓨鐢ㄦ埛淇℃伅锛歿} id-{}", session.getId(), user.getId());
+            return user;
+        }
+       throw new Exception("鑾峰彇鎺堟潈淇℃伅寮傚父");
+    }
+
+    @RequestMapping(value = "wxLogin")
+    public void wxLogin(String code, String state, HttpServletRequest request, HttpServletResponse
+            response, HttpSession session) throws IOException {
+        // 鏍规嵁code鑾峰彇openid
+        SubmitKeyInfo alipayKeyInfo = (SubmitKeyInfo) session.getAttribute(Constant.SESSION_KEY_TEMP_ALIPAY_KEY);
+        if (alipayKeyInfo != null) {
+            wxLogger.info("寰俊鎺堟潈鍥炶皟锛歿} code-{} referer-{}", session.getId(), code, alipayKeyInfo.getReferer());
+        }
+        String failLink = systemConfigService.getValueCache(SystemConfigKeyEnum.WX_LOGIN_FAIL_LINK);
+        String referer = alipayKeyInfo != null ? alipayKeyInfo.getReferer() : "";
+
+        try {
+            String successLink = systemConfigService.getValueCache(SystemConfigKeyEnum.WX_LOGIN_SUCCESS_LINK);
+            if (!StringUtil.isNullOrEmpty(referer)) {
+                Map<String, String> params = HttpUtil.getPramsFromUrl(referer);
+                params.put("state", "SUCCESS");
+                successLink = HttpUtil.getWholeUrl(HttpUtil.getUrlWithoutParams(referer), params);
+            }
+
+            WxUserInfo user = wxLogin(code, session);
+            if(alipayKeyInfo==null){
+                // 鏅�氱櫥褰�
+                wxLogger.info("鏅�氱櫥褰曟垚鍔�");
+                response.sendRedirect("/credit/index.html?state=SUCCESS");
+                return;
+            }
+
+            wxLogger.info("浠巗ession璇诲彇鍒発ey锛歿}", alipayKeyInfo);
+            if (alipayKeyInfo != null) {
+                if (!ipInfoMap.containsKey(alipayKeyInfo.getIp())) {
+                    try {
+                        IPUtil.IPInfo ipInfo = IPUtil.getLocalIPInfo(alipayKeyInfo.getIp());
+                        ipInfoMap.put(alipayKeyInfo.getIp(), ipInfo);
+                    } catch (Exception e) {
+                        throw new RuntimeException(e);
+                    }
+                }
+                addKey(alipayKeyInfo, user.getId());
+            }
+            response.sendRedirect(successLink);
+            return;
+
+        } catch (
+                Exception e) {
+            wxLogger.error("鎺堟潈澶辫触锛歿}", e.getMessage());
+            if (!StringUtil.isNullOrEmpty(referer)) {
+                Map<String, String> params = HttpUtil.getPramsFromUrl(referer);
+                params.put("state", "FAIL");
+                failLink = HttpUtil.getWholeUrl(HttpUtil.getUrlWithoutParams(referer), params);
+            }
+        }
+        response.sendRedirect(failLink);
+    }
+
+
+    /**
+     * 鏌ヨ鍙d护鎻愪氦缁撴灉
+     *
+     * @param id
+     * @param request
+     * @return
+     */
+    @ResponseBody
+    @RequestMapping(value = "queryKeyResult")
+    public String queryKeyResult(String id, HttpServletRequest request) {
+        KeyOrder keyOrder = keyOrderService.selectById(id);
+        if (keyOrder == null) {
+            return JsonUtil.loadFalseResult("鍙d护涓嶅瓨鍦�");
+        }
+        String desc = "";
+        switch (keyOrder.getState()) {
+            case KeyOrder.STATE_NOT_PROCESS:
+                if (keyOrder.getDistributeClientUid() == null) {
+                    desc = "鍙d护宸叉彁浜わ紝绛夊緟鏀粯涓�...";
+                } else {
+                    desc = "鏀粯鎺掗槦涓�...";
+                }
+                break;
+            case KeyOrder.STATE_NOT_PAY:
+                desc = "姝e湪鏀粯涓紝鏀粯瀹屾垚鍚庢墠鍙户缁彁浜ゅ彛浠ゃ��";
+                break;
+            case KeyOrder.STATE_PAY:
+                desc = "鏀粯鎴愬姛";
+                break;
+            case KeyOrder.STATE_REJECT_PAY:
+                desc = keyOrder.getStateDesc();
+                break;
+        }
+        JSONObject data = new JSONObject();
+        data.put("state_desc", desc);
+        data.put("finish", keyOrder.getState() == KeyOrder.STATE_PAY || keyOrder.getState() == KeyOrder.STATE_REJECT_PAY ? 1 : 0);
+        return JsonUtil.loadTrueResult(data);
+    }
+
+    /**
+     * 鏌ヨ鏀粯鍓╀綑娆℃暟
+     *
+     * @param session
+     * @param request
+     * @return
+     */
+
+    @ResponseBody
+    @RequestMapping(value = "queryPayLeftCount")
+    public String queryPayLeftCount(HttpSession session, HttpServletRequest request) {
+        WxUserInfo user = (WxUserInfo) session.getAttribute(Constant.SESSION_KEY_USER);
+        if (user == null || user.getId() == null) {
+            return JsonUtil.loadFalseResult("鐢ㄦ埛灏氭湭鐧诲綍");
+        }
+        // 鏌ヨ鏀粯鍓╀綑娆℃暟
+        Map<Integer, Long> map = payCountVerifyManager.computeUserLeftPayCount(user.getId());
+        return JsonUtil.loadTrueResult(new Gson().toJson(map));
+    }
+
+
 }

--
Gitblit v1.8.0