当前位置: 代码网 > it编程>编程语言>Java > java Springboot对接开发微信支付详细流程

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

2024年08月02日 Java 我要评论
一、微信配置申请1、微信支付配置申请详细操作流程参考官方文档:https://pay.weixin.qq.com/wiki/doc/apiv3/open/pay/chapter2_8_1.shtml#

一、微信配置申请

1、微信支付配置申请

详细操作流程参考官方文档:https://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 caozhen
 * @classname wxpayconfig
 * @description: 微信支付配置类
 * @date 2024年01月03日
 * @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 caozhen
 * @classname wxpayautocertificateconfig
 * @description: 微信支付证书自动更新配置
 * @date 2024年01月03日
 * @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 caozhen
 * @classname wxpayservice
 * @description: 微信支付
 * @date 2024年01月03日
 * @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 曹震
 * @date 2024-1-03
 */
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);
        put("msg", msg);
        put("data", new hashmap<string, object>());
    }

    public static r error() {
        return error(500, "未知异常,请联系管理员");
    }

    public static r errordebug(string message) {
        return error(500, "未知异常 " + message + ",请联系管理员");
    }

    public static r error(string msg) {
        return error(500, msg);
    }
   

    public static r error(int code, string msg) {
        r r = new r();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }

    public r errorinfo(string msg) {
        this.put("errormsg", msg);
        return this;
    }

    public static r ok(string msg) {
        r r = new r();
        r.put("msg", msg);
        r.put("data", new hashmap<string, object>());
        return r;
    }

    public static r ok(map<string, object> map) {
        r r = new r();
        r.putall(map);
        r.put("data", new hashmap<string, object>());
        return r;
    }

    public static r ok() {
        return new r().put("msg", "success").put("data", new hashmap<string, object>());
    }

    public static r ok(integer size) {
        return new r().put("data", new hashmap<string, object>((int)math.round(size / 0.75)));
    }

    @override
    public r put(string key, object value) {
        super.put(key, value);
        return this;
    }

    /**
     * 添加返回结果数据
     *
     * @param key
     * @param value
     * @return
     */
    public r putdata(string key, object value) {
        map<string, object> map = (hashmap<string, object>)this.get("data");
        map.put(key, value);
        return this;
    }
}

3.2、createorderreq类

import io.swagger.annotations.apimodelproperty;
import lombok.data;

/**
 * @author caozhen
 * @classname createorderreq
 * @description: todo
 * @date 2024年01月03日
 * @version: 1.0
 */
@data
public class createorderreq {

    @apimodelproperty(name = "description", value = "商品描述")
    private string description;

    @apimodelproperty(name = "wxopenid", value = "用户小程序openid")
    private string wxopenid;

    @apimodelproperty(name = "outtradeno", value = "商户订单号")
    private string outtradeno;

    @apimodelproperty(name = "totalfee", value = "支付金额,单位:分")
    private long totalfee;

4、微信支付回调通知 

/***
     * 微信支付回调通知
     * @param request
     * @return
     * @throws ioexception
     */
    @transactional
    public synchronized string paynotify(httpservletrequest request) throws exception {
        log.info("------收到支付通知------");
        // 请求头wechatpay-signature
        string signature = request.getheader("wechatpay-signature");
        // 请求头wechatpay-nonce
        string nonce = request.getheader("wechatpay-nonce");
        // 请求头wechatpay-timestamp
        string timestamp = request.getheader("wechatpay-timestamp");
        // 微信支付证书序列号
        string serial = request.getheader("wechatpay-serial");
        // 签名方式
        string signtype = request.getheader("wechatpay-signature-type");
        // 构造 requestparam
        requestparam requestparam = new requestparam.builder()
                .serialnumber(serial)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .signtype(signtype)
                .body(httpservletutils.getrequestbody(request))
                .build();

        // 初始化 notificationparser
        notificationparser parser = new notificationparser(rsaautocertificateconfig);
        // 以支付通知回调为例,验签、解密并转换成 transaction
        log.info("验签参数:{}", requestparam);
        transaction transaction = parser.parse(requestparam, transaction.class);
        log.info("验签成功!-支付回调结果:{}", transaction.tostring());

        map<string, string> returnmap = new hashmap<>(2);
        returnmap.put("code", "fail");
        returnmap.put("message", "失败");
        //修改订单前,建议主动请求微信查询订单是否支付成功,防止恶意post
        wrapper wrapper = new entitywrapper<wxorderentity>();
        wrapper.eq("out_trade_no", transaction.getouttradeno());
        //wrapper.eq("transaction_id", transaction.gettransactionid());
        wxorderentity wxorderentity = wxorderdataservice.selectone(wrapper);
        if (wxorderentity != null) {
            if (wxorderentity.getpaystatus() == 1) {
                //此时已经是支付成功,不在处理订单信息
                returnmap.put("code", "success");
                returnmap.put("message", "成功");
                return jsonobject.tojsonstring(returnmap);
            }
        }
        if (transaction.tradestateenum.success != transaction.gettradestate()) {
            log.info("内部订单号【{}】,微信支付订单号【{}】支付未成功", transaction.getouttradeno(), transaction.gettransactionid());
            if (wxorderentity != null) {
                wxorderentity.setupdatetime(new date());
                wxorderentity.setpaystatus(2);
                wxorderentity.setpaynonce(nonce);
                wxorderentity.settransactionid(transaction.gettransactionid());
                //修改订单信息
                wxorderdataservice.updatebyid(wxorderentity);
            }
            return jsonobject.tojsonstring(returnmap);
        }
        if (wxorderentity != null) {
            wxorderentity.setupdatetime(new date());
            wxorderentity.setpaytime(dateutils.stringtodatetime(transaction.getsuccesstime()));
            wxorderentity.setpaydate(dateutils.stringtodatetime(transaction.getsuccesstime()));
            wxorderentity.setpaystatus(1);
            wxorderentity.setpaynonce(nonce);
            wxorderentity.settransactionid(transaction.gettransactionid());
            //修改订单信息
            wxorderdataservice.updatebyid(wxorderentity);
            //同时处理支付记录
            wrapper paywrapper = new entitywrapper<wxpaylogentity>();
            wrapper.eq("out_trade_no", transaction.getouttradeno());
            wrapper.eq("pay_status", 1);//支付
            wxpaylogentity wxpaylogentity = wxpaylogdataservice.selectone(paywrapper);
            if (wxpaylogentity == null) {
                wxpaylogentity = new wxpaylogentity();
                wxpaylogentity.setcreatetime(new date());
                wxpaylogentity.setouttradeno(wxorderentity.getouttradeno());
                wxpaylogentity.setpaystatus(1);
                wxpaylogentity.settotalfee(wxorderentity.gettotalfee());
                wxpaylogentity.settransactionid(wxorderentity.gettransactionid());
                wxpaylogentity.setwxopenid(wxorderentity.getwxopenid());
                wxpaylogdataservice.insert(wxpaylogentity);
            }
        }
  
        returnmap.put("code", "success");
        returnmap.put("message", "成功");
        return jsonobject.tojsonstring(returnmap);
    }

5、根据商户订单号查询订单(out_trade_no)

/***
     * 根据商户订单号查询订单 outtradeno
     * @param req
     * @return
     */
    @transactional
    public r queryorderbyorderno(queryorderreq req) {
        queryorderbyouttradenorequest queryrequest = new queryorderbyouttradenorequest();
        queryrequest.setmchid(wxpayconfig.getmerchantid());
        queryrequest.setouttradeno(req.getorderno());
        try {
            jsapiserviceextension service =
                    new jsapiserviceextension.builder()
                            .config(rsaautocertificateconfig)
                            .signtype("rsa") // 不填默认为rsa
                            .build();
            transaction result = service.queryorderbyouttradeno(queryrequest);
            linkedhashmap retmap = new linkedhashmap();
            //支付成功
            if (transaction.tradestateenum.success == result.gettradestate()) {
                log.info("内部订单号【{}】,微信支付订单号【{}】支付成功", result.getouttradeno(), result.gettransactionid());
                retmap.put("out_trade_no", result.getouttradeno());
                retmap.put("transaction_id", result.gettransactionid());
                retmap.put("success", true);
                retmap.put("msg", "支付成功!");
                retmap.put("success_time", dateutils.getdatetimestring(dateutils.stringtodatetime(result.getsuccesstime())));
                //主动查询
                wrapper wrapper = new entitywrapper<wxorderentity>();
                wrapper.eq("out_trade_no", req.getorderno());
                wxorderentity wxorderentity = wxorderdataservice.selectone(wrapper);
                if (wxorderentity != null) {
                    if (wxorderentity.getpaystatus() != 1) {
                        wxorderentity.setpaystatus(1);
                        wxorderentity.settransactionid(result.gettransactionid());
                        wxorderentity.setpaydate(dateutils.stringtodatetime(result.getsuccesstime()));
                        wxorderentity.setpaytime(dateutils.stringtodatetime(result.getsuccesstime()));
                        wxorderentity.setupdatetime(new date());
                        wxorderdataservice.updatebyid(wxorderentity);
                        //同时处理支付记录
                        wrapper paywrapper = new entitywrapper<wxpaylogentity>();
                        wrapper.eq("out_trade_no", req.getorderno());
                        wxpaylogentity wxpaylogentity = wxpaylogdataservice.selectone(paywrapper);
                        if (wxpaylogentity == null) {
                            wxpaylogentity = new wxpaylogentity();
                            wxpaylogentity.setcreatetime(new date());
                            wxpaylogentity.setouttradeno(wxorderentity.getouttradeno());
                            wxpaylogentity.setpaystatus(1);
                            wxpaylogentity.settotalfee(wxorderentity.gettotalfee());
                            wxpaylogentity.settransactionid(result.gettransactionid());
                            wxpaylogentity.setwxopenid(wxorderentity.getwxopenid());
                            wxpaylogdataservice.insert(wxpaylogentity);
                        }
                    }
                }
            } else {
                log.info("内部订单号【{}】,微信支付订单号【{}】支付未成功", result.getouttradeno(), result.gettransactionid());
                retmap.put("out_trade_no", result.getouttradeno());
                retmap.put("transaction_id", result.gettransactionid());
                retmap.put("success", false);
                retmap.put("msg", "支付失败!");
                retmap.put("success_time", null);
            }
            return r.ok().put("data", retmap);
        } catch (serviceexception e) {
            log.error("订单查询失败,返回码:{},返回信息:{}", e.geterrorcode(), e.geterrormessage());
            return r.error("订单查询失败!");
        }
    }

5.1  queryorderreq类

mport io.swagger.annotations.apimodelproperty;
import lombok.data;

/**
 * @author caozhen
 * @classname queryorderreq
 * @description: 支付查询
 * @date 2024年01月04日
 * @version: 1.0
 */
@data
public class queryorderreq {
    @apimodelproperty(name = "paymentno", value = "微信支付订单号,同:transaction_id")
    private string paymentno;

    @apimodelproperty(name = "orderno", value = "商户订单号,同:out_trade_no")
    private string orderno;
}

6、根据支付订单号查询订单 (transaction_id)

/***
     * 根据支付订单号查询订单 paymentno
     * @param req
     * @return
     */
    @transactional
    public r queryorderbypaymentno(queryorderreq req) {
        queryorderbyidrequest queryrequest = new queryorderbyidrequest();
        queryrequest.setmchid(wxpayconfig.getmerchantid());
        queryrequest.settransactionid(req.getpaymentno());
        try {
            jsapiserviceextension service =
                    new jsapiserviceextension.builder()
                            .config(rsaautocertificateconfig)
                            .signtype("rsa") // 不填默认为rsa
                            .build();
            transaction result = service.queryorderbyid(queryrequest);
            linkedhashmap map = new linkedhashmap();
            //支付成功
            if (transaction.tradestateenum.success == result.gettradestate()) {
                log.info("内部订单号【{}】,微信支付订单号【{}】支付成功", result.getouttradeno(), result.gettransactionid());
                map.put("out_trade_no", result.getouttradeno());
                map.put("transaction_id", result.gettransactionid());
                map.put("success", true);
                map.put("msg", "支付成功!");
                map.put("success_time", dateutils.getdatetimestring(dateutils.stringtodatetime(result.getsuccesstime())));
                //主动查询
                wrapper wrapper = new entitywrapper<wxorderentity>();
                wrapper.eq("transaction_id", req.getpaymentno());
                wxorderentity wxorderentity = wxorderdataservice.selectone(wrapper);
                if (wxorderentity != null) {
                    if (wxorderentity.getpaystatus() != 1) {
                        wxorderentity.setpaystatus(1);
                        wxorderentity.setpaydate(dateutils.stringtodatetime(result.getsuccesstime()));
                        wxorderentity.setpaytime(dateutils.stringtodatetime(result.getsuccesstime()));
                        wxorderentity.setupdatetime(new date());
                        wxorderdataservice.updatebyid(wxorderentity);
                        //同时处理支付记录
                        wrapper paywrapper = new entitywrapper<wxpaylogentity>();
                        wrapper.eq("transaction_id", req.getpaymentno());
                        wxpaylogentity wxpaylogentity = wxpaylogdataservice.selectone(paywrapper);
                        if (wxpaylogentity == null) {
                            wxpaylogentity = new wxpaylogentity();
                            wxpaylogentity.setcreatetime(new date());
                            wxpaylogentity.setouttradeno(wxorderentity.getouttradeno());
                            wxpaylogentity.setpaystatus(1);
                            wxpaylogentity.settotalfee(wxorderentity.gettotalfee());
                            wxpaylogentity.settransactionid(result.gettransactionid());
                            wxpaylogentity.setwxopenid(wxorderentity.getwxopenid());
                            wxpaylogdataservice.insert(wxpaylogentity);
                        }
                    }
                }
            } else {
                log.info("内部订单号【{}】,微信支付订单号【{}】支付未成功", result.getouttradeno(), result.gettransactionid());
                map.put("out_trade_no", result.getouttradeno());
                map.put("transaction_id", result.gettransactionid());
                map.put("success", false);
                map.put("msg", "支付失败!");
                map.put("success_time", null);
            }
            return r.ok().put("data", map);
        } catch (serviceexception e) {
            log.error("订单查询失败,返回码:{},返回信息:{}", e.geterrorcode(), e.geterrormessage());
            return r.error("订单查询失败!");
        }
    }

7、微信申请退款

/***
     * 微信申请退款
     * @param outtradeno 商户订单号
     * @param totalamount
     * @return
     */
    public r createrefund(string outtradeno, long totalamount) {
        //返回参数
        linkedhashmap map = new linkedhashmap();
        map.put("out_trade_no", outtradeno);
        map.put("success", false);
        map.put("msg", "正在申请退款中!");
        string outrefundno = "refund_" + outtradeno;
        map.put("out_refund_no", outrefundno);
        //申请退款订单,需要变更订单记录
        wrapper wrapper = new entitywrapper<wxorderentity>();
        wrapper.eq("out_trade_no", outtradeno);
        wxorderentity wxorderentity = wxorderdataservice.selectone(wrapper);
        if (wxorderentity == null) {
            return r.error("订单不存在,申请退款不存在!");
        }
        wxorderentity.setpaystatus(4);//退款中
        wxorderentity.setupdatetime(new date());
        wxorderdataservice.updatebyid(wxorderentity);
        try {
            // 构建退款service
            refundservice service = new refundservice.builder()
                    .config(rsaautocertificateconfig)
                    .build();
            createrequest request = new createrequest();
            // 调用request.setxxx(val)设置所需参数,具体参数可见request定义
            request.setouttradeno(outtradeno);
            request.setoutrefundno(outrefundno);

            amountreq amount = new amountreq();
            amount.settotal(totalamount);
            amount.setrefund(totalamount);
            amount.setcurrency("cny");

            request.setamount(amount);
            request.setnotifyurl(wxpayconfig.getrefundnotifyurl());

            //接收退款返回参数
            refund refund = service.create(request);
            log.info("退款返回信息:{}", refund);
            if (refund.getstatus().equals(status.success)) {
                map.put("success", true);
                map.put("msg", "退款成功!");
                //说明退款成功,开始接下来的业务操作
                //主动查询
                wrapper againwrapper = new entitywrapper<wxorderentity>();
                againwrapper.eq("out_trade_no", outtradeno);
                wxorderentity orderentity = wxorderdataservice.selectone(againwrapper);
                if (orderentity != null) {
                    orderentity.setpaystatus(3);//退款成功
                    orderentity.setupdatetime(new date());
                    wxorderdataservice.updatebyid(orderentity);
                    //同时处理退款记录
                    wrapper paywrapper = new entitywrapper<wxpaylogentity>();
                    paywrapper.eq("out_trade_no", outtradeno);
                    paywrapper.eq("pay_status", 2);//退款
                    wxpaylogentity wxpaylogentity = wxpaylogdataservice.selectone(paywrapper);
                    if (wxpaylogentity == null) {
                        wxpaylogentity = new wxpaylogentity();
                        wxpaylogentity.setcreatetime(new date());
                        wxpaylogentity.setouttradeno(outtradeno);
                        wxpaylogentity.setpaystatus(2);
                        wxpaylogentity.settotalfee(totalamount.intvalue());
                        wxpaylogentity.settransactionid(wxorderentity.gettransactionid());
                        wxpaylogentity.setoutrefundno(outrefundno);
                        wxpaylogentity.setwxopenid(wxorderentity.getwxopenid());
                        wxpaylogdataservice.insert(wxpaylogentity);
                    }
                }
            }
        } catch (serviceexception e) {
            log.error("退款失败!,错误信息:{}", e.getmessage());
            return r.error("退款失败!");
        } catch (exception e) {
            log.error("服务返回成功,返回体类型不合法,或者解析返回体失败,错误信息:{}", e.getmessage());
            return r.error("退款失败!");
        }
        return r.ok().put("data", map);
    }

8、退款回调通知 

待续......

四、mysql表结构

set names utf8mb4;
set foreign_key_checks = 0;

-- ----------------------------
-- table structure for t_wx_order
-- ----------------------------
drop table if exists `t_wx_order`;
create table `t_wx_order`  (
  `uuid` varchar(64) character set utf8mb4 collate utf8mb4_bin not null,
  `trade_name` varchar(255) character set utf8mb4 collate utf8mb4_bin null default null comment '商品名称',
  `description` varchar(255) character set utf8mb4 collate utf8mb4_bin null default null comment '订单描述',
  `out_trade_no` varchar(64) character set utf8mb4 collate utf8mb4_bin null default null comment '(商户)订单流水号',
  `transaction_id` varchar(64) character set utf8mb4 collate utf8mb4_bin null default null comment '微信订单号',
  `total_fee` int(10) null default null comment '订单金额(单位:分)',
  `pay_nonce` varchar(64) character set utf8mb4 collate utf8mb4_bin null default null comment '支付成功后的随机32位字符串',
  `pay_time` datetime null default null comment '支付时间',
  `pay_date` date null default null comment '支付日期',
  `pay_status` int(3) null default 0 comment '0:待支付,1:支付成功,2:支付失败,3:退款成功,4:正在退款中,5:未知',
  `wx_open_id` varchar(64) character set utf8mb4 collate utf8mb4_bin null default null comment '微信小程序openid',
  `status` int(2) null default 0 comment '0:未删除,1:已删除',
  `create_time` datetime null default null comment '创建订单时间',
  `update_time` datetime null default null comment '修改订单时间',
  primary key (`uuid`) using btree
) engine = innodb character set = utf8mb4 collate = utf8mb4_bin comment = '微信商品订单表' row_format = dynamic;

-- ----------------------------
-- table structure for t_wx_pay_log
-- ----------------------------
drop table if exists `t_wx_pay_log`;
create table `t_wx_pay_log`  (
  `uuid` varchar(64) character set utf8mb4 collate utf8mb4_bin not null,
  `wx_open_id` varchar(64) character set utf8mb4 collate utf8mb4_bin null default null comment '微信用户openid',
  `out_trade_no` varchar(64) character set utf8mb4 collate utf8mb4_bin null default null comment '(商户)订单流水号',
  `out_refund_no` varchar(64) character set utf8mb4 collate utf8mb4_bin null default null comment '(商户)退款流水号',
  `transaction_id` varchar(64) character set utf8mb4 collate utf8mb4_bin null default null comment '微信订单号',
  `total_fee` int(10) null default null comment '支付金额',
  `pay_status` int(2) null default null comment '1:支付,2:退款',
  `create_time` datetime null default null comment '创建时间',
  primary key (`uuid`) using btree
) engine = innodb character set = utf8mb4 collate = utf8mb4_bin comment = '微信用户支付记录表' row_format = dynamic;

set foreign_key_checks = 1;

五、controller类

退款回调通知,和controller就不写了,如果需要,联系我即可!

哎呀呀呀,缺少了一个类,代码如下:

import javax.servlet.servletinputstream;
import javax.servlet.http.httpservletrequest;
import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
/**
 * @author caozhen
 * @classname httpservletutils
 * @description: todo
 * @date 2024年01月04日
 * @version: 1.0
 */
public class httpservletutils {
    /**
     * 获取请求体
     *
     * @param request
     * @return
     * @throws ioexception
     */
    public static string getrequestbody(httpservletrequest request) throws ioexception {
        servletinputstream stream = null;
        bufferedreader reader = null;
        stringbuffer sb = new stringbuffer();
        try {
            stream = request.getinputstream();
            // 获取响应
            reader = new bufferedreader(new inputstreamreader(stream));
            string line;
            while ((line = reader.readline()) != null) {
                sb.append(line);
            }
        } catch (ioexception e) {
            throw new ioexception("读取返回支付接口数据流出现异常!");
        } finally {
            reader.close();
        }
        return sb.tostring();
    }
}

如果你在微信支付回调通知中出现 “签名错误”,并且你是windows服务器,请在httpservletutils 类中,将reader = new bufferedreader(new inputstreamreader(stream));   替换成:reader = new bufferedreader(new inputstreamreader(stream,"utf-8"));

替换完整代码:

import javax.servlet.servletinputstream;
import javax.servlet.http.httpservletrequest;
import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
/**
 * @author caozhen
 * @classname httpservletutils
 * @description: todo
 * @date 2024年01月04日
 * @version: 1.0
 */
public class httpservletutils {
    /**
     * 获取请求体
     *
     * @param request
     * @return
     * @throws ioexception
     */
    public static string getrequestbody(httpservletrequest request) throws ioexception {
        servletinputstream stream = null;
        bufferedreader reader = null;
        stringbuffer sb = new stringbuffer();
        try {
            stream = request.getinputstream();
            // 获取响应
            reader = new bufferedreader(new inputstreamreader(stream,"utf-8"));
            string line;
            while ((line = reader.readline()) != null) {
                sb.append(line);
            }
        } catch (ioexception e) {
            throw new ioexception("读取返回支付接口数据流出现异常!");
        } finally {
            reader.close();
        }
        return sb.tostring();
    }
}

总结 

到此这篇关于java springboot对接开发微信支付的文章就介绍到这了,更多相关springboot开发微信支付内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com