API v3版微信支付(一)----创建环境、发送请求

微信支付V3版本和之前使用的V2版本最大的区别就是传参由XML变成了JSON,官方文档代码比较简单,我就V3版本的的一些关键步骤做个介绍:

1.首先引入SDK

  <!--微信APIV3版本-->
        <dependency>
            <groupId>com.github.wechatpay-apiv3</groupId>
            <artifactId>wechatpay-apache-httpclient</artifactId>
            <version>0.2.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.1</version>
        </dependency>

2.在yml配置文件中配置相关微信支付参数

webserverconfig:
  #回调通知地址
  notifyaddress: https://hlht.xazdyl.com/notify/api/notify/complaintsNotify
  #API证书私钥
  privateKey: MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDfID3uxhzUBrGv
    u3j3s/MJWmep3N0lv9VWbkk9NI2B7C4usWCxaS58dbgQswdBF9e4X7PxFb7d2M0T
    rnr9roNJEJvDvWYv+zN7b8UqhHEEtwMghxrVycU4W6De2jjxSiptHtF3cZWLHML9
    vPJixhaaFMdVBGZuQ26JswVZHkjDHfrhnbSQVMJn5rqp1TAeXzwvyJNyxJokNEnf
    h7kIUz/ddEUDFdEY1qPVevysWEN6hPT2UIGszQIvafTlQJ2Y9CXW/whLHC4w6G04
    a7iJG2fRwT4hQkGfYSzeJWjL951n69Q9i6eDe9VuzjljfeCi60ERa3CewVccJWZD
    pCKsC7QFAgMBAAECggEAIgu5Z4WzQGcFFdt1SdabbwHsb27UD76Fvvp1EnHCZeCz
    60wFhQyXm0YbH/ExWi1ZLTjtLAw1Y4SBRk+JVMwcHDn8ipGL1iZuZJdZbnNnC2Eh
    iQUUgyqWfVL96QNDTQ4UCzJ4o9EhEGkDF9SM56VyLXCeOcrCFnETnM9EMaT9VUgk
    v7Gpwq2ajnOWVscmcai+ikNUEUMovyglae1aICzT+yXdB+JSaB/CR03Tyyg8kV4G
    QsJtOCMttctukwbg0KotOvd5xjTvq4tQbMbBl3JaY6CSwWvpEQBA5hnE0fAzFQag
    NLNK2G48ZOnPLfY9431XvE9Y6/wtoPBOZI+TLsKwAQKBgQD9g2Rs0t5h6a8mwKbt
    5vwaJwdsL3aSIdItDt9aaKi9oJm2Y2699CFmgL3hVzvN37Njxn7Ms50SOI4+JRxT
    6qVs8mzTsEk+XNXmufjtXiFFpH4NHrq23R5cwe1QSs/2t9hN7EqbUKnwFS+ompwv
    jstQyux9mS1IJZeLUZrBXn8OwQKBgQDhUIr1TKJGYS7agZ29sKZNX/OTsHumdxit
    Wc2KGscTCCxEizBv2uytykqLVTZ53U/wMaUPoleE1DfDE/hcvS5q7+tgfcZ/lfEK
    lm5UbgztmEwKC/wCcOvt2S5lNaj0yaHuebcGKfxe67AS1qtSNj5fB6VRWWpxV0XI
    Y4xA/grgreejyjtyjrjeyjykekekeytkeqcc4WMe8SESY6aNqIIcqpZify1uOPWc
    MxH1nuYXVXvVB2cJBJzD5MmuRHFGtsdoMXKivkZCuwIyI6NddxcN+KKZSpbIN0jr
    fvzv5xUrfoEyDtW5yAe6ks5eiL0SElx7SLxyOV7vxmCb0cQowML9VxFTQQKBgGMC
    oL2gemLRC+TLNoUH3lx8AK5yzDNffIGYx+CbWcW8Pq+0NonAu2a3UUCfJnwwy5Ly
    TeVr4melVgese+RM4dvuKBHT02l3e1+6sSr63UV/OlLj508vTg3L9T5WcTN4c2c3
    Jz1XL+aKTWpJ2SkcWxYpZvUzhLnfrvObAyP/qKe9AoGAGLEznjXMYUcIPj0dJr0r
    x5+kJX4OZjeyjeyjeyj5ejteyj5eahTEG6HuIJsOdmFx1IPW6fYAu6BvFgIaYcUJ
    bFKSfucT3WrdPOIuNZCYaN8NevZ7oMI4qfGirirCekhedtXld1G1pibH7a6b16CB
    sUoPGBBRTNRTNRNRNRQGnJoWCQmE=
  #商户号
  mchId: 165626515841
  #API证书序列号
  mchSerialNo: 40148B8C4SDFSGRDFVRBRBERWDWRF0AA0031A46
  #apiV3秘钥
  apiV3Key: DVREEVEREBERykpbgqcfsdsfggsdg

3.初始化httpClient

    private static CloseableHttpClient httpClient = null;

    /**
     * 初始化httpClient
     *
     * @return
     * @throws IOException
     */
    public static CloseableHttpClient httpClient() throws IOException {
        // 加载商户私钥(privateKey:私钥字符串)
        PrivateKey merchantPrivateKey = PemUtil
                .loadPrivateKey(new ByteArrayInputStream(CommonParameters.privateKey.getBytes("utf-8")));

        // 加载平台证书(mchId:商户号,mchSerialNo:商户证书序列号,apiV3Key:V3密钥)
        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(CommonParameters.mchId, new PrivateKeySigner(CommonParameters.mchSerialNo, merchantPrivateKey)), CommonParameters.apiV3Key.getBytes("utf-8"));

        // 初始化httpClient
        return httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(CommonParameters.mchId, CommonParameters.mchSerialNo, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier)).build();
    }

    public static void after(CloseableHttpClient httpClient) throws IOException {
        httpClient.close();
    }

4.发送GET请求

/**
     * 获取投诉详情
     *
     * @param complaint_id
     * @throws Exception
     */
    public static ComplaintDetail GetComplaintsInfo(String complaint_id) throws Exception {
        CloseableHttpClient httpClient = CommonUtils.httpClient();
        //请求URL
        HttpGet httpGet = new HttpGet("https://api.mch.weixin.qq.com/v3/merchant-service/complaints-v2/" + complaint_id);
        httpGet.setHeader("Accept", "application/json");

        //完成签名并执行请求
        CloseableHttpResponse response = httpClient.execute(httpGet);

        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) { //处理成功
                System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
                return JSONObject.parseObject(EntityUtils.toString(response.getEntity()), ComplaintDetail.class);
            } else if (statusCode == 204) { //处理成功,无返回Body
                System.out.println("success");
                return new ComplaintDetail();
            } else {
                System.out.println("failed,resp code = " + statusCode + ",return body = " + EntityUtils.toString(response.getEntity()));
                return new ComplaintDetail();
            }
        } finally {
            response.close();
            CommonUtils.after(httpClient);
        }
    }

5.发送POST请求

 /**
     * 添加投诉回调地址
     *
     * @return
     * @throws IOException
     */
    @PostMapping("/api/notify/createComplaintsNotify")
    public R createComplaintsNotify() throws IOException {
        CloseableHttpClient httpClient = CommonUtils.httpClient();
        //请求URL
        HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/merchant-service/complaint-notifications");
        // 请求body参数
        Map map = new HashMap();
        map.put("url", CommonParameters.notifyaddress);
        String reqdata = JSONObject.toJSONString(map);
        StringEntity entity = new StringEntity(reqdata);
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");
        //完成签名并执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) { //处理成功
                log.info("success,return body = " + EntityUtils.toString(response.getEntity()));
                return R.ok("获取成功", JSONObject.parse(EntityUtils.toString(response.getEntity())));
            } else if (statusCode == 204) { //处理成功,无返回Body
                log.info("success");
            } else {
                log.info("failed,resp code = " + statusCode + ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException(EntityUtils.toString(response.getEntity()));
            }
        } finally {
            response.close();
            CommonUtils.after(httpClient);
        }
        return R.ok();
    }

 

posted @ 2021-06-15 14:07  william_zhao  阅读(2437)  评论(0编辑  收藏  举报