o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
springboot 接入微信支付,从支付到退款整体闭环
- User
springboot 接入微信支付,从支付到退款整体闭环
- Assistant
springboot 接入微信支付,从支付到退款整体闭环
微信支付是目前主流的移动支付方式之一,在应用中接入微信支付功能,可以极大提升用户的支付体验。本文将详细介绍如何在 Spring Boot 项目中接入微信支付,实现从支付到退款的完整流程,帮助开发者快速集成微信支付功能。
在开始之前,需要确保以下条件已满足:
mch_id)、API 密钥(key)等信息。prepay_id)。prepay_id 调起微信支付界面,完成支付。首先,在 application.properties 或 application.yml 中配置微信支付的必要参数:
# 微信支付配置
wxpay.appId=你的AppID
wxpay.mchId=你的商户号
wxpay.key=你的API密钥
wxpay.notifyUrl=https://yourdomain.com/wxpay/notify
wxpay.refundNotifyUrl=https://yourdomain.com/wxpay/refund/notify
wxpay.certPath=路径/to/你的/apiclient_cert.p12
在 pom.xml 中添加微信支付 SDK 的依赖,可以使用官方提供的 WXPay SDK:
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>0.0.3</version>
</dependency>
创建一个配置类,初始化微信支付所需的参数和证书:
import com.github.wxpay.sdk.WXPayConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.io.*;
@Configuration
public class WxPayConfig implements WXPayConfig {
@Value("${wxpay.appId}")
private String appId;
@Value("${wxpay.mchId}")
private String mchId;
@Value("${wxpay.key}")
private String key;
@Value("${wxpay.certPath}")
private String certPath;
private byte[] certData;
public WxPayConfig() throws Exception {
File file = new File(certPath);
InputStream certStream = new FileInputStream(file);
this.certData = certStream.readAllBytes();
certStream.close();
}
@Override
public String getAppID() {
return appId;
}
@Override
public String getMchID() {
return mchId;
}
@Override
public String getKey() {
return key;
}
@Override
public InputStream getCertStream() {
return new ByteArrayInputStream(certData);
}
@Override
public int getHttpConnectTimeoutMs() {
return 8000;
}
@Override
public int getHttpReadTimeoutMs() {
return 10000;
}
}
在配置类中或者通过配置注入的方式,初始化 WXPay 实例:
import com.github.wxpay.sdk.WXPay;
@Bean
public WXPay wxPay() throws Exception {
return new WXPay(new WxPayConfig());
}
在控制器中,编写统一下单的接口:
import com.github.wxpay.sdk.WXPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/wxpay")
public class WxPayController {
@Autowired
private WXPay wxPay;
@Value("${wxpay.notifyUrl}")
private String notifyUrl;
@PostMapping("/unifiedOrder")
public Map<String, String> unifiedOrder(@RequestBody OrderRequest orderRequest) throws Exception {
Map<String, String> data = new HashMap<>();
data.put("body", orderRequest.getBody());
data.put("out_trade_no", orderRequest.getOutTradeNo());
data.put("fee_type", "CNY");
data.put("total_fee", String.valueOf(orderRequest.getTotalFee()));
data.put("spbill_create_ip", orderRequest.getSpbillCreateIp());
data.put("notify_url", notifyUrl);
data.put("trade_type", "JSAPI"); // JSAPI 代表公众号支付
data.put("openid", orderRequest.getOpenid());
Map<String, String> resp = wxPay.unifiedOrder(data);
// 返回给前端用于调用支付接口的参数
return resp;
}
}
OrderRequest 是一个自定义的请求参数对象,包含订单相关信息。
前端(如微信小程序、H5 页面)接收到服务器返回的参数后,调用微信支付接口:
wx.requestPayment({
'timeStamp': timestamp,
'nonceStr': nonceStr,
'package': 'prepay_id=' + prepay_id,
'signType': 'MD5',
'paySign': paySign,
'success': function(res) {
// 支付成功后的逻辑
},
'fail': function(res) {
// 支付失败的逻辑
}
})
paySign 的生成需要参考微信支付官方文档,按照指定的方式生成签名。
微信支付成功后,会回调商户服务器的通知接口,需要编写对应的处理逻辑:
@PostMapping("/notify")
public String payNotify(HttpServletRequest request, HttpServletResponse response) {
try {
String xml = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml); // 转换成 Map
if (wxPay.isPayResultNotifySignatureValid(notifyMap)) {
// 签名正确
String returnCode = notifyMap.get("return_code");
if ("SUCCESS".equals(returnCode)) {
// 处理业务逻辑
String outTradeNo = notifyMap.get("out_trade_no");
// 根据订单号更新订单状态等操作
// 通知微信服务器已经处理完毕
Map<String, String> resp = new HashMap<>();
resp.put("return_code", "SUCCESS");
resp.put("return_msg", "OK");
return WXPayUtil.mapToXml(resp);
}
} else {
// 签名错误,忽略处理
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
当用户申请退款时,服务器调用微信退款接口:
@PostMapping("/refund")
public Map<String, String> refund(@RequestBody RefundRequest refundRequest) throws Exception {
Map<String, String> data = new HashMap<>();
data.put("out_trade_no", refundRequest.getOutTradeNo());
data.put("out_refund_no", refundRequest.getOutRefundNo());
data.put("total_fee", String.valueOf(refundRequest.getTotalFee()));
data.put("refund_fee", String.valueOf(refundRequest.getRefundFee()));
data.put("notify_url", refundNotifyUrl);
Map<String, String> resp = wxPay.refund(data);
// 返回退款结果
return resp;
}
RefundRequest 是一个自定义的请求参数对象,包含退款相关信息。
微信会异步通知退款结果,需要编写处理回调逻辑:
@PostMapping("/refund/notify")
public String refundNotify(HttpServletRequest request, HttpServletResponse response) {
try {
String xml = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);
String reqInfo = notifyMap.get("req_info");
// 解密 req_info
String decryptedReqInfo = WXPayUtil.decryptReqInfo(reqInfo, wxPayConfig.getKey());
Map<String, String> refundNotifyMap = WXPayUtil.xmlToMap(decryptedReqInfo);
// 处理退款通知逻辑
String outRefundNo = refundNotifyMap.get("out_refund_no");
// 根据退款单号更新退款状态等操作
// 通知微信服务器已经处理完毕
Map<String, String> resp = new HashMap<>();
resp.put("return_code", "SUCCESS");
resp.put("return_msg", "OK");
return WXPayUtil.mapToXml(resp);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
通过以上步骤,我们在 Spring Boot 项目中成功集成了微信支付功能,实现了从支付到退款的完整闭环流程。在实际开发中,还需要根据具体业务需求进行完善,如订单管理、支付状态更新、异常处理等。希望本文能够帮助到需要在项目中集成微信支付的开发者。
Not yet included in a published release.