SpringBoot对接微信支付功能UniApp

uniapp代码

uniapp唤起微信进行支付情况

首先需要给后端发送请求支付的请求,拿到后端返回需要支付的订单,在使用uni.requestPaymentAPI唤醒微信支付

//例:生成订单
pay_type() {
				uni.request({
					url: '支付路径',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
					},
					data: { //生成订单需要的参数 
 },
					//请求成功后返回
					success: (res) => {
						wxpay(res.data.order).then((re) => {
							
						})
					}
				});
			},
         //生成订单返回的参数传给orderInfo{...}
			wxpay(data) {
				return new Promise((r, n) => {
					uni.requestPayment({
						"provider": "wxpay",
						"orderInfo": {
							"appid": data.appid, // 微信开放平台 - 应用 - AppId,注意和微信小程序、公众号 AppId 可能不一致
							"noncestr": data.noncestr, // 随机字符串
							"package": data.package, // 固定值
							"partnerid": data.partnerid, // 微信支付商户号
							"prepayid": data.prepayid, // 统一下单订单号 
							"timestamp": data.timestamp, // 时间戳(单位:秒)
							"sign": data.sign // 签名,这里用的 MD5/RSA 签名
						},
						success: (res) => {
							uni.showToast({
								title: '付款成功'
							})
							r(1)
						},
						fail: (err) => {
							n(0);
						}
					})
				})
			},

调用封装WxPayUtils接口


 Map<String, String> orderApp = WxPayUtils.createOrderApp("支付描述", 生成的订单号,金额, APPID, "回调链接");
log.info("返回生成订单结果"+orderApp )
//生成的订单返回给前端
res.put("order", orderApp);
微信支付封装WxPayUtils

import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.config.properties.JeePlusProperites;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class WxPayUtils {



	private static Logger logger = LoggerFactory.getLogger(WxPayUtils.class);
	/**
	 * 应用 id(用户端)
	 */
	public static final String APP_ID_APP1 = " ";
	public static final String APP_ID_SECRET1 = " ";
	/**
	 * 应用 id(小程序)
	 */
	public static final String APP_ID_APP2 = " ";
	public static final String APP_ID_SECRET2 = " ";

	/**
	 * 商户号 mch id
	 */
	private static final String MCH_ID = "";

	/**
	 * 密钥(key)
	 */
	private static final String KEY = " ";

	
	/**
	 * 异步回调通知地址
	 */
	public static final String NOTIFY_URL2 ="/api/wxPayNotify1";

	/**
	 * 交易类型
	 */
	public static final String TRADE_TYPE_APP = "APP"; // app支付
	public static final String TRADE_TYPE_JSAPI = "JSAPI";// JSAPI支付(或小程序支付)
	public static final String TRADE_TYPE_MWEB = "MWEB";// H5支付
	public static final String TRADE_TYPE_NATIVE = "NATIVE";// Native支付
	/**
	 * 微信接口返回结果成功状态值(SUCCESS)
	 */
	private static final String SUCCESS = "SUCCESS";

	/**
	 * 微信接口返回结果失败状态值(FAIL)
	 */
	private static final String FAIL = "FAIL";

	/**
	 * 微信签名字段名(sign)
	 */
	private static final String FIELD_SIGN = "sign";

	/**
	 * 微信「统一下单」接口地址
	 */
	private static final String UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

	/**
	 * 微信订单查询接口
	 */
	private static final String ORDER_QUERY = "https://api.mch.weixin.qq.com/pay/orderquery";
	/**
	 * 证书路径
	 */
	private static final String CERTNAME = "/cert/apiclient_cert.p12";
	/**
	 * 退款地址
	 */
	private static final String REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund";


	public static final String getCode = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=STAT#wechat_redirect";
	public static final String webAccessTokenhttps = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

	/**
	 * 创建微信预支付订单
	 * 
	 * @param body   商品描述
	 * @param out_trade_no   订单号
	 * @param price    价格 /元
	 * @param appid appid
     * @param notifyUrl 回调地址
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> createOrderApp(String body, String out_trade_no, String price, String appid,String notifyUrl) throws Exception {
		String uuid = getUUID();
		/**
		 * 生成微信「统一下单」请求数据
		 */
		Map<String, String> dataMap = new HashMap<>();
		dataMap.put("appid", appid);
		dataMap.put("mch_id", MCH_ID);
		dataMap.put("nonce_str", uuid);
		dataMap.put("body", body);
		dataMap.put("out_trade_no", out_trade_no);
		dataMap.put("total_fee", new BigDecimal(price).multiply(new BigDecimal("100")).intValue() + "");
		dataMap.put("spbill_create_ip", InetAddress.getLocalHost().getHostAddress());
		dataMap.put("notify_url",  JeePlusProperites.newInstance().filePath+notifyUrl);
		dataMap.put("trade_type", TRADE_TYPE_APP);
		/**
		 * 生成签名(MD5 编码)
		 */
		String md5Sign = getMD5Sign(dataMap, KEY, FIELD_SIGN);
		dataMap.put("sign", md5Sign);

		logger.debug("微信支付请求参数:" + dataMap.toString());
		/**
		 * 发送请求数据
		 */
		String respXml = requestWithoutCert(UNIFIEDORDER_URL, dataMap, 5000, 10000);
		/**
		 * 解析微信返回数据
		 */
		dataMap.clear();
		dataMap = processResponseXml(respXml);
		//dataMap.put("noncestr", uuid);
		logger.debug("微信支付返回参数:" + dataMap.toString());
		/**
		 * 没有生成预支付订单,直接返回
		 */
		if (dataMap.get("prepay_id") == null) {
			throw new RuntimeException(dataMap.get("return_msg") + ";" + dataMap.get("err_code_des"));
		}
		/**
		 * 生成微信APP支付「调起支付接口」的请求参数
		 */
		Map<String, String> resultMap = getPayOrder(dataMap, KEY, FIELD_SIGN, TRADE_TYPE_APP);
		/**
		 * 添加预支付订单创建成功标识
		 */
		resultMap.put("pre_pay_order_status", "success");

		/**
		 * 返回处理结果
		 */
		return resultMap;
	}
	
	
	/**
	 * 创建微信预支付订单(公众号)
	 * 
	 * @param openid   用户标识(trade_type=JSAPI时(即JSAPI支付),此参数必传)
	 * @param body   商品描述
	 * @param price    价格 /元
	 * @return
	 * @throws Exception
	 */

	public static Map<String, String> createOrderGzh(String openid, String threadNo, String price) throws Exception {
		String uuid = getUUID();
		/**
		 * 生成微信「统一下单」请求数据
		 */
		Map<String, String> dataMap = new HashMap<>();
		dataMap.put("appid", APP_ID_APP2);
		dataMap.put("mch_id", MCH_ID);
		dataMap.put("nonce_str", uuid);
		dataMap.put("body", "购买会员");

		dataMap.put("out_trade_no", threadNo);
		dataMap.put("total_fee", new BigDecimal(price).multiply(new BigDecimal("100")).intValue() + "");
		dataMap.put("spbill_create_ip", InetAddress.getLocalHost().getHostAddress());
		dataMap.put("notify_url", JeePlusProperites.newInstance().filePath+NOTIFY_URL2);
		dataMap.put("trade_type", TRADE_TYPE_JSAPI);
		dataMap.put("openid", openid);
		/**
		 * 生成签名(MD5 编码)
		 */
		String md5Sign = getMD5Sign(dataMap, KEY, FIELD_SIGN);
		dataMap.put("sign", md5Sign);
		
		logger.debug("微信支付请求参数:" + dataMap.toString());
		/**
		 * 发送请求数据
		 */
		String respXml = requestWithoutCert(UNIFIEDORDER_URL, dataMap, 5000, 10000);
		/**
		 * 解析微信返回数据
		 */
		dataMap.clear();
		dataMap = processResponseXml(respXml);
		//dataMap.put("noncestr", uuid);
		logger.debug("微信支付返回参数:" + dataMap.toString());
		/**
		 * 没有生成预支付订单,直接返回
		 */
		if (dataMap.get("prepay_id") == null) {
			throw new RuntimeException(dataMap.get("return_msg") + ";" + dataMap.get("err_code_des"));
		}
		/**
		 * 生成微信APP支付「调起支付接口」的请求参数
		 */
		//Map<String, String> resultMap = getPayOrder(dataMap, KEY, FIELD_SIGN, TRADE_TYPE_JSAPI);
		SortedMap<String, String> params = new TreeMap<String, String>();
        params.put("appId", dataMap.get("appid"));
        params.put("timeStamp", getTimeStampSecond()); //时间戳
        params.put("nonceStr", dataMap.get("nonce_str")); //随机字符串
        params.put("package", "prepay_id=" + dataMap.get("prepay_id")); //主意格式必须为 prepay_id=***
        params.put("signType", "MD5"); //签名的方式必须是MD5
        params.put("paySign", getMD5Sign(params, KEY, FIELD_SIGN));
        
        
		/**
		 * 添加预支付订单创建成功标识
		 */
        params.put("pre_pay_order_status", "success");
		
		/**
		 * 返回处理结果
		 */
		return params;
	}
	

	/** 微信退款
     * @param out_trade_no 商户这边的订单号 
     * @param transaction_id 微信那边的交易单号 
     * @param totalFee 订单的金额 单位为分
     * @param refundFee 要退的金额 单位为分
     */  
    @SuppressWarnings("deprecation")
	public static JSONObject refundApp(String out_trade_no, String transaction_id, String totalFee, String refundFee) {
        try{  
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream instream = new FileInputStream(CERTNAME);  
            try {  
                keyStore.load(instream, MCH_ID.toCharArray());  
            }finally {  
                instream.close();  
            }  
            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, MCH_ID.toCharArray()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslcontext, new String[] { "TLSv1" }, null,  
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            HttpPost httppost = new HttpPost(REFUND_URL);
            
            String nonceStr = getUUID();
            
            SortedMap<String,String> parameters = new TreeMap<String,String>();
            parameters.put("appid", APP_ID_APP1);
            parameters.put("mch_id", MCH_ID);
            parameters.put("nonce_str", nonceStr);
            parameters.put("out_trade_no", out_trade_no);
            if (StringUtils.isNotBlank(transaction_id)) {
            	parameters.put("transaction_id", transaction_id);
            }
            parameters.put("out_refund_no", nonceStr);
            parameters.put("fee_type", "CNY");
            parameters.put("total_fee", totalFee);
            parameters.put("refund_fee", refundFee);
            parameters.put("op_user_id", MCH_ID);
            String sign = getMD5Sign(parameters, KEY, FIELD_SIGN);
            parameters.put("sign", sign);
            String xml = map2Xml(parameters);
            logger.debug("微信退款请求XML:" + xml);
            try {  
                StringEntity se = new StringEntity(xml);
                httppost.setEntity(se);  
                CloseableHttpResponse responseEntry = httpclient.execute(httppost);
                try {  
                    HttpEntity entity = responseEntry.getEntity();
                    if (entity != null) {  
                        SAXReader saxReader = new SAXReader();
                        Document document = saxReader.read(entity.getContent());
                        Element rootElt = document.getRootElement();
                        logger.debug(rootElt.asXML());
                        String resultCode = rootElt.elementText("result_code");  
                        JSONObject result = new JSONObject();
                        if("SUCCESS".equals(resultCode)){  
                            result.put("weixinPayUrl", rootElt.elementText("code_url"));  
                            result.put("prepayId", rootElt.elementText("prepay_id"));  
                            result.put("status","success");  
                            result.put("msg","success");  
                        }else{  
                            result.put("status","false");  
                            result.put("msg",rootElt.elementText("err_code_des"));  
                        }
                        logger.debug("微信退款result:" + result.toString());
                        return result;  
                    }  
                    EntityUtils.consume(entity);
                }  
                finally {  
                    responseEntry.close();  
                }  
            }  
            finally {  
                httpclient.close();  
            }  
            return null;  
        }catch(Exception e){  
            e.printStackTrace(); 
            logger.error("微信退款失败:" + e.getMessage());
            JSONObject result = new JSONObject();
            result.put("status","error");  
            result.put("msg",e.getMessage());  
            return result;  
        }  
    }
    /** 微信退款
     * @param out_trade_no 商户这边的订单号 
     * @param transaction_id 微信那边的交易单号 
     * @param totalFee 订单的金额 单位为分
     * @param refundFee 要退的金额 单位为分
     */  
    @SuppressWarnings("deprecation")
	public static JSONObject refundGzh(String out_trade_no, String transaction_id, String totalFee, String refundFee, String appid) {
    	try{  
    		KeyStore keyStore = KeyStore.getInstance("PKCS12");
    		FileInputStream instream = new FileInputStream(CERTNAME);  
    		try {  
    			keyStore.load(instream, MCH_ID.toCharArray());  
    		}finally {  
    			instream.close();  
    		}  
    		SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, MCH_ID.toCharArray()).build();
    		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
    				sslcontext, new String[] { "TLSv1" }, null,  
    				SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    		HttpPost httppost = new HttpPost(REFUND_URL);
    		
    		String nonceStr = getUUID();
    		
    		SortedMap<String,String> parameters = new TreeMap<String,String>();
    		parameters.put("appid", appid);
    		parameters.put("mch_id", MCH_ID);
    		parameters.put("nonce_str", nonceStr);
    		parameters.put("out_trade_no", out_trade_no);
    		if (StringUtils.isNotBlank(transaction_id)) {
    			parameters.put("transaction_id", transaction_id);
    		}
    		parameters.put("out_refund_no", nonceStr);
    		parameters.put("fee_type", "CNY");
    		parameters.put("total_fee", totalFee);
    		parameters.put("refund_fee", refundFee);
    		parameters.put("op_user_id", MCH_ID);
    		String sign = getMD5Sign(parameters, KEY, FIELD_SIGN);
    		parameters.put("sign", sign);
    		String xml = map2Xml(parameters);
    		logger.debug("微信退款请求XML:" + xml);
    		try {  
    			StringEntity se = new StringEntity(xml);
    			httppost.setEntity(se);  
    			CloseableHttpResponse responseEntry = httpclient.execute(httppost);
    			try {  
    				HttpEntity entity = responseEntry.getEntity();
    				if (entity != null) {  
    					SAXReader saxReader = new SAXReader();
    					Document document = saxReader.read(entity.getContent());
    					Element rootElt = document.getRootElement();
    					logger.debug(rootElt.asXML());
    					String resultCode = rootElt.elementText("result_code");  
    					JSONObject result = new JSONObject();
    					if("SUCCESS".equals(resultCode)){  
    						result.put("weixinPayUrl", rootElt.elementText("code_url"));  
    						result.put("prepayId", rootElt.elementText("prepay_id"));  
    						result.put("status","success");  
    						result.put("msg","success");  
    					}else{  
    						result.put("status","false");  
    						result.put("msg",rootElt.elementText("err_code_des"));  
    					}
    					logger.debug("微信退款result:" + result.toString());
    					return result;  
    				}  
    				EntityUtils.consume(entity);
    			}  
    			finally {  
    				responseEntry.close();  
    			}  
    		}  
    		finally {  
    			httpclient.close();  
    		}  
    		return null;  
    	}catch(Exception e){  
    		e.printStackTrace(); 
    		logger.error("微信退款失败:" + e.getMessage());
    		JSONObject result = new JSONObject();
    		result.put("status","error");  
    		result.put("msg",e.getMessage());  
    		return result;  
    	}  
    }
	/**
	 * 查询支付结果/订单状态
	 * 
	 * @param orderNo
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> getPayResult(String orderNo, String appid) throws Exception {

		/**
		 * 生成微信「订单状态查询」请求数据
		 */
		Map<String, String> dataMap = new HashMap<>();
		dataMap.put("appid", appid);
		dataMap.put("mch_id", MCH_ID);
		dataMap.put("out_trade_no", orderNo);
		dataMap.put("nonce_str", getUUID());
		/**
		 * 生成签名 MD5 编码
		 */
		String md5Sign = getMD5Sign(dataMap, KEY, FIELD_SIGN);
		dataMap.put("sign", md5Sign);

		/**
		 * 发送请求数据
		 */
		String resXml = requestWithoutCert(ORDER_QUERY, dataMap, 5000, 10000);
		/**
		 * 解析请求数据
		 */
		dataMap.clear();
		dataMap = processResponseXml(resXml);

		/**
		 * 返回处理结果
		 */
		return dataMap;
	}

	public static Map<String, String> getReceiveMap(HttpServletRequest request) {
		try {
			ServletInputStream inputStream = request.getInputStream();
			String stringFromStream = getStringFromStream(inputStream);
			Map<String, String> processResponseXml = processResponseXml(stringFromStream);
			return processResponseXml;
		} catch (Exception e) {
			throw new RuntimeException("处理微信异步通知数据失败:" + e.getMessage());
		}

	}

	/**
	 * 处理 HTTPS API返回数据,转换成Map对象。return_code为SUCCESS时,验证签名。
	 *
	 */
	private static Map<String, String> processResponseXml(String xmlStr) throws Exception {
		String RETURN_CODE = "return_code";
		String return_code;
		Map<String, String> respData = xml2Map(xmlStr);
		if (respData.containsKey(RETURN_CODE)) {
			return_code = respData.get(RETURN_CODE);
		} else {
			throw new Exception(String.format("No `return_code` in XML: %s", xmlStr));
		}

		if (return_code.equals(FAIL)) {
			return respData;
		} else if (return_code.equals(SUCCESS)) {
			/**
			 * 签名校验
			 */
			if (signValidate(respData, KEY, FIELD_SIGN)) {
				return respData;
			} else {
				throw new Exception(String.format("Invalid sign value in XML: %s", xmlStr));
			}
		} else {
			throw new Exception(String.format("return_code value %s is invalid in XML: %s", return_code, xmlStr));
		}
	}

	/**
	 * 生成微信支付「调起支付接口」请求参数
	 *
	 * @param data
	 *            源数据
	 * @param key
	 *            签名密钥
	 * @param fieldSign
	 *            签名字段名(固定值 sign)
	 * @return
	 * @throws Exception
	 */
	private static Map<String, String> getPayOrder(Map<String, String> data, String key, String fieldSign, String tradeType)	throws Exception {
		Map<String, String> resultMap = new HashMap<>();
		resultMap.put("appid", data.get("appid"));
		resultMap.put("partnerid", data.get("mch_id"));
		resultMap.put("prepayid", data.get("prepay_id"));
		resultMap.put("package", TRADE_TYPE_APP.equals(tradeType) ? "Sign=WXPay" : "prepay_id=" + data.get("prepay_id"));
		resultMap.put("noncestr", data.get("nonce_str"));
		resultMap.put("timestamp", getTimeStampSecond());
		//resultMap.put("mweburl", data.get("mweb_url"));
		//resultMap.put("codeurl", data.get("code_url"));
		//resultMap.put("signType", "MD5");
		/**
		 * 生成签名
		 */
		String sign = getMD5Sign(resultMap, key, fieldSign);
		resultMap.put("sign", sign);

		return resultMap;
	}

	/**
	 * 获取支付订单号
	 *
	 *            微信支付配置信息
	 * @param orderNo
	 *            外部订单号
	 * @return 微信支付流水号
	 * @throws Exception
	 */
	public static String getPayNo(String orderNo) throws Exception {
		Map<String, String> resultMap = getPayResult(orderNo,APP_ID_APP1);
		if (resultMap.isEmpty()) {
			return null;
		}
		if (SUCCESS.equalsIgnoreCase(resultMap.get("trade_state"))) {
			return resultMap.get("transaction_id");
		}
		return null;
	}

	/**
	 * 生成UUID字符串
	 * 
	 * @return string UUID
	 */
	private static String getUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	/**
	 * 生成 md5 签名.将 map 数据按照 key 的升序进行排列 使用URL键值对的格式(即key1=value1&key2=value2…)
	 * 传送的sign参数不参与签名
	 *
	 * @param data
	 *            待签名数据
	 * @param key
	 *            密钥
	 * @param fieldSign
	 *            签名字段(sign)
	 * @return 签名
	 */
	private static String getMD5Sign(final Map<String, String> data, String key, String fieldSign) {
		Set<String> keySet = data.keySet();
		String[] keyArray = keySet.toArray(new String[keySet.size()]);
		Arrays.sort(keyArray);
		StringBuilder sb = new StringBuilder();
		for (String k : keyArray) {
			if (k.equals(fieldSign)) {
				continue;
			}
			if (data.get(k) != null && data.get(k).trim().length() > 0) // 参数值为空,则不参与签名
				sb.append(k).append("=").append(data.get(k).trim()).append("&");
		}
		sb.append("key=").append(key);
		return md5(sb.toString()).toUpperCase();
	}

	/**
	 * 校验签名
	 *
	 * @param data
	 *            待校验数据
	 * @param key
	 *            密钥
	 * @param fieldSign
	 *            签名字段(sign)
	 * @return
	 */
	private static boolean signValidate(Map<String, String> data, String key, String fieldSign) {
		if (!data.containsKey(fieldSign)) {
			return false;
		}
		String sign = data.get(fieldSign);
		return getMD5Sign(data, key, fieldSign).equalsIgnoreCase(sign);
	}

	/**
	 * 普通 md5 编码
	 * 
	 * @param url
	 * @return
	 */
	private static String md5(String url) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(url.getBytes("UTF-8"));
			byte messageDigest[] = md5.digest();

			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++) {
				String t = Integer.toHexString(0xFF & messageDigest[i]);
				if (t.length() == 1) {
					hexString.append("0" + t);
				} else {
					hexString.append(t);
				}
			}
			return hexString.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 从输入流中读取字符数据
	 *
	 * @param inputStream
	 *            servlet request inputStream
	 * @return
	 * @throws IOException
	 */
	private static String getStringFromStream(InputStream inputStream) throws IOException {
		if (inputStream == null) {
			return null;
		}
		StringBuffer sb = new StringBuffer();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		in.close();
		inputStream.close();

		return sb.toString();
	}

	/**
	 * 将 xml 转换为 map
	 *
	 * @param xmlStr
	 *            xml 格式字符串
	 * @return map 对象
	 * @throws DocumentException
	 */
	@SuppressWarnings("rawtypes")
	private static Map<String, String> xml2Map(String xmlStr) throws DocumentException {
		Map<String, String> map = new HashMap<String, String>();
		Document doc = DocumentHelper.parseText(xmlStr);

		if (doc == null)
			return map;
		Element root = doc.getRootElement();
		for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
			Element e = (Element) iterator.next();
			map.put(e.getName(), e.getText());
		}
		return map;
	}

	/**
	 * map 转 xml (仅微信支付xml格式)
	 *
	 * @param dataMap
	 *            map 数据
	 * @return
	 */
	public static String map2Xml(Map<String, String> dataMap) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		for (String key : dataMap.keySet()) {
			String value = "<![CDATA[" + dataMap.get(key) + "]]>";
			sb.append("<" + key + ">" + value + "</" + key + ">");
		}
		sb.append("</xml>");

		return sb.toString();
	}

	/**
	 * 获取当前时间戳(秒级,10位数字)
	 *
	 * @return 时间戳
	 */
	private static String getTimeStampSecond() {
		return Math.round(new Date().getTime() / 1000) + "";
	}

	/**
	 * 不需要证书的请求
	 * 
	 * @param strUrl
	 *            String
	 * @param reqData
	 *            向wxpay post的请求数据
	 * @param connectTimeoutMs
	 *            超时时间,单位是毫秒
	 * @param readTimeoutMs
	 *            超时时间,单位是毫秒
	 * @return API返回数据
	 * @throws Exception
	 */
	private static String requestWithoutCert(String strUrl, Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
		String UTF8 = "UTF-8";
		String reqBody = map2Xml(reqData);
		URL httpUrl = new URL(strUrl);
		HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setRequestMethod("POST");
		httpURLConnection.setConnectTimeout(connectTimeoutMs);
		httpURLConnection.setReadTimeout(readTimeoutMs);
		httpURLConnection.connect();
		OutputStream outputStream = httpURLConnection.getOutputStream();
		outputStream.write(reqBody.getBytes(UTF8));

		// 获取内容
		InputStream inputStream = httpURLConnection.getInputStream();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, UTF8));
		final StringBuffer stringBuffer = new StringBuffer();
		String line = null;
		while ((line = bufferedReader.readLine()) != null) {
			stringBuffer.append(line).append("\n");
		}
		String resp = stringBuffer.toString();
		if (stringBuffer != null) {
			try {
				bufferedReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (outputStream != null) {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return resp;
	}

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值