admin
2024-07-09 6927d3bed414fb1a44312668d4e9d91d62e91b3f
src/main/java/com/taoke/autopay/controller/WebApiController.java
@@ -1,59 +1,238 @@
package com.taoke.autopay.controller;
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.exception.KeyOrderException;
import com.taoke.autopay.exception.WxOrderCountException;
import com.taoke.autopay.factory.OrderFactory;
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.WxUserOrderCountService;
import com.taoke.autopay.service.WxUserService;
import com.taoke.autopay.utils.*;
import com.taoke.autopay.vo.SubmitKeyInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yeshi.utils.UrlUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Controller
@RequestMapping("webapi")
public class WebApiController {
    Logger logger = LoggerFactory.getLogger(WebApiController.class);
    Logger wxLogger = LoggerFactory.getLogger("wxLogger");
    @Resource
    private KeyOrderService keyOrderService;
    @Resource
    private WxUserService wxUserService;
    @Resource
    private SystemConfigService systemConfigService;
    @ResponseBody
    @RequestMapping(value = "submitKey")
    public void push(String  key, PrintWriter out) {
        if(StringUtil.isNullOrEmpty(key)){
            out.print(JsonUtil.loadFalseResult(0,"请上传key"));
            return;
    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(key);
            Long uid =  keyOrderService.getCanDistributeUid();
            if(uid!=null){
                KeyOrder orderUpdate=new KeyOrder();
            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);
            }
            out.print(JsonUtil.loadTrueResult(""));
            return JsonUtil.loadTrueResult("");
        } catch (KeyOrderException e) {
            e.printStackTrace();
            out.print(JsonUtil.loadFalseResult(e.getMessage()));
            return JsonUtil.loadFalseResult(e.getMessage());
        } catch (WxOrderCountException e) {
            return JsonUtil.loadFalseResult("今日超过最大提交次数");
        }
    }
    @ResponseBody
    @RequestMapping(value = "test")
    public String test(String  key) {
      return "123123";
    private void addKey(SubmitKeyInfo keyInfo, Long wxUid) throws KeyOrderException, WxOrderCountException {
        KeyOrder order = keyOrderService.addKeyOrder(keyInfo, wxUid, 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);
        }
    }
    @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(0, "请上传key");
        }
        List<String> urllist = UrlUtils.parseUrlsFromText(keyInfo.getKey());
        if (urllist.isEmpty() || !urllist.get(0).contains("ur.alipay.com")) {
            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());
        }
    }
    /**
     * @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) {
        WxUserInfo user = (WxUserInfo) session.getAttribute(Constant.SESSION_KEY_USER);
        if (StringUtil.isNullOrEmpty(keyInfo.getKey())) {
            return JsonUtil.loadFalseResult(0, "请上传key");
        }
        if (StringUtil.isNullOrEmpty(keyInfo.getMoney())) {
            return JsonUtil.loadFalseResult(0, "请上传money");
        }
        List<String> urllist = UrlUtils.parseUrlsFromText(keyInfo.getKey());
        if (urllist.isEmpty() || !urllist.get(0).contains("ur.alipay.com")) {
            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]));
        }
        // 验证提交的金额是否正确
       String moneyStr =  systemConfigService.getValueCache(SystemConfigKeyEnum.PAY_MONEY_LIST);
       if(StringUtil.isNullOrEmpty(moneyStr)){
           return JsonUtil.loadFalseResult("尚未配置金额");
       }
       JSONArray array=JSONArray.fromObject(moneyStr);
       Set<String> moneySet=new HashSet<>();
       for(int i=0;i<array.size();i++){
           moneySet.add(MoneyUtil.getMoneyStr(new BigDecimal(array.optString(i))));
       }
        if(!moneySet.contains(MoneyUtil.getMoneyStr(new BigDecimal(keyInfo.getMoney())))){
            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());
        }
    }
    @RequestMapping(value = "wxLogin")
    public void wxLogin(String code, String state, HttpServletResponse response, HttpSession session) throws IOException {
        // 根据code获取openid
        wxLogger.info("微信授权回调:{} code-{}", session.getId(), code);
        String failLink = systemConfigService.getValueCache(SystemConfigKeyEnum.WX_LOGIN_FAIL_LINK);
        try {
            WXAppInfoDto wxApp = systemConfigService.getWxAppInfoCache();
            String successLink = systemConfigService.getValueCache(SystemConfigKeyEnum.WX_LOGIN_SUCCESS_LINK);
            WxApiUtil.WXAccessTokenInfo tokenInfo = WxApiUtil.getAcessTokenInfo(code, wxApp);
            if (tokenInfo != null && !StringUtil.isNullOrEmpty(tokenInfo.getOpenid())) {
                WxUserInfo user = wxUserService.login(tokenInfo.getOpenid());
                session.setAttribute(Constant.SESSION_KEY_USER, user);
                wxLogger.info("微信保存用户信息:{} id-{}", session.getId(), user.getId());
                SubmitKeyInfo alipayKeyInfo = (SubmitKeyInfo) session.getAttribute(Constant.SESSION_KEY_TEMP_ALIPAY_KEY);
                wxLogger.info("从session读取到key:{}", alipayKeyInfo);
                if (alipayKeyInfo != null) {
                    addKey(alipayKeyInfo, user.getId());
                }
                response.sendRedirect(successLink);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            wxLogger.error("授权失败:{}", e.getMessage());
        }
        response.sendRedirect(failLink);
    }
}