Merge remote-tracking branch 'origin/main' into main

This commit is contained in:
fang 2024-11-20 15:22:07 +08:00
commit febb8f8fa0
3 changed files with 329 additions and 199 deletions

View File

@ -0,0 +1,325 @@
package shkd.sys.sys.mservice;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.*;
/**
* @Description
* @Author Tao
* @Date 2024/11/11
*/
public class ApiService {
private static final Log logger = LogFactory.getLog(ApiService.class);
public static String getBIPToken() {
String access_token = null;
long currentTimeMillis = System.currentTimeMillis();
try {
// 禁用 SSL 证书验证
disableSSLCertificateChecking();
// RestTemplate restTemplate = new RestTemplate();
String appKey = "22564a240d3140d0b15582aca71a748c";
String timestamp = String.valueOf(currentTimeMillis);
String signature = generateSignature("appKey" + appKey + "timestamp" + timestamp);
// 构建URL
String urlString = "https://biptest.ctny.com.cn/iuap-api-auth/open-auth/selfAppAuth/getAccessToken" +
"?appKey=22564a240d3140d0b15582aca71a748c" +
"&timestamp=" + currentTimeMillis +
"&signature=" + signature;
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 解析响应
JSONObject jsonObject = JSON.parseObject(response.toString());
JSONObject data = jsonObject.getJSONObject("data");
access_token = data.getString("access_token");
logger.info("getBIPToken → 接口调用成功access_token: {}", access_token);
} else {
logger.error("getBIPToken → 接口调用失败,状态码: {}", responseCode);
}
} catch (Exception e) {
logger.error("getBIPToken → 调用接口报错: {}", e);
}
return access_token;
}
public static SSLContext createInsecureSSLContext() throws Exception {
// 创建一个信任所有证书的 TrustManager
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// 安装信任所有证书的 TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
return sslContext;
}
public static void disableSSLCertificateChecking() {
try {
// 创建一个信任所有证书的 SSLContext
SSLContext sslContext = createInsecureSSLContext();
// 设置 HttpsURLConnection 使用这个 SSLContext
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
// 创建一个 HostnameVerifier信任所有主机名
HostnameVerifier allHostsValid = (hostname, session) -> true;
// 安装这个 HostnameVerifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (Exception e) {
e.printStackTrace();
}
}
private static String generateSignature(String toSign) throws Exception {
// 计算 HmacSHA256 签名
byte[] hmacData = computeHmacSha256(toSign);
// Base64 编码
String base64Encoded = Base64.getEncoder().encodeToString(hmacData);
// URL 编码
return URLEncoder.encode(base64Encoded, StandardCharsets.UTF_8.toString());
}
private static byte[] computeHmacSha256(String data) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec("79f0b7daa428c1abd9272565dbc65486ab565c80".getBytes(StandardCharsets.UTF_8), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secretKey);
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
/**
* 组装推送BIP付款单JSON
*
* @param dynamic 某个单据的 某条需要推送的数据
* @param systemName 推送系统名称
* @return
*/
public static JSONObject paymentSlipsJson(DynamicObject dynamic, String systemName) {
// 获取推送的单据标识
String billMark = dynamic.getDataEntityType().getName();
DynamicObject[] objects = BusinessDataServiceHelper.load("shkd_apimapping", "id,billno," +
"shkd_sourcebill,shkd_targetsystem,entryentity,entryentity.shkd_tarfield,entryentity.shkd_tartier," +
"entryentity.shkd_tartype,entryentity.shkd_parentfield,entryentity.shkd_soufield,entryentity.shkd_defaultdata," +
"entryentity.shkd_required,entryentity.shkd_remarks",
new QFilter("shkd_sourcebill", QCP.equals, billMark).and(
new QFilter("shkd_targetsystem", QCP.equals, systemName)).toArray());
// 获取数据表信息
DynamicObjectCollection dynamicObjectCollection = objects[0].getDynamicObjectCollection("entryentity");
// 提取所有层级并存储在 Set
Set<Integer> tiers = new HashSet<>();
dynamicObjectCollection.forEach(dynamicObject -> {
String shkd_tartier = dynamicObject.getString("shkd_tartier");
if (shkd_tartier != null && !shkd_tartier.isEmpty()) {
tiers.add(Integer.parseInt(shkd_tartier));
}
});
List<List<DynamicObject>> floors = new ArrayList<>();
// 目前定的4层之后需要弄成动态的
for (int i = 1; i <= tiers.size(); i++) {
floors.add(new ArrayList<>());
}
// 分层
for (DynamicObject dynamicObject : dynamicObjectCollection) {
int tier = Integer.parseInt(dynamicObject.getString("shkd_tartier"));
floors.get(tier - 1).add(dynamicObject);
}
JSONObject resultJson = new JSONObject();
processFloor(resultJson, "data", floors.get(0), floors);
logger.info("调用接口系统:{}\n调用接口单据{}\n调用JSON{}", systemName, dynamic, resultJson);
return resultJson;
}
public static void traverseJson(JSONObject jsonObject, List<String> path, String level) {
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
String fullPath = buildPath(path, key, level);
System.out.println(fullPath + ": " + value);
if (value instanceof JSONObject) {
path.add(key);
traverseJson((JSONObject) value, path, level + "." + (path.size() + 1));
path.remove(path.size() - 1);
} else if (value instanceof JSONArray) {
path.add(key);
traverseJsonArray((JSONArray) value, path, level + "." + (path.size() + 1));
path.remove(path.size() - 1);
}
}
}
public static void traverseJsonArray(JSONArray jsonArray, List<String> path, String level) {
for (int i = 0; i < jsonArray.size(); i++) {
Object value = jsonArray.get(i);
if (value instanceof JSONObject) {
path.add("[" + i + "]");
traverseJson((JSONObject) value, path, level + "." + (i + 1));
path.remove(path.size() - 1);
} else if (value instanceof JSONArray) {
path.add("[" + i + "]");
traverseJsonArray((JSONArray) value, path, level + "." + (i + 1));
path.remove(path.size() - 1);
} else {
String fullPath = buildPath(path, "[" + i + "]", level);
System.out.println(fullPath + ": " + value);
}
}
}
public static String buildPath(List<String> path, String key, String level) {
StringBuilder sb = new StringBuilder();
sb.append("层级 ").append(level).append(": ");
for (int i = 0; i < path.size(); i++) {
sb.append(path.get(i)).append(".");
}
sb.append(key);
return sb.toString();
}
/**
* 遍历JSON对象
*
* @param parentJson
* @param parentKey
* @param currentFloor
* @param floors
*/
public static void processFloor(JSONObject parentJson, String parentKey, List<DynamicObject> currentFloor, List<List<DynamicObject>> floors) {
if (currentFloor.isEmpty()) {
return;
}
if (currentFloor.size() == 1 && "object".equals(currentFloor.get(0).getString("shkd_tartype"))) {
parentJson.put(parentKey, new JSONObject());
processFloor(parentJson.getJSONObject(parentKey), parentKey, getChildren(floors, currentFloor.get(0).getString("shkd_tarfield")), floors);
return;
}
if ("arrayList".equals(currentFloor.get(0).getString("shkd_tartype"))) {
JSONArray jsonArray = new JSONArray();
//目前JSONArray都是一层
JSONObject json = new JSONObject();
for (DynamicObject dynamicObject : currentFloor) {
String key = dynamicObject.getString("shkd_tarfield");
Object value = dynamicObject.get("shkd_defaultdata");
String tartype = dynamicObject.getString("shkd_tartype");
if ("string".equals(tartype) || "date".equals(tartype)) {
json.put(key, value);
} else if ("int".equals(tartype)) {
json.put(key, Integer.parseInt(value.toString()));
} else if ("object".equals(tartype)) {
JSONObject childJson = new JSONObject();
processFloor(childJson, key, getChildren(floors, dynamicObject.getString("shkd_tarfield")), floors);
json.put(key, childJson);
} else if ("arrayList".equals(tartype)) {
JSONArray childJsonArray = new JSONArray();
for (DynamicObject childDynamicObject : getChildren(floors, dynamicObject.getString("shkd_tarfield"))) {
JSONObject childJson = new JSONObject();
processFloor(childJson, key, Collections.singletonList(childDynamicObject), floors);
childJsonArray.add(childJson);
}
json.put(key, childJsonArray);
}
}
jsonArray.add(json);
parentJson.put(parentKey, jsonArray);
} else {
for (DynamicObject dynamicObject : currentFloor) {
String key = dynamicObject.getString("shkd_tarfield");
Object value = dynamicObject.get("shkd_defaultdata");
String tartype = dynamicObject.getString("shkd_tartype");
if ("string".equals(tartype) || "date".equals(tartype)) {
parentJson.put(key, value);
} else if ("int".equals(tartype)) {
parentJson.put(key, Integer.parseInt(value.toString()));
} else if ("object".equals(tartype)) {
JSONObject childJson = new JSONObject();
processFloor(childJson, key, getChildren(floors, dynamicObject.getString("shkd_tarfield")), floors);
parentJson.put(key, childJson);
} else if ("arrayList".equals(tartype)) {
JSONArray childJsonArray = new JSONArray();
JSONObject childJson = new JSONObject();
processFloor(childJson, key, getChildren(floors, dynamicObject.getString("shkd_tarfield")), floors);
childJsonArray.add(childJson);
parentJson.put(key, childJsonArray);
}
}
}
}
/**
* 获取子节点
*
* @param floors
* @param parentKey
* @return
*/
public static List<DynamicObject> getChildren(List<List<DynamicObject>> floors, String parentKey) {
List<DynamicObject> children = new ArrayList<>();
for (List<DynamicObject> floor : floors) {
for (DynamicObject dynamicObject : floor) {
if (parentKey.equals(dynamicObject.getString("shkd_parentfield"))) {
children.add(dynamicObject);
}
}
}
return children;
}
}

View File

@ -1,194 +0,0 @@
package shkd.sys.sys.mservice;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import shkd.sys.sys.common.ApiEntity;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* @Description
* @Author Tao
* @Date 2024/11/11
*/
public class BIPService {
private static final Log logger = LogFactory.getLog(BIPService.class);
public static String getBIPToken() {
String access_token = null;
long currentTimeMillis = System.currentTimeMillis();
try {
// 禁用 SSL 证书验证
disableSSLCertificateChecking();
// RestTemplate restTemplate = new RestTemplate();
String appKey = "22564a240d3140d0b15582aca71a748c";
String timestamp = String.valueOf(currentTimeMillis);
String signature = generateSignature("appKey" + appKey + "timestamp" + timestamp);
// 构建URL
String urlString = "https://biptest.ctny.com.cn/iuap-api-auth/open-auth/selfAppAuth/getAccessToken" +
"?appKey=22564a240d3140d0b15582aca71a748c" +
"&timestamp=" + currentTimeMillis +
"&signature=" + signature;
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 解析响应
JSONObject jsonObject = JSON.parseObject(response.toString());
JSONObject data = jsonObject.getJSONObject("data");
access_token = data.getString("access_token");
logger.info("getBIPToken → 接口调用成功access_token: {}", access_token);
} else {
logger.error("getBIPToken → 接口调用失败,状态码: {}", responseCode);
}
} catch (Exception e) {
logger.error("getBIPToken → 调用接口报错: {}", e);
}
return access_token;
}
public static SSLContext createInsecureSSLContext() throws Exception {
// 创建一个信任所有证书的 TrustManager
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// 安装信任所有证书的 TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
return sslContext;
}
public static void disableSSLCertificateChecking() {
try {
// 创建一个信任所有证书的 SSLContext
SSLContext sslContext = createInsecureSSLContext();
// 设置 HttpsURLConnection 使用这个 SSLContext
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
// 创建一个 HostnameVerifier信任所有主机名
HostnameVerifier allHostsValid = (hostname, session) -> true;
// 安装这个 HostnameVerifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (Exception e) {
e.printStackTrace();
}
}
private static String generateSignature(String toSign) throws Exception {
// 计算 HmacSHA256 签名
byte[] hmacData = computeHmacSha256(toSign);
// Base64 编码
String base64Encoded = Base64.getEncoder().encodeToString(hmacData);
// URL 编码
return URLEncoder.encode(base64Encoded, StandardCharsets.UTF_8.toString());
}
private static byte[] computeHmacSha256(String data) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec("79f0b7daa428c1abd9272565dbc65486ab565c80".getBytes(StandardCharsets.UTF_8), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secretKey);
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
/**
* 组装推送BIP付款单JSON
*
* @return
*/
public static JSONObject paymentSlipsJson() {
ApiEntity apiEntity = new ApiEntity();
JSONObject root = new JSONObject();
// 创建"data"节点
JSONObject data = new JSONObject();
// 设置"data"节点的属性
data.put("accentity_code", "SIG1040100");
data.put("vouchdate", "2022-04-20");
data.put("tradetype_code", "cmp_fund_payment_other");
data.put("exchangeRateType_code", "01");
data.put("exchRate", 1);
data.put("currency_code", "CNY");
data.put("_status", "Insert");
// 创建"FundPayment_b"列表
JSONArray fundPaymentList = new JSONArray();
// 创建"FundPayment_b"列表中的第一个对象
JSONObject fundPayment = new JSONObject();
fundPayment.put("quickType_code", "6");
fundPayment.put("settlestatus", "1");
fundPayment.put("oriSum", 5000);
fundPayment.put("caobject", 2);
fundPayment.put("oppositeobjectname", "11510107MB1526717D");
fundPayment.put("_status", "Insert");
// "FundPayment_b"对象添加到列表中
fundPaymentList.add(fundPayment);
// "FundPayment_b"列表添加到"data"节点中
data.put("FundPayment_b", fundPaymentList);
// "data"节点添加到根JSON对象中
root.put("data", data);
apiEntity.setURL("");
apiEntity.setRequestBody(root);
apiEntity.setMethod("POST");
Map<String, Object> queryParams = new HashMap<>();
queryParams.put("access_token", getBIPToken());
apiEntity.setQueryParams(queryParams);
Map<String, Object> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
apiEntity.setHeaders(headers);
return ApiEntity.getResponseBody(apiEntity);
}
}

View File

@ -1,11 +1,10 @@
package shkd.sys.sys.plugin.form;
import com.alibaba.fastjson.JSONObject;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.form.control.Toolbar;
import kd.bos.form.control.events.ItemClickEvent;
import kd.sdk.plugin.Plugin;
import shkd.sys.sys.mservice.BIPService;
import shkd.sys.sys.mservice.ApiService;
import java.util.EventObject;
@ -33,13 +32,13 @@ public class ApiTestBillPlugin extends AbstractBillPlugIn implements Plugin {
String key = evt.getItemKey();
if ("shkd_token".equals(key)) {
String bipToken = BIPService.getBIPToken();
String bipToken = ApiService.getBIPToken();
this.getView().showTipNotification(bipToken);
}
if ("shkd_api".equals(key)) {
JSONObject jsonObject = BIPService.paymentSlipsJson();
this.getView().showTipNotification(jsonObject.toJSONString());
// JSONObject jsonObject = BIPService.paymentSlipsJson();
// this.getView().showTipNotification(jsonObject.toJSONString());
}
}