Administrator
2024-07-29 a053811c774ac07340e46561f5d2ab4d892282a0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
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.exception.KeyOrderException;
import com.taoke.autopay.exception.KeyVerifyException;
import com.taoke.autopay.exception.WxOrderCountException;
import com.taoke.autopay.service.KeyOrderService;
import com.taoke.autopay.service.SystemConfigService;
import com.taoke.autopay.service.WxUserService;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yeshi.utils.UrlUtils;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
 
@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;
 
    @Resource
    private SystemConfigService systemConfigService;
 
    @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("今日超过最大提交次数");
        }
    }
 
    private void addKey(SubmitKeyInfo keyInfo, Long wxUid) throws KeyVerifyException, KeyOrderException, WxOrderCountException {
        // 解析链接
        List<String> urllist = UrlUtils.parseUrlsFromText(keyInfo.getKey());
 
 
        String verifyAlipayKey = systemConfigService.getValueCache(SystemConfigKeyEnum.ALIPAY_KEY_VERIFY);
        if (verifyAlipayKey != null && verifyAlipayKey.trim().equalsIgnoreCase("1")) {
            try {
                // 需要验证支付宝口令
                if (urllist.size() < 1) {
                    throw new Exception("口令中不包含链接");
                }
                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("口令内容获取失败");
                }
                // 验证内容
                DYOrderDto dto = keyOrderService.verifyKey(tradeInfo.getGoodsTitle(), orderStatus, tradeInfo.getItemRealAmount());
            } 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());
            }
        }
 
 
        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);
        }
 
 
    }
 
    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("没包含支付宝汉字");
        }
    }
 
    @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());
        }
    }
 
    /**
     * @return java.lang.String
     * @author hxh
     * @description 带口令与金额的口令提交接口
     * @date 0:12 2024/7/9
     * @param: keyInfo
     * @param: session
     **/
    @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());
        }
    }
 
    @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("请上传key");
        }
 
        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.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());
        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) {
            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("提交金额不匹配");
            }
            return JsonUtil.loadFalseResult(e.getMessage());
        }
    }
 
 
    @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);
        wxLogger.info("微信授权回调:{} code-{} referer-{}", session.getId(), code, alipayKeyInfo.getReferer());
        String failLink = systemConfigService.getValueCache(SystemConfigKeyEnum.WX_LOGIN_FAIL_LINK);
        String referer = alipayKeyInfo.getReferer();
 
        try {
            WXAppInfoDto wxApp = systemConfigService.getWxAppInfoCache();
            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);
            }
 
            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);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            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);
    }
 
}