KKSU
2024-01-17 82581bd9f30b38cd5b402bfd15486fe7d37e3178
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package cc.mrbird.febs.pay.service.impl;
 
import cc.mrbird.febs.common.properties.XcxProperties;
import cc.mrbird.febs.common.utils.AppContants;
import cc.mrbird.febs.common.utils.SpringContextHolder;
import cc.mrbird.febs.mall.entity.MallOrderInfo;
import cc.mrbird.febs.mall.mapper.MallOrderInfoMapper;
import cc.mrbird.febs.pay.model.FPCertificateVo;
import cc.mrbird.febs.pay.model.FPCertificates;
import cc.mrbird.febs.pay.model.FPEncryptCertificate;
import cc.mrbird.febs.pay.model.HeaderDto;
import cc.mrbird.febs.pay.service.WxFaPiaoService;
import cc.mrbird.febs.pay.util.RandomStringGenerator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.internal.SignUtils;
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.auth.WechatPay2Validator;
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.AesUtil;
import com.wechat.pay.java.core.notification.Resource;
import io.undertow.util.Certificates;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestBody;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 
@Slf4j
@Service
@RequiredArgsConstructor
public class WxFaPiaoServiceImpl implements WxFaPiaoService {
 
    private final MallOrderInfoMapper mallOrderInfoMapper;
 
    private final XcxProperties xcxProperties = SpringContextHolder.getBean(XcxProperties.class);
 
    @Override
    public String createAuthorization(String method, String canonicalUrl, String body, PrivateKey keyPair) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String nonceStr = RandomStringGenerator.getRandomStringByLength(32);//随机字符串
        long timestamp = System.currentTimeMillis() / 1000;//时间戳
        HttpUrl httpurl = HttpUrl.parse(canonicalUrl);
        String message = buildMessage(method, httpurl, timestamp, nonceStr, body);
        log.info("签名串:\n"+message);
        log.info("签名串长度:\n"+getWordCount(message));
        String signature = sign2(message.getBytes("utf-8"), keyPair);
 
        log.info("签名串sign:\n"+signature);
        log.info("签名串长度sign:\n"+getWordCount(signature));
//        String yourCertificateSerialNo = "221D49AEC4EA538A63941D1936709C8559EB05C5";
        return "mchid=\"" + xcxProperties.getWecharpayMchid() + "\","
                + "nonce_str=\"" + nonceStr + "\","
                + "timestamp=\"" + timestamp + "\","
                + "serial_no=\"" + AppContants.WX_CARD_NUM + "\","
                + "signature=\"" + signature + "\"";
    }
 
    public   int  getWordCount(String s)
    {
        int  length  =   0 ;
        for ( int  i  =   0 ; i  <  s.length(); i ++ )
        {
            int  ascii  =  Character.codePointAt(s, i);
            if (ascii  >=   0   &&  ascii  <= 255 )
                length ++ ;
            else
                length  +=   2 ;
 
        }
        return  length;
 
    }
 
    public String sign2(byte[] message,PrivateKey keyPair) throws NoSuchAlgorithmException {
        Signature sign = Signature.getInstance("SHA256withRSA");
        String s = null;
        try {
            sign.initSign(keyPair);
            sign.update(message);
            s = Base64.getEncoder().encodeToString(sign.sign());
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        }
        return s;
    }
 
    public String buildMessage(String method, HttpUrl url, long timestamp, String nonceStr, String body) {
        String canonicalUrl = url.encodedPath();
        if (url.encodedQuery() != null) {
            canonicalUrl += "?" + url.encodedQuery();
        }
        return method + "\n"
                + canonicalUrl + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + body + "\n";
    }
 
    @Override
    public PrivateKey getPrivateKeyV3() throws IOException {
        InputStream inputStream = new ClassPathResource("wxP12/apiclient_key.pem")
                .getInputStream();
 
        String content = new BufferedReader(new InputStreamReader(inputStream))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        try {
            String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "")
                    .replaceAll("\\s+", "");
 
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(
                    new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持RSA", e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("无效的密钥格式");
        }
    }
 
    @Override
    public String sendPatch(String url, String params, String token) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPatch httpPatch = new HttpPatch(url);
        CloseableHttpResponse response = null;
        httpPatch.setHeader("Content-type", "application/json");
        httpPatch.setHeader("Charset", "utf-8");
        httpPatch.setHeader("Accept", "application/json");
        httpPatch.setHeader("Accept-Charset", "utf-8");
        httpPatch.setHeader("Authorization", token);
        try {
            StringEntity data = new StringEntity(params, "utf-8");
            httpPatch.setEntity(data);
            response = httpClient.execute(httpPatch);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            result = "{\"status\":\"1\",\"error\":\"" + e.getMessage() + "\"}";
        }finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException var22) {
                var22.printStackTrace();
            }
        }
        return result;
    }
 
    @Override
    public String sendPost(String url, String params, String token) {
        String result = "";
        int err = 0;
        while (true) {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            CloseableHttpResponse response = null;
            try {
                httpPost.addHeader("Content-type", "application/json");
                httpPost.addHeader("Charset", "utf-8");
                httpPost.addHeader("Accept", "application/json");
                httpPost.addHeader("Accept-Charset", "utf-8");
                httpPost.addHeader("Authorization", token);
 
                StringEntity data = new StringEntity(params, "utf-8");
                httpPost.setEntity(data);
                response = client.execute(httpPost);
                HttpEntity resEntity = response.getEntity();
                result = EntityUtils.toString(resEntity);
                return result;
            } catch (IOException e) {
                result = "{\"status\":\"1\",\"errors\":\"" + e.getMessage() + "\"}";
                if (err++ > 2) {
                    break;
                }
                try {
                    Thread.sleep((err + 2) * 1000);
                } catch (InterruptedException e1) {
                    result = "{\"status\":\"1\",\"errors\":\"" + e1.getMessage() + "\"}";
                }
            }finally {
                try {
                    client.close();
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException var22) {
                    var22.printStackTrace();
                }
            }
        }
        return result;
    }
 
    @Override
    public Map<String, Object> fapiaoCallBack(HttpServletRequest request, @RequestBody Map<String, Object> requestBody) throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, ParseException {
        Map<String,Object> map = new HashMap<>();
        String signature = request.getHeader("Wechatpay-Signature");
        String timestamp = request.getHeader("Wechatpay-Timestamp");
        String nonce = request.getHeader("Wechatpay-Nonce");
        //平台证书序列号不是API证书序列号
        String serial = request.getHeader("Wechatpay-Serial");
        String body = com.alibaba.fastjson.JSONObject.toJSONString(requestBody);
        log.info("头信息---签名:" + signature);
        log.info("头信息---时间戳:" + timestamp);
        log.info("头信息---随机字符:" + nonce);
        log.info("头信息---平台证书序列号:" + serial);
        log.info("获取到的body信息:" + body);
        //验签
        boolean signCheck = signCheck(timestamp, nonce, requestBody, signature);
        log.info("验签结果:" + signCheck);
        if (signCheck) {
            try {
                //解析请求体
//            Resource resource = com.alibaba.fastjson.JSONObject.parseObject(com.alibaba.fastjson.JSONObject.toJSONString(requestBody.get("resource")), Resource.class);
                Notification notification = com.alibaba.fastjson.JSONObject.parseObject(String.valueOf(body),Notification.class);
                log.info("微信电子发票回调接口....解析请求体:"+notification.toString());
                String decryptData = notification.getDecryptData();//可能是支付业务的回调数据
                log.info("微信电子发票回调接口....decryptData:"+notification.toString());
                Notification.Resource resource = notification.getResource();//电子发票的回调加密数据
                log.info("微信电子发票回调接口....resource:"+notification.toString());
 
                if ("FAPIAO.USER_APPLIED".equals(notification.getEventType())//用户发票抬头填写完成类型:FAPIAO.USER_APPLIED
                        && !"encryptresource".equals(notification.getResourceType())) {//通知的资源数据类型,确认成功通知为encryptresource。
                    //解密
                    AesUtil aesUtil = new AesUtil(xcxProperties.getWecharpaySecretV3().getBytes("utf-8"));
                    String decryptToString = aesUtil.decryptToString(
                            resource.getAssociatedData().getBytes("utf-8"),
                            resource.getNonce().getBytes("utf-8"),
                            resource.getCiphertext());
                    log.info("微信电子发票回调接口....resource解密:"+decryptToString);
 
                    JSONObject parseObj = JSONUtil.parseObj(decryptToString);
 
                    log.info("微信电子发票回调接口....resource解密-JSONObject:"+parseObj);
 
                    String mchid = String.valueOf(parseObj.get("mchid"));
                    String fapiao_apply_id = String.valueOf(parseObj.get("fapiao_apply_id"));
                    String apply_time = String.valueOf(parseObj.get("apply_time"));
                    MallOrderInfo mallOrderInfo = mallOrderInfoMapper.selectByOrderNo(fapiao_apply_id);
                    if(ObjectUtil.isNotEmpty(mallOrderInfo)){
                        //省略查询订单
                        //此处处理业务
                        map.put("code","SUCCESS");
                        map.put("message","成功");
                        //消息推送成功
                        return map;
                    }
                }
                map.put("code","RESOURCE_NOT_EXISTS");
                map.put("message", "订单不存在");
                return map;
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        map.put("code","FAIL");
        map.put("message", "失败");
        return map;
    }
 
    /**
     * 验证签名
     *
     * @param timestamp   微信平台传入的时间戳
     * @param nonce       微信平台传入的随机字符串
     * @param requestBody 微信平台传入的消息体
     * @param signature   微信平台传入的签名
     * @return
     * @throws NoSuchAlgorithmException
     * @throws SignatureException
     * @throws IOException
     * @throws InvalidKeyException
     */
    public boolean signCheck(String timestamp, String nonce, Map<String, Object> requestBody, String signature) throws NoSuchAlgorithmException, SignatureException, IOException, InvalidKeyException, ParseException {
        //构造验签名串
        String signatureStr = timestamp + "\n" + nonce + "\n" + com.alibaba.fastjson.JSONObject.toJSONString(requestBody) + "\n";
        // 加载SHA256withRSA签名器
        Signature signer = Signature.getInstance("SHA256withRSA");
        // 用微信平台公钥对签名器进行初始化(调上一节中的获取平台证书方法)
        signer.initVerify(getCertificates());
        // 把我们构造的验签名串更新到签名器中
        signer.update(signatureStr.getBytes(StandardCharsets.UTF_8));
        // 把请求头中微信服务器返回的签名用Base64解码 并使用签名器进行验证
        boolean result = signer.verify(Base64Utils.decodeFromString(signature));
        return result;
    }
 
 
    /**
     * 获取平台证书
     */
    public X509Certificate getCertificates() throws IOException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        CloseableHttpClient httpClient = HttpClients.createDefault();
 
        PrivateKey privateKey = this.getPrivateKeyV3();
        String baseUrl = "https://api.mch.weixin.qq.com";
        String canonicalUrl = "/v3/certificates";
        String postStr = null;
        try {
            postStr = this.createAuthorization(
                    "GET",
                    baseUrl+canonicalUrl,
                    "",
                    privateKey
 
            );
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //请求URL
        HttpGet httpGet = new HttpGet(baseUrl+canonicalUrl);
        httpGet.setHeader("Accept", "application/json");
        //生成签名
        httpGet.setHeader("Authorization ", "WECHATPAY2-SHA256-RSA2048"+postStr);
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36");
        //完成签名并执行请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        X509Certificate x509Certificate = null;
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) { //处理成功
//                System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
                FPCertificateVo certificateVo = com.alibaba.fastjson.JSONObject.parseObject(EntityUtils.toString(response.getEntity()), 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(xcxProperties.getWecharpaySecretV3().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);
                    }
                }
                return x509Certificate;
            } else if (statusCode == 204) { //处理成功,无返回Body
                System.out.println("success");
                return x509Certificate;
            } else {
                System.out.println("failed,resp code = " + statusCode + ",return body = " + EntityUtils.toString(response.getEntity()));
                return x509Certificate;
            }
        } catch (GeneralSecurityException | ParseException e) {
            e.printStackTrace();
            return null;
        } finally {
            response.close();
            httpClient.close();
        }
    }
 
    public static void main(String[] args) {
        byte[] bytes = new byte[0];
        try {
            bytes = "DVREEVEREBERykpbgqcfsdsfggsdg".getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(bytes.length);
    }
 
}