程序员必备网站(tmxkj.top)https://tmxkj.top/#/
序言:
支付宝的相关信息请到官网去查看,在配置过程中遇到问题可以咨询小编
1.pom.xm 依赖坐标
<!--支付宝支付相关依赖-->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.34.47.ALL</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2.yml配置信息
#支付宝信息
alipay:
#APPID
appId: ""
#应用私钥 是用支付宝密匙工具生成的 下载支付宝密匙工具
appPrivateKey: ""
#沙箱应用-->应用信息-->开发信息-->接口加签方式-->系统默认密钥-->公钥模式-->查看-->支付宝公钥
alipayPublicKey: ""
#回调地址
notifyUrl: "域名地址或者网络穿透地址/alipay/notify"
#网关地址 # 现在是正式地址 如果需要测试地址 网络搜索沙箱测试账户
serverUrl: "https://openapi.alipay.com/gateway.do"
#数据格式,推荐:json
format: "JSON"
#编码格式 推荐:utf-8
charset: "UTF-8"
#签名方式,签名算法,推荐:RSA2
signType: "RSA2"
3.AlipayConfig 配置类
@Data
@Component
@ConfigurationProperties(prefix = "alipay")
public class AlipayConfig {
/**
* APPID
*/
private String appId;
/**
* 应用私钥
*/
private String appPrivateKey;
/**
* 阿里公钥
*/
private String alipayPublicKey;
/**
* 阿里调用我们的地址【内网穿透/或者域名】
*/
private String notifyUrl;
/**
* 网关地址
*/
private String serverUrl;
/**
* 数据格式
*/
private String format;
/**
* 编码格式
*/
private String charset;
/**
* 签名方式,签名算法
*/
private String signType;
}
4.实体类
1.AliPay 发起支付实体类
@Data
public class AliPay {
private String outTradeNo;//商户订单我们的订单号
private Double totalAmount;//总金额
private String subject;//标题
private String alipayTraceNo;//阿里的流水号
private String[] queryOptions;//指定需要返回的参数
private String backUrl;//支付成功后返回前端页面地址
private String refundAmount;//退款金额
private String refundReason;//退款原因
private String outRequestNo;//部分退款使用 部分退款选择 HZ01RF001
private String storeName = "天梦星";// 公司名称
}
2.AliReturnPay 支付宝返回实体类
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class AliReturnPay implements Serializable {
private static final long serialVersionUID = 8683949075381016639L;
// 开发者的app_id
private String app_id;
// 商户订单号
private String out_trade_no;
// 签名
private String sign;
// 交易状态
private String trade_status;
// 支付宝交易号
private String trade_no;
// 交易的金额
private String total_amount;
}
3.AlipayLog 支付日志实体类
@Data
@TableName("pay_alipay_log")
public class AlipayLog {
@TableId(type = IdType.AUTO)
private Integer id;
// 开发者的app_id
private String app_id;
// 商户订单号
private String out_trade_no;
// 签名
private String sign;
// 交易状态
private String trade_status;
// 支付宝交易号
private String trade_no;
// 交易的金额
private String total_amount;
}
4.Order 订单实体类
@Data
@TableName(value = "tab_order")
public class Order implements Serializable {
@TableId(value = "order_id",type = IdType.AUTO)
private String orderId; // 订单id
private String orderName; // 订单名称
private Double totalPrice; // 商品总价格
private String userId; // 下单用户id
private Double paidPrice; // 实付价格
private Integer quantity; // 购买数量
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date orderTime; // 下单时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date payTime; // 支付时间
private String alipayTraceNo;//支付流水号
private String payStatus; // 支付状态
private String payStatusName;//支付状态名称
private String orderStatus; // 订单状态
private String orderStatusName; // 订单状态名称
private String orderRemark; // 订单备注
}
5.AlipayController
@RestController
@RequestMapping("/alipay")
public class AlipayController {
@Resource
private AlipayConfig alipayConfig;
@Resource
private AlipayLogDao alipayLogDao;
@Resource
private OrderDao orderDao;
/**
* 请求支付宝支付
* 返货from表单
*/
@GetMapping("/pay")
public void pay(AliPay aliPay, HttpServletResponse response) {
try {
Order order = new Order();
order.setOrderId(aliPay.getOutTradeNo());
order =orderDao.selectById(order);
if (!(order==null)){
//1.创建client,通过阿里SDK提供的client,负责调用支付宝的API
AlipayClient alipayClient = new DefaultAlipayClient(
alipayConfig.getServerUrl(),
alipayConfig.getAppId(),
alipayConfig.getAppPrivateKey(),
alipayConfig.getFormat(),
alipayConfig.getCharset(),
alipayConfig.getAlipayPublicKey(),
alipayConfig.getSignType()
);
//2.创建request,并设置request参数
AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
request.setNotifyUrl(alipayConfig.getNotifyUrl());//设置异步地址
//支付时候前端把地址传过来
request.setReturnUrl(aliPay.getBackUrl());
JSONObject jsonObject = new JSONObject();
//商户订单号
jsonObject.put("out_trade_no", order.getOrderId());
//商品价格
jsonObject.put("total_amount", order.getPaidPrice());
//商品标题
jsonObject.put("subject", order.getOrderName());
//产品编码
jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
request.setBizContent(jsonObject.toString());
//执行请求,拿到响应的结果,返回给浏览器
String form = "";
form = alipayClient.pageExecute(request).getBody();
//设置响应结果,将返回的内容写出到浏览器
response.setContentType("text/html;charset=" + alipayConfig.getCharset());
response.getWriter().write(form);//直接将完整的表单html输出到页面
response.getWriter().flush();
response.getWriter().close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*二维码支付
* 返回二维码
*/
@PostMapping("/sandPay")
public String sandboxPay(AliPay aliPay) {
try {
Order order = new Order();
order.setOrderId(aliPay.getOutTradeNo());
order =orderDao.selectById(order);
if (!(order==null)){
//1.创建client,通过阿里SDK提供的client,负责调用支付宝的API
AlipayClient alipayClient = new DefaultAlipayClient(
alipayConfig.getServerUrl(),
alipayConfig.getAppId(),
alipayConfig.getAppPrivateKey(),
alipayConfig.getFormat(),
alipayConfig.getCharset(),
alipayConfig.getAlipayPublicKey(),
alipayConfig.getSignType()
);
AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());
JSONObject jsonObject = new JSONObject();
jsonObject.put("out_trade_no", order.getOrderId());// 商户订单号
jsonObject.put("total_amount", aliPay.getTotalAmount());// 商品价格
jsonObject.put("subject", aliPay.getSubject());// 商品标题
jsonObject.put("store_id", aliPay.getStoreName());//组织或公司名
// jsonObject.put("timeout_express","5m");// 订单有效时间
alipayRequest.setBizContent(jsonObject.toString());
AlipayTradePrecreateResponse response = alipayClient.execute(alipayRequest);
System.out.println("创建订单结果:" + response.getBody());
System.out.println("订单编号是" + response.getOutTradeNo());
String qrCode = response.getQrCode();
// AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
return qrCode;
}else {
return "订单错误";
}
} catch (Exception e) {
return null;
}
}
/**
* 支付宝回调
*/
@PostMapping("/notify")
public void call(HttpServletRequest request, HttpServletResponse response, AliReturnPay aliReturnPay) {
response.setContentType("type=text/html;charset=UTF-8");
AlipayLog alipayLog = JSON.parseObject(JSON.toJSONString(aliReturnPay), AlipayLog.class);
//插入日志操作
alipayLogDao.insert(alipayLog);
//更新订单信息
Order order =new Order();
//支付流水号
order.setAlipayTraceNo(aliReturnPay.getTrade_no());
//更新时间
order.setPayTime(new Date());
//已支付状态
order.setPayStatus("Y");
order.setPayStatusName("已支付");
//更新订单状态
order.setOrderStatus("Y");
order.setOrderStatusName("已支付");
orderDao.updateById(order);
}
/**
*查询支付宝支付的订单
*/
@PostMapping("/order")
public String selectArder(AliPay aliPay){
try {
Order order = new Order();
order.setOrderId(aliPay.getOutTradeNo());
order =orderDao.selectById(order);
if (!(order==null)){
//1.创建client,通过阿里SDK提供的client,负责调用支付宝的API
AlipayClient alipayClient = new DefaultAlipayClient(
alipayConfig.getServerUrl(),
alipayConfig.getAppId(),
alipayConfig.getAppPrivateKey(),
alipayConfig.getFormat(),
alipayConfig.getCharset(),
alipayConfig.getAlipayPublicKey(),
alipayConfig.getSignType()
);
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
JSONObject jsonObject = new JSONObject();
jsonObject.put("out_trade_no",order.getOrderId());// 商户订单号
jsonObject.put("trade_no",order.getAlipayTraceNo());//支付宝订单编号
jsonObject.put("query_options",aliPay.getQueryOptions());//指定需要返回那些信息
request.setBizContent(jsonObject.toString());
AlipayTradeQueryResponse response = alipayClient.execute(request);
if(response.isSuccess()){
System.out.println("调用成功");
System.out.println(response.getBody());
}else {
response.getBody();
System.out.println("调用失败");
}
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 全额退款
*/
@PostMapping("/refundAll")
public String refundAll(@RequestBody AliPay aliPay) {
try {
//1.创建client,通过阿里SDK提供的client,负责调用支付宝的API
AlipayClient alipayClient = new DefaultAlipayClient(
alipayConfig.getServerUrl(),
alipayConfig.getAppId(),
alipayConfig.getAppPrivateKey(),
alipayConfig.getFormat(),
alipayConfig.getCharset(),
alipayConfig.getAlipayPublicKey(),
alipayConfig.getSignType()
);
//2.创建request,并设置request参数
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
JSONObject jsonObject = new JSONObject();
jsonObject.put("out_trade_no",aliPay.getOutTradeNo());// 商户订单号
jsonObject.put("trade_no",aliPay.getAlipayTraceNo());//支付宝交易号
jsonObject.put("refund_amount",aliPay.getRefundAmount());//退款金额
jsonObject.put("refund_reason",aliPay.getRefundReason());//退款原因
request.setBizContent(jsonObject.toString());
//执行请求,拿到响应的结果,返回给浏览器
AlipayTradeRefundResponse response = alipayClient.execute(request);
System.out.println(response.getBody());
if (response.isSuccess()) {
System.out.println(response.getBody());
return "退款成功";
} else {
return "退款失败";
}
} catch (Exception e) {
e.printStackTrace();
return "退款异常";
}
}
/**
* 部分退款
*/
@PostMapping("/refund")
public String refund(@RequestBody AliPay aliPay) {
try {
//1.创建client,通过阿里SDK提供的client,负责调用支付宝的API
AlipayClient alipayClient = new DefaultAlipayClient(
alipayConfig.getServerUrl(),
alipayConfig.getAppId(),
alipayConfig.getAppPrivateKey(),
alipayConfig.getFormat(),
alipayConfig.getCharset(),
alipayConfig.getAlipayPublicKey(),
alipayConfig.getSignType()
);
//2.创建request,并设置request参数
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
JSONObject jsonObject = new JSONObject();
jsonObject.put("out_trade_no",aliPay.getOutTradeNo());// 商户订单号
jsonObject.put("trade_no",aliPay.getAlipayTraceNo());//支付宝交易号
jsonObject.put("refund_amount",aliPay.getRefundAmount());//退款金额
jsonObject.put("refund_reason",aliPay.getRefundReason());//退款原因
jsonObject.put("out_request_no","HZ01RF001");//部分退款
request.setBizContent(jsonObject.toString());
//执行请求,拿到响应的结果,返回给浏览器
AlipayTradeRefundResponse response = alipayClient.execute(request);
if (response.isSuccess()) {
System.out.println(response.getBody());
return "退款成功";
} else {
return "退款失败";
}
} catch (Exception e) {
e.printStackTrace();
return "退款异常";
}
}
6.调用示例
备注:拉起支付时候请保证订单表里面有数据
1.拉起支付:
https://4fa48cd8.r8.cpolar.top/alipay/pay?outTradeNo=24020800290010000001&backUrl=https://xn--rsso51ap1b.top/
2.全部退款:
http://localhost:8082/alipay/refundAll
参数:
{
"outTradeNo": "24020723590010000001",
"alipayTraceNo": "2024020822001441601457495589",
"refundAmount": "0.10",
"refundReason": "无",
"outRequestNo": "897"
}
3.部分退款
http://localhost:8082/alipay/refund
参数 全部退款和部分退款可以合并成一个接口 这边方便区分就放两个接口
{
"outTradeNo": "24020800290010000001",
"alipayTraceNo": "2024020822001441601456419097",
"refundAmount": "0.06",
"refundReason": "无"
}