支付宝支付需要的jar包如下:
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>3.7.26.ALL</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.34</version>
<scope>compile</scope>
</dependency>
在服务配置文件.yaml下面配置支付宝的同步回调页面和异步回调接口
注意:异步回调接口中处理支付成功后的业务逻辑
此处由于项目前端路由配置原因:同步回调页面被写到了项目中
alipay:
notifyUrl: http://hbbonc.natapp1.cc/portal/nebula-pay/ali-rec
returnUrl: http://localhost:10101/portal/index.html
前端回调页面:由于支付宝支付时打开的是第三方(支付宝)的接口,需要一个回调页面来跳转到我们自己的网站。
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>回调页面</title>
<style>
body{width: 100%;}
.back-page{width: 100%; height: 100%; padding: 10px; text-align: center; font-size: 16px; padding-top: 20px}
.back-page-box{width: 100%; height: 100%}
.back-page-top{margin-top: 70px;}
.back-page-top span{display: block; width: 60px; height: 60px; border-radius: 30px; background-color: #3388ff; font-size: 32px; color: #fff; margin: 0 auto; line-height: 60px}
.back-page-middle{margin-top: 10px}
.back-page-middle span{font-size: 18px}
.back-page-bottom{margin-top: 20px}
.back-page-bottom button{width: 110px;height: 40px;font-size: 14px; background-color: #fff;box-shadow: none;border: 1px solid #ff9b0b;color: #ff9b0b}
</style>
</head>
<body>
<div class='back-page'>
<div class='back-page-box'>
<div class='back-page-top'>
<span>√</span>
</div>
<div class='back-page-middle'>
<span>支付成功</span>
</div>
<div class='back-page-bottom'>
<button id='button'>返回订单列表</button>
</div>
</div>
</div>
</body>
<script>
var btn = document.getElementById('button')
btn.addEventListener('click', function(){
window.location.reload()
window.history.go(-1)
},false)
</script>
</html>
支付宝配置文件:
AlipayConfig,此文件主要用于配置支付宝的公钥以及私钥,回调地址,回调页面
应用ID:需要用户去支付宝开放平台申请开通
签名方式:RSA2
字符编码格式:UTF-8
生产环境调用网关:https://openapi.alipay.com/gateway.do
@Component
public class AlipayConfig {
@Value("${alipay.notifyUrl}")
private String notifyUrl;
@Value("${alipay.returnUrl}")
private String returnUrl;
@PostConstruct
private void init(){
notify_url=notifyUrl;
return_url=returnUrl;
}
//配置您的基本信息
// 应用ID /自己申请的appid,支付宝的私钥及公钥
public static String app_id ="********";
// 商户私钥,您的PKCS8格式RSA2私钥
//生产环境商户私钥
public static String merchant_private_key = "*******";
// 支付宝公钥
//生产环境支付宝公钥
public static String alipay_public_key = "**********";
// 服务器异步通知页面路径
public static String notify_url ;
// 页面跳转同步通知页面路径
public static String return_url ;
// 签名方式
public static String sign_type = "RSA2";
// 字符编码格式
public static String charset = "utf-8";
//生产环境网关
public static String gatewayUrl = "https://openapi.alipay.com/gateway.do";
// ֧log
public static String log_path = "/home/sce/sce_service/key/log";
//配置您的基本信息
/**
* 写日志,方便测试
* @param sWord
*/
public static void logResult(String sWord) {
FileWriter writer = null;
try {
writer = new FileWriter(log_path + "alipay_log_" + System.currentTimeMillis()+".txt");
writer.write(sWord);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
此处可以将所有支付宝配置信息都写入服务的配置文件中,使用@Value注解进行取值,如下:
alipay:
app_id: *******
merchant_private_key: *******
alipay_public_key : *****
notifyUrl: http://hbbonc.natapp1.cc/portal/nebula-pay/ali-rec
returnUrl: http://localhost:10101/portal/index.html
sign_type :RSA2
charset : utf-8
gatewayUrl : https://openapi.alipay.com/gateway.do
取值时使用@Value注解,如果需要将取得的值转换为静态变量,则可以使用@PostConstruct来实现
public class AliPayConfig{
@Value("${alipay.notifyUrl}")
private String notifyUrl;
@Value("${alipay.returnUrl}")
private String returnUrl;
@Value("${alipay.app_id}")
private String appId;
// 此处省略其它参数取值,参照上面的取值方式
.........
// 此方法用于将非静态变量转为静态变量
@PostConstruct
public void init(){
app_id=appId;
return_url=returnUrl;
notify_url=notifyUrl;
........
}
public static String app_id;
public static String notify_url;
//以下为其它配置信息
.........
}
支付时,客户端用户点击提交订单,跳转到支付界面,选择支付宝支付,调用后端支付接口生成支付宝第三方支付页面,并直接输出到前台
@RequestMapping("/pay")
@RestController
public class PayController {
private final AliPayService aliPayService;
public PayController(AliPayService aliPayService){
this.aliPayService=aliPayService;
}
public void aliPay(HttpServletRequest httpServletRequest
,HttpServletResponse httpServletResponse
,@RequestParam( "WIDout_trade_no" ) String WIDout_trade_no
,@RequestParam( "WIDtotal_amount" ) String WIDtotal_amount
,@RequestParam( "WIDsubject" ) String WIDsubject
,@RequestParam( "WIDbody" ) String WIDbody){
//根据业务需要,可以先进行支付相关的日志记录,只要调用了支付接口,不管用户是否进行支付,均可记录到数据库中
//此demo只做支付操作,不做日志记录,此处的model为日志记录实体类
PayLogOutModel model = new PayLogOutModel();
//model.setCreateBy(userId);
model.setOrderId(WIDout_trade_no);
OrderLogModel log = new OrderLogModel();
log.setOrderNo(WIDout_trade_no);
log.setPayType("2"); //支付类型1银联 2支付宝 3微信
log.setStatus("0"); //0支付
log.setCreateBy("0"); //操作人0本系统 1银联 2支付宝 3微信
orderOperateLogService.operateLog(log);//记录订单操作日志
aliPayService.aliPay(httpServletRequest,httpServletResponse,model);
}
}
业务逻辑处理的层代码:
@Service
@Slf4j
public class AliPayService{
public void aliPay(HttpServletRequest request, HttpServletResponse httpServletResponse,PayLogOutModel model){
//此处已将使用model的日志记录调用服务删除
AliPayServlet ali = new AliPayServlet();
ali.doPost(request,httpServletResponse);
}
}
支付宝支付函数调用:(建议价格,商品信息等通过数据库查询,不要使用前端数据)
参数passback_params,如果请求时传递了该参数,则返回给商户时会回传该参数。支付宝只会在同步返回(包括跳转回商户网站)和异步通知时将该参数原样返回。本参数必须进行UrlEncode之后才可以发送给支付宝。此参数可以做为网站标志,在回调函数中使用,可以保证付款用户是同一人
public class AliPayServlet extends HttpServlet{
@Override
public void init(ServletConfig config) throws ServletException {
super.init();
}
private String message = "";
private void setMessage(String mess){
this.message = mess;
}
public String getMessage(){
return this.message;
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
//设置请求参数
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
alipayRequest.setReturnUrl(AlipayConfig.return_url);
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//商户订单号,商户网站订单系统中唯一订单号,必填
String out_trade_no = req.getParameter("WIDout_trade_no");
//付款金额,必填
String total_amount = req.getParameter("WIDtotal_amount");
//订单名称,必填
String subject = req.getParameter("WIDsubject");
//商品描述,可空
String body = req.getParameter("WIDbody");
//设置传输参数:订单号,订单总价格,订单描述,付款类型
alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
+ "\"total_amount\":\""+ total_amount +"\","
+ "\"subject\":\""+ subject +"\","
+ "\"body\":\""+ body +"\","
+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
//请求
String result = null;
try {
result = alipayClient.pageExecute(alipayRequest).getBody();
this.setMessage(result);
} catch (AlipayApiException e) {
e.printStackTrace();
}
//输出
out.println(result);
//设置输出格式为utf-8,否则会中文乱码
resp.setContentType("text/html;charset=" + AlipayConfig.charset);
resp.getWriter().write(result);
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
}
支付宝回调函数(回调入口):
@PostMapping( "/ali-rec" )
@ResponseBody
public String aliRec(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse
) {
try {
return aliPayService.aliPayResponse(httpServletRequest,httpServletResponse);
} catch (Exception e) {
e.printStackTrace();
}
return "false";
}
回调业务处理:
@Transactional(rollbackFor = Exception.class)
public String aliPayResponse(HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
AliRecServlet ali = new AliRecServlet();
ali.doPost(request,httpServletResponse);
return "success";
}
AliRecServlet回调方法逻辑:
public class AliRecServlet extends HttpServlet{
@Override
public void init(ServletConfig config) throws ServletException {
super.init();
}
private String message = "";
private String orderId = "";
private String outOrderNO = ""; // 外部系统订单号
private String status = "2";
private String amount = "";
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
private void setMessage(String mess){
this.message = mess;
}
public String getMessage(){
return this.message;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getOutOrderNO() {
return outOrderNO;
}
public void setOutOrderNO(String outOrderNO) {
this.outOrderNO = outOrderNO;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse resp)
throws ServletException, IOException {
Map<String,String> params = new HashMap<String,String>();
Map<String,String[]> requestParams = request.getParameterMap();
for (Iterator<String> 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] + ",";
}
//乱码解决,这段代码在出现乱码时使用
// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
params.put(name, valueStr);
}
boolean signVerified = false;
try {
//支付宝回调数据与本订单数据进行校验
signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
} catch (AlipayApiException e) {
e.printStackTrace();
}
//——请在这里编写您的程序(以下代码仅作参考)——
/* 实际验证过程建议商户务必添加以下校验:
1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号,
2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额),
3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email)
4、验证app_id是否为该商户本身。
*/
String out_trade_no = "";
if(request.getParameter("out_trade_no")!=null){
out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
this.setOrderId(out_trade_no);//星云订单号
}
if(request.getParameter("trade_no")!=null){
String zhifubaoOrderNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
this.setOutOrderNO(zhifubaoOrderNo);//支付宝订单号
}
if(request.getParameter("trade_status")!=null){
String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
if (trade_status.equals("TRADE_SUCCESS")){
this.setStatus("1"); //支付成功
}
}
if(request.getParameter("buyer_pay_amount")!=null){
String am = new String(request.getParameter("buyer_pay_amount").getBytes("ISO-8859-1"),"UTF-8");
this.setAmount(am);//金额
}
if(signVerified) {//验证成功
out.println("signVerified验证成功");
//商户订单号
out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//支付宝交易号
String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
//交易状态
String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
if(trade_status.equals("TRADE_FINISHED")){
//判断该笔订单是否在商户网站中已经做过处理
//如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
//如果有做过处理,不执行商户的业务程序
AlipayConfig.logResult("单据号:"+out_trade_no+"/n"+"交易状态:"+"TRADE_FINISHED /n");
//注意:
//退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
}else if (trade_status.equals("TRADE_SUCCESS")){
//判断该笔订单是否在商户网站中已经做过处理
//如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
//如果有做过处理,不执行商户的业务程序
AlipayConfig.logResult("单据号:"+out_trade_no+"/n"+"交易状态:"+"TRADE_SUCCESS /n");
//注意:
//付款完成后,支付宝系统发送该交易状态通知
}
this.setMessage(AlipaySignature.getSignCheckContentV1(params));//记录报文
out.println("success");
}else {//验证失败
out.println("signVerified验证失败");
//调试用,写文本函数记录程序运行情况是否正常
String sWord = AlipaySignature.getSignCheckContentV1(params);
AlipayConfig.logResult(sWord);
this.setMessage(sWord);//记录报文
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
}
H5支付(此支付方式在支付宝官方建议不采用)
H5支付配置信息同PC端二维码支付
Controller层方法如下:
public class AliH5Pay{
private final AppPayService appPayService;
@Autowired
public AliH5Pay(AppPayService appPayService){
this.appPayService=appService;
}
public String aliWapPay(@RequestParam( "WIDout_trade_no" ) String WIDout_trade_no
,@RequestParam( "WIDtotal_amount" ) String WIDtotal_amount
,@RequestParam( "WIDsubject" ) String WIDsubject
,@RequestParam( "WIDbody" ) String WIDbody) throws AlipayApiException {
//日志记录,可忽略,根据系统需求添加
return appPayService.wapAppPay(model,WIDout_trade_no,WIDtotal_amount,WIDbody,WIDsubject);
}
}
付款处理:此处为get方式获取支付链接返回给前端,由前端放在a标签中进行跳转
AliWapPayServlet取得支付宝方的支付链接
public class AliWapPayServlet extends HttpServlet {
public String getJumpUrl(String wiDout_trade_no, String wiDtotal_amount, String wiDbody, String wiDsubject) throws AlipayApiException {
AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
//设置请求参数,使用的实体类不一样
AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
alipayRequest.setReturnUrl(AlipayConfig.return_url);
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//商户订单号,商户网站订单系统中唯一订单号,必填
String out_trade_no = wiDout_trade_no;
//付款金额,必填
String total_amount = wiDtotal_amount;
//订单名称,必填
String subject = wiDsubject;
//商品描述,可空
String body =wiDbody;
//超时时间
String timeout_express="1h";
alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
+ "\"total_amount\":\""+ total_amount +"\","
+ "\"subject\":\""+ subject +"\","
+ "\"body\":\""+ body +"\","
+ "\"timeout_express\":\""+ timeout_express +"\","
+ "\"product_code\":\"QUICK_WAP_PAY\"}");
AlipayTradeWapPayResponse response=alipayClient.pageExecute(alipayRequest,"get");
String result=response.getBody();
out.println(result);
return result;
}
}
若使用post方式,则方法如下,注意此方式调用支付宝付款时,无法控制跳转页面的有效时间,因为此方法是后端直接跳转,前端无法获取跳转链接
public class AliWapPayServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
super.init();
}
private String message = "";
private void setMessage(String mess){
this.message = mess;
}
public String getMessage(){
return this.message;
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
//设置请求参数
AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
alipayRequest.setReturnUrl(AlipayConfig.return_url);
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//商户订单号,商户网站订单系统中唯一订单号,必填
String out_trade_no = req.getParameter("WIDout_trade_no");
//付款金额,必填
String total_amount = req.getParameter("WIDtotal_amount");
//订单名称,必填
String subject = req.getParameter("WIDsubject");
//商品描述,可空
String body = req.getParameter("WIDbody");
//超时时间
String timeout_express="1c";
alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
+ "\"total_amount\":\""+ total_amount +"\","
+ "\"subject\":\""+ subject +"\","
+ "\"body\":\""+ body +"\","
+ "\"timeout_express\":\""+ timeout_express +"\","
+ "\"product_code\":\"QUICK_WAP_PAY\"}");
//请求
String result = null;
try {
result = alipayClient.pageExecute(alipayRequest).getBody();
this.setMessage(result);
} catch (AlipayApiException e) {
e.printStackTrace();
}
//输出
out.println(result);
resp.setContentType("text/html;charset=" + AlipayConfig.charset);
resp.getWriter().write(result);
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
}