v3微信支付

仅做个人记录和参考

引入官方jar包

       <dependency>
            <groupId>com.github.wechatpay-apiv3</groupId>
            <artifactId>wechatpay-apache-httpclient</artifactId>
            <version>0.4.8</version>
        </dependency>

jsapi支付正常

退款未测试

import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import org.springframework.stereotype.Component;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;

import static org.apache.http.HttpHeaders.ACCEPT;
import static org.apache.http.HttpHeaders.CONTENT_TYPE;
import static org.apache.http.entity.ContentType.APPLICATION_JSON;

/**
 * V3新版支付
 */
@Component
public class WeChatPayUtil {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    private String notifyUrl = 支付回调地址;


    private String refundNotifyUrl=退款回调地址;


    private String mchId = 商户号;

    private String miniProgramAppid = appid;


    private String apiclientKey = 公钥证书地址apiclient_key.pem;


    private String wechatPaySerial = 证书序列号;

    private String apiV3Key=v3秘钥用于获取支付证书,详情参考官方文档;

    /**
     * 微信v3 post请求
     *
     * @param url
     * @param body
     * @return
     * @throws Exception
     */
    public String v3Post(String url, String body) throws Exception {
        logger.info("微信v3 post请求参数:" + body);
        CloseableHttpClient httpClient = getClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(ACCEPT, APPLICATION_JSON.toString());
        httpPost.addHeader(CONTENT_TYPE, APPLICATION_JSON.toString());
        httpPost.addHeader("Wechatpay-Serial", wechatPaySerial);
        httpPost.setEntity(new StringEntity(body, "UTF-8"));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            String bodyAsString = EntityUtils.toString(response.getEntity());
            logger.info("微信v3 post请求返回信息:" + bodyAsString);
            return bodyAsString;
        } finally {
            httpClient.close();
            response.close();
        }
    }

    /**
     * 微信v3 get请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String v3Get(String url) throws Exception {
        logger.info("微信v3 get请求URL:" + url);
        CloseableHttpClient httpClient = getClient();
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader(ACCEPT, APPLICATION_JSON.toString());
        httpGet.addHeader(CONTENT_TYPE, APPLICATION_JSON.toString());
        httpGet.addHeader("Wechatpay-Serial", wechatPaySerial);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        try {
            String bodyAsString = EntityUtils.toString(response.getEntity());
            logger.info("微信v3 get请求返回信息:" + bodyAsString);
            return bodyAsString;
        } finally {
            httpClient.close();
            response.close();
        }
    }

    /**
     * 微信通讯client
     *
     * @return CloseableHttpClient
     */
    public CloseableHttpClient getClient() throws NotFoundException, GeneralSecurityException, IOException, HttpCodeException {
        /**商户证书私钥文件*/
        File apiclientKeyFile = new File(apiclientKey);
        InputStream apiclientKeyInputStream = FileUtil.getInputStream(apiclientKeyFile);


        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(apiclientKeyInputStream);


        /**微信支付平台证书文件*/
        // 获取证书管理器实例
        CertificatesManager certificatesManager = CertificatesManager.getInstance();
// 向证书管理器增加需要自动更新平台证书的商户信息
        certificatesManager.putMerchant(mchId, new WechatPay2Credentials(mchId,
                new PrivateKeySigner(wechatPaySerial, merchantPrivateKey)), apiV3Key.getBytes(StandardCharsets.UTF_8));
// ... 若有多个商户号,可继续调用putMerchant添加商户信息

// 从证书管理器中获取verifier
        Verifier verifier = certificatesManager.getVerifier(mchId);

        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, wechatPaySerial, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier));
        CloseableHttpClient httpClient = builder.build();
        return httpClient;
    }



    /**
     * 转换为分数,money小数长度不允许超过2位
     *
     * @param money
     * @return
     */
    public int conversionFraction(BigDecimal money) {
        int fractionMonery = 0;
        if (money != null) {
            fractionMonery = money.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).intValue();
        }
        return fractionMonery;
    }

    /**
     * 获取时间戳
     *
     * @return
     */
    private static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    /**
     * 生成签名
     *
     * @param message
     * @return
     * @throws Exception
     */
    public String sign(byte[] message) throws Exception {
        Signature sign = Signature.getInstance("SHA256withRSA");
        // 商户证书私钥
        sign.initSign(getPrivateKey());
        sign.update(message);
        return Base64.getEncoder().encodeToString(sign.sign());
    }

    /**
     * 获取商户证书私钥
     *
     * @return 私钥对象
     */
    public PrivateKey getPrivateKey() throws IOException {
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
                new FileInputStream(apiclientKey));
        return merchantPrivateKey;
    }

    /**
     * 构造签名串
     *
     * @param signMessage 待签名的参数
     * @return 构造后带待签名串
     */
    static String buildSignMessage(ArrayList<String> signMessage) {
        if (signMessage == null || signMessage.size() <= 0) {
            return null;
        }
        StringBuilder sbf = new StringBuilder();
        for (String str : signMessage) {
            sbf.append(str).append("\n");
        }
        return sbf.toString();
    }

    /**
     * JSAPI下单
     *
     * @param appid       对应openid的应用ID
     * @param description 商品描述
     * @param orderNum    商户订单号
     * @param total       总金额
     * @param openid      个人用户openId
     * @throws Exception
     */
    public String transactionsJsapi(String appid, String description, String orderNum, BigDecimal total, String openid) throws Exception {
        JSONObject transactionsJsapiJSON = new JSONObject();
        transactionsJsapiJSON.put("appid", appid);
        transactionsJsapiJSON.put("mchid", mchId);
        transactionsJsapiJSON.put("description", description);
        transactionsJsapiJSON.put("out_trade_no", orderNum);
        transactionsJsapiJSON.put("notify_url", notifyUrl);
        JSONObject amount = new JSONObject();
        amount.put("total", conversionFraction(total));
        amount.put("currency", "CNY");
        transactionsJsapiJSON.put("amount", amount);
        JSONObject payer = new JSONObject();
        payer.put("openid", openid);
        transactionsJsapiJSON.put("payer", payer);
        String body = transactionsJsapiJSON.toJSONString();
        return v3Post("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi", body);
    }

    /**
     * 小程序支付
     * @param orderNum 商户订单号
     * @param total 总金额
     * @param openid 个人用户openId
     * @throws Exception
     */
    public JSONObject payMini(String orderNum,BigDecimal total,String openid) throws Exception {
        String transactionsJsapiBody = transactionsJsapi(miniProgramAppid,"么丢",orderNum,total,openid);
        JSONObject transactionsJsapiBodyJSON = JSON.parseObject(transactionsJsapiBody);
        String prepayId = transactionsJsapiBodyJSON.getString("prepay_id");
        if(StringUtils.isNotBlank(prepayId)){
            String timeStamp = getTimeStamp();
            String nonceStr = RandomStringUtils.randomNumeric(32);
            ArrayList<String> list = new ArrayList<>();
            list.add(miniProgramAppid);
            list.add(timeStamp);
            list.add(nonceStr);
            list.add("prepay_id=" + prepayId);
            //二次签名,调起支付需要重新签名,注意这个是buildSignMessage()
            String packageSign = sign(buildSignMessage(list).getBytes());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("timeStamp", timeStamp);
            jsonObject.put("nonceStr", nonceStr);
            jsonObject.put("package", "prepay_id=" + prepayId);
            jsonObject.put("signType", "RSA");
            jsonObject.put("paySign", packageSign);
            return jsonObject;
        }else{
            return transactionsJsapiBodyJSON;
        }
    }

    /**
     * 申请退款
     * @param transactionId 微信支付订单号
     * @param outRefundNo 商户退款单号
     * @param refund 退款金额
     * @param total 原订单金额
     * @return
     * @throws Exception
     */
    public String domesticRefunds(String transactionId,String outRefundNo,BigDecimal refund,BigDecimal total) throws Exception {
        JSONObject domesticRefundsJSON = new JSONObject();
        domesticRefundsJSON.put("transaction_id", transactionId);
        domesticRefundsJSON.put("out_refund_no", outRefundNo);
        JSONObject amount = new JSONObject();
        amount.put("refund",conversionFraction(refund));
        amount.put("total",conversionFraction(total));
        amount.put("currency","CNY");
        domesticRefundsJSON.put("amount",amount);
        domesticRefundsJSON.put("notify_url", refundNotifyUrl);
        String body = domesticRefundsJSON.toJSONString();
        String domesticRefundsBody = v3Post("https://api.mch.weixin.qq.com/v3/refund/domestic/refunds",body);
        JSONObject domesticRefundsBodyJSON = JSON.parseObject(domesticRefundsBody);
        if(StringUtils.isNotBlank(domesticRefundsBodyJSON.getString("status")) && (domesticRefundsBodyJSON.getString("status").equals("SUCCESS") || domesticRefundsBodyJSON.getString("status").equals("PROCESSING"))){
            return "200";
        }else{
            return "code="+domesticRefundsBodyJSON.getString("code")+",message="+domesticRefundsBodyJSON.getString("message");
        }
    }




}

回调

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.notification.Notification;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationHandler;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationRequest;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;


/**
 * V3新版微信支付回调
 */
@RestController
public class WeChatPayController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    private String mchId = "商户号";



    private String apiclientKey = "公钥证书地址apiclient_key.pem";


    private String wechatPaySerial = "证书序列号";

    private String apiV3Key="v3秘钥用于获取支付证书,详情参考官方文档";


    /**
     * v3处理微信支付异步回调
     * @param request
     * @param response
     */
    @RequestMapping("/clientWeChatNotify")
    public void clientWeChatNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try{
            //获取微信回调结果
            JSONObject dataJSON = getCallback(request);
            logger.info("v3处理微信支付异步回调=============================================================="+dataJSON);
            String out_trade_no = dataJSON.getString("out_trade_no");//商户平台订单号
            String transaction_id = dataJSON.getString("transaction_id");//微信支付交易号
            //处理业务逻辑

            //返回给微信
            response.setStatus(200);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("v3处理微信支付异步回调:错误-"+e.getMessage());
        }
    }

    /**
     * v3处理微信退款异步回调
     * @param request
     * @param response
     */
    @RequestMapping("/refundWeChatNotify")
    public void refundWeChatNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try{
            //获取微信回调结果
            JSONObject dataJSON = getCallback(request);
            logger.info("v3处理微信退款异步回调=============================================================="+dataJSON);
            String outRefundNo = dataJSON.getString("out_refund_no");//商户退款单号
            String refundStatus = dataJSON.getString("refund_status");//退款状态,枚举值:SUCCESS:退款成功、CLOSED:退款关闭、ABNORMAL:退款异常,退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败,可前往【商户平台—>交易中心】,手动处理此笔退款
            //处理业务逻辑

            //返回给微信
            response.setStatus(200);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("v3处理微信退款异步回调:错误-"+e.getMessage());
        }
    }



    /**
     * 获取微信回调结果
     * @param request
     * @return
     * @throws Exception
     */
    public JSONObject getCallback(HttpServletRequest request) throws Exception {
        //获取报文
        String body = getRequestBody(request);
        //随机串
        String nonce = request.getHeader("Wechatpay-Nonce");
        //微信传递过来的签名
        String signature = request.getHeader("Wechatpay-Signature");
        //证书序列号(微信平台)
        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
        //时间戳
        String timestamp = request.getHeader("Wechatpay-Timestamp");
        // 验签
        NotificationRequest notificationRequest = new NotificationRequest.Builder()
                .withSerialNumber(wechatPaySerial)
                .withNonce(nonce)
                .withTimestamp(timestamp)
                .withSignature(signature)
                .withBody(body)
                .build();
        NotificationHandler handler = new NotificationHandler(verifier(), apiV3Key.getBytes(StandardCharsets.UTF_8));
        // 验签和解析请求体
        Notification notification = handler.parse(notificationRequest);
        return JSON.parseObject(notification.getDecryptData());
    }


    /**
     * 获取报文
     * @param request
     * @return
     * @throws Exception
     */
    private String getRequestBody(HttpServletRequest request) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        ServletInputStream inputStream = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuffer.append(line);
        }
        return stringBuffer.toString();
    }


    /**
     * 获得验签器
     * @return
     * @throws Exception
     */
    public Verifier verifier() throws Exception {
        //获取证书管理器实例
        CertificatesManager certificatesManager = CertificatesManager.getInstance();
        certificatesManager.putMerchant(mchId, new WechatPay2Credentials(mchId,new PrivateKeySigner(wechatPaySerial, getPrivateKey())), apiV3Key.getBytes(StandardCharsets.UTF_8));
        // 从证书管理器中获取verifier
        Verifier verifier = certificatesManager.getVerifier(mchId);
        return verifier;
    }


    /**
     * 获取商户证书私钥
     *
     * @return 私钥对象
     */
    public PrivateKey getPrivateKey() throws IOException {
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
                new FileInputStream(apiclientKey));
        return merchantPrivateKey;
    }



}

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值