package com.nq.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.google.gson.Gson; import com.nq.common.CmcPayConfig; import com.nq.common.ServerResponse; import com.nq.dao.*; import com.nq.pay.PayUtil; import com.nq.pojo.*; import com.nq.service.*; import com.nq.utils.*; import com.nq.utils.http.HttpClientUtil; import com.nq.utils.pay.CmcPayOuterRequestUtil; import com.nq.utils.pay.CmcPayTool; import com.nq.utils.timeutil.DateTimeUtil; import com.nq.vo.pay.GuoPayVO; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.URLDecoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONObject; import org.apache.commons.collections.map.HashedMap; import org.apache.commons.collections.map.LinkedMap; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import static com.nq.utils.timeutil.DateTimeUtil.STANDARD_FORMAT; @Service("iPayService") public class PayServiceImpl implements IPayService { private static final Logger log = LoggerFactory.getLogger(PayServiceImpl.class); @Autowired IUserService iUserService; @Resource UserRechargeMapper userRechargeMapper; @Resource UserMapper userMapper; @Resource SitePayMapper sitePayMapper; @Resource IUserService userService; @Resource IUserAssetsServices iUserAssetsServices; @Resource UserWithdrawMapper userWithdrawMapper; @Autowired ISiteInfoService siteInfoService; public ServerResponse juhe1(String payType, String payAmt, HttpServletRequest request) { if (StringUtils.isBlank(payType) || StringUtils.isBlank(payAmt)) { return ServerResponse.createByErrorMsg("参数不能为空"); } BigDecimal payAmtBig = new BigDecimal(payAmt); if ((new BigDecimal("0")).compareTo(payAmtBig) != -1) { return ServerResponse.createByErrorMsg("支付金额必须大于0"); } User user = this.iUserService.getCurrentRefreshUser(request); if (user == null){ return ServerResponse.createBySuccessMsg("請先登錄"); } UserRecharge userRecharge = new UserRecharge(); userRecharge.setUserId(user.getId()); userRecharge.setNickName(user.getRealName()); userRecharge.setAgentId(user.getAgentId()); String ordersn = KeyUtils.getRechargeOrderSn(); userRecharge.setOrderSn(ordersn); String saveChannel = ""; if ("902".equals(payType)) { saveChannel = "微信-线上"; } else { saveChannel = "支付宝-线上"; } userRecharge.setPayChannel(saveChannel); userRecharge.setPayAmt(new BigDecimal(payAmt)); userRecharge.setOrderStatus(Integer.valueOf(0)); userRecharge.setAddTime(new Date()); int insertCount = this.userRechargeMapper.insert(userRecharge); if (insertCount > 0) { log.info("线上支付,创建支付订单成功!"); } else { log.info("线上支付,创建支付订单失败!"); } String pay_bankcode = ""; if ("902".equals(payType)) { pay_bankcode = payType; } else if ("907".equals(payType)) { pay_bankcode = payType; } else { pay_bankcode = "903"; } String AuthorizationURL = "http://pay.ksunpay.com:8080/Pay_Index.html"; String merchantId = "10098"; String keyValue = "vd7omkkexkt7fvl6wm2jl9yan3g79y6i"; String pay_memberid = merchantId; String pay_orderid = ordersn; String pay_applydate = generateTime(); String pay_notifyurl = PropertiesUtil.getProperty("juhe1.pay.notifyurl"); String pay_callbackurl = PropertiesUtil.getProperty("juhe1.pay.callbackurl"); String pay_amount = payAmt; String pay_attach = ""; String pay_productname = "100元话费充值"; String pay_productnum = ""; String pay_productdesc = ""; String pay_producturl = ""; String stringSignTemp = "pay_amount=" + pay_amount + "&pay_applydate=" + pay_applydate + "&pay_bankcode=" + pay_bankcode + "&pay_callbackurl=" + pay_callbackurl + "&pay_memberid=" + pay_memberid + "&pay_notifyurl=" + pay_notifyurl + "&pay_orderid=" + pay_orderid + "&key=" + keyValue + ""; String pay_md5sign = ""; try { pay_md5sign = md5(stringSignTemp); } catch (Exception e) { log.error("加密md5出错 e= {}", e); } GuoPayVO guoPayVO = new GuoPayVO(); guoPayVO.setPostUrl(AuthorizationURL); guoPayVO.setPay_memberid(merchantId); guoPayVO.setPay_orderid(pay_orderid); guoPayVO.setPay_applydate(pay_applydate); guoPayVO.setPay_bankcode(pay_bankcode); guoPayVO.setPay_notifyurl(pay_notifyurl); guoPayVO.setPay_callbackurl(pay_callbackurl); guoPayVO.setPay_amount(pay_amount); guoPayVO.setPay_productname(pay_productname); guoPayVO.setPay_productnum(pay_productnum); guoPayVO.setPay_productdesc(pay_productdesc); guoPayVO.setPay_producturl(pay_producturl); guoPayVO.setPay_md5sign(pay_md5sign); return ServerResponse.createBySuccess(guoPayVO); } public ServerResponse juhe1Notify(HttpServletRequest request) { String memberid = request.getParameter("memberid"); String orderid = request.getParameter("orderid"); String amount = request.getParameter("amount"); String datetime = request.getParameter("datetime"); String returncode = request.getParameter("returncode"); String transaction_id = request.getParameter("transaction_id"); String attach = request.getParameter("attach"); String sign = request.getParameter("sign"); log.info("支付通知的 orderid = {}", orderid); log.info("支付通知的 transaction_id = {}", transaction_id); log.info("支付通知的 amount = {}", amount); log.info("支付通知的 returncode = {}", returncode); String keyValue = "vd7omkkexkt7fvl6wm2jl9yan3g79y6i"; String SignTemp = "amount=" + amount + "&datetime=" + datetime + "&memberid=" + memberid + "&orderid=" + orderid + "&returncode=" + returncode + "&transaction_id=" + transaction_id + "&key=" + keyValue + ""; log.info("signtemp : {}", SignTemp); String md5sign = ""; try { md5sign = md5(SignTemp); } catch (Exception e) { log.info("线上支付后台通知 生成md5sign出错,e = {}", e); } log.info("支付通知的sign = {}", sign); log.info("自己加密的sign = {}", md5sign); ServerResponse serverResponse = ServerResponse.createByError(); if (sign.equals(md5sign)) { log.info("后台通知校验签名 通过"); if (returncode.equals("00")) { log.info("后台通知成功,开始修改订单 {}", orderid); serverResponse = doSuccess(orderid, amount); } else { log.error("后台通知 returncode 不为 00 , 支付不成功"); } } else { log.info("后台通知校验签名 不通过"); } return serverResponse; } @Transactional public ServerResponse flyPay(Integer payType, String payAmt, String currency, HttpServletRequest request) { User user = iUserService.getCurrentUser(request); SitePay sitePay = sitePayMapper.selectById(payType); UserRecharge userRecharge = new UserRecharge(); userRecharge.setUserId(user.getId()); userRecharge.setNickName(user.getRealName()); userRecharge.setAgentId(user.getAgentId()); String ordersn = KeyUtils.getRechargeOrderSn(); userRecharge.setOrderSn(ordersn); userRecharge.setPayChannel(sitePay.getChannelName()); userRecharge.setPayAmt(new BigDecimal(payAmt)); userRecharge.setOrderStatus(Integer.valueOf(0)); userRecharge.setAddTime(new Date()); userRecharge.setPayId(payType); userRecharge.setImg(currency); userRechargeMapper.insert(userRecharge); return ServerResponse.createBySuccess( ((SiteInfo)siteInfoService.getInfo(request).getData()).getOnlineService()); } /** * 充值方式一 * */ public ServerResponse rechargMethodGe(String ordersn,String payAmt){ Map map = new HashedMap(); map.put("version","1.0"); map.put("mch_id",PayUtil.MCH_ID_TOP1); map.put("notify_url","http://www.jumptalk.net:8091/api/pay/flyNotify.do"); map.put("mch_order_no",ordersn); map.put("pay_type","122"); map.put("trade_amount",payAmt); map.put("order_date", DateTimeUtil.getCurrentDate(STANDARD_FORMAT)); map.put("goods_name","充值"); String signStr = SignUtil.sortData(map); map.put("sign_type","MD5"); try { map.put("sign", SignAPI.sign(signStr,PayUtil.DOWN_TOKEN_TPO1)); String reponse = HttpClientUtil.doPost(PayUtil.PAY_DOWN_ORDER_TOP1, map, "utf-8"); log.info("下单支付返回数据 TOP1 {}" ,reponse); com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(reponse); if(object.getString("respCode").equals("SUCCESS")){ return ServerResponse.createBySuccess(object.getString("payInfo")); }else { return ServerResponse.createBySuccessMsg("Contact customer service"); } }catch (Exception e){ e.printStackTrace(); } return ServerResponse.createByError(); } /** * 充值方式二 富达科技 * */ public ServerResponse rechargMethodTop4(String ordersn,String payAmt){ Map map = new HashedMap(); map.put("merchant","3l001038"); map.put("payCode","101"); map.put("amount",payAmt); map.put("orderId",ordersn); map.put("notifyUrl","122"); String signStr = SignUtil.sortData(map); try { log.info("签名数据 TOP2 {}" ,signStr); String signatureString = SignAPI.sign(signStr,PayUtil.DOWN_TOKEN_TPO4).toLowerCase(); map.put("sign",signatureString); log.info("签完名数据 TOP2 {}" ,signatureString); String reponse = HttpClientUtil.doPost(PayUtil.PAY_DOWN_ORDER_TOP4, map, "utf-8"); log.info("下单支付返回数据 TOP2 {}" ,reponse); com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(reponse); if(object.getString("respCode").equals("SUCCESS")){ return ServerResponse.createBySuccess(object.getString("payInfo")); }else { return ServerResponse.createBySuccessMsg("Contact customer service"); } }catch (Exception e){ e.printStackTrace(); } return ServerResponse.createByError(); } /** * 充值方式3 wow * */ public ServerResponse rechargMethodWow(String ordersn,String payAmt){ Map map = new HashedMap(); map.put("version","1.0"); map.put("mch_id",PayUtil.MCH_ID_TOP2); // map.put("mch_id","222887002"); map.put("notify_url","http://www.jumptalk.net:8091/api/pay/flyNotify2.do"); map.put("mch_order_no",ordersn); map.put("pay_type","151"); // map.put("pay_type","105"); map.put("trade_amount",payAmt); map.put("order_date",DateTimeUtil.getCurrentDate(STANDARD_FORMAT)); map.put("goods_name","充值"); String signStr = SignUtil.sortData(map); map.put("sign_type","MD5"); try { map.put("sign", SignAPI.sign(signStr,PayUtil.DOWN_TOKEN_TPO2)); log.info("下单数据 {}",new Gson().toJson(map)); String reponse = HttpClientUtil.doPost(PayUtil.PAY_DOWN_ORDER_TOP2, map, "utf-8"); log.info("下单支付返回数据 {}" ,reponse); com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(reponse); if(object.getString("respCode").equals("SUCCESS")){ return ServerResponse.createBySuccess(object.getString("payInfo")); }else { return ServerResponse.createBySuccessMsg("Contact customer service"); } }catch (Exception e){ e.printStackTrace(); } return ServerResponse.createByError(); } /** * 充值方式一 * */ public ServerResponse rechargMethodDz(String ordersn,String payAmt){ Map map = new HashedMap(); map.put("version","1.0"); // map.put("mch_id",""); map.put("mch_id",PayUtil.MCH_ID_TOP3); map.put("notify_url","http://www.jumptalk.net:8091/api/pay/flyNotify3.do"); map.put("mch_order_no",ordersn); map.put("pay_type","121"); map.put("trade_amount",payAmt); map.put("order_date",DateTimeUtil.getCurrentDate(STANDARD_FORMAT)); map.put("goods_name","充值"); String signStr = SignUtil.sortData(map); map.put("sign_type","MD5"); try { map.put("sign", SignAPI.sign(signStr,PayUtil.DOWN_TOKEN_TPO3)); log.info("下单数据 {}",new Gson().toJson(map)); String reponse = HttpClientUtil.doPost(PayUtil.PAY_DOWN_ORDER_TOP3, map, "utf-8"); log.info("下单支付返回数据 {}" ,reponse); com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(reponse); if(object.getString("respCode").equals("SUCCESS")){ return ServerResponse.createBySuccess(object.getString("payInfo")); }else { return ServerResponse.createBySuccessMsg("Contact customer service"); } }catch (Exception e){ e.printStackTrace(); } return ServerResponse.createByError(); } public void inrEpayMethod(String orderNo){ Map map = new HashedMap(); map.put("trade_no","1166"); map.put("app_id","188"); map.put("pay_code","2063"); map.put("price","10000"); map.put("order_no",orderNo); map.put("pay_notice_url ","http://61.4.121.99:8091/api/pay/flyNotify.do"); // String sign = PayUtil.ascii(map, PayUtil.token, "&", false, "secret"); } public ServerResponse flyNotify(HttpServletRequest request) throws IOException { Map map = SignUtil.convertRequestParamsToMap(request); log.info("支付通知的 回调参数11111 {}", new Gson().toJson(map)); String tradeResult = map.get("tradeResult"); String mchId = map.get("mchId"); String mchOrderNo = map.get("mchOrderNo"); String oriAmount = map.get("oriAmount"); String amount = map.get("amount"); String orderDate = map.get("orderDate"); String orderNo = map.get("orderNo"); String sign = map.get("sign"); String signType = map.get("signType"); Map params = new HashedMap(); params.put("tradeResult", tradeResult); params.put("mchId", mchId); params.put("mchOrderNo", mchOrderNo); params.put("oriAmount", oriAmount); params.put("amount", amount); params.put("orderDate", orderDate); params.put("orderNo", orderNo); params.put("amount", amount); String signStr = SignUtil.sortData(params); String signInfo =signStr.toString(); boolean result = false; if("MD5".equals(signType)){ result = SignAPI.validateSignByKey(signInfo, PayUtil.DOWN_TOKEN_TPO1, sign); } if(result){ if(tradeResult.equals("1")){ doSuccess(mchOrderNo,oriAmount); } System.out.println("验签结果result的值:" + result + " -->success"); return ServerResponse.createBySuccess(); }else{ System.out.println("验签结果result的值:" + result + " -->Signature Error"); return ServerResponse.createByError(); } } public ServerResponse flyNotify(HttpServletRequest request,String key) throws IOException { Map map = SignUtil.convertRequestParamsToMap(request); log.info("支付通知的 回调参数11111 {}", new Gson().toJson(map)); String tradeResult = map.get("tradeResult"); String mchId = map.get("mchId"); String mchOrderNo = map.get("mchOrderNo"); String oriAmount = map.get("oriAmount"); String amount = map.get("amount"); String orderDate = map.get("orderDate"); String orderNo = map.get("orderNo"); String sign = map.get("sign"); String signType = map.get("signType"); Map params = new HashedMap(); params.put("tradeResult", tradeResult); params.put("mchId", mchId); params.put("mchOrderNo", mchOrderNo); params.put("oriAmount", oriAmount); params.put("amount", amount); params.put("orderDate", orderDate); params.put("orderNo", orderNo); params.put("amount", amount); String signStr = SignUtil.sortData(params); String signInfo =signStr.toString(); boolean result = false; if("MD5".equals(signType)){ result = SignAPI.validateSignByKey(signInfo, key, sign); } if(result){ if(tradeResult.equals("1")){ doSuccess(mchOrderNo,oriAmount); } System.out.println("验签结果result的值:" + result + " -->success"); return ServerResponse.createBySuccess(); }else{ System.out.println("验签结果result的值:" + result + " -->Signature Error"); return ServerResponse.createByError(); } } public ServerResponse withdrawNotify(HttpServletRequest request,String key) throws IOException { Map map = SignUtil.convertRequestParamsToMap(request); String tradeResult = map.get("tradeResult"); String merTransferId = map.get("merTransferId"); String merNo = map.get("merNo"); String tradeNo = map.get("tradeNo"); String transferAmount = map.get("transferAmount"); String sign = map.get("sign"); String signType =map.get("signType"); String applyDate = map.get("applyDate"); String version = map.get("version"); String respCode = map.get("respCode"); Map signStr = new LinkedHashMap(); signStr.put("tradeResult", tradeResult); signStr.put("merTransferId", merTransferId); signStr.put("merNo", merNo); signStr.put("tradeNo", tradeNo); signStr.put("transferAmount", transferAmount); signStr.put("applyDate", applyDate); signStr.put("version", version); signStr.put("respCode", respCode); String signInfo = SignUtil.sortData(signStr); System.out.println(signInfo.length() + " -->" + signInfo); System.out.println(sign.length() + " -->" + sign); boolean result = false; if ("MD5".equals(signType)) { result = SignAPI.validateSignByKey(signInfo, key, sign); } if(result){ UserWithdraw userWithdraw = userWithdrawMapper.selectByPrimaryKey(Integer.parseInt(merTransferId)); if(userWithdraw != null){ if(tradeResult.equals("1")){ userWithdraw.setWithStatus(2); userWithdrawMapper.updateByPrimaryKey(userWithdraw); } } return ServerResponse.createBySuccess(); } return ServerResponse.createByError(); } private ServerResponse doSuccess(String orderId, String amount) { UserRecharge userRecharge = this.userRechargeMapper.findUserRechargeByOrderSn(orderId); if (userRecharge == null) { return ServerResponse.createByErrorMsg("后台通知,查不到订单"); } User user = this.userMapper.selectById(userRecharge.getUserId()); if (user == null) { return ServerResponse.createByErrorMsg("后台通知,查不到用户"); } // if (userRecharge.getPayAmt().compareTo(new BigDecimal(amount)) != 0) { // return ServerResponse.createByErrorMsg("处理失败,后台通知金额和订单金额不一致"); // } if(userRecharge.getOrderStatus() == 1){ return ServerResponse.createBySuccess(); } userRecharge.setPayTime(new Date()); userRecharge.setOrderStatus(Integer.valueOf(1)); int updateCount = this.userRechargeMapper.updateByPrimaryKeySelective(userRecharge); if (updateCount > 0) { log.info("后台通知,修改订单状态成功"); int updateUserCount = this.userMapper.updateById(user); if (updateUserCount > 0) { return ServerResponse.createBySuccessMsg("后台通知 处理成功"); } return ServerResponse.createByErrorMsg("后台通知 处理失败 修改用户资金不成功"); } log.error("后台通知,修改订单状态失败"); return ServerResponse.createByErrorMsg("后台通知修改订单的状态失败"); } public String generateOrderId() { String keyup_prefix = (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date()); String keyup_append = String.valueOf((new Random()).nextInt(899999) + 100000); return keyup_prefix + keyup_append; } public String generateTime() { return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()); } public String md5(String str) throws NoSuchAlgorithmException { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] byteDigest = md.digest(); StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < byteDigest.length; offset++) { int i = byteDigest[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString().toUpperCase(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } public static void main(String[] args) { BigDecimal a = new BigDecimal("0.011"); BigDecimal b = new BigDecimal("0.010"); System.out.println(a.compareTo(b)); } @Override public ServerResponse juhenewpay(String paramString1, String paramString2, HttpServletRequest request) throws Exception { User user = iUserService.getCurrentRefreshUser(request); if (user == null){ return ServerResponse.createBySuccessMsg("請先登錄"); } String orderid = user.getId() + "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); String repson = CmcPayTool.submitOrder(paramString2, orderid, paramString1, request); JSONObject json = JSONObject.fromObject(repson); //JSONObject data = (JSONObject) json.get("data"); return ServerResponse.createBySuccess(json); } @Override public ServerResponse juheh5pay(String paramString1, String paramString2, HttpServletRequest request) throws Exception { User user = iUserService.getCurrentRefreshUser(request); if (user == null){ return ServerResponse.createBySuccessMsg("請先登錄"); } String orderid = user.getId() + "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); String repson = CmcPayTool.submitOrderH5(paramString2, orderid, paramString1); JSONObject json = JSONObject.fromObject(repson); return ServerResponse.createBySuccess(json); } @Override public ServerResponse juhenewpayNotify(HttpServletRequest request) throws UnsupportedEncodingException { LinkedMap map = new LinkedMap(); String out_trade_no = request.getParameter("out_trade_no"); String[] arr = out_trade_no.split("_"); map.put("amount", (String) request.getParameter("amount")); map.put("appid", (String) request.getParameter("appid")); map.put("currency_type", (String) request.getParameter("currency_type")); map.put("goods_name", (String) request.getParameter("goods_name")); map.put("out_trade_no", out_trade_no); map.put("pay_id", (String) request.getParameter("pay_id")); map.put("pay_no", (String) request.getParameter("pay_no")); map.put("payment", (String) request.getParameter("payment")); map.put("resp_code", (String) request.getParameter("resp_code")); map.put("resp_desc", URLDecoder.decode((String) request.getParameter("resp_desc"), "UTF-8")); map.put("sign_type", (String) request.getParameter("sign_type")); map.put("tran_amount", (String) request.getParameter("tran_amount")); map.put("version", (String) request.getParameter("version")); String _sign = CmcPayOuterRequestUtil.getSign(map, CmcPayConfig.KEY); if ("00".equals((String) request.getParameter("resp_code")) && _sign.equals((String) request.getParameter("sign"))) { iUserService.updateUserAmt((Double) map.get("amount"), new Integer(arr[0])); // response.getWriter().println("success"); } else { // response.getWriter().println("error"); } return null; } public static Map convertRequestParamsToMap(HttpServletRequest request) { Map retMap = new HashMap(); Set> entrySet = request.getParameterMap().entrySet(); for (Map.Entry entry : entrySet) { String name = entry.getKey(); String[] values = entry.getValue(); int valLen = values.length; if (valLen == 1) { retMap.put(name, values[0]); } else if (valLen > 1) { StringBuilder sb = new StringBuilder(); for (String val : values) { sb.append(",").append(val); } retMap.put(name, sb.toString().substring(1)); } else { retMap.put(name, ""); } } return retMap; } }