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

409 строки
17 KiB

  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. if (!string.IsNullOrEmpty(responsejson))
  107. {
  108. var weixintokenobj = JsonConvert.DeserializeObject<dynamic>(responsejson);
  109. if (string.IsNullOrEmpty(weixintokenobj.errcode))
  110. {
  111. string openid = weixintokenobj.openid;
  112. var userEntity = userIbll.GetEntityByWeixinOpenId(openid);
  113. if (userEntity != null)
  114. {
  115. ReqParameter req = this.Bind<ReqParameter>();
  116. string token = OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_ADMS_6.1_App", req.loginMark, false);//写入缓存信息
  117. #region 写入日志
  118. LogEntity logEntity = new LogEntity();
  119. logEntity.F_CategoryId = 1;
  120. logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
  121. logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
  122. logEntity.F_OperateAccount = userEntity.F_Account + "(" + userEntity.F_RealName + ")";
  123. logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : userEntity.F_Account;
  124. logEntity.F_Module = Config.GetValue("SoftName");
  125. logEntity.F_Description = "移动端";
  126. #endregion
  127. //写入日志
  128. logEntity.F_ExecuteResult = 1;
  129. logEntity.F_ExecuteResultJson = "登录成功";
  130. logEntity.WriteLog();
  131. OperatorResult res = OperatorHelper.Instance.IsOnLine(token, req.loginMark);
  132. res.userInfo.password = null;
  133. res.userInfo.secretkey = null;
  134. var studententity = stuInfoBasicIBLL.GetStuInfoBasicEntityByStuNo(userEntity.F_Account);
  135. if (studententity != null)
  136. {
  137. var majorinfo = majorIbll.GetCdMajorEntityByMajorNo(studententity.MajorNo);
  138. if (majorinfo != null)
  139. {
  140. res.userInfo.majorno = majorinfo.ID ?? "";
  141. }
  142. }
  143. var jsonData = new
  144. {
  145. logined = true,
  146. baseinfo = res.userInfo,
  147. post = postIBLL.GetListByPostIds(res.userInfo.postIds),
  148. role = roleIBLL.GetListByRoleIds(res.userInfo.roleIds)
  149. };
  150. return Success(jsonData);
  151. }
  152. else
  153. {
  154. return Success(JsonConvert.DeserializeObject(responsejson));
  155. }
  156. }
  157. else
  158. {
  159. return Fail("微信授权失败,请重试。");
  160. }
  161. }
  162. return Fail("微信授权失败,请重试。");
  163. }
  164. private Response Login(dynamic _)
  165. {
  166. LoginModel loginModel = this.GetReqData<LoginModel>();
  167. #region 内部账户验证
  168. UserEntity userEntity = userIbll.CheckLogin(loginModel.username, loginModel.password);
  169. #region 写入日志
  170. LogEntity logEntity = new LogEntity();
  171. logEntity.F_CategoryId = 1;
  172. logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
  173. logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
  174. logEntity.F_OperateAccount = loginModel.username + "(" + userEntity.F_RealName + ")";
  175. logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : loginModel.username;
  176. logEntity.F_Module = Config.GetValue("SoftName");
  177. logEntity.F_Description = "移动端";
  178. #endregion
  179. if (!userEntity.LoginOk)//登录失败
  180. {
  181. //写入日志
  182. logEntity.F_ExecuteResult = 0;
  183. logEntity.F_ExecuteResultJson = "登录失败:" + userEntity.LoginMsg;
  184. logEntity.WriteLog();
  185. return Fail(userEntity.LoginMsg);
  186. }
  187. else
  188. {
  189. ReqParameter req = this.Bind<ReqParameter>();
  190. string token = OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_ADMS_6.1_App", req.loginMark, false);//写入缓存信息
  191. //写入日志
  192. logEntity.F_ExecuteResult = 1;
  193. logEntity.F_ExecuteResultJson = "登录成功";
  194. logEntity.WriteLog();
  195. //保存用户设备号
  196. userIbll.UpdateWeixinOpenId(userEntity.F_UserId, loginModel.openid);
  197. OperatorResult res = OperatorHelper.Instance.IsOnLine(token, req.loginMark);
  198. res.userInfo.password = null;
  199. res.userInfo.secretkey = null;
  200. var studententity = stuInfoBasicIBLL.GetStuInfoBasicEntityByStuNo(userEntity.F_Account);
  201. if (studententity != null)
  202. {
  203. var majorinfo = majorIbll.GetCdMajorEntityByMajorNo(studententity.MajorNo);
  204. if (majorinfo != null)
  205. {
  206. res.userInfo.majorno = majorinfo.ID ?? "";
  207. }
  208. }
  209. var jsonData = new
  210. {
  211. baseinfo = res.userInfo,
  212. post = postIBLL.GetListByPostIds(res.userInfo.postIds),
  213. role = roleIBLL.GetListByRoleIds(res.userInfo.roleIds)
  214. };
  215. return Success(jsonData);
  216. }
  217. #endregion
  218. }
  219. public Response GetWeixinWebaccess_token(dynamic _)
  220. {
  221. var entity = weChatConfigIbll.GetEnableEntity();
  222. string appid = entity?.APPId;
  223. string secret = entity?.secret;
  224. string url = Request.Query["url"];
  225. var responsejson = HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
  226. if (!string.IsNullOrEmpty(responsejson))
  227. {
  228. var weixintokenobj = JsonConvert.DeserializeObject<dynamic>(responsejson);
  229. if (string.IsNullOrEmpty(weixintokenobj.errcode))
  230. {
  231. string access_token = weixintokenobj.access_token;
  232. string jsapi_ticket = HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi");
  233. var weixinjsapiticketobj = JsonConvert.DeserializeObject<dynamic>(jsapi_ticket);
  234. if (weixinjsapiticketobj.errcode == 0)
  235. {
  236. string ticket = weixinjsapiticketobj.ticket;
  237. //生成签名
  238. string noncestr = Util.CommonHelper.CreateNo();
  239. string timestamp = GetTimeStamp(true);
  240. string param = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
  241. string certificate = SHA1(param).ToLower();
  242. return Success(new { appid, noncestr, timestamp, certificate });
  243. }
  244. else
  245. {
  246. return Fail("微信授权失败,请重试。" + weixinjsapiticketobj.errcode + weixinjsapiticketobj.errmsg);
  247. }
  248. }
  249. else
  250. {
  251. return Fail("微信授权失败,请重试。" + weixintokenobj.errcode + weixintokenobj.errmsg);
  252. }
  253. }
  254. else
  255. {
  256. return Fail("微信授权失败,请重试。");
  257. }
  258. }
  259. /// <summary>
  260. /// 发起一个HTTP请求(以GET方式)
  261. /// </summary>
  262. /// <param name="url"></param>
  263. /// <returns></returns>
  264. public string HttpGet(string url)
  265. {
  266. WebRequest myWebRequest = WebRequest.Create(url);
  267. WebResponse myWebResponse = myWebRequest.GetResponse();
  268. Stream ReceiveStream = myWebResponse.GetResponseStream();
  269. string responseStr = "";
  270. if (ReceiveStream != null)
  271. {
  272. StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
  273. responseStr = reader.ReadToEnd();
  274. reader.Close();
  275. }
  276. myWebResponse.Close();
  277. return responseStr;
  278. }
  279. /// <summary>
  280. /// 获取当前时间戳
  281. /// </summary>
  282. /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.bool bflag = true</param>
  283. /// <returns></returns>
  284. public static string GetTimeStamp(bool bflag)
  285. {
  286. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  287. string ret = string.Empty;
  288. if (bflag)
  289. ret = Convert.ToInt64(ts.TotalSeconds).ToString();
  290. else
  291. ret = Convert.ToInt64(ts.TotalMilliseconds).ToString();
  292. return ret;
  293. }
  294. // <summary>
  295. /// SHA1 加密,返回大写字符串
  296. /// </summary>
  297. /// <param name="content">需要加密字符串</param>
  298. /// <returns>返回40位UTF8 大写</returns>
  299. public static string SHA1(string content)
  300. {
  301. return SHA1(content, Encoding.UTF8);
  302. }
  303. /// <summary>
  304. /// SHA1 加密,返回大写字符串
  305. /// </summary>
  306. /// <param name="content">需要加密字符串</param>
  307. /// <param name="encode">指定加密编码</param>
  308. /// <returns>返回40位大写字符串</returns>
  309. public static string SHA1(string content, Encoding encode)
  310. {
  311. try
  312. {
  313. SHA1 sha1 = new SHA1CryptoServiceProvider();
  314. byte[] bytes_in = encode.GetBytes(content);
  315. byte[] bytes_out = sha1.ComputeHash(bytes_in);
  316. sha1.Dispose();
  317. string result = BitConverter.ToString(bytes_out);
  318. result = result.Replace("-", "");
  319. return result;
  320. }
  321. catch (Exception ex)
  322. {
  323. throw new Exception("SHA1加密出错:" + ex.Message);
  324. }
  325. }
  326. /// <summary>
  327. /// 获取IP
  328. /// </summary>
  329. /// <returns></returns>
  330. private string GetIP()
  331. {
  332. //string ip = string.Empty;
  333. //if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
  334. // ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
  335. //if (string.IsNullOrEmpty(ip))
  336. // ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
  337. //return ip;
  338. string userIP = "未获取用户IP";
  339. try
  340. {
  341. if (System.Web.HttpContext.Current == null
  342. || System.Web.HttpContext.Current.Request == null
  343. || System.Web.HttpContext.Current.Request.ServerVariables == null)
  344. {
  345. return "";
  346. }
  347. string CustomerIP = "";
  348. //CDN加速后取到的IP simone 090805
  349. CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
  350. if (!string.IsNullOrEmpty(CustomerIP))
  351. {
  352. return CustomerIP;
  353. }
  354. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  355. if (!string.IsNullOrEmpty(CustomerIP))
  356. {
  357. return CustomerIP;
  358. }
  359. if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
  360. {
  361. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  362. if (CustomerIP == null)
  363. {
  364. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  365. }
  366. }
  367. else
  368. {
  369. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  370. }
  371. if (string.Compare(CustomerIP, "unknown", true) == 0 || string.IsNullOrEmpty(CustomerIP))
  372. {
  373. return System.Web.HttpContext.Current.Request.UserHostAddress;
  374. }
  375. return CustomerIP;
  376. }
  377. catch { }
  378. return userIP;
  379. }
  380. }
  381. }