From 4ee42556139749bf6f29d47b912da0be6c37da2a Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Thu, 15 May 2025 11:29:39 +0800
Subject: [PATCH] feat(mall): 添加商品 SKU静态属性价格字段
---
src/main/java/cc/mrbird/febs/pay/service/impl/WxFaPiaoServiceImpl.java | 542 +++++++++++++++++++++++++++++++++++++----------------
1 files changed, 378 insertions(+), 164 deletions(-)
diff --git a/src/main/java/cc/mrbird/febs/pay/service/impl/WxFaPiaoServiceImpl.java b/src/main/java/cc/mrbird/febs/pay/service/impl/WxFaPiaoServiceImpl.java
index 0182525..935ab4a 100644
--- a/src/main/java/cc/mrbird/febs/pay/service/impl/WxFaPiaoServiceImpl.java
+++ b/src/main/java/cc/mrbird/febs/pay/service/impl/WxFaPiaoServiceImpl.java
@@ -3,50 +3,54 @@
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.MallInvoice;
import cc.mrbird.febs.mall.entity.MallOrderInfo;
+import cc.mrbird.febs.mall.entity.MallOrderItem;
+import cc.mrbird.febs.mall.mapper.MallInvoiceMapper;
import cc.mrbird.febs.mall.mapper.MallOrderInfoMapper;
-import cc.mrbird.febs.pay.model.HeaderDto;
+import cc.mrbird.febs.mall.mapper.MallOrderItemMapper;
+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.service.WxFaPiaoService;
+import cc.mrbird.febs.pay.util.JCEUtil;
import cc.mrbird.febs.pay.util.RandomStringGenerator;
+import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
-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.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 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.client.protocol.HttpClientContext;
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.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.util.Base64;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.*;
import java.util.stream.Collectors;
-import java.util.stream.Stream;
@Slf4j
@Service
@@ -54,6 +58,8 @@
public class WxFaPiaoServiceImpl implements WxFaPiaoService {
private final MallOrderInfoMapper mallOrderInfoMapper;
+ private final MallOrderItemMapper mallOrderItemMapper;
+ private final MallInvoiceMapper mallInvoiceMapper;
private final XcxProperties xcxProperties = SpringContextHolder.getBean(XcxProperties.class);
@@ -147,6 +153,7 @@
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");
@@ -155,11 +162,20 @@
try {
StringEntity data = new StringEntity(params, "utf-8");
httpPatch.setEntity(data);
- HttpResponse response = httpClient.execute(httpPatch);
+ 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;
}
@@ -171,6 +187,7 @@
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");
@@ -180,7 +197,7 @@
StringEntity data = new StringEntity(params, "utf-8");
httpPost.setEntity(data);
- HttpResponse response = client.execute(httpPost);
+ response = client.execute(httpPost);
HttpEntity resEntity = response.getEntity();
result = EntityUtils.toString(resEntity);
return result;
@@ -194,190 +211,387 @@
} 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(HttpServletResponse response, HttpServletRequest request) {
- log.info("微信电子发票回调接口....");
- Map<String,Object> map = new HashMap<>();
- try {
- BufferedReader br = request.getReader();
- String str = null;
- StringBuilder sb = new StringBuilder();
- while ((str = br.readLine())!=null) {
- sb.append(str);
- }
- // 构建request,传入必要参数
- NotificationRequest requests = new NotificationRequest.Builder()
- .withSerialNumber(request.getHeader("Wechatpay-Serial"))
- .withNonce(request.getHeader("Wechatpay-Nonce"))
- .withTimestamp(request.getHeader("Wechatpay-Timestamp"))
- .withSignature(request.getHeader("Wechatpay-Signature"))
- .withBody(String.valueOf(sb))
- .build();
- //验签
- NotificationHandler handler = new NotificationHandler(getVerifier(AppContants.WX_CARD_NUM), xcxProperties.getWecharpaySecretV3().getBytes(StandardCharsets.UTF_8));
- //解析请求体
- Notification notification = handler.parse(requests);
- log.info("微信电子发票回调接口....解析请求体:"+notification.toString());
- String decryptData = notification.getDecryptData();//可能是支付业务的回调数据
- log.info("微信电子发票回调接口....decryptData:"+notification.toString());
- Notification.Resource resource = notification.getResource();//电子发票的回调加密数据
- log.info("微信电子发票回调接口....resource:"+notification.toString());
+ public String sendGet(String url, Map<String, Object> params, String token) {
+ String result = "";
+ int err = 0;
+ while (true) {
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ CloseableHttpResponse response = null;
+ try {
+ 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 urlparm = "";
+ String string = dataparm.toString();
+ if (!"".equals(string)) {
+ urlparm = dataparm.toString().substring(1);
+ }
+ HttpGet httpget = new HttpGet(url + "?" + urlparm);
- 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);
+ httpget.addHeader("Accept", "application/json");
+ httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36");
+ httpget.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
+ httpget.addHeader("Authorization", token);
+ response = httpClient.execute(httpget, HttpClientContext.create());
- 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;
+ 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 {
+ httpClient.close();
+ if (response != null) {
+ response.close();
+ }
+ } catch (IOException var22) {
+ var22.printStackTrace();
}
}
- map.put("code","RESOURCE_NOT_EXISTS");
- map.put("message", "订单不存在");
+ }
+ return result;
+ }
+
+ @Override
+ public Map<String, Object> fapiaoCallBack(HttpServletRequest request, @RequestBody Map<String, Object> requestBody){
+ 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);
+ //应对签名探测流量
+ if(signature.contains("WECHATPAY/SIGNTEST")){
+ map.put("code",500);
+ map.put("message", "失败");
return map;
- }catch (Exception e) {
+ }
+ //验签
+ boolean signCheck = false;
+ try {
+ signCheck = signCheck(timestamp, nonce, requestBody, signature);
+ } catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ } catch (SignatureException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ } catch (InvalidKeyException e) {
+ e.printStackTrace();
+ } catch (ParseException e) {
e.printStackTrace();
}
- map.put("code","FAIL");
+ log.info("验签结果:" + signCheck);
+ if (signCheck) {
+ try {
+ //解析请求体
+ JSONObject jsonObject = JSONUtil.parseObj(body);
+ log.info("微信电子发票回调接口....解析请求体:"+jsonObject);
+
+ String id = jsonObject.getStr("id");//可能是支付业务的回调数据
+ String create_time = jsonObject.getStr("create_time");//可能是支付业务的回调数据
+ String resource_type = jsonObject.getStr("resource_type");//可能是支付业务的回调数据
+ String event_type = jsonObject.getStr("event_type");//可能是支付业务的回调数据
+ String resource = jsonObject.getStr("resource");//可能是支付业务的回调数据
+ log.info("微信电子发票回调接口....id:"+ id);
+ log.info("微信电子发票回调接口....create_time:"+ create_time);
+ log.info("微信电子发票回调接口....resource_type:"+ resource_type);
+ log.info("微信电子发票回调接口....event_type:"+ event_type);
+ log.info("微信电子发票回调接口....resource:"+ resource);
+ if ("FAPIAO.USER_APPLIED".equals(event_type)//用户发票抬头填写完成类型:FAPIAO.USER_APPLIED
+ && "encrypt-resource".equals(resource_type)) {//通知的资源数据类型,确认成功通知为encryptresource。
+ JCEUtil.removeCryptographyRestrictions();
+ //解密
+ AesUtil aesUtil = new AesUtil(xcxProperties.getWecharpaySecretV3().getBytes("utf-8"));
+ JSONObject jsonObjectResource = JSONUtil.parseObj(resource);
+ String original_type = jsonObjectResource.getStr("original_type");//可能是支付业务的回调数据
+ String algorithm = jsonObjectResource.getStr("algorithm");//可能是支付业务的回调数据
+ String ciphertext = jsonObjectResource.getStr("ciphertext");//可能是支付业务的回调数据
+ String associated_data = jsonObjectResource.getStr("associated_data");//可能是支付业务的回调数据
+ String nonceStr = jsonObjectResource.getStr("nonce");//可能是支付业务的回调数据
+ String decryptToString = aesUtil.decryptToString(
+ associated_data.getBytes("utf-8"),
+ nonceStr.getBytes("utf-8"),
+ ciphertext);
+ log.info("微信电子发票回调接口....resource解密:"+decryptToString);
+
+ JSONObject parseObj = JSONUtil.parseObj(decryptToString);
+ log.info("微信电子发票回调接口....resource解密-JSONObject:"+parseObj);
+ String fapiao_apply_id = parseObj.getStr("fapiao_apply_id");
+ log.info("微信电子发票回调接口....resource解密-fapiao_apply_id:"+fapiao_apply_id);
+ MallOrderInfo mallOrderInfo = mallOrderInfoMapper.selectBypayOrderNo(fapiao_apply_id);
+ if(ObjectUtil.isEmpty(mallOrderInfo)){
+ map.put("code",404);
+ map.put("message", "订单不存在");
+ return map;
+ }
+
+ if(ObjectUtil.isNotEmpty(mallOrderInfo)){
+ //更新订单状态
+// mallOrderInfo.setIsInvoice(1);
+// mallOrderInfoMapper.updateById(mallOrderInfo);
+ //获取用户的抬头信息
+ String userInvoiceInfo = this.getUserInvoiceInfo(fapiao_apply_id);
+ JSONObject userInvoiceInfoJson = JSONUtil.parseObj(userInvoiceInfo);
+ //查看当前订单是否已经开具发票
+ Long memberId = mallOrderInfo.getMemberId();
+ String payOrderNo = mallOrderInfo.getPayOrderNo();
+ List<MallInvoice> mallInvoices = mallInvoiceMapper.selectByFapiaoApplyIdAndMemberId(fapiao_apply_id, mallOrderInfo.getMemberId());
+ if(CollUtil.isEmpty(mallInvoices)){
+ MallInvoice mallInvoice = new MallInvoice();
+ mallInvoice.setMemberId(memberId);
+ mallInvoice.setFapiaoApplyId(payOrderNo);
+ mallInvoice.setOrderNo(mallOrderInfo.getOrderNo());
+ mallInvoice.setOrderId(mallOrderInfo.getId());
+ mallInvoice.setStatus(mallOrderInfo.getStatus());
+ mallInvoice.setAmount(mallOrderInfo.getAmount());
+ List<MallOrderItem> mallOrderItemList = mallOrderItemMapper.selectListByOrderId(mallOrderInfo.getId());
+ mallInvoice.setGoodsImg(mallOrderItemList.get(0).getSkuImage());
+ mallInvoice.setState(1);
+ mallInvoice.setType(userInvoiceInfoJson.getStr("type"));
+ mallInvoice.setName(userInvoiceInfoJson.getStr("name"));
+ mallInvoice.setTaxpayerId(userInvoiceInfoJson.getStr("taxpayer_id"));
+ mallInvoice.setAddress(userInvoiceInfoJson.getStr("address"));
+ mallInvoice.setTelephone(userInvoiceInfoJson.getStr("telephone"));
+ mallInvoice.setBankName(userInvoiceInfoJson.getStr("bank_name"));
+ mallInvoice.setBankAccount(userInvoiceInfoJson.getStr("bank_account"));
+ mallInvoiceMapper.insert(mallInvoice);
+ }else{
+ MallInvoice mallInvoice = mallInvoices.get(0);
+ if(2 != mallInvoice.getState()){
+ mallInvoice.setState(1);
+ mallInvoice.setType(userInvoiceInfoJson.getStr("type"));
+ mallInvoice.setName(userInvoiceInfoJson.getStr("name"));
+ mallInvoice.setTaxpayerId(userInvoiceInfoJson.getStr("taxpayer_id"));
+ mallInvoice.setAddress(userInvoiceInfoJson.getStr("address"));
+ mallInvoice.setTelephone(userInvoiceInfoJson.getStr("telephone"));
+ mallInvoice.setBankName(userInvoiceInfoJson.getStr("bank_name"));
+ mallInvoice.setBankAccount(userInvoiceInfoJson.getStr("bank_account"));
+ mallInvoiceMapper.updateById(mallInvoice);
+ }
+ }
+ //省略查询订单
+ //此处处理业务
+ map.put("code","SUCCESS");
+ map.put("message","成功");
+ //消息推送成功
+ return map;
+ }
+ }
+ map.put("code",404);
+ map.put("message", "订单不存在");
+ return map;
+ }catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ map.put("code",500);
map.put("message", "失败");
return map;
}
-
/**
- * 功能描述: 验证签名
- * 注意:使用微信支付平台公钥验签
- * Wechatpay-Signature 微信返签名
- * Wechatpay-Serial 微信平台证书序列号
- *
- * @return java.lang.String
- * @author 影子
+ * 获取用户的抬头信息
*/
- @SneakyThrows
- public boolean verifySign(HttpServletRequest request,String body) {
- boolean verify = false;
+ @Override
+ public String getUserInvoiceInfo(String fapiaoApplyId) throws IOException {
+
+ //初始化请求参数
+ Map<String, Object> params = new HashMap<>();
+ params.put("scene","WITH_WECHATPAY");
+// params.put("fapiao_apply_id","4200002070202401175245187105");
+ params.put("fapiao_apply_id",fapiaoApplyId);
+
+ 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 = this.getPrivateKeyV3();
+ String postStr = null;
try {
- String wechatPaySignature = request.getHeader("Wechatpay-Signature");
- String wechatPayTimestamp = request.getHeader("Wechatpay-Timestamp");
- String wechatPayNonce = request.getHeader("Wechatpay-Nonce");
- String wechatPaySerial = request.getHeader("Wechatpay-Serial");
- //组装签名串
- String signStr = Stream.of(wechatPayTimestamp, wechatPayNonce, body)
- .collect(Collectors.joining("\n", "", "\n"));
- //获取平台证书
- AutoUpdateCertificatesVerifier verifier = getVerifier(wechatPaySerial);
- //获取失败 验证失败
- if (verifier != null) {
- Signature signature = Signature.getInstance("SHA256withRSA");
- signature.initVerify(verifier.getValidCertificate());
- //放入签名串
- signature.update(signStr.getBytes(StandardCharsets.UTF_8));
- verify = signature.verify(Base64.getDecoder().decode(wechatPaySignature.getBytes()));
- }
- } catch (InvalidKeyException e) {
- e.printStackTrace();
+ postStr = this.createAuthorization(
+ "GET",
+ urlparm,
+ "",
+ privateKey
+ );
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
- return verify;
+ return this.sendGet(baseUrl+canonicalUrl, params, "WECHATPAY2-SHA256-RSA2048 "+postStr);
}
/**
- * 保存微信平台证书
+ * 验证签名
+ *
+ * @param timestamp 微信平台传入的时间戳
+ * @param nonce 微信平台传入的随机字符串
+ * @param requestBody 微信平台传入的消息体
+ * @param signature 微信平台传入的签名
+ * @return
+ * @throws NoSuchAlgorithmException
+ * @throws SignatureException
+ * @throws IOException
+ * @throws InvalidKeyException
*/
- private static final ConcurrentHashMap<String, AutoUpdateCertificatesVerifier> verifierMap = new ConcurrentHashMap<>();
-
- /**
- * 功能描述:获取平台证书,自动更新
- * 注意:这个方法内置了平台证书的获取和返回值解密
- */
- public AutoUpdateCertificatesVerifier getVerifier(String mchSerialNo) {
- AutoUpdateCertificatesVerifier verifier = null;
- if (verifierMap.isEmpty() || !verifierMap.containsKey(mchSerialNo)) {
- verifierMap.clear();
- try {
- //传入证书
- PrivateKey privateKey = getPrivateKeyV3();
- //刷新
- PrivateKeySigner signer = new PrivateKeySigner(mchSerialNo, privateKey);
- WechatPay2Credentials credentials = new WechatPay2Credentials(xcxProperties.getWecharpayMchid(), signer);
- verifier = new AutoUpdateCertificatesVerifier(credentials
- , xcxProperties.getWecharpaySecretV3().getBytes("utf-8"));
- verifierMap.put(verifier.getValidCertificate().getSerialNumber()+"", verifier);
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else {
- verifier = verifierMap.get(mchSerialNo);
- }
- return verifier;
+ 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;
}
/**
- * 获取公私钥.通过证书
+ * 获取平台证书
*/
- private KeyStore store;
- private final Object lock = new Object();
- public KeyPair createPKCS12(String keyAlias, String keyPass) {
-// ClassPathResource resource = new ClassPathResource(xcxProperties.getCertLocalPath());
- ClassPathResource resource = new ClassPathResource("wxP12/apiclient_cert.p12");
-// File file = new File("src/main/resources/wxP12/apiclient_cert.p12");
- char[] pem = keyPass.toCharArray();
+ public X509Certificate getCertificates() throws IOException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, ParseException {
+ JCEUtil.removeCryptographyRestrictions();
+ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
+
+ PrivateKey privateKey = this.getPrivateKeyV3();
+ String baseUrl = "https://api.mch.weixin.qq.com";
+ String canonicalUrl = "/v3/certificates";
+ String postStr = null;
try {
- synchronized (lock) {
- if (store == null) {
- synchronized (lock) {
- store = KeyStore.getInstance("PKCS12");
- store.load(resource.getInputStream(), pem);
-// store.load(new FileInputStream(file), pem);
- }
+ postStr = this.createAuthorization(
+ "GET",
+ baseUrl+canonicalUrl,
+ "",
+ privateKey
+
+ );
+ } catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ }
+ //完成签名并执行请求
+ X509Certificate x509Certificate = null;
+ try {
+ String responseBodyAsString = this.sendGet(baseUrl + canonicalUrl, new HashMap<>(), "WECHATPAY2-SHA256-RSA2048 "+postStr);
+ 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(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);
}
}
- X509Certificate certificate = (X509Certificate) store.getCertificate(keyAlias);
- certificate.checkValidity();
- // 证书的序列号 也有用 50F37206347BCC9E6AC9860DAACE52AC035F7C24
- String serialNumber = certificate.getSerialNumber().toString(16).toUpperCase();
- // 证书的 公钥
- PublicKey publicKey = certificate.getPublicKey();
- // 证书的私钥
- PrivateKey storeKey = (PrivateKey) store.getKey(keyAlias, pem);
- return new KeyPair(publicKey, storeKey);
- } catch (Exception e) {
- throw new IllegalStateException("Cannot load keys from store: " , e);
+ return x509Certificate;
+ } catch (GeneralSecurityException | ParseException e) {
+ e.printStackTrace();
}
+ return null;
}
- public static void main(String[] args) {
- HeaderDto headerDto = new HeaderDto();
- headerDto.setCallback_url("https://api.blnka.cn/api/xcxPay/fapiaoCallBack");
- headerDto.setShow_fapiao_cell(true);
- String parseObj = JSONUtil.parseObj(headerDto).toString();
- System.out.println(parseObj);
+ public static void main(String[] args) throws UnsupportedEncodingException, GeneralSecurityException {
+ String signature = "WECHATPAY/SIGNTEST/9WwfXW/noMdzDPcOrFD51Bf5YIThXLTtLCl5hoGlSfIBdY2UpE+5eHLs0XyF7y2cQc4OlzTzDDxSMTp/p/8ZenE2hMBaQjxVrdbTtrOLA1h13/WjCNaTr1URTqQ5+IF5bLCxAW8BmZ0jEqpmI/HYR3wdK8/7W91c1zfKODYgkvJzxFzd8OWi2GtELE5tLamkOLyb0GEcsGww2DUOypO5HjNyITgsy9R00w3OH92UInCD8Z6c5BAsQNySqFK8N52y38AlIWTtKROHmJtu+kHbt+nMOU0kbB5bZcPAptsnVYpp9KMmjMrmyjiKtHZb2TGIWiN/L+bgceyN3g==";
+ if(signature.contains("WECHATPAY/SIGNTEST")){
+ System.out.println(1);
+ }
+
+// JCEUtil.removeCryptographyRestrictions();
+// String body = "{\"id\":\"5fb7f522-466f-5c99-a325-0eb4001f1ec3\",\"create_time\":\"2024-01-17T15:38:33+08:00\",\"resource_type\":\"encrypt-resource\",\"event_type\":\"FAPIAO.USER_APPLIED\",\"summary\":\"用户已申请开票\",\"resource\":{\"original_type\":\"fapiao\",\"algorithm\":\"AEAD_AES_256_GCM\",\"ciphertext\":\"bBOs5WTUV1AhwiYSIUugaw9z4EHXxC28ZVsGHOppCNP4qpxYgnR+W+l983UyETmD/Wgu8ukJhe/xYkSsF947pgDP1ElTXC8MJA3lCc8NlsXQ1csPfWTS6A0XrxBoNMgwGEsYFo/7tPW/zDrEpzRZL/GgEwEtK6X1Y4Ci9IofzeI=\",\"associated_data\":\"fapiao\",\"nonce\":\"7a5dzuYqStef\"}}";
+// JSONObject jsonObject = JSONUtil.parseObj(body);
+// log.info("微信电子发票回调接口....解析请求体:"+jsonObject);
+//
+// String id = jsonObject.getStr("id");//可能是支付业务的回调数据
+// String create_time = jsonObject.getStr("create_time");//可能是支付业务的回调数据
+// String resource_type = jsonObject.getStr("resource_type");//可能是支付业务的回调数据
+// String event_type = jsonObject.getStr("event_type");//可能是支付业务的回调数据
+// String resource = jsonObject.getStr("resource");//可能是支付业务的回调数据
+// log.info("微信电子发票回调接口....id:"+ id);
+// log.info("微信电子发票回调接口....create_time:"+ create_time);
+// log.info("微信电子发票回调接口....resource_type:"+ resource_type);
+// log.info("微信电子发票回调接口....event_type:"+ event_type);
+// log.info("微信电子发票回调接口....resource:"+ resource);
+//
+// if ("FAPIAO.USER_APPLIED".equals(event_type)//用户发票抬头填写完成类型:FAPIAO.USER_APPLIED
+// && !"encryptresource".equals(resource_type)) {//通知的资源数据类型,确认成功通知为encryptresource。
+// //解密
+// AesUtil aesUtil = new AesUtil("daL341aN5orDt13puXadsAf2rpuX12v3".getBytes("utf-8"));
+// JSONObject jsonObjectResource = JSONUtil.parseObj(resource);
+//// String original_type = jsonObjectResource.getStr("original_type");//可能是支付业务的回调数据
+//// String algorithm = jsonObjectResource.getStr("algorithm");//可能是支付业务的回调数据
+// String ciphertext = jsonObjectResource.getStr("ciphertext");//可能是支付业务的回调数据
+// String associated_data = jsonObjectResource.getStr("associated_data");//可能是支付业务的回调数据
+// String nonce = jsonObjectResource.getStr("nonce");//可能是支付业务的回调数据
+// String decryptToString = aesUtil.decryptToString(
+// associated_data.getBytes("utf-8"),
+// nonce.getBytes("utf-8"),
+// ciphertext);
+// log.info("微信电子发票回调接口....resource解密:"+decryptToString);
+//
+// JSONObject parseObj = JSONUtil.parseObj(decryptToString);
+// log.info("微信电子发票回调接口....resource解密-JSONObject:"+parseObj);
+// String fapiao_apply_id = parseObj.getStr("fapiao_apply_id");
+// log.info("微信电子发票回调接口....resource解密-fapiao_apply_id:"+fapiao_apply_id);
+//
+// }
}
}
--
Gitblit v1.9.1