2.配置说明
要记住这几个重要的配置
appId 这个是appId
privateKey 商户私钥
publicKey 支付宝公钥, 即对应APPID下的支付宝公钥
notifyUrl 支付成功后异步回调地址(注意是必须是公网地址)
returnUrl #支付后回调地址
signType 签名类型 一般写 RSA2
charset utf-8
format json
#网关地址 在支付宝开发平台复制拷贝下来
gatewayUrl : https://openapi.alipaydev.com/gateway.do
logPath: F:\ 日志路径
(1)在官网注册账户,获取appId,公钥,私钥等信息
(2)引入依赖
(3)编写支付宝配置类
(4)复制官网的生成订单信息代码,导入到自己的项目中
(5)编写支付的业务代码,调用controller接口实现支付
java
@RequestMapping(value = "/pay", method = RequestMethod.GET)
// http://localhost:8888/alipay/pay?subject=支付&totalAmount=1&traceNo=1758852777989246976
public String pay(AliPayDTO aliPayDTO) throws AlipayApiException {
// 随机一个订单id
// Random random = new Random();
// int tradeNo = random.nextInt(1000000);
//获取订单id
Long tradeNo = Long.parseLong(aliPayDTO.getTraceNo());
// 设置请求参数
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
// 同步回调地址
alipayRequest.setReturnUrl(returnUrl);
// 异步回调地址
alipayRequest.setNotifyUrl(notifyUrl);
// 订单过期时间
LocalDateTime now = LocalDateTime.now();
LocalDateTime plusOneMinute = now.plusMinutes(1L);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String expireTime = plusOneMinute.format(formatter);
alipayRequest.setBizContent("{\"out_trade_no\":\"" + tradeNo + "\","
+ "\"total_amount\":\"" + aliPayDTO.getTotalAmount() + "\","
+ "\"subject\":\"" + aliPayDTO.getSubject() + "\","
+ "\"body\":\"" + aliPayDTO.getBody() + "\","
+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\","
+ "\"timeout_express\":\"1m\"," // 设置订单过期时间为1分钟
+ "\"time_expire\":\"" + expireTime + "\"}"); // 设置订单过期时间
return alipayClient.pageExecute(alipayRequest).getBody();
}
@PostMapping("/notifyUrl") // 注意这里必须是POST接口
public String payNotify(HttpServletRequest request) throws MQClientException {
if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
System.out.println("=========支付宝异步回调========");
Map<String, String> params = new HashMap<>();
Map<String, String[]> requestParams = request.getParameterMap();
for (String name : requestParams.keySet()) {
params.put(name, request.getParameter(name));
}
System.out.println("交易名称: " + params.get("subject"));
System.out.println("交易状态: " + params.get("trade_status"));
System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
System.out.println("商户订单号: " + params.get("out_trade_no"));
System.out.println("交易金额: " + params.get("total_amount"));
System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
System.out.println("买家付款时间: " + params.get("gmt_payment"));
System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
Long orderId = Long.parseLong(params.get("out_trade_no"));
//修改订单状态
orderService.updateOrder(orderId);
Order order = ordermapper.queryById(orderId);
//扣减数据库库存
productMapper.updateStock(order.getProduct_id(), order.getQuantity());
//增加积分,自动执行
//释放锁 redison
}
return "success";
}