Spring Boot project implements WeChat and Alipay payment
This article will introduce in detail how to implement the payment functions of WeChat and Alipay in the Spring Boot project. We will first briefly introduce the payment process of WeChat and Alipay, and then gradually guide you to complete the specific implementation of the payment function.
The article content is as follows:
- Introduction to payment process
- Project environment configuration
- Alipay payment implementation
- WeChat payment implementation
- Summarize
Introduction to payment process
The payment process can be roughly divided into the following steps:
- The user selects the payment method (WeChat or Alipay).
- The backend generates payment order information based on the payment method selected by the user, and sends the order information to the corresponding payment platform.
- The payment platform generates the payment QR code and returns it to the backend.
- The backend returns the payment QR code to the frontend.
- Users scan the QR code to pay.
- After the payment is completed, the payment platform will notify the backend of the payment result.
- The backend updates the order status based on the payment results.
Next, we will implement the payment functions of Alipay and WeChat respectively.
Project environment configuration
First, we need to introduce the dependencies required by Alipay and WeChat Pay into the Spring Boot project. pom.xml
Add the following content to the file :
<dependencies>
<!-- 支付宝支付依赖 -->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.10.30.ALL</version>
</dependency>
<!-- 微信支付依赖 -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-pay</artifactId>
<version>3.7.0</version>
</dependency>
</dependencies>
Then, application.yml
add the configuration information of Alipay and WeChat Pay in the file, as follows:
alipay:
app-id: your_alipay_app_id
private-key: your_alipay_private_key
alipay-public-key: your_alipay_public_key
server-url: https://openapi.alipay.com/gateway.do
charset: utf-8
sign-type: RSA2
notify-url: http://your_domain/alipay/notify
wechat:
app-id: your_wechat_app_id
mch-id: your_wechat_mch_id
mch-key: your_wechat_mch_key
notify-url: http://your_domain/wechat/notify
Alipay payment implementation
Create Alipay payment service class
First, we need to create an Alipay payment service class ( AlipayService.java
) to encapsulate the logic related to Alipay payment:
@Service
public class AlipayService {
@Value("${alipay.app-id}")
private String appId;
@Value("${alipay.private-key}")
private String privateKey;
@Value("${alipay.alipay-public-key}")
private String alipayPublicKey;
@Value("${alipay.server-url}")
private String serverUrl;
@Value("${alipay.charset}")
private String charset;
@Value("${alipay.sign-type}")
private String signType;
@Value("${alipay.notify-url}")
private String notifyUrl;
/**
* 创建支付宝支付订单
* @param orderId 订单ID
* @param amount 支付金额
* @return 支付宝支付二维码链接
* @throws AlipayApiException
*/
public String createAlipayOrder(String orderId, BigDecimal amount) throws AlipayApiException {
// 实例化客户端
AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, "json", charset, alipayPublicKey, signType);
// 创建API对应的request
AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
// 设置支付宝支付回调地址
request.setNotifyUrl(notifyUrl);
// 设置请求参数
AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
model.setOutTradeNo(orderId);
model.setTotalAmount(amount.toString());
model.setSubject("订单支付");
request.setBizModel(model);
// 发起请求,获取支付宝支付二维码链接
AlipayTradePrecreateResponse response = alipayClient.execute(request);
// 判断请求是否成功
if (response.isSuccess()) {
return response.getQrCode();
} else {
throw new AlipayApiException(response.getSubMsg());
}
}
/**
* 处理支付宝支付结果通知
* @param requestParams 支付宝支付结果通知参数
* @return 是否处理成功
*/
public boolean handleAlipayNotify(Map<String, String> requestParams) {
try {
// 验签
boolean signVerified = AlipaySignature.rsaCheckV1(requestParams, alipayPublicKey, charset, signType);
if (signVerified) {
// 获取支付宝支付结果通知数据
String outTradeNo = requestParams.get("out_trade_no"); // 商户订单号
String tradeNo = requestParams.get("trade_no"); // 支付宝交易号
String tradeStatus = requestParams.get("trade_status"); // 交易状态
// 根据支付结果更新订单状态
if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
// 更新订单状态为已支付
// updateOrderStatus(outTradeNo, tradeNo, "已支付");
return true;
}
}
} catch (AlipayApiException e) {
e.printStackTrace();
}
return false;
}
}
Create Alipay payment controller class
Next, we need to create an Alipay payment controller class ( AlipayController.java
) to handle the front-end payment request and Alipay payment result notification:
@RestController
@RequestMapping("/alipay")
public class AlipayController {
@Autowired
private AlipayService alipayService;
/**
* 创建支付宝支付订单
* @param orderId 订单ID
* @param amount 支付金额
* @return 支付宝支付二维码链接
*/
@GetMapping("/createOrder")
public String createAlipayOrder(@RequestParam String orderId, @RequestParam BigDecimal amount) {
try {
String qrCodeUrl = alipayService.createAlipayOrder(orderId, amount);
return qrCodeUrl;
} catch (AlipayApiException e) {
e.printStackTrace();
return "创建支付宝支付订单失败";
}
}
/**
* 支付宝支付结果通知处理
* @param request 请求对象
* @return 支付宝支付结果通知响应
*/
@PostMapping("/notify")
public String handleAlipayNotify(HttpServletRequest request) {
// 获取支付宝支付结果通知参数
Map<String, String> requestParams = new HashMap<>();
Map<String, String[]> parameterMap = request.getParameterMap();
for (String key : parameterMap.keySet()) {
requestParams.put(key, StringUtils.join(parameterMap.get(key), ","));
}
// 处理支付宝支付结果通知
boolean success = alipayService.handleAlipayNotify(requestParams);
if (success) {
return "success";
} else {
return "failure";
}
}
}
At this point, the Alipay payment function has been implemented. /alipay/createOrder
Users can create Alipay payment orders through the request interface, and then scan the returned payment QR code to pay. After the payment is completed, Alipay will /alipay/notify
send a payment result notification to the interface.
WeChat payment implementation
We can first define an WechatPayService
interface to encapsulate WeChat payment-related operations:
public interface WechatPayService {
/**
* 统一下单
*
* @param order 订单信息
* @return 统一下单结果
* @throws WxPayException 微信支付异常
*/
WxPayUnifiedOrderResult unifiedOrder(WxPayUnifiedOrderRequest order) throws WxPayException;
/**
* 查询订单
*
* @param transactionId 微信订单号
* @param outTradeNo 商户订单号
* @return 订单查询结果
* @throws WxPayException 微信支付异常
*/
WxPayOrderQueryResult queryOrder(String transactionId, String outTradeNo) throws WxPayException;
/**
* 关闭订单
*
* @param outTradeNo 商户订单号
* @return 关闭订单结果
* @throws WxPayException 微信支付异常
*/
WxPayOrderCloseResult closeOrder(String outTradeNo) throws WxPayException;
/**
* 申请退款
*
* @param request 退款请求
* @return 退款结果
* @throws WxPayException 微信支付异常
*/
WxPayRefundResult refund(WxPayRefundRequest request) throws WxPayException;
/**
* 查询退款
*
* @param transactionId 微信订单号
* @param outTradeNo 商户订单号
* @param outRefundNo 商户退款单号
* @param refundId 微信退款单号
* @return 退款查询结果
* @throws WxPayException 微信支付异常
*/
WxPayRefundQueryResult refundQuery(String transactionId, String outTradeNo, String outRefundNo, String refundId) throws WxPayException;
/**
* 下载对账单
*
* @param request 下载对账单请求
* @return 下载对账单结果
* @throws WxPayException 微信支付异常
*/
WxPayBillResult downloadBill(WxPayDownloadBillRequest request) throws WxPayException;
/**
* 通知处理
*
* @param xmlData 通知内容
* @return 通知结果
* @throws WxPayException 微信支付异常
*/
WxPayNotifyResult parsePayNotifyResult(String xmlData) throws WxPayException;
}
Then, we can implement this interface and inject WeChat payment-related configuration information into the implementation class:
@Service
public class WechatPayServiceImpl implements WechatPayService {
private final WxPayService wxPayService;
@Autowired
public WechatPayServiceImpl(WxPayConfig wxPayConfig) {
this.wxPayService = new WxPayServiceImpl();
this.wxPayService.setConfig(wxPayConfig);
}
@Override
public WxPayUnifiedOrderResult unifiedOrder(WxPayUnifiedOrderRequest order) throws WxPayException {
return wxPayService.unifiedOrder(order);
}
@Override
public WxPayOrderQueryResult queryOrder(String transactionId, String outTradeNo) throws WxPayException {
return wxPayService.queryOrder(transactionId, outTradeNo);
}
@Override
public WxPayOrderCloseResult closeOrder(String outTradeNo) throws WxPayException {
return wxPayService.closeOrder(outTradeNo);
}
@Override
public WxPayRefundResult refund(WxPayRefundRequest request) throws WxPayException {
return wxPayService.refund(request);
}
@Override
public WxPayRefundQueryResult refundQuery(String transactionId, String outTradeNo, String outRefundNo, String refundId) throws WxPayException {
return wxPayService.refundQuery(transactionId, outTradeNo, outRefundNo, refundId);
}
@Override
public WxPayBillResult downloadBill(WxPayDownloadBillRequest request) throws WxPayException {
return wxPayService.downloadBill(request);
}
@Override
public WxPayNotifyResult parsePayNotifyResult(String xmlData) throws WxPayException {
return wxPayService.parseOrderNotifyResult(xmlData);
}
}
When implementing the WeChat payment interface, we used it WxPayService
. This is a class provided by the WeChat payment SDK that encapsulates WeChat payment related operations. We WxPayConfig
configure via injection WxPayService
. WxPayConfig
Contains the relevant parameters of WeChat payment. We can configure these parameters in the configuration file and then WxPayConfig
build it through WxPayService
.