微信支付Java+uniapp微信小程序

JS:

javascript 复制代码
					request.post('/vip/pay', {//这是自己写的java支付接口
						id: this.vipInfo.id,
						payWay: 'wechat-mini'
					}).then((res) => {
						let success = (res2) => {//前端的支付成功回调函数
							this.$refs.popup.close();
							// 支付成功刷新当前页面
							setTimeout(() => {
								this.doGetVipInfo(this.vipInfo.id);
							}, 2500)
						}
						let fail = (res) => {
							//支付失败,进行提示
							util.showToast(this.$t('pay.fail'))
						}
						let payObj = {
								"provider": "wxpay",
								"timeStamp": res.data.timeStamp,
								"nonceStr": res.data.nonceStr,
								"package": res.data.packageValue,
								"signType": res.data.signType,
								"paySign": res.data.paySign,
								"appId": res.data.appId,
								success,
								fail
						};
						console.log("支付>>>" + JSON.stringify(payObj));
						uni.requestPayment(payObj);//uniapp提供的统一支付接口,可以在微信小程序内调起微信支付界面
					}).finally(() => {})

Java:

java 复制代码
    /**
     * 会员卡支付
     */
    @PostMapping("/pay")
    @RepeatSubmit
    public R<Object> pay(@RequestBody AppVipPayVo pay) {
		long tradeId = payTradeService.save(pay.payWay(), pay.getPayAmount(), pay.getVipId(), TradeTypeEnum.VIP.getCode());//创建自己的交易订单
		
		if (StrUtil.equals(payWay, PayWayEnum.MIN_WECART.getCode()) || StrUtil.equals(payWay, PayWayEnum.WECART.getCode())) {
            return wxPayRequest(tradeId, pay.getPayAmount(), pay.payWay(), "https://xxx.xxx.xxx/vip/wxpayCallback","会员卡");
        }
        return R.fail();
    }
	
	//发起微信支付
	private Object wxPayRequest(Long tradeId, BigDecimal payMoney, String payWay, String notifyUrl, String subject) {
        WxPayConfig wechat= new WxPayConfig();//获取商户的支付配置
		WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        orderRequest.setBody(subject);
        orderRequest.setOutTradeNo(String.valueOf(tradeId));//存入我们自己的流水号
        orderRequest.setTotalFee(BaseWxPayRequest.yuanToFen(String.valueOf(payMoney)));
        orderRequest.setSpbillCreateIp(ServletUtils.getClientIP());
        orderRequest.setTradeType(WxPayConstants.TradeType.APP);
        if (StrUtil.equals(payWay, PayWayEnum.MIN_WECHAT.getCode())) {
            orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
            orderRequest.setOpenid(LoginHelper.getLoginUser().getToken());//获取用户的openid,微信登录时就需要保存openid作为token
        }
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(wechat.getAppId());
        wxPayConfig.setMchKey(wechat.getSecret());
        wxPayConfig.setMchId(wechat.getMchId());
        wxPayConfig.setNotifyUrl(notifyUrl);
        wxPayConfig.setSubMchId(StrUtil.isBlank(wechat.getSubMchId()) ? null : wechat.getSubMchId());//如果有子商户,则设置子商户

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig);
        try {
            Object payResult = wxPayService.createOrder(orderRequest);
            JSONObject json = JSONUtil.parseObj(payResult);
            json.set("tradeId", tradeId);
            return json;
        } catch (WxPayException e) {
            log.error("微信缴费失败" + wechat.getAppId() + ">>>" + wechat.getMchId());
            throw new ServiceException(e.getMessage());
        }
    }
	
	/**
     * 回调
     */
    @PostMapping("/wxpayCallback")
    @SaIgnore
    public String wxpayCallback(HttpServletRequest request) {
	
		String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        StaticLog.info("微信支付回调={}", xmlResult);
		WxPayOrderNotifyResult result = WxPayOrderNotifyResult.fromXML(xmlResult);

        String outTradeNo = result.getOutTradeNo();//拿到我们自己的流水号
	
        LambdaQueryWrapper<PayTrade> eq = Wrappers.<PayTrade>lambdaQuery()
                .eq(PayTrade::getId, outTradeNo)
                .isNull(PayTrade::getOutTradeNo)
                .eq(PayTrade::getTradeStatus, TradeStatusEnum.WAIT_PAY.getCode());
        PayTrade trade = PayTradeMapper.selectOne(eq);

        if (ObjectUtil.isNull(trade)) {
            StaticLog.error("支付订单不存在");
            return WxPayNotifyResponse.success("OK");
        }
        WxPayConfig wechat= new WxPayConfig();//获取商户的支付配置
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(wechat.getAppId());
        wxPayConfig.setMchKey(wechat.getSecret());
        wxPayConfig.setMchId(wechat.getMchId());
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig);
        wxPayService.parseOrderNotifyResult(xmlResult);//解密,如果解密失败,会抛出异常

        if (result.getResultCode().contains("FAIL")) {
            return WxPayNotifyResponse.fail("FAIL");
        }

        long orderId = trade.getOutPayId();//会员卡ID
        long payTime = DateUtil.parse(result.getTimeEnd(), PURE_DATETIME_PATTERN).getTime() / 1000;

        paySuccess(result.getTransactionId(), payTime, outTradeNo, orderId, trade.getUserId());
        return WxPayNotifyResponse.success("OK");
    }
	
	//支付成功业务逻辑
	private void paySuccess(String tradeNo, long payTime, String outTradeNo, long orderId, Long userId) {
		//修改订单状态
        payTradeMapper.update(null, new LambdaUpdateWrapper<PayTrade>()
                .set(PayTrade::getTradeStatus, TradeStatusEnum.PAY_SUCCESS.getCode())
                .set(PayTrade::getOutTradeNo, tradeNo)
                .set(PayTrade::getPayTime, payTime)
                .set(PayTrade::getHasNotify, true)
                .eq(PayTrade::getId, outTradeNo));
    }

pom.xml:

xml 复制代码
		<dependency>
		    <groupId>com.github.binarywang</groupId>
		    <artifactId>weixin-java-pay</artifactId>
		    <version>4.5.0</version>
		</dependency>
		<dependency>
		    <groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.11.0</version>
		</dependency>
相关推荐
阿乾之铭1 分钟前
Spring Boot框架中的IO
java·spring boot·log4j·1024程序员节
程序猿阿伟7 分钟前
《C++中的魔法:实现类似 Python 的装饰器模式》
java·c++·装饰器模式
Mr. zhihao9 分钟前
装饰器模式详解:动态扩展对象功能的优雅解决方案
java·开发语言·装饰器模式
2401_8576009516 分钟前
商场应急管理:SpringBoot技术解决方案
java·spring boot·后端
想做白天梦28 分钟前
多级反馈队列
java·windows·算法
潇雷30 分钟前
算法Day12|226-翻转二叉树;101-对称二叉树;104-二叉树最大深度;111-二叉树最小深度
java·算法·leetcode
一颗甜苞谷37 分钟前
开源一套基于若依的wms仓库管理系统,支持lodop和网页打印入库单、出库单的源码
java·开源
半夏之沫39 分钟前
✨最新金九银十✨大厂后端面经✨
java·后端·面试
计算机学姐1 小时前
基于uniapp微信小程序的餐厅预约点餐系统
java·spring boot·微信小程序·小程序·java-ee·uni-app·tomcat