/**   
* @Title: AlipayNotify.java 
* @Package com.platform.util 
* @Description: TODO(用一句话描述该文件做什么) 
* @author kiosk
* @date 2017年9月13日 下午2:24:24 
* @version V1.0   
*/
package com.platform.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;

/** 
 * @ClassName: AlipayNotify 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author kiosk
 * @date 2017年9月13日 下午2:24:24 
 *  
 */
public class AlipayNotify {
	private static final String HTTPS_VERIFY_URL="https://mapi.alipay.com/gateway.do?service=notify_verify&";
	private static String checkUrl(String urlvalue){
		String inputLine="";
		try {
			URL url=new URL(urlvalue);
		    HttpURLConnection urlConnection= (HttpURLConnection)url.openConnection();
		    BufferedReader in=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
		    inputLine=in.readLine().toString();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return inputLine;
	}
	private static String verifyResponse(String notify_id){
		String partner=ConstantsUtil.PARTNER;
		String veryfy_url=HTTPS_VERIFY_URL+"partner="+partner+"&notify_id="+notify_id;
		return checkUrl(veryfy_url);
	}
	private static boolean getRSASignVerify(Map<String,String> params,String sign){
		Map<String,String> sParaNew=AlipayCore.paraFilter(params);
		String preSignStr=AlipayCore.createLinkString(sParaNew);
		boolean isSign=false;
		 try {
			isSign=AlipaySignature.rsaCheckContent(preSignStr,sign,ConstantsUtil.ALIPAY_PUBLIC_KEY, ConstantsUtil.CHARSET);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return isSign;
	}
	public static boolean verify(Map<String,String> params){
		String responseTxt="true";
		if(params.get("notify_id")!=null){
			String notify_id=params.get("notify_id");
			responseTxt=verifyResponse(notify_id);
		}
		String sign="";
		if(params.get("sign")!=null){
			sign=params.get("sign");
		}
		boolean isSign=getRSASignVerify(params, sign);
		if(isSign&&responseTxt.equals("true")){
			return true;
		}else{
			return false;
		}
		
	}
}
