在当今数字化时代,小程序支付功能已成为众多应用的核心需求之一。通过小程序支付,用户可以便捷地完成购物、充值等操作,极大地提升了用户体验和业务效率。Spring Boot作为一款流行的Java开发框架,以其简洁、高效的特点,为实现小程序支付功能提供了强大的支持。本文将详细介绍如何在Spring Boot项目中实现微信小程序支付功能,包括环境搭建、接口开发、支付流程实现以及支付结果通知处理等关键环节。
mch_id
)、API密钥(key
)等基本信息。notify_url
)等。Spring Web
、Spring Boot DevTools
等。pom.xml
文件中添加微信支付相关依赖:<dependency> <groupId>com.github.wechatpay-apiv3</groupId> <artifactId>wechatpay-java</artifactId> <version>1.0.0</version> </dependency>在application.properties
或application.yml
文件中配置微信支付相关参数:
wx.pay.appId: your_app_id
wx.pay.mchId: your_mch_id
wx.pay.key: your_api_key
wx.pay.notifyUrl: your_notify_url
WxPayService
类,用于处理支付相关逻辑:
@Service public class WxPayService { @Value("${wx.pay.appId}") private String appId; @Value("${wx.pay.mchId}") private String mchId; @Value("${wx.pay.key}") private String key; @Value("${wx.pay.notifyUrl}") private String notifyUrl; public Map<String, String> unifiedOrder(Map<String, String> params) { // 构建统一下单请求参数 Map<String, String> requestParams = new HashMap<>(); requestParams.put("appid", appId); requestParams.put("mch_id", mchId); requestParams.put("nonce_str", UUID.randomUUID().toString().replace("-", "")); requestParams.put("body", params.get("body")); requestParams.put("out_trade_no", params.get("out_trade_no")); requestParams.put("total_fee", params.get("total_fee")); requestParams.put("spbill_create_ip", params.get("spbill_create_ip")); requestParams.put("notify_url", notifyUrl); requestParams.put("trade_type", "JSAPI"); requestParams.put("openid", params.get("openid")); // 签名 String sign = WxPayUtil.createSign(requestParams, key); requestParams.put("sign", sign); // 发起统一下单请求 String xml = WxPayUtil.mapToXml(requestParams); String result = HttpClientUtil.doPost("https://api.mch.weixin.qq.com/pay/unifiedorder", xml); Map<String, String> resultMap = WxPayUtil.xmlToMap(result); // 返回前端需要的支付参数 Map<String, String> payParams = new HashMap<>(); payParams.put("appId", appId); payParams.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000)); payParams.put("nonceStr", UUID.randomUUID().toString().replace("-", "")); payParams.put("package", "prepay_id=" + resultMap.get("prepay_id")); payParams.put("signType", "MD5"); payParams.put("paySign", WxPayUtil.createSign(payParams, key)); return payParams; } }WxPayController
类,用于接收小程序的支付请求并调用统一下单接口:
@RestController @RequestMapping("/wxpay") public class WxPayController { @Autowired private WxPayService wxPayService; @PostMapping("/unifiedOrder") public Map<String, String> unifiedOrder(@RequestBody Map<String, String> params) { return wxPayService.unifiedOrder(params); } }WxPayNotifyController
类,用于接收微信支付结果通知:
@RestController @RequestMapping("/wxpay") public class WxPayNotifyController { @Autowired private WxPayService wxPayService; @PostMapping("/notify") public String notify(@RequestBody String notifyData) { return wxPayService.notify(notifyData); } }WxPayService
中实现支付结果处理逻辑:
public String notify(String notifyData) { try { // 解析通知数据 Map<String, String> notifyMap = WxPayUtil.xmlToMap(notifyData); // 验证签名 if (!WxPayUtil.verifySignature(notifyMap, key)) { return "FAIL"; } // 处理支付结果 if ("SUCCESS".equals(notifyMap.get("result_code"))) { // 更新订单状态等业务逻辑 return "SUCCESS"; } } catch (Exception e) { e.printStackTrace(); } return "FAIL"; }在小程序前端页面中,调用后端接口获取支付参数,并调用微信支付API完成支付:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WeChat Pay Example</title>
</head>
<body>
<h1>WeChat Pay Example</h1>
<button id="payButton">Pay Now</button>
<script>
document.getElementById("payButton").addEventListener("click", function() {
// 调用后端接口获取支付参数
fetch('/wxpay/unifiedOrder', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
body: 'Test Payment',
out_trade_no: '123456789',
total_fee: '1',
spbill_create_ip: '127.0.0.1',
openid: 'your_openid'
})
})
.then(response => response.json())
.then(payParams => {
// 调用微信支付API
WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
"appId": payParams.appId,
"timeStamp": payParams.timeStamp,
"nonceStr": payParams.nonceStr,
"package": payParams.package,
"signType": payParams.signType,
"paySign": payParams.paySign
},
function(res) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
alert("支付成功");
} else {
alert("支付失败");
}
}
);
});
});
</script>
</body>
</html>
通过以上步骤,我们成功在Spring Boot项目中实现了微信小程序支付功能。从环境搭建到接口开发,再到支付流程实现和支付结果通知处理,每一步都至关重要。在实际开发中,还需要根据具体业务需求进行进一步的优化和调整 。希望本文能够为开发者提供一个清晰的实现思路和参考代码,帮助大家快速实现小程序支付功能。
以下是完整的参考代码:
WxPayService.java
@Service
public class WxPayService {
@Value("${wx.pay.appId}")
private String appId;
@Value("${wx.pay.mchId}")
private String mchId;
@Value("${wx.pay.key}")
private String key;
@Value("${wx.pay.notifyUrl}")
private String notifyUrl;
public Map<String, String> unifiedOrder(Map<String, String> params) {
Map<String, String> requestParams = new HashMap<>();
requestParams.put("appid", appId);
requestParams.put("mch_id", mchId);
requestParams.put("nonce_str", UUID.randomUUID().toString().replace("-", ""));
requestParams.put("body", params.get("body"));
requestParams.put("out_trade_no", params.get("out_trade_no"));
requestParams.put("total_fee", params.get("total_fee"));
requestParams.put("spbill_create_ip", params.get("spbill_create_ip"));
requestParams.put("notify_url", notifyUrl);
requestParams.put("trade_type", "JSAPI");
requestParams.put("openid", params.get("openid"));
String sign = WxPayUtil.createSign(requestParams, key);
requestParams.put("sign", sign);
String xml = WxPayUtil.mapToXml(requestParams);
String result = HttpClientUtil.doPost("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
Map<String, String> resultMap = WxPayUtil.xmlToMap(result);
Map<String, String> payParams = new HashMap<>();
payParams.put("appId", appId);
payParams.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
payParams.put("nonceStr", UUID.randomUUID().toString().replace("-", ""));
payParams.put("package", "prepay_id=" + resultMap.get("prepay_id"));
payParams.put("signType", "MD5");
payParams.put("paySign", WxPayUtil.createSign(payParams, key));
return payParams;
}
public String notify(String notifyData) {
try {
Map<String, String> notifyMap = WxPayUtil.xmlToMap(notifyData);
if (!WxPayUtil.verifySignature(notifyMap, key)) {
return "FAIL";
}
if ("SUCCESS".equals(notifyMap.get("result_code"))) {
// Update order status and other business logic
return "SUCCESS";
}
} catch (Exception e) {
e.printStackTrace();
}
return "FAIL";
}
}
WxPayController.java
@RestController
@RequestMapping("/wxpay")
public class WxPayController {
@Autowired
private WxPayService wxPayService;
@PostMapping("/unifiedOrder")
public Map<String, String> unifiedOrder(@RequestBody Map<String, String> params) {
return wxPayService.unifiedOrder(params);
}
}
WxPayNotifyController.java
@RestController
@RequestMapping("/wxpay")
public class WxPayNotifyController {
@Autowired
private WxPayService wxPayService;
@PostMapping("/notify")
public String notify(@RequestBody String notifyData) {
return wxPayService.notify(notifyData);
}
}
通过以上代码示例和详细步骤,可以快速实现微信小程序支付功能。希望能够帮助大家更好地理解和应用Spring Boot实现小程序支付功能。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有