- 引入微信支付依赖
在pom.xml文件中添加以下依赖:
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-pay</artifactId>
<version>3.7.1</version>
</dependency>
- 配置微信支付参数
在配置文件中添加以下配置,配置微信支付相关参数:
wx:
pay:
appId: your_appId
mchId: your_mchId
mchKey: your_mchKey
keyPath: your_keyPath
notifyUrl: your_notifyUrl
其中,appId、mchId和mchKey是微信支付分配的账号信息,keyPath是API证书的路径,notifyUrl是支付结果通知地址。
- 创建微信支付服务
创建一个微信支付服务,包括创建订单、发起支付请求、处理支付结果等功能。例如:
@Service
public class WeixinPayService {
@Autowired
private WxPayService wxPayService;
/**
* 创建微信支付订单
*/
public WxPayUnifiedOrderResult createOrder(WxPayUnifiedOrderRequest request) throws WxPayException {
return wxPayService.unifiedOrder(request);
}
/**
* 查询微信支付订单
*/
public WxPayOrderQueryResult queryOrder(String transactionId, String outTradeNo) throws WxPayException {
return wxPayService.queryOrder(transactionId, outTradeNo);
}
/**
* 处理微信支付结果通知
*/
public String processPayResultNotify(String xmlData) throws WxPayException {
WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
// 处理支付结果通知
return "SUCCESS";
}
}
在上面的代码中,WeixinPayService中封装了微信支付的一些操作,包括创建订单、查询订单、处理支付结果通知等。
- 调用微信支付服务
在需要使用微信支付的地方,注入WeixinPayService,并调用相关方法。例如:
@RestController
public class PayController {
@Autowired
private WeixinPayService weixinPayService;
@PostMapping("/pay")
public WxPayUnifiedOrderResult pay(@RequestBody PayRequestDTO request) throws WxPayException {
WxPayUnifiedOrderRequest wxPayRequest = new WxPayUnifiedOrderRequest();
wxPayRequest.setBody(request.getBody());
wxPayRequest.setOutTradeNo(request.getOutTradeNo());
wxPayRequest.setTotalFee(BaseWxPayRequest.yuanToFen(request.getTotalFee()));
wxPayRequest.setSpbillCreateIp(request.getSpbillCreateIp());
wxPayRequest.setTradeType(request.getTradeType());
wxPayRequest.setNotifyUrl(request.getNotifyUrl());
wxPayRequest.setOpenid(request.getOpenid());
return weixinPayService.createOrder(wxPayRequest);
}
}
在上面的代码中,PayController接收支付请求并将请求转换为WxPayUnifiedOrderRequest,调用WeixinPayService的createOrder方法创建微信支付订单,并返回结果。
- 处理支付结果通知
在微信支付结果通知的地址上,接收微信支付结果通知,并调用WeixinPayService的processPayResultNotify方法处理支付结果通知。例如:
@RestController
public class PayResultNotifyController {
@Autowired
private WeixinPayService weixinPayService;
@PostMapping("/pay/notify")
public String payResultNotify(@RequestBody String xmlData) throws WxPayException {
return weixinPayService.processPayResultNotify(xmlData);
}
}
在上面的代码中,PayResultNotifyController接收支付结果通知,并调用WeixinPayService的processPayResultNotify方法处理支付结果通知。