微信支付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>
相关推荐
hadage2332 分钟前
--- stream 数据流 java ---
java·开发语言
ZL_56710 分钟前
uniapp中使用uni-forms实现表单管理,验证表单
前端·javascript·uni-app
《源码好优多》20 分钟前
基于Java Springboot汽配销售管理系统
java·开发语言·spring boot
小林想被监督学习1 小时前
Java后端如何进行文件上传和下载 —— 本地版
java·开发语言
Erosion20201 小时前
SPI机制
java·java sec
逸风尊者1 小时前
开发也能看懂的大模型:RNN
java·后端·算法
尘浮生2 小时前
Java项目实战II基于Java+Spring Boot+MySQL的智能停车计费系统(开发文档+数据库+源码)
java·开发语言·数据库·spring boot·mysql·微信小程序·maven
frost-cold2 小时前
【JavaEE】Servlet:表白墙
java·servlet·java-ee
總鑽風2 小时前
解决单元测试时找不到类名
java·单元测试·mybatis
渊渟岳2 小时前
秒懂Java为什么只有值传递
java