/**   
* @Title: AlipayJsonController.java 
* @Package com.platform.controller.alipay 
* @Description: TODO(用一句话描述该文件做什么) 
* @author kiosk
* @date 2017年8月28日 上午8:21:02 
* @version V1.0   
*/
package com.platform.controller.alipay;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.request.AlipayTradeCancelRequest;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayTradeCancelResponse;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.platform.pojo.AlipayConfig;
import com.platform.pojo.AlipayConfigExample;
import com.platform.pojo.AlipayJournal;
import com.platform.pojo.InterfaceInvokeLog;
import com.platform.request.json.AliPayRequestParameter;
import com.platform.request.json.AlipayRequestParameterForCancel;
import com.platform.request.json.AlipayRequestParameterForDownloadurlQuery;
import com.platform.request.json.AlipayRequestParameterForQuery;
import com.platform.request.json.AlipayRequestParameterForRefund;
import com.platform.request.json.AlipayRequestParameterForRefundQuery;
import com.platform.response.json.AlipayResponseParameterForCancel;
import com.platform.response.json.AlipayResponseParameterForDownloadurlQuery;
import com.platform.response.json.AlipayResponseParameterForInsert;
import com.platform.response.json.AlipayResponseParameterForQrCode;
import com.platform.response.json.AlipayResponseParameterForQuery;
import com.platform.response.json.AlipayResponseParameterForRefund;
import com.platform.response.json.AlipayResponseParameterForRefundQuery;
import com.platform.service.AlipayJournalService;
import com.platform.service.IAliPayService;
import com.platform.util.ConstantsUtil;
import com.platform.util.DateUtil;
import com.platform.util.JSONUtil;
import com.platform.util.QRCodeUtil;
import com.platform.util.WebToolUtils;
import com.platform.util.Xml2JsonUtil;

/** 
 * @ClassName: AlipayJsonController 
 * @Description: TODO(支付宝AliPay扫码付对接类) 
 * @author kiosk
 * @date 2017年8月28日 上午8:21:02 
 *  
 */
@Controller
@RequestMapping("/alipayjson")
public class AlipayJsonController {
	//定义日志文件操作类对象
	private static Logger logger =(Logger) LoggerFactory.getLogger(AlipayJsonController.class);
	@Resource
	private IAliPayService aliPayService;//引入service
	@Resource
	private AlipayJournalService alipayJournalService;
	
	//定义变量和查询条件类
	List<AlipayConfig> alipayConfigs = new ArrayList<AlipayConfig>();
	AlipayConfigExample example = new AlipayConfigExample();
	
	/**
	 * 
	* @Title: pay 
	* @Description: TODO(支付宝扫码付预下单方法) 
	* @param @param requestParameter
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	@RequestMapping(value="/pay", consumes="application/json",method=RequestMethod.POST)
	@ResponseBody
	public String pay(@RequestBody AliPayRequestParameter requestParameter){
		logger.debug("###################################################执行支付宝扫码支付下单接口pay方法开始");
		logger.debug("###################################################接收到的body值："+requestParameter);
		String resultStr=null;
		String str = null;
		String errorString=null;
		//将返回的XML结果封装处理成接口调用日志Java类对象
		XmlMapper xmlMapper = new XmlMapper();
		ObjectMapper mapper = new ObjectMapper(); //转换器
		logger.debug("##########################################################读取支付宝扫码支付配置表开始");
		example.or().andDeleteFlagEqualTo(0);
		alipayConfigs=aliPayService.getConfigList(example);
		logger.debug("#########################################获取到的支付配置表数据记录条数"+alipayConfigs.size());
		if (alipayConfigs.size()==0) {
			errorString="支付配置表没有配置！";
			resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_precreate_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_precreate_response> ";
			try {
				resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
			} catch (DocumentException e) {

				// TODO Auto-generated catch block
				errorString=e.toString();
			}
			logger.debug("支付配置表没有配置");
		}else if (alipayConfigs.size() ==1){
			logger.debug("#########################################################获取到的支付配置表唯一一条记录，支付开始");
			//全局DeserializationFeature配置：配置该objectMapper在反序列化时，忽略目标对象没有的属性。凡是使用该objectMapper反序列化时，都会拥有该特性。
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
			try {
				//将传入的Java类转换为Json串
				str = JSONUtil.objectToJson(requestParameter).toString();
				logger.debug("##########################################body值转换为Json串："+str);
				//声明支付宝支付请求客户端
				AlipayClient alipayClient = AlipayAPIClientFactory.getAlipayClient(alipayConfigs.get(0).getPrepayGateUrl(),alipayConfigs.get(0).getAppId(), ConstantsUtil.PRIVATE_KEY, ConstantsUtil.CHARSET, ConstantsUtil.ALIPAY_PUBLIC_KEY,ConstantsUtil.SIGN_TYPE);
				System.out.println(alipayClient.toString());
				// 使用SDK，构建群发请求模型
				AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
				request.setBizContent(str);
				//这里设置支付扫码完成回调的异步通知url，地址必须是外网，保证支付宝能访问到，最好用域名
				request.setNotifyUrl(alipayConfigs.get(0).getPrepayNotifyUrl());
				AlipayTradePrecreateResponse response = null;
				try {
					// 使用SDK，调用交易下单接口
					response = alipayClient
							.execute(request);
					logger.debug("#########响应对象为"+response);
					System.out.println(response.getBody());
					System.out.println(response.getSubMsg());
					System.out.println(response.isSuccess());
					System.out.println(response.getMsg());
					// 这里只是简单的打印，请开发者根据实际情况自行进行处理
					AlipayResponseParameterForQrCode alipayResponse=new AlipayResponseParameterForQrCode();
					if (null != response && response.isSuccess()) {
						if (response.getCode().equals("10000")) {
							System.out.println("商户订单号："+response.getOutTradeNo());
							System.out.println("二维码值："+response.getQrCode());//商户将此二维码值生成二维码，然后展示给用户，用户用支付宝手机钱包扫码完成支付
							String qrCodePath=getWebappsURL()+File.separator+"uploadImages"+
							File.separator+"qrcode"+File.separator+"alipay"+File.separator+"mb"+
								File.separator+DateUtil.format(new Date(),"yyyyMMdd");
							System.err.println("#######二维码存放地址"+qrCodePath);
							String ip="";
							String code_url="";
							ip=WebToolUtils.getLocalIP();
							logger.debug("#########本机ip"+ip);
							String filename=QRCodeUtil.encode(response.getQrCode(), qrCodePath, false);
							code_url="Http://"+ip+":"+ConstantsUtil.TOMCAT_PORT_WXALIPAY+File.separator+"uploadImages"+
									File.separator+"qrcode"+File.separator+"alipay"+File.separator+"mb"+File.separator+
									DateUtil.format(new Date(),"yyyyMMdd")+File.separator+filename;
							System.err.println(code_url);
							code_url=code_url.replace("\\", "/");
							Map mapStr=JSON.parseObject(response.getBody(), Map.class);
							for(Object obj:mapStr.keySet()){
								if(obj=="sign"){
									alipayResponse.setSign((String)mapStr.get(obj));
								}
							}
							alipayResponse.setCode(response.getCode());
							alipayResponse.setMsg(response.getMsg());
							alipayResponse.setCode_url(code_url);
							alipayResponse.setQr_code(response.getQrCode());
							alipayResponse.setOut_trade_no(response.getOutTradeNo());
							alipayResponse.setSub_code(response.getSubCode());
							alipayResponse.setSub_msg(response.getSubMsg());
							resultStr=JSONUtil.objectToJson(alipayResponse).toString();
							System.err.println("________________返回的数据"+resultStr);
							AlipayResponseParameterForInsert alipayResponseParameterForInsert=new AlipayResponseParameterForInsert();
							alipayResponseParameterForInsert.setCode(response.getCode());
							alipayResponseParameterForInsert.setService("unifiedorder_service");
							alipayResponseParameterForInsert.setService_version("2.0");
							alipayResponseParameterForInsert.setSign_type(ConstantsUtil.SIGN_TYPE);
							alipayResponseParameterForInsert.setInput_charset("UTF-8");
							alipayResponseParameterForInsert.setCode_url(code_url);
							alipayResponseParameterForInsert.setOut_trade_no(response.getOutTradeNo());
							alipayResponseParameterForInsert.setMsg(response.getMsg());
							alipayResponseParameterForInsert.setSub_code(response.getSubCode());
							alipayResponseParameterForInsert.setSub_msg(response.getSubMsg());
							InterfaceInvokeLog interfaceInvokeLog=new InterfaceInvokeLog();
							interfaceInvokeLog.setService(alipayResponseParameterForInsert.getService());
							interfaceInvokeLog.setServiceVersion(alipayResponseParameterForInsert.getService_version());
							interfaceInvokeLog.setSignType(alipayResponseParameterForInsert.getSign_type());
							interfaceInvokeLog.setCode(alipayResponseParameterForInsert.getCode());
							interfaceInvokeLog.setInputCharset(alipayResponseParameterForInsert.getInput_charset());
							interfaceInvokeLog.setMsg(alipayResponseParameterForInsert.getMsg());
							interfaceInvokeLog.setOutTradeNo(alipayResponseParameterForInsert.getOut_trade_no());
							interfaceInvokeLog.setSubCode(alipayResponseParameterForInsert.getSub_code());
							interfaceInvokeLog.setSubMsg(alipayResponseParameterForInsert.getSub_msg());
							int num=aliPayService.saveInvokeLog(interfaceInvokeLog);
							logger.debug("#########返回行数"+num);
						} else{
						//打印错误码
						 Map mapStr=JSON.parseObject(response.getBody(), Map.class);
							for(Object obj:mapStr.keySet()){
								if(obj=="sign"){
									alipayResponse.setSign((String)mapStr.get(obj));
								}
							}
					       alipayResponse.setCode(response.getCode());
					       alipayResponse.setOut_trade_no(response.getOutTradeNo());
					       alipayResponse.setMsg(response.getMsg());
					       alipayResponse.setSub_code(response.getSubCode());
					       alipayResponse.setSub_msg(response.getSubMsg());
					       resultStr=JSONUtil.objectToJson(alipayResponse).toString();
						}
					}else if(response!=null){
						//打印错误码
						 Map mapStr=JSON.parseObject(response.getBody(), Map.class);
							for(Object obj:mapStr.keySet()){
								if(obj=="sign"){
									alipayResponse.setSign((String)mapStr.get(obj));
								}
							}
					       alipayResponse.setCode(response.getCode());
					       alipayResponse.setOut_trade_no(response.getOutTradeNo());
					       alipayResponse.setMsg(response.getMsg());
					       alipayResponse.setSub_code(response.getSubCode());
					       alipayResponse.setSub_msg(response.getSubMsg());
					       resultStr=JSONUtil.objectToJson(alipayResponse).toString();
						}
				}catch (AlipayApiException e) {
					System.out.println("异常描述："+e.toString());
					errorString=e.toString();
					resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_precreate_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_precreate_response> ";
					try {
						resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
					} catch (DocumentException ee) {
						// TODO Auto-generated catch block
						ee.printStackTrace();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}catch (JSONException e) {
				errorString="数据转换错误(JSONException)！";
				resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_precreate_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_precreate_response> ";
				try {
					resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException ee) {
					// TODO Auto-generated catch block
					errorString=ee.toString();
				}
				logger.debug("################################################################数据转换错误(JSONException)："+e.toString());
			} catch (IOException e) {
				errorString="流异常(IOException)！";
				resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_precreate_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_precreate_response> ";
				try {
					resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException ee) {
					// TODO Auto-generated catch block
					errorString=ee.toString();
				}
				logger.debug("#######################################################################流异常(IOException)："+e.toString());
			}
		}else {
			errorString="支付配置表存在多条记录！";
			resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_precreate_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_precreate_response> ";
			try {
				resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				errorString=e.toString();
			}
			logger.debug("################################################################################支付配置表存在多条记录");
		}
		logger.debug("#######################################################################执行支付宝扫码支付下单接口pay方法结束");
		return resultStr;
	}


	/**
	 * 
	* @Title: pay 
	* @Description: TODO（支付宝扫码查询方法）
	* @param @param requestParameter
	* @param @return  设定文件
	* @return String  返回类型
	* @throws
	 */
	@RequestMapping(value="/query",consumes="application/json",method=RequestMethod.POST)
	@ResponseBody
    public String query(@RequestBody AlipayRequestParameterForQuery requestParameterForQuery){
		logger.debug("########支付宝查询方法开始执行");
		String resultStr=null;
		String str=null;
		String errorString=null;
		ObjectMapper mapper = new ObjectMapper();
		example.or().andDeleteFlagEqualTo(0);
		alipayConfigs=aliPayService.getConfigList(example);
		if(alipayConfigs.size()==0){
			errorString="配置表没有配置";
			resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_query_response>";
			try {
				resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(alipayConfigs.size()==1){
			logger.debug("#######获得支付表唯一一条记录 查询开始");
			try {
				str=JSONUtil.objectToJson(requestParameterForQuery).toString();
				logger.debug("body值返回json串"+str);
				AlipayClient alipayClient=AlipayAPIClientFactory.getAlipayClient(alipayConfigs.get(0).getSearchGateUrl(), alipayConfigs.get(0).getAppId(), ConstantsUtil.PRIVATE_KEY, ConstantsUtil.CHARSET, ConstantsUtil.ALIPAY_PUBLIC_KEY, ConstantsUtil.SIGN_TYPE);
				System.err.println(alipayClient.toString());
				AlipayTradeQueryRequest request=new AlipayTradeQueryRequest();
				request.setBizContent(str);
				AlipayTradeQueryResponse response=null;
				try {
					response=alipayClient.execute(request);
					System.out.println(response.getBody());
					System.out.println(response.getMsg());
					System.out.println(response.getTotalAmount());
					AlipayResponseParameterForQuery alipayResponseParameterForQuery=new AlipayResponseParameterForQuery();
					if(response!=null&&response.isSuccess()){
					Map mapStr=JSON.parseObject(response.getBody(), Map.class);
						for(Object obj:mapStr.keySet()){
							if(obj=="sign"){
								alipayResponseParameterForQuery.setSign((String)mapStr.get(obj));
							}
						}
					alipayResponseParameterForQuery.setCode(response.getCode());
					alipayResponseParameterForQuery.setMsg(response.getMsg());
					alipayResponseParameterForQuery.setSub_msg(response.getSubCode());
					alipayResponseParameterForQuery.setSub_msg(response.getSubMsg());
					alipayResponseParameterForQuery.setTrade_no(response.getTradeNo());
					alipayResponseParameterForQuery.setOut_trade_no(response.getOutTradeNo());
					alipayResponseParameterForQuery.setBuyer_logon_id(response.getBuyerLogonId());
					alipayResponseParameterForQuery.setTrade_status(response.getTradeStatus());
					alipayResponseParameterForQuery.setTotal_amount(response.getTotalAmount());
					alipayResponseParameterForQuery.setReceipt_amount(response.getReceiptAmount());
					alipayResponseParameterForQuery.setBuyer_pay_amount(response.getBuyerPayAmount());
					alipayResponseParameterForQuery.setPoint_amount(response.getPointAmount());
					alipayResponseParameterForQuery.setInvoice_amount(response.getInvoiceAmount());
					alipayResponseParameterForQuery.setSend_pay_date(response.getSendPayDate());
					System.out.println(response.getSendPayDate());
					alipayResponseParameterForQuery.setStore_id(response.getStoreId());
					alipayResponseParameterForQuery.setTerminal_id(response.getTerminalId());
					alipayResponseParameterForQuery.setFund_bill_list(response.getFundBillList());
					alipayResponseParameterForQuery.setStore_name(response.getAlipayStoreId());
					alipayResponseParameterForQuery.setBuyer_user_id(response.getBuyerUserId());
					resultStr=JSONUtil.objectToJson(alipayResponseParameterForQuery).toString();
					AlipayResponseParameterForInsert alipayResponseParameterForInsert=new AlipayResponseParameterForInsert();
					alipayResponseParameterForInsert.setService("query_order_service");
					alipayResponseParameterForInsert.setService_version("1.0");
					InterfaceInvokeLog interfaceInvokeLog=new InterfaceInvokeLog();
					interfaceInvokeLog.setService(alipayResponseParameterForInsert.getService());
					interfaceInvokeLog.setServiceVersion(alipayResponseParameterForInsert.getService_version());
					interfaceInvokeLog.setTradeNo(alipayResponseParameterForQuery.getTrade_no());
					interfaceInvokeLog.setOutTradeNo(alipayResponseParameterForQuery.getOut_trade_no());
					interfaceInvokeLog.setBuyerLogonId(alipayResponseParameterForQuery.getBuyer_logon_id());
					interfaceInvokeLog.setTradeStatus(alipayResponseParameterForQuery.getTrade_status());
					interfaceInvokeLog.setTotalFee(Float.parseFloat(alipayResponseParameterForQuery.getTotal_amount()));
					interfaceInvokeLog.setReceiptAmount(alipayResponseParameterForQuery.getReceipt_amount());
					interfaceInvokeLog.setCode(response.getCode());
					interfaceInvokeLog.setMsg(response.getMsg());
					interfaceInvokeLog.setSubCode(response.getSubCode());
					interfaceInvokeLog.setSubMsg(response.getSubMsg());
					interfaceInvokeLog.setBuyerUserId(alipayResponseParameterForQuery.getBuyer_user_id());
					int num=aliPayService.saveInvokeLog(interfaceInvokeLog);
					System.err.println("影响了多少行"+num);
					}else if(response!=null){
						Map mapStr=JSON.parseObject(response.getBody(), Map.class);
						for(Object obj:mapStr.keySet()){
							if(obj=="sign"){
								alipayResponseParameterForQuery.setSign((String)mapStr.get(obj));
							}
						}
						alipayResponseParameterForQuery.setSub_code(response.getSubMsg());
						alipayResponseParameterForQuery.setSub_msg(response.getSubMsg());
						alipayResponseParameterForQuery.setCode(response.getCode());
						alipayResponseParameterForQuery.setMsg(response.getMsg());
						alipayResponseParameterForQuery.setTrade_no(response.getTradeNo());
						alipayResponseParameterForQuery.setOut_trade_no(response.getOutTradeNo());
						alipayResponseParameterForQuery.setBuyer_logon_id(response.getBuyerLogonId());
						resultStr=JSONUtil.objectToJson(alipayResponseParameterForQuery).toString();
						logger.debug("#########查询接口对象转换为JSON字符串"+resultStr);
					}
				} catch (AlipayApiException e) {
					errorString=e.toString();
					resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_query_response>";
					try {
						resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
					} catch (DocumentException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			} catch(JSONException e){
				errorString="数据转换错误(JSONException)";
				resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_query_response>";
				try {
					resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			 } catch (IOException e) {
				errorString="流异常(IOException)";
				resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_query_response>";
				try {
					resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}else{
			  errorString="配置表有多条记录";
			  resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_query_response>";
			  try {
				resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
			} catch (DocumentException e) {
				errorString=e.toString();
				e.printStackTrace();
			}
		  }
    	return resultStr;
    }
	/**
	 * 
	* @Title: refund 
	* @Description: TODO(支付宝扫码退款方法) 
	* @param @param requestParameterForRefund
	* @param @return 设定文件
	* @return String 返回类型
	* @throws
	 */
	@RequestMapping(value="/refund",consumes="application/json",method=RequestMethod.POST)
	@ResponseBody
	public String refund(@RequestBody AlipayRequestParameterForRefund requestParameterForRefund){
		String resultStr=null;
		String str=null;
		String errorString=null;
		example.or().andDeleteFlagEqualTo(0);
		alipayConfigs=aliPayService.getConfigList(example);
		if(alipayConfigs.size()==0){
			errorString="配置表里没有配置";
			resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_refund_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_refund_response>";
			try {
				resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(alipayConfigs.size()==1){
			logger.debug("#######获得支付表里唯一一条记录 退款开始");
		    try {
				str=JSONUtil.objectToJson(requestParameterForRefund).toString();
				logger.debug("body返回的json串"+str);
				AlipayClient alipayClient=AlipayAPIClientFactory.getAlipayClient(alipayConfigs.get(0).getRefundGateUrl(),alipayConfigs.get(0).getAppId(),ConstantsUtil.PRIVATE_KEY,ConstantsUtil.CHARSET, ConstantsUtil.ALIPAY_PUBLIC_KEY,ConstantsUtil.SIGN_TYPE);
				System.out.println(alipayClient.toString());
				AlipayTradeRefundRequest request=new AlipayTradeRefundRequest();
				request.setBizContent(str);
				AlipayTradeRefundResponse response=null;
				response=alipayClient.execute(request);
			    System.out.println(response.getBody());
			    System.out.println(response.getRefundFee());
			    System.out.println(response.getGmtRefundPay());
			    AlipayResponseParameterForRefund alipayResponseParameterForRefund=new AlipayResponseParameterForRefund();
			    InterfaceInvokeLog interfaceInvokeLog=new InterfaceInvokeLog();
			    AlipayResponseParameterForInsert alipayResponseParameterForInsert=new AlipayResponseParameterForInsert();
			    if(response!=null&&response.isSuccess()){
			    Map mapStr=JSON.parseObject(response.getBody(), Map.class);
					for(Object obj:mapStr.keySet()){
						if(obj=="sign"){
							alipayResponseParameterForRefund.setSign((String)mapStr.get(obj));
						}
					}
			    alipayResponseParameterForRefund.setCode(response.getCode());
			    alipayResponseParameterForRefund.setMsg(response.getMsg());
			    alipayResponseParameterForRefund.setSub_code(response.getSubCode());
			    alipayResponseParameterForRefund.setSub_msg(response.getSubMsg());
			    alipayResponseParameterForRefund.setTrade_no(response.getTradeNo());
			    alipayResponseParameterForRefund.setOut_trade_no(response.getOutTradeNo());
			    alipayResponseParameterForRefund.setBuyer_logon_id(response.getBuyerLogonId());
			    alipayResponseParameterForRefund.setFund_change(response.getFundChange());
			    alipayResponseParameterForRefund.setRefund_fee(response.getRefundFee());
			    alipayResponseParameterForRefund.setGmt_refund_pay(response.getGmtRefundPay());
			    alipayResponseParameterForRefund.setRefund_detail_item_list(response.getRefundDetailItemList());
			    alipayResponseParameterForRefund.setStore_name(response.getStoreName());
			    alipayResponseParameterForRefund.setBuyer_user_id(response.getBuyerUserId());
			    resultStr=JSONUtil.objectToJson(alipayResponseParameterForRefund).toString();
			    AlipayJournal alipayJournal=new AlipayJournal();
			    alipayJournal.setCode(response.getCode());
			    alipayJournal.setOut_trade_no(response.getOutTradeNo());
			    alipayJournal.setTrade_no(response.getTradeNo());
			    alipayJournal.setBuyer_logon_id(response.getBuyerLogonId());
			    alipayJournal.setFund_change(response.getFundChange());
			    alipayJournal.setRefund_fee(response.getSendBackFee());
			    alipayJournal.setOut_request_no(requestParameterForRefund.getOut_request_no());
			    SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			    String strdate=formate.format(response.getGmtRefundPay());
			    alipayJournal.setGmt_refund_pay(strdate);
			    alipayJournal.setRefund_status("1");
			    int number=alipayJournalService.insertAlipayJournal(alipayJournal);
			    logger.debug("#########支付宝流水表影响行数"+number);
			    alipayResponseParameterForInsert.setService("refund_service");
			    alipayResponseParameterForInsert.setService_version("1.0");
			    alipayResponseParameterForInsert.setInput_charset("utf-8");
			    interfaceInvokeLog.setCode(alipayResponseParameterForRefund.getCode());
			    interfaceInvokeLog.setMsg(alipayResponseParameterForRefund.getMsg());
			    interfaceInvokeLog.setSubCode(alipayResponseParameterForRefund.getSub_code());
			    interfaceInvokeLog.setSubMsg(alipayResponseParameterForRefund.getSub_msg());
			    interfaceInvokeLog.setTradeNo(alipayResponseParameterForRefund.getTrade_no());
			    interfaceInvokeLog.setOutTradeNo(alipayResponseParameterForRefund.getOut_trade_no());
			    interfaceInvokeLog.setRefundFee(alipayResponseParameterForRefund.getRefund_fee());
			    interfaceInvokeLog.setBuyerUserId(alipayResponseParameterForRefund.getBuyer_user_id());
			    interfaceInvokeLog.setService(alipayResponseParameterForInsert.getService());
			    interfaceInvokeLog.setServiceVersion(alipayResponseParameterForInsert.getService_version());
			    int num=aliPayService.saveInvokeLog(interfaceInvokeLog);
			    logger.debug("影响了行数"+num);
			    }else if(response!=null){
			      Map mapStr=JSON.parseObject(response.getBody(), Map.class);
						for(Object obj:mapStr.keySet()){
							if(obj=="sign"){
								alipayResponseParameterForRefund.setSign((String)mapStr.get(obj));
							}
						}
			    	alipayResponseParameterForRefund.setCode(response.getCode());
			    	alipayResponseParameterForRefund.setMsg(response.getMsg());
			    	alipayResponseParameterForRefund.setSub_code(response.getSubCode());
			    	alipayResponseParameterForRefund.setSub_msg(response.getSubMsg());
			    	alipayResponseParameterForRefund.setBuyer_logon_id(response.getBuyerLogonId());
			    	alipayResponseParameterForRefund.setBuyer_user_id(response.getBuyerUserId());
			    	alipayResponseParameterForRefund.setTrade_no(response.getTradeNo());
			    	alipayResponseParameterForRefund.setOut_trade_no(response.getOutTradeNo());
			    	alipayResponseParameterForRefund.setStore_name(response.getStoreName());
			    	resultStr=JSONUtil.objectToJson(alipayResponseParameterForRefund).toString();
			    	logger.debug("#############退款接口对象"+resultStr);
			    	alipayResponseParameterForInsert.setService("refund_service");
				    alipayResponseParameterForInsert.setService_version("1.0");
				    alipayResponseParameterForInsert.setInput_charset("utf-8");
			    	interfaceInvokeLog.setSubCode(alipayResponseParameterForRefund.getSub_code());
				    interfaceInvokeLog.setSubMsg(alipayResponseParameterForRefund.getSub_msg());
				    interfaceInvokeLog.setTradeNo(alipayResponseParameterForRefund.getTrade_no());
				    interfaceInvokeLog.setOutTradeNo(alipayResponseParameterForRefund.getOut_trade_no());
				    interfaceInvokeLog.setBuyerUserId(alipayResponseParameterForRefund.getBuyer_user_id());
				    interfaceInvokeLog.setService(alipayResponseParameterForInsert.getService());
				    interfaceInvokeLog.setServiceVersion(alipayResponseParameterForInsert.getService_version());
				    int num=aliPayService.saveInvokeLog(interfaceInvokeLog);
				    logger.debug("##########影响行数"+num);
			    }
			} catch (JSONException e) {
				errorString="数据转换错误(JSONException)";
				resultStr="<?xml version=\1.0\" encoding=\"UTF-8\"?> <alipay_trade_refund_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_refund_response>";
				try {
					resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			} catch (IOException e) {
				errorString="流异常(IOException)";
				resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_refund_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_refund_response>";
				try {
					resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			} catch (AlipayApiException e) {
				errorString=e.toString();
				resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_refund_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_refund_response>";
				try {
					resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}else{
			errorString="配置表有多条记录";
			resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_refund_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_refund_response>";
			try {
				resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return resultStr;
	}

	@RequestMapping(value="/refundQuery",consumes="application/json",method=RequestMethod.POST)
	@ResponseBody
	public String refundQuery(@RequestBody AlipayRequestParameterForRefundQuery alipayRequestParameterForRefundQuery){
		String resultStr=null;
		String str=null;
		String errorString=null;
		example.or().andDeleteFlagEqualTo(0);
		alipayConfigs=aliPayService.getConfigList(example);
		if(alipayConfigs.size()==0){
			errorString="配置表里没配置";
			resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_refund_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_refund_query_response>";
			try {
				resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(alipayConfigs.size()==1){
			logger.debug("##########获得配置表中的唯一一条记录 退款查询开始");
			try {
				str=JSONUtil.objectToJson(alipayRequestParameterForRefundQuery).toString();
				AlipayClient alipayClient=AlipayAPIClientFactory.getAlipayClient(ConstantsUtil.ALIPAY_GATEWAY,alipayConfigs.get(0).getAppId(),ConstantsUtil.PRIVATE_KEY, ConstantsUtil.CHARSET, ConstantsUtil.ALIPAY_PUBLIC_KEY, ConstantsUtil.SIGN_TYPE);
				System.err.println(alipayClient.toString());
				AlipayTradeFastpayRefundQueryRequest request=new AlipayTradeFastpayRefundQueryRequest();
				request.setBizContent(str);
				AlipayTradeFastpayRefundQueryResponse response=null;
			    try {
					response=alipayClient.execute(request);
					System.out.println(response.getBody());
					System.out.println(response.getTotalAmount());
					System.out.println(response.getRefundReason());
					AlipayResponseParameterForRefundQuery alipayResponseParameterForRefundQuery=new AlipayResponseParameterForRefundQuery();
					 Map mapStr=JSON.parseObject(response.getBody(), Map.class);
						for(Object obj:mapStr.keySet()){
							if(obj=="sign"){
								alipayResponseParameterForRefundQuery.setSign((String)mapStr.get(obj));
							}
						}
					alipayResponseParameterForRefundQuery.setCode(response.getCode());
					alipayResponseParameterForRefundQuery.setMsg(response.getMsg());
					alipayResponseParameterForRefundQuery.setSub_code(response.getSubCode());
					alipayResponseParameterForRefundQuery.setSub_msg(response.getSubMsg());
					alipayResponseParameterForRefundQuery.setTrade_no(response.getTradeNo());
					alipayResponseParameterForRefundQuery.setOut_trade_no(response.getOutTradeNo());
					alipayResponseParameterForRefundQuery.setOut_request_no(response.getOutRequestNo());
					alipayResponseParameterForRefundQuery.setRefund_reason(response.getRefundReason());
					alipayResponseParameterForRefundQuery.setTotal_amount(response.getTotalAmount());
					alipayResponseParameterForRefundQuery.setRefund_amount(response.getRefundAmount());
					resultStr=JSONUtil.objectToJson(alipayResponseParameterForRefundQuery).toString();
					InterfaceInvokeLog interfaceInvokeLog=new InterfaceInvokeLog();
					interfaceInvokeLog.setTradeNo(alipayResponseParameterForRefundQuery.getTrade_no());
					interfaceInvokeLog.setOutTradeNo(alipayResponseParameterForRefundQuery.getOut_trade_no());
					interfaceInvokeLog.setTotalFee(Float.parseFloat(alipayResponseParameterForRefundQuery.getTotal_amount()));
					interfaceInvokeLog.setRefundFee(alipayResponseParameterForRefundQuery.getRefund_amount());
				    int num=aliPayService.saveInvokeLog(interfaceInvokeLog);
				    logger.debug("影响的行数"+num);
				} catch (AlipayApiException e) {
				    errorString=e.toString();
				    resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_refund_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_refund_query_response>";
				    try {
						resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
					} catch (DocumentException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			} catch (JSONException e) {
				 errorString="数据格式转换错误(JSONException)";
				 resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_refund_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_refund_query_response>";
				 try {
					resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				 
			} catch (IOException e) {
				errorString="流异常(IOException)";
				resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_refund_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_refund_query_response>";
				try {
					resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}else{
			errorString="配置表中有多条记录";
			resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_refund_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_refund_query_response>";
			try {
				resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return resultStr;
	}
	/**
	 * 
	* @Title: cancel 
	* @Description: TODO(支付宝扫码撤销订单方法) 
	* @param @param alipayRequestParameterForCancel
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	@RequestMapping(value="/cancel",consumes="application/json",method=RequestMethod.POST)
	@ResponseBody
	public String cancel(@RequestBody AlipayRequestParameterForCancel alipayRequestParameterForCancel){
		String resultStr=null;
		String str=null;
		String errorString=null;
		example.or().andDeleteFlagEqualTo(0);
		alipayConfigs=aliPayService.getConfigList(example);
		if(alipayConfigs.size()==0){
			errorString="配置表里没配置";
			resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_cancel_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_cancel_response>";
		    try {
				resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
		}else if(alipayConfigs.size()==1){
			logger.debug("配置表里有唯一一条记录 撤销订单开始");
			try {
				str=JSONUtil.objectToJson(alipayRequestParameterForCancel).toString();
				System.out.println("body返回的json串"+str);
				AlipayClient alipayClient=AlipayAPIClientFactory.getAlipayClient(alipayConfigs.get(0).getCancelGateUrl(),alipayConfigs.get(0).getAppId(), ConstantsUtil.PRIVATE_KEY,ConstantsUtil.CHARSET,ConstantsUtil.ALIPAY_PUBLIC_KEY,ConstantsUtil.SIGN_TYPE);
				System.out.println(alipayClient.toString());
				AlipayTradeCancelRequest request=new AlipayTradeCancelRequest();
				request.setBizContent(str);
				AlipayTradeCancelResponse response=null;
				try {
					response=alipayClient.execute(request);
					System.out.println(response.getBody());
					System.out.println(response.getAction());
					System.out.println(response.getRetryFlag());
					AlipayResponseParameterForCancel alipayResponseParameterForCancel=new AlipayResponseParameterForCancel();
					 Map mapStr=JSON.parseObject(response.getBody(), Map.class);
						for(Object obj:mapStr.keySet()){
							if(obj=="sign"){
								alipayResponseParameterForCancel.setSign((String)mapStr.get(obj));
							}
						}
					alipayResponseParameterForCancel.setCode(response.getCode());
					alipayResponseParameterForCancel.setMsg(response.getMsg());
					alipayResponseParameterForCancel.setSub_code(response.getSubCode());
					alipayResponseParameterForCancel.setSub_msg(response.getSubMsg());
					alipayResponseParameterForCancel.setTrade_no(response.getTradeNo());
					alipayResponseParameterForCancel.setOut_trade_no(response.getOutTradeNo());
					alipayResponseParameterForCancel.setRetry_flag(response.getRetryFlag());
					alipayResponseParameterForCancel.setAction(response.getAction());
					resultStr=JSONUtil.objectToJson(alipayResponseParameterForCancel).toString();
					InterfaceInvokeLog interfaceInvokeLog=new InterfaceInvokeLog();
					interfaceInvokeLog.setCode(alipayResponseParameterForCancel.getCode());
					interfaceInvokeLog.setMsg(alipayResponseParameterForCancel.getMsg());
					interfaceInvokeLog.setSubCode(alipayResponseParameterForCancel.getSub_code());
					interfaceInvokeLog.setSubMsg(alipayResponseParameterForCancel.getSub_msg());
					interfaceInvokeLog.setTradeNo(alipayResponseParameterForCancel.getTrade_no());
					interfaceInvokeLog.setOutTradeNo(alipayResponseParameterForCancel.getOut_trade_no());
					interfaceInvokeLog.setRetryFlag(alipayResponseParameterForCancel.getRetry_flag());
					interfaceInvokeLog.setAction(alipayResponseParameterForCancel.getAction());
					int num=aliPayService.saveInvokeLog(interfaceInvokeLog);
					logger.debug("影响的行数"+num);
				} catch (AlipayApiException e) {
				   errorString=e.toString();
				   resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_cancel_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_cancel_response>";
				   try {
					resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					}
				}
			} catch (JSONException e) {
				errorString="数据格式转换错误(JSONException)";
				resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_cancel_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_cancel_response>";
				try {
					resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			} catch (IOException e) {
				errorString="流异常(IOException)";
				resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_cancel_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_cancel_response>";
			}
		}else{
			errorString="配置表有多条记录";
			resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_trade_cancel_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_trade_cancel_response>";
			try {
				resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return resultStr;
	}

	/**
	 * 
	* @Title: downloadurlQuery 
	* @Description: TODO(支付宝扫码对账单下载方法) 
	* @param @param alipayRequestParameterForCancel
	* @param @return    设定文件
	* @return String    返回类型 
	* @throws
	 */
	@RequestMapping(value="/billDownloadurlQuery",consumes="application/json",method=RequestMethod.POST)
	@ResponseBody
	public String billDownloadurlQuery(@RequestBody AlipayRequestParameterForDownloadurlQuery requestParameterForDownloadurlQuery){
		String resultStr=null;
		String str=null;
		String errorString=null;
		example.or().andDeleteFlagEqualTo(0);
		alipayConfigs=aliPayService.getConfigList(example);
		if(alipayConfigs.size()==0){
			errorString="配置表中没有配置";
			resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_data_dataservice_bill_downloadurl_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_data_dataservice_bill_downloadurl_query_response>";
			try {
				resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(alipayConfigs.size()==1){
			logger.debug("配置表里有唯一一条记录 对账单下载开始");
			try {
				str=JSONUtil.objectToJson(requestParameterForDownloadurlQuery).toString();
				System.out.println("body转换为json串"+str);
				AlipayClient alipayClient=AlipayAPIClientFactory.getAlipayClient(alipayConfigs.get(0).getAccountDownloadGateUrl(),alipayConfigs.get(0).getAppId(), ConstantsUtil.PRIVATE_KEY, ConstantsUtil.CHARSET, ConstantsUtil.ALIPAY_PUBLIC_KEY, ConstantsUtil.SIGN_TYPE);
				System.out.println(alipayClient.toString());
				AlipayDataDataserviceBillDownloadurlQueryRequest request=new AlipayDataDataserviceBillDownloadurlQueryRequest();
				request.setBizContent(str);
				AlipayDataDataserviceBillDownloadurlQueryResponse response=null;
				try {
					response=alipayClient.execute(request);
					System.out.println(response.getBillDownloadUrl());
					AlipayResponseParameterForDownloadurlQuery alipayResponseParameterForDownloadurlQuery=new AlipayResponseParameterForDownloadurlQuery();
					 Map mapStr=JSON.parseObject(response.getBody(), Map.class);
						for(Object obj:mapStr.keySet()){
							if(obj=="sign"){
								alipayResponseParameterForDownloadurlQuery.setSign((String)mapStr.get(obj));
							}
						}
					alipayResponseParameterForDownloadurlQuery.setCode(response.getCode());
					alipayResponseParameterForDownloadurlQuery.setMsg(response.getMsg());
					alipayResponseParameterForDownloadurlQuery.setSub_code(response.getSubCode());
					alipayResponseParameterForDownloadurlQuery.setSub_msg(response.getSubMsg());
					alipayResponseParameterForDownloadurlQuery.setBill_download_url(response.getBillDownloadUrl());
					resultStr=JSONUtil.objectToJson(alipayResponseParameterForDownloadurlQuery).toString();
					InterfaceInvokeLog interfaceInvokeLog=new InterfaceInvokeLog();
					interfaceInvokeLog.setCode(alipayResponseParameterForDownloadurlQuery.getCode());
					interfaceInvokeLog.setMsg(alipayResponseParameterForDownloadurlQuery.getMsg());
					interfaceInvokeLog.setSubCode(alipayResponseParameterForDownloadurlQuery.getSub_code());
				    interfaceInvokeLog.setSubMsg(alipayResponseParameterForDownloadurlQuery.getSub_msg());
				    interfaceInvokeLog.setBillDownloadUrl(alipayResponseParameterForDownloadurlQuery.getBill_download_url());
				    int num=aliPayService.saveInvokeLog(interfaceInvokeLog);
				    logger.debug("影响的行数"+num);
				} catch (AlipayApiException e) {
					errorString=e.toString();
					resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_data_dataservice_bill_downloadurl_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_data_dataservice_bill_downloadurl_query_response>";
					try {
						resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
					} catch (DocumentException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			} catch (JSONException e) {
			      errorString="数据格式转换错误(JSONException)";
			      resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_data_dataservice_bill_downloadurl_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_data_dataservice_bill_downloadurl_query_response>";
			      try {
					resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			} catch (IOException e) {
				errorString = "流异常(IOException)";
				resultStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_data_dataservice_bill_downloadurl_query_response> <code>" + "-1" + "</code><msg>" + errorString + "</msg></alipay_data_dataservice_bill_downloadurl_query_response>";
				try {
					resultStr = Xml2JsonUtil.xml2Json(resultStr).toString();
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}else{
			errorString="配置表里存在多条记录";
			resultStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <alipay_data_dataservice_bill_downloadurl_query_response> <code>"+"-1"+"</code><msg>"+errorString+"</msg></alipay_data_dataservice_bill_downloadurl_query_response>";
			try {
				resultStr=Xml2JsonUtil.xml2Json(resultStr).toString();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return resultStr;
	}

	/**
	 * 
	* @Title: payNotify 
	* @Description: TODO(支付宝扫码回调方法) 
	* @param @param responseParameterForNotify
	* @param @return    设定文件
	* @return String    返回类型 
	* @throws
	 */
	@RequestMapping(value="/payNotify",method=RequestMethod.POST,produces=MediaType.TEXT_HTML_VALUE)
	@ResponseBody
    public String payNotify(HttpServletRequest request){
		logger.debug("#############支付回调开始");
	    try{
		Map<String,String> param=new HashMap<String, String>();
		Map<String,String[]> requestParam=request.getParameterMap();
		for(Iterator iter=requestParam.keySet().iterator();iter.hasNext();){
			String name=(String) iter.next();
			String[] values=(String[])requestParam.get(name);
			String valueStr="";
			for(int i=0;i<values.length;i++){
				valueStr=(i==values.length-1)?valueStr+values[i]:valueStr+values[i]+",";
			}
			valueStr=new String(valueStr.getBytes("UTF-8"),"UTF-8");
			param.put(name, valueStr);
		}
		if(request.getParameter("refund_fee")==null){
		AlipayJournal alipayJournal=new AlipayJournal();
		String trade_no=new String(request.getParameter("trade_no").getBytes("UTF-8"),"UTF-8");
		String out_trade_no=new String(request.getParameter("out_trade_no").getBytes("UTF-8"),"UTF-8");
		String buyer_logon_id=new String(request.getParameter("buyer_logon_id").getBytes("UTF-8"),"UTF-8");
		String seller_id=new String(request.getParameter("seller_id").getBytes("UTF-8"),"UTF-8");
		String seller_email=new String(request.getParameter("seller_email").getBytes("UTF-8"),"UTF-8");
		String trade_status=new String(request.getParameter("trade_status").getBytes("UTF-8"),"UTF-8");
		String total_amount=new String(request.getParameter("total_amount").getBytes("UTF-8"),"UTF-8");
		String receipt_amount=new String(request.getParameter("receipt_amount").getBytes("UTF-8"),"UTF-8");
		String invoice_amount=new String(request.getParameter("invoice_amount").getBytes("UTF-8"),"UTF-8");
		String buyer_pay_amount=new String(request.getParameter("buyer_pay_amount").getBytes("UTF-8"),"UTF-8");
		String subject=new String(request.getParameter("subject").getBytes("UTF-8"),"UTF-8");
		String sign_type=new String(request.getParameter("sign_type").getBytes("UTF-8"),"UTF-8");
		String notify_id=new String(request.getParameter("notify_id").getBytes("UTF-8"),"UTF-8");
		String notify_type=new String(request.getParameter("notify_type").getBytes("UTF-8"),"UTF-8");
		String notify_time=new String(request.getParameter("notify_time").getBytes("UTF-8"),"UTF-8");
		alipayJournal.setTrade_no(trade_no);
		alipayJournal.setOut_trade_no(out_trade_no);
		alipayJournal.setBuyer_logon_id(buyer_logon_id);
		alipayJournal.setSeller_id(seller_id);
		alipayJournal.setSeller_email(seller_email);
		alipayJournal.setTrade_status(trade_status);
		alipayJournal.setTotal_amount(total_amount);
		alipayJournal.setReceipt_amount(receipt_amount);
		alipayJournal.setInvoice_amount(invoice_amount);
		alipayJournal.setBuyer_pay_amount(buyer_pay_amount);
		alipayJournal.setSubject(subject);
	    alipayJournal.setSign_type(sign_type);
	    alipayJournal.setNotify_id(notify_id);
	    alipayJournal.setNotify_time(DateUtil.parseDate(notify_time));
	    alipayJournal.setNotify_type(notify_type);
	    int num=alipayJournalService.insertAlipayJournal(alipayJournal);
	    logger.debug("影响的行数"+num);
	    InterfaceInvokeLog interfaceInvokeLog=new InterfaceInvokeLog();
	    interfaceInvokeLog.setTradeNo(trade_no);
	    interfaceInvokeLog.setOutTradeNo(out_trade_no);
	    interfaceInvokeLog.setTotalFee(Float.valueOf(total_amount));
	    interfaceInvokeLog.setBuyerLogonId(buyer_logon_id);
	    interfaceInvokeLog.setReceiptAmount(receipt_amount);
	    interfaceInvokeLog.setTradeStatus(trade_status);
	    interfaceInvokeLog.setNotifyId(notify_id);
	    int number=aliPayService.saveInvokeLog(interfaceInvokeLog);
	    logger.debug("#########影响行数"+number);
		}
//        if(AlipayNotify.verify(param)){
//				out.write("success");
//		 }else{
//	    	out.write("fail");
//		 }
			if(AlipaySignature.rsaCheckV1(param, ConstantsUtil.ALIPAY_PUBLIC_KEY,ConstantsUtil.CHARSET, ConstantsUtil.SIGN_TYPE)){
				logger.debug("#############################################################################给回调接口发送接收成功结果开始");
				//给回调接口发送接收成功结果
				
				
				logger.debug("##################################################################给回调接口发送接收成功结果字符串"+"success");
				logger.debug("############################################################################给回调接口发送接收成功结果结束");
				return "success";
			 }else{
				return "fail";
			 }
	    }catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(IOException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
    }
	
	
	@RequestMapping(value="/refundNotify",method=RequestMethod.POST)
	public String refundNotify(HttpServletRequest request,HttpServletResponse response){
		logger.debug("##########退款回调开始");
		try {
			PrintWriter out=response.getWriter();
		
		Map<String,String> params=new HashMap<String, String>();
		Map<String,String[]> requestParams=request.getParameterMap();
		for(Iterator iter=requestParams.keySet().iterator();iter.hasNext();){
			String name=(String) iter.next();
			String[] values=(String[]) requestParams.get(name);
			String valueStr="";
			for(int i=0;i<values.length;i++){
				valueStr=(i==values.length-1)?valueStr+values[i]:valueStr+values[i]+",";
			}
			params.put(name, valueStr);
		}
		String notify_time=new String(request.getParameter("notify_time").getBytes("UTF-8"),"UTF-8");
		String notify_type=new String(request.getParameter("notify_type").getBytes("UTF-8"),"UTF-8");
		String  notify_id=new String(request.getParameter("notify_id").getBytes("UTF-8"),"UTF-8");
		String sign_type=new String(request.getParameter("sign_type").getBytes("UTF-8"),"UTF-8");
		String trade_no=new String(request.getParameter("trade_no").getBytes("UTF-8"),"UTF-8");
		String out_trade_no=new String(request.getParameter("out_trade_no").getBytes("UTF-8"),"UTF-8");
		String buyer_logon_id =new String(request.getParameter("buyer_logon_id").getBytes("UTF-8"),"UTF-8");
		String seller_id=new String(request.getParameter("seller_id").getBytes("UTF-8"),"UTF-8");
		String seller_email=new String(request.getParameter("seller_email").getBytes("UTF-8"),"UTF-8");
		String total_amount =new String(request.getParameter("total_amount").getBytes("UTF-8"),"UTF-8");
		String refund_fee=new String(request.getParameter("refund_fee").getBytes("UTF-8"),"UTF-8");
		String send_back_fee=new String(request.getParameter("send_back_fee").getBytes("UTF-8"),"UTF-8");
		String gmt_refund=new String(request.getParameter("gmt_refund").getBytes("UTF-8"),"UTF-8");
		AlipayJournal alipayJournal=new AlipayJournal();
		alipayJournal.setNotify_time(DateUtil.parseDate(notify_time));
		alipayJournal.setNotify_type(notify_type);
		alipayJournal.setNotify_id(notify_id);
		alipayJournal.setSign_type(sign_type);
		alipayJournal.setTrade_no(trade_no);
		alipayJournal.setOut_trade_no(out_trade_no);
		alipayJournal.setBuyer_logon_id(buyer_logon_id);
		alipayJournal.setSeller_id(seller_id);
		alipayJournal.setSeller_email(seller_email);
		alipayJournal.setTotal_amount(total_amount);
		alipayJournal.setRefund_fee(refund_fee);
		alipayJournal.setSend_back_fee(send_back_fee);
		SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    String strdate=formate.format(gmt_refund);
		alipayJournal.setGmt_refund_pay(strdate);
		int num=alipayJournalService.insertAlipayJournal(alipayJournal);
		logger.debug("######影响行数"+num);
		InterfaceInvokeLog interfaceInvokeLog=new InterfaceInvokeLog();
		interfaceInvokeLog.setNotifyId(notify_id);
		interfaceInvokeLog.setOutTradeNo(out_trade_no);
		interfaceInvokeLog.setTradeNo(trade_no);
		interfaceInvokeLog.setRefundFee(refund_fee);
		interfaceInvokeLog.setTotalFee(Float.valueOf(total_amount));
		int number=aliPayService.saveInvokeLog(interfaceInvokeLog);
		logger.debug("######影响的行数"+number);
			if(AlipaySignature.rsaCheckV1(params, ConstantsUtil.ALIPAY_PUBLIC_KEY, ConstantsUtil.CHARSET, ConstantsUtil.SIGN_TYPE)){
				logger.debug("###########退款异步验签");
				return "success";
			}else{
				return "fail";
			}
		
		}catch(IOException e){
			e.printStackTrace();
		}catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public String getWebappsURL(){
		String fengeFu = File.separator;
		WebApplicationContext webApplicationContext = ContextLoader
				.getCurrentWebApplicationContext();
		ServletContext servletContext = webApplicationContext.getServletContext();
		String webRoot = servletContext.getRealPath(fengeFu);
		int lastXiegangIndex = webRoot.substring(0,
				webRoot.lastIndexOf(fengeFu)).lastIndexOf(fengeFu);
		String webappsLujing = webRoot.substring(0, lastXiegangIndex);
		return webappsLujing;
	}
}
