• 微信支付


    调用的接口

    public Map<String, String> signPayData(RegOrderInfo regOrderInfo) {
         
            String total_fee =String.valueOf((new BigDecimal(regOrderInfo.getFee()).multiply(new BigDecimal("100"))).intValue());
            String subAppId = WX_TokenUtil.appId;//.getDictValue(TourConst.TOUR_APP_ID, TourConst.TOUR_WEIXIN_PARAM, TourConst.TOUR_APP_ID);    //小程序ID
            String appId = ("0".equals(regOrderInfo.getSubMchId())?subAppId:TourConst.PAY_APP_ID_SERVER);    //服务商关联的服务号ID
            String mchId = ("0".equals(regOrderInfo.getSubMchId())?TourConst.PAY_MCHID:TourConst.PAY_MCHID_SERVER);    //服务商号
            String subMchId = regOrderInfo.getSubMchId();    //子商户号
    
            String nonceStr = PayUtil.getRandomStringByLength(32);
            //组装参数,用户生成统一下单接口的签名
            Map<String, String> packageParams = new HashMap<String, String>();
            packageParams.put("appid", appId);
            packageParams.put("mch_id", mchId);
            if(!"0".equals(regOrderInfo.getSubMchId())) {
                packageParams.put("sub_appid", subAppId);
                packageParams.put("sub_mch_id", subMchId);
                packageParams.put("sub_openid", regOrderInfo.getOpenId());
            } else {
                packageParams.put("openid", regOrderInfo.getOpenId());
            }
            packageParams.put("nonce_str", nonceStr);    //32位随机字符串
            packageParams.put("body", regOrderInfo.getName());    //商品描述
            packageParams.put("out_trade_no", regOrderInfo.getOrderSn());//商户订单号
            packageParams.put("total_fee", total_fee);//支付金额,这边需要转成字符串类型,否则后面的签名会失败
            packageParams.put("notify_url", ("0".equals(regOrderInfo.getSubMchId())?TourConst.SIGN_NOTIFY_URL:TourConst.SIGN_PAY_NOTIFY_SERVER_URL));//支付成功后的回调地址
            packageParams.put("trade_type", "JSAPI");//支付方式 小程序为JSAPI
    
            String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
            //MD5运算生成签名,这里是第一次签名,用于调用统一下单接口
            String mysign = PayUtil.sign(prestr, ("0".equals(regOrderInfo.getSubMchId())?TourConst.PAY_KEY:TourConst.PAY_KEY_SERVER), "utf-8").toUpperCase();
    
            //拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去
            String xml = "<xml>" + "<appid>" + appId + "</appid>"
                + "<body><![CDATA[" + regOrderInfo.getName() + "]]></body>"
                + "<mch_id>" + mchId + "</mch_id>"
                + "<nonce_str>" + nonceStr + "</nonce_str>"
                + "<notify_url>" + TourConst.SIGN_NOTIFY_URL + "</notify_url>"
                + "<openid>" + regOrderInfo.getOpenId() + "</openid>"
                + "<out_trade_no>" + regOrderInfo.getOrderSn() + "</out_trade_no>"
                /* + "<spbill_create_ip>" + paymentPo.getSpbill_create_ip() + "</spbill_create_ip>" */
                + "<total_fee>" + total_fee + "</total_fee>"
                + "<trade_type>" + "JSAPI" + "</trade_type>"
                + "<sign>" + mysign + "</sign>"
                + "</xml>";
    
            String xmlServer = "<xml>" + "<appid>" + appId + "</appid>"
                + "<sub_appid>" + subAppId + "</sub_appid>"
                + "<sub_mch_id>" + subMchId + "</sub_mch_id>"
                + "<body><![CDATA[" + regOrderInfo.getName() + "]]></body>"
                + "<mch_id>" + mchId + "</mch_id>"
                + "<nonce_str>" + nonceStr + "</nonce_str>"
                + "<notify_url>" + TourConst.SIGN_PAY_NOTIFY_SERVER_URL + "</notify_url>"
                //+ "<openid>" + regOrderInfo.getOpenId() + "</openid>"
                + "<sub_openid>" + regOrderInfo.getOpenId() + "</sub_openid>"
                + "<out_trade_no>" + regOrderInfo.getOrderSn() + "</out_trade_no>"
                /* + "<spbill_create_ip>" + paymentPo.getSpbill_create_ip() + "</spbill_create_ip>" */
                + "<total_fee>" + total_fee + "</total_fee>"
                + "<trade_type>" + "JSAPI" + "</trade_type>"
                + "<sign>" + mysign + "</sign>"
                + "</xml>";
    
            if(!"0".equals(regOrderInfo.getSubMchId())) {
                System.out.println("调试模式_统一下单接口 请求xmlServer数据:" + xmlServer);
            } else {
                System.out.println("调试模式_统一下单接口 请求XML数据:" + xml);
            }
            //调用统一下单接口,并接受返回的结果
            String res = PayUtil.httpRequest(TourConst.PAY_UNIFIED_ORDER_URL, "POST", "0".equals(regOrderInfo.getSubMchId())?xml:xmlServer);
            System.out.println("调试模式_统一下单接口 返回XML数据:" + res);
            // 将解析结果存储在HashMap中
            Map<String, String> result = new HashMap<String, String>();//返回给小程序端需要的参数
            try {
                Map map = PayUtil.doXMLParse(res);
                String return_code = (String) map.get("return_code");//返回状态码
                String prepay_id = null;
                if(return_code=="SUCCESS"||return_code.equals(return_code)){
                    prepay_id = (String) map.get("prepay_id");//返回的预付单信息
                    result.put("returnCode", return_code);
                    result.put("nonceStr", nonceStr);
                    result.put("package", "prepay_id=" + prepay_id);
                    Long timeStamp = System.currentTimeMillis() / 1000;
                    result.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串,不然小程序端调用wx.requestPayment方法会报签名错误
                    //拼接签名需要的参数
                    String stringSignTemp = "appId=" + ("0".equals(regOrderInfo.getSubMchId())?appId:subAppId) + "&nonceStr=" + nonceStr + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;
                    //再次签名,这个签名用于小程序端调用wx.requesetPayment方法
                    String paySign = PayUtil.sign(stringSignTemp, ("0".equals(regOrderInfo.getSubMchId())? TourConst.PAY_KEY:TourConst.PAY_KEY_SERVER), "utf-8").toUpperCase();
                    result.put("paySign", paySign);
                }
                result.put("appid", appId);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            return result;
        }

    使用的方法

    public class PayUtil {
    
        /**  
         * 签名字符串  
         * @param text需要签名的字符串  
         * @param key 密钥  
         * @param input_charset编码格式  
         * @return 签名结果  
         */   
        public static String sign(String text, String key, String input_charset) {   
            text = text + "&key=" + key;   
            return DigestUtils.md5Hex(getContentBytes(text, input_charset));   
        }   
        /**  
         * 签名字符串  
         *  @param text需要签名的字符串  
         * @param sign 签名结果  
         * @param key密钥  
         * @param input_charset 编码格式  
         * @return 签名结果  
         */   
        public static boolean verify(String text, String sign, String key, String input_charset) {   
            text = text + key;   
            String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));   
            if (mysign.equals(sign)) {   
                return true;   
            } else {   
                return false;   
            }   
        }   
        /**  
         * @param content  
         * @param charset  
         * @return  
         * @throws SignatureException  
         * @throws UnsupportedEncodingException  
         */   
        public static byte[] getContentBytes(String content, String charset) {   
            if (charset == null || "".equals(charset)) {   
                return content.getBytes();   
            }   
            try {   
                return content.getBytes(charset);   
            } catch (UnsupportedEncodingException e) {   
                throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);   
            }   
        }   
        
        private static boolean isValidChar(char ch) {   
            if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))   
                return true;   
            if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))   
                return true;// 简体中文汉字编码   
            return false;   
        }   
        /**  
         * 除去数组中的空值和签名参数  
         * @param sArray 签名参数组  
         * @return 去掉空值与签名参数后的新签名参数组  
         */   
        public static Map<String, String> paraFilter(Map<String, String> sArray) {   
            Map<String, String> result = new HashMap<String, String>();   
            if (sArray == null || sArray.size() <= 0) {   
                return result;   
            }   
            for (String key : sArray.keySet()) {   
                String value = sArray.get(key);   
                if (value == null || value.equals("") || key.equalsIgnoreCase("sign")   
                        || key.equalsIgnoreCase("sign_type")) {   
                    continue;   
                }   
                result.put(key, value);   
            }   
            return result;   
        }   
        /**  
         * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串  
         * @param params 需要排序并参与字符拼接的参数组  
         * @return 拼接后字符串  
         */   
        public static String createLinkString(Map<String, String> params) {   
            List<String> keys = new ArrayList<String>(params.keySet());   
            Collections.sort(keys);   
            String prestr = "";   
            for (int i = 0; i < keys.size(); i++) {   
                String key = keys.get(i);   
                String value = params.get(key);   
                if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符   
                    prestr = prestr + key + "=" + value;   
                } else {   
                    prestr = prestr + key + "=" + value + "&";   
                }   
            }   
            return prestr;   
        }   
        /**  
         *  
         * @param requestUrl请求地址  
         * @param requestMethod请求方法  
         * @param outputStr参数  
         */   
        public static String httpRequest(String requestUrl,String requestMethod,String outputStr){   
            // 创建SSLContext   
            StringBuffer buffer = null;   
            try{   
                URL url = new URL(requestUrl);   
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
                conn.setRequestMethod(requestMethod);   
                conn.setDoOutput(true);   
                conn.setDoInput(true);   
                conn.connect();   
                //往服务器端写内容   
                if(null !=outputStr){   
                    OutputStream os=conn.getOutputStream();   
                    os.write(outputStr.getBytes("utf-8"));   
                    os.close();   
                }   
                // 读取服务器端返回的内容   
                InputStream is = conn.getInputStream();   
                InputStreamReader isr = new InputStreamReader(is, "utf-8");   
                BufferedReader br = new BufferedReader(isr);   
                buffer = new StringBuffer();   
                String line = null;   
                while ((line = br.readLine()) != null) {   
                    buffer.append(line);   
                }   
                br.close();
            }catch(Exception e){   
                e.printStackTrace();   
            }
            return buffer.toString();
        }     
        public static String urlEncodeUTF8(String source){   
            String result=source;   
            try {   
                result=java.net.URLEncoder.encode(source, "UTF-8");   
            } catch (UnsupportedEncodingException e) {   
                // TODO Auto-generated catch block   
                e.printStackTrace();   
            }   
            return result;   
        } 
        /**
         * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
         * @param strxml
         * @return
         * @throws JDOMException
         * @throws IOException
         */
        public static Map doXMLParse(String strxml) throws Exception {
            if(null == strxml || "".equals(strxml)) {
                return null;
            }
            
            Map m = new HashMap();
            
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                StringReader sr = new StringReader(strxml);
                InputSource is = new InputSource(sr);
                Document document = db.parse(is);
    
                Element root = document.getDocumentElement();
                NodeList nodeList = root.getChildNodes();
                System.out.println(nodeList.getLength());
                for(int i=0;i<nodeList.getLength();i++) {
                    Node node = nodeList.item(i);
                    String nodeName = node.getNodeName();
                    String nodeValue = node.getTextContent();
                    
                    System.out.println("nodeName = " + nodeName + "; nodeValue = " + nodeValue);
                    m.put(nodeName, nodeValue);
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            return m;
        }
    
        public static InputStream String2Inputstream(String str) {
            return new ByteArrayInputStream(str.getBytes());
        }
        
        /**
         * 获取一定长度的随机字符串
         * @param length 指定字符串长度
         * @return 一定长度的字符串
         */
        public static String getRandomStringByLength(int length) {
            String base = "abcdefghijklmnopqrstuvwxyz0123456789";
            Random random = new Random();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < length; i++) {
                int number = random.nextInt(base.length());
                sb.append(base.charAt(number));
            }
            return sb.toString();
        }
    
    
    }

    回调

    BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while((line = br.readLine()) != null){
                sb.append(line);
            }
            br.close();
            //sb为微信返回的xml
            String notityXml = sb.toString();
            String resXml = "";
            System.out.println("普通商户接收到的报文:" + notityXml);
            Map map = PayUtil.doXMLParse(notityXml);
            String returnCode = (String) map.get("return_code");
            if("SUCCESS".equals(returnCode)){
                //验证签名是否正确
                Map<String, String> validParams = PayUtil.paraFilter(map);  //回调验签时需要去除sign和空值参数
                String validStr = PayUtil.createLinkString(validParams);//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
                String sign = PayUtil.sign(validStr, RegConst.PAY_KEY, "utf-8").toUpperCase();//拼装生成服务器端验证的签名
                // 因为微信回调会有八次之多,所以当第一次回调成功了,那么我们就不再执行逻辑了
                //根据微信官网的介绍,此处不仅对回调的参数进行验签,还需要对返回的金额与系统订单的金额进行比对等
                if(sign.equals(map.get("sign"))){
                    /**此处添加自己的业务逻辑代码start**/
                    String totalFee = (String)map.get("total_fee");
                    String transactionId = (String)map.get("transaction_id");
                    String outTradeNo = (String)map.get("out_trade_no");
                    String mchId = (String)map.get("mch_id");
                    String subMchId = (String)map.get("sub_mch_id");
                    RegOrderInfo tourOrderInfo = iRegOrderInfoService.getOne(new LambdaQueryWrapper<RegOrderInfo>().eq(RegOrderInfo::getOrderSn, outTradeNo));
                    int fee = new BigDecimal(tourOrderInfo.getFee()).multiply(new BigDecimal("100")).intValue();
                    if(tourOrderInfo!=null) {
                        if("UNPAY".equals(tourOrderInfo.getStatus()) && Integer.valueOf(totalFee).intValue()==fee) {
                            //订单未支付状态修改为已支付
                            tourOrderInfo.setStatus("PAID");
                            tourOrderInfo.setPayTime(LocalDateTime.now());
                            tourOrderInfo.setTransactionId(transactionId);
                            tourOrderInfo.setMchId(mchId);
                            tourOrderInfo.setSubMchId(subMchId);
                            iRegOrderInfoService.updateById(tourOrderInfo);
                            //更新购买记录表状态
                            ApplyInfo applyInfo =  applyInfoService.getOne(new LambdaQueryWrapper<ApplyInfo>().eq(ApplyInfo::getId, tourOrderInfo.getRegApplyId()));
                            applyInfo.setPayStatus("PAID");
                            applyInfo.setPayTime(LocalDateTime.now());
                            applyInfoService.updateById(applyInfo);
                        }
                    }
                    /**此处添加自己的业务逻辑代码end**/
                    //通知微信服务器已经支付成功
                    resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                } else {
                    System.out.println("普通商户微信支付回调失败!签名不一致");
                }
            }else{
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            }
            System.out.println(resXml);
            System.out.println("普通商户微信支付回调数据结束");
    
            BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
  • 相关阅读:
    elselect下拉数据过多解决办法
    移动端开发遇到的问题汇总
    win7系统可关闭的服务
    安装Qcreator2.5 + Qt4.8.2 + MinGW_gcc_4.4 (win7环境)
    学习Qt的资源
    c++学习 定位new表达式
    eltablecolumn中添加echarts
    js对象数组封装,形成表格,并在表格中添加echarts直折线图
    Unity学习笔记3:随机数和动画脚本
    关于Unity的一些概念和语法
  • 原文地址:https://www.cnblogs.com/-mzh/p/13084885.html
Copyright © 2020-2023  润新知