本本章基于阿里的沙箱测试完成,前期的支付功能集成自行百度
1、依赖,可采用maven依赖和导包依赖的两种方式
https://search.maven.org/artifact/com.alipay.sdk/alipay-sdk-java/4.22.67.ALL/jar
本人采用的是jar导入依赖集成JavaWeb项目
maven依赖方式:
com.alipay.sdk
alipay-sdk-java
4.22.67.ALL
导包方式:
一、controller层代码
package com.lcj.controller;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.lcj.service.AliPayService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@RestController
@RequestMapping("pay")
public class AliPayController {
@Resource
private AliPayService aliPayService;//调用支付服务
/*阿里支付*/
/**
* 支付接口
*
* @param out_trade_no 商户订单号
* @param subject 订单名称
* @param total_amount 付款金额
* @param body 产品描述
* @return
*/
@RequestMapping(value = "payment")
public String alipay(String out_trade_no, String subject, String total_amount, String body) {
System.out.println("进入支付接口");
String result = "";
try {
result = aliPayService.aliPay(out_trade_no, subject, total_amount, body);
System.out.println(result);
System.out.println("进入支付页面");
} catch (AlipayApiException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* 查询交易
* @param out_trade_no 商户订单号
* @param trade_no 支付宝交易号
*/
@RequestMapping(value = "queryPayment")
public String queryPayment(String out_trade_no,String trade_no){
System.out.println("开始查询交易");
String result = null;
try {
result = aliPayService.queryPayment(out_trade_no,trade_no);
System.out.println(result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (AlipayApiException e) {
e.printStackTrace();
}
return result;
}
/**
*
* @param out_trade_no 商户订单号
* @param trade_no 支付宝交易号
* @param refund_amount 退款金额
* @param refund_reason 退款原因
* @param out_request_no 退款请求号
*/
@RequestMapping(value = "refund")
public String refund(String out_trade_no,String trade_no,String refund_amount,String refund_reason,String out_request_no){
System.out.println("开始退款");
String refund = null;
try {
refund = aliPayService.refund(out_trade_no, trade_no, refund_amount, refund_reason, out_request_no);
System.out.println(refund);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (AlipayApiException e) {
e.printStackTrace();
}
return refund;
}
/**
*退款查询
* @param out_trade_no 商户订单号
* @param trade_no 支付宝交易号
* @param out_request_no 退款请求号
* @return
*/
@RequestMapping(value = "refundQuery")
public String refundQuery(String out_trade_no,String trade_no,String out_request_no){
String resout="";
try {
resout = aliPayService.refundQuery(out_trade_no, trade_no, out_request_no);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (AlipayApiException e) {
e.printStackTrace();
}
return resout;
}
@RequestMapping(value = "closeTrade")
public String closeTrade(String out_trade_no,String trade_no){
String result = null;
try {
result = aliPayService.closeTrade(out_trade_no, trade_no);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (AlipayApiException e) {
e.printStackTrace();
}
return result;
}
/**
* 用户支付成功后返回的自定义页面
*
* @return
*/
@RequestMapping("success")
public String result(HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String[]> requestParams = request.getParameterMap();
Map<String, String> params = new HashMap<>();
for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
String name = iter.next();
String[] values = 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);
}
System.out.println(JSON.toJSONString(params));
System.out.println("用户支付成功");
return "success";
}
/**
* 支付宝主动推送的异步消息
*
* @return
*/
@RequestMapping("notify")
public String message(HttpServletRequest request) {
System.out.println("接收到异步通知!");
return aliPayService.notifyMsg(request);
}
}
二、server层代码
package com.lcj.service.impl;
import com.alipay.api.AlipayApiException;
import com.lcj.pojo.AlipayBean;
import com.lcj.service.AliPayService;
import com.lcj.util.AlipayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@Service
public class AliPayServiceImpl implements AliPayService {
@Autowired
private AlipayUtil alipayUtil;
/**
* 付款
*
* @param out_trade_no
* @param subject
* @param total_amount
* @param body
* @return
* @throws AlipayApiException
* @throws UnsupportedEncodingException
*/
@Override
public String aliPay(String out_trade_no, String subject, String total_amount, String body) throws AlipayApiException, UnsupportedEncodingException {
//将参数封装到AlipayBean对象中
AlipayBean alipayBean = new AlipayBean();
alipayBean.setBody(new String(body.getBytes("ISO-8859-1"), "UTF-8"));
alipayBean.setOut_trade_no(new String(out_trade_no.getBytes("ISO-8859-1"), "UTF-8"));
alipayBean.setTotal_amount(new String(total_amount.getBytes("ISO-8859-1"), "UTF-8"));
alipayBean.setSubject(new String(subject.getBytes("ISO-8859-1"), "UTF-8"));
return alipayUtil.pay(alipayBean);
}
/**
* 查询交易
* @param out_trade_no 商户订单号,商户网站订单系统中唯一订单号
* @param trade_no 支付宝交易号
* @return
* @throws UnsupportedEncodingException
* @throws AlipayApiException
*/
public String queryPayment(String out_trade_no, String trade_no) throws UnsupportedEncodingException, AlipayApiException {
//查询交易
String result = alipayUtil.queryPayment(new AlipayBean()
.setOut_trade_no(new String(out_trade_no.getBytes("ISO-8859-1"), "UTF-8"))
.setTrade_no(new String(trade_no.getBytes("ISO-8859-1"), "UTF-8")));
return result;
}
/**
* 退款
* @param out_trade_no 商户订单号,商户网站订单系统中唯一订单号
* @param trade_no 支付宝交易号
* @param refund_amount 请二选一设置 需要退款的金额,该金额不能大于订单金额,必填
* @param refund_reason 退款的原因说明
* @param out_request_no 标识一次退款请求,同一笔交易多次退款需要保证唯一,如需部分退款,则此参数必传
*/
@Override
public String refund(String out_trade_no, String trade_no, String refund_amount, String refund_reason, String out_request_no) throws UnsupportedEncodingException, AlipayApiException {
String refund = alipayUtil.refund(new AlipayBean()
.setOut_trade_no(new String(out_trade_no.getBytes("ISO-8859-1"), "UTF-8"))
.setTrade_no(new String(trade_no.getBytes("ISO-8859-1"), "UTF-8"))
.setRefund_amount(new String(refund_amount.getBytes("ISO-8859-1"), "UTF-8"))
.setRefund_reason(new String(refund_reason.getBytes("ISO-8859-1"), "UTF-8"))
.setOut_request_no(new String(out_request_no.getBytes("ISO-8859-1"), "UTF-8")));
return refund;
}
/**
* 退款查询
* @param out_trade_no 商户订单号,商户网站订单系统中唯一订单号
* @param trade_no 支付宝交易号
* @param out_request_no 请求退款接口时,传入的退款请求号,如果在退款请求时未传入,则该值为创建交易时的外部交易号,必填
* @return
*/
@Override
public String refundQuery(String out_trade_no, String trade_no, String out_request_no) throws UnsupportedEncodingException, AlipayApiException {
String result = alipayUtil.refundQuery(new AlipayBean()
.setOut_trade_no(new String(out_trade_no.getBytes("ISO-8859-1"), "UTF-8"))
.setTrade_no(new String(trade_no.getBytes("ISO-8859-1"), "UTF-8"))
.setOut_request_no(new String(out_request_no.getBytes("ISO-8859-1"), "UTF-8")));
return result;
}
/**
*
* @param out_trade_no 商户订单号,商户网站订单系统中唯一订单号
* @param trade_no 支付宝交易号
* @return
*/
@Override
public String closeTrade(String out_trade_no, String trade_no) throws UnsupportedEncodingException, AlipayApiException {
String result = alipayUtil.closeTrade(new AlipayBean()
.setOut_trade_no(new String(out_trade_no.getBytes("ISO-8859-1"), "UTF-8"))
.setTrade_no(new String(trade_no.getBytes("ISO-8859-1"), "UTF-8")));
return result;
}
/**
* 异常通知
*
* @param request
* @return
*/
@Override
public String notifyMsg(HttpServletRequest request) {
boolean result = false;
//获取支付宝POST过来反馈信息
Map<String, String> params = new HashMap<>();
Map<String, String[]> requestParams = request.getParameterMap();
try {
for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
String name = iter.next();
String[] values = 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);
}
//验证支付宝推送的异步消息
result = alipayUtil.notifyMsg(request, params);
System.out.println(result ? "交易成功" : "交易失败");
} catch (UnsupportedEncodingException | AlipayApiException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result ? "交易成功" : "交易失败";
}
}
三、阿里支付的工具层
package com.lcj.util;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.lcj.pojo.AlipayBean;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Properties;
/* 支付宝 */
@Component
public class AlipayUtil {
private static String gatewayUrl;
private static String app_id;
private static String merchant_private_key;
private static String charset;
private static String alipay_public_key;
private static String sign_type;
private static String return_url;
private static String notify_url;
/**
* 获取配置文件中的属性值
*/
public void getPropKey() {
try {
Properties prop = ReadByClassLoader.readPropStream1("alipay.properties");
gatewayUrl = prop.getProperty("gatewayUrl");
app_id = prop.getProperty("app_id");
merchant_private_key = prop.getProperty("merchant_private_key");
charset = prop.getProperty("charset");
alipay_public_key = prop.getProperty("alipay_public_key");
sign_type = prop.getProperty("sign_type");
return_url = prop.getProperty("return_url");
notify_url = prop.getProperty("notify_url");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 付款
*
* @param alipayBean
* @return
* @throws AlipayApiException
*/
public String pay(AlipayBean alipayBean) throws AlipayApiException {
//获取配置文件中的属性值
getPropKey();
//1、获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json", charset, alipay_public_key, sign_type);
//2、设置请求参数
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//页面跳转同步通知页面路径
alipayRequest.setReturnUrl(return_url);
// alipay.properties
alipayRequest.setNotifyUrl(notify_url);
//封装参数
alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
//3、请求支付宝进行付款,并获取支付结果
return alipayClient.pageExecute(alipayRequest).getBody();
}
/**
* 交易查询
*
* @param alipayBean
* @return
*/
public String queryPayment(AlipayBean alipayBean) throws UnsupportedEncodingException, AlipayApiException {
//获取配置文件中的属性值
getPropKey();
//获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json", charset, alipay_public_key, sign_type);
//设置请求参数
AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
//请二选一设置
alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
//请求
return alipayClient.execute(alipayRequest).getBody();
}
/**
* 退款
*
* @param alipayBean
* @return
* @throws AlipayApiException
*/
public String refund(AlipayBean alipayBean) throws AlipayApiException {
//获取配置文件中的属性值
getPropKey();
//获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id,
merchant_private_key, "json", charset, alipay_public_key, sign_type);
//设置请求参数
AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
//请求
return alipayClient.execute(alipayRequest).getBody();
}
/**
* 退款查询
*
* @param alipayBean
* @return
*/
public String refundQuery(AlipayBean alipayBean) throws AlipayApiException {
//获取配置文件中的属性值
getPropKey();
//获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key,
"json", charset, alipay_public_key, sign_type);
//设置请求参数
AlipayTradeFastpayRefundQueryRequest alipayRequest = new AlipayTradeFastpayRefundQueryRequest();
alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
//请求
return alipayClient.execute(alipayRequest).getBody();
}
/**
* 关闭交易
*
* @param alipayBean
* @return
*/
public String closeTrade(AlipayBean alipayBean) throws AlipayApiException {
//获取配置文件中的属性值
getPropKey();
//获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json", charset, alipay_public_key, sign_type);
//设置请求参数
AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();
alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
return alipayClient.execute(alipayRequest).getBody();
}
public boolean notifyMsg(HttpServletRequest request, Map<String, String> params) throws AlipayApiException, UnsupportedEncodingException {
boolean reFlag = false;
//获取配置文件中的属性值
getPropKey();
boolean signVerified = AlipaySignature.rsaCheckV1(params, merchant_private_key, charset, sign_type); //调用SDK验证签名
if (signVerified) {//验证成功
//商户订单号
String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
System.out.println("商户订单号:" + out_trade_no);
//支付宝交易号
String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
System.out.println("支付宝交易号:" + trade_no);
//交易状态
String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
if (trade_status.equals("TRADE_FINISHED")) {
//判断该笔订单是否在商户网站中已经做过处理
//如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
//如果有做过处理,不执行商户的业务程序
System.out.println("交易完成");
//注意:
//退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
} else if (trade_status.equals("TRADE_SUCCESS")) {
//判断该笔订单是否在商户网站中已经做过处理
//如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
//如果有做过处理,不执行商户的业务程序
System.out.println("支付成功");
reFlag = true;
//注意:
//付款完成后,支付宝系统发送该交易状态通知
}
System.out.println("success");
} else {//验证失败
System.out.println("fail");
//调试用,写文本函数记录程序运行情况是否正常
//String sWord = AlipaySignature.getSignCheckContentV1(params);
//AlipayConfig.logResult(sWord);
}
return reFlag;
}
}
四、配置文件
# 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
app_id =
# 商户私钥,您的PKCS8格式RSA2私钥
merchant_private_key =
# 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
alipay_public_key =
# 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数
notify_url = http://127.0.0.1:8083/pay/notify
# 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数
return_url = http://127.0.0.1:8083/pay/success
# 签名方式
sign_type = RSA2
# 字符编码格式
charset = utf-8
# 支付宝网关
gatewayUrl = https://openapi.alipaydev.com/gateway.do
# 支付宝网关
log_path = D:\\workspace\\
说明:
notify_url ,此url是阿里支付主动通知商户服务器的http路径,阿里会将信息放入在request请求中,开发者可以回去对应的参数进行处理
return_url ,此url是用户支付成功后,用于用户页面跳转。由开发者自行定义
本人的测试demo连接地址,自行获取
https://gitee.com/lcj_273482106/alipay-web