Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

606 rader
24 KiB

  1. using Learun.Application.Organization;
  2. using Learun.Application.WeChat.WeChat;
  3. using Learun.Util;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Net;
  8. using System.Text;
  9. using System.Web.Mvc;
  10. namespace Learun.Application.Web.Areas.LR_WebChatModule.Controllers
  11. {
  12. /// <summary>
  13. /// 版 本 Learun-ADMS-Ultimate V7.0.0 数字化智慧校园
  14. /// Copyright (c) 2013-2018 北京泉江科技有限公司
  15. /// 创建人:陈彬彬
  16. /// 日 期:2017.04.01
  17. /// 描 述:企业号部门同步
  18. /// </summary>
  19. public class OrganizeController : MvcControllerBase
  20. {
  21. private UserIBLL userIBLL = new UserBLL();
  22. private static Access_tokenWithTime mode = new Access_tokenWithTime();
  23. private DepartmentIBLL departmentIBLL = new DepartmentBLL();
  24. private CompanyIBLL companyIBLL = new CompanyBLL();
  25. //List表单数据
  26. private static List<UserEntity> Userlist;
  27. #region 视图功能
  28. /// <summary>
  29. /// 部门主界面
  30. /// </summary>
  31. /// <returns></returns>
  32. [HttpGet]
  33. public ActionResult Index()
  34. {
  35. return View();
  36. }
  37. /// <summary>
  38. /// 同步员工
  39. /// </summary>
  40. /// <returns></returns>
  41. [HttpGet]
  42. public ActionResult MemberForm()
  43. {
  44. return View();
  45. }
  46. #endregion
  47. #region 获取数据
  48. /// <summary>
  49. /// 获取部门列表
  50. /// </summary>
  51. /// <param name="keyword">关键字</param>
  52. /// <returns></returns>
  53. [HttpGet]
  54. [AjaxOnly]
  55. public ActionResult GetTreeList(string keyword)
  56. {
  57. //获取微信部门数据
  58. WXDepartmentListEntity wXDepartmentList = GetDepartmentList("");
  59. if (wXDepartmentList.errcode != 0)
  60. {
  61. return Fail("微信接口错误码" + wXDepartmentList.errcode + ",错误信息" + wXDepartmentList.errmsg);
  62. }
  63. else
  64. {
  65. //转换成dic数据
  66. Dictionary<string, string> dir = new Dictionary<string, string>();
  67. foreach (var item in wXDepartmentList.department)
  68. {
  69. dir.Add(item.id.ToString(), item.name);
  70. }
  71. //获取内部系统公司部门列表
  72. var data = companyIBLL.GetWeChatList(keyword);
  73. //判断是否同步过
  74. foreach (var item in data)
  75. {
  76. if (dir.ContainsKey(item.F_EnCode) && dir[item.F_EnCode] == item.F_FullName + "1")
  77. {
  78. item.F_Fax = "已同步";
  79. }
  80. else
  81. {
  82. item.F_Fax = "未同步";
  83. }
  84. }
  85. return JsonResult(data);
  86. }
  87. }
  88. /// <summary>
  89. /// 同步部门
  90. /// </summary>
  91. /// <param name="keyword">关键字</param>
  92. /// <returns></returns>
  93. public ActionResult Sync()
  94. {
  95. //获取微信部门数据
  96. WXDepartmentListEntity wXDepartmentList = GetDepartmentList("");
  97. if (wXDepartmentList.errcode != 0)
  98. {
  99. return Fail("微信接口错误码" + wXDepartmentList.errcode + ",错误信息" + wXDepartmentList.errmsg);
  100. }
  101. else
  102. {
  103. Dictionary<string, string> dir = new Dictionary<string, string>();
  104. foreach (var item in wXDepartmentList.department)
  105. {
  106. dir.Add(item.id.ToString(), item.name);
  107. }
  108. var data = companyIBLL.GetWeChatList("");
  109. foreach (var item in data)
  110. {
  111. WX_DepartmentEntity entity = new WX_DepartmentEntity();
  112. if (dir.ContainsKey(item.F_EnCode))
  113. {
  114. //在微信中修改部门
  115. entity.F_WXId = item.F_EnCode.ToInt();
  116. entity.F_Name = item.F_FullName;
  117. var parentEntity = data.Find(i => i.F_CompanyId == item.F_ParentId);
  118. if (parentEntity != null)
  119. {
  120. entity.F_ParentId = parentEntity.F_EnCode.ToInt();
  121. }
  122. else
  123. {
  124. entity.F_ParentId = 1;
  125. }
  126. var res = UpdateDepartment(entity);
  127. if (res.errcode != 0)
  128. {
  129. item.F_Description = "微信接口错误码" + res.errcode + ",错误信息" + res.errmsg;
  130. companyIBLL.SaveEntity(item.F_CompanyId, item);
  131. //return Fail("微信接口错误码" + res.errcode + ",错误信息" + res.errmsg);
  132. continue;
  133. }
  134. }
  135. else
  136. {
  137. entity.F_WXId = item.F_EnCode.ToInt();
  138. entity.F_Name = item.F_FullName + "1";
  139. var parentEntity = data.Find(i => i.F_CompanyId == item.F_ParentId);
  140. if (parentEntity != null)
  141. {
  142. entity.F_ParentId = parentEntity.F_EnCode.ToInt();
  143. }
  144. else
  145. {
  146. entity.F_ParentId = 1;
  147. }
  148. //在微信中创建部门
  149. var res = CreateDepartment(entity);
  150. if (res.errcode != 0)
  151. {
  152. item.F_Description = "微信接口错误码" + res.errcode + ",错误信息" + res.errmsg;
  153. companyIBLL.SaveEntity(item.F_CompanyId, item);
  154. //return Fail("微信接口错误码" + res.errcode + ",错误信息" + res.errmsg);
  155. continue;
  156. }
  157. }
  158. }
  159. return JsonResult(data);
  160. }
  161. }
  162. /// <summary>
  163. /// 获取微信人员同步左侧部门信息
  164. /// </summary>
  165. /// <returns></returns>
  166. [HttpGet]
  167. [AjaxOnly]
  168. public ActionResult GetLeftTree(string parentId)
  169. {
  170. var data = companyIBLL.GetWeChatTree(parentId);
  171. return JsonResult(data);
  172. }
  173. /// <summary>
  174. /// 获取微信人员同步右侧同步信息
  175. /// </summary>
  176. /// <param name="companyId">微信公司Id</param>
  177. /// <param name="keyword">查询关键字</param>
  178. /// <param name="departmentId">部门Id</param>
  179. /// <returns></returns>
  180. public ActionResult GetUserPageList(string pagination, string keyword, string companyId, string departmentId)
  181. {
  182. Pagination paginationobj = pagination.ToObject<Pagination>();
  183. //获取内部系统人员列表
  184. var data = userIBLL.GetPageList(companyId, departmentId, paginationobj, keyword,"");
  185. //获取微信员工列表
  186. var wxData = GetUserList("1", 1);
  187. if (wxData.errcode != 0)
  188. {
  189. return Fail("微信接口错误码" + wxData.errcode + ",错误信息" + wxData.errmsg);
  190. }
  191. #region 判断数据是否相同
  192. Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
  193. foreach (var i in wxData.userlist)
  194. {
  195. dic.Add(i.userid, new List<string> { i.name, i.mobile });
  196. }
  197. foreach (var item in data)
  198. {
  199. if (dic.ContainsKey(item.F_Account))
  200. {
  201. if (item.F_RealName != dic[item.F_Account][0])
  202. {
  203. item.F_AnswerQuestion = "未同步";
  204. }
  205. else
  206. {
  207. item.F_AnswerQuestion = "已同步";
  208. }
  209. }
  210. else
  211. {
  212. item.F_AnswerQuestion = "未同步";
  213. }
  214. }
  215. #endregion
  216. Userlist = data;
  217. var jsonData = new
  218. {
  219. rows = data,
  220. total = paginationobj.total,
  221. page = paginationobj.page,
  222. records = paginationobj.records,
  223. };
  224. return JsonResult(jsonData);
  225. }
  226. /// <summary>
  227. /// 同步员工
  228. /// </summary>
  229. /// <param name="keyword">关键字</param>
  230. /// <returns></returns>
  231. public ActionResult SyncMember()
  232. {
  233. //获取微信部门数据
  234. UserListEntity wXUserList = GetSimpleUserList("1", 1);
  235. if (wXUserList.errcode != 0)
  236. {
  237. return Fail("微信接口错误码" + wXUserList.errcode + ",错误信息" + wXUserList.errmsg);
  238. }
  239. else
  240. {
  241. Dictionary<string, string> dir = new Dictionary<string, string>();
  242. foreach (var item in wXUserList.userlist)
  243. {
  244. dir.Add(item.userid, item.name);
  245. }
  246. //获取当前
  247. var data = userIBLL.GetAllList();
  248. foreach (var item in data)
  249. {
  250. WeChatUserEntity userEntity = new WeChatUserEntity();
  251. if (string.IsNullOrEmpty(item.F_DepartmentId) || string.IsNullOrEmpty(item.F_Mobile)) continue;
  252. if (dir.ContainsKey(item.F_Account))
  253. {
  254. if (dir[item.F_Account] != item.F_RealName)
  255. {
  256. userEntity.name = item.F_RealName;
  257. userEntity.mobile = item.F_Mobile;
  258. userEntity.userid = item.F_Account;
  259. userEntity.enable = 1;
  260. if (item.F_DepartmentId != null)
  261. {
  262. var departmentEntity = departmentIBLL.GetEntity(item.F_DepartmentId);
  263. userEntity.department = new List<int> { departmentEntity == null ? 0 : departmentEntity.F_EnCode.ToInt() };
  264. }
  265. else
  266. {
  267. var companyEntity = companyIBLL.GetEntity(item.F_CompanyId);
  268. userEntity.department = new List<int> { companyEntity == null ? 0 : companyEntity.F_EnCode.ToInt() };
  269. }
  270. //更新微信部门成员
  271. //var res = UpdateWXUser(userEntity);
  272. //if (res.errcode != 0)
  273. //{
  274. // item.F_Description = "微信接口错误码" + res.errcode + ",错误信息" + res.errmsg;
  275. // userIBLL.SaveEntity(item.F_UserId, item);
  276. // return Fail("微信接口错误码" + res.errcode + ",错误信息" + res.errmsg);
  277. // //continue;
  278. //}
  279. }
  280. else
  281. {
  282. continue;
  283. }
  284. }
  285. else
  286. {
  287. userEntity.name = item.F_RealName;
  288. userEntity.mobile = item.F_Mobile;
  289. userEntity.userid = item.F_Account;
  290. userEntity.enable = 1;
  291. if (item.F_DepartmentId != null)
  292. {
  293. var departmentEntity = departmentIBLL.GetEntity(item.F_DepartmentId);
  294. userEntity.department = new List<int> { departmentEntity == null ? 0 : departmentEntity.F_EnCode.ToInt() };
  295. }
  296. else
  297. {
  298. var companyEntity = companyIBLL.GetEntity(item.F_CompanyId);
  299. userEntity.department = new List<int> { companyEntity == null ? 0 : companyEntity.F_EnCode.ToInt() };
  300. }
  301. //创建微部门成员
  302. var res = CreateWXUser(userEntity);
  303. if (res.errcode != 0)
  304. {
  305. item.F_Description = "微信接口错误码" + res.errcode + ",错误信息" + res.errmsg;
  306. userIBLL.SaveEntity(item.F_UserId, item);
  307. //return Fail("微信接口错误码" + res.errcode + ",错误信息" + res.errmsg);
  308. continue;
  309. }
  310. }
  311. }
  312. return Success("");
  313. }
  314. }
  315. #endregion
  316. #region 微信接口方法
  317. /// <summary>
  318. /// 判断token是否过期
  319. /// </summary>
  320. /// <returns></returns>
  321. public Access_TokenEntity IsExistAccess_Token()
  322. {
  323. if (mode.token != null)
  324. {
  325. TimeSpan st1 = new TimeSpan(mode.time.Ticks); //最后刷新的时间
  326. TimeSpan st2 = new TimeSpan(DateTime.Now.Ticks); //当前时间
  327. TimeSpan st = st2 - st1; //两者相差时间
  328. if (st.TotalSeconds > mode.token.expires_in)
  329. {
  330. mode.token = GetToken();
  331. mode.time = DateTime.Now;
  332. }
  333. }
  334. else
  335. {
  336. mode.token = GetToken();
  337. mode.time = DateTime.Now;
  338. }
  339. return mode.token;
  340. }
  341. /// <summary>
  342. /// 获取微信token
  343. /// </summary>
  344. /// <returns></returns>
  345. public Access_TokenEntity GetToken()
  346. {
  347. var corpId = Config.GetValue("CorpId");
  348. var corpSecret = Config.GetValue("CorpSecret");
  349. string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + corpSecret;
  350. Access_TokenEntity token = new Access_TokenEntity();
  351. token = HttpGet(url).ToObject<Access_TokenEntity>();
  352. return token;
  353. }
  354. /// <summary>
  355. /// 获取微信账户
  356. /// </summary>
  357. /// <param name="userId">用户账户</param>
  358. public GetUserEntity GetWeChatUser(string userId)
  359. {
  360. var token = IsExistAccess_Token();
  361. string url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + token.access_token + "&userid=" + userId;
  362. GetUserEntity account = new GetUserEntity();
  363. account = HttpGet(url).ToObject<GetUserEntity>();
  364. return account;
  365. }
  366. /// <summary>
  367. /// 获取部门成员
  368. /// </summary>
  369. /// <param name="departmentId"></param>
  370. /// <param name="fetchchild"></param>
  371. /// <returns></returns>
  372. public UserListEntity GetSimpleUserList(string departmentId, int fetchchild)
  373. {
  374. var token = IsExistAccess_Token();
  375. string url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=" + token.access_token + "&department_id=" + departmentId + "&fetch_child=" + fetchchild;
  376. UserListEntity account = new UserListEntity();
  377. account = HttpGet(url).ToObject<UserListEntity>();
  378. return account;
  379. }
  380. /// <summary>
  381. /// 获取部门列表
  382. /// </summary>
  383. /// <param name="departmentId"></param>
  384. /// <param name="fetchchild"></param>
  385. /// <returns></returns>
  386. public WXDepartmentListEntity GetDepartmentList(string departmentId)
  387. {
  388. var token = IsExistAccess_Token();
  389. string url = " https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + token.access_token + "&id=" + departmentId;
  390. WXDepartmentListEntity res = new WXDepartmentListEntity();
  391. res = HttpGet(url).ToObject<WXDepartmentListEntity>();
  392. return res;
  393. }
  394. /// <summary>
  395. /// 获取部门成员详情
  396. /// </summary>
  397. /// <param name="departmentId"></param>
  398. /// <param name="fetchchild"></param>
  399. /// <returns></returns>
  400. public UserDetailListEntity GetUserList(string departmentId, int fetchchild)
  401. {
  402. var token = IsExistAccess_Token();
  403. string url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=" + token.access_token + "&department_id=" + departmentId + "&fetch_child=" + fetchchild;
  404. UserDetailListEntity account = new UserDetailListEntity();
  405. account = HttpGet(url).ToObject<UserDetailListEntity>();
  406. return account;
  407. }
  408. /// <summary>
  409. /// 创建微信账户
  410. /// </summary>
  411. /// <param name="entity"></param>
  412. public ReturnMessageEntity CreateWXUser(WeChatUserEntity account)
  413. {
  414. var token = IsExistAccess_Token();
  415. var url = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=" + token.access_token;
  416. ReturnMessageEntity res = new ReturnMessageEntity();
  417. res = HttpPost(url, account.ToJson()).ToObject<ReturnMessageEntity>();
  418. return res;
  419. }
  420. /// <summary>
  421. /// 更新微信账户
  422. /// </summary>
  423. /// <param name="entity"></param>
  424. public ReturnMessageEntity UpdateWXUser(WeChatUserEntity account)
  425. {
  426. var token = IsExistAccess_Token();
  427. var url = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=" + token.access_token;
  428. ReturnMessageEntity res = new ReturnMessageEntity();
  429. res = HttpPost(url, account.ToJson()).ToObject<ReturnMessageEntity>();
  430. return res;
  431. }
  432. /// <summary>
  433. /// 删除微信账户
  434. /// </summary>
  435. /// <param name="userId"></param>
  436. /// <returns></returns>
  437. public ReturnMessageEntity DeleteWeChatUser(string userId)
  438. {
  439. var token = IsExistAccess_Token();
  440. string url = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=" + token.access_token + "&userid=" + userId;
  441. ReturnMessageEntity res = new ReturnMessageEntity();
  442. res = HttpGet(url).ToObject<ReturnMessageEntity>();
  443. return res;
  444. }
  445. /// <summary>
  446. /// 批量删除微信账户
  447. /// </summary>
  448. /// <param name="userId"></param>
  449. /// <returns></returns>
  450. public ReturnMessageEntity BatchDeleteWeChatUser(List<string> userId)
  451. {
  452. var token = IsExistAccess_Token();
  453. BatchDelete list = new BatchDelete();
  454. list.useridlist = userId;
  455. string url = "https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=" + token.access_token;
  456. ReturnMessageEntity res = new ReturnMessageEntity();
  457. res = HttpPost(url, list.ToString()).ToObject<ReturnMessageEntity>();
  458. return res;
  459. }
  460. /// <summary>
  461. /// 创建微信部门
  462. /// </summary>
  463. /// <param name="entity"></param>
  464. /// <returns></returns>
  465. public WXDepartmentReMsgEntity CreateDepartment(WX_DepartmentEntity entity)
  466. {
  467. WXDepartmentEntity dep = new WXDepartmentEntity();
  468. dep.name = entity.F_Name;
  469. dep.id = entity.F_WXId;
  470. dep.parentid = entity.F_ParentId;
  471. dep.order = entity.F_Order;
  472. var token = IsExistAccess_Token();
  473. var url = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=" + token.access_token;
  474. WXDepartmentReMsgEntity res = new WXDepartmentReMsgEntity();
  475. res = HttpPost(url, dep.ToJson()).ToObject<WXDepartmentReMsgEntity>();
  476. return res;
  477. }
  478. /// <summary>
  479. /// 更新微信部门
  480. /// </summary>
  481. /// <param name="entity"></param>
  482. /// <returns></returns>
  483. public WXDepartmentReMsgEntity UpdateDepartment(WX_DepartmentEntity entity)
  484. {
  485. WXDepartmentEntity dep = new WXDepartmentEntity();
  486. dep.name = entity.F_Name;
  487. dep.id = entity.F_WXId;
  488. dep.parentid = entity.F_ParentId;
  489. dep.order = entity.F_Order;
  490. var token = IsExistAccess_Token();
  491. var url = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=" + token.access_token;
  492. WXDepartmentReMsgEntity res = new WXDepartmentReMsgEntity();
  493. res = HttpPost(url, dep.ToJson()).ToObject<WXDepartmentReMsgEntity>();
  494. return res;
  495. }
  496. /// <summary>
  497. /// 删除微信部门
  498. /// </summary>
  499. /// <param name="departmentId"></param>
  500. /// <returns></returns>
  501. public ReturnMessageEntity DeleteDepartment(string departmentId)
  502. {
  503. var token = IsExistAccess_Token();
  504. string url = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=" + token.access_token + "&id=" + departmentId;
  505. ReturnMessageEntity res = new ReturnMessageEntity();
  506. res = HttpGet(url).ToObject<ReturnMessageEntity>();
  507. return res;
  508. }
  509. #endregion
  510. #region 实体类
  511. /// <summary>
  512. /// token-time类
  513. /// </summary>
  514. public class Access_tokenWithTime
  515. {
  516. public DateTime time { get; set; }
  517. public Access_TokenEntity token { get; set; }
  518. }
  519. public class BatchDelete
  520. {
  521. public List<string> useridlist { get; set; }
  522. }
  523. #endregion
  524. #region HTTP操作
  525. public string HttpGet(string Url)
  526. {
  527. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  528. request.Method = "GET";
  529. request.ContentType = "text/html;charset=UTF-8";
  530. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  531. Stream myResponseStream = response.GetResponseStream();
  532. StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
  533. string retString = myStreamReader.ReadToEnd();
  534. myStreamReader.Close();
  535. myResponseStream.Close();
  536. return retString;
  537. }
  538. public string HttpPost(string Url, string postDataStr)
  539. {
  540. //创建一个HTTP请求
  541. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  542. //Post请求方式
  543. request.Method = "POST";
  544. //内容类型
  545. request.ContentType = "application/x-www-form-urlencoded";
  546. //设置参数,并进行URL编码
  547. string paraUrlCoded = postDataStr;//System.Web.HttpUtility.UrlEncode(jsonParas);
  548. byte[] payload;
  549. //将Json字符串转化为字节
  550. payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
  551. //设置请求的ContentLength
  552. request.ContentLength = payload.Length;
  553. //发送请求,获得请求流
  554. Stream writer;
  555. try
  556. {
  557. writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
  558. }
  559. catch (Exception)
  560. {
  561. writer = null;
  562. Console.Write("连接服务器失败!");
  563. }
  564. //将请求参数写入流
  565. writer.Write(payload, 0, payload.Length);
  566. writer.Close();//关闭请求流
  567. HttpWebResponse response;
  568. try
  569. {
  570. //获得响应流
  571. response = (HttpWebResponse)request.GetResponse();
  572. }
  573. catch (WebException ex)
  574. {
  575. response = ex.Response as HttpWebResponse;
  576. }
  577. Stream s = response.GetResponseStream();
  578. Stream postData = Request.InputStream;
  579. StreamReader sRead = new StreamReader(s);
  580. string postContent = sRead.ReadToEnd();
  581. sRead.Close();
  582. return postContent;//返回Json数据
  583. }
  584. #endregion
  585. }
  586. }