935090232@qq.com
2021-10-20 240b9fb99d759c0a40d9a8f4098ccea8a945db67
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package com.matrix.system.shopXcx.api.action;
 
import com.matrix.component.asyncmessage.AsyncMessageManager;
import com.matrix.component.rabbitmq.RabiitMqTemplate;
import com.matrix.component.wechat.externalInterface.common.Signature;
import com.matrix.component.wechat.externalInterface.common.Util;
import com.matrix.component.wechat.externalInterface.protocol.queryProtocol.NotifyData;
import com.matrix.core.pojo.AjaxResult;
import com.matrix.core.tools.LogUtil;
import com.matrix.system.common.bean.BusParameterSettings;
import com.matrix.system.common.constance.AppConstance;
import com.matrix.system.common.dao.BusParameterSettingsDao;
import com.matrix.system.hive.bean.MoneyCardUse;
import com.matrix.system.hive.bean.MoneyCardUseFlow;
import com.matrix.system.hive.bean.SysVipInfo;
import com.matrix.system.hive.dao.MoneyCardUseDao;
import com.matrix.system.hive.dao.MoneyCardUseFlowDao;
import com.matrix.system.hive.dao.SysVipInfoDao;
import com.matrix.system.score.service.ScoreVipDetailService;
import com.matrix.system.shopXcx.bean.ShopActivitiesGroupJoin;
import com.matrix.system.shopXcx.bean.ShopActivitiesGroupJoinUser;
import com.matrix.system.shopXcx.bean.ShopOrder;
import com.matrix.system.shopXcx.bean.ShopPayLog;
import com.matrix.system.shopXcx.dao.ShopActivitiesGroupJoinDao;
import com.matrix.system.shopXcx.dao.ShopActivitiesGroupJoinUserDao;
import com.matrix.system.shopXcx.dao.ShopOrderDao;
import com.matrix.system.shopXcx.dao.ShopPayLogDao;
import com.matrix.system.shopXcx.mqTask.AsyncMessageRouting;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * @author jyy
 * @description 微信公共接口
 * @date 2018-05-23 00:08
 */
@Controller
@RequestMapping(value = "wxCommon")
public class WxCommonAction {
 
 
    /**
     * 错误报文占位符
     */
    private static final String ERRORMSG = "ERRORMSG";
    /**
     * 异步任务和订单类型的映射关系
     */
    private static Map<Integer, String> TASK_ORDER_MAPPING = new HashMap<>();
 
    @Autowired
    private ShopOrderDao shopOrderDao;
    @Autowired
    private ShopPayLogDao shopPayLogDao;
 
    @Autowired
    private RabiitMqTemplate rabiitMqTemplate;
 
    @Autowired
    private ShopActivitiesGroupJoinUserDao shopActivitiesGroupJoinUserDao;
 
    @Autowired
    private ShopActivitiesGroupJoinDao shopActivitiesGroupJoinDao;
 
    @Autowired
    private SysVipInfoDao sysVipInfoDao;
 
    @Autowired
    BusParameterSettingsDao busParameterSettingsDao;
 
    @Autowired
    ScoreVipDetailService scoreVipDetailService;
 
    @Autowired
    AsyncMessageManager asyncMessageManager;
 
 
    @Value("${evn}")
    private String evn;
    /**
     * 微信支付回调接口
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/wxapi/wxpayCallback")
    public void payCallBack(HttpServletResponse response, HttpServletRequest request) throws IOException {
        LogUtil.info("微信支付回调start....");
 
        // 获取输入参数
        String inputLine;
        StringBuffer notityXml = new StringBuffer();
        String resXml = "";
        String orderId = "";
 
        AjaxResult threadResult = new AjaxResult(AjaxResult.STATUS_SUCCESS, "");
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml.append(inputLine);
            }
            request.getReader().close();
            LogUtil.info("notityXml ---- :{} ", notityXml);
 
 
            // XMl转对象
            Object bb = Util.getObjectFromXML(notityXml.toString(), NotifyData.class);
            NotifyData    data = new NotifyData();
            BeanUtils.copyProperties(bb,data);
            LogUtil.info("----return_code = {}", data.getReturn_code());
 
 
            // 返回状态码 SUCCESS/FAIL
            if (AppConstance.CODE_SUCCESS.equals(data.getReturn_code())) {
 
                orderId = data.getAttach();
                // 检验订单状态
                ShopOrder order = shopOrderDao.selectById(Integer.valueOf(orderId));
 
                // 校验签名
                BusParameterSettings paySecret = busParameterSettingsDao.selectCompanyParamByCode(AppConstance.WECHARPAY_SECRET, order.getCompanyId());
                if (Signature.checkIsSignValidFromResponseString(notityXml.toString(),paySecret.getParamValue())) {
                    // 校验业务结果
                    if (AppConstance.CODE_SUCCESS.equals(data.getResult_code())) {
                        // 返回SUCCESS报文
                        resXml = AppConstance.RESULT_XML_SUCCESS;
                        // 支付费用
                        Double total_fee = Double.parseDouble(data.getTotal_fee());
                        // 商户订单号
                        String payNum = data.getOut_trade_no();
 
                        LogUtil.info("支付回调关键信息---total_fee:{},payNum:{},orderId:{}", total_fee, payNum, orderId);
                        // 订单ID
                        BigDecimal payMoney = new BigDecimal(total_fee).divide(new BigDecimal(100), 2,
                                RoundingMode.HALF_UP);
 
 
                        if (order != null && ShopOrder.ORDER_PAY_STATUS_WAIT == order.getPayStatus()) {
                            ShopPayLog payLog = new ShopPayLog();
                            // TODO 校验支付金额
                            LogUtil.debug("检查支付金额payMoney={},order.getPayMoney()={}", payMoney, order.getOrderMoney());
 
                            //构建需要修改订单信息Map
                            Map<String, Object> modifyMap = new HashMap<>();
                            modifyMap.put("id", order.getId());
                            //设置微信支付状态为已支付
                            modifyMap.put("payResult", ShopOrder.ORDER_WX_STATUS_PAY_SUCCESS);
                            //设置支付状态为支付成功
                            modifyMap.put("payStatus", ShopOrder.ORDER_PAY_STATUS_SUCCESS);
                            //设置订单状态
                            if (ShopOrder.SHIPPING_METHOD_WL == order.getShippingMethod()) {
                                //如果是商品订单则进入待发货
                                modifyMap.put("orderStatus", ShopOrder.ORDER_STATUS_WAIT_SEND);
                            } else if (ShopOrder.SHIPPING_METHOD_MDZT == order.getShippingMethod()) {
                                //如果是门店自提则进入待收款
                                modifyMap.put("orderStatus", ShopOrder.ORDER_STATUS_WAIT_RECEIVE);
                            }
                            shopOrderDao.updateByMap(modifyMap);
 
                            // 判断该订单是否为拼团产生的订单
                            ShopActivitiesGroupJoinUser joinUser = shopActivitiesGroupJoinUserDao.selectGroupJoinUserByOrderId(order.getId().longValue());
                            if (joinUser != null) {
                                joinUser.setIsHasPay(ShopActivitiesGroupJoinUser.IS_HAS_PAY_Y);
                                shopActivitiesGroupJoinUserDao.updateByModel(joinUser);
 
                                ShopActivitiesGroupJoin groupJoin = shopActivitiesGroupJoinDao.selectGroupAndPriceById(joinUser.getGjId());
                                List<ShopActivitiesGroupJoinUser> joinUserList = shopActivitiesGroupJoinUserDao.selectGroupJoinUserListByGjId(joinUser.getGjId());
                                LogUtil.info("#当前已支付完成:{}#", joinUserList.size());
                                // 若拼团中已支付的数量等于几人团预设值,则更新拼团状态为拼团成功
                                if (groupJoin.getGroupPrice().getGpCount()  == joinUserList.size()) {
                                    groupJoin.setGjStatus(ShopActivitiesGroupJoin.ACTIVITIES_JOIN_SUCCESS);
                                } else {
                                    if (joinUser.getUserId().equals(groupJoin.getGjHeadId())) {
                                        groupJoin.setGjStatus(ShopActivitiesGroupJoin.ACTIVITIES_JOIN_ING);
                                    }
                                }
                                shopActivitiesGroupJoinDao.updateByModel(groupJoin);
 
                                SysVipInfo sysVipInfo = sysVipInfoDao.selectByPhone(order.getUserTel(), order.getCompanyId());
                                if(sysVipInfo!=null){
                                    sysVipInfo.setIsDeal(SysVipInfo.DEAL_VIP);
                                    sysVipInfoDao.update(sysVipInfo);
                                }
 
                            }
 
                            // 根据订单类型创建不同的处理任务
                            asyncMessageManager.sendMsg(AsyncMessageRouting.CREATE_ORDER,"orderId=%s",orderId);
 
 
                            threadResult.putInMap("status", "success");
                            resXml = AppConstance.RESULT_XML_SUCCESS;
 
                            //支付记录
                            recordPayLog(Integer.valueOf(orderId), 1, order.getOrderNo(), payMoney,  "支付成功", ShopOrder.ORDER_PAY_STATUS_SUCCESS);
 
 
                        } else {
                            LogUtil.info("订单状态不为待付款,order status=", order.getOrderStatus());
                        }
 
                    } else {
                        LogUtil.info("微信标识业务是失败");
                        threadResult.putInMap("status", "err");
                        threadResult.putInMap("msg", "查询支付信息失败,请联系客服或者刷新支付信息(错误码:001)");
                        resXml = AppConstance.RESULT_XML_FAIL.replace(ERRORMSG, "微信标识业务是失败");
                    }
                } else {
                    LogUtil.info("无效签名");
                    threadResult.putInMap("status", "err");
                    threadResult.putInMap("msg", "查询支付信息失败,请联系客服或者刷新支付信息(错误码:002)");
                    resXml = AppConstance.RESULT_XML_FAIL.replace(ERRORMSG, "微信标识业务是失败");
                }
            } else {
                LogUtil.info("通信标识失败");
                threadResult.putInMap("status", "err");
                threadResult.putInMap("msg", "查询支付信息失败,请联系客服或者刷新支付信息(错误码:003)");
                resXml = AppConstance.RESULT_XML_FAIL.replace(ERRORMSG, "通信标识失败");
            }
        } catch (Exception e) {
            LogUtil.error("支付回调签名错误", e);
            threadResult.putInMap("status", "err");
            threadResult.putInMap("msg", "查询支付信息失败,请联系客服或者刷新支付信息(错误码:004)");
            resXml = AppConstance.RESULT_XML_FAIL.replace(ERRORMSG, "支付回调签名错误");
        } finally {
            // 通知线程消息
            PayThreadPool.notifyThread(Integer.valueOf(orderId), threadResult);
            sendResultBack(response, resXml);
        }
        return;
 
    }
 
 
    @Autowired
    MoneyCardUseFlowDao moneyCardUseFlowDao;
 
    @Autowired
    MoneyCardUseDao moneyCardUseDao;
 
    /**
     * 微信充值回调
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/wxapi/rechargeCallBack")
    public void rechargeCallBack(HttpServletResponse response, HttpServletRequest request) throws IOException {
        LogUtil.info("微信充值回调start....");
 
        // 获取输入参数
        String inputLine;
        StringBuffer notityXml = new StringBuffer();
        String resXml = "";
        String moneyCardUseFlowId = "";
 
        AjaxResult threadResult = new AjaxResult(AjaxResult.STATUS_SUCCESS, "");
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml.append(inputLine);
            }
            request.getReader().close();
            LogUtil.info("notityXml ---- :{} ", notityXml);
 
 
            // XMl转对象
            Object bb = Util.getObjectFromXML(notityXml.toString(), NotifyData.class);
            NotifyData    data = new NotifyData();
            BeanUtils.copyProperties(bb,data);
            LogUtil.info("----return_code = {}", data.getReturn_code());
 
 
            // 返回状态码 SUCCESS/FAIL
            if (AppConstance.CODE_SUCCESS.equals(data.getReturn_code())) {
 
                moneyCardUseFlowId = data.getAttach();
                // 检验订单状态
                MoneyCardUseFlow moneyCardUseFlow = moneyCardUseFlowDao.selectById(Long.valueOf(moneyCardUseFlowId));
                SysVipInfo user=sysVipInfoDao.selectById(moneyCardUseFlow.getVipId());
 
                // 校验签名
                BusParameterSettings paySecret = busParameterSettingsDao.selectCompanyParamByCode(AppConstance.WECHARPAY_SECRET, user.getCompanyId());
                if (Signature.checkIsSignValidFromResponseString(notityXml.toString(),paySecret.getParamValue())) {
                    // 校验业务结果
                    if (AppConstance.CODE_SUCCESS.equals(data.getResult_code())) {
                        // 返回SUCCESS报文
                        resXml = AppConstance.RESULT_XML_SUCCESS;
                        // 支付费用
                        Double total_fee = Double.parseDouble(data.getTotal_fee());
                        // 商户订单号
                        String payNum = data.getOut_trade_no();
 
                        LogUtil.info("支付回调关键信息---total_fee:{},payNum:{},moneyCardUseFlowId:{}", total_fee, payNum, moneyCardUseFlowId);
                        // 订单ID
                        Double payMoney = new BigDecimal(total_fee).divide(new BigDecimal(100), 2,
                                BigDecimal.ROUND_HALF_DOWN).doubleValue();
 
                        if (moneyCardUseFlow.getCarUseId()==null) {
 
                            if(payMoney.equals(moneyCardUseFlow.getTotal())){
                                threadResult.putInMap("status", "success");
                                resXml = AppConstance.RESULT_XML_SUCCESS;
                                MoneyCardUse moneyCardUse = moneyCardUseDao.selectVipCard(user.getId());
                                moneyCardUseFlow.setCarUseId(moneyCardUse.getId());
                                moneyCardUseFlow.setCardName(moneyCardUse.getCardName());
                                Double balance=moneyCardUse.getGiftMoney() + moneyCardUse.getRealMoney();
                                moneyCardUseFlow.setBalance(balance==null?0:balance);
                                moneyCardUseFlowDao.update(moneyCardUseFlow);
 
                                moneyCardUse.setRealMoney(moneyCardUse.getRealMoney()+payMoney.doubleValue());
                                moneyCardUseDao.update(moneyCardUse);
 
                                //充值记录
                                recordPayLog(Integer.valueOf(moneyCardUseFlowId),2,moneyCardUseFlow.getPayNo(),new BigDecimal(payMoney), "充值成功", ShopOrder.ORDER_PAY_STATUS_SUCCESS);
                            }else{
                                LogUtil.debug("支付金额不一致,检查支付金额payMoney={},order.getPayMoney()={}", payMoney, moneyCardUseFlow.getTotal());
                                threadResult.putInMap("status", "err");
                                threadResult.putInMap("msg", "支付金额不一致");
                                resXml = AppConstance.RESULT_XML_FAIL.replace(ERRORMSG, "微信标识业务是失败");
                            }
 
                        } else {
                            LogUtil.info("充值已经确认");
                        }
 
                    } else {
                        LogUtil.info("微信标识业务是失败");
                        threadResult.putInMap("status", "err");
                        threadResult.putInMap("msg", "查询支付信息失败,请联系客服或者刷新支付信息(错误码:001)");
                        resXml = AppConstance.RESULT_XML_FAIL.replace(ERRORMSG, "微信标识业务是失败");
                    }
                } else {
                    LogUtil.info("无效签名");
                    threadResult.putInMap("status", "err");
                    threadResult.putInMap("msg", "查询支付信息失败,请联系客服或者刷新支付信息(错误码:002)");
                    resXml = AppConstance.RESULT_XML_FAIL.replace(ERRORMSG, "微信标识业务是失败");
                }
            } else {
                LogUtil.info("通信标识失败");
                threadResult.putInMap("status", "err");
                threadResult.putInMap("msg", "查询支付信息失败,请联系客服或者刷新支付信息(错误码:003)");
                resXml = AppConstance.RESULT_XML_FAIL.replace(ERRORMSG, "通信标识失败");
            }
        } catch (Exception e) {
            LogUtil.error("支付回调签名错误", e);
            threadResult.putInMap("status", "err");
            threadResult.putInMap("msg", "查询支付信息失败,请联系客服或者刷新支付信息(错误码:004)");
            resXml = AppConstance.RESULT_XML_FAIL.replace(ERRORMSG, "支付回调签名错误");
        } finally {
            // 通知线程消息
            PayThreadPool.notifyThread(Integer.valueOf(moneyCardUseFlowId), threadResult);
            sendResultBack(response, resXml);
        }
        return;
 
    }
 
 
 
    private void recordPayLog(Integer orderId, Integer type,String orderNo, BigDecimal payMoney, String payRemark, int payStatus) {
        //设置支付类型为收款
        ShopPayLog payLog=new ShopPayLog();
        payLog.setPayType(type);
        payLog.setJoinId(orderId);
        payLog.setPayMoney(payMoney);
        payLog.setPayOrderNo(orderNo);
        payLog.setPayRemark(payRemark);
        payLog.setPayStatus(payStatus);
        payLog.setCreateBy(AppConstance.SYSTEM_USER);
        payLog.setUpdateBy(AppConstance.SYSTEM_USER);
        shopPayLogDao.insert(payLog);
    }
 
 
    private void sendResultBack(HttpServletResponse response, String resXml) throws IOException {
        LogUtil.info("返回微信数据={}", resXml);
        ServletOutputStream out = response.getOutputStream();
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }
 
    /**
     * 二维码消核
     *
     * @param id
     * @return
     * @author HEMING
     * @email 910000889@qq.com
     * @date 2018年7月7日
     */
    @RequestMapping(value = "/verify/{keys}")
    public @ResponseBody
    AjaxResult verify(@PathVariable("keys") String id) {
        LogUtil.debug("消核请求:{}", id);
        return null;
    }
 
 
 
}