java后台 apiV3 对接微信app支付

发布时间 2023-03-22 21:15:43作者: 且行且思

因为项目中需要用到微信支付,这里对自己对接的流程做一个记录
一、接入前准备

1.申请应用appId与商户号,配置apiV3秘钥

2.生成商户证书

首先登录微信商家平台,进入"账户中心–>账户设置–>API安全",申请API证书(此证书为商户证书,跟下文的微信平台支付证书不一样),下载安装方式见官方文档

经过上面链接中的教程,你将会在本地得到如下三个文件:

我们将用到apiclient_key.pem文件,为商户私钥

3.生成微信支付平台证书
这一步至关重要,因为很多人接入的时候由于官方文档写的很笼统而忽略此步,再调用API的时候错误的使用的商户证书,导致签名验证微信返回的内容时不成功,而爆出如下的错误:应答的微信支付签名验证失败

关于这个错误,其实只需要按照本文的此步生成微信支付平台证书即可。

3.1下载微信支付平台证书生成工具
下载jar包

3.2.执行命令生成微信支付平台证书
执行:“java -jar CertificateDownloader-1.2.0-jar-with-dependencies.jar -f 商户私钥文件路径 -k 证书解密的密钥 -m 商户号 -o 证书保存路径 -s 商户证书序列号”就行了。

这条命令的参数搞清楚3点:

a)“商户私钥文件路径”是账号中心->API安全->API证书中设置并下载的证书(就是其中的apiclient_key.pem,下载还会获得apiclient_cert.pem,我之前把这个当做支付证书了,其实不是,apiclient_cert.pem这用不着)

b)“商户证书序列号”这个东西也是设置API证书那里知道;

c)“证书解密的密钥”在账号中心->API安全->APIv3密钥中设置的(注意api密钥和apiv3密钥是2个东西)。

执行完了是个类似wechatpay_525846BC3402533386FD3D9DF7C13AA9D3CBBBC4.pem的文件,这个就是微信支付平台证书

**
二、java后台接入微信支付

**
1.引入微信支付服务端sdk

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

 

2.创建一个微信支付工具类(我这里是用流的方式加载商户私钥与平台证书文件)

import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Data;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;

@Component
@Data
public class WxPayUtil {
    
    public static final String mchId = ""; // 商户号

    public static final String appId = ""; // appId

    public static final String apiV3Key = ""; // apiV3秘钥
    //商户私钥路径
    public static final String privateKeyUrl = "";
    
    //平台证书路径
    public static final String wechatPayCertificateUrl = "";
    //第一步申请完证书后,在API证书哪里点击管理证书就能看到
   public static final String mchSerialNo = ""; // 商户证书序列号

    private CloseableHttpClient httpClient;

    public void setup()  {
     //   PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(privateKey);
        PrivateKey merchantPrivateKey = null;
        X509Certificate wechatPayCertificate = null;

        try {
            merchantPrivateKey = PemUtil.loadPrivateKey(
                    new FileInputStream(privateKeyUrl));
            wechatPayCertificate = PemUtil.loadCertificate(
                    new FileInputStream(wechatPayCertificateUrl));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatPayCertificate);

        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
                .withWechatPay(listCertificates);
        httpClient = builder.build();
    }

    /**
     * wxMchid商户号
     * wxCertno证书编号
     * wxCertPath证书地址
     * wxPaternerKey   v3秘钥
     * url 下单地址
     * body 构造好的消息体
     */
    public JSONObject doPostWexinV3(String url, String body) {
        if (httpClient == null) {
            setup();
        }

        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;chartset=utf-8");
        httpPost.addHeader("Accept", "application/json");
        try {
            if (body == null) {
                throw new IllegalArgumentException("data参数不能为空");
            }
            StringEntity stringEntity = new StringEntity(body, "utf-8");
            httpPost.setEntity(stringEntity);
            // 直接执行execute方法,官方会自动处理签名和验签,并进行证书自动更新
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String jsonResult = EntityUtils.toString(httpEntity);
                return JSONObject.parseObject(jsonResult);
            } else {
                System.err.println("微信支付错误信息" + EntityUtils.toString(httpEntity));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    //获取签名
    public String getSign(String appId, long timestamp, String nonceStr, String pack){
        String message = buildMessage(appId, timestamp, nonceStr, pack);
        String paySign= null;
        try {
            paySign = sign(message.getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paySign;
    }

    private String buildMessage(String appId, long timestamp, String nonceStr, String pack) {
        return appId + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + pack + "\n";
    }
    private String sign(byte[] message) throws Exception{
        PrivateKey merchantPrivateKey = null;
        X509Certificate wechatPayCertificate = null;

        try {
            merchantPrivateKey = PemUtil.loadPrivateKey(
                    new FileInputStream(privateKeyUrl));
            wechatPayCertificate = PemUtil.loadCertificate(
                    new FileInputStream(wechatPayCertificateUrl));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Signature sign = Signature.getInstance("SHA256withRSA");
        //这里需要一个PrivateKey类型的参数,就是商户的私钥。
        sign.initSign(merchantPrivateKey);
        sign.update(message);
        return Base64.getEncoder().encodeToString(sign.sign());
    }
}

 

2.调用微信app支付下单接口,返回返回预交易prepay_id,通过prepay_id,appid,随机字符串,时间戳,计算得到签名,返回给客户端调起支付

public CommonResult WxPayApp(){

        com.alibaba.fastjson.JSONObject amountJson = new com.alibaba.fastjson.JSONObject();
        amountJson.put("total",Integer.valueOf(1));
        amountJson.put("currency","CNY");

        //基础信息json
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
      //  json.put("appid","wx043e87691cbad09f");
        json.put("appid", WxPayUtil.appId);
        json.put("mchid",WxPayUtil.mchId);
        json.put("description","测试");
        json.put("out_trade_no","1111223344456");
        json.put("notify_url","https://www.baidu.com");
        json.put("amount",amountJson);
        com.alibaba.fastjson.JSONObject jsonObject1 = wxPayUtil.doPostWexinV3("https://api.mch.weixin.qq.com/v3/pay/transactions/app", json.toJSONString());
        log.info("结果:"+jsonObject1.toJSONString());
        String prepay_id = jsonObject1.getString("prepay_id");

        //时间戳
        Long timestamp = System.currentTimeMillis()/1000;
        //随机串
        String nonceStr = UUID.randomUUID().toString().replace("-","");

        String sign = wxPayUtil.getSign(WxPayUtil.appId,timestamp,nonceStr,prepay_id);
        log.info("签名:"+sign);

        Map payMap = new HashMap();
        payMap.put("prepayid",prepay_id);
        payMap.put("timestamp",timestamp+"");
        payMap.put("noncestr",nonceStr);
        payMap.put("sign",sign);
        payMap.put("appid",WxPayUtil.appId);
        payMap.put("package","Sign=WXPay");
        payMap.put("extData","sign");
        payMap.put("partnerid",WxPayUtil.mchId);

        return CommonResult.success(payMap);
    }

 

3.微信回调处理,微信会向通过基础下单接口中的请求参数“notify_url”设置的接口地址推送支付结果信息


 public void wxCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {

        log.info("微信支付回调");

        //获取报文
        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");

        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new FileInputStream(WxPayUtil.privateKeyUrl));
        // 获取证书管理器实例
        CertificatesManager certificatesManager = CertificatesManager.getInstance();
        // 向证书管理器增加需要自动更新平台证书的商户信息
        certificatesManager.putMerchant(WxPayUtil.mchId, new WechatPay2Credentials(WxPayUtil.mchId,
                        new PrivateKeySigner(WxPayUtil.mchSerialNo, merchantPrivateKey)),
                WxPayUtil.apiV3Key.getBytes(StandardCharsets.UTF_8));
        // 从证书管理器中获取verifier
        Verifier verifier = certificatesManager.getVerifier(WxPayUtil.mchId);

                // 构建request,传入必要参数
        NotificationRequest notificationRequest = new NotificationRequest.Builder().withSerialNumber(wechatPaySerial)
                .withNonce(nonce)
                .withTimestamp(timestamp)
                .withSignature(signature)
                .withBody(body)
                .build();
        NotificationHandler handler = new NotificationHandler(verifier, WxPayUtil.apiV3Key.getBytes(StandardCharsets.UTF_8));
        // 验签和解析请求体
        Notification notification = handler.parse(notificationRequest);
        Assert.assertNotNull(notification);
        String result = notification.getDecryptData();
        log.info("解密报文:"+result);
        com.alibaba.fastjson.JSONObject resultJson = JSON.parseObject(result);
        String trade_state = resultJson.getString("trade_state").trim();
        String out_trade_no = resultJson.getString("out_trade_no").trim();
        String trade_type = resultJson.getString("trade_type").trim();
        log.info("微信支付交易状态码:"+trade_state);
        log.info("微信支付交易订单号:"+out_trade_no);
        log.info("微信支付交易类型:"+trade_type);

        if("SUCCESS".equals(trade_state)){
            //支付成功,你的业务逻辑
   
            }

        }
    }

 

 

4.getRequestBody方法

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) {
            log.error("读取数据流异常:{}", e);
        }

        return sb.toString();

    }

 

 

通过上面的步骤,可以完成微信支付了!! 收工。