首页 > 基础资料 博客日记

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

2024-10-27 15:00:13基础资料围观91

Java资料网推荐微信支付Java+uniapp微信小程序这篇文章给大家,欢迎收藏Java资料网享受知识的乐趣

JS:

					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:

    /**
     * 会员卡支付
     */
    @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:

		<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>

文章来源:https://blog.csdn.net/u012643122/article/details/143255195
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云