1. 程式人生 > >Java 關於支付的實現(微信、支付寶)

Java 關於支付的實現(微信、支付寶)

在開發中我們經常會使用到支付功能,目前國內使用頻率高的支付方式有微信支付和支付寶支付,apple pay和三星pay沒有深入研究過,我們暫時不考慮這兩個支付。

下面我們來先講講支付的基本流程

A、客戶端發起支付訂單

    不管是web端還是手機端,發起訂單是都有對你發起的訂單的資料進行簽名(所謂的加密,目前大部分使用的是md5加密,可能還有SHA),加密過程一般都是在我們的伺服器   上進行

B、支付寶微信伺服器收到支付訂單

       加密之後我們都會使用post(get)向支付寶微信伺服器發起一請求

C、支付寶微信伺服器驗證訂單的合法性,扣錢,通知我們的伺服器

      接受到資料後會對我們提交的資料進行驗證,所有支付開發不能再區域網中進行測試(推薦一個工具ngrok,不過國內被強,可以使用https://natapp.cn/),同樣退款的也是一樣的,但是退款需要的還更多,後面我們會單獨說明

D、接受到支付寶微信伺服器通知,驗證訊息的合法性,業務處理

      接受到通知我們要對資料進行解密驗證合法性(在這個步驟很多人為了省事情,把驗證環節省了,這個可能會出現模擬支付成功訊息,這樣會造成問題)

E、發通知告訴支付寶微信伺服器收到支付成功訊息

F、退款,如果有涉及

現在我們對上面的支付過程進行抽象一下,發現支付的基本流程很相似,我們把其業務抽象出來

1、獲取發起訂單的引數(id是訂單號)

public abstract Map<String, Object> getParameterMap(String id, HttpServletRequest request); 
2、訂單合法性驗證
public abstract boolean verifyNotify(String id, HttpServletRequest request);

3、通知支付吧微信伺服器支付成功訊息收到

public abstract String getNotifyMessage(String id, HttpServletRequest request);
4、編碼方式
public abstract String getRequestCharset();

5、關於簽名方法我思考了很久是否放在抽象類中,後面還覺得不放進來(因為和支付的業務流程沒多少關係),我會將其放在工具類中

好的那麼現在我們就抽象出一個支付的流程類(PaymentPlugin)

package test;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public abstract class PaymentPlugin {
	
	public enum NotifyMethod {

		/** 同步 */
		sync,

		/** 非同步 */
		async
	}
	
	/**
	 * 1、獲取發起訂單的引數(id是訂單號)
	 */

	public abstract Map<String, Object> getParameterMap(String id, HttpServletRequest request); 

	/**
	 * 2、訂單合法性驗證
	 */

	public abstract boolean verifyNotify(String id,  HttpServletRequest request);

	/**
	 * 3、通知支付吧微信伺服器支付成功訊息收到
	 */

	public abstract String getNotifyMessage(NotifyMethod notifyMethod, HttpServletRequest request);

	/**
	 * 4、編碼方式
	 */

	public abstract String getRequestCharset();
	
}



下面我們先來說說支付寶支付

支付寶支付有銀行支付、支付寶雙介面(即時到賬支付、擔保支付)、移動支付等幾種,原來上基本一致,只是在簽名和參與簽名的引數上有細微的差別,我們在這兒就不過多深究,我們以支付寶雙介面為例子

具體的引數要求我就不過多去說明,請參考支付寶的API

1、為了方便我會模擬一個訂單類(一般是存庫的),大家可以結合物業自行處理

public class Payment {
	
	private String id;
	private Type type;
	private BigDecimal amount;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public Type getType() {
		return type;
	}
	public void setType(Type type) {
		this.type = type;
	}
	public BigDecimal getAmount() {
		return amount;
	}
	public void setAmount(BigDecimal amount) {
		this.amount = amount;
	}
	
}

2、為了方便獲取支付時需要用到的支付寶、微信給的引數(什麼appid、partner的)我們新建一個類(一般也是存庫方便修改,我們就模擬一下)
public class PluginConfig {
	private Map<String, String> attributes = new HashMap<String, String>();

	public Map<String, String> getAttributes() {
		return attributes;
	}

	public void setAttributes(Map<String, String> attributes) {
		this.attributes = attributes;
	}
	
}


public class AlipayDualPlugin extends PaymentPlugin{
	
	
	protected Payment getPayment(String id) {
		//模擬查庫過程
		Payment payment = new Payment();
		payment.setId("1");
		payment.setAmount(new BigDecimal("0.01"));
		return payment;
	}
	
	protected  PluginConfig getPluginConfig() {
		//模擬獲取支付所需的引數
		PluginConfig pluginConfig = new PluginConfig();
		
		return pluginConfig;
	}
	//獲取回撥地址
	protected String getNotifyUrl(String id, NotifyMethod notify) {
		if (notify==NotifyMethod.sync) {
			//返回訂單地址
			return "http://XXXXX.com/oder/" + id ;
		}
		//返回回撥地址
		return  "http://XXXXX.com/payment/notify/" + id ;
	}
	
	@Override
	public Map<String, Object> getParameterMap(String id,
			HttpServletRequest request) {
		Payment payment = getPayment(id);
		PluginConfig pluginConfig = getPluginConfig();
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("service", "trade_create_by_buyer");
		parameterMap.put("partner", pluginConfig.getAttributes().get("partner"));
		parameterMap.put("_input_charset", "utf-8");
		parameterMap.put("sign_type", "MD5");
		//支付成功之後同步跳轉的頁面(一般跳轉到訂單頁面)
		parameterMap.put("return_url", getNotifyUrl(id, NotifyMethod.sync));
		//支付成功之後支付寶伺服器呼叫地址
		parameterMap.put("notify_url", getNotifyUrl(id, NotifyMethod.async));
		parameterMap.put("out_trade_no", id);
		parameterMap.put("subject", "");
		parameterMap.put("body", "");
		parameterMap.put("payment_type", "1");
		parameterMap.put("logistics_type", "EXPRESS");
		parameterMap.put("logistics_fee", "0");
		parameterMap.put("logistics_payment", "SELLER_PAY");
		parameterMap.put("price", payment.getAmount().setScale(2).toString());
		parameterMap.put("quantity", "1");
		parameterMap.put("seller_id",  pluginConfig.getAttributes().get("partner"));
		parameterMap.put("total_fee", payment.getAmount().setScale(2).toString());
		parameterMap.put("show_url", "");
		parameterMap.put("paymethod", "directPay");
		parameterMap.put("exter_invoke_ip", request.getLocalAddr());
		parameterMap.put("extra_common_param", "shopxx");
		parameterMap.put("sign", generateSign(parameterMap));
		return parameterMap;
	}

	//簽名工具
	private String generateSign(Map<String, ?> parameterMap) {
		PluginConfig pluginConfig = getPluginConfig();
		return DigestUtils.md5Hex(joinKeyValue(new TreeMap<String, Object>(parameterMap), null,  pluginConfig.getAttributes().get("key"), "&", true, "sign_type", "sign"));
	}
	
	protected String joinKeyValue(Map<String, Object> map, String prefix, String suffix, String separator, boolean ignoreEmptyValue, String... ignoreKeys) {
		List<String> list = new ArrayList<String>();
		if (map != null) {
			for (Entry<String, Object> entry : map.entrySet()) {
				String key = entry.getKey();
				String value = ConvertUtils.convert(entry.getValue());
				if (StringUtils.isNotEmpty(key) && !ArrayUtils.contains(ignoreKeys, key) && (!ignoreEmptyValue || StringUtils.isNotEmpty(value))) {
					list.add(key + "=" + (value != null ? value : ""));
				}
			}
		}
		return (prefix != null ? prefix : "") + StringUtils.join(list, separator) + (suffix != null ? suffix : "");
	}
	
	@Override
	public boolean verifyNotify(String id, HttpServletRequest request) {
		PluginConfig pluginConfig = getPluginConfig();
		Payment payment = getPayment(id);
		if (generateSign(request.getParameterMap()).equals(request.getParameter("sign")) && pluginConfig.getAttributes().get("partner").equals(request.getParameter("seller_id")) && id.equals(request.getParameter("out_trade_no"))
				&& ("WAIT_SELLER_SEND_GOODS".equals(request.getParameter("trade_status")) || "TRADE_SUCCESS".equals(request.getParameter("trade_status")) || "TRADE_FINISHED".equals(request.getParameter("trade_status"))) && payment.getAmount().compareTo(new BigDecimal(request.getParameter("total_fee"))) == 0) {
			Map<String, Object> parameterMap = new HashMap<String, Object>();
			parameterMap.put("service", "notify_verify");
			parameterMap.put("partner", pluginConfig.getAttributes().get("partner"));
			parameterMap.put("notify_id", request.getParameter("notify_id"));
			if ("true".equals(post("https://mapi.alipay.com/gateway.do", parameterMap))) {
				return true;
			}
		}
		return false;
	}
	protected String post(String url, Map<String, Object> parameterMap) {
		Assert.hasText(url);
		String result = null;
		HttpClient httpClient = new DefaultHttpClient();
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			if (parameterMap != null) {
				for (Entry<String, Object> entry : parameterMap.entrySet()) {
					String name = entry.getKey();
					String value = ConvertUtils.convert(entry.getValue());
					if (StringUtils.isNotEmpty(name)) {
						nameValuePairs.add(new BasicNameValuePair(name, value));
					}
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			result = EntityUtils.toString(httpEntity);
			EntityUtils.consume(httpEntity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

	@Override
	public String getNotifyMessage(NotifyMethod notifyMethod, HttpServletRequest request) {
		if (notifyMethod == NotifyMethod.async) {
			return "success";
		}
		return null;
	}

	@Override
	public String getRequestCharset() {
		return "UTF-8";
	}

}

接下來我們說一下微信支付,同樣的微信支付也有很多種,公眾號支付、掃碼支付(web端和線下支付)、app支付等,下面我為與公眾號支付為例

public class WeixinPayPlugin extends PaymentPlugin{
	protected Payment getPayment(String id) {
		//模擬查庫過程
		Payment payment = new Payment();
		payment.setId("1");
		payment.setAmount(new BigDecimal("0.01"));
		return payment;
	}
	
	protected static  PluginConfig getPluginConfig() {
		//模擬獲取支付所需的引數
		PluginConfig pluginConfig = new PluginConfig();
		
		return pluginConfig;
	}
	//獲取回撥地址
	protected String getNotifyUrl(String id, NotifyMethod notify) {
		if (notify==NotifyMethod.sync) {
			//返回訂單地址
			return "http://XXXXX.com/oder/" + id ;
		}
		//返回回撥地址
		return  "http://XXXXX.com/payment/notify/" + id ;
	}
	@Override
	public Map<String, Object> getParameterMap(String id,
			HttpServletRequest request) {
		Payment payment = getPayment(id);
		PluginConfig pluginConfig = getPluginConfig();
		SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
		parameterMap.put("appid",  pluginConfig.getAttributes().get("appid"));
		parameterMap.put("mch_id",pluginConfig.getAttributes().get("mch_id"));
		parameterMap.put("nonce_str", getRandomString(32));
		parameterMap.put("body","");
		parameterMap.put("out_trade_no", id);
		parameterMap.put("fee_type", "CNY");
		BigDecimal total = payment.getAmount().multiply(new BigDecimal(100));
		java.text.DecimalFormat df=new java.text.DecimalFormat("0");
		parameterMap.put("total_fee", df.format(total));
		parameterMap.put("spbill_create_ip", request.getLocalAddr());
		parameterMap.put("notify_url",  getNotifyUrl(id, NotifyMethod.async));
		parameterMap.put("trade_type", "NATIVE");
		
		parameterMap.put("product_id","");
		String sign = createSign("UTF-8", parameterMap);
		parameterMap.put("sign", sign);
		String requestXML = getRequestXml(parameterMap);
		String result = httpsRequest(
				"https://api.mch.weixin.qq.com/pay/unifiedorder", "POST",
				requestXML);
		Map<String, Object> map = null;
		try {
			map = doXMLParse(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return map;
	}

	@Override
	public boolean verifyNotify(String id, HttpServletRequest request) {
		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 result = new String(outSteam.toByteArray(), "utf-8");// 獲取微信呼叫我們notify_url的返回資訊
		Map<Object, Object> map = doXMLParse(result);
		if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
			SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
			String sign = (String) map.get("sign");
			for (Object keyValue : map.keySet()) {
				if(!keyValue.toString().equals("sign")){
					parameterMap.put(keyValue.toString(), map.get(keyValue));
				}
			}
			String createSign = createSign("UTF-8", parameterMap);
			if(createSign.equals(sign)){
				return true;
			}else{
				return false;
			}
		}
		return false;
	}

	@Override
	public String getNotifyMessage(NotifyMethod notifyMethod,
			HttpServletRequest request) {
		if (notifyMethod == NotifyMethod.async) {
			return "success";
		}
		return null;
	}

	@Override
	public String getRequestCharset() {
		return "UTF-8";
	}
	//隨機字串生成
		public static String getRandomString(int length) { //length表示生成字串的長度    
		       String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";       
		       Random random = new Random();       
		       StringBuffer sb = new StringBuffer();       
		       for (int i = 0; i < length; i++) {       
		           int number = random.nextInt(base.length());       
		           sb.append(base.charAt(number));       
		       }       
		       return sb.toString();       
		    }  
		//請求xml組裝
		  public static String getRequestXml(SortedMap<String,Object> parameters){
		        StringBuffer sb = new StringBuffer();
		        sb.append("<xml>");
		        Set es = parameters.entrySet();
		        Iterator it = es.iterator();
		        while(it.hasNext()) {
		            Map.Entry entry = (Map.Entry)it.next();
		            String key = (String)entry.getKey();
		            String value = (String)entry.getValue();
		            if ("attach".equalsIgnoreCase(key)||"body".equalsIgnoreCase(key)||"sign".equalsIgnoreCase(key)) {
		                sb.append("<"+key+">"+"<![CDATA["+value+"]]></"+key+">");
		            }else {
		                sb.append("<"+key+">"+value+"</"+key+">");
		            }
		        }
		        sb.append("</xml>");
		        return sb.toString();
		    }
		  //生成簽名
		  public static String createSign(String characterEncoding,SortedMap<String,Object> parameters){
			  PluginConfig pluginConfig = getPluginConfig();
			  StringBuffer sb = new StringBuffer();
		        Set es = parameters.entrySet();
		        Iterator it = es.iterator();
		        while(it.hasNext()) {
		            Map.Entry entry = (Map.Entry)it.next();
		            String k = (String)entry.getKey();
		            Object v = entry.getValue();
		            if(null != v && !"".equals(v)
		                    && !"sign".equals(k) && !"key".equals(k)) {
		                sb.append(k + "=" + v + "&");
		            }
		        }
		        sb.append("key=" + pluginConfig.getAttributes().get("appid"));
		        String sign = MD5Encode(sb.toString(), characterEncoding).toUpperCase();
		        return sign;
		    }
		  //請求方法
		  public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		        try {
		           
		            URL url = new URL(requestUrl);
		            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		          
		            conn.setDoOutput(true);
		            conn.setDoInput(true);
		            conn.setUseCaches(false);
		            // 設定請求方式(GET/POST)
		            conn.setRequestMethod(requestMethod);
		            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
		            // 當outputStr不為null時向輸出流寫資料
		            if (null != outputStr) {
		                OutputStream outputStream = conn.getOutputStream();
		                // 注意編碼格式
		                outputStream.write(outputStr.getBytes("UTF-8"));
		                outputStream.close();
		            }
		            // 從輸入流讀取返回內容
		            InputStream inputStream = conn.getInputStream();
		            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		            String str = null;
		            StringBuffer buffer = new StringBuffer();
		            while ((str = bufferedReader.readLine()) != null) {
		                buffer.append(str);
		            }
		            // 釋放資源
		            bufferedReader.close();
		            inputStreamReader.close();
		            inputStream.close();
		            inputStream = null;
		            conn.disconnect();
		            return buffer.toString();
		        } catch (ConnectException ce) {
		            System.out.println("連線超時:{}"+ ce);
		        } catch (Exception e) {
		        	System.out.println("https請求異常:{}"+ e);
		        }
		        return null;
		    }
		  //退款的請求方法
		  public static String httpsRequest2(String requestUrl, String requestMethod, String outputStr,String PaymentPluginId) throws Exception {
		        KeyStore keyStore  = KeyStore.getInstance("PKCS12");
		        StringBuilder res = new StringBuilder("");
		        SSLContext sslcontext=null;
		        if(PaymentPluginId.equals("weixinAppPay")){
		        FileInputStream instream = new FileInputStream(new File("/home/apiclient_cert.p12"));
		        try {
				keyStore.load(instream, "13XXXXXXXX".toCharArray());
		        } finally {
		            instream.close();
		        }
		         sslcontext = SSLContexts.custom()
		                .loadKeyMaterial(keyStore, "13XXXXXXXXX".toCharArray())
		                .build();
		        }else{
		        	 FileInputStream instream = new FileInputStream(new File("/home/apiclient_cert2.p12"));
		 	        try {
		 	            keyStore.load(instream, "1XXXXXXXXXX".toCharArray());
		 	        } finally {
		 	            instream.close();
		 	        }
		 	        sslcontext = SSLContexts.custom()
			                .loadKeyMaterial(keyStore, "1XXXXXXXXXXXX".toCharArray())
			                .build();
		        }
		        // Trust own CA and all self-signed certs
		       
		        // 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();
		        try {

		        	HttpPost httpost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");
		            httpost.addHeader("Connection", "keep-alive");
		            httpost.addHeader("Accept", "*/*");
		            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		            httpost.addHeader("Host", "api.mch.weixin.qq.com");
		            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
		            httpost.addHeader("Cache-Control", "max-age=0");
		            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
		        	 StringEntity entity2 = new StringEntity(outputStr ,Consts.UTF_8);
		        	 httpost.setEntity(entity2);

		            CloseableHttpResponse response = httpclient.execute(httpost);
		           
		            try {
		                HttpEntity entity = response.getEntity();
		                
		                if (entity != null) {
		                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
		                    String text;
		                    while ((text = bufferedReader.readLine()) != null) {
		                        res.append(text);
		                    }
		                   
		                }
		                EntityUtils.consume(entity);
		            } finally {
		                response.close();
		            }
		        } finally {
		            httpclient.close();
		        }
				return res.toString();
		        
		    }
		  //xml解析
		  public static Map doXMLParse(String strxml) throws JDOMException, IOException {
		        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
		        if(null == strxml || "".equals(strxml)) {
		            return null;
		        }
		        Map m = new HashMap();
		        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
		        SAXBuilder builder = new SAXBuilder();
		        Document doc = builder.build(in);
		        Element root = doc.getRootElement();
		        List list = root.getChildren();
		        Iterator it = list.iterator();
		        while(it.hasNext()) {
		            Element e = (Element) it.next();
		            String k = e.getName();
		            String v = "";
		            List children = e.getChildren();
		            if(children.isEmpty()) {
		                v = e.getTextNormalize();
		            } else {
		                v = getChildrenText(children);
		            }
		            
		            m.put(k, v);
		        }
		        
		        //關閉流
		        in.close();
		        
		        return m;
		    }
		  
		  public static String getChildrenText(List children) {
		        StringBuffer sb = new StringBuffer();
		        if(!children.isEmpty()) {
		            Iterator it = children.iterator();
		            while(it.hasNext()) {
		                Element e = (Element) it.next();
		                String name = e.getName();
		                String value = e.getTextNormalize();
		                List list = e.getChildren();
		                sb.append("<" + name + ">");
		                if(!list.isEmpty()) {
		                    sb.append(getChildrenText(list));
		                }
		                sb.append(value);
		                sb.append("</" + name + ">");
		            }
		        }
		        
		        return sb.toString();
		    }
		  public static String setXML(String return_code, String return_msg) {
		        return "<xml><return_code><![CDATA[" + return_code
		                + "]]></return_code><return_msg><![CDATA[" + return_msg
		                + "]]></return_msg></xml>";

		}  
		  private static String byteArrayToHexString(byte b[]) {
		        StringBuffer resultSb = new StringBuffer();
		        for (int i = 0; i < b.length; i++)
		            resultSb.append(byteToHexString(b[i]));

		        return resultSb.toString();
		    }

		    private static String byteToHexString(byte b) {
		        int n = b;
		        if (n < 0)
		            n += 256;
		        int d1 = n / 16;
		        int d2 = n % 16;
		        return hexDigits[d1] + hexDigits[d2];
		    }

		    public static String MD5Encode(String origin, String charsetname) {
		        String resultString = null;
		        try {
		            resultString = new String(origin);
		            MessageDigest md = MessageDigest.getInstance("MD5");
		            if (charsetname == null || "".equals(charsetname))
		                resultString = byteArrayToHexString(md.digest(resultString
		                        .getBytes()));
		            else
		                resultString = byteArrayToHexString(md.digest(resultString
		                        .getBytes(charsetname)));
		        } catch (Exception exception) {
		        }
		        return resultString;
		    }
		    
		    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
		        "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}


主要的方法都包含在上面了,這個程式碼是扣出來的,未進行驗證,但是獲取引數、微信的預支付、回撥的驗證方法是一定正確的,包括微信支付的退款(這裡強調一下,需要去微信支付官網下載證書,Java的需要p12)支付寶退款就不整理,直接貼一下

public Map<String, Object> getRefundParameterMap(Long id, HttpServletRequest request) {
		
		Map<String, Object> refundParameterMap = new HashMap<String, Object>();
		refundParameterMap.put("service", "refund_fastpay_by_platform_pwd");
		refundParameterMap.put("partner", "");
		refundParameterMap.put("_input_charset", "utf-8");
		refundParameterMap.put("sign_type", "MD5");
		refundParameterMap.put("notify_url",  "");
		refundParameterMap.put("seller_email", ".com");
		refundParameterMap.put("seller_id", "");
		refundParameterMap.put("refund_date", DateUtils.format(new Date(), DateUtils.FORMAT_LONG));
		refundParameterMap.put("batch_no", DateUtils.format(new Date(), DateUtils.FORMAT_DATE)+	refunds.getSn());
		refundParameterMap.put("batch_num", "1");
		refundParameterMap.put("detail_data", generateDetailData(refunds));
		refundParameterMap.put("sign", generateSign(refundParameterMap));
		return refundParameterMap;
	}
	private String generateDetailData(Refunds refunds) {
		Set<Payment> paymentSet =  refunds.getOrder().getPayments();
		List<Payment> paymentList = new ArrayList<Payment>(paymentSet);
		Payment payment = null;
		if(null!=paymentList){
			payment=paymentList.get(0);
		}
		StringBuffer data = new StringBuffer();
		data.append(payment.getTradeNo());
		data.append("^");
		java.text.DecimalFormat df=new java.text.DecimalFormat("0.00");
		data.append(df.format(refunds.getAmount()));
		data.append("^");
		data.append("協商退款");
		return data.toString();
	}
public boolean verifyNotify(HttpServletRequest request){
		if (generateSign(request.getParameterMap()).equals(request.getParameter("sign"))) {
			Map<String, Object> parameterMap = new HashMap<String, Object>();
			parameterMap.put("service", "notify_verify");
			parameterMap.put("partner", "2088311389671021");
			parameterMap.put("notify_id", request.getParameter("notify_id"));
			if ("true".equals(post("https://mapi.alipay.com/gateway.do", parameterMap))) {
				return true;
			}
		}
		return false;
	}


退款方法也可以方法介面中,剛開始考慮不周全,大家可以補一下
package test;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public abstract class PaymentPlugin {
	
	public enum NotifyMethod {

		/** 同步 */
		sync,

		/** 非同步 */
		async
	}
	
	/**
	 * 1、獲取發起訂單的引數(id是訂單號)
	 */

	public abstract Map<String, Object> getParameterMap(String id, HttpServletRequest request); 

	/**
	 * 2、訂單合法性驗證
	 */

	public abstract boolean verifyNotify(String id,  HttpServletRequest request);

	/**
	 * 3、通知支付吧微信伺服器支付成功訊息收到
	 */

	public abstract String getNotifyMessage(NotifyMethod notifyMethod, HttpServletRequest request);

	/**
	 * 4、編碼方式
	 */

	public abstract String getRequestCharset();
	/**
	 * 
	 *退款介面
	 */
	public abstract Map<String, Object>  getRefundParameterMap (String id, HttpServletRequest request);
}