【微信开发】SpringBoot 集成微信小程序支付
在上一篇文章的基础上,实现小程序支付就很简单了,直接对接支付的接口,以及前端怎么唤起微信小程序的支付就OK了
1、SprinBoot 后端
增加controller两个方法,一个创建订单,一个支付成功的回调
@ApiOperation("统一下单")
@PostMapping("createOrder")
public AjaxResult createOrder(@RequestBody OrderInfo entity) {
return weiXinService.createOrder(entity);
}
@ApiOperation("支付回调")
@RequestMapping("notifyUrl")
public String notifyUrl() {
return weiXinService.notifyUrl();
}
service方法照样实现
AjaxResult createOrder(OrderInfo entity);
String notifyUrl();
service两个方法的实现类
@Override
public AjaxResult createOrder(OrderInfo entity) {
try {
WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
orderRequest.setSignType(WxPayConstants.SignType.MD5);
orderRequest.setBody("Tellsea科技");
orderRequest.setOutTradeNo(UUID.randomUUID().toString().substring(0, 32));
orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
orderRequest.setTotalFee(BaseWxPayRequest.yuanToFen(entity.getMoney()));
orderRequest.setOpenid(entity.getOpenId());
orderRequest.setSpbillCreateIp(ServletUtils.getClientIP());
orderRequest.setNotifyUrl(wxPayProperties.getNotifyUrl());
Object order = wxPayService.createOrder(orderRequest);
log.error("下单成功:{}", order.toString());
return AjaxResult.success("下单成功", JSON.toJSONString(order));
} catch (WxPayException e) {
log.error("下单失败:{}", e.toString());
return AjaxResult.error("下单失败");
}
}
@Override
public String notifyUrl() {
try {
HttpServletRequest request = ServletUtils.getRequest();
HttpServletResponse response = ServletUtils.getResponse();
String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlResult);
String orderId = result.getOutTradeNo();
String tradeNo = result.getTransactionId();
String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());
return WxPayNotifyResponse.success("处理成功!");
} catch (Exception e) {
log.error("微信回调结果异常,异常原因{}", e.getMessage());
return WxPayNotifyResponse.fail(e.getMessage());
}
}
模拟订单参数
import lombok.Data;
@Data
public class OrderInfo {
private String openId;
private String money;
}
2、Uniapp 前端
(1)唤起支付
在第一个篇集成小程序登录的文章中,该有的所有配置都有了,这里只需要通过统一下单接口返回的参数,唤起支付即可
let param = {
openId: '登录成功获取的openId',
money: 1
};
that.$u.post('/au/weiXin/createOrder', param).then(res => {
let data = JSON.parse(res.data);
wx.requestPayment({
timeStamp: data.timeStamp,
nonceStr: data.nonceStr,
package: data.packageValue,
signType: data.signType,
paySign: data.paySign
});
});
(2)测试案例
这里微信开发者工具中的测试样子
微信公众号
|