/**
* @Title:getPayparams
* @Description:根据支付方式获取相应的支付参数
* @param orderMain
* @param payType
* @param request
* @return
* @throws Exception Result<Map<String,Object>> 返回类型
*/
public Result<Map<String, Object>> getPayparams(OrderMain orderMain, String payType, HttpServletRequest request) throws Exception{
Result<Map<String, Object>> result = new Result<Map<String, Object>>();
switch (payType) {
case PaymentConst.PAY_METHOD_WECHACT://微信支付方式
result = getWechatPayparams(orderMain, request);
break;
case PaymentConst.PAY_METHOD_ALI://支付宝支付方式

break;
default:
break;
}
return result;
}

/**
* @Title:getWechatPayparams
* @Description:生成微信支付需要的参数
* @param orderMain
* @param request
* @return
* @throws Exception Result<Map<String,Object>> 返回类型
*/
public Result<Map<String, Object>> getWechatPayparams(OrderMain orderMain, HttpServletRequest request) throws Exception{
Result<Map<String, Object>> result = new Result<Map<String, Object>>();
//Map<String, Object> paramMap = new HashMap<String, Object>();
/*StringBuilder getCodeID = new StringBuilder();
getCodeID.append("https://open.weixin.);
getCodeID.append(PaymentConst.WECHAT_APPID);
        getCodeID.append("&redirect_uri=" + authorizeNotifyUrl);
        getCodeID.append("&response_type=code&scope=snsapi_base#wechat_redirect");
        String openid = HttpClientUtil.post(getCodeID.toString(), "");
        LOGGER.info("微信认证返回结果:"+openid);
        LOGGER.info("终端ip:"+Util.getIpAddr(request));*/
        /*if("".equals(openid)){
        throw new MessageException("微信授权失败");
        }*/
String openid=request.getSession().getAttribute("bd").toString();
if("".equals(openid)){
LOGGER.info("微信支付openid为空重新认证wxUserAuth():"+openid);
wxUserAuth(request);
       }
/*String openid=request.getSession().getAttribute("wxOpenid").toString();
if("".equals(openid)){
LOGGER.info("微信支付openid为空重新认证wxUserAuth():"+openid);
wxUserAuth(request);
       }*/
System.out.println(openid+"3213213213213213214214214214");
        TreeMap paramMap = new TreeMap();
paramMap.put("appid", PaymentConst.WECHAT_APPID);//公众账号ID
paramMap.put("mch_id", PaymentConst.WECHAT_MCHID);//商户号
paramMap.put("nonce_str", Util.getRandomString(30, null));//随机字符串
paramMap.put("sign_type", PaymentConst.WECHAT_SIGNTYPE);//签名类型
paramMap.put("body", "Melical Fee");//商品描述
paramMap.put("out_trade_no", orderMain.getNumber());//商户订单号
//交易金额默认为人民币交易,接口中参数支付金额单位为【分】,参数值不能带小数。
paramMap.put("total_fee", (int)(orderMain.getTotalamount()*100));//标价金额
paramMap.put("spbill_create_ip", Util.getIpAddr(request));//终端IP
paramMap.put("notify_url", weChatNotifyUrl);//通知地址
paramMap.put("trade_type", PaymentConst.WECHAT_TRADETYPE_JSAPI);//交易类型
paramMap.put("openid", openid);//用户标识
paramMap.put("sign",Signature.createSign("UTF-8", paramMap));//签名
LOGGER.info("签名:"+paramMap.get("sign"));
//String response = HttpClientUtil.post(PaymentConst.wechatPayUrl, XMLUtils.simpleMapToXml(paramMap));
String response = HttpClientUtil.post(PaymentConst.wechatPayUrl,new String( XMLUtils.simpleMapToXml(paramMap).getBytes(), "UTF-8"));
System.out.println("预支付返回结果:"+response);
Map<String, String> resultParams = getWechatXmlToMap(response);
        if (PaymentConst.WECHAT_STATUSCODE_FAIL.equals(resultParams.get("return_code"))){
            throw new MessageException(resultParams.get("return_msg"));
        }else{
        if (PaymentConst.WECHAT_STATUSCODE_FAIL.equals(resultParams.get("result_code"))){
        throw new MessageException(resultParams.get("return_msg"));
            }else{
                String prepay_id = resultParams.get("prepay_id");
                
                TreeMap paramMap1 = new TreeMap();
        paramMap1.put("appId", paramMap.get("appid"));//公众账号ID
        String s = String.valueOf(Util.getSecond());
        paramMap1.put("timeStamp", s);
        paramMap1.put("nonceStr", Util.getRandomString(30, null));
        paramMap1.put("package", "prepay_id="+prepay_id);//签名类型
        paramMap1.put("signType", paramMap.get("sign_type"));//签名类型
        paramMap1.put("sign1",Signature.createSign("UTF-8", paramMap1));//签名
        LOGGER.info("最终签名:"+paramMap1.get("sign1"));
                
                //生成前台支付需要的数据
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("appId", paramMap.get("appid"));
                String s1 = String.valueOf(Util.getSecond());
                map.put("timeStamp", s1);
                map.put("nonceStr", Util.getRandomString(30, null));
                map.put("package", "prepay_id="+prepay_id);
                map.put("signType", paramMap.get("sign_type"));
                map.put("paySign", paramMap1.get("sign1"));
                System.out.println("tttttttttttttttttttttttttttttt9999999999999tttttttttttttttttttttttttttttttttttttt");
                result.setT(map);
            }
        }
        return result;
}

/**
* @Title:wxUserAuth
* @Description:微信认证
* @param request
* @return 
* @return String 返回类型
*/
@RequestMapping(value = "/wxUserAuth", method ={RequestMethod.POST,RequestMethod.GET})
@ResponseBody
public Object wxUserAuth(HttpServletRequest request){
StringBuilder getCodeID = new StringBuilder();
getCodeID.append("https://open.weixin.);
getCodeID.append(PaymentConst.WECHAT_APPID);
        getCodeID.append("&redirect_uri=" + authorizeNotifyUrl);
        getCodeID.append("&response_type=code&scope=snsapi_base#wechat_redirect");
        LOGGER.info("微信认证wxUserAuth:");
        return getCodeID.toString();
}
/**
* @Title:getOpenId
* @Description:获取openid----授权后重定向的回调链接地址(获取code后重定向到这里)
* @param request
* @return String 返回类型
*/
@RequestMapping(value = "/authorizeNotify", method = RequestMethod.GET)
public void getOpenId(HttpServletRequest request){
String code = request.getParameter("code");
StringBuilder getOpenIDUrl = new StringBuilder();
        getOpenIDUrl.append("https://api.weixin.);
        getOpenIDUrl.append(PaymentConst.WECHAT_APPID);
        getOpenIDUrl.append("&secret=" + PaymentConst.WECHAT_PUBLICKEY);
        getOpenIDUrl.append("&code=");
        getOpenIDUrl.append(code);
        getOpenIDUrl.append("&grant_type=authorization_code");
        String openIDResponse = HttpClientUtil.sendGetRequest(getOpenIDUrl.toString(), "UTF-8");
        LOGGER.info("微信认证authorizeNotify返回结果:"+openIDResponse);
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> params = new HashMap<String,Object>();
        String openid = "";
try {
params = mapper.readValue(openIDResponse, Map.class);
if(!params.containsKey("errcode")){
openid = Util.getMapString(params, "openid");
}
} catch (IOException e) {
LOGGER.error("获取openid异常" ,e);
}
request.getSession().setAttribute("wxOpenid", openid);
}

/**
* @Title:weixinPayBack
* @Description:支付回调(微信支付)
* @param request
* @return String 返回类型
*/
@RequestMapping(value="/weiXinPayNotify")
public String weixinPayBack(HttpServletRequest request){
   try {
       InputStream inStream = request.getInputStream();
       ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
       byte[] buffer = new byte[1024];
       int len = 0;
       while ((len = inStream.read(buffer)) != -1) {
           outSteam.write(buffer, 0, len);
       }
       outSteam.close();
       inStream.close();
       String resultStr  = new String(outSteam.toByteArray(),"utf-8");
       System.out.println("微信支付的回调:"+resultStr);
       Map<String, String> resultMap = getWechatXmlToMap(resultStr);
       String return_code = resultMap.get("return_code");
       if("SUCCESS".equals(return_code)){
        //检验API返回的数据里面的签名是否合法,避免数据在传输的过程中被第三方篡改
       if(!Signature.checkIsSignValidFromResponseString(resultStr)){
        throw new MessageException("微信回调参数签名不合法");
       }
        String result_code = resultMap.get("result_code");
        if("SUCCESS".equals(result_code)){
        //支付成功的业务逻辑
        String out_trade_no = resultMap.get("out_trade_no");
       OrderMain orderMain = orderMainService.findUniqueByProperty("number", out_trade_no);
       //修改订单状态为已付款
       if (null!=orderMain.getStatus()) {
        if ("10".equals(orderMain.getStatus())){
       orderMainService.updateOrderStatus(out_trade_no, "20");
       }
        }
       //通知微信.异步确认成功.必写.不然微信会一直通知后台.八次之后就认为交易失败了.
       return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        }  
   }
   } catch (Exception e) {
    LOGGER.error(e.getMessage() ,e);
   }
   return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>";
}

    /**
     * @Title:getWechatXmlToMap
     * @Description:微信返回xml结果转为Map
     * @param result
     * @return
     * @throws Exception Map<String,String> 返回类型
     */
    private Map<String, String> getWechatXmlToMap(String result) throws Exception{
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLHandler xmlHandler = new XMLHandler();
        parser.parse(new ByteArrayInputStream(result.getBytes("UTF-8")), xmlHandler);
        return xmlHandler.getParams();
    }