这段时间把支付基本搞完了,因为做的过程中遇到许多问题,特地记录下来,同时方便其他java coder,废话少说,下面开始。
整体思路:在后台,根据参数创建支付宝客户端AlipayClient,发送参数到支付宝,支付宝直接返回一个表单,我们只需要将表单输出到页面上,后续支付宝异步通知,比较重要是验签,支付宝也提供的工具,比较方便。微信支付java开发详细
(jar包或maven的引入这里省略)
1、申请支付宝支付,这里大家自己研究,网上很多教程。
2、创建支付
/**
* 调用支付宝支付alipay.trade.page.pay
* 商户系统请求支付宝接口alipay.trade.page.pay,支付宝对商户请求参数进行校验,而后重定向至用户登录页面。
*
* @param model
* @return
* @throws Exception
*/
public String createAlipay(Model model, String order_no, BigDecimal amount, Integer resource_trad_id, String trad_type, HttpServletResponse response) throws Exception {
String form = "";
User user = (User) model.asMap().get("user");
//生成一笔预付订单流水
String trad_no = "PC_ALIPAY" + OrderNoUtil.leadsNo();//订单流水号
ShareUserTrad trad = new ShareUserTrad();
trad.setResourceTradId(resource_trad_id);
trad.setUserId(user.getId());
trad.setCreatedBy(user.getId());
trad.setLastUpdBy(user.getId());
trad.setOnlineOfflineFlag("0");//线上
trad.setOrderNo(order_no);
trad.setUserTradAmount(amount);
trad.setTradMethod("3");//支付宝
trad.setPayReceiveFlag("2");//支出
trad.setSuccessFlag("0");//交易进行中
trad.setTradType("1");//订单支付
trad.setTradNo(trad_no);
trad.setModifyNum(0);
shareUserTradMapper.insertSelective(trad);
try {
//初始化客户端
AlipayClient alipayClient = new DefaultAlipayClient(Config.alipay_url, Config.alipay_appid, Config.alipay_app_private_key, Config.alipay_format, Config.alipay_charset, Config.alipay_app_public_key, Config.alipay_sign_type);
//创建API对应的request
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
alipayRequest.setReturnUrl("");//回退到订单列表页面
alipayRequest.setNotifyUrl("");//在公共参数中设置回跳和通知地址
alipayRequest.setBizContent("{" +
" \"out_trade_no\":\"" + trad_no + "\"," +
" \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
//" \"total_amount\":" + amount.toString() + "," +
"\"total_amount\":\"0.01\"," +
" \"subject\":\"订单支付\"," +
" \"body\":\"订单:" + order_no + "支付\"," +
" \"passback_params\":\"" + order_no + "\"" +
" }");//填充业务参数
form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
} catch (Exception e) {
e.printStackTrace();
String sOut = "";
StackTraceElement[] trace = e.getStackTrace();
for (StackTraceElement s : trace) {
sOut += "\tat " + s + "\r\n";
}
model.addAttribute("failMsg", sOut + "alipay_url:" + Config.alipay_url);
return "/pay/payFail";
}
response.setContentType("text/html;charset=" + Config.alipay_charset);
response.getWriter().write(form);//直接将完整的表单html输出到页面
response.getWriter().flush();
response.getWriter().close();
return null;
}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/sanxing/article-70423-1.html