评论

微信app支付-java服务端

在开发中,可能需要对接微信app支付. (使用了idea的lombok插件, 没有装这个插件的,需要装一下哦)

第一步: 微信的pom.xml依赖(这里主要是对xml的解析)

<!--微信支付需要解析XML-->
<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom</artifactId>
    <version>1.1</version>
</dependency>

第二步: 微信配置WxPayConfig.java(配置请到微信开发平台查找)

/**
 * Created by NooYoo.
 * Created on 2019/7/16.
 * Description: 微信支付
 */
public class WxPayConfig {
 
    /**
     * 微信开发平台应用ID
     */
    public static final String APP_ID="your APP_ID";
    /**
     * 应用对应的凭证
     */
    public static final String APP_SECRET="your APP_SECRET";
    /**
     * 应用对应的密钥 key设置路径:微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
     */
    public static final String APP_KEY="your APP_KEY";
    /**
     * 微信支付商户号
     */
    public static final String PARTNER_ID="";
    /**
     * 微信支付商户号
     */
    public static final String MCH_ID="your MCH_ID";
    /**
     * 商户号对应的密钥
     */
    public static final String PARTNER_key="";
    /**
     * 常量固定值
     */
    public static final String GRANT_TYPE="client_credential";
    /**
     * 获取预支付id的接口url
     */
    public static String GATEURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    /**
     * 微信服务器回调通知url
     */
    public static String NOTIFY_URL = "your NOTIFY_URL";
}

支付效果:http://github.crmeb.net/u/LXT

第三步: 统一下单Wxpay.java (注意微信的0.01元 = 100哦)

/**
 * Created by NooYoo.
 * Created on 2019/7/16.
 * Description:
 */
 
@Slf4j
@RestController
public class WxPay {
 
    /**
     * 统一下单接口
     *
     * @param params
     * @return
     */
    public String wxPrePay(Map<String, Object> params) {
        int price100 = new BigDecimal(String.valueOf(params.get("price"))).multiply(new BigDecimal(100)).intValue(); //
        if (price100 <= 0) {
            return null;
        }
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid",  WxPayConfig.APP_ID);
        parameters.put("mch_id",  WxPayConfig.MCH_ID);
        parameters.put("nonce_str", WxPayCommonUtils.CreateNoncestr());
        parameters.put("body", params.get("body"));
        parameters.put("out_trade_no", params.get("serialNumber")); // 流水号
        parameters.put("fee_type", "CNY");
        parameters.put("total_fee", String.valueOf(price100)); // 订单金额
        parameters.put("spbill_create_ip", params.get("spbillCreateIp"));
        parameters.put("notify_url", params.get("notifyURL"));  //回调地址
        parameters.put("trade_type", "APP");
        parameters.put("attach", params.get("attach")); // 原始订单号(即你的业务系统订单号)
        //设置签名
        String sign = WxPayCommonUtils.createSign("UTF-8", parameters,  WxPayConfig.APP_KEY);
        parameters.put("sign", sign);
        System.out.println("parameters:" + parameters);
        //封装请求参数结束
        String requestXML = WxPayCommonUtils.getRequestXml(parameters);
        System.out.println("requestXML:" + requestXML);
        //调用统一下单接口
        String result = WxPayCommonUtils.httpsRequest( WxPayConfig.GATEURL, "POST", requestXML);
        SortedMap<Object, Object> parameterMap = new TreeMap<>();
        try {
            System.out.println("result:" + result);
            // 统一下单接口返回正常的prepay_id,再按签名规范重新生成签名后,将数据传输给APP。参与签名的字段名为appId,partnerId,prepayId,nonceStr,timeStamp。注意:package的值格式为Sign=WXPay
            Map map = XMLUtils.doXMLParse(result);
            log.info("微信统一下单接口===>>>" + map);
            if (null != map && "FAIL".equals(map.get("return_code"))) {
                return null;
            }
            parameterMap.put("appid",  WxPayConfig.APP_ID); // TODO 这里需要跟微信文档字段名一致,签名验证(统一下单是带下划线变量,app唤起支付参数不带下划线)
            parameterMap.put("partnerid",  WxPayConfig.MCH_ID);
            parameterMap.put("prepayid", map.get("prepay_id") == null ? "" : map.get("prepay_id"));
            parameterMap.put("package", "Sign=WXPay");
            parameterMap.put("noncestr", WxPayCommonUtils.CreateNoncestr());
            //本来生成的时间戳是13位,但是ios必须是10位,所以截取了一下
            parameterMap.put("timestamp", Long.parseLong(String.valueOf(System.currentTimeMillis()).substring(0, 10)));
            String sign2 = WxPayCommonUtils.createSign("UTF-8", parameterMap,  WxPayConfig.APP_KEY);
            parameterMap.put("sign", sign2);
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
        log.info("微信报文===>>>" + JSONObject.toJSON(parameterMap));
        return JSONObject.toJSON(parameterMap).toString();
    }
}

第四步: 微信异步回调

/**
 * 微信支付异步回调
 *
 * @param request
 * @param response
 * @throws IOException
 * @throws JDOMException
 */
@RequestMapping(value = "/pay/wxpay/notify", method = {RequestMethod.POST, RequestMethod.GET})
public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
    //读取参数
    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();
    Map<String, String> params = XMLUtils.doXMLParse(sb.toString()); //解析xml成map
    SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>(); //过滤空 设置 TreeMap
    Iterator it = params.keySet().iterator();
    while (it.hasNext()) {
        String parameter = (String) it.next();
        String parameterValue = params.get(parameter);
 
        String v = "";
        if (null != parameterValue) {
            v = parameterValue.trim();
        }
        packageParams.put(parameter, v);
    }
    log.info("===>>>>wxPay notify, 流水号: {}, 系统订单号: {}", packageParams.get("out_trade_no"), packageParams.get("attach"));
    String resXml;
    boolean flag = WxPayCommonUtils.isTenpaySign("UTF-8", packageParams, WxPayConfig.APP_KEY); //判断签名是否正确
    if (flag) {
        if ("SUCCESS".equals(packageParams.get("result_code"))) {
            //////////支付成功, 执行自己的业务逻辑//////////
            // TODO 增加一些订单判断
        } else {
            log.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> ";
        log.info("====>>>>微信通知签名验证失败");
    }
    BufferedOutputStream out = new BufferedOutputStream(
            response.getOutputStream());
    out.write(resXml.getBytes());
    out.flush();
    out.close();
}

相关工具类:

/**
 * Created by NooYoo.
 * Created on 2019/7/16.
 * Description: 微信xml解析
 */
public class XMLUtils {
 
    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
     * @param strxml
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public static Map<String, String> 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 = XMLUtils.getChildrenText(children);
            }
 
            m.put(k, v);
        }
 
        //关闭流
        in.close();
 
        return m;
    }
 
    /**
     * 获取子结点的xml
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if(!children.isEmpty()) {
            Iterator it = children.iterator();
            while(it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if(!list.isEmpty()) {
                    sb.append(XMLUtils.getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }
 
        return sb.toString();
    }
 
}
/**
 * Created by Administrator.
 * Created on 2019/7/16.
 * Description:
 */
public class WxPayCommonUtils {
 
    private static final Logger logger = LoggerFactory.getLogger(WxPayCommonUtils.class);
 
    public static String CreateNoncestr(int length) {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String res = "";
        for (int i = 0; i < length; i++) {
            Random rd = new Random();
            res += chars.indexOf(rd.nextInt(chars.length() - 1));
        }
        return res;
    }
 
    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;
    }
 
 
    /**
     * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     * @return boolean
     */
    public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String appKey) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.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(!"sign".equals(k) && null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
            }
        }
 
        sb.append("key=").append(appKey);
 
        //算出摘要
        String mysign = MD5Utils.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
        String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();
 
        //System.out.println(tenpaySign + "    " + mysign);
        return tenpaySign.equals(mysign);
    }
 
 
    /**
     * @Description:sign签名
     * @param characterEncoding 编码格式
     * @param parameters 请求参数
     * @return
     */
    public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters, String appKey){
        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=").append(appKey);
        String sign = MD5Utils.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }
    /**
     * @Description: 将请求参数转换为xml格式的string
     * @param parameters  请求参数
     * @return
     */
    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();
    }
    /**
     * @Description: 返回给微信的参数
     * @param return_code 返回编码
     * @param return_msg  返回信息
     * @return
     */
    public static String setXML(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code
                + "]]></return_code><return_msg><![CDATA[" + return_msg
                + "]]></return_msg></xml>";
    }
 
 
    /**
     * 发送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 MyX509TrustManagerUtil() };
            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) {
          logger.error("连接超时:{}", ce);
        } catch (Exception e) {
            logger.error("https请求异常:{}", e);
        }
        return null;
    }
 
    /**
     * 发送https请求
     *
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod) {
        JSONObject jsonObject = null;
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManagerUtil() };
            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);
            conn.setConnectTimeout(3000);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            //conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            // 从输入流读取返回内容
            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();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
            logger.error("连接超时:{}", ce);
        } catch (Exception e) {
            logger.error("https请求异常:{}", e);
        }
        return jsonObject;
    }
 
    public static String urlEncodeUTF8(String source){
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}
/**
 * Created by Administrator.
 * Created on 2019/7/16.
 * Description:
 */
public class MD5Utils {
 
    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));
 
        return resultSb.toString();
    }
 
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
 
    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }
 
    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}
/**
 * Created by NooYoo.
 * Created on 2019/7/16.
 * Description:
 */
public class WxPayCommonUtils {
 
    private static final Logger logger = LoggerFactory.getLogger(WxPayCommonUtils.class);
 
    public static String CreateNoncestr(int length) {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String res = "";
        for (int i = 0; i < length; i++) {
            Random rd = new Random();
            res += chars.indexOf(rd.nextInt(chars.length() - 1));
        }
        return res;
    }
 
    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;
    }
 
 
    /**
     * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     * @return boolean
     */
    public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String appKey) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.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(!"sign".equals(k) && null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
            }
        }
 
        sb.append("key=").append(appKey);
 
        //算出摘要
        String mysign = MD5Utils.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
        String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();
 
        //System.out.println(tenpaySign + "    " + mysign);
        return tenpaySign.equals(mysign);
    }
 
 
    /**
     * @Description:sign签名
     * @param characterEncoding 编码格式
     * @param parameters 请求参数
     * @return
     */
    public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters, String appKey){
        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=").append(appKey);
        String sign = MD5Utils.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }
    /**
     * @Description: 将请求参数转换为xml格式的string
     * @param parameters  请求参数
     * @return
     */
    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();
    }
    /**
     * @Description: 返回给微信的参数
     * @param return_code 返回编码
     * @param return_msg  返回信息
     * @return
     */
    public static String setXML(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code
                + "]]></return_code><return_msg><![CDATA[" + return_msg
                + "]]></return_msg></xml>";
    }
 
 
    /**
     * 发送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 MyX509TrustManagerUtil() };
            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) {
          logger.error("连接超时:{}", ce);
        } catch (Exception e) {
            logger.error("https请求异常:{}", e);
        }
        return null;
    }
 
    /**
     * 发送https请求
     *
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod) {
        JSONObject jsonObject = null;
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManagerUtil() };
            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);
            conn.setConnectTimeout(3000);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            //conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            // 从输入流读取返回内容
            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();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
            logger.error("连接超时:{}", ce);
        } catch (Exception e) {
            logger.error("https请求异常:{}", e);
        }
        return jsonObject;
    }
 
    public static String urlEncodeUTF8(String source){
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}

代码中使用:

Map<String, Object> wxpayMap = new HashMap<>();
wxpayMap.put("attach", "你自己的订单号");
wxpayMap.put("spbillCreateIp", request.getRemoteAddr());
wxpayMap.put("body", "xx费用");
wxpayMap.put("serialNumber", "你的流水号");
wxpayMap.put("orderId", "你自己的订单号");
wxpayMap.put("price", "订单金额"); // orderTrade.getTotalFee()
wxpayMap.put("notifyURL", WxPayConfig.NOTIFY_URL);
paymentStr = wxPay.wxPrePay(wxpayMap);
最后一次编辑于  08-20  (未经腾讯允许,不得转载)
点赞 0
收藏
评论

1 个评论

  • <
    08-30
    <dependency>
       <groupId>com.github.wxpay</groupId>
       <artifactId>wxpay-sdk</artifactId>
       <version>0.0.3</version>
    </dependency>


    08-30
    赞同
    回复