springboot 集成支付宝扫描支付

时间:2024-10-27 07:23:28

准备

       企业支付宝商家开通当面付、电脑支付产品,蚂蚁开发平台创建应用获取相关参数

appId,privateKey,publicKey等参数。

集成SDK

        <dependency>
            <groupId>com.alipay.sdk</groupId>
            <artifactId>alipay-sdk-java</artifactId>
            <version>4.39.144.ALL</version>
        </dependency>

支付实现

public String pay(String orderNo,BigDecimal amount,String notifyUrl,String title) {
        // 构造请求参数
        AlipayClient client = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                appId, privateKey, "json", "utf-8", publicKey, "RSA2");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        // 异步通知
        request.setNotifyUrl(notifyUrl);
        //String orderNo= TouUtil.getOrderNo();
        //request.setBizContent("{\"out_trade_no\":\"" + orderNo + "\",\"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                //"\"total_amount\":\"" + amount + "\",\"subject\":\"商品\"}");
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(orderNo);
        model.setTotalAmount(String.valueOf(amount));
        model.setSubject(title);
        request.setBizModel(model);
        // 发起支付请求
        try {
            AlipayTradePrecreateResponse response = client.execute(request);
            if (response.isSuccess()) {
                //插入记录
                // 获取二维码链接
                String qrCode = response.getQrCode();
                // 返回或展示二维码链接
                return qrCode;
            } else {
                throw new SystemException("创建预支付交易单失败:" + response.getSubMsg());
            }
            //return client.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

回调函数

@RequestMapping("chargeBuy")
    public String alipayNotifyNo(HttpServletRequest request) throws AlipayApiException {
        // 解析支付宝回调请求参数
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            StringBuilder valueStr = new StringBuilder();
            for (int i = 0; i < values.length; i++) {
                valueStr.append((i == values.length - 1) ? values[i] : values[i] + ",");
            }
            params.put(name, valueStr.toString());
        }
        logger.info("会员充值回调 {}",requestParams);
        // 验证支付宝回调请求签名
        boolean verifyResult = AlipaySignature.rsaCheckV1(params, publicKey, "utf-8", "RSA2");
        if (verifyResult) {
            // 处理支付宝回调请求
            String outTradeNo = params.get("out_trade_no");
            String tradeNo = params.get("trade_no");
            String totalAmount = params.get("total_amount");
            logger.info("会员充值回调 {}",outTradeNo);
            LambdaQueryWrapper<TnlMoneyDto>wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(TnlMoneyDto::getOrderNo,outTradeNo);
            wrapper.eq(TnlMoneyDto::getStatus,0);
            TnlMoneyDto moneyDto=moneyMapper.selectOne(wrapper);
            if(ObjectUtil.isNotEmpty(moneyDto)){
                moneyDto.setStatus(1);
                moneyMapper.update(moneyDto,wrapper);
                //等级处理
                LambdaQueryWrapper<UserDto>queryWrapper=new LambdaQueryWrapper<>();
                queryWrapper.eq(UserDto::getId,moneyDto.getUId());
                UserDto userDto=userMapper.selectOne(queryWrapper);
                BigDecimal money= NumberUtil.add(userDto.getScore(), Convert.toBigDecimal(totalAmount));
                userDto.setScore(money);
                userMapper.update(userDto,queryWrapper);
            }
            // ...
            return "success";
        } else {
            return "fail";
        }
    }

测试结果

{
	"code": 200,
	"msg": "操作成功",
	"data": {
		"orderNo": "202410260909518307",
		"qrUrl": "https://qr.alipay.com/bax04786vowh4rmrehpr55b8"
	}
}

qrUrl让前端转二维码,大功告成。