新增 宁波点行平台Controller

This commit is contained in:
Lemon
2024-05-10 15:27:59 +08:00
parent 2f5cb3bd74
commit 68f4b8c651
7 changed files with 221 additions and 25 deletions

View File

@@ -0,0 +1,47 @@
package com.jsowell.web.controller.thirdparty.dianxing;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.thirdparty.platform.ThirdPartyPlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
/**
* 宁波电刑平台
*
* @author Lemon
* @Date 2024/5/10 9:21:59
*/
@Anonymous
@RestController
@RequestMapping("/dianxing")
public class DianXingPlatformController extends BaseController {
@Autowired
@Qualifier("dianXingPlatformServiceImpl")
private ThirdPartyPlatformService dianXingService;
/**
* 推送充电记录
* @param orderCode
* @return
*/
@GetMapping("/pushChargeRecord/{orderCode}")
public RestApiResponse<?> pushChargeRecordInfo(@PathVariable("orderCode") String orderCode) {
RestApiResponse<?> response = null;
try {
String result = dianXingService.notificationChargeOrderInfo(orderCode);
response = new RestApiResponse<>(result);
} catch (BusinessException e) {
logger.error("点行平台推送充电记录 error:{}, {}", e.getCode(), e.getMessage());
response = new RestApiResponse<>(e);
} catch (Exception e) {
logger.error("点行平台推送充电记录 error", e);
}
logger.info("点行平台推送充电记录 result:{}", response);
return response;
}
}

View File

@@ -20,6 +20,7 @@ public enum ThirdPlatformTypeEnum {
HUA_WEI("9", "华为平台", "MA5GTQ528"),
NEI_MENG_GU_PLATFORM("10", "内蒙古平台", ""),
QING_HAI_PLATFORM("11", "青海平台", "630000000"),
DIAN_XING_PLATFORM("12", "宁波点行停车平台", ""),
;
private String typeCode;

View File

@@ -28,12 +28,13 @@ import java.util.TreeMap;
*/
public class Sm2Util {
static{
static {
Security.addProvider(new BouncyCastleProvider());
}
/**
* 随机生成sm2的公钥私钥对
*
* @return 公钥私钥对
*/
public static KeyPair generateSm2KeyPair() {
@@ -54,9 +55,8 @@ public class Sm2Util {
}
/**
*
* @param data 加密前的json数据
* @param platformPublicKeyStr 点行平台的国密二公钥
* @param data 加密前的json数据
* @param platformPublicKeyStr 点行平台的国密二公钥
* @param thirdPartyPrivateKeyStr 第三方平台生成的国密二私钥
* @return 用于http发送请求的数据
* @throws NoSuchAlgorithmException
@@ -67,14 +67,13 @@ public class Sm2Util {
public static String generateEncryptedRequestInfo(JSONObject data, String platformPublicKeyStr, String thirdPartyPrivateKeyStr)
throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException, CryptoException {
String sign = sign(thirdPartyPrivateKeyStr, data);
data.put("sign",sign);
data.put("sign", sign);
return encrypt(platformPublicKeyStr, data.toString());
}
/**
*
* @param publicKeyStr 以BASE64表示的sm2公钥
* @param data 待加密字符串, UTF-8编码
* @param data 待加密字符串, UTF-8编码
* @return 以BASE64表示的加密结果
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
@@ -106,9 +105,8 @@ public class Sm2Util {
}
/**
*
* @param privateKeyStr 以BASE64表示的sm2私钥
* @param cipherData 以BASE64表示的加密结果
* @param cipherData 以BASE64表示的加密结果
* @return 解密后字符串, UTF-8编码
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
@@ -140,9 +138,8 @@ public class Sm2Util {
}
/**
*
* @param privateKeyStr 以BASE64表示的sm2私钥
* @param dataJson 待签名json数据
* @param dataJson 待签名json数据
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidKeySpecException
@@ -175,9 +172,8 @@ public class Sm2Util {
}
/**
*
* @param publicKeyStr 以BASE64表示的sm2公钥
* @param dataJson 含有签名的待验签json数据
* @param dataJson 含有签名的待验签json数据
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
@@ -202,22 +198,22 @@ public class Sm2Util {
return sm2Signer.verifySignature(Base64.decode(sign));
}
private static String getSignContent(JSONObject rawData){
private static String getSignContent(JSONObject rawData) {
JSONObject data = new JSONObject(new TreeMap<>());
rawData.forEach((k,v) -> data.put(k,v));
rawData.forEach((k, v) -> data.put(k, v));
StringBuffer sb = new StringBuffer();
data.forEach((k,v)->{
data.forEach((k, v) -> {
if (v != null && !"".equals(v)) {
sb.append(k + "=" + v + "&");
}
});
String stringData = sb.toString();
return stringData == null || stringData.isEmpty() ? "" : stringData.substring(0,stringData.length()-1);
return stringData == null || stringData.isEmpty() ? "" : stringData.substring(0, stringData.length() - 1);
}
private static BCECPrivateKey getPrivateKey(byte[] privateBytes) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
PKCS8EncodedKeySpec eks2 = new PKCS8EncodedKeySpec(privateBytes);
KeyFactory kf= KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
KeyFactory kf = KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
return (BCECPrivateKey) kf.generatePrivate(eks2);
}
@@ -228,9 +224,9 @@ public class Sm2Util {
}
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException, CryptoException {
// KeyPair keyPair = generateSm2KeyPair();
// System.out.println(Base64.toBase64String(keyPair.getPublic().getEncoded()));
// System.out.println(Base64.toBase64String(keyPair.getPrivate().getEncoded()));
// KeyPair keyPair = generateSm2KeyPair();
// System.out.println(Base64.toBase64String(keyPair.getPublic().getEncoded()));
// System.out.println(Base64.toBase64String(keyPair.getPrivate().getEncoded()));
String platformPublicKeyStr = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEYPOlKmr/XY+na8KxiNvRui1esFugt4tT2AVk+eRlH4KCYLabDZDordal3kcn4UNM7t6J+dyhcfLstNWXpf4lQA==";
String thirdPartyPrivateKeyStr = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgCMref1FGlPZ9RfeJw/cnU5uEvFZNhHt7OvF4sgXnBjWgCgYIKoEcz1UBgi2hRANCAARj6kqkCaeNJSxWExQFsot1OuSCFrQOblhKx0U/y8GhgSND2MOAM08yXzl308waLqLt+jcsLF2UTW6XfrZNS5pk";
JSONObject data = new JSONObject();

View File

@@ -269,6 +269,61 @@ public class HttpUtils {
}
}
/**
*
* @param url
* @param param
* @param tpToken
* @return
*/
public static String sendPostTpToken(String url, String param, String tpToken) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
// log.info("sendPost - {}", url);
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
// conn.setRequestProperty("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0MjUwMTA3NjUiLCJpYXQiOjE2ODU0MjM3ODMsInN1YiI6IjNEU0JUV0hWSUM2S1ZDS0kiLCJleHAiOjY4Njk0MjM3ODN9.nU-6QNNBp0dcz65_lT-yVAoESZFUHmOwZpoqsKVNspQ");
conn.setRequestProperty("tpToken", tpToken);
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
// log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {

File diff suppressed because one or more lines are too long

View File

@@ -16,9 +16,13 @@ import com.jsowell.thirdparty.lianlian.vo.LianLianResultVO;
import com.jsowell.thirdparty.platform.util.Cryptos;
import com.jsowell.thirdparty.platform.util.Encodes;
import com.jsowell.thirdparty.platform.util.GBSignUtils;
import org.bouncycastle.crypto.CryptoException;
import org.springframework.beans.factory.InitializingBean;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.InvalidKeySpecException;
import java.util.*;
/**
@@ -275,7 +279,7 @@ public interface ThirdPartyPlatformService extends InitializingBean {
* @param orderCode 订单编号
* @throws UnsupportedOperationException 未实现异常
*/
default String notificationChargeOrderInfo(String orderCode) {
default String notificationChargeOrderInfo(String orderCode) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException, CryptoException {
throw new UnsupportedOperationException("This method is not yet implemented");
}

View File

@@ -0,0 +1,92 @@
package com.jsowell.thirdparty.platform.ningbodianxing.service;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.enums.thirdparty.BusinessInformationExchangeEnum;
import com.jsowell.common.enums.thirdparty.ThirdPlatformTypeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.Sm2Util;
import com.jsowell.common.util.http.HttpUtils;
import com.jsowell.pile.domain.OrderBasicInfo;
import com.jsowell.pile.service.OrderBasicInfoService;
import com.jsowell.pile.vo.ThirdPartySecretInfoVO;
import com.jsowell.thirdparty.platform.ThirdPartyPlatformService;
import com.jsowell.thirdparty.platform.factory.ThirdPartyPlatformFactory;
import com.jsowell.thirdparty.service.ThirdpartySecretInfoService;
import org.bouncycastle.crypto.CryptoException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.InvalidKeySpecException;
/**
* 宁波点行平台
*
* @author Lemon
* @Date 2024/5/9 10:18:12
*/
@Service
public class DianXingPlatformServiceImpl implements ThirdPartyPlatformService {
@Autowired
private OrderBasicInfoService orderBasicInfoService;
@Autowired
private ThirdpartySecretInfoService thirdpartySecretInfoService;
Logger logger = LoggerFactory.getLogger(this.getClass());
// 平台类型
private final String thirdPlatformType = ThirdPlatformTypeEnum.DIAN_XING_PLATFORM.getTypeCode();
@Override
public void afterPropertiesSet() throws Exception {
ThirdPartyPlatformFactory.register(thirdPlatformType, this);
}
/**
* 推送订单接口
* @param orderCode 订单编号
* @return
*/
@Override
public String notificationChargeOrderInfo(String orderCode) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException, CryptoException {
// 通过订单编号查询订单信息
OrderBasicInfo orderBasicInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
if (orderBasicInfo == null) {
throw new BusinessException("", "未查询到该订单信息");
}
String plateNum = orderBasicInfo.getPlateNumber() == null ? "" : orderBasicInfo.getPlateNumber();
// 拼装订单信息 JSON 参数
JSONObject jsonObject = new JSONObject();
jsonObject.put("outTradeId", orderBasicInfo.getOrderCode()); // 充电桩平台订单号
jsonObject.put("plateNum", plateNum); // 车牌号
jsonObject.put("startTime", orderBasicInfo.getChargeStartTime()); // 充电开始时间,格式 yyyy-MM-dd HH:mm:ss
jsonObject.put("endTime", orderBasicInfo.getChargeEndTime()); // 充电结束时间,
jsonObject.put("payAmount", orderBasicInfo.getPayAmount()); // 支付金额,格式为小数点后保留 2 位
jsonObject.put("recordTime", DateUtils.getDateTime()); // 记录上报时间
// 查询出该平台的配置参数
ThirdPartySecretInfoVO thirdPartySecretInfoVO = thirdpartySecretInfoService.queryByThirdPlatformType(thirdPlatformType);
if (thirdPartySecretInfoVO == null) {
throw new BusinessException("", "无此平台配置信息");
}
// 加密参数(方法中已将 sign 放入参数中并返回)
String recordInfoStr = Sm2Util.generateEncryptedRequestInfo(jsonObject, thirdPartySecretInfoVO.getTheirPublicSecret(), thirdPartySecretInfoVO.getOurPrivateSecret());
String tpToken = "4121d1c9121a41d894ed5082d264db30";
// 发送请求
String url = thirdPartySecretInfoVO.getTheirUrlPrefix();
JSONObject postParam = new JSONObject();
postParam.put("recordInfo", recordInfoStr);
String result = HttpUtils.sendPostTpToken(url, postParam.toJSONString(), tpToken);
return result;
}
}