Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

4 лет назад
4 лет назад
4 лет назад
1 год назад
4 лет назад
1 год назад
4 лет назад
4 лет назад
4 лет назад
4 лет назад
4 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. using Learun.Application.Base.SystemModule;
  2. using Learun.Util;
  3. using Nancy;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Configuration;
  7. using System.IO;
  8. using System.Linq.Expressions;
  9. using System.Net;
  10. using System.Security.Cryptography;
  11. using System.Text;
  12. using System.Web.Mvc;
  13. using System.Web.WebSockets;
  14. using Learun.Application.Organization;
  15. using Learun.Application.TwoDevelopment.EducationalAdministration;
  16. using Learun.Application.TwoDevelopment.LR_Desktop;
  17. using Learun.Util.Operat;
  18. using Nancy.ModelBinding;
  19. using Nancy.Responses;
  20. using Newtonsoft.Json;
  21. namespace Learun.Application.WebApi.Modules
  22. {
  23. public class WeixinApi : BaseNoAuthentication
  24. {
  25. private UserIBLL userIbll = new UserBLL();
  26. private PostIBLL postIBLL = new PostBLL();
  27. private RoleIBLL roleIBLL = new RoleBLL();
  28. private StuInfoBasicIBLL stuInfoBasicIBLL = new StuInfoBasicBLL();
  29. private WeChatConfigIBLL weChatConfigIbll = new WeChatConfigBLL();
  30. LR_Base_LogoIBLL baseLogoIbll = new LR_Base_LogoBLL();
  31. CdMajorIBLL majorIbll = new CdMajorBLL();
  32. public WeixinApi()
  33. : base("/weixinapi")
  34. {
  35. Get["/weixinconfig"] = GetWeixinConfig;
  36. Post["/getweixinaccess_token"] = GetWeixinAccess_token;
  37. Post["/login"] = Login;
  38. Get["/getweixinwebaccess_token"] = GetWeixinWebaccess_token;
  39. //获取ACIp
  40. Get["/GetACIp"] = GetACIp;
  41. //获取logo
  42. Get["/GetLogo"] = GetImg;
  43. }
  44. public Response GetImg(dynamic _)
  45. {
  46. string code = Request.Query["code"];
  47. string rootPath = ConfigurationManager.AppSettings["AnnexesFile"] + "\\";
  48. string midPath = "Content/images/logo";
  49. try
  50. {
  51. LR_Base_LogoEntity logoEntity = baseLogoIbll.GetLR_Base_LogoEntityByCode(code);
  52. if (logoEntity != null)
  53. {
  54. return new GenericFileResponse(logoEntity.F_FileName, "image/jpeg");
  55. }
  56. else
  57. {
  58. switch (code)
  59. {
  60. case "default":
  61. return new GenericFileResponse(Path.Combine(rootPath, midPath, "default.png"), "image/jpeg");
  62. case "accordion":
  63. return new GenericFileResponse(Path.Combine(rootPath, midPath, "accordion.png"), "image/jpeg");
  64. case "windows":
  65. return new GenericFileResponse(Path.Combine(rootPath, midPath, "windows.png"), "image/jpeg");
  66. case "top":
  67. return new GenericFileResponse(Path.Combine(rootPath, midPath, "top.png"), "image/jpeg");
  68. case "applogo":
  69. return new GenericFileResponse(Path.Combine(rootPath, midPath, "applogo.png"), "image/jpeg");
  70. }
  71. }
  72. }
  73. catch (Exception e)
  74. {
  75. Console.WriteLine(e);
  76. throw;
  77. }
  78. return null;
  79. }
  80. public Response GetACIp(dynamic _)
  81. {
  82. string Ip = GetIP();
  83. string ACIp = ConfigurationManager.AppSettings["ACIp"] ?? "";
  84. string ACIp2 = ConfigurationManager.AppSettings["ACIp2"] ?? "";
  85. return Success(new
  86. {
  87. Ip,
  88. ACIp,
  89. ACIp2
  90. });
  91. }
  92. public Response GetWeixinConfig(dynamic _)
  93. {
  94. var entity = weChatConfigIbll.GetEnableEntity();
  95. string appid = entity?.APPId;
  96. string secret = entity?.secret;
  97. return Success(new { appid, secret });
  98. }
  99. public Response GetWeixinAccess_token(dynamic _)
  100. {
  101. var entity = weChatConfigIbll.GetEnableEntity();
  102. string appid = entity?.APPId;
  103. string secret = entity?.secret;
  104. string code = Request.Query["code"];
  105. var responsejson = HttpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code");
  106. LogEntity logEntity = new LogEntity();
  107. logEntity.F_CategoryId = 1234;
  108. logEntity.F_OperateTypeId = ((int)OperationType.Visit).ToString();
  109. logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Visit);
  110. logEntity.F_OperateAccount = "wxlogin:access_token";
  111. logEntity.F_OperateUserId = "wxlogin:access_token";
  112. logEntity.F_Module = "wxlogin:access_token";
  113. logEntity.F_Description = "wxlogin:access_token";
  114. logEntity.F_SourceContentJson = responsejson;
  115. logEntity.WriteLog();
  116. if (!string.IsNullOrEmpty(responsejson))
  117. {
  118. var weixintokenobj = JsonConvert.DeserializeObject<dynamic>(responsejson);
  119. if (string.IsNullOrEmpty(weixintokenobj.errcode))
  120. {
  121. string openid = weixintokenobj.openid;
  122. var userEntity = userIbll.GetEntityByWeixinOpenId(openid);
  123. if (userEntity != null)
  124. {
  125. ReqParameter req = this.Bind<ReqParameter>();
  126. string token = OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_ADMS_6.1_App", req.loginMark, false);//写入缓存信息
  127. #region 写入日志
  128. logEntity = new LogEntity();
  129. logEntity.F_CategoryId = 1;
  130. logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
  131. logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
  132. logEntity.F_OperateAccount = userEntity.F_Account + "(" + userEntity.F_RealName + ")";
  133. logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : userEntity.F_Account;
  134. logEntity.F_Module = Config.GetValue("SoftName");
  135. logEntity.F_Description = "移动端";
  136. #endregion
  137. //写入日志
  138. logEntity.F_ExecuteResult = 1;
  139. logEntity.F_ExecuteResultJson = "登录成功";
  140. logEntity.WriteLog();
  141. OperatorResult res = OperatorHelper.Instance.IsOnLine(token, req.loginMark);
  142. res.userInfo.password = null;
  143. res.userInfo.secretkey = null;
  144. var studententity = stuInfoBasicIBLL.GetStuInfoBasicEntityByStuNo(userEntity.F_Account);
  145. if (studententity != null)
  146. {
  147. res.userInfo.grade = studententity.Grade;
  148. var majorinfo = majorIbll.GetCdMajorEntityByMajorNo(studententity.MajorNo);
  149. if (majorinfo != null)
  150. {
  151. res.userInfo.majorno = majorinfo.ID ?? "";
  152. }
  153. }
  154. var jsonData = new
  155. {
  156. logined = true,
  157. baseinfo = res.userInfo,
  158. post = postIBLL.GetListByPostIds(res.userInfo.postIds),
  159. role = roleIBLL.GetListByRoleIds(res.userInfo.roleIds)
  160. };
  161. return Success(jsonData);
  162. }
  163. else
  164. {
  165. return Success(JsonConvert.DeserializeObject(responsejson));
  166. }
  167. }
  168. else
  169. {
  170. return Fail("微信授权失败,请重试。");
  171. }
  172. }
  173. return Fail("微信授权失败,请重试。");
  174. }
  175. private Response Login(dynamic _)
  176. {
  177. LoginModel loginModel = this.GetReqData<LoginModel>();
  178. #region 内部账户验证
  179. UserEntity userEntity = userIbll.CheckLogin(loginModel.username, loginModel.password);
  180. #region 写入日志
  181. LogEntity logEntity = new LogEntity();
  182. logEntity.F_CategoryId = 1;
  183. logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
  184. logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
  185. logEntity.F_OperateAccount = loginModel.username + "(" + userEntity.F_RealName + ")";
  186. logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : loginModel.username;
  187. logEntity.F_Module = Config.GetValue("SoftName");
  188. logEntity.F_Description = "移动端";
  189. #endregion
  190. if (!userEntity.LoginOk)//登录失败
  191. {
  192. //写入日志
  193. logEntity.F_ExecuteResult = 0;
  194. logEntity.F_ExecuteResultJson = "登录失败:" + userEntity.LoginMsg;
  195. logEntity.WriteLog();
  196. return Fail(userEntity.LoginMsg);
  197. }
  198. else
  199. {
  200. ReqParameter req = this.Bind<ReqParameter>();
  201. string token = OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_ADMS_6.1_App", req.loginMark, false);//写入缓存信息
  202. //写入日志
  203. logEntity.F_ExecuteResult = 1;
  204. logEntity.F_ExecuteResultJson = "登录成功";
  205. logEntity.WriteLog();
  206. OperatorResult res = OperatorHelper.Instance.IsOnLine(token, req.loginMark);
  207. res.userInfo.password = null;
  208. res.userInfo.secretkey = null;
  209. var studententity = stuInfoBasicIBLL.GetStuInfoBasicEntityByStuNo(userEntity.F_Account);
  210. if (studententity != null)
  211. {
  212. res.userInfo.grade = studententity.Grade;
  213. var majorinfo = majorIbll.GetCdMajorEntityByMajorNo(studententity.MajorNo);
  214. if (majorinfo != null)
  215. {
  216. res.userInfo.majorno = majorinfo.ID ?? "";
  217. }
  218. }
  219. //是否强密码验证
  220. bool pwd = false;
  221. if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["verifypwd"]) && ConfigurationManager.AppSettings["verifypwd"] == "true" && loginModel.up == false)
  222. {
  223. pwd = true;
  224. }
  225. else
  226. {
  227. //保存用户设备号
  228. userIbll.UpdateWeixinOpenId(userEntity.F_UserId, loginModel.openid);
  229. }
  230. var jsonData = new
  231. {
  232. baseinfo = res.userInfo,
  233. post = postIBLL.GetListByPostIds(res.userInfo.postIds),
  234. role = roleIBLL.GetListByRoleIds(res.userInfo.roleIds),
  235. pwd = pwd
  236. };
  237. return Success(jsonData);
  238. }
  239. #endregion
  240. }
  241. public Response GetWeixinWebaccess_token(dynamic _)
  242. {
  243. var entity = weChatConfigIbll.GetEnableEntity();
  244. string appid = entity?.APPId;
  245. string secret = entity?.secret;
  246. string url = Request.Query["url"];
  247. var responsejson = HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
  248. if (!string.IsNullOrEmpty(responsejson))
  249. {
  250. var weixintokenobj = JsonConvert.DeserializeObject<dynamic>(responsejson);
  251. if (string.IsNullOrEmpty(weixintokenobj.errcode))
  252. {
  253. string access_token = weixintokenobj.access_token;
  254. string jsapi_ticket = HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi");
  255. var weixinjsapiticketobj = JsonConvert.DeserializeObject<dynamic>(jsapi_ticket);
  256. if (weixinjsapiticketobj.errcode == 0)
  257. {
  258. string ticket = weixinjsapiticketobj.ticket;
  259. //生成签名
  260. string noncestr = Util.CommonHelper.CreateNo();
  261. string timestamp = GetTimeStamp(true);
  262. string param = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
  263. string certificate = SHA1(param).ToLower();
  264. return Success(new { appid, noncestr, timestamp, certificate });
  265. }
  266. else
  267. {
  268. return Fail("微信授权失败,请重试。" + weixinjsapiticketobj.errcode + weixinjsapiticketobj.errmsg);
  269. }
  270. }
  271. else
  272. {
  273. return Fail("微信授权失败,请重试。" + weixintokenobj.errcode + weixintokenobj.errmsg);
  274. }
  275. }
  276. else
  277. {
  278. return Fail("微信授权失败,请重试。");
  279. }
  280. }
  281. /// <summary>
  282. /// 发起一个HTTP请求(以GET方式)
  283. /// </summary>
  284. /// <param name="url"></param>
  285. /// <returns></returns>
  286. public string HttpGet(string url)
  287. {
  288. WebRequest myWebRequest = WebRequest.Create(url);
  289. WebResponse myWebResponse = myWebRequest.GetResponse();
  290. Stream ReceiveStream = myWebResponse.GetResponseStream();
  291. string responseStr = "";
  292. if (ReceiveStream != null)
  293. {
  294. StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
  295. responseStr = reader.ReadToEnd();
  296. reader.Close();
  297. }
  298. myWebResponse.Close();
  299. return responseStr;
  300. }
  301. /// <summary>
  302. /// 获取当前时间戳
  303. /// </summary>
  304. /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.bool bflag = true</param>
  305. /// <returns></returns>
  306. public static string GetTimeStamp(bool bflag)
  307. {
  308. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  309. string ret = string.Empty;
  310. if (bflag)
  311. ret = Convert.ToInt64(ts.TotalSeconds).ToString();
  312. else
  313. ret = Convert.ToInt64(ts.TotalMilliseconds).ToString();
  314. return ret;
  315. }
  316. // <summary>
  317. /// SHA1 加密,返回大写字符串
  318. /// </summary>
  319. /// <param name="content">需要加密字符串</param>
  320. /// <returns>返回40位UTF8 大写</returns>
  321. public static string SHA1(string content)
  322. {
  323. return SHA1(content, Encoding.UTF8);
  324. }
  325. /// <summary>
  326. /// SHA1 加密,返回大写字符串
  327. /// </summary>
  328. /// <param name="content">需要加密字符串</param>
  329. /// <param name="encode">指定加密编码</param>
  330. /// <returns>返回40位大写字符串</returns>
  331. public static string SHA1(string content, Encoding encode)
  332. {
  333. try
  334. {
  335. SHA1 sha1 = new SHA1CryptoServiceProvider();
  336. byte[] bytes_in = encode.GetBytes(content);
  337. byte[] bytes_out = sha1.ComputeHash(bytes_in);
  338. sha1.Dispose();
  339. string result = BitConverter.ToString(bytes_out);
  340. result = result.Replace("-", "");
  341. return result;
  342. }
  343. catch (Exception ex)
  344. {
  345. throw new Exception("SHA1加密出错:" + ex.Message);
  346. }
  347. }
  348. /// <summary>
  349. /// 获取IP
  350. /// </summary>
  351. /// <returns></returns>
  352. private string GetIP()
  353. {
  354. //string ip = string.Empty;
  355. //if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
  356. // ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
  357. //if (string.IsNullOrEmpty(ip))
  358. // ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
  359. //return ip;
  360. string userIP = "未获取用户IP";
  361. try
  362. {
  363. if (System.Web.HttpContext.Current == null
  364. || System.Web.HttpContext.Current.Request == null
  365. || System.Web.HttpContext.Current.Request.ServerVariables == null)
  366. {
  367. return "";
  368. }
  369. string CustomerIP = "";
  370. //CDN加速后取到的IP simone 090805
  371. CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
  372. if (!string.IsNullOrEmpty(CustomerIP))
  373. {
  374. return CustomerIP;
  375. }
  376. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  377. if (!string.IsNullOrEmpty(CustomerIP))
  378. {
  379. return CustomerIP;
  380. }
  381. if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
  382. {
  383. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  384. if (CustomerIP == null)
  385. {
  386. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  387. }
  388. }
  389. else
  390. {
  391. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  392. }
  393. if (string.Compare(CustomerIP, "unknown", true) == 0 || string.IsNullOrEmpty(CustomerIP))
  394. {
  395. return System.Web.HttpContext.Current.Request.UserHostAddress;
  396. }
  397. return CustomerIP;
  398. }
  399. catch { }
  400. return userIP;
  401. }
  402. }
  403. }