微信支付API v3接口使用应用篇

前言

版本

jdk:1.8
wechatpay-apache-httpclient:0.2.2

应用

基础配置

1.申请商户API证书

2.设置接口密钥

3.下载平台证书

下载平台证书至本地,执行命令

至此基础配置参数已准备就绪

接口实测

在请求接口之前先了解下接口中一些参数概念,首次接触最容易搞混的就是商户API证书和平台证书,如下图

微信支付API官方客户端

talk is cheap, show me the code

1.客户端

以post请求方式说明,get请求类似

private static String basePostRequest(String requestUrl,String requestJson) {
          
   
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        try {
          
   
            PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));
            X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(certificate.getBytes("utf-8")));
            ArrayList<X509Certificate> listCertificates = new ArrayList<>();
            listCertificates.add(wechatpayCertificate);

            httpClient = WechatPayHttpClientBuilder.create()
                    .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
                    .withWechatpay(listCertificates)
                    .build();

            HttpPost httpPost = new HttpPost(requestUrl);

            // NOTE: 建议指定charset=utf-8。低于4.4.6版本的HttpCore,不能正确的设置字符集,可能导致签名错误
            StringEntity reqEntity = new StringEntity(requestJson, ContentType.create("application/json", "utf-8"));
            httpPost.setEntity(reqEntity);
            httpPost.addHeader("Accept", "application/json");
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            return EntityUtils.toString(entity);
        } catch (Exception e) {
          
   
            e.printStackTrace();
        } finally {
          
   
            // 关闭流
        }
        return null;
    }

方法中涉及参数说明

参数名 说明 privateKey 商户私钥(商户API证书apiclient_key.pem文件内容) certificate 平台证书(通过CertificateDownloader下载的证书文件内容) mchSerialNo 商户API证书序列号
PemUtil.java类为com.wechat.pay.contrib.apache.httpclient.util.PemUtil

2.支付调起参数签名

以为例,简单说明参数签名方式,先看下文档中签名是怎么说的,如下图

方法中涉及参数说明

参数名 说明 appId 小程序appid keyFilePath 商户API证书apiclient_key.pem路径

3.回调通知

回调通知涉及验签及解密

回调数据获取

String body = request.getReader().lines().collect(Collectors.joining());

验签

方法中涉及参数说明

参数名 说明

解密

方法中涉及参数说明

参数名 说明 apiv3 商户API v3密钥 jsonStr 对resource对象进行解密后,得到的资源对象数据

参考资料

经验分享 程序员 微信小程序 职场和发展