Spring Boot项目实现微信和支付宝支付

Spring Boot项目实现微信和支付宝支付

本文将为大家详细介绍如何在Spring Boot项目中实现微信和支付宝的支付功能。我们将首先对微信和支付宝的支付流程进行简要介绍,然后逐步引导大家完成支付功能的具体实现。

文章内容如下:

  • 支付流程简介
  • 项目环境配置
  • 支付宝支付实现
  • 微信支付实现
  • 总结

支付流程简介

支付流程大致可以分为以下几个步骤:

  1. 用户选择支付方式(微信或支付宝)。
  2. 后端根据用户选择的支付方式,生成支付订单信息,并将订单信息发送给对应的支付平台。
  3. 支付平台生成支付二维码,并返回给后端。
  4. 后端将支付二维码返回给前端。
  5. 用户扫描二维码进行支付。
  6. 支付完成后,支付平台会通知后端支付结果。
  7. 后端根据支付结果更新订单状态。

接下来,我们将分别实现支付宝和微信的支付功能。

项目环境配置

首先,我们需要在Spring Boot项目中引入支付宝和微信支付所需的依赖。在pom.xml文件中添加以下内容:

<dependencies>
    <!-- 支付宝支付依赖 -->
    <dependency>
        <groupId>com.alipay.sdk</groupId>
        <artifactId>alipay-sdk-java</artifactId>
        <version>4.10.30.ALL</version>
    </dependency>
    <!-- 微信支付依赖 -->
    <dependency>
        <groupId>com.github.binarywang</groupId>
        <artifactId>weixin-java-pay</artifactId>
        <version>3.7.0</version>
    </dependency>
</dependencies>

然后,在application.yml文件中添加支付宝和微信支付的配置信息,如下:

alipay:
  app-id: your_alipay_app_id
  private-key: your_alipay_private_key
  alipay-public-key: your_alipay_public_key
  server-url: https://openapi.alipay.com/gateway.do
  charset: utf-8
  sign-type: RSA2
  notify-url: http://your_domain/alipay/notify

wechat:
  app-id: your_wechat_app_id
  mch-id: your_wechat_mch_id
  mch-key: your_wechat_mch_key
  notify-url: http://your_domain/wechat/notify

支付宝支付实现

创建支付宝支付服务类

首先,我们需要创建一个支付宝支付服务类(AlipayService.java)来封装支付宝支付相关的逻辑:

@Service
public class AlipayService {
    
    

    @Value("${alipay.app-id}")
    private String appId;

    @Value("${alipay.private-key}")
    private String privateKey;

    @Value("${alipay.alipay-public-key}")
    private String alipayPublicKey;

    @Value("${alipay.server-url}")
    private String serverUrl;

    @Value("${alipay.charset}")
    private String charset;

    @Value("${alipay.sign-type}")
    private String signType;

    @Value("${alipay.notify-url}")
    private String notifyUrl;

    /**
     * 创建支付宝支付订单
     * @param orderId 订单ID
     * @param amount 支付金额
     * @return 支付宝支付二维码链接
     * @throws AlipayApiException
     */
    public String createAlipayOrder(String orderId, BigDecimal amount) throws AlipayApiException {
    
    
        // 实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, "json", charset, alipayPublicKey, signType);

        // 创建API对应的request
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();

        // 设置支付宝支付回调地址
        request.setNotifyUrl(notifyUrl);

        // 设置请求参数
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(orderId);
        model.setTotalAmount(amount.toString());
        model.setSubject("订单支付");
        request.setBizModel(model);

        // 发起请求,获取支付宝支付二维码链接
        AlipayTradePrecreateResponse response = alipayClient.execute(request);

        // 判断请求是否成功
        if (response.isSuccess()) {
    
    
            return response.getQrCode();
        } else {
    
    
            throw new AlipayApiException(response.getSubMsg());
        }
    }

    /**
     * 处理支付宝支付结果通知
     * @param requestParams 支付宝支付结果通知参数
     * @return 是否处理成功
     */
    public boolean handleAlipayNotify(Map<String, String> requestParams) {
    
    
        try {
    
    
            // 验签
            boolean signVerified = AlipaySignature.rsaCheckV1(requestParams, alipayPublicKey, charset, signType);

            if (signVerified) {
    
    
                // 获取支付宝支付结果通知数据
                String outTradeNo = requestParams.get("out_trade_no"); // 商户订单号
                String tradeNo = requestParams.get("trade_no"); // 支付宝交易号
                String tradeStatus = requestParams.get("trade_status"); // 交易状态

                // 根据支付结果更新订单状态
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
    
    
                    // 更新订单状态为已支付
                    // updateOrderStatus(outTradeNo, tradeNo, "已支付");
                    return true;
                }
            }
        } catch (AlipayApiException e) {
    
    
            e.printStackTrace();
        }
        return false;
    }
}

创建支付宝支付控制器类

接下来,我们需要创建一个支付宝支付控制器类(AlipayController.java)来处理前端的支付请求和支付宝支付结果通知:

@RestController
@RequestMapping("/alipay")
public class AlipayController {
    
    

    @Autowired
    private AlipayService alipayService;

    /**
     * 创建支付宝支付订单
     * @param orderId 订单ID
     * @param amount 支付金额
     * @return 支付宝支付二维码链接
     */
    @GetMapping("/createOrder")
    public String createAlipayOrder(@RequestParam String orderId, @RequestParam BigDecimal amount) {
    
    
        try {
    
    
            String qrCodeUrl = alipayService.createAlipayOrder(orderId, amount);
            return qrCodeUrl;
        } catch (AlipayApiException e) {
    
    
            e.printStackTrace();
            return "创建支付宝支付订单失败";
        }
    }

    /**
     * 支付宝支付结果通知处理
     * @param request 请求对象
     * @return 支付宝支付结果通知响应
     */
    @PostMapping("/notify")
    public String handleAlipayNotify(HttpServletRequest request) {
    
    
        // 获取支付宝支付结果通知参数
        Map<String, String> requestParams = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
    
    
            requestParams.put(key, StringUtils.join(parameterMap.get(key), ","));
        }

        // 处理支付宝支付结果通知
        boolean success = alipayService.handleAlipayNotify(requestParams);

        if (success) {
    
    
            return "success";
        } else {
    
    
            return "failure";
        }
    }
}

至此,支付宝支付功能已经实现。用户可以通过请求/alipay/createOrder接口创建支付宝支付订单,然后扫描返回的支付二维码进行支付。支付完成后,支付宝会向/alipay/notify接口发送支付结果通知。

微信支付实现

我们可以先定义一个WechatPayService接口,用于封装微信支付相关的操作:

public interface WechatPayService {
    
    
    /**
     * 统一下单
     *
     * @param order 订单信息
     * @return 统一下单结果
     * @throws WxPayException 微信支付异常
     */
    WxPayUnifiedOrderResult unifiedOrder(WxPayUnifiedOrderRequest order) throws WxPayException;

    /**
     * 查询订单
     *
     * @param transactionId 微信订单号
     * @param outTradeNo    商户订单号
     * @return 订单查询结果
     * @throws WxPayException 微信支付异常
     */
    WxPayOrderQueryResult queryOrder(String transactionId, String outTradeNo) throws WxPayException;

    /**
     * 关闭订单
     *
     * @param outTradeNo 商户订单号
     * @return 关闭订单结果
     * @throws WxPayException 微信支付异常
     */
    WxPayOrderCloseResult closeOrder(String outTradeNo) throws WxPayException;

    /**
     * 申请退款
     *
     * @param request 退款请求
     * @return 退款结果
     * @throws WxPayException 微信支付异常
     */
    WxPayRefundResult refund(WxPayRefundRequest request) throws WxPayException;

    /**
     * 查询退款
     *
     * @param transactionId 微信订单号
     * @param outTradeNo    商户订单号
     * @param outRefundNo   商户退款单号
     * @param refundId      微信退款单号
     * @return 退款查询结果
     * @throws WxPayException 微信支付异常
     */
    WxPayRefundQueryResult refundQuery(String transactionId, String outTradeNo, String outRefundNo, String refundId) throws WxPayException;

    /**
     * 下载对账单
     *
     * @param request 下载对账单请求
     * @return 下载对账单结果
     * @throws WxPayException 微信支付异常
     */
    WxPayBillResult downloadBill(WxPayDownloadBillRequest request) throws WxPayException;

    /**
     * 通知处理
     *
     * @param xmlData 通知内容
     * @return 通知结果
     * @throws WxPayException 微信支付异常
     */
    WxPayNotifyResult parsePayNotifyResult(String xmlData) throws WxPayException;
}

然后,我们可以实现这个接口,并在实现类中注入微信支付相关的配置信息:

@Service
public class WechatPayServiceImpl implements WechatPayService {
    
    

    private final WxPayService wxPayService;

    @Autowired
    public WechatPayServiceImpl(WxPayConfig wxPayConfig) {
    
    
        this.wxPayService = new WxPayServiceImpl();
        this.wxPayService.setConfig(wxPayConfig);
    }

    @Override
    public WxPayUnifiedOrderResult unifiedOrder(WxPayUnifiedOrderRequest order) throws WxPayException {
    
    
        return wxPayService.unifiedOrder(order);
    }

    @Override
    public WxPayOrderQueryResult queryOrder(String transactionId, String outTradeNo) throws WxPayException {
    
    
        return wxPayService.queryOrder(transactionId, outTradeNo);
    }

    @Override
    public WxPayOrderCloseResult closeOrder(String outTradeNo) throws WxPayException {
    
    
        return wxPayService.closeOrder(outTradeNo);
    }

    @Override
    public WxPayRefundResult refund(WxPayRefundRequest request) throws WxPayException {
    
    
        return wxPayService.refund(request);
    }

    @Override
    public WxPayRefundQueryResult refundQuery(String transactionId, String outTradeNo, String outRefundNo, String refundId) throws WxPayException {
    
    
        return wxPayService.refundQuery(transactionId, outTradeNo, outRefundNo, refundId);
    }

    @Override
    public WxPayBillResult downloadBill(WxPayDownloadBillRequest request) throws WxPayException {
    
    
        return wxPayService.downloadBill(request);
    }

    @Override
    public WxPayNotifyResult parsePayNotifyResult(String xmlData) throws WxPayException {
    
    
        return wxPayService.parseOrderNotifyResult(xmlData);
    }
}

在实现微信支付接口的时候,我们使用了WxPayService,这是微信支付SDK提供的封装了微信支付相关操作的类。我们通过注入WxPayConfig来配置WxPayServiceWxPayConfig中包含了微信支付的相关参数,我们可以在配置文件中配置这些参数,然后通过WxPayConfig来构建WxPayService

猜你喜欢

转载自blog.csdn.net/orton777/article/details/131538447