package com.ssj.framework.weixin.pay;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import javax.net.ssl.SSLContext;

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.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.ssj.alipay.utils.AlipayClientFactory;
import com.ssj.alipay.utils.AlipayPayConfig;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.PropertiesUtil;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.pay.util.CommonUtil;
import com.ssj.framework.weixin.pay.util.ConfigUtil;
import com.ssj.framework.weixin.pay.util.HttpUtil;
import com.ssj.framework.weixin.pay.util.PayCommonUtil;
import com.ssj.framework.weixin.pay.util.XMLUtil;
import com.ssj.framework.weixin.util.SHA1Util;
import com.ssj.framework.weixin.util.WxUtil;


/**
 * 
 *
 */
public class OrderHelper {
	
	private static Logger logger = LoggerFactory.getLogger(OrderHelper.class);

	private static final String ALIPAY_WAP = "WAP";
	private static final String ALIPAY_APP = "APP";

	/**
	 * 发起微信统一订单的请求
	 * @return
	 * @throws IOException 
	 * @throws JDOMException 
	 */
	public Map<String,Object> reqestOrder(String openId,String total_fee,String order_no,String body) throws Exception{
		SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
		
		parameters.put("appid", ConfigUtil.APPID);//"wxb36078b375f8c63a"
		parameters.put("mch_id", ConfigUtil.MCH_ID);//商户号"1360047702"  1433580402
		parameters.put("nonce_str", CommonUtil.CreateNoncestr());
		parameters.put("body", body);//支付商品详情
		parameters.put("out_trade_no", order_no);//商户系统内部的订单号,32个字符内、可包含字母
		parameters.put("total_fee", total_fee);//订单总金额，单位为分 total_fee
		parameters.put("spbill_create_ip",CommonUtil.getIpAddress());//此处获取用户端的ip,APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。IpAddressUtil.getIpAddr(request)
		parameters.put("notify_url", ConfigUtil.PAY_SUCCESS_URL);//"http://dc.51xue.me/duicuo/weixin/payment/pay_test" 属性文件配置   接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。如：http://www.weixin.qq.com/wxpay/pay.php
		parameters.put("trade_type", "JSAPI");
		parameters.put("openid",openId);//
		String sign = PayCommonUtil.createSign("UTF-8", parameters,ConfigUtil.PAYKEY);
		parameters.put("sign", sign);
		String requestXML = PayCommonUtil.getRequestXml(parameters);
		logger.info("===请求微信统一下单接口参数准备完毕：");
		logger.info(requestXML);
		String result =  HttpUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
		logger.info("===请求微信统一下单接口返回结果：");
		logger.info(result);
		Map<String, Object> map = XMLUtil.doXMLParse(result);
		return map;
	}
	public Map<String,Object> reqestOrder(String openId,String total_fee,String order_no,String body,String notify_url) throws Exception{
		SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
		
		parameters.put("appid", ConfigUtil.APPID);//"wxb36078b375f8c63a"
		parameters.put("mch_id", ConfigUtil.MCH_ID);//商户号"1360047702"  1433580402
		parameters.put("nonce_str", CommonUtil.CreateNoncestr());
		parameters.put("body", body);//支付商品详情
		parameters.put("out_trade_no", order_no);//商户系统内部的订单号,32个字符内、可包含字母
		parameters.put("total_fee", total_fee);//订单总金额，单位为分 total_fee
		parameters.put("spbill_create_ip",CommonUtil.getIpAddress());//此处获取用户端的ip,APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。IpAddressUtil.getIpAddr(request)
		parameters.put("notify_url",notify_url);//接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。如：http://www.weixin.qq.com/wxpay/pay.php
		parameters.put("trade_type", "JSAPI");
		parameters.put("openid",openId);//
		String sign = PayCommonUtil.createSign("UTF-8", parameters,ConfigUtil.PAYKEY);
		parameters.put("sign", sign);
		String requestXML = PayCommonUtil.getRequestXml(parameters);
		logger.info("===请求微信统一下单接口参数准备完毕：");
		logger.info(requestXML);
		String result =  HttpUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
		logger.info("===请求微信统一下单接口返回结果：");
		logger.info(result);
		Map<String, Object> map = XMLUtil.doXMLParse(result);
		return map;
	}
	public Map<String,Object> reqestXCXOrder(String openId,String total_fee,String order_no,String body, String url, String appType) throws Exception{
		SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
		
		String appId = "";
		if("2".equals(appType)){
			appId = WxUtil.map.get("readAppId");
		}else if("30".equals(appType)){
			appId = WxUtil.map.get("courseAppId");
		}else{
			appId = WxUtil.map.get("zuoybAppId");
		}
		
		
		parameters.put("appid", appId);//"wxb36078b375f8c63a"
		parameters.put("mch_id", ConfigUtil.MCH_ID);//商户号"1360047702"  1433580402
		parameters.put("nonce_str", CommonUtil.CreateNoncestr());
		parameters.put("body", body);//支付商品详情
		parameters.put("out_trade_no", order_no);//商户系统内部的订单号,32个字符内、可包含字母
		parameters.put("total_fee", total_fee);//订单总金额，单位为分 total_fee
		parameters.put("spbill_create_ip",CommonUtil.getIpAddress());//此处获取用户端的ip,APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。IpAddressUtil.getIpAddr(request)
		parameters.put("notify_url", url);//"http://dc.51xue.me/duicuo/weixin/payment/pay_test" 属性文件配置   接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。如：http://www.weixin.qq.com/wxpay/pay.php
		parameters.put("trade_type", "JSAPI");
		parameters.put("openid",openId);//
		String sign = PayCommonUtil.createSign("UTF-8", parameters,ConfigUtil.PAYKEY);
		parameters.put("sign", sign);
		String requestXML = PayCommonUtil.getRequestXml(parameters);
		logger.info("===请求小程序微信统一下单接口参数准备完毕：");
		logger.info(requestXML);
		logger.info("===");
		
		String result =  HttpUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
		logger.info("===请求小程序微信统一下单接口返回结果：");
		logger.info(result);
		Map<String, Object> map = XMLUtil.doXMLParse(result);
		return map;
	}
	/**
	 * 
	 * @param appType  6://家长端小程序小程序;7//老师端小程序小程序（校长端和老师端) ;11 (app 老师端)，12app家长端
	* @param openId 小程序必传
	* @param orderMoney 金额
	* @param order_no  订单编号
	* @param body   支付提示语
	* @return
	* @throws Exception
	* 创建人：ZhangCaibao 
	* 2018年6月8日 上午9:56:14 
	* @Map<String,Object>
	 */
	public static Map<String, String> reqestAPPOrder(String openId, BigDecimal orderMoney, String order_no, String body, int appType) throws Exception {
		String url = SystemResourceLocator.getValue("sys_url") + "/pay/payment/order_callback.html";
		Map<String, String> data = requestAPPOrder(openId, orderMoney, order_no, body, appType, url, null);
		return data;
	}

	public static Map<String, String> requestH5Order(String openId, BigDecimal orderMoney, String order_no, String body, String url, String clientIP) throws Exception {
		Map<String, String> data = requestAPPOrder(openId, orderMoney, order_no, body, 13, url, clientIP);
		return data;
	}

	public static Map<String,String> requestAPPOrder(String openId,BigDecimal orderMoney,String order_no,String body, int appType,String url,String clientIP) throws Exception{
		SortedMap<Object, Object> parameters = new TreeMap<>();
		TokenManager tokenManager = SystemResourceLocator.getBean(TokenManager.class, "tokenManager");
		String appId = WxUtil.map.get("jzdAppId");
		String trade_type = "JSAPI";
		if (StringUtil.isBlank(clientIP)) {
			clientIP = CommonUtil.getIpAddress();
		}
		String mch_id = ConfigUtil.MCH_ID;
		if(6==appType){
			appId=WxUtil.map.get("jzdAppId");
			trade_type ="JSAPI";
			parameters.put("openid",openId);
		}else if(7==appType){
			appId=WxUtil.map.get("lsdAppId");
			trade_type ="JSAPI";
			parameters.put("openid",openId);
		}else if(11==appType){
			appId = WxUtil.map.get("lsdMobileAppId");
			trade_type ="APP";
			mch_id="1507058141";
		}else if(12==appType){
			appId = WxUtil.map.get("jzdMobileAppId");
			trade_type ="APP";
			mch_id="1507058141";
		} else if (13 == appType) {
			//H5的相关信息
			appId = ConfigUtil.APPID;
			trade_type = "MWEB";
			String wapUrl = PropertiesUtil.getValue("STATIC_FILE_URL");
			parameters.put("scene_info", "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"" + wapUrl + "\",\"wap_name\": \"会员充值\"}}");
		} else if (14 == appType) {
			appId = WxUtil.map.get("curatorAppId");
			trade_type = "JSAPI";
			parameters.put("openid", openId);
		}
		String key =trade_type+order_no;
		Map<String, String> prepaymap =tokenManager.hget(key);
		logger.info("key="+key);
		if(!prepaymap.isEmpty()){
			logger.info("===返回前端参数redis获取:"+prepaymap);
			return prepaymap;
		}
		parameters.put("appid", appId);//"wxb36078b375f8c63a"
		parameters.put("body", body);//支付商品详情
		parameters.put("mch_id",mch_id);//商户号"1360047702"  1433580402
		parameters.put("nonce_str", CommonUtil.CreateNoncestr());
		parameters.put("notify_url", url);//"http://dc.51xue.me/duicuo/weixin/payment/pay_test" 属性文件配置   接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。如：http://www.weixin.qq.com/wxpay/pay.php
		parameters.put("out_trade_no", order_no);//商户系统内部的订单号,32个字符内、可包含字母
		parameters.put("spbill_create_ip", clientIP);//此处获取用户端的ip,APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。IpAddressUtil.getIpAddr(request)
		parameters.put("total_fee", orderMoney.multiply(new BigDecimal(100)).setScale(0,BigDecimal.ROUND_HALF_UP).toString());//订单总金额，单位为分 total_fee
		parameters.put("trade_type", trade_type);
		logger.info("==="+parameters);
		String sign = PayCommonUtil.createSign("UTF-8", parameters,ConfigUtil.PAYKEY);
		parameters.put("sign", sign);
		String requestXML = PayCommonUtil.getRequestXml(parameters);
		logger.info("下单接口参数准备完毕===");
		logger.info(requestXML);
		String result =  HttpUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
		logger.info("===微信统一下单接口返回结果：");
		logger.info(result);
		Map<String, Object> map = XMLUtil.doXMLParse(result);
		String prepay_id = (String) map.get("prepay_id");
		logger.info("===微信统一下单接口返回的prepay_id："+prepay_id);
		String nonceStr = CommonUtil.CreateNoncestr();
		String timeStamp = Long.toString(System.currentTimeMillis()/1000);
		String signType = ConfigUtil.SIGN_TYPE;
		SortedMap<Object,Object> params = new TreeMap<>();
		//组织map去sign签名
		String package_ = "prepay_id="+prepay_id;
		if (appType == 11 || appType == 12) {
			params.put("appid", appId);
			package_ = "Sign=WXPay";
			params.put("noncestr", nonceStr);
			params.put("package", package_);
			params.put("partnerid", mch_id);
			params.put("prepayid", prepay_id);
			//最新版的支付后台生成签名使用的timeStamp字段名
			params.put("timestamp", timeStamp);
		} else if (appType == 13) {
			//H5支付
			params.put("timeStamp", timeStamp);
			params.put("nonceStr", nonceStr);
			params.put("package", package_);
			params.put("signType", signType);
			params.put("appId", appId);
		} else {
			params.put("appId", appId);
			params.put("nonceStr", nonceStr);
			params.put("package", package_);
			params.put("signType", signType);
			//最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
			params.put("timeStamp", timeStamp);
		}
		logger.info("===组织支付接口所需的sign签名:"+params);
		Map<String, String> data = new HashMap<>(16);
		//paySign的生成规则和Sign的生成规则一致
		String paySign = PayCommonUtil.createSign("UTF-8", params,ConfigUtil.PAYKEY);
		//将参数传到页面，组织发起支付
		//6,7，14小程序
		if(appType==6||appType==7||appType==14){
			data.put("appId", appId);
			data.put("timeStamp",timeStamp);
			data.put("nonceStr", nonceStr);
			data.put("package", package_);
			data.put("signType", signType);
			//paySign的生成规则和Sign的生成规则一致
			data.put("paySign", paySign);
			data.put("prepayid", prepay_id == null ? "" : prepay_id);
		}else if(appType==13){
			//H5支付
			data.put("appId", appId);
			data.put("timeStamp",timeStamp);
			data.put("nonceStr", nonceStr);
			data.put("package",package_);
			data.put("signature", getSignature("https://t.sharingschool.com", tokenManager.getSSJJSAccessToken()));
			data.put("signType", signType);
			data.put("paySign",paySign);
			data.put("mwebUrl",map.get("mweb_url")+"");
		}else {
			//App支付
			data.put("appid", appId);
			data.put("partnerid", mch_id);
			data.put("package",package_);
			data.put("prepayid", prepay_id == null ? "" : prepay_id);
			data.put("timeStamp",timeStamp);
			data.put("nonceStr", nonceStr);
			//paySign的生成规则和Sign的生成规则一致
			data.put("sign", paySign);
		}
		logger.info("===返回前端参数:"+data);
		if(!data.isEmpty()){
			tokenManager.hset(key, data,3600);
		}
		return data;
	}

	/**
	 * 获取签名
	 * @param url
	 * @param jsapiToken
	 * @return
	 */
	public static String getSignature(String url, String jsapiToken) {
		String signature = "";
		if (jsapiToken != null) {
			String timestamp = Long.toString(System.currentTimeMillis() / 1000);
			String noncestr = UUID.randomUUID().toString();
			// 排序
			String sortString =
					"jsapi_ticket=" + jsapiToken +
							"&noncestr=" + noncestr +
							"&timestamp=" + timestamp +
							"&url=" + url;
			// 加密
			signature = new SHA1Util().sha1(sortString);
		}
		return signature;
	}


	/**
	 * 支付宝APP支付
	 * @param orderMoney 金额,
	 * @param order_no   订单编号
	 * @param title      商品的标题/交易标题/订单标题/订单关键字等。
	 * @param body       支付提示语
	 * @return
	 * @throws Exception 创建人：wuwen
	 *                   2019年4月23日11:45:12
	 * @Map<String,Object>
	 */
	public static Map<String, String> reqestAPPAliPayOrder(BigDecimal orderMoney, String order_no, String title, String body) throws Exception {
		String url = SystemResourceLocator.getValue("sys_url") + "/pay/payment/order_alipay_callback.html";
		Map<String, String> data = requestAliPayOrder(orderMoney, order_no, title, body, url, "APP");
		return data;
	}
	/**
	 * 支付宝手机网页支付
	 * @param orderMoney
	 * @param order_no
	 * @param title
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> reqestWapAliPayOrder(BigDecimal orderMoney, String order_no, String title, String body) throws Exception {
		String url = SystemResourceLocator.getValue("sys_url") + "/pay/payment/order_alipay_callback.html";
		Map<String, String> data = requestAliPayOrder(orderMoney, order_no, title, body, url, "WAP");
		return data;
	}

	public static Map<String, String> requestAliPayOrder(BigDecimal orderMoney, String order_no, String title, String body, String url, String payType) throws Exception {
		TokenManager tokenManager = SystemResourceLocator.getBean(TokenManager.class, "tokenManager");
		String key = payType + order_no;
		Map<String, String> prepaymap = tokenManager.hget(key);
		logger.info("key=" + key);
		if (!prepaymap.isEmpty()) {
			logger.info("===返回支付宝orderString参数redis获取:" + prepaymap);
			return prepaymap;
		}
		String orderString = "";
		// 支付宝统一下单接口
		AlipayClient alipayClient = AlipayClientFactory.getAlipayClient();

		if (ALIPAY_WAP.equals(payType)) {
			//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.wap.pay
			AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();

			//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
			AlipayTradeWapPayModel wapPayModel = new AlipayTradeWapPayModel();
			//设置未付款支付宝交易的超时时间
			wapPayModel.setTimeoutExpress(AlipayPayConfig.TIMEOUTEXPRESS);
			//为固定值QUICK_MSECURITY_PAY
			wapPayModel.setProductCode(AlipayPayConfig.QUICK_MSECURITY_PAY);
			//商户网站唯一订单号
			wapPayModel.setOutTradeNo(order_no);
			//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
			wapPayModel.setBody(body);
			//商品的标题/交易标题/订单标题/订单关键字等。
			wapPayModel.setSubject(title);
			//订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
			wapPayModel.setTotalAmount(orderMoney.toString());

			request.setBizModel(wapPayModel);
			//页面跳转同步通知页面路径 需http://或者https://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问 商户可以自定义同步跳转地址
			request.setReturnUrl("");
			//服务器异步通知页面路径 需http://或者https://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
			request.setNotifyUrl(url);

			AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
			//就是orderString 可以直接给客户端请求，无需再做处理。
			orderString = response.getBody();
		} else if (ALIPAY_APP.equals(payType)) {
			//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
			AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
			//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
			AlipayTradeAppPayModel appPayModel = new AlipayTradeAppPayModel();

			//设置未付款支付宝交易的超时时间
			appPayModel.setTimeoutExpress(AlipayPayConfig.TIMEOUTEXPRESS);
			//为固定值QUICK_MSECURITY_PAY
			appPayModel.setProductCode(AlipayPayConfig.QUICK_MSECURITY_PAY);
			//商户网站唯一订单号
			appPayModel.setOutTradeNo(order_no);
			//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
			appPayModel.setBody(body);
			//商品的标题/交易标题/订单标题/订单关键字等。
			appPayModel.setSubject(title);
			//订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
			appPayModel.setTotalAmount(orderMoney.toString());

			request.setBizModel(appPayModel);
			//支付宝服务器主动通知商户服务器里指定的页面
			request.setNotifyUrl(url);
			//这里和普通的接口调用不同，使用的是sdkExecute
			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
			//就是orderString 可以直接给客户端请求，无需再做处理。
			orderString = response.getBody();
		}
		Map<String, String> data = new HashMap<>(16);
		data.put("orderString", orderString);
		logger.info("===返回支付宝orderString参数:" + data);
		if (!data.isEmpty()) {
			tokenManager.hset(key, data, 1800);
		}
		return data;
	}

	 //退款请求
    @SuppressWarnings({ "deprecation", "rawtypes" })
	public String refundPost(SortedMap params,String url,String remark) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException{
    	 String result = "";
    	 String mch_id = ConfigUtil.MCH_ID;
    	 
    	 KeyStore keyStore  = KeyStore.getInstance("PKCS12");
         FileInputStream instream = new FileInputStream(new File(ConfigUtil.APICLIENT_CERT));//证书在系统中的所在地址
         logger.info("========证书位置为："+ConfigUtil.APICLIENT_CERT+",是否取到证书：instream="+instream);
         try {
             keyStore.load(instream, mch_id.toCharArray());
         } finally {
             instream.close();
         }

         // Trust own CA and all self-signed certs
         SSLContext sslcontext = SSLContexts.custom()
                 .loadKeyMaterial(keyStore, mch_id.toCharArray())
                 .build();
         // Allow TLSv1 protocol only
         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                 sslcontext,
                 new String[] { "TLSv1" },
                 null,
                 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
         CloseableHttpClient httpclient = HttpClients.custom()
                 .setSSLSocketFactory(sslsf)
                 .build();
         
         
         String requestXML = PayCommonUtil.getRequestXml(params);
        
         logger.info("===请求微信"+remark+"接口参数："+requestXML);
     	 StringEntity myEntity = new StringEntity(requestXML, "UTF-8"); 
         HttpPost post = new HttpPost(url); 
         post.addHeader("Content-Type", "text/xml");
         post.setEntity(myEntity);
         
         CloseableHttpResponse response = httpclient.execute(post);
         logger.info("===请求微信"+remark+"接口:" + post.getRequestLine());
         
         try {
        	 
             HttpEntity entity = response.getEntity();
             logger.info("==微信"+remark+"接口返回状态："+response.getStatusLine());
             if (entity != null) {
                 logger.info("---Response content length: " + entity.getContentLength());
                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
                 String text;
                 
                 while ((text = bufferedReader.readLine()) != null) {
                	 logger.info("===微信"+remark+"接口返回xml:"+text);
                     result += text;
                 }
                
             }
             EntityUtils.consume(entity);
             return result;
         } finally {
             response.close();
             httpclient.close();
         } 
    }
    
    public String B2CPost(String openid,String twr_total,String desc) throws KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{
    	logger.info("===B2CPost方法，准备参数发起企业付款接口，向opendid为"+openid+"的用户付款金额："+twr_total);
    	
    	SortedMap<Object,Object> params = new TreeMap<Object,Object>();
    	String result = null;
    	
    	String appid = ConfigUtil.APPID;
		String mch_id = ConfigUtil.MCH_ID;//"1360047702";
		String nonceStr = CommonUtil.CreateNoncestr();
		String partner_trade_no = OrderUtil.getOrderCodeB2C();//商户订单号
		String open_id = openid;
		String check_name = "NO_CHECK";//校验用户姓名选项，NO_CHECK：不校验真实姓名， FORCE_CHECK：强校验真实姓名（未实名认证的用户会校验失败，无法转账），OPTION_CHECK：针对已实名认证的用户才校验真实姓名（未实名认证用户不校验，可以转账成功）
		//String re_user_name = UserUtil.getUser(request).getName();
		String amount = twr_total;//企业金额，这里是以分为单位（必须大于100分）
		String spbill_create_ip = ConfigUtil.SPBILL_CREATE_IP;//"172.17.0.1";//CommonUtil.getIpAddress();
		
		//向微信企业付款接口发起的请求数据：
		//<xml><amount>101</amount><check_name>NO_CHECK</check_name><desc>对错教育向答题者支付佣金</desc><mch_appid>wxb36078b375f8c63a</mch_appid><mchid>1360047702</mchid><nonce_str>YU48L3OEFDU2FSIN</nonce_str><openid>oUUSrwAWHjnClFsNepPbU7dXh-rc</openid><partner_trade_no>dcjyb2c2016071818061931240</partner_trade_no><re_user_name>辟坭草堂</re_user_name><sign><![CDATA[244FC9A5AC762A626BAFE246FA3754D7]]></sign><spbill_create_ip>123.56.29.125</spbill_create_ip></xml>
		
		params.put("amount", amount);
		params.put("check_name", check_name);
		params.put("desc", desc);
		params.put("mch_appid", appid);
		params.put("mchid", mch_id);
		params.put("nonce_str", nonceStr);
		params.put("openid", open_id);
		params.put("partner_trade_no", partner_trade_no);//商户订单号
		//params.put("re_user_name", re_user_name);
		params.put("spbill_create_ip", spbill_create_ip);
		String sign =  PayCommonUtil.createSign("UTF-8", params,ConfigUtil.PAYKEY);
		params.put("sign", sign);
		
		//微信企业付款接口成功返回数据：
       //result = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[]]></return_msg><mch_appid><![CDATA[wxb36078b375f8c63a]]></mch_appid><mchid><![CDATA[1360047702]]></mchid><device_info><![CDATA[]]></device_info><nonce_str><![CDATA[DKIHQPNGL8QPUEQQ]]></nonce_str><result_code><![CDATA[SUCCESS]]></result_code><partner_trade_no><![CDATA[dcjyb2c2016071818535994161]]></partner_trade_no><payment_no><![CDATA[1000018301201607180956181720]]></payment_no><payment_time><![CDATA[2016-07-18 19:14:56]]></payment_time></xml>";

		result = this.refundPost(params,"https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers","企业付款");
		
    	return result;
    }
    
    
	
}
