18582019636
2024-06-25 ca497f8389174bb81e91f840cab70c9579bcdd29
ruoyi-service/ruoyi-user/src/main/java/com/ruoyi/user/service/impl/WithdrawServiceImpl.java
@@ -1,10 +1,14 @@
package com.ruoyi.user.service.impl;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.admin.api.entity.WithdrawalSetting;
import com.ruoyi.admin.api.feignClient.AdminClient;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.WechatConstants;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.SnowflakeIdWorker;
import com.ruoyi.user.entity.Order;
import com.ruoyi.user.entity.RecoveryServe;
import com.ruoyi.user.entity.User;
@@ -17,27 +21,30 @@
import com.ruoyi.user.vo.WithdrawListVO;
import com.ruoyi.user.vo.WithdrawMoneyVO;
import com.ruoyi.user.vo.WithdrawOrderVO;
import com.ruoyi.user.vx.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
/**
 * <p>
 * 用户提现申请记录表 服务实现类
 * </p>
 *
 * @author hjl
 * @since 2024-06-07
 */
@Service
public class WithdrawServiceImpl extends ServiceImpl<WithdrawMapper, Withdraw> implements WithdrawService {
    /**
     * 雪花算法类
     */
    private static final SnowflakeIdWorker SNOW_FLAKE_ID_WORKER = new SnowflakeIdWorker(5, 5);
    @Resource
    private OrderService orderService;
@@ -47,24 +54,60 @@
    private UserService userService;
    @Resource
    private AdminClient adminClient;
    /**
     * 小程序id
     */
    @Value("wx.appid")
    private String appId;
    /**
     * 转账名称
     */
    @Value("wx.batchName")
    private String batchName;
    /**
     * 商户号
     */
    @Value("wx.mchId")
    private String mchId;
    /**
     * 支付证书序列号
     */
    @Value("wx.wechatPayserialNo")
    private String wechatPayserialNo;
    /**
     * 转账备注
     */
    @Value("wx.transferRemark")
    private String transferRemark;
    @Override
    public WithdrawListVO withdrawList(Long userid) {
    public WithdrawListVO withdrawList(Integer userid) {
        WithdrawListVO withdrawList = new WithdrawListVO();
        List<Order> orderList = orderService.lambdaQuery().eq(Order::getUserId, userid)
                .eq(Order::getState, 3).eq(Order::getIsDelete, 0).list();
        // 总金额
        BigDecimal totalMoney = orderList.stream().map(Order::getOrderMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalMoney = BigDecimal.ZERO;
        // 未提现金额
        BigDecimal undelivered = orderList.stream().filter(data -> Constants.ZERO.equals(data.getIsWithdrawal()))
                .map(Order::getOrderMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal undelivered = BigDecimal.ZERO;
        // 已提现金额
        BigDecimal withdrawn = orderList.stream().filter(data -> Constants.ONE.equals(data.getIsWithdrawal()))
                .map(Order::getOrderMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal withdrawn = BigDecimal.ZERO;
        if (!orderList.isEmpty()) {
            // 总金额
            totalMoney = orderList.stream().map(Order::getOrderMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            // 未提现金额
            undelivered = orderList.stream().filter(data -> Constants.ZERO.equals(data.getIsWithdrawal()))
                    .map(Order::getOrderMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            // 已提现金额
            withdrawn = orderList.stream().filter(data -> Constants.ONE.equals(data.getIsWithdrawal()))
                    .map(Order::getOrderMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        }
        withdrawList.setMoneyCount(new WithdrawMoneyVO(totalMoney, undelivered, withdrawn));
        // 回收服务列表
        List<RecoveryServe> serveList = recoveryServeService.lambdaQuery().eq(RecoveryServe::getIsDelete, 0)
                .in(RecoveryServe::getId, orderList.stream().map(Order::getServeId).collect(Collectors.toList())).list();
        List<Integer> serveIds = orderList.stream().map(Order::getServeId).collect(Collectors.toList());
        LambdaQueryChainWrapper<RecoveryServe> wrapper = recoveryServeService.lambdaQuery()
                .eq(RecoveryServe::getIsDelete, 0);
        wrapper = serveIds.isEmpty() ? wrapper : wrapper.in(RecoveryServe::getId, serveIds);
        List<RecoveryServe> serveList = wrapper.list();
        Map<Integer, RecoveryServe> serveMap = serveList.stream().collect(Collectors.toMap(RecoveryServe::getId, serve -> serve));
        // 订单列表
        List<WithdrawOrderVO> list = new ArrayList<>();
@@ -86,7 +129,8 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean confirmWithdraw(Integer orderId, Long userid) {
    public Boolean confirmWithdraw(Integer orderId, Integer userid) {
        User user = userService.lambdaQuery().eq(User::getId, userid).eq(User::getIsDelete, 0).one();
        Order order = orderService.lambdaQuery().eq(Order::getId, orderId).eq(Order::getIsDelete, 0).one();
        if (null == order) {
            throw new GlobalException("订单信息异常!");
@@ -100,13 +144,21 @@
        } else if (stateList.contains(Constants.ONE)) {
            throw new GlobalException("当前订单已提现通过!");
        }
        User user = userService.lambdaQuery().eq(User::getId, userid).eq(User::getIsDelete, 0).one();
        // 系统审核设置
        WithdrawalSetting setting = adminClient.withdrawProcess().getData();
        Withdraw withdraw = new Withdraw();
        // 未开启全局 提现审核,则用户提现不需要后台审核
        if (Constants.ZERO.equals(setting.getEnableProcess())) {
            // 已通过
            withdraw.setState(Constants.ONE);
            // 商家微信打款至微信零钱
            boolean update = weChatPay(order.getOrderMoney(), user.getOpenId());
            if (!update) {
                throw new GlobalException("交易提现失败,请检查是否绑定微信!");
            }
        } else {
            // 待审核
            withdraw.setState(Constants.ZERO);
            // todo 商家微信打款至微信零钱
        }
        withdraw.setUserId(user.getId());
        withdraw.setUserPhone(user.getPhone());
@@ -115,4 +167,66 @@
        withdraw.setOrderId(orderId);
        return this.save(withdraw);
    }
    private boolean weChatPay(BigDecimal orderMoney, String openId) {
        Map<String, Object> postMap = new HashMap<>(8);
        // 小程序 id
        postMap.put(WechatConstants.APP_ID, appId);
        postMap.put(WechatConstants.OUT_BATCH_NO, String.valueOf(UUID.randomUUID()).replaceAll("-", ""));
        // 该笔批量转账的名称
        postMap.put(WechatConstants.BATCH_NAME, batchName);
        // 转账说明,UTF8编码,最多允许32个字符
        postMap.put(WechatConstants.BATCH_REMARK, batchName);
        // 转账金额单位为“分”。 总金额
        postMap.put(WechatConstants.TOTAL_AMOUNT, orderMoney.multiply(new BigDecimal(Constants.ONE_HUNDRED)));
        // 转账总笔数
        postMap.put(WechatConstants.TOTAL_NUM, Constants.ONE);
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> subMap = new HashMap<>(4);
        // 商家明细单号 该商家下唯一
        // subMap.put("out_detail_no", RandomUtil.randomString(32))
        subMap.put(WechatConstants.OUT_DETAIL_NO, SNOW_FLAKE_ID_WORKER.nextId());
        // 转账金额
        subMap.put(WechatConstants.TRANSFER_AMOUNT, orderMoney);
        // 转账备注
        subMap.put(WechatConstants.TRANSFER_REMARK, transferRemark);
        // 用户在直连商户应用下的用户标示
        subMap.put(WechatConstants.OPEN_ID, openId);
        // 大金额需要传入真实姓名
        /*subMap.put("user_name",
        RsaCryptoUtil.encryptOAEP(userName,WechatPayV3Util.getSaveCertificates(privatekeypath)))*/
        list.add(subMap);
        postMap.put(WechatConstants.TRANSFER_DETAIL_LIST, list);
        // 使用类加载器获取资源 URL
        ClassPathResource classPathResource = new ClassPathResource("vx/apiclient_key.pem");
        /*// 获取 resources 目录下的文件路径,假设文件路径为 "resources/data/example.txt"
        String filePath = "resources/data/vx/apiclient_key.pem";
        File file = new File(filePath);
        // 输出文件的绝对路径
        String absolutePath = file.getAbsolutePath();*/
        String result = HttpUtil.postTransBatRequest(
                WechatConstants.WE_CHAT_URL_PRE,
                JSONObject.toJSONString(postMap),
                // 支付证书序列号
                wechatPayserialNo,
                // 商户号
                mchId,
                classPathResource.getPath(), WechatConstants.WE_CHAT_URL_SUF);
        JSONObject jsonObject = JSONObject.parseObject(result);
        /*
         * 成功示例
         * {
         *   "out_batch_no": "plfk2020042013",
         *   "batch_id": "1030000071100999991182020050700019480001",
         *   "create_time": "2015-05-20T13:29:35.120+08:00"
         * }
         */
        if (null == jsonObject || null != jsonObject.get(WechatConstants.CREATE_TIME)) {
            //转账成功
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }
}