package com.xzx.gc.pay.service; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.date.DateUtil; import cn.hutool.core.exceptions.ExceptionUtil; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpUtil; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.CertAlipayRequest; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.domain.AlipayOpenOperationOpenbizmockBizQueryModel; import com.alipay.api.domain.AlipayTradeAppPayModel; import com.alipay.api.internal.util.AlipaySignature; import com.alipay.api.request.AlipayOpenOperationOpenbizmockBizQueryRequest; import com.alipay.api.request.AlipayTradeAppPayRequest; import com.alipay.api.response.AlipayOpenOperationOpenbizmockBizQueryResponse; import com.alipay.api.response.AlipayTradeAppPayResponse; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.xzx.gc.common.constant.*; import com.xzx.gc.common.dto.CommonDto; import com.xzx.gc.common.dto.SimplePage; import com.xzx.gc.common.dto.log.PayInfoLog; import com.xzx.gc.common.exception.BusinessException; import com.xzx.gc.common.exception.RestException; import com.xzx.gc.common.exception.wx.WxPayNotifyResponseException; import com.xzx.gc.common.utils.*; import com.xzx.gc.entity.*; import com.xzx.gc.model.JsonResult; import com.xzx.gc.model.admin.*; import com.xzx.gc.model.pay.*; import com.xzx.gc.model.user.AccountVo; import com.xzx.gc.pay.mapper.*; import com.xzx.gc.util.DoubleUtil; import com.xzx.gc.util.SessionUtil; import com.xzx.gc.util.pay.util.WechatpayUtil; import com.xzx.gc.util.pay.util.entity.ResultEntity; import com.xzx.gc.util.pay.util.entity.TransfersDtoAdmin; import io.swagger.annotations.ApiModelProperty; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import tk.mybatis.mapper.entity.Example; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; @Service @Transactional @Slf4j public class PayService { @Autowired private PayInfoMapper payInfoMapper; @Autowired private AccountLogMapper accountLogMapper; @Autowired private SysMessageMapper sysMessageMapper; @Autowired private IdUtils idUtils; @Autowired private HttpServletRequest request; @Autowired private OtherUserMapper otherUserMapper; @Autowired private UserMapper userMapper; @Autowired private UserService userService; @Autowired private PayRequestMapper payRequestMapper; @Autowired private PlatformAccountInfoMapper platformAccountInfoMapper; @Autowired private RedisUtil redisUtil; @Autowired private BusinessUtil businessUtil; @Autowired private AccountMapper accountMapper; @Autowired private PayInfoLogService payInfoLogService; @Autowired private AccountService accountService; @Autowired private OtherUserService otherUserService; @Autowired private PlatformAccountLogService platformAccountLogService; @Autowired private PlatformAccountInfoService platformAccountInfoService; @Autowired private ConfigService configService; @Autowired private ConfigMapper configMapper; @Autowired private AccountBindService accountBindService; @Autowired private SessionUtil sessionUtil; @Autowired private UserRoleMapper userRoleMapper; @Autowired private PlatformAccountLogMapper platformAccountLogMapper; @Autowired private AccountScoreLogMapper accountScoreLogMapper; @Autowired private CityPartnerService cityPartnerService; @Value("${anroidAppId}") private String anroidAppId; @Value("${wx.app.url}") String TRANS_URL; @Value("${wx.app.key}") String APP_KEY; @Value("${wx.path}") String CERT_PATH; @Value("${wx.pay.appid}") String APP_ID; @Value("${wx.mchid}") String MCH_ID; @Value("${wx.name}") String MCH_NAME; @Value("${wx.create.ip}") String CREATE_IP; @Autowired private PartnerAccountLogService partnerAccountLogService; @Autowired private PartnerAccountService partnerAccountService; private static CertAlipayRequest getClientParams() { CertAlipayRequest certParams = new CertAlipayRequest(); //https://blog.csdn.net/sinat_32575213/article/details/79651110 certParams.setServerUrl("https://openapi.alipaydev.com/gateway.do"); //请更换为您的AppId certParams.setAppId("2021000119674887"); //请更换为您的PKCS8格式的应用私钥 certParams.setPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCDXABjX661uzuAbwEOa2YV9S3Xm409k27LRkJsBHRyhHuq4+MK5OnFMpNmYl+e2rIvQ9y+1YI65NovPV4XTAt6tr2wIE2uD8dLJELHxwZyUpLSgdLW4Ds6qoea8qoZk3563baO2i0EnuSk9evBpzzJtO0+QDiNGASrE+7mPL9ygCv8V4i185h/LpinKTymnIhyTtEmjEAXITPM/e2PvWTE+RCz07kkXIEquVtcj/5geRPqXaogsbaMgwy3oKiZLRw8Axo8OhO9zDTnfFeO7pwPvWTAMFYKZu7jbOTMa4vT0DQYqDIDmNzCbTCfkfE3VQrmI4KTacprTz46fNC5UXq9AgMBAAECggEAdtaS21RC4NJkgErsb7kmABNxx69IVj69a1VC3iohl0DYCMBmNQLnoqmgxG2XCEXeEfiZCmRqjxFfeoFQUE9Ry1Drxx1SaXiI2igR6l7aLC8b+SnOLutpaifAyqNi1ASl1k4izJYBSD7fp4V8JhRAYFM4lqrO/oaOIp/D77NhmBmfV5XIzZOzeLkHaLN8pTqUdvTF917MkmUsY1iysol+EmU/pZePkcwIcHoQcJ9yWam8bRErXAqoKSvMcXetpsaIN6Fgn/sMkk/coJW2rSWNxUQVn+RTvKwT9UGehah/jwqzNwg/FhiKu28PDLccQzbK/VkZ2sTla3w/AlKnmn91QQKBgQDcHdwyjI25tRMayjneZc5VOKA65Du1RubiXdJU+14288qDNHmR4CMxIe49gHPknWwkiLNa0VnhnINJSsEXtvpcPY1ICL9TnHGBCYFpA+4Wc6gYa6CqUeg41O5ki0b+Ar3xp3hVOqeBnHdyKwv1/UvHWeFYPXwqg5MFu3iA1mLnNQKBgQCYxgeecZshL6iwww8kHaCxNf92l4s89YIpiTFsv70SAt+h7OxN9wzJcF2dQbUIEB0Q26KWeomzd4rZRr0CqcpMj/HRQzk0W8fGGEKGAZwjf33aa1VSehY8ZMYBCgJcVk7CRl/XQ+51ppqr80HwGBgSqV5P3b6T1vmiZlRP1GTOaQKBgQCiAwRo3FUQY/u80y3GyK4WwcgFsKlV4urboGzIif+teMEM01nLieq9JhlBgUNL+KZ5OXixlreOPHHRR0laWB5sOA2+AFo6g0Jz1HhAwFjEg7osx0MJOaIv+mHA9VZ6bbA6pqYGLVbPKkgsawyxsQ7OmxQmq5KxhAh5xqOKSMGhJQKBgGFpg9onnj7e4LU06yagLaJRR/8aShIoiUJq1DT/XVNquaXKKDLeYCzhlQ98oi3t+FqTcWx53eutQb+hN0vHb9K5xfsk3gjgrNVHCsPfquuHk3v+DH12k08XApoPA8pUzgtaTCo6ioZCIUWa6mRpOJBNpnFOdwJVhP9kOEZeq5hhAoGAMKztAVJCzjiJr7Htd8pUc/hjLXUznUfbNfigNtNXAKL7QWHmrz5NIDuFKY2gn08ahAoZG/P34N2DrrhEOrBlT249FEFEo7HH1EvFbEN1QosCZFhXTWkcgSxcmj9TRu4uLVppW+6hMxVbR2ZY4MGmCQPJEu91JnQzYqyZAt6SGYw="); //请更换为您使用的字符集编码,推荐采用utf-8 certParams.setCharset("utf-8"); certParams.setFormat("json"); certParams.setSignType("RSA2"); //请更换为您的应用公钥证书文件路径 certParams.setCertPath("E:/card/appCertPublicKey_2021000119674887.crt"); //请更换您的支付宝公钥证书文件路径 certParams.setAlipayPublicCertPath("E:/card/alipayCertPublicKey_RSA2.crt"); //更换为支付宝根证书文件路径 certParams.setRootCertPath("E:/card/alipayRootCert.crt"); return certParams; } private AlipayClient alipayClient; @PostConstruct public void init() throws AlipayApiException { // 1. 创建AlipayClient实例 if (SpringUtil.isDev()) { alipayClient = new DefaultAlipayClient(getClientParams()); } } public int addPayInfo(PayInfoModel model) { CoreUser user = sessionUtil.getCurrentUser(); model.setAccountId(""); model.setStatus("1"); model.setPayType("1"); model.setCreateUserId(user.getId() + ""); model.setCreateTime(DateUtil.now()); return payInfoMapper.addPayInfo(model); } public CommonDto PayInfoAdd(PayInfoReq payInfoReq) { String lockId = ""; if (StrUtil.isNotBlank(payInfoReq.getCreateUserId())) { lockId = payInfoReq.getCreateUserId(); } else if (StrUtil.isNotBlank(payInfoReq.getUserId())) { lockId = payInfoReq.getUserId(); } CommonDto commonDto = new CommonDto(); if (StrUtil.isNotBlank(lockId) && redisUtil.setnx(Constants.REDIS_PAY_KEY + "add:" + lockId, lockId)) { try { String payOrderId = idUtils.generate("ZF", 0); payInfoReq.setPayOrderId(payOrderId); String now = DateUtil.now(); payInfoReq.setCreateTime(now); //充值或者支入则不需要写入支付申请表 if (PayEnum.提现.getValue().equals(payInfoReq.getPayType())) { String configValue = configService.findByCode("WITHDRAW_MAX_MONEY").getConfigValue(); if (Convert.toBigDecimal(payInfoReq.getMoney()).compareTo(Convert.toBigDecimal(configValue)) > 0) { throw new RestException(-1, "单笔提现金额不能超过" + configValue); } //查询账号是否被冻结 AccountInfo byUserIdWithStatus = accountService.findByUserId(payInfoReq.getCreateUserId()); if (byUserIdWithStatus == null) { throw new RestException(-1, "账户已被禁用"); } List withdrawList = payInfoMapper.queryWithdrawInfo(payInfoReq); if (withdrawList.size() >= 1) { throw new RestException(-1, "一天只能提现一次"); } List accountList = payInfoMapper.queryMyMoney(payInfoReq); AccountVo accountVo = accountList.get(0); //提现金额 BigDecimal bigDecimal = NumberUtil.toBigDecimal(payInfoReq.getMoney()); //余额 BigDecimal bigDecimal1 = NumberUtil.toBigDecimal(accountVo.getMoney()); //判断账户余额是否足够,返回-1表示余额不够 if (NumberUtil.isGreater(bigDecimal, bigDecimal1)) { throw new RestException(-1, "用户余额不足"); } //查询账户信息 安卓回收员提现转成普通用户 if (1 == Convert.toInt(payInfoReq.getChangeUserFlag(), 0)) { String createUserId = payInfoReq.getCreateUserId(); OtherUserInfo otherUserInfo = otherUserMapper.selectByPrimaryKey(createUserId); String mobilePhone = otherUserInfo.getMobilePhone(); UserInfo userInfo1 = userService.findByMobile(mobilePhone); if (userInfo1 != null) { payInfoReq.setOpenId(userInfo1.getOpenId()); } } payInfoReq.setStatus(PayEnum.待审核.getValue()); payInfoReq.setAccountId(accountVo.getAccountId()); payInfoMapper.payRequestInfoAdd(payInfoReq); PayInfoLog payInfoLog = new PayInfoLog(); BeanUtil.copyProperties(payInfoReq, payInfoLog); payInfoLog.setAccount(accountVo.getAccountName()); payInfoLog.setAccountClass(PayEnum.微信.getValue()); payInfoLog.setPayType(PayEnum.提现交易.getValue()); payInfoLogService.add(payInfoLog); commonDto.setId(payOrderId); if (PayEnum.银行卡.getValue().equals(Convert.toStr(payInfoReq.getAccountType(), ""))) { commonDto.setExtra(PayEnum.手动审核.getValue()); } else { ConfigInfo configInfo = new ConfigInfo(); configInfo.setConfigTypeCode("APPROVAL_TYPE"); ConfigInfo configInfo1 = configMapper.selectOne(configInfo); if (PayEnum.自动审核.getValue().equals(configInfo1.getConfigValue())) { log.debug("调用后台的提现方法"); TransfersDtoAdmin transfersDtoAdmin = new TransfersDtoAdmin(); transfersDtoAdmin.setPayOrderId(payOrderId); if (businessUtil.isApp(request.getHeader("clientType"))) { transfersDtoAdmin.setOtherUserId(payInfoReq.getCreateUserId()); } else { transfersDtoAdmin.setUserId(payInfoReq.getCreateUserId()); transfersDtoAdmin.setOtherUserId(""); } wxPay(transfersDtoAdmin); //防止前端在调用自动审核接口 commonDto.setExtra(PayEnum.自动审核.getValue()); } else { //防止前端在调用自动审核接口 commonDto.setExtra(PayEnum.手动审核.getValue()); } } } } catch (RestException e) { ExceptionUtils.err(e.getMsg(), e); } catch (Exception e) { ExceptionUtils.err("提现失败", e); } finally { redisUtil.del(Constants.REDIS_PAY_KEY + "add:" + lockId); } } return commonDto; } public List queryPayInfo(PayInfoReq payInfoReq) { List payInfoList = payInfoMapper.queryPayInfo(payInfoReq); return payInfoList; } public List queryPayRequestInfo(PayInfoReq payInfoReq) { List payInfoList = payInfoMapper.queryPayRequestInfo(payInfoReq); return payInfoList; } public void addPay(PayInfo payInfo) { payInfo.setCreateTime(DateUtil.now()); payInfoMapper.insertSelective(payInfo); } public int webChatRechargeCallback(Map map) { String userId = (String) map.get("userId"); String money = (String) map.get("money"); String fee = (String) map.get("fee"); String payOrderId = (String) map.get("payOrderId"); //更改状态 int returnvalue = payInfoMapper.updatePayInfoStatus(map); AccountInfo accountInfo1 = accountService.findByUserId(userId); if (accountInfo1 == null) { throw new WxPayNotifyResponseException("账户不存在:" + userId); } OtherUserInfo otherUserInfo = otherUserService.findByIdByNotDel(userId); boolean flag = otherUserInfo != null && (CommonEnum.回收员.getValue().equals(otherUserInfo.getUserType()) || CommonEnum.入库员.getValue().equals(otherUserInfo.getUserType()) || CommonEnum.打包站运营员.getValue().equals(otherUserInfo.getUserType()) || CommonEnum.打包员.getValue().equals(otherUserInfo.getUserType())) && StrUtil.isNotBlank(accountInfo1.getFixedLimit()) && Convert.toBigDecimal(accountInfo1.getFixedLimit(), Constants.MONEY_INIT).compareTo(BigDecimal.ZERO) > 0; if (flag) { //回收员充值 和额度相关 AccountVo accountVo = new AccountVo(); BeanUtil.copyProperties(accountInfo1, accountVo); accountService.addAccount(accountVo, CommonEnum.充值操作.getValue(), payOrderId, money); } else { String now = DateUtil.now(); AccountLog accountLog = new AccountLog(); accountLog.setCreateTime(now); accountLog.setAccountId(accountInfo1.getAccountId()); accountLog.setOldMoney(accountInfo1.getMoney()); accountLog.setNewMoney(Convert.toStr(NumberUtil.add(Convert.toBigDecimal(accountInfo1.getMoney()), Convert.toBigDecimal(money)))); accountLog.setCreateUserId(userId); accountLog.setChannelType(Convert.toShort(CommonEnum.充值操作.getValue())); accountLog.setOrderId(payOrderId); accountLogMapper.insertSelective(accountLog); map.put("money", Convert.toBigDecimal(money)); payInfoMapper.updateMyMoneyByOrder(map); } //添加平台日志 String oldMoney = Constants.MONEY_INIT.toString(); String oldHbb = Constants.MONEY_INIT.toString(); PlatformAccountInfo moneyKey = platformAccountInfoService.findByKey(Constants.PLAT_MONEY_KEY); if (moneyKey != null) { oldMoney = moneyKey.getFieldValue(); } PlatformAccountInfo hbbKey = platformAccountInfoService.findByKey(Constants.PLAT_HBB_KEY); if (hbbKey != null) { oldHbb = hbbKey.getFieldValue(); } //算上服务费的金额 String MoneyAndFee = money; // if(StrUtil.isNotBlank(fee)){ // MoneyAndFee=NumberUtil.add(Convert.toBigDecimal(money),Convert.toBigDecimal(fee)).toString(); // } PlatformAccountLog platformAccountLog = new PlatformAccountLog(); platformAccountLog.setCreateUserId(userId); platformAccountLog.setType(Convert.toInt(CommonEnum.平台充值.getValue())); platformAccountLog.setOldMoney(Convert.toBigDecimal(oldMoney)); platformAccountLog.setMoney(Convert.toBigDecimal(MoneyAndFee)); platformAccountLog.setNewMoney(NumberUtil.add(platformAccountLog.getOldMoney(), platformAccountLog.getMoney())); platformAccountLog.setOldHbb(Convert.toBigDecimal(oldHbb)); platformAccountLog.setHbb(Convert.toBigDecimal("-" + money)); platformAccountLog.setNewHbb(NumberUtil.add(platformAccountLog.getOldHbb(), platformAccountLog.getHbb())); platformAccountLog.setFlowNo(payOrderId); platformAccountLogService.add(platformAccountLog); //更新平台账户 platformAccountInfoService.updateMoney(MoneyAndFee); platformAccountInfoService.updateHbb("-" + money); //充值消息录入 SysMessage sysMessage = new SysMessage(); sysMessage.setCreateTime(DateUtils.getCurDateTime()); sysMessage.setCreateUserId(userId); sysMessage.setFlag("2"); sysMessage.setMessage("您已经充值" + money + "元"); sysMessage.setMessageSubTypeName("充值"); sysMessage.setMessageType("2"); sysMessage.setUserId(userId); sysMessageMapper.insert(sysMessage); return returnvalue; } // public int audit(CommonDto commonDto) { // String payOrderId = commonDto.getId(); // boolean lock = false; // try { // if (redisUtil.setnx(Constants.REDIS_PAY_KEY + "audit:" + payOrderId, payOrderId)) { // lock = true; // PayRequestInfo payInfo = payRequestMapper.selectByPrimaryKey(payOrderId); // if (payInfo != null) { // //调用提现自动审核接口 // log.info("调用提现自动审核接口"); // Map map = new HashMap<>(); // map.put("payOrderId", commonDto.getId()); // if (businessUtil.isApp(request.getHeader("clientType"))) { // map.put("otherUserId", request.getHeader("userId")); // } else { // map.put("userId", payInfo.getCreateUserId()); // map.put("otherUserId", ""); // } // // String post = null; // boolean error = false; // log.info("提现审核请求参数:{}", JSONUtil.toJsonPrettyStr(map)); // try { // post = HttpUtil.post(adminUrl + "gc-pay/admin/front/wx/pay/wxPay.do", JSONUtil.toJsonStr(map)); // } catch (Exception e) { // error = true; // log.error("远程调用提现审核接口失败", e); // } // // if (error) { // //修改状态 // PayRequestInfo payRequestInfo = new PayRequestInfo(); // payRequestInfo.setPayOrderId(payOrderId); // payRequestInfo.setPayFlag(Convert.toInt(PayEnum.支付失败.getValue())); // payRequestInfo.setStatus(PayEnum.已审核完成.getValue()); // payRequestInfo.setUnpassReason("提现审核接口超时"); // payRequestMapper.updateByPrimaryKeySelective(payRequestInfo); // return -1; // } else { // log.info("提现审核返回结果:{}", post); // JSONObject jsonObject = JSONUtil.parseObj(post); // Integer code = jsonObject.getInt("code"); // String data = jsonObject.getStr("data", ""); // if (code != 0) { // throw new RestException(-1, data); // } // } // } else { // throw new RestException(-1, "提现订单不存在"); // } // } // } catch (RestException e) { // throw new BusinessException(-1, e.getMsg(), ExceptionUtil.getMessage(e)); // } catch (Exception e) { // ExceptionUtils.err("提现审核失败", e); // } finally { // if (lock == true) { // redisUtil.del(Constants.REDIS_PAY_KEY + "audit:" + payOrderId); // } // } // return 0; // } /** * 提现 * @param money */ // public void withdraw(String money,String userId,String clientType,Long accountBindId) { // boolean lock=false; // try { // if(redisUtil.setnx(Constants.REDIS_PAY_KEY + "withdraw:" +userId, userId)) { // lock=true; // PayInfoReq payInfoReq = new PayInfoReq(); // payInfoReq.setMoney(money); // payInfoReq.setCreateUserId(userId); // List withdrawList = payMapper.queryWithdrawInfo(payInfoReq); // if (withdrawList.size() >= 1) { // throw new RestException(-1, "一天只能提现一次"); // } // String payOrderId = idUtils.generate("ZF", 0); // payInfoReq.setPayOrderId(payOrderId); // String now = DateUtil.now(); // payInfoReq.setCreateTime(now); // List accountList = payMapper.queryMyMoney(payInfoReq); // AccountVo accountVo = accountList.get(0); // payInfoReq.setAccountId(accountVo.getAccountId()); // payInfoReq.setPayType(PayEnum.提现.getValue()); // //提现金额 // BigDecimal bigDecimal = NumberUtil.toBigDecimal(payInfoReq.getMoney()); // //余额 // BigDecimal bigDecimal1 = NumberUtil.toBigDecimal(accountVo.getMoney()); // // //判断账户余额是否足够,返回-1表示余额不够 // // if (NumberUtil.isGreater(bigDecimal, bigDecimal1)) { // throw new RestException(-1, "用户余额不足"); // } // // //查询用户openId // if (CommonEnum.WEB.getValue().equals(clientType)) { // UserInfo userInfo = userMapper.selectByPrimaryKey(userId); // payInfoReq.setOpenId(userInfo.getOpenId()); // } else { // OtherUserInfo otherUserInfo = otherUserMapper.selectByPrimaryKey(userId); // payInfoReq.setOpenId(otherUserInfo.getOpenId()); // } // // payInfoReq.setStatus(PayEnum.已审核.getValue()); // payInfoReq.setAccountBindId(accountBindId); // payMapper.payRequestInfoAdd(payInfoReq); // // // PayInfoLog payInfoLog = new PayInfoLog(); // BeanUtil.copyProperties(payInfoReq, payInfoLog); // payInfoLog.setAccount(accountVo.getAccountName()); // payInfoLog.setAccountClass(PayEnum.微信.getValue()); // payInfoLog.setPayType(PayEnum.提现交易.getValue()); // payInfoLogService.add(payInfoLog); // // //是否自动审核 银行卡等肯定是手动审核 // ConfigInfo configInfo = new ConfigInfo(); // configInfo.setConfigTypeCode("APPROVAL_TYPE"); // ConfigInfo configInfo1 = configMapper.selectOne(configInfo); // if (configInfo1 != null) { // String configValue = configInfo1.getConfigValue(); // if(PayEnum.自动审核.getValue().equals(configValue)){ // log.info("调用提现自动审核接口"); // Map map = new HashMap<>(); // map.put("payOrderId", commonDto.getId()); // } // } // // // // } // }catch (RestException e){ // throw new RestException(-1,e.getMsg()); // }catch (Exception e){ // ExceptionUtils.err("提现审核失败",e); // }finally { // if(lock){ // redisUtil.del(Constants.REDIS_PAY_KEY +"withdraw:" +userId); // } // } // // } /** * 查询当前用户一周内是否有充值成功的记录 */ // public List findForWeekByUserIdAndType(String userId, String payType) { // return payInfoMapper.findForWeekByUserIdAndType(userId, payType); // } public void updateStatus(String payOrderId, String status) { Example example = new Example(PayInfo.class); Example.Criteria criteria = example.createCriteria(); criteria.andEqualTo("payOrderId", payOrderId); criteria.andNotEqualTo("status", "2"); PayInfo payInfo = new PayInfo(); payInfo.setStatus(status); payInfoMapper.updateByExampleSelective(payInfo, example); } public AccountBindInfo findPayMethod(String userId) { AccountBindInfo payMethod = payInfoMapper.findPayMethod(userId); if (payMethod == null) { List byUserId = accountBindService.findByUserId(userId); if (CollUtil.isNotEmpty(byUserId)) { return byUserId.get(0); } else { return null; } } else { return payMethod; } } public void sendWxPay(String url, String path, TransfersDtoAdmin dto, UserAccountModel userAccount, String mobilePhone, String oldMoney) { String param = WechatpayUtil.getStringBuild(dto); PayLog payLog = insertLog(dto, userAccount, param); ResultEntity iResult = WechatpayUtil.doTransfers(url, path, dto, userAccount, param); payLog.setResponseData(iResult.getMsg()); if (!iResult.isSuccess()) { throw new RestException(iResult.getMsg()); } else { updateAccount(payLog, dto.getPayOrderId(), mobilePhone, oldMoney); } } /** * 企业提现零钱接口 * * @param dto * @param userAccount */ private PayLog insertLog(TransfersDtoAdmin dto, UserAccountModel userAccount, String param) { // 添加账户log请求前信息 PayLog payLog = new PayLog(); payLog.setId(IdUtil.getSnowflake(1, 3).nextId()); payLog.setAccountBeforeMoney(userAccount.getMoney()); payLog.setUserId(dto.getUserId()); payLog.setAccountId(userAccount.getAccountId()); payLog.setWxOpenid(dto.getOpenid()); payLog.setCreateTime(DateUtil.now()); payLog.setPayStatus("0"); //因为接口使用的是以分为单位,所以需要转为元 String a = new BigDecimal(dto.getAmount()).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP).toString(); payLog.setMoney(Double.valueOf(a)); payLog.setWithdrawBeforeMoney(Double.parseDouble("0")); payLog.setMchBillno(dto.getPayOrderId()); payLog.setRequestParams(param); return payLog; } private void updateAccount(PayLog payLog, String payOrderId, String mobilePhone, String oldMoney) { UserAccountModel userAccountModel1 = accountMapper.queryAccountInfo(payLog.getUserId(), mobilePhone); double mm = MathUtils.subDouble(userAccountModel1.getMoney(), payLog.getMoney()); PayLog newPl = new PayLog(); newPl.setAccountId(payLog.getAccountId()); newPl.setMoney(mm); // 更新账号余额 accountMapper.updateAccountMoneyDouble(newPl); //写入消息列表中 String message = "您的提现已经到了:" + payLog.getMoney() + "元,提现单号:" + payOrderId + ",请注意查收."; sysMessageMapper.insertMessage(message, payLog.getUserId(), "", "1", "提现", DateUtil.now()); UserAccountModel userAccountModel = accountMapper.queryAccountInfo(payLog.getUserId(), mobilePhone); AccountLogModel model = new AccountLogModel(); model.setAccountId(userAccountModel.getAccountId()); model.setChannelType("2"); model.setCreateTime(DateUtil.now()); model.setCreateUserId(userAccountModel.getUserId()); model.setNewFixedLimit(userAccountModel.getFixedLimit()); model.setNewLimit(userAccountModel.getOverdraftLimit()); model.setNewMoney(String.valueOf(userAccountModel.getMoney())); model.setOldFixedLimit(userAccountModel.getFixedLimit()); model.setOldLimit(userAccountModel.getOverdraftLimit()); model.setOldMoney(oldMoney); model.setOrderId(payOrderId); accountLogMapper.insertAccountLog(model); //写入平台日志表,扣除平台金额添加环保币 insertPlatLog(payLog.getMoney() + "", payOrderId); } public Map queryPayInfoDetail(String payOrderId) { Map map = payRequestMapper.queryPayInfoDetail(payOrderId); if (!"1".equals(map.get("usertype"))) { String roleName = userRoleMapper.queryPayInfoUserRole(map.get("usertype").toString()); map.put("roleName", roleName); } else { map.put("roleName", "普通用户"); } if (map.get("status").equals("2")) { map.put("statusName", "已审核"); } else if (map.get("status").equals("3")) { map.put("statusName", "审核未通过"); } else { map.put("statusName", "待审核"); } return map; } private void insertPlatLog(String amount, String payOrderId) { String acc = platformAccountInfoMapper.queryAccountByAdminId(); String[] accArr = acc.split(","); String adminMoney = accArr[1]; String adminhbb = accArr[2]; //平台 BigDecimal oldAdminMoney = new BigDecimal(adminMoney); BigDecimal oldAdminhbb = new BigDecimal(adminhbb); //平台账户处理红包 BigDecimal newAdminMoney = oldAdminMoney.subtract(new BigDecimal(amount)); BigDecimal newAdminhbb = oldAdminhbb.add(new BigDecimal(amount)); platformAccountInfoMapper.updatePlatformHbb(DoubleUtil.roundTwo(newAdminhbb.toString())); platformAccountInfoMapper.updatePlatformMoney(DoubleUtil.roundTwo(newAdminMoney.toString())); PlatformAccountLogModel platformAccountLogModel = new PlatformAccountLogModel(); platformAccountLogModel.setCreateTime(DateUtil.now()); platformAccountLogModel.setCreateUserId("1"); platformAccountLogModel.setMoney(DoubleUtil.roundTwo("0")); platformAccountLogModel.setHbb("-" + DoubleUtil.roundTwo(amount)); platformAccountLogModel.setOldHbb(DoubleUtil.roundTwo(adminhbb)); platformAccountLogModel.setOldMoney(DoubleUtil.roundTwo(adminMoney)); platformAccountLogModel.setNewHbb(DoubleUtil.roundTwo(newAdminhbb.toString())); platformAccountLogModel.setNewMoney(DoubleUtil.roundTwo(adminMoney)); platformAccountLogModel.setCreateUserName("平台管理员"); platformAccountLogModel.setCreateUserType("2"); platformAccountLogModel.setCreateUserMobile("--"); platformAccountLogModel.setFlowNo(payOrderId); platformAccountLogMapper.insertPlatFormLog(platformAccountLogModel); } public void wxPay(TransfersDtoAdmin dto) { MoneyModel moneyModel; String payOrderId = dto.getPayOrderId(); String otherUserId = dto.getOtherUserId(); String key=RedisKeyConstant.WITHDRAW_KEY+payOrderId; try { if(redisUtil.setnx(key,"0")){ if (StringUtils.isEmpty(dto.getPayOrderId())) { throw new RestException("payOrderId不能为空"); } else { moneyModel = getMoneyModel(dto.getPayOrderId()); String desc; //监测金额和用户是否一致 if (null != otherUserId && !"".equals(otherUserId)) { desc = checkMoneyModel(moneyModel, otherUserId); } else { desc = checkMoneyModel(moneyModel, dto.getUserId()); } if (!"success".equals(desc)) { throw new RestException(desc); } } //查询用户openId String openId; UserModel userModel = null; CityPartner cityPartner = null; if (StrUtil.isNotBlank(otherUserId)) { //根据用户ID判断是否是合伙人 是则代表是合伙人的运营员在操作 cityPartner = cityPartnerService.findByUserId(otherUserId, OrderEnum.合伙人.getValue()); if (cityPartner == null) { //回收员之类的在提现 dto.setMch_appid(anroidAppId); userModel = otherUserMapper.queryUserOtherInfoById(otherUserId); } } else { dto.setMch_appid(APP_ID); userModel = userMapper.queryUserById(dto.getUserId()); } //不是合伙人提现 if (cityPartner == null && userModel == null) { throw new RestException("用户不存在"); } //查询用户账户是否能提现 if (cityPartner == null) { //检测金额是否足够 UserAccountModel userAccount=checkUserAccount(moneyModel, userModel); String oldMoney = String.valueOf(userAccount.getMoney()); openId = userModel.getOpenId(); String mobilePhone = userModel.getMobilePhone(); if (StrUtil.isNotBlank(openId)) { dto.setOpenid(openId); dto.setMchid(MCH_ID); dto.setAppkey(APP_KEY); dto.setSpbill_create_ip(CREATE_IP); dto.setMch_name("湖南小棕熊环保科技有限责任公司"); dto.setDesc("企业付款到零钱"); if (null != otherUserId && !"".equals(otherUserId)) { dto.setUserId(otherUserId); } //自动转为以分为单位 dto.setAmount(Double.parseDouble(moneyModel.getMoney())); dto.setPayOrderId(payOrderId); sendWxPay(TRANS_URL, CERT_PATH, dto, userAccount, mobilePhone, oldMoney); }else { throw new RestException("用户OPENID为空"); } }else { //线下打款 减去其环保币 PartnerAccountLog partnerAccountLog=new PartnerAccountLog(); partnerAccountLog.setPartnerId(cityPartner.getId()+""); partnerAccountLog.setFlowNo(payOrderId); //提现 partnerAccountLog.setType("2"); partnerAccountLog.setMoney("-"+moneyModel.getMoney()); partnerAccountLogService.add(partnerAccountLog); partnerAccountService.updateReduceMoneyByPartnerId(cityPartner.getId()+"",Convert.toBigDecimal(moneyModel.getMoney())); } // 更新支付状态 PayRequestInfo payRequestInfo=new PayRequestInfo(); payRequestInfo.setPayOrderId(payOrderId); payRequestInfo.setStatus("2"); payRequestInfo.setPayFlag(2); payRequestInfo.setExamineTime(DateUtil.now()); payRequestMapper.updateByPrimaryKeySelective(payRequestInfo); } }catch (RestException e){ ExceptionUtils.err(e.getMsg(), e); }catch (Exception e){ ExceptionUtils.err("提现失败", e); }finally { redisUtil.del(key); } } private MoneyModel getMoneyModel(String payOrderId) { MoneyModel moneyModel = new MoneyModel(); moneyModel.setPayOrderId(payOrderId); moneyModel = payRequestMapper.queryMoney(moneyModel); moneyModel.setStatus("3"); moneyModel.setPayFlag("3"); moneyModel.setExamineTime(DateUtil.now()); return moneyModel; } private UserAccountModel checkUserAccount(MoneyModel moneyModel, UserModel userModel) { // 查询用户账号表 UserAccountModel userAccountModel = accountMapper.queryAccountInfo(userModel.getUserId(), userModel.getMobilePhone()); if (userAccountModel == null) { throw new RestException("此用户未查询到账户信息"); } if (userAccountModel.getDelFlag().equals("1")) { throw new RestException("账户信息已删除"); } if (userAccountModel.getMoney() < Double.parseDouble(moneyModel.getMoney())) { throw new RestException("账户金额不足"); } if (!userModel.getOpenId().equals(moneyModel.getOpenId())) { throw new RestException("用户和支付的openId不一致"); } return userAccountModel; } /** * @param model * @return */ private String checkMoneyModel(MoneyModel model, String userId) { if (!model.getCreateUserId().equals(userId)) { model.setUnpassReason("userId和支付订单里面的userId不一致"); payRequestMapper.updateMoney(model); return "userId和支付订单里面的userId不一致"; } if (StringUtils.isEmpty(model.getCreateUserId())) { model.setUnpassReason("用户ID不能为空"); payRequestMapper.updateMoney(model); return "用户ID不能为空"; } if (StringUtils.isEmpty(model.getMoney())) { model.setUnpassReason("金钱不能为空"); payRequestMapper.updateMoney(model); return "金钱不能为空"; } if (Double.parseDouble(model.getMoney()) <= 0.3) { model.setUnpassReason("金额不能等于或小于0.3"); payRequestMapper.updateMoney(model); return "金额不能等于或小于1"; } return "success"; } /** * 根据用户id和支付类型和支付第二类型分页查询 * * @param userId 用户id * @param payType 支付类型 * @param secondType 第二类型 * @return */ public PageInfo findPageByUserIdAndSecondType(SimplePage simplePage, String userId, String payType, String secondType) { Example example = new Example(PayInfo.class); Example.Criteria criteria = example.createCriteria(); criteria.andEqualTo("createUserId", userId); if (StrUtil.isNotBlank(payType)) criteria.andEqualTo("payType", payType); if (StrUtil.isNotBlank(secondType)) criteria.andEqualTo("paySecondType", secondType); example.setOrderByClause("create_time desc"); PageHelper.startPage(simplePage.getPageNo(), simplePage.getPageSize()); List payInfos = payInfoMapper.selectByExample(example); PageInfo payInfoPageInfo = new PageInfo<>(payInfos); return payInfoPageInfo; } /** * 积分列表 * * @param payScoreParamDTO * @return */ public PayScoreResDTO scoreList(PayScoreParamDTO payScoreParamDTO) { PayScoreResDTO resDTO = new PayScoreResDTO(); List list = payInfoMapper.scoreList(payScoreParamDTO); PageInfo pageInfo = new PageInfo<>(list); resDTO.setPageInfo(pageInfo); //平台总积分 String collectScore = platformAccountInfoService.findByKey("collectScore").getFieldValue(); resDTO.setAllPlatScore(businessUtil.changeMoney(collectScore)); //获取总积分 BigDecimal allRechargeScore = Constants.MONEY_INIT; //消耗总积分 BigDecimal allConsumeScore = Constants.MONEY_INIT; List accountScoreLogs = accountScoreLogMapper.selectAll(); for (AccountScoreLog accountScoreLog : accountScoreLogs) { Short channelType = accountScoreLog.getChannelType(); String manageScore = accountScoreLog.getManageScore(); if (Convert.toShort(1).equals(channelType)) { //获取 allRechargeScore = NumberUtil.add(allRechargeScore, businessUtil.changeMul(manageScore)); } else if (Convert.toShort(2).equals(channelType)) { //消耗 allConsumeScore = NumberUtil.add(allConsumeScore, businessUtil.changeMul(manageScore)); } } resDTO.setAllRechargeScore(businessUtil.changeMoney(allRechargeScore)); resDTO.setAllConsumeScore(businessUtil.changeMoney(allConsumeScore)); return resDTO; } private AlipayTradeAppPayRequest getRequest() { // 初始化Request,并填充Model属性。实际调用时请替换为您想要使用的API对应的Request对象。 AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); // AlipayOpenOperationOpenbizmockBizQueryModel model = new AlipayOpenOperationOpenbizmockBizQueryModel(); // model.setBizNo("test"); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.setBody("我是测试数据"); model.setSubject("App支付测试Java"); model.setOutTradeNo(idUtils.generate("ZF", 1)); model.setTimeoutExpress("30m"); model.setTotalAmount("0.01"); model.setProductCode("QUICK_MSECURITY_PAY"); request.setBizModel(model); request.setNotifyUrl("http://zan7755.ngrok2.xiaomiqiu.cn/gc-pay/pay/ali/notify"); return request; } public String aliPay(AliPayDTO aliPayDTO) throws AlipayApiException { // 2. 创建使用的Open API对应的Request请求对象 AlipayTradeAppPayRequest request = getRequest(); // 3. 发起请求并处理响应 AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request); if (response.isSuccess()) { log.debug("阿里支付调用成功。"); } else { log.debug("阿里支付调用失败,原因:" + response.getMsg() + "," + response.getSubMsg()); } return response.getBody(); } public String aliPayNotify(Map params) throws AlipayApiException { log.debug("阿里回调返回:{}", JSONUtil.toJsonStr(params)); //切记alipaypublickey是支付宝的公钥,请去open.alipay.com对应应用下查看。 //boolean AlipaySignature.rsaCertCheckV1(Map params, String publicKeyCertPath, String charset,String signType) boolean flag = AlipaySignature.rsaCertCheckV1(params, "E:/card/alipayCertPublicKey_RSA2.crt", "UTF-8", "RSA2"); return Convert.toStr(flag); } }