客户自动分配组织调整

This commit is contained in:
mzr 2025-06-11 19:07:32 +08:00
parent 0f9535de9a
commit cfb4c8d2fd
4 changed files with 459 additions and 13 deletions

View File

@ -0,0 +1,268 @@
package nccloud.web.uapbd.customer.baseinfo.action;
import com.alibaba.fastjson.JSONObject;
import com.sm.misc.BASE64Decoder;
import com.sm.misc.BASE64Encoder;
import nc.bs.dao.DAOException;
import nc.bs.logging.Logger;
import nc.bs.trade.business.HYSuperDMO;
import nc.vo.opm.thirdapp.ThirdappVO;
import nc.ws.opm.pub.utils.security.SecurityUtil;
import org.apache.commons.httpclient.Header;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @description: openapi请求
* @author: mzr
* @date: 20250611
*/
public class BaseOpenApiReq {
public String BASE_URL_DEV = "http://127.0.0.1:9080";
/**
* APP ID
*/
public String CLIENT_ID = "BIP2312";
/**
* APP Secret
*/
public String CLIENT_SECRET = "";
/**
* 公钥
*/
public String PUBLIC_KEY = "";
/**
* 账套编码
*/
public String BIZ_CENTER = "01";
/**
* 用户编码
*/
public String USER_CODE = "BIP";
public HttpClientWapper client = new HttpClientWapper();
/**
* 调用openAPI给客户分配组织
*/
public void assignOrgApi(String url, JSONObject param) {
ThirdappVO apiInfo = getApiInfo();
if (apiInfo == null) {
return;
}
CLIENT_ID = apiInfo.getApp_id();
CLIENT_SECRET = apiInfo.getApp_secret();
PUBLIC_KEY = apiInfo.getPublic_key();
USER_CODE = apiInfo.getUser_code();
try {
String result = requestOpenApi(url, param);
Logger.error("CustomerSaveAction-assignOrg-result = " + result);
} catch (Exception e) {
Logger.error("assignOrgApi-exp:" + e.getMessage());
throw new RuntimeException(e);
}
}
/**
* 获取openAPI的应用信息
*/
private ThirdappVO getApiInfo() {
ThirdappVO result = new ThirdappVO();
String strWhere = " code = 'BIP2312' and dr=0";
try {
ThirdappVO[] vos = (ThirdappVO[]) new HYSuperDMO().queryByWhereClause(ThirdappVO.class, strWhere);
if (vos != null) {
result = vos[0];
}
} catch (DAOException e) {
e.printStackTrace();
}
return result;
}
/**
* @param url
* @param param
* @return
* @throws Exception
*/
public String requestOpenApi(String url, Map<String, Object> param) throws Exception {
return requestOpenApi(url, new JSONObject(param));
}
/**
* @param url
* @param param
* @return
* @throws Exception
*/
public String requestOpenApi(String url, JSONObject param) throws Exception {
return requestOpenApi(url, param.toJSONString());
}
public String requestOpenApi(String url, String param) throws Exception {
String accessToken = this.getAccessTokenByClient();
Logger.info("requestOpenApi-param:" + param.replace(" ", ""));
String sign = digest(CLIENT_ID + PUBLIC_KEY);
List<Header> headers = new ArrayList<>();
headers.add(new Header("Content-Type", "application/json;charset=UTF-8"));
headers.add(new Header("signature", sign));
headers.add(new Header("ucg_flag", "y"));
headers.add(new Header("access_token", accessToken));
headers.add(new Header("client_id", CLIENT_ID));
HttpClientWapper.Response response;
try {
response = client.post(BASE_URL_DEV + url, headers.toArray(new Header[headers.size()]), null, param);
return response.getData();
} catch (Exception e) {
Logger.error("requestOpenApi-exp:" + e.getMessage());
return e.getMessage();
}
}
/**
* @param seed 种子用于生成公钥
* @param src 明文
* @return
* @throws Exception
* @description RSA加密
*/
public String pubEncrypt(String seed, String src) throws Exception {
String target = null;
ByteArrayOutputStream out = null;
try {
Key key = genPublicKey(PUBLIC_KEY);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(1, key);
byte[] data = src.getBytes();
int inputLen = data.length;
out = new ByteArrayOutputStream();
int offSet = 0;
int i = 0;
while (inputLen - offSet > 0) {
byte[] cache;
;
if (inputLen - offSet > 117) {
cache = cipher.doFinal(data, offSet, 117);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * 117;
}
target = new BASE64Encoder().encodeBuffer(out.toByteArray());
} catch (Exception e) {
throw new Exception("加密失败" + e.getMessage());
} finally {
if (out != null) {
out.close();
}
}
return target;
}
/**
* @param str
* @return
* @description 信息摘要
*/
public static String digest(String str) {
String encodestr = "";
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
encodestr = byte2Hex(messageDigest.digest());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return encodestr;
}
private static String byte2Hex(byte[] bytes) {
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
for (int i = 0; i < bytes.length; i++) {
temp = Integer.toHexString(bytes[i] & 0xFF);
if (temp.length() == 1) {
stringBuffer.append("0");
}
stringBuffer.append(temp);
}
return stringBuffer.toString();
}
/**
* @return
* @throws Exception
* @description 根据种子生成密钥对
*/
public static Key genPublicKey(String seed) throws Exception {
Key key = null;
try {
byte[] keyBytes = new BASE64Decoder().decodeBuffer(seed);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
key = keyFactory.generatePublic(x509KeySpec);
} catch (Exception e) {
throw new Exception("无效的密钥 " + e.getMessage());
}
return key;
}
public static String getSHA256(String str, String key) throws Exception {
byte[] salt = new byte[16];
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(key.getBytes());
random.nextBytes(salt);
String salt_value = new BASE64Encoder().encodeBuffer(salt);
return digest(str + salt_value.replaceAll("\r|\n", ""));
}
/**
* @return
* @throws Exception
* @description 获取AccessToken
*/
@SuppressWarnings("static-access")
public String getAccessTokenByClient() throws Exception {
String url = BASE_URL_DEV + "/nccloud/opm/accesstoken";
List<Header> headers = new ArrayList<Header>();
headers.add(new Header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"));
// 获取信息摘要
String signature = getSHA256(CLIENT_ID + CLIENT_SECRET + PUBLIC_KEY, PUBLIC_KEY);
// 使用PUBLIC_KEY生成公钥对CLIENT_SECRET加密
SecurityUtil securityUtil = new SecurityUtil();
String CLIENT_SECRETEn = URLEncoder.encode(securityUtil.pubEncrypt(PUBLIC_KEY, CLIENT_SECRET), StandardCharsets.UTF_8);
Map<String, Object> params = new HashMap<String, Object>();
params.put("client_id", CLIENT_ID);
params.put("userCode", USER_CODE);
params.put("grant_type", "client_credentials");
params.put("biz_center", BIZ_CENTER);
params.put("signature", signature);
params.put("client_secret", CLIENT_SECRETEn);
try {
HttpClientWapper.Response response = client.post(url, headers.toArray(new Header[headers.size()]), null, client.getURLParam(params));
JSONObject result = JSONObject.parseObject(response.getData());
boolean success = result.getBoolean("success");
if (success) {
return result.getJSONObject("data").getString("access_token");
}
} catch (Exception e) {
Logger.error("getAccessTokenByClient-exp:" + e.getMessage());
}
return null;
}
}

View File

@ -5,9 +5,9 @@
package nccloud.web.uapbd.customer.baseinfo.action;
import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.logging.Logger;
import nc.bs.uif2.LockFailedException;
import nc.bs.uif2.VersionConflictException;
import nc.itf.bd.cust.assign.ICustAssignService;
@ -17,14 +17,12 @@ import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.MapProcessor;
import nc.uap.utils.ResHelper;
import nc.vo.bd.cust.*;
import nc.vo.bd.errorlog.ErrLogReturnValue;
import nc.vo.bd.supplier.SupplierVO;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.org.OrgVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;
import nc.vo.pub.lang.UFDateTime;
import nccloud.baseapp.core.log.NCCForUAPLogger;
import nccloud.commons.lang.StringUtils;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.service.ServiceLocator;
@ -163,15 +161,12 @@ public class CustomerSaveAction implements ICommonAction {
}
}
// 自动分配组织
String[] customerPks = {customerVO.getPk_customer()};
/*String[] customerPks = {customerVO.getPk_customer()};
OrgVO[] virtulaOrg = getVirtulaOrg();
String[] assignOrgPks = Arrays.stream(virtulaOrg).map(OrgVO::getPk_org).toArray(String[]::new);
// assignOrgPks = new String[]{"0001A1100000000026HI", "0001A110000000002H9M"};
ErrLogReturnValue errLogReturnValue = cs.getAssignService().assignCustomerByPks(customerPks, assignOrgPks, null);
Logger.error("CustomerSaveAction-errLogReturnValue = " + errLogReturnValue.getErrLogResult());
// NCCForUAPLogger.debug("customerPks = " + customerPks[0]);
// NCCForUAPLogger.debug("assignOrgPks = " + Arrays.toString(assignOrgPks));
// NCCForUAPLogger.debug("CustomerSaveAction-errLogReturnValue = " + errLogReturnValue.getErrLogResult());
Logger.error("CustomerSaveAction-errLogReturnValue = " + errLogReturnValue.getErrLogResult());*/
assignOrgApi(customerVO);
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
Throwable undeclaredThrowable = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
@ -200,6 +195,23 @@ public class CustomerSaveAction implements ICommonAction {
return ebc;
}
public void assignOrgApi(CustomerVO customerVO) throws BusinessException {
String[] customerPks = {customerVO.getCode()};
OrgVO[] virtulaOrg = getVirtulaOrg();
String[] assignOrgPks = Arrays.stream(virtulaOrg).map(OrgVO::getCode).toArray(String[]::new);
JSONObject param = new JSONObject();
JSONObject ufinterfaceJson = new JSONObject();
JSONObject dataJson = new JSONObject();
dataJson.put("customer", customerPks);
dataJson.put("org", assignOrgPks);
ufinterfaceJson.put("sender", "default");
ufinterfaceJson.put("data", dataJson);
param.put("ufinterface", ufinterfaceJson);
BaseOpenApiReq req = new BaseOpenApiReq();
req.assignOrgApi("/nccloud/api/uapbd/customermanageext/customer/assign", param);
}
/**
* 查询组织信息
*
@ -214,4 +226,6 @@ public class CustomerSaveAction implements ICommonAction {
Collection<OrgVO> collection = (new BaseDAO()).retrieveByClause(OrgVO.class, condition, "code");
return collection.toArray(new OrgVO[0]);
}
}

View File

@ -5,6 +5,7 @@
package nccloud.web.uapbd.customer.baseinfo.action;
import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.logging.Logger;
@ -109,13 +110,12 @@ public class CustomerSaveAddAction implements ICommonAction {
ebc.setUserjson(billCodeContext == null ? "" : "" + billCodeContext.isEditable());
// 自动分配组织
String[] customerPks = {customerVO.getPk_customer()};
/*String[] customerPks = {customerVO.getPk_customer()};
OrgVO[] virtulaOrg = getVirtulaOrg();
String[] assignOrgPks = Arrays.stream(virtulaOrg).map(OrgVO::getPk_org).toArray(String[]::new);
// assignOrgPks = new String[]{"0001A1100000000026HI", "0001A110000000002H9M"};
ErrLogReturnValue errLogReturnValue = cs.getAssignService().assignCustomerByPks(customerPks, assignOrgPks, null);
Logger.error("CustomerSaveAddAction-errLogReturnValue = " + errLogReturnValue.getErrLogResult());
Logger.error("CustomerSaveAddAction-errLogReturnValue = " + errLogReturnValue.getErrLogResult());*/
assignOrgApi(customerVO);
} catch (BusinessException e) {
ExceptionUtils.wrapException(e);
}
@ -123,6 +123,23 @@ public class CustomerSaveAddAction implements ICommonAction {
return ebc;
}
public void assignOrgApi(CustomerVO customerVO) throws BusinessException {
String[] customerPks = {customerVO.getCode()};
OrgVO[] virtulaOrg = getVirtulaOrg();
String[] assignOrgPks = Arrays.stream(virtulaOrg).map(OrgVO::getCode).toArray(String[]::new);
JSONObject param = new JSONObject();
JSONObject ufinterfaceJson = new JSONObject();
JSONObject dataJson = new JSONObject();
dataJson.put("customer", customerPks);
dataJson.put("org", assignOrgPks);
ufinterfaceJson.put("sender", "default");
ufinterfaceJson.put("data", dataJson);
param.put("ufinterface", ufinterfaceJson);
BaseOpenApiReq req = new BaseOpenApiReq();
req.assignOrgApi("/nccloud/api/uapbd/customermanageext/customer/assign", param);
}
/**
* 查询组织信息
*

View File

@ -0,0 +1,147 @@
package nccloud.web.uapbd.customer.baseinfo.action;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.util.EncodingUtil;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.Map;
/**
* Http请求包装类
*
* @author guoxiangqiao
* @date 2019年12月11日
*/
public class HttpClientWapper {
public static final int HTTP_STATUS_SUCCESS = 200;
/**
* post请求
*
* @param url
* @param headers
* @param requestBody
* @return
* @throws Exception
*/
public Response post(String url, Header[] headers, NameValuePair[] requestBody, String requestEntityStr) throws Exception {
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
if (headers != null) {
for (Header header : headers) {
postMethod.setRequestHeader(header);
}
}
if (requestBody != null) {
postMethod.setRequestBody(requestBody);
}
if (StringUtils.isNotEmpty(requestEntityStr)) {
StringRequestEntity requestEntity = new StringRequestEntity(requestEntityStr, null, "utf-8");
postMethod.setRequestEntity(requestEntity);
}
int httpStatus = client.executeMethod(postMethod);
String result = this.getResponseBodyAsString(postMethod);
return new Response(httpStatus, result);
}
public String getResponseBodyAsString(PostMethod postMethod) throws IOException {
byte[] rawdata = null;
rawdata = postMethod.getResponseBody();
return rawdata != null ? EncodingUtil.getString(rawdata, "utf-8") : null;
}
/**
* @param params
* @return
* @description Map转URL参数
* @author guoxqc@yonyou.com
* @date 2020年10月22日
*/
public String getURLParam(Map<String, Object> params) {
StringBuffer paramStr = new StringBuffer();
if (!params.isEmpty()) {
for (Map.Entry<String, Object> kv : params.entrySet()) {
paramStr.append(kv.getKey());
paramStr.append("=");
paramStr.append(kv.getValue());
paramStr.append("&");
}
paramStr.deleteCharAt(paramStr.length() - 1);
}
return paramStr.toString();
}
/**
* get请求
*
* @param url
* @param headers
* @param params
* @return
* @throws Exception
*/
public Response get(String url, Header[] headers, NameValuePair[] params) throws Exception {
HttpClient client = new HttpClient();
GetMethod getMethod = new GetMethod(url);
if (params != null) {
getMethod.setQueryString(params);
}
if (headers != null) {
for (Header header : headers) {
getMethod.setRequestHeader(header);
}
}
int httpStatus = client.executeMethod(getMethod);
String result = getMethod.getResponseBodyAsString();
return new Response(httpStatus, result);
}
/**
* 获取url查询参数
*
* @param params
* @return
*/
public String getQueryString(NameValuePair[] params) {
GetMethod getMethod = new GetMethod();
getMethod.setQueryString(params);
return getMethod.getQueryString();
}
class Response {
private int httpStatus;
private String data;
public int getHttpStatus() {
return httpStatus;
}
public void setHttpStatus(int httpStatus) {
this.httpStatus = httpStatus;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Response(int httpStatus, String data) {
super();
this.httpStatus = httpStatus;
this.data = data;
}
public Response() {
super();
}
}
}