spring boot 微信小程序支付

引入微信支付

<!--weixin 支付-->
        <dependency>
            <groupId>com.github.wechatpay-apiv3</groupId>
            <artifactId>wechatpay-java</artifactId>
            <version>0.2.5</version>
        </dependency>

参数封装类

package com.ruoyi.business.payment.dto;

import com.ruoyi.common.core.annotation.Excel;

public class GetJsapiServiceDto {
    /** 商户号 */
    private String wechatpayMchid;
    /** 商户证书序列号 */
    private String wechatpayMchserialno;
    /** 商户私钥 */
    private String wechatpayPrivatekey;
    /** apiV3Key */
    private String wechatpayApiv3key;

    /** 微信支付appid */
    private String wechatpayAppid;
    /** 微信支付AppSecret */
    private String wechatpayAppsecret;

    //物业公司ID
    private Long id;

    public String getWechatpayMchid() {
        return wechatpayMchid;
    }

    public void setWechatpayMchid(String wechatpayMchid) {
        this.wechatpayMchid = wechatpayMchid;
    }

    public String getWechatpayMchserialno() {
        return wechatpayMchserialno;
    }

    public void setWechatpayMchserialno(String wechatpayMchserialno) {
        this.wechatpayMchserialno = wechatpayMchserialno;
    }

    public String getWechatpayPrivatekey() {
        return wechatpayPrivatekey;
    }

    public void setWechatpayPrivatekey(String wechatpayPrivatekey) {
        this.wechatpayPrivatekey = wechatpayPrivatekey;
    }

    public String getWechatpayApiv3key() {
        return wechatpayApiv3key;
    }

    public void setWechatpayApiv3key(String wechatpayApiv3key) {
        this.wechatpayApiv3key = wechatpayApiv3key;
    }

    public String getWechatpayAppid() {
        return wechatpayAppid;
    }

    public void setWechatpayAppid(String wechatpayAppid) {
        this.wechatpayAppid = wechatpayAppid;
    }

    public String getWechatpayAppsecret() {
        return wechatpayAppsecret;
    }

    public void setWechatpayAppsecret(String wechatpayAppsecret) {
        this.wechatpayAppsecret = wechatpayAppsecret;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

支付类

package com.ruoyi.business.payment;

import com.google.gson.Gson;
import com.ruoyi.business.payment.dto.GetJsapiServiceDto;
import com.ruoyi.business.payment.dto.PayParamDto;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;


import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.core.util.PemUtil;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.model.TransactionAmount;
import org.springframework.stereotype.Service;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatPayment {

    public static Map<String,RSAAutoCertificateConfig> config=new HashMap<>();

    /**
     * 获取jsapi服务类
     * @return
     */
    public RSAAutoCertificateConfig getJsapiService(GetJsapiServiceDto dto){
        RSAAutoCertificateConfig rsaAutoCertificateConfig = config.get(dto.getWechatpayAppid());
        if(rsaAutoCertificateConfig == null){
            RSAAutoCertificateConfig build = new RSAAutoCertificateConfig.Builder()
                    .merchantId(dto.getWechatpayMchid())
                    .privateKey(dto.getWechatpayPrivatekey())
                    //.privateKeyFromPath(WxConfig.privateKeyPath)
                    .merchantSerialNumber(dto.getWechatpayMchserialno())
                    .apiV3Key(dto.getWechatpayApiv3key()).build();
            config.put(dto.getWechatpayAppid(),build);
            rsaAutoCertificateConfig = build;
        }
        //JsapiService service = new JsapiService.Builder().config(rsaAutoCertificateConfig).build();
        return rsaAutoCertificateConfig;
    }

    /**
     * 进行支付
     * @param payParam
     * @return
     */
    public String pay(PayParamDto payParam,GetJsapiServiceDto dto) {
        RSAAutoCertificateConfig jsapiService = getJsapiService(dto);
        JsapiService service = new JsapiService.Builder().config(jsapiService).build();

        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal((int)(Double.parseDouble(payParam.getAmount().toPlainString())*100));
        //amount.setTotal(1);
        request.setAmount(amount);
        request.setAppid(payParam.getAppid());
        request.setMchid(payParam.getMerchantId());
        request.setDescription(payParam.getDescription());
        request.setNotifyUrl("http://127.0.0.1/gateway/business/api/paymentweChatPay/payment/notify/"+dto.getId());//这个回调url必须是https开头的
        request.setOutTradeNo(payParam.getOutTradeNo());
        Payer payer = new Payer();
        payer.setOpenid(payParam.getOpenid());
        request.setPayer(payer);

        //设置回传参数
        Gson gson=new Gson();
        request.setAttach(gson.toJson(payParam.getParam()));

        PrepayResponse prepay = service.prepay(request);


        String prepayid=prepay.getPrepayId();
        return prepayid;
    }


    /** 商户订单号查询订单 */
    public Transaction queryOrderByOutTradeNo(String orderNum,GetJsapiServiceDto dto) {
        RSAAutoCertificateConfig jsapiService = getJsapiService(dto);
        JsapiService service = new JsapiService.Builder().config(jsapiService).build();
        QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
        request.setOutTradeNo(orderNum);
        // 调用request.setXxx(val)设置所需参数,具体参数可见Request定义
        // 调用接口
        return service.queryOrderByOutTradeNo(request);
    }

    /**
     * 支付成功验签
     * @param request
     * @return
     */
    public Map paySuccessCheck(HttpServletRequest request,GetJsapiServiceDto dto) {
        /*Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(dto.getWechatpayMchid())
                        .privateKey(dto.getWechatpayPrivatekey())
                        .merchantSerialNumber(dto.getWechatpayMchserialno())
                        .apiV3Key(dto.getWechatpayApiv3key())
                        .build();*/

        /*RSAAutoCertificateConfig config1 = config.get(dto.getWechatpayAppid());
        if(config1 == null){
            RSAAutoCertificateConfig build = new RSAAutoCertificateConfig.Builder()
                    .merchantId(dto.getWechatpayMchid())
                    .privateKey(dto.getWechatpayPrivatekey())
                    //.privateKeyFromPath(WxConfig.privateKeyPath)
                    .merchantSerialNumber(dto.getWechatpayMchserialno())
                    .apiV3Key(dto.getWechatpayApiv3key()).build();
            config.put(dto.getWechatpayAppid(),build);
            config1 = build;
        }*/

        //获取
        RSAAutoCertificateConfig config1 = getJsapiService(dto);

        // 从请求头中获取信息
        String timestamp                        = request.getHeader("Wechatpay-Timestamp");
        String nonce                            = request.getHeader("Wechatpay-Nonce");
        String signature                        = request.getHeader("Wechatpay-Signature");
        String singType                         = request.getHeader("Wechatpay-Signature-Type");
        String wechatPayCertificateSerialNumber = request.getHeader("Wechatpay-Serial");

        String requestBody = getRequestBody(request);

        // 构造 RequestParam
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(wechatPayCertificateSerialNumber)
                .nonce(nonce)
                .signature(signature)
                .signType(singType)
                .timestamp(timestamp)
                .body(requestBody)
                .build();

        // 初始化解析器 NotificationParser
        NotificationParser parser = new NotificationParser((NotificationConfig) config1);

        // 这个Transaction是微信包里面的
        Transaction decryptObject = parser.parse(requestParam, Transaction.class);

        TransactionAmount amount = decryptObject.getAmount();
        String outTradeNo = decryptObject.getOutTradeNo();
        String attach = decryptObject.getAttach();

        Map map=new HashMap();
        map.put("amount",amount.getTotal());
        map.put("outTradeNo",outTradeNo);
        map.put("attach",attach);
        return map;
    }
    // 获取请求头里的数据
    private String getRequestBody(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        try (
                ServletInputStream inputStream = request.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            System.out.println("读取数据流异常:"+e);
        }
        return sb.toString();
    }

    /**
     * 组装支付参数
     * @param appid
     * @param privateKey
     * @param prepayId
     * @return
     */
    public Map getPayParameter(String appid ,String privateKey,String prepayId){
        Map<String,String> map=new HashMap<>();
        map.put("appId",appid);
        map.put("timeStamp",String.valueOf(new Date().getTime()));
        map.put("nonceStr",UUID.randomUUID().toString().replace("-",""));
        map.put("package","prepay_id="+prepayId);
        map.put("signType","RSA");

        String s = map.get("appId") + "\n" + map.get("timeStamp") + "\n" + map.get("nonceStr") + "\n" + map.get("package") + "\n";
        try {
            PrivateKey privateKey1 = PemUtil.loadPrivateKeyFromString(privateKey);
            Signature sign = Signature.getInstance("SHA256withRSA");
            sign.initSign(privateKey1);
            sign.update(s.getBytes("utf-8"));
            String string = Base64.getEncoder().encodeToString(sign.sign());
            map.put("paySign",string);
            return map;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        }
        return null;
    }
}

调用支付

String pay = weChatPayment.pay(payParamDto, getJsapiServiceDto);
        Map payParameter = weChatPayment.getPayParameter(byId2.getWechatpayAppid(), byId2.getWechatpayPrivatekey(), pay);

支付回调

package com.ruoyi.business.apicontroller;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.business.domain.BPropertyCompany;
import com.ruoyi.business.payment.WeChatPayment;
import com.ruoyi.business.payment.dto.GetJsapiServiceDto;
import com.ruoyi.business.payment.event.PaymentEvent;
import com.ruoyi.business.service.IBPropertyCompanyService;
import com.ruoyi.common.security.service.TokenService;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 商城支付项微信支付的回调接口
 */
@RestController
@RequestMapping("/api/paymentweChatPay")
public class WeChatPayNotify {
    private static final Logger log = LoggerFactory.getLogger(WeChatPayNotify.class);
    @Autowired
    private com.ruoyi.business.payment.WeChatPayment weChatPayment;

    @Autowired
    private IBPropertyCompanyService bPropertyCompanyService;

    @Autowired
    private ApplicationEventPublisher publisher;


    /**
     * 微信支付/充值回调
     */
    @PostMapping("/payment/notify/{propertyCompany}")
    public ResponseEntity.BodyBuilder  renotify(HttpServletRequest request,@PathVariable("propertyCompany") String propertyCompany) {

        BPropertyCompany byId = bPropertyCompanyService.getById(propertyCompany);
        if (byId == null){
            log.error("微信支付回调 参数 :"+propertyCompany +" 未找到物业公司");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);//500 服务器异常
        }

        GetJsapiServiceDto getJsapiServiceDto = new GetJsapiServiceDto();
        BeanUtil.copyProperties(byId,getJsapiServiceDto);

        Map map = weChatPayment.paySuccessCheck(request,getJsapiServiceDto);

        Integer amount = (Integer)map.get("amount");
        String outTradeNo = (String)map.get("outTradeNo");

        String attach = (String)map.get("attach");
        //Map<String, Object> map1 = new HashMap<>();
        //将附加信息 attach 解析到 map1 中,因为现在没有传递任何参数,所以没有解析

        BigDecimal divide = new BigDecimal(amount).divide(new BigDecimal("100"));

        publisher.publishEvent(new PaymentEvent(this, outTradeNo,0,attach,divide.toString()));

        return ResponseEntity.status(HttpStatus.OK);
    }
}

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值