fix
Hentua
2024-01-28 6b2c727379ec8abd93ffcbfdbac3a0fd74676bb9
src/test/java/cc/mrbird/febs/ProfitTest.java
@@ -12,18 +12,26 @@
import cc.mrbird.febs.mall.entity.*;
import cc.mrbird.febs.mall.mapper.*;
import cc.mrbird.febs.mall.service.*;
import cc.mrbird.febs.mall.vo.MallGoodsListVo;
import cc.mrbird.febs.mall.vo.MallMemberCouponVo;
import cc.mrbird.febs.pay.model.*;
import cc.mrbird.febs.pay.service.IXcxPayService;
import cc.mrbird.febs.pay.service.WxFaPiaoService;
import cc.mrbird.febs.pay.util.JCEUtil;
import cc.mrbird.febs.pay.util.WechatConfigure;
import cc.mrbird.febs.rabbit.consumer.AgentConsumer;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationHandler;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import okhttp3.HttpUrl;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.httpclient.HttpClient;
@@ -40,12 +48,14 @@
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@@ -53,9 +63,12 @@
import java.math.BigDecimal;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
@@ -109,6 +122,16 @@
    private WxFaPiaoService wxFaPiaoService;
    @Autowired
    ResourceLoader resourceLoader;
    @Test
    public void redisTest() throws IOException {//配置开发选项
        String obj = redisUtils.getString("mall_goods_json");//获取JSONARRAY字符串对象
        System.out.println(obj);
        JSONArray jsonArray = JSONUtil.parseArray(obj);//转换成JSONARRAY对象
        List<MallGoodsListVo> mallGoodsListVos = JSONUtil.toList(jsonArray, MallGoodsListVo.class);//转换成对象集合
        System.out.println(mallGoodsListVos.size());
    }
    @Test
    public void rankProfit() throws IOException {//配置开发选项
//        System.out.println(new ClassPathResource("wxP12/apiclient_cert.p12").getFile().exists());
@@ -187,33 +210,39 @@
    @Test
    public void rankProfit04() throws IOException {//获取用户填写的抬头
        FPUserTitleDto fpUserTitleDto = new FPUserTitleDto();
        fpUserTitleDto.setScene("WITH_WECHATPAY");
        fpUserTitleDto.setFapiao_apply_id("");
        //初始化请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("scene","WITH_WECHATPAY");
        params.put("fapiao_apply_id","4200002059202401191880748568");
        String parseObj = JSONUtil.parseObj(fpUserTitleDto).toString();
        System.out.println(parseObj);
        String baseUrl = "https://api.mch.weixin.qq.com";
        String canonicalUrl = "/v3/new-tax-control-fapiao/user-title";
        String urlparm = baseUrl+canonicalUrl;//有参数的get请求,加密是需要把参数加载进去URL
        List<BasicNameValuePair> parameters = new ArrayList<>();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
        }
        StringBuilder dataparm = new StringBuilder();
        params.forEach((k, v) -> dataparm.append("&" + k + "=" + v));
        String string = dataparm.toString();
        if (!"".equals(string)) {
            urlparm = baseUrl+canonicalUrl + "?" + dataparm.substring(1);
        }
        PrivateKey privateKey = wxFaPiaoService.getPrivateKeyV3();
        String postStr = null;
        try {
            postStr = wxFaPiaoService.createAuthorization(
                    "POST",
                    baseUrl+canonicalUrl,
                    parseObj,
                    "GET",
                    urlparm,
                    "",
                    privateKey
            );
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String token = AppContants.FP_TOKEN_HEADER_TYPE+postStr;
        System.out.println("WECHATPAY2-SHA256-RSA2048 "+postStr);
        String s = wxFaPiaoService.sendPost(baseUrl + canonicalUrl, parseObj, "WECHATPAY2-SHA256-RSA2048 "+postStr);
        String s = wxFaPiaoService.sendGet(baseUrl+canonicalUrl, params, "WECHATPAY2-SHA256-RSA2048 "+postStr);
        System.out.println(s);
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(s);
        System.out.println(jsonObject);
    }
    @Test
@@ -234,23 +263,97 @@
            e.printStackTrace();
        }
        System.out.println("WECHATPAY2-SHA256-RSA2048"+postStr);
        String s = wxFaPiaoService.sendGet(baseUrl + canonicalUrl, new HashMap<>(), "WECHATPAY2-SHA256-RSA2048 "+postStr);
        System.out.println(s);
//        try {
//            HttpClient httpClient = new HttpClient();
//            GetMethod method = new GetMethod(baseUrl+canonicalUrl);
//            method.setRequestHeader("Accept", "application/json");
//            method.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36");
//            method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//            method.setRequestHeader("Connection", "keep-alive");
//            method.setRequestHeader("Authorization", "WECHATPAY2-SHA256-RSA2048 "+postStr);
//            httpClient.executeMethod(method);
//            System.out.println(method);
//            String responseBodyAsString = method.getResponseBodyAsString();
//            cn.hutool.json.JSONObject maps = JSONUtil.parseObj(responseBodyAsString);
//            System.out.println(maps);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
    @Test
    public void rankProfit2_01() throws IOException, ParseException, GeneralSecurityException {//获取平台证书
        JCEUtil.removeCryptographyRestrictions();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        PrivateKey privateKey = wxFaPiaoService.getPrivateKeyV3();
        String baseUrl = "https://api.mch.weixin.qq.com";
        String canonicalUrl = "/v3/certificates";
        String postStr = null;
        try {
            HttpClient httpClient = new HttpClient();
            GetMethod method = new GetMethod(baseUrl+canonicalUrl);
            method.setRequestHeader("Accept", "application/json");
            method.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36");
            method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            method.setRequestHeader("Connection", "keep-alive");
            method.setRequestHeader("Authorization", "WECHATPAY2-SHA256-RSA2048 "+postStr);
            httpClient.executeMethod(method);
            System.out.println(method);
            String responseBodyAsString = method.getResponseBodyAsString();
            postStr = wxFaPiaoService.createAuthorization(
                    "GET",
                    baseUrl+canonicalUrl,
                    "",
                    privateKey
            );
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String responseBodyAsString = wxFaPiaoService.sendGet(baseUrl + canonicalUrl, new HashMap<>(), "WECHATPAY2-SHA256-RSA2048 "+postStr);
        //完成签名并执行请求
        X509Certificate x509Certificate = null;
        try {
            cn.hutool.json.JSONObject maps = JSONUtil.parseObj(responseBodyAsString);
            System.out.println(maps);
            FPCertificateVo certificateVo = com.alibaba.fastjson.JSONObject.parseObject(responseBodyAsString, FPCertificateVo.class);
            for (FPCertificates certificates : certificateVo.getData()) {
                if (format.parse(certificates.getEffective_time()).before(new Date())
                        && format.parse(certificates.getExpire_time()).after(new Date())) {
                    FPEncryptCertificate encrypt_certificate = certificates.getEncrypt_certificate();
                    //解密
                    AesUtil aesUtil = new AesUtil("daL341aN5orDt13puXadsAf2rpuX12v3".getBytes("utf-8"));
                    String pulicKey = aesUtil.decryptToString(
                            encrypt_certificate.getAssociated_data().getBytes("utf-8"),
                            encrypt_certificate.getNonce().getBytes("utf-8"),
                            encrypt_certificate.getCiphertext());
                    //获取平台证书
                    final CertificateFactory cf = CertificateFactory.getInstance("X509");
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(pulicKey.getBytes(StandardCharsets.UTF_8));
                    x509Certificate = (X509Certificate) cf.generateCertificate(inputStream);
                    System.out.println(x509Certificate);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String timestamp = "1705548628";
        String nonce = "sJBCGwYIM8WFJCpTE3gDGifC6VOyrPFY";
        String body = "{\"id\":\"f23942b4-b128-56ef-9172-2da8204b5159\",\"create_time\":\"2024-01-18T11:30:28+08:00\",\"resource_type\":\"encrypt-resource\",\"event_type\":\"FAPIAO.USER_APPLIED\",\"summary\":\"用户已申请开票\",\"resource\":{\"original_type\":\"fapiao\",\"algorithm\":\"AEAD_AES_256_GCM\",\"ciphertext\":\"X7XjgHrepsnVpFqNgjl9EfRbJIdMUf15izFrtnvEf7So3SWlg6CFNofcQAJE+iL1XfkFk7DNNW0rILNbY1cGWGlAlKbbPhv5SFEakZVe9GZsSTd4EC5zTk9D6g+FTS6EQNxCkj4ut2WyYaSSqJjHgYaqdKzLNPSTGRVQnynafFE=\",\"associated_data\":\"fapiao\",\"nonce\":\"X7daAHdejNsm\"}}";
        Map<String, Object> requestBody = JSONUtil.parseObj(body);
        String signature = "WECHATPAY/SIGNTEST/9WwfXW/noMdzDPcOrFD51Bf5YIThXLTtLCl5hoGlSfIBdY2UpE+5eHLs0XyF7y2cQc4OlzTzDDxSMTp/p/8ZenE2hMBaQjxVrdbTtrOLA1h13/WjCNaTr1URTqQ5+IF5bLCxAW8BmZ0jEqpmI/HYR3wdK8/7W91c1zfKODYgkvJzxFzd8OWi2GtELE5tLamkOLyb0GEcsGww2DUOypO5HjNyITgsy9R00w3OH92UInCD8Z6c5BAsQNySqFK8N52y38AlIWTtKROHmJtu+kHbt+nMOU0kbB5bZcPAptsnVYpp9KMmjMrmyjiKtHZb2TGIWiN/L+bgceyN3g==";
        //构造验签名串
        String signatureStr = timestamp + "\n" + nonce + "\n" + com.alibaba.fastjson.JSONObject.toJSONString(requestBody) + "\n";
        System.out.println(signature.length());
        System.out.println(signature);
        System.out.println(signatureStr.length());
        System.out.println(signatureStr);
        // 加载SHA256withRSA签名器
        Signature signer = Signature.getInstance("SHA256withRSA");
        // 用微信平台公钥对签名器进行初始化(调上一节中的获取平台证书方法)
        signer.initVerify(x509Certificate);
        // 把我们构造的验签名串更新到签名器中
        signer.update(signatureStr.getBytes(StandardCharsets.UTF_8));
        // 把请求头中微信服务器返回的签名用Base64解码 并使用签名器进行验证
        boolean result = signer.verify(Base64Utils.decodeFromString(signature));
        System.out.println(result);
    }
@@ -864,4 +967,10 @@
        BigDecimal amount = new BigDecimal("0.15").setScale(2,BigDecimal.ROUND_DOWN);
        System.out.println(amount);
    }
    @Test
    public void aaaTest() {
//        agentConsumer.vipLevelUp(133L);
        agentConsumer.getScoreMsg(152L);
    }
}