前端代码:
// 获取微信支付参数
wx.request({
url: 'https://yourdomain.com/wechat/pay',
method: 'POST',
data: {
orderId: '123456' // 传入订单 ID
},
success: function (res) {
wx.requestPayment({
timeStamp: res.data.timeStamp,
nonceStr: res.data.nonceStr,
package: res.data.package,
signType: res.data.signType,
paySign: res.data.paySign,
success: function (res) {
wx.showToast({
title: '支付成功',
icon: 'success',
duration: 2000
});
},
fail: function (res) {
wx.showToast({
title: '支付失败',
icon: 'none',
duration: 2000
});
}
})
},
fail: function (res) {
wx.showToast({
title: '获取支付信息失败',
icon: 'none',
duration: 2000
});
}
})
后端代码:
@RestController
@RequestMapping("/wechat")
public class WechatController {
/**
* 获取微信支付参数
*/
@PostMapping("/pay")
public ResultVo getWechatPayParams(@RequestParam("orderId") String orderId) {
// 根据订单 ID 查询订单信息并计算订单金额 totalFee
// 调用统一下单接口生成预付单
WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
request.setBody("商品描述");
request.setOutTradeNo(orderId); // 商户订单号
request.setTotalFee(BaseWxPayRequest.yuanToFen(totalFee)); // 订单金额,单位分
request.setSpbillCreateIp("127.0.0.1"); // 终端 IP
request.setNotifyUrl("https://yourdomain.com/wechat/pay/notify"); // 回调地址
request.setTradeType("JSAPI"); // 小程序支付类型
request.setOpenid("用户的 openid");
try {
WxPayUnifiedOrderResult result = wxPayService.unifiedOrder(request);
// 前端需要的微信支付参数
Map<String, String> payParams = new HashMap<>();
payParams.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
payParams.put("nonceStr", result.getNonceStr());
payParams.put("package", "prepay_id=" + result.getPrepayId());
payParams.put("signType", "MD5");
payParams.put("paySign", WXPayUtil.generateSignature(payParams, wxPayService.getConfig().getKey())); // 生成签名
return ResultVoUtil.success(payParams);
} catch (Exception e) {
log.error("【小程序支付】获取支付参数失败,orderId={}", orderId, e);
return ResultVoUtil.error(ResultEnum.ORDER_PAY_FAIL);
}
}
/**
* 微信支付回调通知
*/
@PostMapping("/pay/notify")
public String notify(@RequestBody String xmlData) {
try {
WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
// 处理支付成功逻辑
// ...
return WxPayNotifyResponse.success("OK");
} catch (Exception e) {
log.error("【小程序支付】微信支付异步通知失败", e);
return WxPayNotifyResponse.fail("处理失败");
}
}
}
以上代码中 wxPayService
是封装了微信支付相关功能的服务类,如有需求,请自行实现或引入第三方库。