123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601 |
- using OASystem.Domain.Dtos.QiYeWeChat;
- using OASystem.Domain.ViewModels.JuHeExchangeRate;
- using OASystem.Domain.ViewModels.QiYeWeChat;
- using Org.BouncyCastle.Ocsp;
- using System.Collections.Generic;
- using System.Text.Json;
- using Ubiety.Dns.Core;
- namespace OASystem.API.OAMethodLib.QiYeWeChatAPI
- {
- /// <summary>
- /// 聚合Api 服务
- /// </summary>
- public class QiYeWeChatApiService: IQiYeWeChatApiService
- {
- private readonly HttpClient _httpClient;
- private readonly string CorpId = "wwe978bef5495a0728"; //企业Id
- private readonly string PersonnelAssistant_AgentId = "3010011"; //人事助手Id
- private readonly string PersonnelAssistant_Corpsecret = "ig--IJd6TxWDMJ1wT4e-RDRcRX12v5GjB359DNATwJ4"; //人事助手凭证密钥
- private readonly string PunchCard_AgentId = "3010185"; //打卡Id
- private readonly string PunchCard_Corpsecret = "Xhrl37GOqlAjsu0VzUSJECaJdjzkDXQLbvrzRsZQb8M"; //打卡凭证密钥
- private readonly string Email_AgentId = "1000004"; //E-Mail Id
- private readonly string Email_Corpsecret = "NA1zbJM15GmgjPYwDOqz59dIo1Wnug-MbU107MeUemc"; //E-Mail 凭证密钥
- private readonly string AddressBook_Corpsecret = "Y1tnjh7j-BvbqAytAoXZPUbmDR6dqLTL6mXtc6PZ7fo"; //通讯录同步 凭证密钥
- private readonly string Approve_AgentId = "3010040"; //审批 Id
- private readonly string Approve_Corpsecret = "k_Jo69Jw9Hqg_in-Rypbs30PNbxOYa1t4e-dxYuT-kw"; //审批 凭证密钥
- private readonly DateTime _1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
- private readonly JobPostRepository _jobPostRep;
- /// <summary>
- /// 初始化
- /// </summary>
- /// <param name="clientFactory"></param>
- /// <param name="jobPostRep"></param>
- public QiYeWeChatApiService(IHttpClientFactory clientFactory, JobPostRepository jobPostRep)
- {
- _httpClient = clientFactory.CreateClient("PublicQiYeWeChatApi"); ;
- _jobPostRep = jobPostRep;
- }
- /// <summary>
- /// 获取access_token
- /// </summary>
- /// <param name="applicationType">
- /// 1:人事助手
- /// 2:打卡
- /// 3:邮件
- /// 4:通讯录同步
- /// 5:审批
- /// </param>
- /// <returns></returns>
- private async Task<Access_TokenView> GetTokenAsync(int applicationType)
- {
- Access_TokenView tokenResult = new Access_TokenView();
- Access_Token_Request access_Token = new Access_Token_Request();
- string cacheName = string.Empty;
- if (applicationType == 1)
- {
- access_Token.corpsecret = PersonnelAssistant_Corpsecret; //人事助手
- cacheName = "PersonnelAssistant_Access_Token";
- }
- else if (applicationType == 2)
- {
- access_Token.corpsecret = PunchCard_Corpsecret; //打卡
- cacheName = "PunchCard_Access_Token";
- }
- else if (applicationType == 3)
- {
- access_Token.corpsecret = Email_Corpsecret; //E-Mail
- cacheName = "Enail_Access_Token";
- }
- else if (applicationType == 4) //通讯录同步
- {
- access_Token.corpsecret = AddressBook_Corpsecret;
- cacheName = "AddressBook_Access_Token";
- }
- else if (applicationType == 5) //审批
- {
- access_Token.corpsecret = Approve_Corpsecret;
- cacheName = "Approve_Access_Token";
- }
- else
- {
- tokenResult.errmsg = "未识别应用类型Id!";
- return tokenResult;
- }
- string access_token = await RedisRepository.RedisFactory
- .CreateRedisRepository()
- .StringGetAsync<string>(cacheName);//string 取
- if (string.IsNullOrEmpty(access_token))
- {
- string access_token_url = string.Format(@"/cgi-bin/gettoken?corpid={0}&corpsecret={1}", access_Token.corpid, access_Token.corpsecret);
- var access_tokenReq = await _httpClient.GetAsync(access_token_url);
- if (access_tokenReq.IsSuccessStatusCode)
- {
- var stringResponse = await access_tokenReq.Content.ReadAsStringAsync();
- tokenResult = System.Text.Json.JsonSerializer.Deserialize<Access_TokenView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (tokenResult.errcode == 0)
- {
- TimeSpan ts = DateTime.Now.AddMinutes(118) - DateTime.Now; //设置redis 过期时间 118分钟
- await RedisRepository
- .RedisFactory
- .CreateRedisRepository()
- .StringSetAsync<string>(cacheName, tokenResult.access_token, ts);//string 存
- }
- }
- else
- {
- tokenResult.errmsg = "企业微信Token未获取到!";
- }
- }
- else
- {
- tokenResult.errcode = 0;
- tokenResult.access_token = access_token;
- }
- return tokenResult;
- }
- #region 添加员工
- /// <summary>
- /// 获取成员ID列表
- /// </summary>
- /// <returns></returns>
- private async Task<UserIdListView> GetUserIdListAsync()
- {
- UserIdListView userIdListView = new UserIdListView();
- Access_TokenView access_Token = await GetTokenAsync(4);
- if (access_Token.errcode != 0)
- {
- userIdListView.errcode = access_Token.errcode;
- userIdListView.errmsg = access_Token.errmsg;
- return userIdListView;
- }
- string url = string.Format("/cgi-bin/user/list_id?access_token={0}&debug=1", access_Token.access_token);
- var jsonData = new
- {
- access_token = access_Token.access_token, //调用接口凭证
- };
- var json = System.Text.Json.JsonSerializer.Serialize(jsonData);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- userIdListView = System.Text.Json.JsonSerializer.Deserialize<UserIdListView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- return userIdListView;
- }
- /// <summary>
- /// 获取部门列表
- /// </summary>
- /// <param name="access_token"></param>
- /// <returns></returns>
- private async Task<DepartmentListView> GetDepartmentAsync(string access_token)
- {
- DepartmentListView result = new DepartmentListView();
- string dep_url = string.Format("/cgi-bin/department/list?access_token={0}&debug=1", access_token);
- var depReq = await _httpClient.GetAsync(dep_url);
- if (depReq.IsSuccessStatusCode)
- {
- var stringResponse = await depReq.Content.ReadAsStringAsync();
- result = System.Text.Json.JsonSerializer.Deserialize<DepartmentListView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- }
- else
- {
- result.errcode = -1;
- result.errmsg = "企业微信部门列表未获取到!";
- }
- return result;
- }
- /// <summary>
- /// 创建员工
- /// </summary>
- /// <param name="create_Request"></param>
- /// <returns></returns>
- public async Task<ResponseBase> CreateAsync(Create_Request create_Request)
- {
- ResponseBase responseBase = new ResponseBase();
- #region 职位
- string depName = string.Empty,
- jobName = string.Empty;
- List<Sys_JobPostI> jobs = await _jobPostRep.QueryJobPost(string.Empty);
- Sys_JobPostI jobPost = jobs.Where(it => it.IsDel == 0 && it.Id == Convert.ToInt32(create_Request.position)).FirstOrDefault();
- if (jobPost != null)
- {
- depName = jobPost.DepName;
- jobName = jobPost.JobName;
- }
- create_Request.position = jobName;
- if (string.IsNullOrEmpty(create_Request.biz_mail))
- {
- create_Request.biz_mail = string.Format("{0}@pan-american-intl.com", create_Request.userid);
- }
- #endregion
- Access_TokenView access_Token = new Access_TokenView();
- access_Token = await GetTokenAsync(4);
- if (access_Token.errcode == 0)
- {
- create_Request.access_token = access_Token.access_token;
- #region 处理部门
- Access_TokenView dep_Access_Token = await GetTokenAsync(1);
- if (dep_Access_Token.errcode != 0)
- {
- responseBase.errcode = dep_Access_Token.errcode;
- responseBase.errmsg = dep_Access_Token.errmsg;
- }
- DepartmentListView depData = await GetDepartmentAsync(dep_Access_Token.access_token);
- if (depData.errcode == 0)
- {
- var depData1 = depData.department.Where(x => x.name == depName).FirstOrDefault();
- if (depData1 != null)
- {
- create_Request.department = new List<long> { depData1.id };
- }
- else
- {
- responseBase.errcode = -1;
- responseBase.errmsg = "未在企业微信上找到OA内设置的部门";
- return responseBase;
- }
- }
- else
- {
- responseBase.errcode = depData.errcode;
- responseBase.errmsg = depData.errmsg;
- return responseBase;
- }
- #endregion
- create_Request.access_token = access_Token.access_token;
- string create_url = string.Format("/cgi-bin/user/create?access_token={0}", create_Request.access_token);
- var json = System.Text.Json.JsonSerializer.Serialize(create_Request);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(create_url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- responseBase = System.Text.Json.JsonSerializer.Deserialize<ResponseBase>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- }
- else
- {
- responseBase.errcode = access_Token.errcode;
- responseBase.errmsg = access_Token.errmsg;
- }
- return responseBase;
- }
- #endregion
- #region 打卡
- /// <summary>
- /// 获取月打卡数据(redis缓存)
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<CheckInView> GetCheckin_MonthDataAsync(DateTime startDt,DateTime endDt)
- {
- CheckInView checkInView = new CheckInView();
- //获取员工Id
- UserIdListView userIdListView = await GetUserIdListAsync();
- if (userIdListView.errcode != 0)
- {
- checkInView.errcode = userIdListView.errcode;
- checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】{0}",userIdListView.errmsg);
- return checkInView;
- }
- if (userIdListView.dept_user == null || userIdListView.dept_user.Count <= 0)
- {
- checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】未查出员工Id");
- return checkInView;
- }
- //获取月打卡数据 token
- Access_TokenView access_Token = await GetTokenAsync(2);
- if (access_Token.errcode != 0)
- {
- checkInView.errcode = access_Token.errcode;
- checkInView.errmsg = string.Format("【企业微信】【获取月打卡数据】【Token】【Msg】{0}", access_Token.errmsg);
- return checkInView;
- }
- string url = string.Format("/cgi-bin/checkin/getcheckin_monthdata?access_token={0}", access_Token.access_token);
- Checkin_MonthData_Request checkInReq = new Checkin_MonthData_Request();
- checkInReq.access_token = access_Token.access_token;
-
- checkInReq.starttime = (uint)(startDt - _1970).TotalSeconds;
- checkInReq.endtime = (uint)(endDt - _1970).TotalSeconds;
- checkInReq.useridlist = userIdListView.dept_user.Select(it => it.userid).ToList();
- var json = System.Text.Json.JsonSerializer.Serialize(checkInReq);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- checkInView = System.Text.Json.JsonSerializer.Deserialize<CheckInView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- return checkInView;
- }
- /// <summary>
- /// 获取月打卡数据(redis缓存)
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<CheckInView> GetCheckin_MonthDataRedisAsync(DateTime startDt, DateTime endDt)
- {
- CheckInView checkInView = new CheckInView();
- string checkInDatastring = await RedisRepository.RedisFactory
- .CreateRedisRepository()
- .StringGetAsync<string>("Checkin_MonthData");//List<T> 取
- if (!string.IsNullOrEmpty(checkInDatastring))
- {
- checkInView = JsonConvert.DeserializeObject<CheckInView>(checkInDatastring);
- return checkInView;
- }
- //获取员工Id
- UserIdListView userIdListView = await GetUserIdListAsync();
- if (userIdListView.errcode != 0)
- {
- checkInView.errcode = userIdListView.errcode;
- checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】{0}", userIdListView.errmsg);
- return checkInView;
- }
- if (userIdListView.dept_user == null || userIdListView.dept_user.Count <= 0)
- {
- checkInView.errmsg = string.Format("【企业微信】【获取员工IdList】【Msg】未查出员工Id");
- return checkInView;
- }
- //获取月打卡数据 token
- Access_TokenView access_Token = await GetTokenAsync(2);
- if (access_Token.errcode != 0)
- {
- checkInView.errcode = access_Token.errcode;
- checkInView.errmsg = string.Format("【企业微信】【获取月打卡数据】【Token】【Msg】{0}", access_Token.errmsg);
- return checkInView;
- }
- string url = string.Format("/cgi-bin/checkin/getcheckin_monthdata?access_token={0}", access_Token.access_token);
- Checkin_MonthData_Request checkInReq = new Checkin_MonthData_Request();
- checkInReq.access_token = access_Token.access_token;
- checkInReq.starttime = (uint)(startDt - _1970).TotalSeconds;
- checkInReq.endtime = (uint)(endDt - _1970).TotalSeconds;
- checkInReq.useridlist = userIdListView.dept_user.Select(it => it.userid).ToList();
- var json = System.Text.Json.JsonSerializer.Serialize(checkInReq);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- checkInView = System.Text.Json.JsonSerializer.Deserialize<CheckInView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- if (checkInView.errcode == 0)
- {
- TimeSpan ts = DateTime.Now.AddMinutes(60) - DateTime.Now; //设置redis 过期时间 60分钟
- await RedisRepository
- .RedisFactory
- .CreateRedisRepository()
- .StringSetAsync<string>("Checkin_MonthData", JsonConvert.SerializeObject(checkInView), ts);//List<T> 存
- }
- return checkInView;
- }
- #endregion
- #region 审批
- /// <summary>
- /// 获取审批数据(旧)
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<ApprovalDataView> GetApprovalDataAsync(DateTime startDt, DateTime endDt)
- {
- ApprovalDataView approvalDataView = new ApprovalDataView();
- //获取审批数据 token
- Access_TokenView access_Token = await GetTokenAsync(5);
- if (access_Token.errcode != 0)
- {
- approvalDataView.errcode = access_Token.errcode;
- approvalDataView.errmsg = string.Format("【企业微信】【获取审批数据】【Token】【Msg】{0}", access_Token.errmsg);
- return approvalDataView;
- }
- string url = string.Format("/cgi-bin/corp/getapprovaldata?access_token={0}", access_Token.access_token);
- ApprovalData_Request approvalDataReq = new ApprovalData_Request();
- approvalDataReq.access_token = access_Token.access_token;
- approvalDataReq.starttime = (uint)(startDt - _1970).TotalSeconds;
- approvalDataReq.endtime = (uint)(endDt - _1970).TotalSeconds;
- var json = System.Text.Json.JsonSerializer.Serialize(approvalDataReq);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var create_Req = await _httpClient.PostAsync(url, content);
- var stringResponse = await create_Req.Content.ReadAsStringAsync();
- approvalDataView = System.Text.Json.JsonSerializer.Deserialize<ApprovalDataView>(stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- List<Sp_Info> sp_datas = new List<Sp_Info>();
- sp_datas.AddRange(approvalDataView.data);
- int index = 0;
- //多次访问审批接口
- if (approvalDataView.total>=100)
- {
- approvalDataView.total -= 100;
- int forTotal = approvalDataView.total % 100 == 0 ? approvalDataView.total / 100 : approvalDataView.total / 100 + 1;
- long? next_spnum = approvalDataView.next_spnum;
- approvalDataReq.next_spnum = next_spnum;
-
- for (int i = 0; i < forTotal; i++)
- {
- index++;
- var for_json = System.Text.Json.JsonSerializer.Serialize(approvalDataReq);
- var for_content = new StringContent(for_json, Encoding.UTF8, "application/json");
- var for_create_Req = await _httpClient.PostAsync(url, for_content);
- var for_stringResponse = await for_create_Req.Content.ReadAsStringAsync();
- ApprovalDataView for_approvalDataView = System.Text.Json.JsonSerializer.Deserialize<ApprovalDataView>(for_stringResponse,
- new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
- approvalDataReq.next_spnum = for_approvalDataView.next_spnum; //重新定义游标
- sp_datas.AddRange(for_approvalDataView.data); //追加数据
- }
- approvalDataView.total += 100;
- }
- approvalDataView.data = sp_datas;
- return approvalDataView;
- }
- /// <summary>
- /// 获取审批数据(旧)(redis缓存)
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<List<Sp_Info>> GetApprovalDatasAsync(DateTime startDt, DateTime endDt)
- {
- List<Sp_Info> sp_Infos = new List<Sp_Info>();
- //获取所有打卡补卡,审批 数据 前后范围增加10天
- DateTime sp_startDt = startDt.AddDays(-10);
- DateTime sp_centerDt = sp_startDt.AddDays(30);
- DateTime sp_endDt = endDt.AddDays(10);
- ApprovalDataView approvalData_1 = await GetApprovalDataAsync(sp_startDt, sp_centerDt); //时间段内所有 审批数据
- ApprovalDataView approvalData_2 = await GetApprovalDataAsync(sp_centerDt, sp_endDt); //时间段内所有 审批数据
- if (approvalData_1.errcode != 0)
- {
- Log.Error("企业微信 获取 " + sp_startDt + " - " + sp_centerDt + " 内审批 Msg:" + approvalData_1.errmsg);
- return sp_Infos;
- }
- sp_Infos.AddRange(approvalData_1.data);
- if (approvalData_2.errcode != 0)
- {
- Log.Error("企业微信 获取 " + sp_centerDt + " - " + sp_endDt + " 内审批 Msg:" + approvalData_2.errmsg);
- return sp_Infos;
- }
- sp_Infos.AddRange(approvalData_2.data);
- sp_Infos = sp_Infos.Where(it => it.sp_status == 2).ToList(); //存储已审核的数据
- return sp_Infos;
- }
- /// <summary>
- /// 获取审批数据(旧)(redis缓存)
- /// </summary>
- /// <param name="startDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- public async Task<List<Sp_Info>> GetApprovalDatasRedisAsync(DateTime startDt, DateTime endDt)
- {
- List<Sp_Info> sp_Infos = new List<Sp_Info>();
- //获取所有打卡补卡,审批 数据 前后范围增加10天
- DateTime sp_startDt = startDt.AddDays(-10);
- DateTime sp_centerDt = sp_startDt.AddDays(30);
- DateTime sp_endDt = endDt.AddDays(10);
- string redisName = "ApprovalData" + sp_startDt.ToString("yyyyMMdd") + "-" + sp_endDt.ToString("yyyyMMdd");
- string sp_InfosString = string.Empty;
- //sp_InfosString = await RedisRepository.RedisFactory
- // .CreateRedisRepository()
- // .StringGetAsync<string>(redisName);//string 取
- if (string.IsNullOrEmpty(sp_InfosString))
- {
- ApprovalDataView approvalData_1 = await GetApprovalDataAsync(sp_startDt, sp_centerDt); //时间段内所有 审批数据
- ApprovalDataView approvalData_2 = await GetApprovalDataAsync(sp_centerDt, sp_endDt); //时间段内所有 审批数据
- if (approvalData_1.errcode != 0)
- {
- Log.Error("企业微信 获取 "+ sp_startDt + " - "+ sp_centerDt + " 内审批 Msg:" + approvalData_1.errmsg);
- return sp_Infos;
- }
- sp_Infos.AddRange(approvalData_1.data);
- if (approvalData_2.errcode != 0)
- {
- Log.Error("企业微信 获取 "+ sp_centerDt + " - "+ sp_endDt + " 内审批 Msg:" + approvalData_2.errmsg);
- return sp_Infos;
- }
- sp_Infos.AddRange(approvalData_2.data);
- sp_Infos = sp_Infos.Where(it => it.sp_status == 2).ToList(); //存储已审核的数据
- TimeSpan ts = DateTime.Now.AddMinutes(60) - DateTime.Now; //设置redis 过期时间 60分钟
- await RedisRepository
- .RedisFactory
- .CreateRedisRepository()
- .StringSetAsync<string>(redisName, JsonConvert.SerializeObject(sp_Infos), ts);//string 存
- }
- else
- {
- sp_Infos = JsonConvert.DeserializeObject<List<Sp_Info>>(sp_InfosString);
- }
- return sp_Infos;
- }
- #endregion
- }
- }
|