自学内容网 自学内容网

Springboot对接开发微信支付详细流程

一、微信配置申请

1、微信支付配置申请

详细操作流程参考官方文档:接入前准备-小程序支付 | 微信支付商户平台文档中心

接入前准备-小程序支付 | 微信支付商户平台文档中心icon-default.png?t=O83Ahttps://pay.weixin.qq.com/wiki/doc/apiv3/open/pay/chapter2_8_1.shtml#part-1

配置完成需要以下信息:

  • APPID
  • 商户号(mchid)
  • 商户API私钥(apiclient_key.pem)
  • 商户证书序列号
  • 商户APIv3密钥

二、开发环境

1、开发环境

开发语言:java ,编译工具:idea ,框架:springboot ,仓库:maven

2、maven依赖

<dependency>
  <groupId>com.github.wechatpay-apiv3</groupId>
  <artifactId>wechatpay-java</artifactId>
  <version>0.2.10</version>
</dependency>

3、application.yml文件配置

#微信支付配置
wx:
  pay:
    #应用id(小程序id)
    appId: wx6b5xxxxxxxxxxxx
    #商户号
    merchantId: 1xxxxxxxxx
    #商户API私钥
    privateKey: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    #商户证书序列号
    merchantSerialNumber: 315DDXXXXXXXXXXXXXXXXXXXXXXXXXXX
    #商户APIv3密钥
    apiV3Key: XXXXXXXXXXXXXXXXXXXXXXXXXX
    #支付通知地址
    payNotifyUrl: https://xxx.xxxx.xxx.xxx/xx/xxxx/xxxx/openapi/wx/payNotify
    #退款通知地址
    refundNotifyUrl: https://xxx.xxx.xxx.xxx/xxxx/xxxx/xxxx/openapi/wx/refundNotify

三、代码开发

1、配置类

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author gwh
 * @ClassName WxPayConfig
 * @description: 微信支付配置类
 * @date 2024年11月11日
 * @version: 1.0
 */
@Data
@Component
@ConfigurationProperties(prefix = "wx.pay")
public class WxPayConfig {
    //APPID
    private String appId;
    //mchid
    private String merchantId;
    //商户API私钥
    private String privateKey;
    //商户证书序列号
    private String merchantSerialNumber;
    //商户APIv3密钥
    private String apiV3Key;
    //支付通知地址
    private String payNotifyUrl;
    //退款通知地址
    private String refundNotifyUrl;
}

2、初始化商户配置

import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author gwh
 * @ClassName WxPayAutoCertificateConfig
 * @description: 微信支付证书自动更新配置
 * @date 2024年11月11日
 * @version: 1.0
 */
@Configuration
public class WxPayAutoCertificateConfig {
    @Resource
    private WxPayConfig wxPayConfig;

    /**
     * 初始化商户配置
     * @return
     */
    @Bean
    public RSAAutoCertificateConfig rsaAutoCertificateConfig() {
        RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
                .merchantId(wxPayConfig.getMerchantId())
                .privateKey(wxPayConfig.getPrivateKey())
                .merchantSerialNumber(wxPayConfig.getMerchantSerialNumber())
                .apiV3Key(wxPayConfig.getApiV3Key())
                .build();
        return config;
    }
}

3、JSAPI微信预下单

3.1、先建个WxPayService服务类
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hvit.user.exception.DataAccessException;
import com.hvit.user.util.DateUtils;
import com.hvit.user.util.R;
import com.hvit.user.yst.entity.WxOrderEntity;
import com.hvit.user.yst.entity.WxPayLogEntity;
import com.hvit.user.yst.request.CreateOrderReq;
import com.hvit.user.yst.request.QueryOrderReq;
import com.hvit.user.yst.request.WxNotifyReq;
import com.hvit.user.yst.service.WKShoppingMallService;
import com.hvit.user.yst.service.data.WxOrderDataService;
import com.hvit.user.yst.service.data.WxPayLogDataService;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.*;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.*;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author gwh
 * @ClassName WxPayService
 * @description: 微信支付
 * @date 2024年11月11日
 * @version: 1.0
 */
@Slf4j
@Service
public class WxPayService {

    @Resource
    private WxPayConfig wxPayConfig;
    @Autowired
    private RSAAutoCertificateConfig rsaAutoCertificateConfig;
    @Autowired
    private WxOrderDataService wxOrderDataService;
    @Autowired
    private WxPayLogDataService wxPayLogDataService;

    /***
     * 预支付订单
     * @param req
     * @return
     */
    public R createOrder(CreateOrderReq req) throws Exception {
        if (req == null) {
            return R.error("创建订单失败,缺少参数!");
        }
        //先解密
        
        String orderNo = req.getOutTradeNo();
        Integer totalFee = req.getTotal();
        //创建初始化订单
        //todo,创建订单这边你们自己来(后面我会放出表结构)
        //请求微信支付相关配置
        JsapiServiceExtension service =
                new JsapiServiceExtension.Builder()
                        .config(rsaAutoCertificateConfig)
                        .signType("RSA") // 不填默认为RSA
                        .build();
        PrepayWithRequestPaymentResponse response = new PrepayWithRequestPaymentResponse();
        try {
            PrepayRequest request = new PrepayRequest();
            request.setAppid(wxPayConfig.getAppId());
            request.setMchid(wxPayConfig.getMerchantId());
            request.setDescription(description);
            request.setOutTradeNo(orderNo);
            request.setNotifyUrl(wxPayConfig.getPayNotifyUrl());
            Amount amount = new Amount();
            //amount.setTotal(totalFee.multiply(new BigDecimal("100")).intValue());
            amount.setTotal(totalFee);
            request.setAmount(amount);
            Payer payer = new Payer();
            payer.setOpenid(req.getWxOpenId());
            request.setPayer(payer);
            log.info("请求预支付下单,请求参数:{}", JSONObject.toJSONString(request));
            // 调用预下单接口
            response = service.prepayWithRequestPayment(request);
            log.info("订单【{}】发起预支付成功,返回信息:{}", orderNo, response);
        } catch (HttpException e) { // 发送HTTP请求失败
            log.error("微信下单发送HTTP请求失败,错误信息:{}", e.getHttpRequest());
            return R.error("下单失败");
        } catch (ServiceException e) { // 服务返回状态小于200或大于等于300,例如500
            log.error("微信下单服务状态错误,错误信息:{}", e.getErrorMessage());
            return R.error("下单失败");
        } catch (MalformedMessageException e) { // 服务返回成功,返回体类型不合法,或者解析返回体失败
            log.error("服务返回成功,返回体类型不合法,或者解析返回体失败,错误信息:{}", e.getMessage());
            return R.error("下单失败");
        }

        return R.ok().put("data", response);
    }
}
3.1、R实体类
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author gwh
 * @date 2024-11-11
 */
public class R extends HashMap<String, Object> {

    private static final long serialVersionUID = 1L;

    public R() {
        put("code", 0);
    }

    public R(Integer code) {
        put("code", code);
        put("data", new HashMap<String, Object>());
    }

    public R(Integer code, String msg) {
        put("code", code);

原文地址:https://blog.csdn.net/gaowenhui2008/article/details/143683335

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!