即时到账接口不能使用httpclient会出现跨域问题
Alipay.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mice.pay.config.AliPayConfig;
import com.mice.pay.emuns.AliPayParasEmuns;
import com.mice.pay.emuns.GetAliPayParasEmuns;
import com.mice.pay.util.AlipayNotify;
import com.mice.pay.util.AlipaySubmit;
@SuppressWarnings("rawtypes")
public class Alipay implements Payable {
@Override
public String simplePay(Map<Enum, String> payParas, AliPayParasEmuns aliPayParas) {
String formHtml = "";
try {
formHtml = buildHtmlText(payParas, aliPayParas);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return formHtml;
}
/**
* @Description:阿里支付宝创建支付表单
* @date 2016年1月26日 下午1:45:29
* @field:PayUtil.java
* @return:String 创建的表单
* @param payParas
* 需要提交的参数 subject 商品名称 body 商品描述 total_fee 商品金额 out_trade_no
* 订单号(自动生成) 必须
* @param aliPayParas
* 支付用途
* @throws UnsupportedEncodingException
*/
private static String buildHtmlText(Map<Enum, String> payParas, AliPayParasEmuns aliPayParas)
throws UnsupportedEncodingException {
String sHtmlText = "";
switch (aliPayParas) {
case PAYMONEY:
sHtmlText = sendAlipayParasInFrom(payParas);
break;
case GOODSBUY:
sHtmlText=sendAlipayParasInHttpClient(payParas);
break;
default:
break;
}
return sHtmlText;
}
private static String sendAlipayParasInHttpClient(Map<Enum, String> payParas) throws UnsupportedEncodingException {
List<Enum> keys = new ArrayList<Enum>(payParas.keySet());
Map<String, String> sParaTemp = new Hashtable<String, String>();
for (int i = 0; i < keys.size(); i++) {
GetAliPayParasEmuns name = (GetAliPayParasEmuns) keys.get(i);
String value = payParas.get(name);
sParaTemp.put(new String(name.toString().getBytes("ISO-8859-1"), "UTF-8"), value);
}
// 把请求参数打包成数组
sParaTemp.put("service", AliPayConfig.service);
sParaTemp.put("partner", AliPayConfig.partner);
sParaTemp.put("seller_email", AliPayConfig.seller_email);
sParaTemp.put("_input_charset", AliPayConfig.input_charset);
sParaTemp.put("payment_type", AliPayConfig.payment_type);
sParaTemp.put("notify_url", AliPayConfig.notify_url);
sParaTemp.put("return_url", AliPayConfig.return_url);
sParaTemp.put("show_url", AliPayConfig.show_url);
sParaTemp.put("anti_phishing_key", AliPayConfig.anti_phishing_key);
sParaTemp.put("exter_invoke_ip", AliPayConfig.exter_invoke_ip);
String html=AlipaySubmit.buildRequest(sParaTemp);
return html;
}
private static String sendAlipayParasInFrom(Map<Enum,String> payParas) throws UnsupportedEncodingException {
String sHtmlText="";
List<Enum> keys = new ArrayList<Enum>(payParas.keySet());
Map<String, String> sParaTemp = new Hashtable<String, String>();
for (int i = 0; i < keys.size(); i++) {
GetAliPayParasEmuns name = (GetAliPayParasEmuns) keys.get(i);
String value = payParas.get(name);
sParaTemp.put(new String(name.toString().getBytes("ISO-8859-1"), "UTF-8"), value);
}
// 把请求参数打包成数组
sParaTemp.put("service", AliPayConfig.service);
sParaTemp.put("partner", AliPayConfig.partner);
sParaTemp.put("seller_email", AliPayConfig.seller_email);
sParaTemp.put("_input_charset", AliPayConfig.input_charset);
sParaTemp.put("payment_type", AliPayConfig.payment_type);
sParaTemp.put("notify_url", AliPayConfig.notify_url);
sParaTemp.put("return_url", AliPayConfig.return_url);
sParaTemp.put("show_url", AliPayConfig.show_url);
sParaTemp.put("anti_phishing_key", AliPayConfig.anti_phishing_key);
sParaTemp.put("exter_invoke_ip", AliPayConfig.exter_invoke_ip);
sHtmlText = AlipaySubmit.buildRequest(sParaTemp, "post", "确认");
return sHtmlText;
}
/**
* @Description:阿里支付的同步通知
* @date 2016年1月26日 下午2:34:51
* @field:PayUtil.java
* @return: String 根据字符串完成响应业务逻辑
* @param request
* 请求
* @throws UnsupportedEncodingException
*/
@Override
public String returnUrl(HttpServletRequest request) {
// 获取支付宝GET过来反馈信息
Map<String, String> params = new HashMap<String, String>();
Map 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] + ",";
}
try {
// 乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
params.put(name, valueStr);
}
// 获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
// 交易状态
String trade_status = "";
try {
trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
// 计算得出通知验证结果
boolean verify_result = AlipayNotify.verify(params);
if (verify_result) {// 验证成功
//
// 请在这里加上商户的业务逻辑程序代码
// ——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
/*if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
// 判断该笔订单是否在商户网站中已经做过处理
// 如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
// 如果有做过处理,不执行商户的业务程序
}*/
// 该页面可做页面美工编辑
return trade_status;
// ——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
//
} else {
// 该页面可做页面美工编辑
return trade_status;
}
}
/**
* @Description:阿里支付的异步通知
* @date 2016年1月26日 下午2:36:13
* @field:PayUtil.java
* @return: String 根据字符串完成响应业务逻辑
* @param request
* 请求
* @param response
* 响应
* @return
* @throws IOException
*/
@Override
public String notifyUrl(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> params = new HashMap<String, String>();
Map 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] + ",";
}
// 乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
params.put(name, valueStr);
}
// 获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
// 交易状态
String trade_status = "";
try {
trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
if (AlipayNotify.verify(params)) {// 验证成功
//
// 请在这里加上商户的业务逻辑程序代码
// ——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
/*
* if (trade_status.equals("TRADE_FINISHED")) { //
* 判断该笔订单是否在商户网站中已经做过处理 //
* 如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //
* 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的 //
* 如果有做过处理,不执行商户的业务程序
*
* // 注意: // 退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知 } else if
* (trade_status.equals("TRADE_SUCCESS")) { // 判断该笔订单是否在商户网站中已经做过处理
* // 如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //
* 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的 //
* 如果有做过处理,不执行商户的业务程序 flag = true; // 注意: // 付款完成后,支付宝系统发送该交易状态通知 }
*/
// ——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
try {
// 请不要修改或删除
response.getWriter().println("success");
} catch (IOException e) {
e.printStackTrace();
}
return trade_status;
//
} else {// 验证失败
try {
// 请不要修改或删除
response.getWriter().println("fail");
} catch (IOException e) {
e.printStackTrace();
}
return trade_status;
}
}
}
AlipaySubmit.java
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import com.mice.pay.config.AliPayConfig;
import com.mice.pay.config.MD5;
/* *
*类名:AlipaySubmit
*功能:支付宝各接口请求提交类
*详细:构造支付宝各接口表单HTML文本,获取远程HTTP数据
*版本:3.3
*日期:2012-08-13
*说明:
*以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
*该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
@SuppressWarnings("unchecked")
public class AlipaySubmit {
/**
* 支付宝提供给商户的服务接入网关URL(新)
*/
private static final String ALIPAY_GATEWAY_NEW = "https://mapi.alipay.com/gateway.do?";
/**
* 生成签名结果
*
* @param sPara
* 要签名的数组
* @return 签名结果字符串
*/
public static String buildRequestMysign(Map<String, String> sPara) {
String prestr = AlipayCore.createLinkString(sPara); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
String mysign = "";
if (AliPayConfig.sign_type.equals("MD5")) {
mysign = MD5.sign(prestr, AliPayConfig.key, AliPayConfig.input_charset);
}
return mysign;
}
/**
* 生成要请求给支付宝的参数数组
*
* @param sParaTemp
* 请求前的参数数组
* @return 要请求的参数数组
*/
private static Map<String, String> buildRequestPara(Map<String, String> sParaTemp) {
// 除去数组中的空值和签名参数
Map<String, String> sPara = AlipayCore.paraFilter(sParaTemp);
// 生成签名结果
String mysign = buildRequestMysign(sPara);
// 签名结果与签名方式加入请求提交参数组中
sPara.put("sign", mysign);
sPara.put("sign_type", AliPayConfig.sign_type);
return sPara;
}
/**
* 建立请求,以表单HTML形式构造(默认)
*
* @param sParaTemp
* 请求参数数组
* @param strMethod
* 提交方式。两个值可选:post、get
* @param strButtonName
* 确认按钮显示文字
* @return 提交表单HTML文本
*/
public static String buildRequest(Map<String, String> sParaTemp, String strMethod, String strButtonName) {
// 待请求参数数组
Map<String, String> sPara = buildRequestPara(sParaTemp);
List<String> keys = new ArrayList<String>(sPara.keySet());
StringBuffer sbHtml = new StringBuffer();
sbHtml.append("<form id=\"alipaysubmit\" name=\"alipaysubmit\" action=\"" + ALIPAY_GATEWAY_NEW
+ "_input_charset=" + AliPayConfig.input_charset + "\" method=\"" + strMethod + "\">");
for (int i = 0; i < keys.size(); i++) {
String name = (String) keys.get(i);
String value = (String) sPara.get(name);
sbHtml.append("<input type=\"hidden\" name=\"" + name + "\" value=\"" + value + "\"/>");
}
// submit按钮控件请不要含有name属性
sbHtml.append("<input type=\"submit\" value=\"" + strButtonName + "\" style=\"display:none;\"></form>");
sbHtml.append("<script>document.forms['alipaysubmit'].submit();</script>");
return sbHtml.toString();
}
/**
* 建立请求,以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果
*
* @param sParaTemp
* 请求参数数组
* @return 支付宝处理结果
*/
public static String buildRequest(Map<String, String> sParaTemp) {
// 待请求参数数组
Map<String, String> sPara = buildRequestPara(sParaTemp);
HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance();
String html = httpProtocolHandler.execute(sPara,ALIPAY_GATEWAY_NEW);
return html;
}
/**
* 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数 注意:远程解析XML出错,与服务器是否支持SSL等配置有关
*
* @return 时间戳字符串
* @throws IOException
* @throws DocumentException
* @throws MalformedURLException
*/
public static String query_timestamp() {
// 构造访问query_timestamp接口的URL串
String strUrl = ALIPAY_GATEWAY_NEW + "service=query_timestamp&partner=" + AliPayConfig.partner
+ "&_input_charset" + AliPayConfig.input_charset;
StringBuffer result = new StringBuffer();
SAXReader reader = new SAXReader();
Document doc = null;
try {
doc = reader.read(new URL(strUrl).openStream());
} catch (Exception e) {
e.printStackTrace();
}
List<Node> nodeList = doc.selectNodes("//alipay/*");
for (Node node : nodeList) {
// 截取部分不需要解析的信息
if (node.getName().equals("is_success") && node.getText().equals("T")) {
// 判断是否有成功标示
List<Node> nodeList1 = doc.selectNodes("//response/timestamp/*");
for (Node node1 : nodeList1) {
result.append(node1.getText());
}
}
}
return result.toString();
}
}
HttpProtocolHandler.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.mice.pay.config.AliPayConfig;
public class HttpProtocolHandler {
/** 设置连接超时时间,单位毫秒 */
private static final int CONNECTTIMEOUT = 5000;
/** 设置从connect Manager获取Connection 超时时间,单位毫秒 */
private static final int CONNECTIONREQUESTTIMEOUT = 1000;
/** 请求获取数据的超时时间,单位毫秒 */
private static final int SOCKETTIMEOUT = 5000;
/** 对每个指定连接的服务器(指定的ip)可以创建并发数socket进行访问 */
private static final int DEFAULTMAXPERROUTE = 5;
/** 创建socket的上限 */
private static final int MAXTOTAL = 200;
private static HttpProtocolHandler httpProtocolHandler = new HttpProtocolHandler();
/**
* 工厂方法
*
* @return
*/
public static HttpProtocolHandler getInstance() {
return httpProtocolHandler;
}
private HttpProtocolHandler() {
}
public String execute(Map<String, String> sPara, String url) {
PoolingHttpClientConnectionManager connManager = ignoreSSL();
// 创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager)
.setRedirectStrategy(new LaxRedirectStrategy()).build();
// 创建post方式请求对象
HttpPost httpPost = new HttpPost(url + "_input_charset=" + AliPayConfig.input_charset);
// 设置请求参数
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间,单位毫秒。
.setConnectTimeout(CONNECTTIMEOUT).setConnectionRequestTimeout(CONNECTIONREQUESTTIMEOUT)
// 请求获取数据的超时时间,单位毫秒。
.setSocketTimeout(SOCKETTIMEOUT).build();
httpPost.setConfig(requestConfig);
// 装填参数
List<NameValuePair> nvps = new LinkedList<NameValuePair>();
if (sPara != null) {
for (Entry<String, String> entry : sPara.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
// 设置参数到请求对象中
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps, AliPayConfig.input_charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 设置header信息
// 指定报文头【Content-type】、【User-Agent】
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// 执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = null;
try {
response = client.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 获取结果实体
HttpEntity entity = response.getEntity();
String body = "";
if (entity != null) {
// 按指定编码转换结果实体为String类型
try {
body = EntityUtils.toString(entity, AliPayConfig.input_charset);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
// 自动释放连接
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 释放链接
try {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("请求地址:" + url + "_input_charset=" + AliPayConfig.input_charset);
System.out.println("请求参数:" + nvps.toString());
return body;
}
private PoolingHttpClientConnectionManager ignoreSSL() {
// 采用绕过验证的方式处理https请求
SSLContext sslcontext = null;
try {
sslcontext = createIgnoreVerifySSL();
} catch (KeyManagementException e1) {
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
// 设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext)).build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connManager.setDefaultMaxPerRoute(DEFAULTMAXPERROUTE);
connManager.setMaxTotal(MAXTOTAL);
return connManager;
}
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
private SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
}