package com.szwl.service.impl; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.AlipayConfig; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.domain.AlipayTradePrecreateModel; import com.alipay.api.request.AlipayTradePrecreateRequest; import com.alipay.api.response.AlipayTradePrecreateResponse; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.google.gson.Gson; import com.szwl.constant.*; import com.szwl.feign.bean.OrderFeign; import com.szwl.feign.bean.SzwlFeign; import com.szwl.mapper.TOrderMapper; import com.szwl.model.bean.WeChatTemplateMsg; import com.szwl.model.bo.JsonMessage; import com.szwl.model.bo.R; import com.szwl.model.bo.ResponseModel; import com.szwl.model.entity.*; import com.szwl.model.utils.CodeUtil; import com.szwl.model.utils.HttpClientUtils; import com.szwl.model.utils.PushUtils; import com.szwl.model.utils.RSAUtil; import com.szwl.service.*; import com.szwl.service.es.EsTOrderService; import com.szwl.utils.HuifuUtils; import com.szwl.utils.IDGenerator; import com.szwl.utils.shouqianba.HttpProxy; import com.szwl.weixin.util.HttpUtils; import com.wechat.pay.java.core.Config; import com.wechat.pay.java.service.payments.nativepay.model.Amount; import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest; import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse; import com.wechat.pay.java.service.payments.nativepay.model.SceneInfo; import com.wechat.pay.java.service.refund.model.CreateRequest; import com.wechat.pay.java.service.refund.model.Refund; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpStatus; import org.apache.http.message.BasicNameValuePair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.CompletableFuture; import static com.szwl.service.impl.TJoinpayMchServiceImpl.createHmacSign; /** *

* 服务实现类 *

* * @author wuhs * @since 2022-06-17 */ @Slf4j @Service public class TOrderServiceImpl extends ServiceImpl implements TOrderService { @Autowired OrderFeign orderFeign; @Autowired SzwlFeign szwlFeign; @Autowired TOrderService orderService; @Autowired EsTOrderService esTOrderService; @Autowired TEquipmentService equipmentService; @Autowired TWechatPayConfigService wechatPayConfigService; @Resource TAlipayConfigService alipayConfigService; @Autowired TSqbConfigService sqbConfigService; @Autowired THuifuMchService huifuMchService; @Autowired TJoinpayMchService joinpayMchService; @Autowired private TOrderDetailsService orderDetailsService; @Override public synchronized String initSn(Long equipmentId) { StringBuilder number = new StringBuilder(); if (equipmentId != null) { Random random = new Random(); /** * 6位随机 */ for (int i = 0; i < 6; i++) { number.append(String.valueOf(random.nextInt(10))); } /** * 设备id */ number.append(equipmentId.toString()); /** * 日期 */ number.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())); } return number.toString(); } @Override public String wechatPay(String sn, BigDecimal amount, String productName, Long id, String notifyUrl, String clientId, HttpServletRequest request) { TWechatPayConfig wechatPayConfig = wechatPayConfigService.getById(id); Config config = wechatPayConfigService.getWechatConfig(id); if (config == null) { wechatPayConfigService.initConfig(id); config = wechatPayConfigService.getWechatConfig(id); } // 构建service NativePayService service = new NativePayService.Builder().config(config).build(); PrepayRequest payRequest = new PrepayRequest(); Amount amount1 = new Amount(); amount1.setTotal(amount.intValue()); payRequest.setAmount(amount1); payRequest.setAppid(wechatPayConfig.getAppId()); payRequest.setMchid(wechatPayConfig.getMerchantId()); payRequest.setDescription(productName); // 添加设备编号 String ipAddress = HttpClientUtils.getIpAddress(request); SceneInfo sceneInfo = new SceneInfo(); sceneInfo.setPayerClientIp(ipAddress); sceneInfo.setDeviceId(clientId); payRequest.setSceneInfo(sceneInfo); payRequest.setNotifyUrl(notifyUrl); // payRequest.setNotifyUrl("http://evxz5m.natappfree.cc/wechatPay/notify");; payRequest.setOutTradeNo(sn); // 调用下单方法,得到应答 PrepayResponse response = service.prepay(payRequest); return response.getCodeUrl(); } /** * 处理退款回调通知 */ @Override public String wechatRefund(HttpServletRequest request, HttpServletResponse response) { Gson gson = new Gson(); Map hashMap = new HashMap<>(3); try { // 处理退款通知参数 String body = HttpUtils.readData(request); Map bodyMap = gson.fromJson(body, HashMap.class); String eventType = (String) bodyMap.get("event_type"); if (eventType.equals("REFUND.SUCCESS")) { // 处理退款单 processRefund(bodyMap); //成功应答 response.setStatus(HttpStatus.SC_OK); // hashMap.put("code", "SUCCESS"); } else { response.setStatus(HttpStatus.SC_BAD_GATEWAY); hashMap.put("code", "FAIL"); hashMap.put("message", "系统错误"); } return gson.toJson(hashMap); } catch (Exception e) { e.printStackTrace(); } return null; } @Override public Refund weixinRefundApi(CreateRequest createRequest, Long id) { Config config = wechatPayConfigService.getWechatConfig(id); if (config == null) { wechatPayConfigService.initConfig(id); config = wechatPayConfigService.getWechatConfig(id); } // 构建service NativePayService service = new NativePayService.Builder().config(config).build(); Refund refund = service.refund(createRequest); return refund; } /** * 汇聚查询退款状态 */ @Override public JSONObject queryRefund(String refundTrxNo) { String url = "https://www.joinpay.com/trade/queryRefund.action"; List data = new ArrayList(); data.add(new BasicNameValuePair("p1_MerchantNo", JoinpayConstant.mch_no)); data.add(new BasicNameValuePair("p2_RefundOrderNo", refundTrxNo)); data.add(new BasicNameValuePair("p3_Version", "2.1")); String hmac = null; try { hmac = createHmacSign(data, JoinpayConstant.key); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } data.add(new BasicNameValuePair("hmac", hmac)); String result = HttpClientUtils.postKeyValue(url, data); JSONObject resultJson = JSONObject.parseObject(result); return resultJson; } @Override public String joinpayNotifyRefund(HttpServletRequest request) { String r6_Status = request.getParameter("ra_Status"); // 订单号 String sn = request.getParameter("r2_OrderNo"); // 退款订单号 if (StringUtils.isEmpty(sn)) { return "error"; } LambdaQueryWrapper query = Wrappers.lambdaQuery(); query.eq(TOrder::getSn, sn); TOrder order = orderService.getOne(query); if (order == null) { return "error"; } if (order.getStatus() == 3) { return "success"; } // 订单商品数量 if (JoinpayConstant.r6_Status_100.equals(r6_Status)) { if (order.getRefundQuantity() < order.getProductNumber()) { order.setStatus(1); } else { order.setStatus(3); } // 更改订单明细表 LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(TOrderDetails::getOrderSn, sn); // 处理退款中状态的明细 queryWrapper.eq(TOrderDetails::getRefundStatus, "4"); List tOrderDetails = orderDetailsService.list(queryWrapper); for (TOrderDetails tOrderDetail : tOrderDetails) { Integer refundQuantity = tOrderDetail.getRefundQuantity(); Integer productNumber = tOrderDetail.getProductNumber(); if (refundQuantity < productNumber) { // 部分退款 tOrderDetail.setRefundStatus("2"); orderDetailsService.updateById(tOrderDetail); } else { // 全部退款 tOrderDetail.setRefundStatus("3"); orderDetailsService.updateById(tOrderDetail); } } // r4_refundAmount: 退款金额 BigDecimal r4_refundAmount = new BigDecimal(request.getParameter("r4_RefundAmount_str")); if (order.getRefundMarketingAmount() != null) { r4_refundAmount = r4_refundAmount.add(order.getRefundMarketingAmount()); } // price: 订单金额, refundAmount:已退款的金额 BigDecimal price = order.getPrice(); BigDecimal refundAmount = order.getRefundAmount(); TProportion proportion = R.getDataIfSuccess(szwlFeign.getProportion(String.valueOf(order.getEquipmentId()))); if (order.getRefundAmount() != null) { BigDecimal newRefundAmount = refundAmount.add(r4_refundAmount); order.setRefundAmount(refundAmount.add(r4_refundAmount)); // 如果小于订单金额 if (newRefundAmount.compareTo(price) < 0) { JSONArray altInfo = getAltInfo(proportion, price.subtract(newRefundAmount)); order.setAltInfo(altInfo.toString()); } else { JSONArray altInfo = getAltInfo(proportion, price); order.setAltInfo(altInfo.toString()); } } else { order.setRefundAmount(r4_refundAmount); if (r4_refundAmount.compareTo(price) < 0) { JSONArray altInfo = getAltInfo(proportion, price.subtract(r4_refundAmount)); order.setAltInfo(altInfo.toString()); } } // 支付平台产生的退款流水号 String r5_RefundTrxNo = request.getParameter("r5_RefundTrxNo"); order.setRefundTrxNo(r5_RefundTrxNo); order.setRefundDate(new Date()); order.setModifyDate(new Date()); String orderStatus = order.getOrderStatus(); if (StringUtils.isNotEmpty(orderStatus) && orderStatus.equals("0")) { if (order.getStatus().toString().equals("3")) { TEquipment byClientId = R.getDataIfSuccess(szwlFeign.findEquipmentByClientId(order.getClientId())); JSONObject kindData = new JSONObject(); String s = order.getId().toString(); if (s.length() > 6) { s = s.substring(s.length() - 6, s.length()); } kindData.put("mealCode", s); equipmentService.sentMessage(byClientId.getClientId(), PushUtils.buildJson("refuse_success", kindData.toString()).toString()); } } try { esTOrderService.updateDataById(order); } catch (Exception e) { e.printStackTrace(); } finally { orderService.updateById(order); } return "success"; } return "success"; } @Override public String huifuNotifyRefund(HttpServletRequest request) { String respData = request.getParameter("resp_data"); try { // 验签请参sign String sign = request.getParameter("sign"); if (!RSAUtil.verify(respData, HuifuConstant.HUIFU_PUBLIC_KEY, sign)) { // 验签失败处理 log.info("验签失败"); return ""; } JSONObject data = JSONObject.parseObject(respData); String transStat = data.getString("trans_stat"); // 订单号 String sn = data.getString("org_req_seq_id"); if (StrUtil.hasEmpty(sn)) { log.info("返回参数订单编号为空"); return "订单号为空!"; } LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.eq(TOrder::getSn, sn); TOrder order = orderService.getOne(wrapper); if (order == null) { log.info("找不到订单"); return "订单不存在"; } if (HuifuConstant.TRANS_STAT_S.equals(transStat)) { if (order.getRefundQuantity() < order.getProductNumber()) { order.setStatus(1); } else { order.setStatus(3); } String refundOrderNo = data.getString("req_seq_id"); String ordAmt = data.getString("ord_amt"); String refundTrxNo = data.getString("hf_seq_id"); order.setRefundOrderNo(refundOrderNo); order.setRefundDate(new Date()); order.setRefundTrxNo(refundTrxNo); // 更改订单明细表 LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(TOrderDetails::getOrderSn, sn); // 处理退款中状态的明细 queryWrapper.eq(TOrderDetails::getRefundStatus, "4"); List tOrderDetails = orderDetailsService.list(queryWrapper); for (TOrderDetails tOrderDetail : tOrderDetails) { Integer refundQuantity = tOrderDetail.getRefundQuantity(); Integer productNumber = tOrderDetail.getProductNumber(); if (refundQuantity < productNumber) { // 部分退款 tOrderDetail.setRefundStatus("2"); orderDetailsService.updateById(tOrderDetail); } else { // 全部退款 tOrderDetail.setRefundStatus("3"); orderDetailsService.updateById(tOrderDetail); } } String acctSplitBunch = ""; // 部分退款或全部退款 TProportion proportion = R.getDataIfSuccess(szwlFeign.getProportion(String.valueOf(order.getEquipmentId()))); if (order.getRefundAmount() != null) { // 退款总额 BigDecimal newRefundAmount = order.getRefundAmount().add(new BigDecimal(ordAmt).setScale(2, RoundingMode.HALF_UP)); order.setRefundAmount(newRefundAmount); // 如果小于订单金额 if (newRefundAmount.compareTo(order.getPrice()) < 0) { acctSplitBunch = getAcctSplitBunch(proportion, order.getPrice().subtract(newRefundAmount), order.getCompanyType()).toString(); order.setAcctSplitBunch(acctSplitBunch); } else { acctSplitBunch = getAcctSplitBunch(proportion, order.getPrice(), order.getCompanyType()).toString(); order.setAcctSplitBunch(acctSplitBunch); } } else { order.setRefundAmount(new BigDecimal(ordAmt).setScale(2, RoundingMode.HALF_UP)); if (new BigDecimal(ordAmt).setScale(2, RoundingMode.HALF_UP).compareTo(order.getPrice()) < 0) { // 重新设置分销 acctSplitBunch = getAcctSplitBunch(proportion, order.getPrice() .subtract(new BigDecimal(ordAmt).setScale(2, RoundingMode.HALF_UP)), order.getCompanyType()).toString(); order.setAcctSplitBunch(acctSplitBunch); } } try { esTOrderService.updateDataById(order); } catch (Exception e) { e.printStackTrace(); } finally { orderService.updateById(order); } return "RECV_ORD_ID_" + refundOrderNo; } } catch (Exception e) { log.info("异步回调开始,参数,request={}", respData, e); } return ""; } @Override public String alipayPay(String sn, BigDecimal amount, String productName, Long alipayId, String notifyUrl, String clientId) throws AlipayApiException { TAlipayConfig tAlipayConfig = alipayConfigService.getById(alipayId); AlipayConfig alipayConfig = new AlipayConfig(); alipayConfig.setAppId(tAlipayConfig.getAppId()); alipayConfig.setPrivateKey(tAlipayConfig.getPrivateKey()); alipayConfig.setFormat("json"); alipayConfig.setAlipayPublicKey(tAlipayConfig.getAlipayPublicKey()); alipayConfig.setCharset("UTF-8"); alipayConfig.setSignType("RSA2"); AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig); AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest(); AlipayTradePrecreateModel model = new AlipayTradePrecreateModel(); model.setOutTradeNo(sn); model.setTotalAmount(amount.toString()); model.setSubject(productName); model.setSellerId(tAlipayConfig.getSellerId()); model.setTerminalId(clientId); request.setBizModel(model); request.setNotifyUrl(notifyUrl); AlipayTradePrecreateResponse response = alipayClient.execute(request); System.out.println(response.getBody()); log.info("支付宝扫码支付接口返回结果:{}", response.getBody()); if (response.isSuccess()) { log.info("调用支付宝扫码支付接口成功:{}", response.getBody()); System.out.println("二维码地址:" + response.getQrCode()); return response.getQrCode(); } else { System.out.println("调用失败"); log.info("调用支付宝扫码支付接口失败:{}", response.getBody()); return null; } } @Transactional(rollbackFor = Exception.class) @Override public void processAlipayOrder(Map params, TOrder order) { log.info("处理订单"); if (order.getStatus() != 0) { return; } order.setStatus(1); // 交易时间 String gmtPayment = params.get("gmt_payment"); Date date = new Date(); try { date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(gmtPayment); } catch (ParseException e) { // 忽略时间转换错误 } order.setPayDate(date); // 支付宝交易号 String tradeNo = params.get("trade_no"); order.setTrxNo(tradeNo); // 更新订单明细状态 LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.eq(TOrderDetails::getOrderSn, order.getSn()); List orderDetails = orderDetailsService.list(lambdaQueryWrapper); for (TOrderDetails orderDetail : orderDetails) { orderDetail.setRefundStatus("1"); orderDetailsService.updateById(orderDetail); } // 发送支付成功消息给设备 TEquipment equipment = R.getDataIfSuccess(szwlFeign.findEquipmentByClientId(order.getClientId())); JSONObject kindData = new JSONObject(); kindData.put("sn", order.getSn()); kindData.put("productName", order.getProductName()); if (!order.getIsNotified().equals("1")) { String paySuccess = equipmentService.sentMessage(equipment.getClientId(), PushUtils.buildJson("pay_success", kindData.toString()).toString()); if (paySuccess.equals("success")) { order.setIsNotified("1"); } // 推送微信订单 TAdmin admin = R.getDataIfSuccess(szwlFeign.getAdmin(String.valueOf(order.getAdminId()))); // 判断是否开启订单推送功能 if (admin != null && StringUtils.isNotEmpty(admin.getOrderNotice()) && admin.getOrderNotice().equals("1")) { String openId = R.getDataIfSuccess(szwlFeign.getOpenId(order.getAdminId())); // 获取openId if (StringUtils.isNotEmpty(openId)) { orderService.newSendWechatMessage(openId, equipment, order, admin.getCompanyType()); } } } orderService.updateById(order); try { // 保存订单信息到ES if (order.getProductNumber() == null || order.getProductNumber() == 0) { order.setProductNumber(1); } orderFeign.saveToEs(order); } catch (Exception e) { e.printStackTrace(); } } @Override public void sendWechatMessage(String openId, TEquipment equipment, TOrder order, String companyType) { String accessToken = ""; try { if (StringUtils.isEmpty(companyType) || companyType.equals("0")) { TAdmin admin = R.getDataIfSuccess(szwlFeign.getAdmin("2738")); accessToken = admin.getApiKey(); log.info("申泽的accessToken:{}", accessToken); } else { TAdmin admin = R.getDataIfSuccess(szwlFeign.getAdmin("2739")); accessToken = admin.getApiKey(); log.info("七云的accessToken:{}", accessToken); } } catch (Exception e) { e.printStackTrace(); } // 推送消息 // 模板参数 Map sendMag = new HashMap(); // 转换时间为String类型 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String payTime = format.format(order.getPayDate()); // 模版参数 if (StringUtils.isNotEmpty(equipment.getName())) { if (equipment.getName().length() > 20) { sendMag.put("thing15", new WeChatTemplateMsg(equipment.getName().substring(0, 15) + "...")); } else { sendMag.put("thing15", new WeChatTemplateMsg(equipment.getName())); } } else { String clientId = equipment.getClientId(); sendMag.put("thing15", new WeChatTemplateMsg(clientId.substring(clientId.length() - 6))); } if (order.getProductName().length() > 20) { sendMag.put("thing37", new WeChatTemplateMsg(order.getProductName().substring(0, 15) + "...")); } else { sendMag.put("thing37", new WeChatTemplateMsg(order.getProductName())); } sendMag.put("character_string8", new WeChatTemplateMsg(order.getSn())); sendMag.put("amount34", new WeChatTemplateMsg(order.getPrice().toString())); sendMag.put("time36", new WeChatTemplateMsg(payTime)); RestTemplate restTemplate = new RestTemplate(); Map sendBody = new HashMap<>(); sendBody.put("touser", openId); sendBody.put("topcolor", "#FF0000"); sendBody.put("data", sendMag); if (StringUtils.isEmpty(companyType) || companyType.equals("0")) { sendBody.put("template_id", HuifuConstant.SZ_TEMPLATE_ID); } else { sendBody.put("template_id", HuifuConstant.SC_TEMPLATE_ID); } sendMessage(accessToken, restTemplate, sendBody); } @Override public void newSendWechatMessage(String openId, TEquipment equipment, TOrder order, String companyType) { String accessToken = ""; try { if (StringUtils.isEmpty(companyType) || companyType.equals("0")) { TAdmin admin = R.getDataIfSuccess(szwlFeign.getAdmin("2738")); accessToken = admin.getApiKey(); log.info("申泽的accessToken:{}", accessToken); } else { TAdmin admin = R.getDataIfSuccess(szwlFeign.getAdmin("2739")); accessToken = admin.getApiKey(); log.info("七云的accessToken:{}", accessToken); } } catch (Exception e) { e.printStackTrace(); } // 推送消息 // 模板参数 Map sendMag = new HashMap(); // 转换时间为String类型 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String payTime = format.format(order.getPayDate()); // 模版参数 // 设备名称 if (StringUtils.isNotEmpty(equipment.getName())) { if (equipment.getName().length() > 20) { sendMag.put("thing15", new WeChatTemplateMsg(equipment.getName().substring(0, 15) + "...")); } else { sendMag.put("thing15", new WeChatTemplateMsg(equipment.getName())); } } else { String clientId = equipment.getClientId(); sendMag.put("thing15", new WeChatTemplateMsg(clientId.substring(clientId.length() - 6))); } // 订单编号 sendMag.put("character_string8", new WeChatTemplateMsg(order.getSn())); // 交易金额 sendMag.put("amount29", new WeChatTemplateMsg(order.getPrice().toString())); // 支付方式 sendMag.put("const44", new WeChatTemplateMsg(checkPayType(order.getFrpCode()))); // 交易时间 sendMag.put("time36", new WeChatTemplateMsg(payTime)); RestTemplate restTemplate = new RestTemplate(); Map sendBody = new HashMap<>(); sendBody.put("touser", openId); sendBody.put("topcolor", "#FF0000"); sendBody.put("data", sendMag); if (StringUtils.isEmpty(companyType) || companyType.equals("0")) { sendBody.put("template_id", HuifuConstant.NEW_SZ_TEMPLATE_ID); } else { sendBody.put("template_id", HuifuConstant.NEW_SC_TEMPLATE_ID); } sendMessage(accessToken, restTemplate, sendBody); } public String sqCardPay(String orderNo, BigDecimal amount, String productName, String authCode, TSqbConfig sqbConfig, String userName, String ip) { HttpProxy hp = new HttpProxy(ShouQianBaConstant.API_DOMAIN); try { CompletableFuture future = CompletableFuture.supplyAsync(() -> { // 异步调用支付接口 String payResult = hp.pay( ip, sqbConfig.getTerminalSn(), sqbConfig.getNewTerminalKey(), orderNo, authCode, amount.toString(), productName, userName); log.info("支付结果:{}", payResult); return payResult; }); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } long startTimestampMs = System.currentTimeMillis(); String orderStatus = ""; while (System.currentTimeMillis() - startTimestampMs < ShouQianBaConstant.REMAINING_TIME) { String query = hp.query( sqbConfig.getTerminalSn(), sqbConfig.getNewTerminalKey(), orderNo); log.info("查询结果:{}", query); JSONObject queryJsonObject = JSON.parseObject(query); JSONObject bizResponse = queryJsonObject.getJSONObject("biz_response"); String resultCode = bizResponse.getString("result_code"); if (resultCode.equals(ShouQianBaConstant.FAIL)) { break; } orderStatus = bizResponse.getJSONObject("data") .getString("order_status"); if (orderStatus.equals(ShouQianBaConstant.PAID)) { log.info("订单支付成功:{}", orderNo); // JSONObject bizResponse = queryJsonObject.getJSONObject("biz_response"); // 付款时间 String channelFinishTime = bizResponse.getJSONObject("data").getString("channel_finish_time"); // 收钱吧订单号 String sn = bizResponse.getJSONObject("data").getString("sn"); LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(); queryWrapper.eq(TOrder::getSn, orderNo); queryWrapper.eq(TOrder::getStatus, 0); TOrder order = getOne(queryWrapper); if (order != null) { order.setStatus(1); order.setTrxNo(sn); Date date = new Date(); try { date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(channelFinishTime); } catch (ParseException e) { // 忽略时间转换错误 } order.setPayDate(date); // 更新订单明细状态 LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.eq(TOrderDetails::getOrderSn, orderNo); List orderDetails = orderDetailsService.list(lambdaQueryWrapper); for (TOrderDetails orderDetail : orderDetails) { orderDetail.setRefundStatus("1"); orderDetailsService.updateById(orderDetail); } // 发送支付成功消息给设备 TEquipment equipment = R.getDataIfSuccess(szwlFeign.findEquipmentByClientId(order.getClientId())); JSONObject kindData = new JSONObject(); kindData.put("sn", order.getSn()); kindData.put("productName", order.getProductName()); if (!order.getIsNotified().equals("1")) { String paySuccess = equipmentService.sentMessage(equipment.getClientId(), PushUtils.buildJson("pay_success", kindData.toString()).toString()); if (paySuccess.equals("success")) { order.setIsNotified("1"); } // 推送微信订单 TAdmin admin = R.getDataIfSuccess(szwlFeign.getAdmin(String.valueOf(order.getAdminId()))); // 判断是否开启订单推送功能 if (admin != null && StringUtils.isNotEmpty(admin.getOrderNotice()) && admin.getOrderNotice().equals("1")) { String openId = R.getDataIfSuccess(szwlFeign.getOpenId(order.getAdminId())); // 获取openId if (StringUtils.isNotEmpty(openId)) { orderService.newSendWechatMessage(openId, equipment, order, admin.getCompanyType()); } } } orderService.updateById(order); try { // 保存订单信息到ES if (order.getProductNumber() == null || order.getProductNumber() == 0) { order.setProductNumber(1); } orderFeign.saveToEs(order); } catch (Exception e) { e.printStackTrace(); } } break; } else if (!orderStatus.equals(ShouQianBaConstant.CREATED) && !orderStatus.equals(ShouQianBaConstant.PAY_ERROR)) { break; } try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } return orderStatus; } catch (Exception e) { e.printStackTrace(); } return null; } @Override public JsonMessage sqbCardPay(String authCode, String frpCode, String clientId, String ip, Map productNameMap) { if (productNameMap == null) { return JsonMessage.error("数据出错"); } if (StringUtils.isEmpty(ip)) { return JsonMessage.error("ip不能为空"); } if (!authCode.startsWith("0100")) { return JsonMessage.error("请使用数币钱包支付"); } StringBuilder note = new StringBuilder(); StringBuilder productName = new StringBuilder(); String productNo = ""; Map productMap = new HashMap<>(); int productNumber = 0; TEquipment equipment = R.getDataIfSuccess(szwlFeign.findEquipmentByClientId(clientId)); if (equipment == null || equipment.getId() == null) { return JsonMessage.error("找不到设备"); } BigDecimal price = new BigDecimal("0.00"); TEquipmentDesc equipmentDesc = R.getDataIfSuccess(szwlFeign.findEquipmentById(equipment.getId())); if (equipmentDesc == null || equipmentDesc.getEquipmentId() == null || equipmentDesc.getPayType() == null || equipmentDesc.getPayType().equals("0")) { for (String key : productNameMap.keySet()) { String entryValue = String.valueOf(productNameMap.get(key)); List value = JSON.parseArray(entryValue, String.class); List promoCodeList = new ArrayList<>(); //1,校验优惠码 if (value.size() > 0) { for (String code : value) { if (!code.equals("0")) { TPromoCode promoCode = new TPromoCode(); ResponseModel tPromoCodeResponseModel = szwlFeign.selectTPromoCode(code, equipment.getAdminId().toString()); TPromoCode tPromoCode = tPromoCodeResponseModel.getData(); promoCode = tPromoCode; if (tPromoCode == null || tPromoCode.getId() == null) { //不存在 return JsonMessage.success("1"); } Date lastUseDate = null; if (promoCode != null) { lastUseDate = promoCode.getLastUseDate(); } if (lastUseDate != null && lastUseDate.getTime() < ((new Date()).getTime())) { promoCode.setIsUse("2"); szwlFeign.updatePromoCode(String.valueOf(promoCode.getId()), "2"); //过期 return JsonMessage.success("4"); } if (promoCode.getId() == null) { //不存在 return JsonMessage.success("1"); } if (promoCode.getIsUse().equals("1")) { //被使用 return JsonMessage.success("2"); } if (!promoCode.getAdminId().equals("1")) { if (!String.valueOf(equipment.getAdminId()).equals(promoCode.getAdminId())) { return JsonMessage.success("3"); } } if (promoCode.getDiscount() == null) { //旧优惠码 return JsonMessage.success("0"); } if (promoCode.getDiscount() != null && promoCode.getDiscount() == 0) { //0折 return JsonMessage.success("0"); } promoCodeList.add(promoCode); } } } String[] productNum = key.split("-"); String productNamea = productNum[0]; String num = productNum[1]; productMap.put(productNamea, Integer.valueOf(num)); productNumber += Integer.parseInt(num); productName.append(productNamea).append("x").append(num).append(","); TProduct product = R.getDataIfSuccess(szwlFeign.getProduct(String.valueOf(equipment.getId()), productNamea)); if (product == null) { return JsonMessage.error("找不到商品"); } note.append(productNamea).append("-").append(product.getNo()).append(":"); BigDecimal productPrice = product.getRmbPrice(); productNo = product.getNo(); if (promoCodeList.size() > 0) { //有优惠码 BigDecimal onePrice = new BigDecimal("0.00"); int i; for (i = 0; i < promoCodeList.size(); i++) { BigDecimal discount = BigDecimal.valueOf(promoCodeList.get(i).getDiscount()).setScale(2, RoundingMode.HALF_DOWN); BigDecimal price1 = productPrice.multiply(discount).divide(new BigDecimal(10)).setScale(2, RoundingMode.HALF_DOWN); price = price.add(price1); onePrice = onePrice.add(price1); } if (i < Integer.parseInt(num)) { int a = Integer.parseInt(num) - i; BigDecimal price2 = productPrice.multiply(new BigDecimal(a)).setScale(2, RoundingMode.HALF_DOWN); price = price.add(price2); onePrice = onePrice.add(price2); } note.append(onePrice).append("-").append(num).append(","); } else { //1,type=0,原始设定,没有第二件半价 int a = Integer.parseInt(num); BigDecimal price2 = productPrice.multiply(new BigDecimal(a)).setScale(2, RoundingMode.HALF_DOWN); price = price.add(price2); note.append(price2).append("-").append(num).append(","); } } } else { for (String key : productNameMap.keySet()) { String[] productNum = key.split("-"); String productNamea = productNum[0]; String num = productNum[1]; productMap.put(productNamea, Integer.valueOf(num)); TProduct product = R.getDataIfSuccess(szwlFeign.getProduct(String.valueOf(equipment.getId()), productNamea)); productNo = product.getNo(); BigDecimal productPrice = product.getRmbPrice(); productName.append(productNamea).append("x").append(num).append(","); note.append(productNamea).append("-").append(product.getNo()).append(":"); switch (num) { case "1": //1个 0个半价 price = price.add(productPrice); note.append(price).append("-").append(num).append(","); break; case "2": //2个 1个半价 price = price.add(productPrice); price = price.add(productPrice.multiply(new BigDecimal(5)).divide(new BigDecimal(10)).setScale(2, RoundingMode.HALF_DOWN)); note.append(price).append("-").append(num).append(","); break; case "3": //3个 1个半价 price = price.add(productPrice); price = price.add(productPrice.multiply(new BigDecimal(5)).divide(new BigDecimal(10)).setScale(2, RoundingMode.HALF_DOWN)); price = price.add(productPrice); note.append(price).append("-").append(num).append(","); break; case "4": //4个 2个半价 price = price.add(productPrice); price = price.add(productPrice.multiply(new BigDecimal(5)).divide(new BigDecimal(10)).setScale(2, RoundingMode.HALF_DOWN)); price = price.add(productPrice); price = price.add(productPrice.multiply(new BigDecimal(5)).divide(new BigDecimal(10)).setScale(2, RoundingMode.HALF_DOWN)); note.append(price).append("-").append(num).append(","); break; case "5": //5个 2个半价 price = price.add(productPrice); price = price.add(productPrice.multiply(new BigDecimal(5)).divide(new BigDecimal(10)).setScale(2, RoundingMode.HALF_DOWN)); price = price.add(productPrice); price = price.add(productPrice.multiply(new BigDecimal(5)).divide(new BigDecimal(10)).setScale(2, RoundingMode.HALF_DOWN)); price = price.add(productPrice); note.append(price).append("-").append(num).append(","); break; } } } Long equipmentId = equipment.getId(); //查找商品 if (BigDecimal.ZERO.compareTo(price) >= 0) { return JsonMessage.error("商品价格异常"); } Long client6 = Long.parseLong(clientId.substring(clientId.length() - 6)); String sn = orderService.initSn(client6); //获取分销 关联设备 TAdmin admin = R.getDataIfSuccess(szwlFeign.getAdmin(String.valueOf(equipment.getAdminId()))); // 获取收钱吧配置 LambdaQueryWrapper sqbConfigQuery = Wrappers.lambdaQuery(); sqbConfigQuery.eq(TSqbConfig::getAdminId, admin.getId()); TSqbConfig sqbConfig = sqbConfigService.getOne(sqbConfigQuery); if (sqbConfig == null) { return JsonMessage.error("商户未配置"); } // 查询是否签到,没有的话就进行签到 if (StringUtils.isNotEmpty(sqbConfig.getCheckin()) && sqbConfig.getCheckin().equals("0")) { HttpProxy hp = new HttpProxy(ShouQianBaConstant.API_DOMAIN_CONFIG); org.json.JSONObject terminal = hp.checkin(sqbConfig.getDeviceId(), sqbConfig.getTerminalSn(), sqbConfig.getTerminalKey()); if (terminal == null) { return JsonMessage.error("签到失败"); } String newTerminalKey = terminal.getString("terminal_key"); sqbConfig.setTerminalKey(newTerminalKey); sqbConfig.setNewTerminalKey(newTerminalKey); sqbConfig.setCheckin("1"); sqbConfigService.updateById(sqbConfig); } String companyType = admin.getCompanyType(); BigDecimal amount = price.setScale(2, RoundingMode.HALF_DOWN); amount = amount.multiply(new BigDecimal(100)).setScale(0); TOrder order = new TOrder(); order.setId(IDGenerator.orderID()); order.setCreateDate(new Date()); order.setModifyDate(new Date()); order.setAdminId(admin.getId()); order.setSn(sn); if (productNumber == 1) { productName.delete(productName.length() - 3, productName.length()); } else { productName.deleteCharAt(productName.length() - 1); } order.setProductName(productName.toString()); order.setPrice(price); order.setClientId(equipment.getClientId()); order.setEquipmentId(equipmentId); order.setFrpCode(frpCode); order.setProductNumber(productNumber); order.setStatus(0); String payPlatform = "4"; order.setPayPlatform(payPlatform); order.setCompanyType(companyType); order.setMachineType(equipment.getMachineType()); order.setProductNo(productNo); order.setNote(note.toString()); // 订单明细表 TOrderDetails orderDetails = new TOrderDetails(); orderDetails.setAdminId(admin.getId()); orderDetails.setEquipmentId(equipmentId); orderDetails.setCreateDate(new Date()); orderDetails.setCompanyType(companyType); orderDetails.setRefundStatus("0"); orderDetails.setMachineType(equipment.getMachineType()); // 添加到订单明细表 for (String key : productMap.keySet()) { Integer productNum = productMap.get(key); TProduct product = R.getDataIfSuccess(szwlFeign.getProduct(String.valueOf(equipment.getId()), key)); orderDetails.setProductNo(product.getNo()); orderDetails.setProductName(key); orderDetails.setPrice(product.getRmbPrice()); orderDetails.setProductNumber(productNum); orderDetails.setAmount(product.getRmbPrice().multiply(new BigDecimal(productNum))); orderDetails.setId(HuifuUtils.initDetailsId()); orderDetails.setOrderSn(sn); orderDetailsService.save(orderDetails); } orderService.save(order); String productName1 = ""; if (productNumber > 1) { productName1 = "棉花糖"; } else { productName1 = productName.toString(); } String result; try { result = sqCardPay( sn, amount, productName1, authCode, sqbConfig, admin.getUsername(), ip ); } catch (Exception e) { e.printStackTrace(); return JsonMessage.error("申请支付失败"); } // 微信支付支付申请返回支付二维码图片 if (result.equals(ShouQianBaConstant.PAID)) { JSONObject kindData = new JSONObject(); kindData.put("sn", sn); return JsonMessage.success(kindData.toString()); } else { return JsonMessage.error("支付失败"); } } @Override public ResponseModel sqbRefund(TOrder torder) { // 退款金额: refusePrice BigDecimal refusePrice = torder.getPrice().setScale(2, RoundingMode.HALF_DOWN); // 退款数量: refundNumber Integer refundNumber = torder.getProductNumber(); // 退款明细:note String note = torder.getNote(); String[] refundDetails = note.split(","); Map refundMap = new HashMap<>(); for (String refundDetail : refundDetails) { String[] keyValue = refundDetail.split("-"); String key = keyValue[0]; String value = keyValue[1]; refundMap.put(key, Integer.valueOf(value)); } if (refusePrice.compareTo(new BigDecimal("0.00")) <= 0) { return R.fail(ResponseCodesEnum.A0001, "退款金额非法"); } TOrder order = orderService.getById(torder.getId()); if (order.getRefundQuantity() != null && order.getRefundQuantity() > 0) { order.setRefundQuantity(refundNumber + order.getRefundQuantity()); } else { order.setRefundQuantity(refundNumber); } if (refusePrice.compareTo(order.getPrice()) > 0) { return R.fail(ResponseCodesEnum.A0001, "退款金额非法"); } if (order.getRefundAmount() != null && order.getRefundAmount().add(refusePrice).compareTo(order.getPrice()) > 0) { return R.fail(ResponseCodesEnum.A0001, "退款金额非法"); } if (order.getStatus().equals("0")) { return R.fail(ResponseCodesEnum.A0002, "订单非支付状态"); } // 获取收钱吧配置 LambdaQueryWrapper sqbConfigQuery = Wrappers.lambdaQuery(); sqbConfigQuery.eq(TSqbConfig::getAdminId, order.getAdminId()); TSqbConfig sqbConfig = sqbConfigService.getOne(sqbConfigQuery); if (sqbConfig == null) { return R.fail(ResponseCodesEnum.A0002, "商户未配置"); } LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.eq(TOrderDetails::getOrderSn, order.getSn()); List orderDetails = orderDetailsService.list(wrapper); HttpProxy hp = new HttpProxy(ShouQianBaConstant.API_DOMAIN); try { String amount = refusePrice.multiply(new BigDecimal(100)).setScale(0).toString(); String refund = hp.refund(sqbConfig.getTerminalSn(), sqbConfig.getNewTerminalKey(), order.getSn(), amount); log.info("退款结果:{}", refund); JSONObject jsonObject = JSON.parseObject(refund); String resultCode = jsonObject.getString("result_code"); log.info("下单结果码:{}", resultCode); if (resultCode.equals("200")) { String bizResultCode = jsonObject.getJSONObject("biz_response").getString("result_code"); log.info("下单业务结果码:{}", bizResultCode); if (bizResultCode.equals(ShouQianBaConstant.REFUND_SUCCESS)) { String orderStatus = jsonObject.getJSONObject("biz_response").getJSONObject("data").getString("order_status"); log.info("订单状态:{}", orderStatus); if (orderStatus.equals(ShouQianBaConstant.REFUNDED) || orderStatus.equals(ShouQianBaConstant.PARTIAL_REFUNDED)) { // 退款序列号 String refundRequestNo = jsonObject.getJSONObject("biz_response").getJSONObject("data").getString("refund_request_no"); // 退款成功 // 已退款 if (order.getRefundQuantity() < order.getProductNumber()) { order.setStatus(1); } else { order.setStatus(3); } orderService.updateById(order); // 修改订单明细 for (TOrderDetails orderDetail : orderDetails) { String orderDetailId = orderDetail.getId(); Integer productNumber = refundMap.get(orderDetailId); if (productNumber != null) { // 退款数量 orderDetail.setRefundQuantity(productNumber); // 退款状态 if (productNumber < orderDetail.getProductNumber()) { // 部分退款 orderDetail.setRefundStatus("2"); } else { // 全部退款 orderDetail.setRefundStatus("3"); } // 退款金额 orderDetail.setRefundAmount(orderDetail.getPrice().multiply(new BigDecimal(productNumber))); orderDetailsService.updateById(orderDetail); } } // 已退款金额 BigDecimal refundAmount = order.getRefundAmount(); BigDecimal price = order.getPrice(); if (refundAmount != null) { if (price.compareTo(refundAmount) == 0) { order.setRefundAmount(refundAmount); } else { order.setRefundAmount(refundAmount.add(refusePrice)); } } else { order.setRefundAmount(refusePrice); } // 退款时间 order.setRefundDate(new Date()); order.setModifyDate(new Date()); order.setRefundTrxNo(refundRequestNo); try { orderFeign.saveToEs(order); } catch (Exception e) { e.printStackTrace(); } finally { orderService.updateById(order); } return R.ok("申请退款已成功"); } } } } catch (Exception e) { e.printStackTrace(); } return R.fail(ResponseCodesEnum.B0001, "申请退款失败,请联系管理员"); } @Override public JsonMessage scanpay(String code, String clientId, String productName, String frpCode, String pri) throws Exception { TEquipment equipment = R.getDataIfSuccess(szwlFeign.findEquipmentByClientId(clientId)); if (equipment == null || equipment.getId() == null) { return JsonMessage.error("找不到设备"); } // 验证优惠码,code为空则不选用优惠码 TPromoCode promoCode = new TPromoCode(); if (StringUtils.isNotEmpty(code)) { //有优惠码,需要对优惠码进行验证 ResponseModel tPromoCodeResponseModel = szwlFeign.selectTPromoCode(code, equipment.getAdminId().toString()); promoCode = tPromoCodeResponseModel.getData(); String checkCode = checkCode(promoCode, equipment); if (StringUtils.isNotEmpty(checkCode)) { return JsonMessage.success(checkCode); } } // 支付方式 if (!ConfigConsts.ALIPAY_NATIVE.equals(frpCode) && !ConfigConsts.WECHAT_NATIVE.equals(frpCode)) { return JsonMessage.error("参数错误"); } Long equipmentId = equipment.getId(); // 查找商品 ResponseModel product1 = szwlFeign.getProduct(String.valueOf(equipmentId), productName); TProduct product = product1.getData(); if (product == null) { return JsonMessage.error("找不到商品"); } BigDecimal price = product.getRmbPrice(); if (StringUtils.isNotEmpty(pri)) { price = new BigDecimal(pri); } // 计算折扣后的价格 if (StringUtils.isNotEmpty(code)) { BigDecimal discount = BigDecimal.valueOf(promoCode.getDiscount()); if (StringUtils.isNotEmpty(promoCode.getType()) && promoCode.getType().equals("1")) { if (price.compareTo(discount) > 0) { // 如果 price 大于 discount,从 price 中减去 discount price = price.subtract(discount).setScale(2, RoundingMode.HALF_DOWN); } else { // 如果 price 小于等于 discount,将 price 设置为 0 return JsonMessage.success("0"); } } else { price = product.getRmbPrice().multiply(discount).divide(new BigDecimal(10)).setScale(2, RoundingMode.HALF_DOWN); } } // 判断价格是否小于等于0 if (BigDecimal.ZERO.compareTo(price) >= 0) { return JsonMessage.error("商品价格异常"); } // 生成订单编号 Long client6 = Long.parseLong(clientId.substring(clientId.length() - 6)); String sn = orderService.initSn(client6); // 获取关联设备的分销 TProportion proportion = R.getDataIfSuccess(szwlFeign.getProportion(String.valueOf(equipmentId))); if (proportion == null || proportion.getId() == null) { return JsonMessage.error("设备商家未完成分销设置"); } TAdmin admin = R.getDataIfSuccess(szwlFeign.getAdmin(String.valueOf(equipment.getAdminId()))); if (admin == null) { return JsonMessage.error("找不到设备商家"); } // 支付方式:0或null为汇聚,1为汇付支付 String payPlatform = admin.getPayPlatform(); String companyType = admin.getCompanyType(); // 汇聚分账参数 JSONArray altInfo = new JSONArray(); // 汇付分账明细参数 JSONObject acctSplitBunch = new JSONObject(); if (StringUtils.isNotEmpty(payPlatform) && payPlatform.equals("1")) { acctSplitBunch = getAcctSplitBunch(proportion, price, companyType); if (!(acctSplitBunch.size() > 0)) { return JsonMessage.error("设备商家未注册结算账号"); } } else { altInfo = getAltInfo(proportion, price); if (!(altInfo.size() > 0)) { return JsonMessage.error("设备商家未注册结算账号"); } } BigDecimal amount = price.setScale(2, RoundingMode.HALF_DOWN); String productDesc = ""; String commonParameter = ""; String returnUrl = null; String notifyUrl = JoinpayConstant.Notify_Url; String isShowPic = "1"; String openId = null; String authCode = null; String appid = null; String transactionModel = null; String tradeMerchantNo = admin.getTradeMerchantNo(); String buyerId = null; String isAlt = "1"; String altType = "11"; String altUrl = null; BigDecimal marketingAmount = null; if (StringUtils.isNotEmpty(pri)) { productName = "棉花糖"; } Integer productNumber = 1; TOrder order = new TOrder(); order.setId(IDGenerator.orderID()); order.setCreateDate(new Date()); order.setModifyDate(new Date()); order.setAdminId(admin.getId()); order.setSn(sn); order.setProductId(product.getId()); order.setProductNo(product.getNo()); order.setProductName(productName); order.setPrice(price); order.setClientId(equipment.getClientId()); order.setEquipmentId(equipmentId); order.setFrpCode(frpCode); order.setAltInfo(altInfo.toString()); order.setStatus(0); order.setType(admin.getType()); order.setProductNumber(productNumber); order.setCompanyType(admin.getCompanyType()); order.setMachineType(equipment.getMachineType()); if (admin.getType() == 0) { order.setAdminProportion(proportion.getAdminProportion()); order.setAgencyProportion(proportion.getAgencyProportion()); order.setAgencyId(proportion.getAgencyId()); } if (admin.getType() == 1) { order.setAdminProportion(proportion.getAdminProportion()); order.setAgencyProportion(proportion.getAgencyProportion()); order.setAgencyId(proportion.getAgencyId()); order.setMerchantProportion(proportion.getMerchantProportion()); order.setMerchantId(proportion.getMerchantId()); } if (admin.getType() == 2) { order.setAdminProportion(proportion.getAdminProportion()); order.setAgencyProportion(proportion.getAgencyProportion()); order.setAgencyId(proportion.getAgencyId()); order.setMerchantProportion(proportion.getMerchantProportion()); order.setMerchantId(proportion.getMerchantId()); order.setPersonageProportion(proportion.getPersonageProportion()); order.setPersonageId(proportion.getPersonageId()); } order.setPayPlatform(payPlatform); // 订单明细表 TOrderDetails orderDetails = new TOrderDetails(); orderDetails.setId(HuifuUtils.initDetailsId()); orderDetails.setAdminId(admin.getId()); orderDetails.setEquipmentId(equipmentId); orderDetails.setCreateDate(new Date()); orderDetails.setOrderSn(sn); orderDetails.setPrice(price); orderDetails.setProductName(productName); orderDetails.setProductNo(product.getNo()); orderDetails.setProductNumber(productNumber); orderDetails.setAmount(price); orderDetails.setRefundStatus("0"); orderDetails.setCompanyType(companyType); orderDetails.setMachineType(equipment.getMachineType()); String productName1 = productName + "-" + equipment.getName() + "-" + client6; String result = null; if (StringUtils.isNotEmpty(payPlatform) && payPlatform.equals("1")) { // 汇付分账参数 order.setAcctSplitBunch(acctSplitBunch.toString()); if (frpCode.equals(ConfigConsts.WECHAT_NATIVE)) { String resultSn = ""; try { resultSn = huifuMchService.payWechat(order); } catch (Exception e) { e.printStackTrace(); return JsonMessage.error("申请支付失败"); } if (StrUtil.isEmpty(resultSn)) { return JsonMessage.error("找不到支付图片"); } //添加到汇付临时表 if (StrUtil.isNotEmpty(companyType) && companyType.equals("1")) { result = HuifuConstant.SC_JUMP_URL + "/#/payWechat?sn=" + resultSn; } else { result = HuifuConstant.SZ_JUMP_URL + "/#/payWechat?sn=" + resultSn; } log.info("返回链接:{}", result); String qrcode = CodeUtil.toQrcode(result); JSONObject kindData = new JSONObject(); kindData.put("sn", sn); kindData.put("rd_Pic", qrcode); orderService.save(order); orderDetailsService.save(orderDetails); return JsonMessage.success(kindData.toString()); } // 汇付支付 try { result = huifuMchService.uniPay( sn, amount, productName1, productDesc, notifyUrl, frpCode, openId, appid, acctSplitBunch, companyType ); } catch (Exception e) { e.printStackTrace(); return JsonMessage.error("申请支付失败"); } if (StrUtil.isEmpty(result)) { return JsonMessage.error("找不到支付图片"); } String qrcode = CodeUtil.toQrcode(result); JSONObject kindData = new JSONObject(); kindData.put("sn", sn); kindData.put("rd_Pic", qrcode); orderService.save(order); orderDetailsService.save(orderDetails); return JsonMessage.success(kindData.toString()); } else { try { result = joinpayMchService.uniPay( sn, amount, productName1, productDesc, commonParameter, returnUrl, notifyUrl, frpCode, isShowPic, openId, authCode, appid, transactionModel, tradeMerchantNo, buyerId, isAlt, altType, altInfo, altUrl, marketingAmount ); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return JsonMessage.error("申请支付失败"); } JSONObject resultJson = JSONObject.parseObject(result); // 汇聚支付支付申请返回支付二维码图片 String rdPic = resultJson.getString("rd_Pic"); if (StringUtils.isBlank(rdPic)) { return JsonMessage.error("找不到支付图片"); } JSONObject kindData = new JSONObject(); kindData.put("sn", sn); kindData.put("rd_Pic", rdPic); orderService.save(order); orderDetailsService.save(orderDetails); return JsonMessage.success(kindData.toString()); } } /** * 发送微信消息 */ private void sendMessage(String accessToken, RestTemplate restTemplate, Map sendBody) { String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken; ResponseEntity forEntity = restTemplate.postForEntity(sendUrl, sendBody, String.class); JSONObject jsonObject = JSONObject.parseObject(forEntity.getBody()); String messageCode = jsonObject.getString("errcode"); String msgId = jsonObject.getString("msgid"); System.out.println("messageCode : " + messageCode + ", msgId: " + msgId); log.info("微信推送结果:{}", "messageCode : " + messageCode + ", msgId: " + msgId); } public void processRefund(Map bodyMap) { String decrypt = wechatPayConfigService.decryptFromResource(bodyMap); Gson gson = new Gson(); Map map = gson.fromJson(decrypt, HashMap.class); String sn = map.get("out_trade_no").toString(); String refundNo = map.get("out_refund_no").toString(); String amount = map.get("amount").toString(); Map amountMap = gson.fromJson(amount, HashMap.class); String refundPrice = amountMap.get("refund").toString(); if (StringUtils.isNotEmpty(sn)) { LambdaQueryWrapper query = Wrappers.lambdaQuery(); query.eq(TOrder::getSn, sn); TOrder order = getOne(query); // 已退款 if (order.getRefundQuantity() < order.getProductNumber()) { order.setStatus(1); } else { order.setStatus(3); } // 更改订单明细表 LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(TOrderDetails::getOrderSn, sn); // 处理退款中状态的明细 queryWrapper.eq(TOrderDetails::getRefundStatus, "4"); List tOrderDetails = orderDetailsService.list(queryWrapper); for (TOrderDetails tOrderDetail : tOrderDetails) { Integer refundQuantity = tOrderDetail.getRefundQuantity(); Integer productNumber = tOrderDetail.getProductNumber(); if (refundQuantity < productNumber) { // 部分退款 tOrderDetail.setRefundStatus("2"); orderDetailsService.updateById(tOrderDetail); } else { // 全部退款 tOrderDetail.setRefundStatus("3"); orderDetailsService.updateById(tOrderDetail); } } //退款金额要除以100 BigDecimal r4_refundAmount = new BigDecimal(refundPrice).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP).setScale(2, RoundingMode.HALF_DOWN); // if(order.getRefundMarketingAmount()!=null){ // r4_refundAmount =r4_refundAmount.add(order.getRefundMarketingAmount()); // } BigDecimal refundAmount = order.getRefundAmount(); BigDecimal price = order.getPrice(); if (refundAmount != null) { if (price.compareTo(refundAmount) == 0) { order.setRefundAmount(refundAmount); } else { order.setRefundAmount(refundAmount.add(r4_refundAmount)); } } else { order.setRefundAmount(r4_refundAmount); } order.setRefundDate(new Date()); order.setModifyDate(new Date()); order.setRefundTrxNo(refundNo); try { orderFeign.saveToEs(order); } catch (Exception e) { e.printStackTrace(); } finally { updateById(order); } } } /** * 验证优惠码 */ public String checkCode(TPromoCode promoCode, TEquipment equipment) { //有优惠码,需要对优惠码进行验证 if (promoCode == null || promoCode.getId() == null) { //不存在 return "1"; } Date lastUseDate = promoCode.getLastUseDate(); if (lastUseDate != null && lastUseDate.getTime() < ((new Date()).getTime())) { promoCode.setIsUse("2"); szwlFeign.updatePromoCode(String.valueOf(promoCode.getId()), "2"); //过期 return "4"; } if (promoCode.getIsUse().equals("1")) { //被使用 return "2"; } if (!promoCode.getAdminId().equals("1")) { if (!String.valueOf(equipment.getAdminId()).equals(promoCode.getAdminId())) { //不是本机 return "3"; } } if (promoCode.getDiscount() == null) { //旧优惠码 return "0"; } if (promoCode.getDiscount() == 0) { //0折 return "0"; } return null; } /** * 汇聚分销明细 */ public JSONArray getAltInfo(TProportion proportion, BigDecimal price) { // 获取分账有几方:0:分账方2个,1:分账方3个,2:分账方4个,3:分账方超4个 Integer type = proportion.getType(); // 汇聚分账参数 JSONArray altInfo = new JSONArray(); BigDecimal agencyProportion = null, merchantProportion = null, selfProportion = null; BigDecimal agencyAmount = null; BigDecimal merchantAmount = null; BigDecimal selfAmount = null; TJoinpayMch agencyMch = null; TJoinpayMch merchantMch = null; TJoinpayMch selfMch = null; JSONObject agencyJson = null; JSONObject merchantJson = null; JSONObject selfJson = null; //取消平台扣手续费 BigDecimal cutPrice = price.setScale(2, RoundingMode.HALF_UP); BigDecimal refuseAmount = new BigDecimal(0.00); switch (type) { case 0: // 商家自己的分销 selfProportion = proportion.getProportion(); // 商家分销获得利润 selfAmount = cutPrice.multiply(selfProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN); // 汇聚平台 selfMch = R.getDataIfSuccess(szwlFeign.getMch(String.valueOf(proportion.getAdminId()))); if (selfMch == null) { return altInfo; } selfJson = new JSONObject(); selfJson.put("altMchNo", selfMch.getAltMchNo()); selfJson.put("altAmount", selfAmount.toString()); selfJson.put("isGuar", "12"); altInfo.add(selfJson); break; case 1: // 商家自己的分销 selfProportion = proportion.getProportion(); // 一级分销 agencyProportion = proportion.getAgencyProportion(); // 商家分销获得利润 selfAmount = cutPrice.multiply(selfProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN); // 汇聚平台 agencyMch = R.getDataIfSuccess(szwlFeign.getMch(String.valueOf(proportion.getAgencyId()))); selfMch = R.getDataIfSuccess(szwlFeign.getMch(String.valueOf(proportion.getAdminId()))); if (selfMch == null || agencyMch == null) { return altInfo; } if (!(agencyProportion.compareTo(refuseAmount) == 0 || agencyProportion == null)) { // 一级分销获得利润 agencyAmount = cutPrice.multiply(agencyProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN); agencyJson = new JSONObject(); agencyJson.put("altMchNo", agencyMch.getAltMchNo()); agencyJson.put("altAmount", agencyAmount.toString()); agencyJson.put("isGuar", "12"); altInfo.add(agencyJson); } // 商家自己分销获得利润 selfJson = new JSONObject(); selfJson.put("altMchNo", selfMch.getAltMchNo()); selfJson.put("altAmount", selfAmount.toString()); selfJson.put("isGuar", "12"); altInfo.add(selfJson); break; case 2: // 商家自己的分销 selfProportion = proportion.getProportion(); // 一级分销 agencyProportion = proportion.getAgencyProportion(); // 二级分销 merchantProportion = proportion.getMerchantProportion(); // 三级分销 // personageProportion = proportion.getPersonageProportion(); // 商家分销获得利润 selfAmount = cutPrice.multiply(selfProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN); // 汇聚 agencyMch = R.getDataIfSuccess(szwlFeign.getMch(String.valueOf(proportion.getAgencyId()))); merchantMch = R.getDataIfSuccess(szwlFeign.getMch(String.valueOf(proportion.getMerchantId()))); selfMch = R.getDataIfSuccess(szwlFeign.getMch(String.valueOf(proportion.getAdminId()))); if (selfMch == null || agencyMch == null || merchantMch == null) { return altInfo; } if (!(agencyProportion.compareTo(refuseAmount) == 0 || agencyProportion == null)) { // 代理分销获得利润 agencyAmount = cutPrice.multiply(agencyProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN); agencyJson = new JSONObject(); agencyJson.put("altMchNo", agencyMch.getAltMchNo()); agencyJson.put("altAmount", agencyAmount.toString()); agencyJson.put("isGuar", "12"); altInfo.add(agencyJson); } if (!(merchantProportion.compareTo(refuseAmount) == 0 || merchantProportion == null)) { // 经销商分销获得利润 merchantAmount = cutPrice.multiply(merchantProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN); merchantJson = new JSONObject(); merchantJson.put("altMchNo", merchantMch.getAltMchNo()); merchantJson.put("altAmount", merchantAmount.toString()); merchantJson.put("isGuar", "12"); altInfo.add(merchantJson); } // 商家自己分销获得利润 merchantJson = new JSONObject(); merchantJson.put("altMchNo", selfMch.getAltMchNo()); merchantJson.put("altAmount", selfAmount.toString()); merchantJson.put("isGuar", "12"); altInfo.add(merchantJson); break; } Iterator iterator = altInfo.iterator(); while (iterator.hasNext()) { JSONObject jsonObject = (JSONObject) iterator.next(); String altAmount = jsonObject.getString("altAmount"); if (altAmount.equals("0.00")) { iterator.remove(); } } return altInfo; } /** * 汇付分销明细 */ public JSONObject getAcctSplitBunch(TProportion proportion, BigDecimal price, String companyType) { // 获取分账有几方:0:分账方2个,1:分账方3个,2:分账方4个,3:分账方超4个 Integer type = proportion.getType(); // 汇付分账明细参数 JSONObject acctSplitBunch = new JSONObject(); JSONArray acctInfos = new JSONArray(); BigDecimal adminProportion = null, agencyProportion = null, merchantProportion = null, selfProportion = null; BigDecimal agencyAmount = null; BigDecimal merchantAmount = null; BigDecimal selfAmount = null; BigDecimal adminAmount = null; THuifuMch agencyHuifu = null; THuifuMch merchantHuifu = null; THuifuMch selfHuifu = null; JSONObject agencyJson = null; JSONObject merchantJson = null; JSONObject selfJson = null; JSONObject adminJson = null; //取消平台扣手续费 BigDecimal cutPrice = price.setScale(2, RoundingMode.HALF_UP); BigDecimal refuseAmount = new BigDecimal(0.00); switch (type) { case 0: // 公司平台分销 adminProportion = proportion.getAdminProportion(); // 商家自己的分销 selfProportion = proportion.getProportion(); // 平台分销获得利润 adminAmount = cutPrice.multiply(adminProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_UP); // 商家分销获得利润 selfAmount = cutPrice.multiply(selfProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN); // 汇付平台 // 商家汇付信息:agencyHuifu selfHuifu = R.getDataIfSuccess(szwlFeign.getHuifuId(proportion.getAdminId())); if (selfHuifu == null) { return acctSplitBunch; } // 公司平台分销 adminJson = new JSONObject(); adminJson.put("div_amt", adminAmount.toString()); // 判断为申泽还是七云 if (StrUtil.isNotEmpty(companyType) && companyType.equals("1")) { adminJson.put("huifu_id", HuifuConstant.SC_DIV_HUIFU_ID); } else { adminJson.put("huifu_id", HuifuConstant.SZ_DIV_HUIFU_ID); } acctInfos.add(adminJson); // 商家分销获得利润 selfJson = new JSONObject(); selfJson.put("div_amt", selfAmount.toString()); selfJson.put("huifu_id", selfHuifu.getHuifuId()); acctInfos.add(selfJson); break; case 1: // 公司平台分销 adminProportion = proportion.getAdminProportion(); // 商家自己的分销 selfProportion = proportion.getProportion(); // 一级分销 agencyProportion = proportion.getAgencyProportion(); // 平台分销获得利润 adminAmount = cutPrice.multiply(adminProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_UP); // 商家分销获得利润 selfAmount = cutPrice.multiply(selfProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN); // 汇付平台 selfHuifu = R.getDataIfSuccess(szwlFeign.getHuifuId(proportion.getAdminId())); agencyHuifu = R.getDataIfSuccess(szwlFeign.getHuifuId(proportion.getAgencyId())); if (selfHuifu == null || agencyHuifu == null) { return acctSplitBunch; } // 公司平台分销 adminJson = new JSONObject(); adminJson.put("div_amt", adminAmount.toString()); // 判断为申泽还是七云 if (StrUtil.isNotEmpty(companyType) && companyType.equals("1")) { adminJson.put("huifu_id", HuifuConstant.SC_DIV_HUIFU_ID); } else { adminJson.put("huifu_id", HuifuConstant.SZ_DIV_HUIFU_ID); } acctInfos.add(adminJson); // 商家分销获得利润 selfJson = new JSONObject(); selfJson.put("div_amt", selfAmount.toString()); selfJson.put("huifu_id", selfHuifu.getHuifuId()); acctInfos.add(selfJson); if (!(agencyProportion.compareTo(refuseAmount) == 0 || agencyProportion == null)) { // 一级分销获得利润 agencyAmount = cutPrice.multiply(agencyProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN); agencyJson = new JSONObject(); agencyJson.put("div_amt", agencyAmount.toString()); agencyJson.put("huifu_id", agencyHuifu.getHuifuId()); acctInfos.add(agencyJson); } break; case 2: // 公司平台分销 adminProportion = proportion.getAdminProportion(); // 商家自己的分销 selfProportion = proportion.getProportion(); // 一级分销 agencyProportion = proportion.getAgencyProportion(); // 二级分销 merchantProportion = proportion.getMerchantProportion(); // 平台分销获得利润 adminAmount = cutPrice.multiply(adminProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_UP); // 商家分销获得利润 selfAmount = cutPrice.multiply(selfProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN); selfHuifu = R.getDataIfSuccess(szwlFeign.getHuifuId(proportion.getAdminId())); agencyHuifu = R.getDataIfSuccess(szwlFeign.getHuifuId(proportion.getAgencyId())); merchantHuifu = R.getDataIfSuccess(szwlFeign.getHuifuId(proportion.getMerchantId())); if (selfHuifu == null || agencyHuifu == null || merchantHuifu == null) { return acctSplitBunch; } // 公司平台分销 adminJson = new JSONObject(); adminJson.put("div_amt", adminAmount.toString()); // 判断为申泽还是七云 if (StrUtil.isNotEmpty(companyType) && companyType.equals("1")) { adminJson.put("huifu_id", HuifuConstant.SC_DIV_HUIFU_ID); } else { adminJson.put("huifu_id", HuifuConstant.SZ_DIV_HUIFU_ID); } acctInfos.add(adminJson); // 商家分销获得利润 selfJson = new JSONObject(); selfJson.put("div_amt", selfAmount.toString()); selfJson.put("huifu_id", selfHuifu.getHuifuId()); acctInfos.add(selfJson); if (!(agencyProportion.compareTo(refuseAmount) == 0 || agencyProportion == null)) { // 一级分销获得利润 agencyAmount = cutPrice.multiply(agencyProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN); agencyJson = new JSONObject(); agencyJson.put("div_amt", agencyAmount.toString()); agencyJson.put("huifu_id", agencyHuifu.getHuifuId()); acctInfos.add(agencyJson); } if (!(merchantProportion.compareTo(refuseAmount) == 0 || merchantProportion == null)) { // 二级分销获得利润 merchantAmount = cutPrice.multiply(merchantProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN); merchantJson = new JSONObject(); merchantJson.put("div_amt", merchantAmount.toString()); merchantJson.put("huifu_id", merchantHuifu.getHuifuId()); acctInfos.add(merchantJson); } break; } // 计算div_amt的总和 BigDecimal totalAmount = BigDecimal.ZERO; for (int i = 0; i < acctInfos.size(); i++) { JSONObject jsonObject = acctInfos.getJSONObject(i); BigDecimal divAmt = new BigDecimal(jsonObject.getString("div_amt")); totalAmount = totalAmount.add(divAmt); } // 如果总和超过原本金额,调整div_amt if (totalAmount.compareTo(price) > 0) { BigDecimal diffAmount = totalAmount.subtract(price); for (int i = 0; i < acctInfos.size(); i++) { JSONObject jsonObject = acctInfos.getJSONObject(i); String huifuId = jsonObject.getString("huifu_id"); if (huifuId.equals(HuifuConstant.SZ_DIV_HUIFU_ID) || huifuId.equals(HuifuConstant.SC_DIV_HUIFU_ID)) { BigDecimal currentDivAmt = new BigDecimal(jsonObject.getString("div_amt")); BigDecimal adjustedDivAmt = currentDivAmt.subtract(diffAmount).max(BigDecimal.ZERO); jsonObject.put("div_amt", adjustedDivAmt.toString()); break; } } } acctSplitBunch.put("acct_infos", acctInfos); return acctSplitBunch; } /** * 判断支付方式 */ public String checkPayType(String payType) { if (StrUtil.isNotEmpty(payType)) { if (payType.contains("ALIPAY")) { return "支付宝"; } else if (payType.contains("WEIXIN")) { return "微信"; } else if (payType.equals("ECNY_CARD")) { return "数字人民币"; } else { return "微信"; } } return "微信"; } }