金蝶k3 webapi 扩展封装
配置文件
public class KingdeeK3CloudConfig
{
public string Name { get; set; }
public string CloudDbId { get; set; }
public string CloudUrl { get; set; }
public string AppId { get; set; }
public string AppSec { get; set; }
public string CloudUser { get; set; }
public int Language { get; set; }
public string OrgId { get; set; }
public string CloudUserPwd { get; set; }
}
字段扩展
/// <summary>
/// 只使用属性
/// </summary>
public static class KingdeeK3CloudFieldHelper
{
/// <summary>
/// 获取参数对应的字符串名称
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static string GetFieldString<T>() where T : new()
{
var fieldNames = GetFieldList<T>();
return string.Join(",", fieldNames);
}
public static T MapData<T>(List<object> data) where T : new()
{
var fieldNames = GetFieldList<T>();
if (fieldNames == null || fieldNames.Count == 0)
{
return default;
}
var result = new T();
var prop = typeof(T).GetProperties();
if (prop == null)
{
return default;
}
foreach (var item in prop)
{
var attrs = item.GetCustomAttributes(false);
foreach (var attr in attrs)
{
if (attr is DescriptionAttribute desc)
{
if (!fieldNames.Exists(f => f == desc.Description))
{
continue;
//throw new System.Exception("");
}
var index = fieldNames.IndexOf(desc.Description);
if (data.Count < index)
{
continue;
//throw new System.Exception("");
}
//Activator.CreateInstance(item.PropertyType);
try
{
item.SetValue(result, data[index]);
}
catch (System.Exception)
{
throw new System.Exception($"类型无法匹配,目标字段:{item.PropertyType.Name} {item.Name} 原始数据:{data[index].GetType().Name} {data[index]}");
}
}
}
}
return result;
}
/// <summary>
/// 获取所有的字段名称
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static List<string> GetFieldList<T>() where T : new()
{
//使用hashset保证不会出现重复的字段名
var result = new HashSet<string>();
var type = typeof(T);
var props = type.GetProperties();
if (props == null)
{
return default;
}
foreach (var item in props)
{
var attrs = item.GetCustomAttributes(false);
if (attrs == null)
{
continue;
}
foreach (var attr in attrs)
{
if (attr is DescriptionAttribute desc)
{
result.Add(desc.Description);
}
}
}
return result.ToList();
}
}
主帮助类
public partial class KingdeeK3CloudHelper
{
private KingdeeK3CloudConfig config;
private K3CloudApi client;
public KingdeeK3CloudHelper()
{
config = MES.Server.Toolkit.Helper.AppSettingsHelper.GetObject<KingdeeK3CloudConfig>("DataAdapterConfig");
}
public static List<string> ClearPara(List<string> para)
{
if (para.IsNullOrEmpty())
{
return para;
}
para = para.Distinct().ToList();
para.RemoveAll(f => string.IsNullOrWhiteSpace(f));
para.RemoveAll(f => string.IsNullOrEmpty(f));
para.RemoveAll(f => f == "0");
return para;
}
/// <summary>
/// 获取指定单据所有数据
/// </summary>
public List<T> GetAllListData<T>(string orderString, string filterString, int limit = 2000) where T : new()
{
string desc = string.Empty;
var formModelType = typeof(T);
var cusDesc = formModelType.GetCustomAttributes(true);
ExceptionHelper.CheckException(cusDesc.IsNullOrEmpty(), "未配置FormID");
foreach (var item in cusDesc)
{
if (item is DescriptionAttribute description)
{
desc = description.Description;
break;
}
}
return GetAllListData<T>(desc, orderString, filterString, limit);
}
/// <summary>
/// 获取指定单据所有数据
/// </summary>
public List<T> GetAllListData<T>(string formID, string orderString, string filterString, int limit = 2000) where T : new()
{
var result = new List<T>();
int startRow = 0;
var data = GetListData<T>(formID, orderString, filterString, startRow, limit);
while (!data.IsNullOrEmpty())
{
result.AddRange(data);
startRow += limit;
data = GetListData<T>(formID, orderString, filterString, startRow, limit);
}
return result;
}
public string GetFormID<T>() where T : new()
{
string desc = string.Empty;
var formModelType = typeof(T);
var cusDesc = formModelType.GetCustomAttributes(true);
ExceptionHelper.CheckException(cusDesc.IsNullOrEmpty(), "未配置FormID");
foreach (var item in cusDesc)
{
if (item is DescriptionAttribute description)
{
desc = description.Description;
break;
}
}
return desc;
}
public List<T> GetListData<T>(string orderString, string filterString, int startRow = 0, int limit = 2000) where T : new()
{
string desc = GetFormID<T>();
return GetListData<T>(desc, orderString, filterString, startRow, limit);
}
/// <summary>
/// 获取指定单据列表数据
/// </summary>
public List<T> GetListData<T>(string formID, string orderString, string filterString, int startRow = 0, int limit = 2000) where T : new()
{
var result = new List<T>();
string formId = formID;
var fieldKeys = KingdeeK3CloudFieldHelper.GetFieldString<T>();
var param = new QueryParam()
{
FormId = formId,
FieldKeys = fieldKeys,
StartRow = startRow,
Limit = limit,
OrderString = orderString,
FilterString = filterString
};
Console.WriteLine(formId);
Console.WriteLine(param.ToJson());
//调用接口
var data = client.ExecuteBillQuery(param.ToJson());
if (data.Count == 1)
{
//对返回结果进行解析和校验,这里使用的是JsonPatch
var resultJObject = JArray.Parse(JsonConvert.SerializeObject(data[0]));
var queryNode = resultJObject.SelectToken("$..IsSuccess");
if (queryNode != null)
{
var isSuccess = queryNode.Value<bool>();
ExceptionHelper.CheckException(!isSuccess, $"操作失败:{data.ToJson()}");
}
}
foreach (var item in data)
{
var temp = KingdeeK3CloudFieldHelper.MapData<T>(item);
result.Add(temp);
}
return result;
}
public long GetCount(string formID, string orderString, string filterString)
{
var param = new QueryParam()
{
FormId = formID,
FieldKeys = "count(0)",
StartRow = 0,
Limit = 0,
OrderString = orderString,
FilterString = filterString
};
Console.WriteLine(param.ToJson());
//调用接口
var data = client.ExecuteBillQuery(param.ToJson());
if (data.Count == 1)
{
//对返回结果进行解析和校验,这里使用的是JsonPatch
var resultJObject = JArray.Parse(JsonConvert.SerializeObject(data[0]));
var queryNode = resultJObject.SelectToken("$..IsSuccess");
if (queryNode != null)
{
var isSuccess = queryNode.Value<bool>();
ExceptionHelper.CheckException(!isSuccess, $"操作失败:{data.ToJson()}");
}
var resultItem = data[0];
ExceptionHelper.CheckException(resultItem.Count != 1, $"操作失败:无法获取数量信息");
var countStr = resultItem[0];
if (!long.TryParse(countStr.ToString(), out long count))
{
ExceptionHelper.CheckException(true, "无法解析数据量");
}
return count;
}
return 0;
}
/// <summary>
/// 下推
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="formID"></param>
/// <param name="obj"></param>
/// <returns></returns>
public TResult Push<TResult>(string formID, object obj)
{
var result = client.Push(formID, JsonConvert.SerializeObject(obj));
//ReturnCheck(result);
return JsonConvert.DeserializeObject<TResult>(result);
}
/// <summary>
/// 单据查询
/// </summary>
/// <returns></returns>
public List<TResult> BillQuery<TResult>(string formID, string filterString, int limit, int startRow) where TResult : new()
{
var result = new List<TResult>();
string fieldKeys = KingdeeK3CloudFieldHelper.GetFieldString<TResult>();
QueryParam param = new QueryParam()
{
FormId = formID,
FieldKeys = fieldKeys,
FilterString = filterString,
Limit = limit,
StartRow = startRow,
};
Console.WriteLine(JsonConvert.SerializeObject(param));
//调用接口
List<List<object>> data = client.ExecuteBillQuery(param.ToJson());
Console.WriteLine(JsonConvert.SerializeObject(data));
//返回的数据类型为List<List<object>>,错误的返回结果只有一行数据且IsSuccess为False
ReturnCheck(data);
foreach (List<object> item in data)
{
var temp = KingdeeK3CloudFieldHelper.MapData<TResult>(item);
//Console.WriteLine(item[0]?.ToString());
result.Add(temp);
}
return result;
}
/// <summary>
/// 获取SDK调用对象
/// </summary>
/// <returns></returns>
public void Init(int timeout = 60 * 1000)
{
Console.WriteLine(JsonConvert.SerializeObject(config));
client = new K3CloudApi(new ThirdPassPortInfo
{
CloudUrl = config.CloudUrl,
CloudUser = config.CloudUser,
CloudDbId = config.CloudDbId,
Language = config.Language.ToString(),
ApiAppId = "",
AppSec = "",
Name = config.Name,
OrgId = ""
}, timeout);
//client = new K3CloudApi(config.CloudUrl, 10000);
string loginResult = client.ValidateLogin(config.CloudDbId, config.CloudUser, config.CloudUserPwd, config.Language);
ExceptionHelper.CheckException(string.IsNullOrEmpty(loginResult), "无法校验erp登录结果");
var resultJObject = JObject.Parse(loginResult);
JToken queryNode = resultJObject.SelectToken("$..IsSuccessByAPI");
if (queryNode != null)
{
bool isSuccess = queryNode.Value<bool>();
if (!isSuccess)
{
JToken messageNode = resultJObject.SelectToken("$..Message");
ExceptionHelper.CheckException(messageNode == null, "无法获取错误信息");
var message = messageNode.Value<string>();
ExceptionHelper.CheckException(true, "登录失败:" + message);
}
}
Console.WriteLine(loginResult);
}
public static string GetIdString(List<string> id)
{
StringBuilder allId = new StringBuilder();
foreach (string item in id)
{
if (allId.Length != 0)
{
allId.Append(",");
}
allId.Append($"\'{item}\'");
}
return allId.ToString();
}
public static string GetIdString(List<long> id)
{
List<string> value = new List<string>();
foreach (var item in id)
{
value.Add(item.ToString());
}
return GetIdString(value);
}
/// <summary>
/// 校验返回值
/// </summary>
/// <param name="data"></param>
private static void ReturnCheck(List<List<object>> data)
{
if (data.Count == 1)
{
//对返回结果进行解析和校验,这里使用的是JsonPatch
JArray resultJObject = JArray.Parse(JsonConvert.SerializeObject(data[0]));
JToken queryNode = resultJObject.SelectToken("$..IsSuccess");
if (queryNode != null)
{
bool isSuccess = queryNode.Value<bool>();
ExceptionHelper.CheckException(!isSuccess, "操作失败" + JsonConvert.SerializeObject(data));
}
}
}
private static void ReturnCheck(string resultJson)
{
//对返回结果进行解析和校验,这里使用的是JsonPatch
JObject resultJObject = JObject.Parse(resultJson);
JToken queryNode = resultJObject.SelectToken("$..IsSuccess");
//判断并记录结果
ExceptionHelper.CheckException(queryNode == null, "返回异常");
bool isSuccess = queryNode.Value<Boolean>();
ExceptionHelper.CheckException(!isSuccess, "操作失败");
}
public static bool ISResultSuccess(string resultJson)
{
try
{
//对返回结果进行解析和校验,这里使用的是JsonPatch
JObject resultJObject = JObject.Parse(resultJson);
JToken queryNode = resultJObject.SelectToken("$..IsSuccess");
//判断并记录结果
ExceptionHelper.CheckException(queryNode == null, "返回异常");
if (queryNode == null)
{
return false;
}
bool isSuccess = queryNode.Value<Boolean>();
if (!isSuccess)
{
return false;
}
return true;
}
catch (Exception)
{
return false;
}
}
private static ResKingdeeK3Cloud ConvertResult(string resultJson)
{
if (string.IsNullOrWhiteSpace(resultJson)) return null;
ResKingdeeK3Cloud result = JsonConvert.DeserializeObject<ResKingdeeK3Cloud>(resultJson);
return result;
}
}
留待后查,同时方便他人
联系我:renhanlinbsl@163.com
联系我:renhanlinbsl@163.com