luodangjia
2025-01-08 7efbfadf902d77d3dc17d03b8261a65d2f214398
ruoyi-service/ruoyi-admin/src/main/java/com/ruoyi/admin/controller/FranchiseeController.java
@@ -6,6 +6,8 @@
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
@@ -15,8 +17,13 @@
import com.ruoyi.admin.service.*;
import com.ruoyi.admin.utils.MD5AndKL;
import com.ruoyi.admin.utils.WeChatUtil;
import com.ruoyi.admin.utils.util.CreateLinkStringByGet1;
import com.ruoyi.admin.utils.util.HttpRequester;
import com.ruoyi.admin.utils.util.HttpRespons;
import com.ruoyi.admin.utils.util.Md5_Sign;
import com.ruoyi.admin.vo.InfoDto;
import com.ruoyi.admin.vo.MoneyRecentQuery;
import com.ruoyi.admin.vo.PayDto;
import com.ruoyi.admin.vo.RencentBalance;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.R;
@@ -137,6 +144,16 @@
        return R.ok(balance3);
    }
    @ApiOperation(value = "详情",tags = {"师傅段2.0-统一充值扣款列表"})
    @PostMapping(value = "/change/detail")
    public R<TFranchiseeBalanceChange> detail1(@RequestParam Integer id) throws AlipayApiException {
        TFranchiseeBalanceChange byId = balanceChangeService.getById(id);
        return R.ok(byId);
    }
    @ApiOperation(value = "扣款记录及充值记录", tags = {"后台2.0-统一充值扣款列表","师傅段2.0-统一充值扣款列表"})
    @PostMapping(value = "/recent/money/list")
    public R<Page<TFranchiseeBalanceChange>> recentmoneylist(@RequestBody MoneyRecentQuery moneyRecentQuery) {
@@ -145,17 +162,22 @@
                .eq(moneyRecentQuery.getFranchName() != null && !"".equals(moneyRecentQuery.getFranchName()), TFranchiseeBalanceChange::getFranchiseeName, moneyRecentQuery.getFranchName())
                .ge(moneyRecentQuery.getDate1() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate1())
                .le(moneyRecentQuery.getDate2() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate2())
                .eq(TFranchiseeBalanceChange::getIs_pay,1)
                .orderByDesc(TFranchiseeBalanceChange::getCreateTime)
                .page(Page.of(moneyRecentQuery.getPageNum(), moneyRecentQuery.getPageSize()));
        for (TFranchiseeBalanceChange record : page.getRecords()) {
            Franchisee franchisee = franchiseeService.getById(record.getFranchiseeId());
            String siteIds = franchisee.getSiteIds();
            if (franchisee.getSiteIds()!=null) {
                String siteIds = franchisee.getSiteIds();
                List<Site> list1 = siteService.lambdaQuery().in(Site::getId, siteIds.split(",")).list();
                record.setList1(list1);
            }
            String cityCode = franchisee.getCityCode();
            List<Region> list = regionService.lambdaQuery().in(Region::getCode, cityCode.split(",")).list();
            List<Site> list1 = siteService.lambdaQuery().in(Site::getId, siteIds.split(",")).list();
            record.setList(list);
            record.setList1(list1);
            record.setFranchiseeName(franchisee.getName());
        }
        return R.ok(page);
@@ -164,38 +186,74 @@
    @ApiOperation(value = "导出", tags = {"后台2.0-统一充值扣款列表"})
    @PostMapping(value = "/recent/money/list/export")
    public R<Page<TFranchiseeBalanceChange>> export(@RequestBody MoneyRecentQuery moneyRecentQuery, HttpServletResponse response) {
        List<TFranchiseeBalanceChange> page = balanceChangeService.lambdaQuery().eq(moneyRecentQuery.getType() != null, TFranchiseeBalanceChange::getType, moneyRecentQuery.getType())
                .eq(moneyRecentQuery.getFranchId() != null, TFranchiseeBalanceChange::getFranchiseeId, moneyRecentQuery.getFranchId())
                .eq(moneyRecentQuery.getFranchName() != null && !"".equals(moneyRecentQuery.getFranchName()), TFranchiseeBalanceChange::getFranchiseeName, moneyRecentQuery.getFranchName())
                .ge(moneyRecentQuery.getDate1() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate1())
                .le(moneyRecentQuery.getDate2() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate2())
                .list();
        if (moneyRecentQuery.getType()==2) {
            List<TFranchiseeBalanceChange> page = balanceChangeService.lambdaQuery().eq(moneyRecentQuery.getType() != null, TFranchiseeBalanceChange::getType, moneyRecentQuery.getType())
                    .eq(moneyRecentQuery.getFranchId() != null, TFranchiseeBalanceChange::getFranchiseeId, moneyRecentQuery.getFranchId())
                    .eq(moneyRecentQuery.getFranchName() != null && !"".equals(moneyRecentQuery.getFranchName()), TFranchiseeBalanceChange::getFranchiseeName, moneyRecentQuery.getFranchName())
                    .ge(moneyRecentQuery.getDate1() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate1())
                    .le(moneyRecentQuery.getDate2() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate2())
                    .list();
        try {
            response.setCharacterEncoding(Constants.UTF8);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(Constants.EXCEL_ORDER_FILE_NAME, CharEncoding.UTF_8) + ".xlsx");
        } catch (UnsupportedEncodingException e) {
            return R.fail("excel导出失败!");
        }
        try {
            // excel模板封装
            ExcelWriterBuilder excelWriterBuilder = EasyExcelFactory.write(response.getOutputStream());
            InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/" + Constants.EXCEL_ORDER_FILE_NAME1 + ".xlsx");
            // 自动释放资源
            try (ExcelWriter excelWriter = excelWriterBuilder.withTemplate(stream).build()) {
                WriteSheet writeSheet = EasyExcelFactory.writerSheet().build();
                excelWriter.fill(page, writeSheet);
                excelWriter.finish();
            } catch (Exception e) {
            try {
                response.setCharacterEncoding(Constants.UTF8);
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        URLEncoder.encode(Constants.EXCEL_ORDER_FILE_NAME, CharEncoding.UTF_8) + ".xlsx");
            } catch (UnsupportedEncodingException e) {
                return R.fail("excel导出失败!");
            }
        } catch (IOException e) {
            return R.fail("excel导出失败!");
            try {
                // excel模板封装
                ExcelWriterBuilder excelWriterBuilder = EasyExcelFactory.write(response.getOutputStream());
                InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/" + Constants.EXCEL_ORDER_FILE_NAME1 + ".xlsx");
                // 自动释放资源
                try (ExcelWriter excelWriter = excelWriterBuilder.withTemplate(stream).build()) {
                    WriteSheet writeSheet = EasyExcelFactory.writerSheet().build();
                    excelWriter.fill(page, writeSheet);
                    excelWriter.finish();
                } catch (Exception e) {
                    return R.fail("excel导出失败!");
                }
            } catch (IOException e) {
                return R.fail("excel导出失败!");
            }
            return R.ok();
        }else {
            List<TFranchiseeBalanceChange> page = balanceChangeService.lambdaQuery().eq(moneyRecentQuery.getType() != null, TFranchiseeBalanceChange::getType, moneyRecentQuery.getType())
                    .eq(moneyRecentQuery.getFranchId() != null, TFranchiseeBalanceChange::getFranchiseeId, moneyRecentQuery.getFranchId())
                    .eq(moneyRecentQuery.getFranchName() != null && !"".equals(moneyRecentQuery.getFranchName()), TFranchiseeBalanceChange::getFranchiseeName, moneyRecentQuery.getFranchName())
                    .ge(moneyRecentQuery.getDate1() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate1())
                    .le(moneyRecentQuery.getDate2() != null, TFranchiseeBalanceChange::getCreateTime, moneyRecentQuery.getDate2())
                    .list();
            try {
                response.setCharacterEncoding(Constants.UTF8);
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        URLEncoder.encode(Constants.EXCEL_ORDER_FILE_NAME, CharEncoding.UTF_8) + ".xlsx");
            } catch (UnsupportedEncodingException e) {
                return R.fail("excel导出失败!");
            }
            try {
                // excel模板封装
                ExcelWriterBuilder excelWriterBuilder = EasyExcelFactory.write(response.getOutputStream());
                InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/" + Constants.EXCEL_ORDER_FILE_NAME2 + ".xlsx");
                // 自动释放资源
                try (ExcelWriter excelWriter = excelWriterBuilder.withTemplate(stream).build()) {
                    WriteSheet writeSheet = EasyExcelFactory.writerSheet().build();
                    excelWriter.fill(page, writeSheet);
                    excelWriter.finish();
                } catch (Exception e) {
                    return R.fail("excel导出失败!");
                }
            } catch (IOException e) {
                return R.fail("excel导出失败!");
            }
            return R.ok();
        }
        return R.ok();
    }
@@ -204,6 +262,12 @@
    public R<Page<TFranchiseeBalanceChange>> consume(@RequestBody TFranchiseeBalanceChange franchiseeBalanceChange) {
        Franchisee byId = franchiseeService.getById(franchiseeBalanceChange.getFranchiseeId());
        franchiseeBalanceChange.setFranchiseeName(byId.getName());
        Region byId1 = regionService.getById(franchiseeBalanceChange.getRegionId());
        franchiseeBalanceChange.setRegionName(byId1.getName());
        Site byId2 = siteService.getById(franchiseeBalanceChange.getSiteId());
        franchiseeBalanceChange.setSiteName(byId2.getSiteName());
        franchiseeBalanceChange.setIs_pay(1);
        balanceChangeService.save(franchiseeBalanceChange);
        byId.setBalance(byId.getBalance().subtract(franchiseeBalanceChange.getAmount()));
        franchiseeService.updateById(byId);
@@ -215,7 +279,7 @@
    @ApiOperation(value = "js支付", tags = {"2.0-支付"})
    @GetMapping(value = "/js/wxPay")
    public R jsPay(@RequestParam String openId,@RequestParam BigDecimal money,@RequestParam Integer userId) {
    public R jsPay(@RequestParam String openId,@RequestParam BigDecimal money,@RequestParam Integer userId) throws IOException {
        SysUser byId1 = sysUserService.getById(userId);
        this.privateKey = PemUtil.loadPrivateKey(getPrivateKeyStream());
        this.privateKeySigner = new PrivateKeySigner(weChatConfig.merchantSerialNumber, privateKey);
@@ -225,37 +289,66 @@
        Franchisee byId = franchiseeService.getById(byId1.getFranchiseeId());
        PrepayRequest prepayRequest = new PrepayRequest();
        prepayRequest.setAppid(weChatConfig.appId);
        prepayRequest.setMchid(weChatConfig.merchantId);
        prepayRequest.setDescription("加盟商充值");
        prepayRequest.setOutTradeNo(code);
        prepayRequest.setNotifyUrl("http://www.zhipingwang.com.cn:9090/admin/franchisee/callBack");
        Amount amount = new Amount();
        amount.setTotal(i);
        prepayRequest.setAmount(amount);
        Payer payer = new Payer();
        payer.setOpenid(openId);
        prepayRequest.setPayer(payer);
        PrepayResponse prepay = jsapiService.prepay(prepayRequest);
        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        String packageStr = "prepay_id=" + prepay.getPrepayId();
        //
        String key = "ad273ceb5e1b49e68d5c565d28d1d305";/** md5密钥商户后台-商户中心-商户设置-密钥管理获取 必填!*/
        Map<String, String> map = new HashMap<String, String>();
        map.put("p0_Version", "2.5");/** 版本号 */
        map.put("p1_MerchantNo", "888122400007793");/** 商户编号 */
        map.put("p2_OrderNo", code); /**商户订单号*/
        map.put("p3_Amount", String.valueOf(money));/**订单金额*/
        map.put("p4_Cur", "1"); /**交易币种 */
        map.put("q5_OpenId", openId);
        map.put("p5_ProductName", "加盟商充值"); /** 商品名称 */
        map.put("p9_NotifyUrl", "http://www.zhipingwang.com.cn:9100/admin/franchisee/callBack"); /** 服务器异步通知地址 */
        map.put("q1_FrpCode", "WEIXIN_APP3"); /** 交易类型*/
        map.put("q7_AppId", "wx1a4a7760be53a835"); /** 交易类型*/
        map.put("qa_TradeMerchantNo", "777165000859101"); /** 777开头的报备商户号   必填!*/
        String prepay_id = prepay.getPrepayId();
        //重新进行签名后返回给前端
        String Strmap = CreateLinkStringByGet1.createLinkStringByGet(map);
        // 签名
        String sign = "";
        sign = Md5_Sign.SignByMD5(Strmap, key);
        map.put("hmac", sign);/** 签名数据 */
        System.out.println("发送:" + JSON.toJSONString(map).toString());
        // post请求参数内容
        HttpRequester hr = new HttpRequester();
        HttpRespons HP = hr.sendPost("https://www.joinpay.com/trade/uniPayApi.action", map);
        System.out.println("接收返回参数:" + HP.getContent());
        JSONObject jsonObject = JSONObject.parseObject(HP.getContent());
        JSONObject rcResult = JSONObject.parseObject(jsonObject.getString("rc_Result"));
        Map<String, Object> map2 = new HashMap<>();
        map2.put("appid", weChatConfig.getAppId());
        map2.put("noncestr", code);
        map2.put("package", "Sign=WXPay");
        map2.put("partnerid", weChatConfig.getMerchantId());
        map2.put("prepayid", prepay_id);
        map2.put("timestamp", timeStamp);
//        String s1 = this.weixinSignature(map2);
        String signStr = Stream.of(weChatConfig.getAppId(), timeStamp, code, packageStr).collect(Collectors.joining("\n", "", "\n"));
        String packageSign = privateKeySigner.sign(signStr.getBytes(StandardCharsets.UTF_8)).getSign();
        map2.put("sign", packageSign);
        System.err.println(map2);
        map2.put("rcResult", rcResult);
//        map2.put("timestamp", rcResult.get("timeStamp"));
//        map2.put("prepayid", rcResult.get("package"));
//        map2.put("sign", rcResult.get("paySign"));
        //
//        PrepayRequest prepayRequest = new PrepayRequest();
//        prepayRequest.setAppid(weChatConfig.appId);
//        prepayRequest.setMchid(weChatConfig.merchantId);
//        prepayRequest.setDescription("加盟商充值");
//        prepayRequest.setOutTradeNo(code);
//        prepayRequest.setNotifyUrl("http://www.zhipingwang.com.cn:9090/admin/franchisee/callBack");
//        Amount amount = new Amount();
//        amount.setTotal(i);
//        prepayRequest.setAmount(amount);
//        Payer payer = new Payer();
//        payer.setOpenid(openId);
//        prepayRequest.setPayer(payer);
//        PrepayResponse prepay = jsapiService.prepay(prepayRequest);
//        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
//        String packageStr = "prepay_id=" + prepay.getPrepayId();
//
//        String prepay_id = prepay.getPrepayId();
//        //重新进行签名后返回给前端
////        String s1 = this.weixinSignature(map2);
//        String signStr = Stream.of(weChatConfig.getAppId(), timeStamp, code, packageStr).collect(Collectors.joining("\n", "", "\n"));
//        String packageSign = privateKeySigner.sign(signStr.getBytes(StandardCharsets.UTF_8)).getSign();
//
//        System.err.println(map2);
        TFranchiseeBalanceChange tFranchiseeBalanceChange = new TFranchiseeBalanceChange();
@@ -323,11 +416,18 @@
                tFranchiseeBalanceChange.setAmount(money);
                tFranchiseeBalanceChange.setIs_pay(0);
                tFranchiseeBalanceChange.setFranchiseeName(byId.getName());
                tFranchiseeBalanceChange.setFranchiseeId(String.valueOf(userid));
                tFranchiseeBalanceChange.setFranchiseeId(String.valueOf(byId.getId()));
                tFranchiseeBalanceChange.setType(2);
                tFranchiseeBalanceChange.setCode(code);
                balanceChangeService.save(tFranchiseeBalanceChange);
                return R.ok(prepay.getCodeUrl());
                PayDto payDto = new PayDto();
                payDto.setOrderId(tFranchiseeBalanceChange.getId());
                payDto.setQrCode(prepay.getCodeUrl());
                return R.ok(payDto);
            } catch (HttpException e) { // 发送HTTP请求失败
//                log.error("发送HTTP请求失败: {}", e.getHttpRequest());
            } catch (ServiceException e) { // 服务返回状态小于200或大于等于300,例如500
@@ -340,19 +440,32 @@
            return null;
    }
    @ApiOperation(value = "轮询获取支付状态",tags = {"后台2.0-加盟商列表余额"})
    @PostMapping(value = "/code/check")
    public R buy(@RequestParam Integer orderId) throws AlipayApiException {
        TFranchiseeBalanceChange byId = balanceChangeService.getById(orderId);
        if (byId.getIs_pay()==1){
            return R.ok(true);
        }else {
            return R.ok(false);
        }
    }
    @Resource
    private NotificationParser notificationParser;
    @ApiOperation(value = "支付回调",tags = {"微信支付回调"})
    @RequestMapping (value = "/callBack")
    @Transactional
    public R payNotify(HttpServletRequest request) throws Exception{
    public R payNotify(HttpServletRequest request,String r2_OrderNo) throws Exception{
        System.err.println("======回调开始");
        Transaction transaction;
        transaction = notificationParser.parse(WeChatUtil.handleNodifyRequestParam(request), Transaction.class);
        if (transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
        System.err.println("======回调开始"+r2_OrderNo);
//        Transaction transaction;
//        transaction = notificationParser.parse(WeChatUtil.handleNodifyRequestParam(request), Transaction.class);
//        if (transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
            //将记录变为已支付
            TFranchiseeBalanceChange one = balanceChangeService.lambdaQuery().eq(TFranchiseeBalanceChange::getCode, transaction.getOutTradeNo()).one();
            TFranchiseeBalanceChange one = balanceChangeService.lambdaQuery().eq(TFranchiseeBalanceChange::getCode,r2_OrderNo).one();
            if (one.getIs_pay()==0) {
                //将加盟商的余额增加
                Franchisee byId = franchiseeService.getById(one.getFranchiseeId());
@@ -361,7 +474,7 @@
                one.setIs_pay(1);
                balanceChangeService.updateById(one);
            }
//            }
        }
        return R.ok(null,"SUCCESS");