//按钮触发跳转到下面js
<a href="javascript:void(0);" id="pay">立即支付</a>
//js判断后成功就跳转到下面的action
$('#pay').click(function(e){
var btn = false;$('input[name="pay_yh"]').each(function(index, element) {
if( element.checked ){
btn = true;
}
});
if( btn ){//成功
var form = $("input:checked").attr('data');
if($('#'+form).length == 0 && $('#alipayment').length == 0){
alert("num1")
window.location = baseContext + "/user/1_0";
}else if(form == 'alipayment' && $('#'+form).length >0){
alert("num2")
layer.open({
type: 1,
title: false, //不显示标题
content: $('.pay_box'), //捕获的元素
area: ['459px', '146px']
});
$('#'+form).submit();
}else{
alert("num3")
layer.msg('您所选的支付方式尚未开通!(目前仅支持 支付宝)');
e.preventDefault();
}
}else{
layer.msg('请选择支付方式');
e.preventDefault();
}
})
})
//上面js将跳转到前台的这个action并将表单的内容提交到jsp
<form id="alipayment" name="alipayment" action="${base}/plugin/alipay/alipayapi.jsp" method="post" target="_blank">
<input type="hidden" name="WIDout_trade_no" value="${alipay.WIDout_trade_no}"/>
<input type="hidden" name="WIDsubject" value="${alipay.WIDsubject}"/>
<input type="hidden" name="WIDtotal_fee" value="${alipay.WIDtotal_fee}"/>
<input type="hidden" name="WIDbody" value="${alipay.WIDbody}"/>
<input type="hidden" name="WIDshow_url" value="${alipay.WIDshow_url}"/>
</form>
---------------------------------------------------------------------------------------------------------------------------------------------------------
//这个jsp主要是把你要发送到支付宝平台的信息包装一下然后发送出去
//alipayapi.jsp
<%
/* *
*功能:即时到账交易接口接入页
*版本:3.3
*日期:2012-08-14
*说明:
*以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
*该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*************************注意*****************
*如果您在接口集成过程中遇到问题,可以按照下面的途径来解决
*1、商户服务中心(https://b.alipay.com/support/helperApply.htm?action=consultationApply),提交申请集成协助,我们会有专业的技术工程师主动联系您协助解决
*2、商户帮助中心(http://help.alipay.com/support/232511-16307/0-16307.htm?sh=Y&info_type=9)
*3、支付宝论坛(http://club.alipay.com/read-htm-tid-8681712.html)
*如果不想使用扩展功能请把扩展功能参数赋空值。
**********************************************
*/
%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.service.plugin.pay.alipay.config.*"%>
<%@ page import="com.service.plugin.pay.alipay.util.*"%>
<%@ page import="java.util.HashMap"%>
<%@ page import="java.util.Map"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>支付宝即时到账交易接口</title>
</head>
<%
请求参数//
StringBuffer url = request.getRequestURL();
String baseContextPath = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(application.getContextPath()).append("/").toString();
//支付类型
String payment_type = "1";
//必填,不能修改
//服务器异步通知页面路径
String notify_url = baseContextPath + "pay/alipay_notify";
//需http://格式的完整路径,不能加?id=123这类自定义参数
//页面跳转同步通知页面路径
String return_url = baseContextPath + "pay/alipay_return";
//需http://格式的完整路径,不能加?id=123这类自定义参数,不能写成http://localhost/
//商户订单号
String out_trade_no = request.getParameter("WIDout_trade_no");//new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//商户网站订单系统中唯一订单号,必填
//订单名称
String subject = request.getParameter("WIDsubject");//new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
//必填
//付款金额
String total_fee = request.getParameter("WIDtotal_fee");//new String(request.getParameter("WIDtotal_fee").getBytes("ISO-8859-1"),"UTF-8");
//必填
//订单描述
String body = request.getParameter("WIDbody");//new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");
//商品展示地址
String show_url = request.getParameter("WIDshow_url");//new String(request.getParameter("WIDshow_url").getBytes("ISO-8859-1"),"UTF-8");
//需以http://开头的完整路径,例如:http://www.商户网址.com/myorder.html
//防钓鱼时间戳
String anti_phishing_key = "";
//若要使用请调用类文件submit中的query_timestamp函数
//客户端的IP地址
String exter_invoke_ip = "";
//非局域网的外网IP地址,如:221.0.0.1
//
//把请求参数打包成数组
Map<String, String> sParaTemp = new HashMap<String, String>();
sParaTemp.put("service", "create_direct_pay_by_user");
sParaTemp.put("partner", AlipayConfig.partner);
sParaTemp.put("seller_email", AlipayConfig.seller_email);
sParaTemp.put("_input_charset", AlipayConfig.input_charset);
sParaTemp.put("payment_type", payment_type);
sParaTemp.put("notify_url", notify_url);
sParaTemp.put("return_url", return_url);
sParaTemp.put("out_trade_no", out_trade_no);
sParaTemp.put("subject", subject);
sParaTemp.put("total_fee", total_fee);
sParaTemp.put("body", body);
sParaTemp.put("show_url", show_url);
sParaTemp.put("anti_phishing_key", anti_phishing_key);
sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
//建立请求
String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
out.println(sHtmlText);
%>
<body>
</body>
</html>
-------------------------------------------------------------------------------------------------------------------------------
package com.service.plugin.pay.alipay.util;
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.apache.commons.httpclient.NameValuePair;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import com.service.plugin.pay.alipay.config.AlipayConfig;
import com.service.plugin.pay.alipay.sign.MD5;
import com.service.plugin.pay.alipay.util.httpClient.HttpProtocolHandler;
import com.service.plugin.pay.alipay.util.httpClient.HttpRequest;
import com.service.plugin.pay.alipay.util.httpClient.HttpResponse;
import com.service.plugin.pay.alipay.util.httpClient.HttpResultType;
//这个只是支付宝各接口请求提交类
/* *
*类名:AlipaySubmit
*功能:支付宝各接口请求提交类
*详细:构造支付宝各接口表单HTML文本,获取远程HTTP数据
*版本:3.3
*日期:2012-08-13
*说明:
*以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
*该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
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();
}
//
/**
* 建立请求,以表单HTML形式构造,带文件上传功能
* @param sParaTemp 请求参数数组
* @param strMethod 提交方式。两个值可选:post、get
* @param strButtonName 确认按钮显示文字
* @param strParaFileName 文件上传的参数名
* @return 提交表单HTML文本
*/
public static String buildRequest(Map<String, String> sParaTemp, String strMethod, String strButtonName, String strParaFileName) {
//待请求参数数组
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\" enctype=\"multipart/form-data\" 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 + "\"/>");
}
sbHtml.append("<input type=\"file\" name=\"" + strParaFileName + "\" />");
//submit按钮控件请不要含有name属性
sbHtml.append("<input type=\"submit\" value=\"" + strButtonName + "\" style=\"display:none;\"></form>");
return sbHtml.toString();
}
/**
* 建立请求,以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果
* 如果接口中没有上传文件参数,那么strParaFileName与strFilePath设置为空值
* 如:buildRequest("", "",sParaTemp)
* @param strParaFileName 文件类型的参数名
* @param strFilePath 文件路径
* @param sParaTemp 请求参数数组
* @return 支付宝处理结果
* @throws Exception
*/
public static String buildRequest(String strParaFileName, String strFilePath,Map<String, String> sParaTemp) throws Exception {
//待请求参数数组
Map<String, String> sPara = buildRequestPara(sParaTemp);
HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance();
HttpRequest request = new HttpRequest(HttpResultType.BYTES);
//设置编码集
request.setCharset(AlipayConfig.input_charset);
request.setParameters(generatNameValuePair(sPara));
request.setUrl(ALIPAY_GATEWAY_NEW+"_input_charset="+AlipayConfig.input_charset);
HttpResponse response = httpProtocolHandler.execute(request,strParaFileName,strFilePath);
if (response == null) {
return null;
}
String strResult = response.getStringResult();
return strResult;
}
/**
* MAP类型数组转换成NameValuePair类型
* @param properties MAP类型数组
* @return NameValuePair类型数组
*/
private static NameValuePair[] generatNameValuePair(Map<String, String> properties) {
NameValuePair[] nameValuePair = new NameValuePair[properties.size()];
int i = 0;
for (Map.Entry<String, String> entry : properties.entrySet()) {
nameValuePair[i++] = new NameValuePair(entry.getKey(), entry.getValue());
}
return nameValuePair;
}
/**
* 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数
* 注意:远程解析XML出错,与服务器是否支持SSL等配置有关
* @return 时间戳字符串
* @throws IOException
* @throws DocumentException
* @throws MalformedURLException
*/
@SuppressWarnings("unchecked")
public static String query_timestamp() throws MalformedURLException,
DocumentException, IOException {
//构造访问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 = reader.read(new URL(strUrl).openStream());
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();
}
}
------------------------------------------------------------------------------------------------------------------------
package com.controller.basic;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.service.cache.OrderCacheService;
import com.service.freemarker.FreemarkerCommonService;
import com.service.plugin.pay.PayService;
import com.service.plugin.pay.alipay.util.AlipayNotify;
/**
*处理付款 交互控制层
*
* @author Jackie
* @since 2015-09-08
* @version 1.0
*/
@Controller
@RequestMapping("pay")
public class PayController extends BasicController {
@Resource
private PayService payService;
@Resource
private OrderCacheService orderCacheService;
@Resource
private FreemarkerCommonService freemarkerCommonService;
/**
* 处理支付宝的异步支付响应请求
* @param request
* @param response
* @throws IOException
*/
@SuppressWarnings("rawtypes")
@RequestMapping(value = { "alipay_notify" }, method = RequestMethod.POST)
public void acceptAliPayNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取支付宝POST过来反馈信息
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 out_trade_no = request.getParameter("out_trade_no");//new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//支付宝交易号
String trade_no = request.getParameter("trade_no");//new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
//交易状态
String trade_status = request.getParameter("trade_status");//new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
//
String total_fee = request.getParameter("total_fee");
//获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
if(AlipayNotify.verify(params)){//验证成功
this.payService.updateOrderByAlipay(params,out_trade_no, trade_no, trade_status, total_fee);
response.getWriter().write("success");
this.orderCacheService.refreshOrderCache();
}else{//验证失败
response.getWriter().write("fail");
}
}
//支付成功或者失败都有一个响应回来,然后在这里进行处理
/**
* 处理支付宝的页面通知支付响应请求
* @param request
* @param response
* @return
* @throws IOException
*/
@SuppressWarnings("rawtypes")
@RequestMapping(value = { "alipay_return" }, method = RequestMethod.GET)
public String acceptAliPayReturn(ModelMap model,HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取支付宝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] + ",";
}
//乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
params.put(name, valueStr);
}
//获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
//商户订单号
String out_trade_no = request.getParameter("out_trade_no");// new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//支付宝交易号
String trade_no = request.getParameter("trade_no");//new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
//交易状态
String trade_status = request.getParameter("trade_status");//new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
//
String total_fee = request.getParameter("total_fee");
//获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
this.freemarkerCommonService.initSharedData(model);
if(AlipayNotify.verify(params)){//验证成功
Long orderId = this.payService.updateOrderByAlipay(params,out_trade_no, trade_no, trade_status, total_fee);
model.addAttribute("order", orderCacheService.getOrderById(orderId));
this.orderCacheService.refreshOrderCache();//
return "/kzgui/cart/pay_list";
}else{
//TODO 出错处理
return "redirect:/user/1_0";
}
}
}