Administrator
2025-05-09 320e9165ac6cc6d90978fbef3074a8ed9add1790
src/main/java/com/taoke/autopay/controller/WebApiController.java
@@ -6,18 +6,22 @@
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.exception.KeyVerifyException;
import com.taoke.autopay.exception.WxOrderCountException;
import com.taoke.autopay.manager.PayCountVerifyManager;
import com.taoke.autopay.service.KeyOrderService;
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;
@@ -27,7 +31,10 @@
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("webapi")
@@ -39,8 +46,6 @@
    Logger verifyLogger = LoggerFactory.getLogger("keyVerifyLogger");
    @Resource
    private KeyOrderService keyOrderService;
@@ -49,49 +54,30 @@
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private PayCountVerifyManager payCountVerifyManager;
    @ResponseBody
    @RequestMapping(value = "submitKey")
    public String submitKey(String key) {
        if(1>0){
            return JsonUtil.loadFalseResult(0, "接口已关闭");
        }
        if (StringUtil.isNullOrEmpty(key)) {
            return JsonUtil.loadFalseResult(0, "请上传key");
        }
        List<String> urllist = UrlUtils.parseUrlsFromText(key);
        if (urllist.isEmpty() || !urllist.get(0).contains("ur.alipay.com")) {
            return JsonUtil.loadFalseResult("支付宝口令不正确");
        }
        try {
            KeyOrder order = keyOrderService.addKeyOrder(new SubmitKeyInfo(key), null, TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyyMMdd"));
            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);
            }
            return JsonUtil.loadTrueResult("");
        } catch (KeyOrderException e) {
            e.printStackTrace();
            return JsonUtil.loadFalseResult(e.getMessage());
        } catch (WxOrderCountException e) {
            return JsonUtil.loadFalseResult("今日超过最大提交次数");
        }
    }
    @Resource
    private ChannelAgentService channelAgentService;
    private void addKey(SubmitKeyInfo keyInfo, Long wxUid) throws KeyVerifyException, KeyOrderException, WxOrderCountException {
       // 解析链接
    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(keyInfo.getKey());
        String verifyAlipayKey = systemConfigService.getValueCache(SystemConfigKeyEnum.ALIPAY_KEY_VERIFY);
        if(verifyAlipayKey!=null&&verifyAlipayKey.trim().equalsIgnoreCase("1")) {
        DYOrderDto orderDto = null;
        int orderType = Constant.ORDER_TYPE_UNKNOWN;
        if (verifyAlipayKey != null && verifyAlipayKey.trim().equalsIgnoreCase("1")) {
            try {
                // 需要验证支付宝口令
                if (urllist.size() < 1) {
                if (urllist.isEmpty()) {
                    throw new Exception("口令中不包含链接");
                }
                AlipayOrderUtil.AlipayOrderTradeInfo tradeInfo = AlipayOrderUtil.getTradeInfo(urllist.get(0));
@@ -110,23 +96,21 @@
                if (tradeInfo == null) {
                    throw new Exception("口令内容获取失败");
                }
                orderType = AlipayOrderUtil.getOrderType(tradeInfo.getGoodsTitle());
                // 验证内容
                DYOrderDto dto = keyOrderService.verifyKey(tradeInfo.getGoodsTitle(), orderStatus, tradeInfo.getItemRealAmount());
            }catch(KeyVerifyException ee){
                orderDto = keyOrderService.verifyKey(tradeInfo.getGoodsTitle(), orderStatus, tradeInfo.getItemRealAmount(), wxUid, null);
            } catch (KeyVerifyException ee) {
                try {
                    verifyLogger.warn("校验不通过:【{}】-{}", keyInfo.getKey(), ee.getMessage());
                }catch(Exception e){
                } catch (Exception e) {
                }
                throw  ee;
            }
            catch(Exception e){
                throw ee;
            } catch (Exception e) {
                throw new KeyVerifyException(KeyVerifyException.CODE_COMMON, e.getMessage());
            }
        }
        KeyOrder order = keyOrderService.addKeyOrder(keyInfo, wxUid, TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyyMMdd"));
        Long uid = keyOrderService.getCanDistributeUid();
        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());
@@ -134,139 +118,20 @@
            orderUpdate.setDistributeTime(new Date());
            keyOrderService.update(orderUpdate);
        }
        return order;
    }
    private void verifySubmitKey(String key) throws Exception{
    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("不包含支付宝链接");
            throw new Exception("不包含支付宝链接");
        }
        if(!key.contains("支付宝")){
        if (!key.contains("支付宝")) {
            throw new Exception("没包含支付宝汉字");
        }
    }
    @ResponseBody
    @RequestMapping(value = "submitKeyV2")
    public String submitKeyV2(SubmitKeyInfo keyInfo, HttpSession session) {
        WxUserInfo user = (WxUserInfo) session.getAttribute(Constant.SESSION_KEY_USER);
        if (StringUtil.isNullOrEmpty(keyInfo.getKey())) {
            return JsonUtil.loadFalseResult("请上传key");
        }
        try{
            verifySubmitKey(keyInfo.getKey());
        }catch (Exception e){
            return JsonUtil.loadFalseResult("支付宝口令不正确");
        }
        if (user == null) {
            // 先保存KEY
//            SESSION_KEY_TEMP_ALIPAY_KEY
            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("无法获取到授权链接");
            }
            // 没有登录,返回登录链接
            JSONObject root = new JSONObject();
            root.put("link", redictLink);
            return JsonUtil.loadTrueResult(Constant.RESULT_CODE_NEED_LOGIN, root);
        }
        wxLogger.info("微信有授权:" + session.getId());
        try {
            addKey(keyInfo, user.getId());
            return JsonUtil.loadTrueResult("");
        } catch (KeyOrderException e) {
            e.printStackTrace();
            return JsonUtil.loadFalseResult(e.getMessage());
        } catch (WxOrderCountException e) {
            return JsonUtil.loadFalseResult(e.getMessage());
        } catch (KeyVerifyException e) {
            switch (e.getCode()){
                case KeyVerifyException.CODE_KEY_MONEY_NOT_MATCH:
                    return JsonUtil.loadFalseResult("该笔订单有误,不予提交");
                case KeyVerifyException.CODE_ORDER_MONEY_NOT_MATCH:
                    return JsonUtil.loadFalseResult("提交金额不匹配");
            }
            logger.debug("口令验证结果异常:{}-{}", keyInfo.getKey(), e.getMessage());
            return JsonUtil.loadFalseResult(e.getMessage());
        }
    }
    /**
     * @author hxh
     * @description 带口令与金额的口令提交接口
     * @date 0:12 2024/7/9
     * @param: keyInfo
     * @param: session
     * @return java.lang.String
     **/
    @ResponseBody
    @RequestMapping(value = "submitKeyV3")
    public String submitKeyV3(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( "请上传key");
        }
//        if (StringUtil.isNullOrEmpty(keyInfo.getMoney())) {
//            return JsonUtil.loadFalseResult("请上传money");
//        }
        try{
            verifySubmitKey(keyInfo.getKey());
        }catch (Exception e){
            return JsonUtil.loadFalseResult("支付宝口令不正确");
        }
        // 验证提交时间
        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("口令提交时间段为:%s-%s",timeStr.split(",")[0],timeStr.split(",")[1]));
        }
        if (user == null) {
            // 先保存KEY
//            SESSION_KEY_TEMP_ALIPAY_KEY
            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("无法获取到授权链接");
            }
            // 没有登录,返回登录链接
            JSONObject root = new JSONObject();
            root.put("link", redictLink);
            return JsonUtil.loadTrueResult(Constant.RESULT_CODE_NEED_LOGIN, root);
        }
        wxLogger.info("微信有授权:" + session.getId());
        try {
            addKey(keyInfo, user.getId());
            return JsonUtil.loadTrueResult("");
        } catch (KeyOrderException e) {
            e.printStackTrace();
            return JsonUtil.loadFalseResult(e.getMessage());
        } catch (WxOrderCountException e) {
            return JsonUtil.loadFalseResult(e.getMessage());
        } catch (KeyVerifyException e) {
            logger.debug("口令校验失败:{}-{}-{}", 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("提交金额不匹配");
            }
            return JsonUtil.loadFalseResult(e.getMessage());
        }
    }
    private Map<String, IPUtil.IPInfo> ipInfoMap = new HashMap<>();
    @ResponseBody
    @RequestMapping(value = "submitKeyV4")
@@ -275,29 +140,66 @@
        keyInfo.setReferer(referer);
        WxUserInfo user = (WxUserInfo) session.getAttribute(Constant.SESSION_KEY_USER);
        if (StringUtil.isNullOrEmpty(keyInfo.getKey())) {
            return JsonUtil.loadFalseResult( "请上传key");
            return JsonUtil.loadFalseResult("请上传key");
        }
        if(1<0) {
        String ip = IPUtil.getRemotIP(request);
        keyInfo.setIp(ip);
        if (!ipInfoMap.containsKey(ip)) {
            try {
                verifySubmitKey(keyInfo.getKey());
                IPUtil.IPInfo ipInfo = IPUtil.getLocalIPInfo(ip);
                ipInfoMap.put(ip, ipInfo);
            } catch (Exception e) {
                return JsonUtil.loadFalseResult("支付宝口令不正确");
            }
            // 验证提交时间
            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("口令提交时间段为:%s-%s", timeStr.split(",")[0], timeStr.split(",")[1]));
                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("暂时无法上传口令");
                    }
                }
            }
        }
        try {
            verifySubmitKey(keyInfo.getKey());
        } catch (Exception e) {
            return JsonUtil.loadFalseResult("支付宝口令不正确");
        }
        // 验证提交时间
        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("口令提交时间段为:%s-%s", timeStr.split(",")[0], timeStr.split(",")[1]));
        }
        if (user == null) {
            // 先保存KEY
//            SESSION_KEY_TEMP_ALIPAY_KEY
            session.setAttribute(Constant.SESSION_KEY_TEMP_ALIPAY_KEY, keyInfo);
            wxLogger.info("微信没有授权:" + session.getId());
            String redictLink = systemConfigService.getValueCache(SystemConfigKeyEnum.WX_REDIRECT_LINK);
@@ -305,87 +207,177 @@
                return JsonUtil.loadFalseResult("无法获取到授权链接");
            }
            redictLink=redictLink.replace("snsapi_base","snsapi_userinfo");
            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 {
            addKey(keyInfo, user.getId());
            return JsonUtil.loadTrueResult("");
            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) {
            logger.debug("口令校验失败:{}-{}-{}", keyInfo.getKey(), e.getCode(), e.getMessage());
            switch (e.getCode()){
            LogUtil.loggerDebug.debug("口令校验失败:{}-{}-{}", 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("解析结果", new Gson().toJson(wxUserInfo));
                } catch (Exception e) {
                    wxLogger.error("解析出错", 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 {
    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);
        wxLogger.info("微信授权回调:{} code-{} referer-{}", session.getId(), code, alipayKeyInfo.getReferer());
        if (alipayKeyInfo != null) {
            wxLogger.info("微信授权回调:{} code-{} referer-{}", session.getId(), code, alipayKeyInfo.getReferer());
        }
        String failLink = systemConfigService.getValueCache(SystemConfigKeyEnum.WX_LOGIN_FAIL_LINK);
        String referer = alipayKeyInfo.getReferer();
        String referer = alipayKeyInfo != null ? alipayKeyInfo.getReferer() : "";
        try {
            WXAppInfoDto wxApp = systemConfigService.getWxAppInfoCache();
            String successLink = systemConfigService.getValueCache(SystemConfigKeyEnum.WX_LOGIN_SUCCESS_LINK);
            if(!StringUtil.isNullOrEmpty(referer)){
            if (!StringUtil.isNullOrEmpty(referer)) {
                Map<String, String> params = HttpUtil.getPramsFromUrl(referer);
                params.put("state","SUCCESS");
                successLink = HttpUtil.getWholeUrl(HttpUtil.getUrlWithoutParams(referer),params);
                params.put("state", "SUCCESS");
                successLink = HttpUtil.getWholeUrl(HttpUtil.getUrlWithoutParams(referer), params);
            }
            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("解析结果",new Gson().toJson(wxUserInfo));
                    }catch(Exception e){
                        wxLogger.error("解析出错",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());
                wxLogger.info("从session读取到key:{}", alipayKeyInfo);
                if (alipayKeyInfo != null) {
                    addKey(alipayKeyInfo, user.getId());
                }
                response.sendRedirect(successLink);
            WxUserInfo user = wxLogin(code, session);
            if(alipayKeyInfo==null){
                // 普通登录
                wxLogger.info("普通登录成功");
                response.sendRedirect("/credit/index.html?state=SUCCESS");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            wxLogger.info("从session读取到key:{}", 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)){
            if (!StringUtil.isNullOrEmpty(referer)) {
                Map<String, String> params = HttpUtil.getPramsFromUrl(referer);
                params.put("state","FAIL");
                failLink = HttpUtil.getWholeUrl(HttpUtil.getUrlWithoutParams(referer),params);
                params.put("state", "FAIL");
                failLink = HttpUtil.getWholeUrl(HttpUtil.getUrlWithoutParams(referer), params);
            }
        }
        response.sendRedirect(failLink);
    }
    /**
     * 查询口令提交结果
     *
     * @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("口令不存在");
        }
        String desc = "";
        switch (keyOrder.getState()) {
            case KeyOrder.STATE_NOT_PROCESS:
                if (keyOrder.getDistributeClientUid() == null) {
                    desc = "口令已提交,等待支付中...";
                } else {
                    desc = "支付排队中...";
                }
                break;
            case KeyOrder.STATE_NOT_PAY:
                desc = "正在支付中,支付完成后才可继续提交口令。";
                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));
    }
}