微信支付Java后台—app篇

作者: Helloword_Cc | 来源:发表于2019-05-10 15:08 被阅读237次

    app的微信支付Java实现

    首先我们需要拿到微信的商户号,appid,秘钥等信息。在微信支付自己账号下获取。
    之后我们查看微信支付统一下单的api接口文档。
    https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1
    具体中文注释查看此网站,我们看一下xml的demo

    image.png
    具体流程:
    1:appid,mch_id(商户号),nonce_str(随机字字符串),body(内容),out_trade_no(商户订单号),fee_type(货币类型),total_fee(总金额),spbill_create_ip (终端IP:一般为服务器本机:127.0.0.1),notify_url(回调url),trade_type(交易类型:APP)这些参数生成签名(参数具体注释参看上面的网址),将生成的签名连同这些参数一起生成xml报文请求统一下单api
    2:统一下单api成功后会返回prepayid(预支付交易会话标识),将prepayid,appid,partnerid(商户号),package(Sign=WXPay),noncestr,timestamp参数再次进行签名,再将签名,连同这些参数发送到app端供其调用完成。

    流程比较啰嗦,上代码。
    首先是一些工具类:
    1: 自己微信支付基本信息类

    public class ConfigUtil {
        /**
         * 服务号相关信息
         */
        public final static String APPID = "";//服务号的应用号
        public final static String MCH_ID = "";//商户号
        public final static String API_KEY = "";//API密钥
        public final static String SIGN_TYPE = "MD5";//签名加密方式
    
    
        public final static String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";//请求下单的http
    }
    

    2 :签名类 utf-8格式

     public static String createSign(String characterEncoding, SortedMap<Object, Object> parameters) {
            StringBuffer sb = new StringBuffer();
            Set es = parameters.entrySet();
            Iterator it = es.iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String k = (String) entry.getKey();
                Object v = entry.getValue();
                if (null != v && !"".equals(v)
                        && !"sign".equals(k) && !"key".equals(k)) {
                    sb.append(k + "=" + v + "&");
                }
            }
            sb.append("key=" + ConfigUtil.API_KEY);
            String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
            return sign;
        }
    

    3:将map数组拼装成xml

     public static String getRequestXml(SortedMap<Object, Object> parameters) {
            StringBuffer sb = new StringBuffer();
            sb.append("<xml>");
            Set es = parameters.entrySet();
            Iterator it = es.iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String k = (String) entry.getKey();
                String v = (String) entry.getValue();
                if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k)) {
                    sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
                } else {
                    sb.append("<" + k + ">" + v + "</" + k + ">");
                }
            }
            sb.append("</xml>");
            return sb.toString();
        }
    

    4: SSL协议发起http请求

     /**
         * 发送https请求
         *
         * @param requestUrl    请求地址
         * @param requestMethod 请求方式(GET、POST)
         * @param outputStr     提交的数据
         * @return 返回微信服务器响应的信息
         */
        public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
            try {
                // 创建SSLContext对象,并使用我们指定的信任管理器初始化
                TrustManager[] tm = {new MyX509TrustManager()};
                SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
                sslContext.init(null, tm, new java.security.SecureRandom());
                // 从上述SSLContext对象中得到SSLSocketFactory对象
                SSLSocketFactory ssf = sslContext.getSocketFactory();
                URL url = new URL(requestUrl);
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                //conn.setSSLSocketFactory(ssf);
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches(false);
                // 设置请求方式(GET/POST)
                conn.setRequestMethod(requestMethod);
                conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                // 当outputStr不为null时向输出流写数据
                if (null != outputStr) {
                    OutputStream outputStream = conn.getOutputStream();
                    // 注意编码格式
                    outputStream.write(outputStr.getBytes("UTF-8"));
                    outputStream.close();
                }
                // 从输入流读取返回内容
                InputStream inputStream = conn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                StringBuffer buffer = new StringBuffer();
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                // 释放资源
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();
                inputStream = null;
                conn.disconnect();
                return buffer.toString();
            } catch (ConnectException ce) {
    //          log.error("连接超时:{}", ce);
            } catch (Exception e) {
    //          log.error("https请求异常:{}", e);
            }
            return null;
        }
    

    5:生成随机字符串

     public static String CreateNoncestr() {
            String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            String res = "";
            for (int i = 0; i < 16; i++) {
                Random rd = new Random();
                res += chars.charAt(rd.nextInt(chars.length() - 1));
            }
            return res;
        }
    

    6 将返回的xml 转换成map数组

     /**
         * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
         *
         * @param strxml
         * @return
         * @throws JDOMException
         * @throws IOException
         */
        public static Map doXMLParse(String strxml) throws JDOMException, IOException {
            strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
    
            if (null == strxml || "".equals(strxml)) {
                return null;
            }
    
            Map m = new HashMap();
    
            InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(in);
            Element root = doc.getRootElement();
            List list = root.getChildren();
            Iterator it = list.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String k = e.getName();
                String v = "";
                List children = e.getChildren();
                if (children.isEmpty()) {
                    v = e.getTextNormalize();
                } else {
                    v = XMLUtil.getChildrenText(children);
                }
    
                m.put(k, v);
            }
    
            //关闭流
            in.close();
    
            return m;
        }
    

    基本工具类都在这里,接下来就是下单的controller类,
    因为含有业务逻辑的代码就不上了,直接贴下单的那部分

    //测试环境
    //微信默认从单位为分,所以用此方法将单位调整成元
      int price100 = new BigDecimal(price).multiply(new BigDecimal(100)).intValue();
                SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
                parameters.put("appid", ConfigUtil.APPID);
                parameters.put("mch_id", ConfigUtil.MCH_ID);
                parameters.put("nonce_str", noPayOrder.getWxOutTradeNo());
                parameters.put("body", message);
                parameters.put("out_trade_no", UUID.randomUUID().toString().substring(0, 15)); //订单id
                parameters.put("fee_type", "CNY");
                parameters.put("total_fee", String.valueOf(price100));
                parameters.put("spbill_create_ip", "127.0.0.1");
                parameters.put("notify_url", returnUrl);
                parameters.put("trade_type", "APP");
                //设置签名
                String sign = PayCommonUtil.createSign("UTF-8", parameters);
                parameters.put("sign", sign);
                //封装请求参数结束
                String requestXML = PayCommonUtil.getRequestXml(parameters);
                //调用统一下单接口
                String result = PayCommonUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
                System.out.println("\n" + result);
                try {
                    /**统一下单接口返回正常的prepay_id,再按签名规范重新生成签名后,将数据传输给APP。参与签名的字段名为appId,partnerId,prepayId,nonceStr,timeStamp,package。注意:package的值格式为Sign=WXPay**/
                    Map<String, String> map = XMLUtil.doXMLParse(result);
                    SortedMap<Object, Object> parameterMap2 = new TreeMap<Object, Object>();
                    parameterMap2.put("appid", ConfigUtil.APPID);
                    parameterMap2.put("partnerid", ConfigUtil.MCH_ID);
                    parameterMap2.put("prepayid", map.get("prepay_id"));
                    parameterMap2.put("package", "Sign=WXPay");
                    parameterMap2.put("noncestr", PayCommonUtil.CreateNoncestr());
                    //本来生成的时间戳是13位,但是ios必须是10位,所以截取了一下
                    parameterMap2.put("timestamp", Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10)));
                    String sign2 = PayCommonUtil.createSign("UTF-8", parameterMap2);
                    parameterMap2.put("sign", sign2);//此 parameterMap2内容送到ios调用就可以了
                   /* landlordNew.setWxSign(sign2);
                    this.landlordNewService.update(landlordNew);*/
                    resultMap.put("code", "200");
                    resultMap.put("msg", parameterMap2);
                } catch (JDOMException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    

    将最后生成的parameterMap2内容送到ios调用就完成支付调用。

    好了支付调用成功了,用户付完款肯定是需要回调来完成支付成功后的业务逻辑了(用户成功支付后,微信会主动调用我们预先设置好的url(需要外网链接),同时微信会将:商户订单号,微信支付订单号发送给我们,我们可以通过这些来完成业务逻辑)下面为回调接口代码:

    /**
         * 微信异步通知 (签约支付)
         */
        @RequestMapping("/wxNotifySignContract")
        public void wxNotifySignContract(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
    
            try {
                //读取参数
                InputStream inputStream;
                StringBuffer 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();
                //解析xml成map
                Map<String, String> m = new HashMap<String, String>();
                m = XMLUtil.doXMLParse(sb.toString());
                for (Object keyValue : m.keySet()) {
                    System.out.println(keyValue + "=" + m.get(keyValue));
                }
                //过滤空 设置 TreeMap
                SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
                Iterator it = m.keySet().iterator();
                while (it.hasNext()) {
                    String parameter = (String) it.next();
                    String parameterValue = m.get(parameter);
    
                    String v = "";
                    if (null != parameterValue) {
                        v = parameterValue.trim();
                    }
                    packageParams.put(parameter, v);
                }
    
                //判断签名是否正确
                String resXml = "";
                if (PayCommonUtil.isTenpaySign("UTF-8", packageParams)) {
                    if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
                        // 这里是支付成功
                        //////////执行自己的业务逻辑////////////////
                        String appid = (String) packageParams.get("appid");//appid
                        String sign = (String) packageParams.get("sign");//签名
                        String total_fee = (String) packageParams.get("total_fee");//总金额
                        String mch_id = (String) packageParams.get("mch_id"); //商户号
                        String openid = (String) packageParams.get("openid");  //用户标识
    
                    //微信回调 商户号回调的商户订单号是out_trade_no
                   //(需要唯一,同一个订单号执行下单接口会报错),这里笔者使用
                  //nonce_str作为订单号,后续还需要改动。这个字段官方文档解释为随机字
                  //符串,但后来发现回调的时候返回的nonce_str跟下单填进去的nonce_str
                 //一致,所以暂时用来当订单号了。)
                        String out_trade_no = (String) packageParams.get("nonce_str"); //商户订单号
                        String transaction_id = (String) packageParams.get("transaction_id"); //微信支付订单号
                        this.contractpayReturn(appid, sign, total_fee, mch_id, openid, out_trade_no, transaction_id);
                        resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                                + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    } else {
                        logger.info("支付失败,错误信息:" + packageParams.get("err_code"));
                        resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                                + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                } else {
                    resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                            + "<return_msg><![CDATA[通知签名验证失败]]></return_msg>" + "</xml> ";
                    logger.info("通知签名验证失败");
                }
                //------------------------------
                //处理业务完毕
                //------------------------------
                BufferedOutputStream out = new BufferedOutputStream(
                        response.getOutputStream());
                out.write(resXml.getBytes());
                out.flush();
                out.close();
                logger.error("微信回调接口成功--------");
            } catch (Exception ex) {
                logger.error(ex.toString());
                ExceptionUntil.setLogger(logger, ex);
                logger.error("微信回调接口失败--------");
            }
    

    实现结果展示

    image.png
    image.png
    image.png
    image.png

    相关文章

      网友评论

        本文标题:微信支付Java后台—app篇

        本文链接:https://www.haomeiwen.com/subject/ncnooqtx.html