package com.supplier.controller; import com.supplier.model.*; import com.supplier.service.PersonalServce; import com.supplier.service.SupplierReleaseService; import com.supplier.service.WxPayService; import com.supplier.util.ParsingToken; import com.supplier.util.SnowflakeUtil; import com.supplier.util.WXPayUtil; import com.supplier.vx.WxLogin; import com.supplier.vx.pay.HttpUtil; import com.supplier.util.PayToolUtil; import com.supplier.vx.pay.WxPayUtils; import com.supplier.vx.pay.doXMLParse; import org.jdom2.JDOMException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.math.BigDecimal; import java.util.*; /** * app支付 */ @RestController @RequestMapping("appPay") public class WxPayAppController extends WxPayUtils { private SnowflakeUtil snowflakeUtil = new SnowflakeUtil(1, 1, 1); @Autowired private WxPayService wxPayService; @Autowired private SupplierReleaseService supplierReleaseService; @Autowired private WXLoginController wxLoginController; @Autowired private PersonalServce personalServce; @Autowired private WxLogin wxLogin; /** * app预支付 * @param price 金额 * @return 返回结果 */ @RequestMapping("wxPayApp") @ResponseBody public Map wxPayApp(String price, String attach){ Map map = new HashMap<>(); try{ if(price.equals("0")){ map.put("errMsg", "付款金额错误"); map.put("msg", "500"); return map; } //拼接参数 WXPayUtil wxPayUtil = new WXPayUtil(); //微信工具类 PayToolUtil payToolUtil = new PayToolUtil();//数据转换工具类 String outTradeNo = wxPayUtil.getOrderNo(); String nonce_str = wxPayUtil.generateNonceStr(); SortedMap packageParams = new TreeMap(); //获取订单金额 SupplierRelease supplierRelease = new SupplierRelease().setUuid(attach); List list = supplierReleaseService.getSupplierRelease(supplierRelease); packageParams.put("appid", APPID);//app_id---需要申请 packageParams.put("attach", attach);//报价单编号 packageParams.put("body", "途丫-" + outTradeNo);//商品参数信息 packageParams.put("fee_type", "CNY");//货币类型 packageParams.put("mch_id", MCHID);//微信商户账号--需要申请 packageParams.put("nonce_str", nonce_str);//32位不重复的编号 packageParams.put("notify_url", NOTIFY_URL);//回调页面--这个是回调接口 packageParams.put("out_trade_no", outTradeNo);//订单编号 packageParams.put("spbill_create_ip", CREATE_IP);//金额 packageParams.put("total_fee", wxPayUtil.getMoney(list.get(0).getPriceAll()));//金额 packageParams.put("trade_type", "APP");//支付类型 // 签名 String sign = payToolUtil.createSign("UTF-8", packageParams, KEY); packageParams.put("sign", sign); // 将请求参数转换为xml格式的string String requestXML = payToolUtil.getRequestXml(packageParams); // 调用微信支付统一下单接口 String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML); //xml返回结果转换 Map mapVal = wxPayUtil.xmlToMap(resXml); if(null == mapVal.get("prepay_id")){ throw new Exception("获取预支付id失败"); } Map mapVal1 = new HashMap<>(); String time = String.valueOf(wxPayUtil.getCurrentTimestamp()); mapVal1.put("outTradeNo", outTradeNo);//自生成订单号 mapVal1.put("prepayId", mapVal.get("prepay_id"));//微信订单号 mapVal1.put("nonceStr", nonce_str); //不重复编号 mapVal1.put("time", time); //不重复编号 mapVal1.put("sign", wxPayUtil.singGenerate(packageParams, mapVal.get("prepay_id"), KEY, time, nonce_str)); //签名 map.put("msg", "200"); map.put("data", mapVal1); WxPay wxPay1 = wxPayService.getRefundVal(attach);//获取付该报价单付款的信息 // if(null != wxPay1){ // throw new Exception("请勿重复支付"); // } //生成uuid // String uuid = UUID.randomUUID().toString().replace("-", ""); // WxPay wxPay = new WxPay() // .setUuid(uuid) // .setMchId(MCHID) // .setReleaseUuid(attach) // .setCodeUrl((String) map.get("code_url")) // .setOutTradeNo(outTradeNo) // .setTotalFee(price) // .setBody("途丫-" + outTradeNo); // wxPayService.pay(wxPay); }catch (Exception e){ e.printStackTrace(); map.put("msg", "500"); map.put("errMsg", "服务器请求异常,请稍后再试"); } return map; } /** * app支付回调 * @param request 参数 * @param response 参数 * @return 返回结果 */ @RequestMapping("appNotify") @ResponseBody public String appNotify(HttpServletRequest request, HttpServletResponse response) throws Exception { //读取参数 InputStream inputStream ; StringBuffer sb = null; try { sb = new StringBuffer(); inputStream = request.getInputStream(); String s ; BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); while ((s = in.readLine()) != null){ sb.append(s); } in.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } //解析xml成map Map mapVal = new HashMap(); WXPayUtil wxPayUtil = new WXPayUtil(); //微信工具类 try { mapVal = wxPayUtil.xmlToMap(sb.toString()); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //过滤空 设置 TreeMap SortedMap packageParams = new TreeMap(); Iterator it = mapVal.keySet().iterator(); while (it.hasNext()) { String parameter = (String) it.next(); String parameterValue = mapVal.get(parameter); String v = ""; if(null != parameterValue) { v = parameterValue.trim(); } packageParams.put(parameter, v); } //判断签名是否正确 if(PayToolUtil.isTenpaySign("UTF-8", packageParams, KEY)) { //业务处理 String resXml = ""; if("SUCCESS".equals((String)packageParams.get("result_code"))){ //生成uuid String uuid = UUID.randomUUID().toString().replace("-", ""); WxPay wxPay = new WxPay() .setUuid(uuid) .setReleaseUuid((String)packageParams.get("attach")) .setFeeType((String)packageParams.get("fee_type")) .setMchId((String)packageParams.get("mch_id")) .setNonceStr((String)packageParams.get("nonce_str")) .setOutTradeNo((String)packageParams.get("out_trade_no")) .setTotalFee((float)Integer.parseInt((String)packageParams.get("total_fee")) / 100 + "") .setTradeType((String)packageParams.get("trade_type")) .setPrepayId((String)packageParams.get("transaction_id")) .setOpenId((String)packageParams.get("openid")) .setTimeEnd((String)packageParams.get("time_end")) .setPayType("微信支付"); //如果自定义参数是gysTopUp则代表的是供应商充值余额 if(((String) packageParams.get("attach")).indexOf("gysTopUp") != -1){ WxPay buySupplier = new WxPay() .setCode(((String) packageParams.get("attach")).split(",")[2]) .setUuid(((String) packageParams.get("attach")).split(",")[1]) .setTotalFee((float)Integer.parseInt((String)packageParams.get("total_fee")) / 100 + "") .setPayType("微信支付"); //充值信息入库 WxPay wxPayBuy = new WxPay() .setCode(((String) packageParams.get("attach")).split(",")[2]) .setUuid(((String) packageParams.get("attach")).split(",")[1]) .setPayType("微信支付") .setTotalFee((float)Integer.parseInt((String)packageParams.get("total_fee")) / 100 + ""); wxPayService.buySupplierBalance(wxPayBuy);//充值记录 wxPayService.updateBuySupplier(buySupplier); //金额录入 } else if(((String) packageParams.get("attach")).indexOf("gysOfferNum") != -1){ //报价单次数购买 BuyOfferNum buyOfferNum = new BuyOfferNum() .setCode(((String) packageParams.get("attach")).split(",")[2]) .setUuid(((String) packageParams.get("attach")).split(",")[1]) .setPayAmount((float)Integer.parseInt((String)packageParams.get("total_fee")) / 100 + "") .setOfferNum(((String) packageParams.get("attach")).split(",")[3]) .setPayType("微信支付"); //购买次数信息入库 BuyOfferNum buyOfferNumAdd = new BuyOfferNum() .setUuid(((String) packageParams.get("attach")).split(",")[1]) .setOfferNum(((String) packageParams.get("attach")).split(",")[3]) .setCode(((String) packageParams.get("attach")).split(",")[2]) .setPayType("微信支付") .setPayAmount((float)Integer.parseInt((String)packageParams.get("total_fee")) / 100 + ""); personalServce.addBuyOfferNum(buyOfferNumAdd); //充值记录 wxPayService.updateBuyOfferNum(buyOfferNum);//次数录入 } else { //报价单购买 wxPayService.pay(wxPay); //修改报价单信息 SupplierRelease supplierRelease = new SupplierRelease().setUuid((String)packageParams.get("attach")); List list = supplierReleaseService.getSupplierRelease(supplierRelease); List list1 = supplierReleaseService.getSupplierReleaseType(list.get(0).getDemandUuid()); for(SupplierRelease supplierRelease1 : list1){ //修改定制单状态判断是否是当前报价单的供应商 SupplierRelease supplierRelease2 = new SupplierRelease() .setCode(supplierRelease1.getCode()) .setDemandUuid(supplierRelease1.getDemandUuid()); if(supplierRelease1.getCode().equals(list.get(0).getCode())){ //修改状态为已付费 supplierRelease2.setOrderType("2"); supplierReleaseService.updatePrivateType(supplierRelease2); //用户购买报价单后将100%的资金转入供应商余额 Map mapCommis = supplierReleaseService.getSitesInfo();//查询系统配置 BigDecimal bigDecimal = new BigDecimal(wxPay.getTotalFee());//支付金额 BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(mapCommis.get("percentage_fee")));//平台手续费 BigDecimal poundage = bigDecimal.multiply(bigDecimal1);//手续费 //实际金额 - 手续费 = 供应商收入 poundage = bigDecimal.subtract(poundage); Supplier supplier = new Supplier() .setCode(list.get(0).getCode()) .setBalanceOf(String.valueOf(poundage)); wxPayService.addSupplierBalanceOf(supplier); } else { supplierRelease2.setOrderType("9"); supplierReleaseService.updatePrivateType(supplierRelease2);//修改状态 supplierReleaseService.updateSupplierOffer(supplierRelease2);//返回报价单次数 } } } resXml = "" + "" + "" + " "; } else { resXml = "" + "" + "" + " "; return ("fail"); } try { BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); out.write(resXml.getBytes()); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } else { throw new Exception("签名验证失败"); } return ("success"); } /** * 供应商充值小程序 * @param price 金额 */ @GetMapping("wxpaySupplierBalanceJSAPI") public Map wxpaySupplierBalanceJSAPI(String price, String code, HttpServletRequest request) throws IOException { //当前时间 String currTime = PayToolUtil.getCurrTime(); String strTime = currTime.substring(8, currTime.length()); String strRandom = String.valueOf(PayToolUtil.buildRandom(4)); String nonce_str = strTime + strRandom; //获取token Map userMap = ParsingToken.tokenParsing(request); //订单号 WXPayUtil wxPayUtil = new WXPayUtil(); //微信工具类 PayToolUtil payToolUtil = new PayToolUtil();//数据转换工具类 String out_trade_no = wxPayUtil.getOrderNo(); SortedMap packageParams = new TreeMap(); String uuid = snowflakeUtil.nextId() + "";//不重复编号 packageParams.put("appid", wxLogin.getAppIdJSAPI());//公众账号ID packageParams.put("attach", "gysTopUp" + "," + uuid + "," + userMap.get("code"));//自定义信息 packageParams.put("mch_id", MCHID);//商户号 packageParams.put("body", "途丫-" + out_trade_no);//商品描述 packageParams.put("out_trade_no", out_trade_no);//商户订单号 packageParams.put("nonce_str", nonce_str);//随机字符串 packageParams.put("total_fee", wxPayUtil.getMoney(price)); //订单金额 packageParams.put("spbill_create_ip", CREATE_IP);//终端IP APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP packageParams.put("notify_url", NOTIFY_URL);//通知地址 异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数 packageParams.put("trade_type", "JSAPI"); Map mapUser = wxLoginController.wxLoginJSAPI(code); packageParams.put("openid", (String) mapUser.get("openId"));//支付者 // 签名 String sign = payToolUtil.createSign("UTF-8", packageParams, KEY); packageParams.put("sign", sign); // 将请求参数转换为xml格式的string String requestXML = payToolUtil.getRequestXml(packageParams); // 调用微信支付统一下单接口 String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML); // 解析微信支付结果 Map map = null; try { map = doXMLParse.doXMLParse(resXml); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //返回前端生成二维码 Map resultMap = new HashMap<>(); String time = String.valueOf(wxPayUtil.getCurrentTimestamp()); resultMap.put("outTradeNo", out_trade_no);//自生成订单号 resultMap.put("prepayId", map.get("prepay_id"));//微信订单号 resultMap.put("nonceStr", nonce_str); //不重复编号 resultMap.put("time", time); //不重复编号 resultMap.put("sign", wxPayUtil.singGenerate(packageParams, (String) map.get("prepay_id"), KEY, time, nonce_str)); //签名 resultMap.put("key", KEY); Map returnMap = new HashMap<>();//返回结果 returnMap.put("data", resultMap); returnMap.put("msg", "200"); return returnMap; } /** * 供应商购买次数 小程序 * @param offerNum 次数 * @param request 参数 * @return 返回结果 */ @GetMapping("wxpaySupplierOfferNumJSAPI") public Map wxpaySupplierOfferNumJSAPI(String offerNum, String code, HttpServletRequest request) throws IOException { //当前时间 String currTime = PayToolUtil.getCurrTime(); String strTime = currTime.substring(8, currTime.length()); String strRandom = String.valueOf(PayToolUtil.buildRandom(4)); String nonce_str = strTime + strRandom; //获取token Map userMap = ParsingToken.tokenParsing(request); Map map1 = personalServce.getByNumber();//获取报价单单价 Map map2 = (Map) map1.get("data"); String price = (Integer.parseInt(offerNum) * Double.parseDouble(String.valueOf(map2.get("power_unit")))) + ""; //购买次数 * 报价单单价 //订单号 WXPayUtil wxPayUtil = new WXPayUtil(); //微信工具类 PayToolUtil payToolUtil = new PayToolUtil();//数据转换工具类 String out_trade_no = wxPayUtil.getOrderNo(); SortedMap packageParams = new TreeMap(); String uuid = snowflakeUtil.nextId() + "";//不重复编号 packageParams.put("appid", wxLogin.getAppIdJSAPI());//公众账号ID packageParams.put("attach", "gysOfferNum" + "," + uuid + "," + userMap.get("code") + "," + offerNum);//自定义信息 packageParams.put("mch_id", MCHID);//商户号 packageParams.put("body", "途丫-" + out_trade_no);//商品描述 packageParams.put("out_trade_no", out_trade_no);//商户订单号 packageParams.put("nonce_str", nonce_str);//随机字符串 packageParams.put("total_fee", wxPayUtil.getMoney(price)); //订单金额信息 packageParams.put("spbill_create_ip", CREATE_IP);//终端IP APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP packageParams.put("notify_url", NOTIFY_URL);//通知地址 异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数 packageParams.put("trade_type", "JSAPI");//小程序支付 Map mapUser = wxLoginController.wxLoginJSAPI(code); packageParams.put("openid", (String) mapUser.get("openId"));//支付者 // 签名 String sign = payToolUtil.createSign("UTF-8", packageParams, KEY); packageParams.put("sign", sign); // 将请求参数转换为xml格式的string String requestXML = payToolUtil.getRequestXml(packageParams); // 调用微信支付统一下单接口 String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML); System.out.println(resXml); // 解析微信支付结果 Map map = null; try { map = doXMLParse.doXMLParse(resXml); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //返回前端生成二维码 Map resultMap = new HashMap<>(); String time = String.valueOf(wxPayUtil.getCurrentTimestamp()); resultMap.put("outTradeNo", out_trade_no);//自生成订单号 resultMap.put("prepayId", map.get("prepay_id"));//微信订单号 resultMap.put("nonceStr", nonce_str); //不重复编号 resultMap.put("time", time); //不重复编号 resultMap.put("sign", wxPayUtil.singGenerate(packageParams, (String) map.get("prepay_id"), KEY, time, nonce_str)); //签名 resultMap.put("key", KEY); Map returnMap = new HashMap<>();//返回结果 returnMap.put("data", resultMap); returnMap.put("msg", "200"); return returnMap; } }