支付宝支付Java+uniapp支付宝小程序

JS:

					request.post('/vip/pay', {//这是自己写的java支付接口
						id: this.vipInfo.id,
						payWay: 'alipay-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": "alipay",
							"orderInfo": res.data.tradeNo,
							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_ALIPAY.getCode()) || StrUtil.equals(payWay, PayWayEnum.ALIPAY.getCode())) {
            return aliPayRequest(tradeId, pay.getPayAmount(), pay.payWay(), "https://xxx.xxx.xxx/vip/alipayCallback","会员卡");
        }
        return R.fail();
    }
	
	//发起支付宝支付
	private Object aliPayRequest(Long tradeId, BigDecimal payMoney, String payWay, String notifyUrl, String subject) {
        AliPayConfig ali = new AliPayConfig();//获取商户的支付配置

        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do"
                , ali.getAppId(), ali.getPrivateSign(), "json", StandardCharsets.UTF_8.name(), ali.getPublicKey(), ali.getSignType());

        if (StrUtil.equals(payWay, PayWayEnum.MIN_ALIPAY.getCode())) {//支付宝小程序
            AlipayTradePayModel bizContent = new AlipayTradePayModel();
            bizContent.setBuyerOpenId(LoginHelper.getLoginUser().getToken());
            bizContent.setOutTradeNo(String.valueOf(tradeId));//存入我们自己的流水号
            bizContent.setTotalAmount(String.valueOf(payMoney));
            bizContent.setSubject(subject);

            AlipayTradeCreateRequest aliRequest = new AlipayTradeCreateRequest();
            aliRequest.setNotifyUrl(notifyUrl);
            aliRequest.setBizModel(bizContent);
            try {
                AlipayTradeCreateResponse response = alipayClient.execute(aliRequest);
                if (response.isSuccess()) {
                    return response;
                }
                throw new ServiceException(response.getSubMsg());
            } catch (AlipayApiException e) {
                throw new ServiceException(e.getErrMsg());
            }

        }

        if (StrUtil.equals(payWay, PayWayEnum.ALIPAY.getCode())) {//支付宝
            AlipayTradeAppPayModel bizContent = new AlipayTradeAppPayModel();
            bizContent.setOutTradeNo(String.valueOf(tradeId));//存入我们自己的流水号
            bizContent.setTotalAmount(String.valueOf(payMoney));
            bizContent.setSubject(subject);

            AlipayTradeAppPayRequest aliRequest = new AlipayTradeAppPayRequest();
            aliRequest.setNotifyUrl(notifyUrl);
            aliRequest.setBizModel(bizContent);
            try {
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(aliRequest);
                if (response.isSuccess()) {
                    return response.getBody();
                }
                throw new ServiceException(response.getSubMsg());
            } catch (AlipayApiException e) {
                throw new ServiceException(e.getErrMsg());
            }
        }
        return R.ok();
    }
	
	/**
     * 回调
     */
    @PostMapping("/alipayCallback")
    @SaIgnore
    public String alipayCallback(HttpServletRequest request) {
	
		Map<String, String> params = ServletUtils.getParamMap(request);
        StaticLog.info("支付宝支付回调={}", JSONObject.toJSONString(params));

        String outTradeNo = params.get("out_trade_no");//拿到我们自己的流水号
        String tradeNo = params.get("trade_no");
        String tradeStatus = params.get("trade_status");
        String gmtPayment = params.get("gmt_payment");
	
        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) || !"TRADE_SUCCESS".equals(tradeStatus)) {
            StaticLog.info("支付信息不存在或支付失败");
            return "failure";
        }

        AliPayConfig ali = new AliPayConfig();//获取商户的支付配置

        boolean signVerified = AlipaySignature.rsaCheckV1(params, ali.getPublicKey(),
                StandardCharsets.UTF_8.name(), ali.getSignType());

        if (!signVerified) {
            StaticLog.info("验签失败");
            return "failure";
        }

        long orderId = trade.getOrderId();//这个是业务订单ID,也就是VIP表的ID
        long payTime = DateUtil.parse(gmtPayment, NORM_DATETIME_FORMATTER).getTime() / 1000;

        paySuccess(tradeNo, payTime, outTradeNo, orderId, trade.getUserId());
        return "success";
    }
	
	//支付成功业务逻辑
	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.alipay.sdk</groupId>
            <artifactId>alipay-sdk-java</artifactId>
			<version>4.39.150.ALL</version>
        </dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值