public void GetOpenId(string state, string code) { if (code == null) { Response.Write("Null"); return; } string AppId = ConfigurationManager.AppSettings["wxAppId"].ToString(); string AppSecret = ConfigurationManager.AppSettings["wxAppSecret"].ToString(); string reg = string.Empty; wxLogin wxLogin = new wxLogin(); ACCESST ACCESST = wxLogin.GetWeiXinAccess(code, AppId, AppSecret, out reg); if (ACCESST.openid.IsNullOrEmpty()) { Response.Redirect("/Mobile/WeiXinErr.html?msg=您未授权,暂时不能参与活动"); return; } Response.Cookies.SetWXOpenId(ACCESST.openid); WeiXinUsers WeiXinUsers = Entity.WeiXinUsers.FirstOrNew(n => n.OpenId == ACCESST.openid); string BackUrl = ""; if (Request.QueryString["BackUrl"] != null) { if (!Request.QueryString["BackUrl"].ToString().IsNullOrEmpty()) { BackUrl = Request.QueryString["BackUrl"].ToString(); } } if (WeiXinUsers.Id == 0) { if (state == "Base") { string burl = "http://" + Utils.GetHostName() + "/Mobile/Weixin/GetOpenId.html?BackUrl=" + BackUrl + ""; burl = System.Web.HttpUtility.UrlEncode(burl); string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AppId + "&redirect_uri=" + burl + "&response_type=code&scope=snsapi_userinfo&state=UserInfo#wechat_redirect"; Response.Redirect(url); } if (state == "UserInfo") { WeiXinUser WeiXinUser = wxLogin.GetWeiXinUser(ACCESST.access_token, ACCESST.openid, out reg); WeiXinUsers = new WeiXinUsers(); WeiXinUsers.UId = 0; WeiXinUsers.OpenId = WeiXinUser.openid; WeiXinUsers.ComeId = 0; WeiXinUsers.AddTime = DateTime.Now; WeiXinUsers.State = 1; WeiXinUsers.NickName = WeiXinUser.nickname; WeiXinUsers.Sex = WeiXinUser.sex; WeiXinUsers.Province = WeiXinUser.province; WeiXinUsers.City = WeiXinUser.city; WeiXinUsers.Country = WeiXinUser.country; WeiXinUsers.HeadImgUrl = WeiXinUser.headimgurl; WeiXinUsers.Privilege = WeiXinUser.privilege; Entity.WeiXinUsers.AddObject(WeiXinUsers); Entity.SaveChanges(); } } Response.Redirect(BackUrl); }
public bool UpdateMsgAccount(int agentId, Guid managerId, WeiXinUser userInfo) { if (isRepeat(agentId: agentId, managerAccount: managerId, unionId: userInfo.unionid)) { return(true); } TransactionModel updateTran = new TransactionModel(); //获取当前配置消息账号 //MsgAccount currentMsgAccount = GetByManagerAgent(agentId: agentId, managerId: managerId); //if (currentMsgAccount != null) //{ // //删除现有配置消息账号 // currentMsgAccount.State = -1; // updateTran.Add(BuildUpdateSql(currentMsgAccount, "State")); //} string addresss = $"{userInfo.province} {userInfo.city} {userInfo.country}"; //添加新消息账号 MsgAccount newMsgAccount = new MsgAccount() { AddTime = DateTime.Now, Agentid = agentId, ManagerGuid = managerId, OpenId = userInfo.openid, UnionId = userInfo.unionid, NickName = userInfo.nickname, HeadImgUrl = userInfo.headimgurl, Sex = userInfo.sex, Address = addresss, State = 0, }; updateTran.Add(BuildAddSql(newMsgAccount)); //return 执行事务 return(ExecuteTransaction(updateTran.sqlArray, updateTran.ParameterArray)); }
/// <summary> /// 记录学生体温 /// </summary> /// <param name="model"></param> /// <returns></returns> public InvokeResult RecordStudentBbt(InputTeacherRecordStudentBbtModel model) { var xLog = new Logger(); xLog.AddLine("=================== Teacher RecordStudentBbt ========================"); string ip = HttpContext.Current.Request.UserHostAddress; xLog.AddLine($"Ip :{ip}"); xLog.AddLine("---------------------------------------------------------------"); xLog.AddLine($"Input Data:{Environment.NewLine}{JsonConvert.SerializeObject(model, Formatting.Indented)}"); var r = new InvokeResult(); try { var xUser = new WeiXinUser(); if (xUser.CheckTeacher(model.UnionId, model.TeamId, out var teacher)) { var xBbt = new StudentBbtRecord(); if (xBbt.AddByTeacher(teacher.TeacherId, model.StudentId, DateTime.Today, (Base.EnumBbtType)model.Type, model.Temperature, "")) { xLog.AddLine("Success."); r.Success = true; } else { xLog.AddLine("Error:" + xBbt.ErrorMessage); r.Success = false; r.ErrorMessage = xBbt.ErrorMessage; r.ErrorNumber = xBbt.ErrorNumber; } } else { r.Success = false; r.ErrorMessage = "教职工信息不存在!"; r.ErrorNumber = xUser.ErrorNumber; xLog.AddLine($"CheckTeacher Error:{r.ErrorMessage}"); } return(r); } catch (Exception ex) { xLog.AddLine("Exception:\n" + ex.Message); r.Success = false; r.ErrorMessage = ex.Message; return(r); } finally { xLog.AddLine($"Results:{Environment.NewLine}{JsonConvert.SerializeObject(r, Formatting.Indented)}"); xLog.Save(); } }
public async Task <ActionResult> Edit([Bind(Include = "Id,openid,nickname,sex,province,city,country,headimgurl,unionid,phone")] WeiXinUser weiXinUser) { if (ModelState.IsValid) { db.Entry(weiXinUser).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(weiXinUser)); }
public void RefreshUserList(int pageIndex, int pageSize, string groupId) { Init(false); httpClient.Url = "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize={0}&pageidx={1}&type=0&groupid={2}&token={3}&lang=zh_CN".FormatWith(pageSize, pageIndex, groupId, MPToken); string response = httpClient.GetString(); List <WeiXinUser> list = new List <WeiXinUser>(); Match match = userListRegex.Match(response); while (match.Success) { WeiXinUser weiXinUser = new WeiXinUser(); weiXinUser.OpenId = match.Groups["id"].Value; weiXinUser.NickName = match.Groups["nickname"].Value; weiXinUser.RemarkName = match.Groups["remarkname"].Value; weiXinUser.GroupId = match.Groups["groupid"].Value; weiXinUser.ValidFlag = true; list.Add(weiXinUser); match = match.NextMatch(); } using (DbSession dbSession = new DbSession(WeiXinConstants.WeiXinConnString, true)) { List <WeiXinUser> dbUser = dbSession.Query <WeiXinUser>(); foreach (WeiXinUser item in list) { WeiXinUser dbItemValue = (from dbItem in dbUser where dbItem.OpenId == item.OpenId select dbItem).SingleOrDefault(); if (dbItemValue != null) { item.Id = dbItemValue.Id; item.FakeId = dbItemValue.FakeId; // FakeId 需要保留 item.CreateTime = dbItemValue.CreateTime; } dbSession.Save(item); } dbSession.CommitTransaction(); } foreach (WeiXinUser item in list) { if (string.IsNullOrEmpty(item.UserName)) { RefreshUserContactInfo(item.OpenId); } } }
// GET: Admin/WeiXinUsers/Edit/5 public async Task <ActionResult> Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } WeiXinUser weiXinUser = await db.WeiXinUsers.FindAsync(id); if (weiXinUser == null) { return(HttpNotFound()); } return(View(weiXinUser)); }
/// <summary> /// 添加新用户到基础表 /// </summary> /// <param name="xml"></param> public void RegisterOAuthUser(RequestXML xml) { try { if (xml == null) { return; } if (string.IsNullOrEmpty(xml.FromUserName)) { return; } //log4net.LogHelper.WriteInfo(this.GetType(), $"扫码事件推送:{JsonConvert.SerializeObject(xml)}"); UserBaseInfo umodel = UserBaseInfoBLL.SingleModel.GetModelByOpenId(xml.FromUserName, xml.ToUserName); if (umodel == null) { WeiXinUser wx = WxHelper.GetWxUserInfo(WxHelper.GetToken(), xml.FromUserName); if (wx != null && !string.IsNullOrEmpty(wx.openid)) { umodel = new UserBaseInfo(); umodel.headimgurl = wx.headimgurl; umodel.nickname = wx.nickname; umodel.openid = wx.openid; umodel.unionid = wx.unionid; umodel.country = wx.country; umodel.sex = wx.sex; umodel.city = wx.city; umodel.province = wx.province; umodel.serverid = xml.ToUserName; UserBaseInfoBLL.SingleModel.Add(umodel); } } else { WeiXinUser wx = WxHelper.GetWxUserInfo(WxHelper.GetToken(), xml.FromUserName); if (wx != null && !string.IsNullOrEmpty(wx.openid) && umodel.headimgurl != wx.headimgurl) { umodel.headimgurl = wx.headimgurl; UserBaseInfoBLL.SingleModel.Update(umodel, "headimgurl"); } } } catch (Exception ex) { log4net.LogHelper.WriteInfo(this.GetType(), $"报错扫码事件推送:{JsonConvert.SerializeObject(ex)}"); log4net.LogHelper.WriteError(this.GetType(), ex); } }
public async Task <ActionResult> DeleteConfirmed(int id) { WeiXinUser weiXinUser = await db.WeiXinUsers.FindAsync(id); if (weiXinUser.state == (int)WeiXinUserStateEnum.NotAccess) { weiXinUser.state = (int)WeiXinUserStateEnum.Normal; } else { weiXinUser.state = (int)WeiXinUserStateEnum.NotAccess; } await db.SaveChangesAsync(); return(RedirectToAction("Index")); }
/// <summary> /// 公众号获取微信用户基本信息 /// </summary> /// <param name="token"></param> /// <param name="openid"></param> /// <returns></returns> public static WeiXinUser GetWxUserInfo(string token, string openid) { WeiXinUser model = new WeiXinUser(); //string url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", token, openid); string url = string.Format(WxSysConfig.User_infoURL(token), token, openid); string jsonstr = HttpGet(url); try { model = new JavaScriptSerializer().Deserialize <WeiXinUser>(jsonstr); model.serverid = token; } catch (Exception ex) { log4net.LogHelper.WriteInfo(typeof(WxHelper), "GetWxUserInfo出错:" + url + "===" + ex.Message); return(null); } return(model); }
public virtual ActionResult Text(string content) { int index = content.IndexOf("$校验码$"); if (index > 0) { string code = content.Substring(index + 5); try { string openId = SecurityUtil.DecryptS(code, ConfigUtil.GetAppSettingValue <string>("WeiXinToken").Substring(0, 8)); using (DbSession dbSession = new DbSession(WeiXinConstants.WeiXinConnString)) { WeiXinUser weiXinUser = dbSession.Query <WeiXinUser>(SqlCriteria.New.Equal("openid", openId)).FirstOrDefault(); if (weiXinUser != null) { weiXinUser.FakeId = ViewData["FromUserName"].ToString(); dbSession.Save(weiXinUser); } else { Logger.Debug("绑定未成功!" + ViewData.ToString()); return(WeiXinText("绑定未成功!")); } } } catch (Exception e) { Logger.Error("校验出错!" + ViewData.ToString(), e); return(WeiXinText("校验出错!")); } return(WeiXinText("绑定成功!")); } return(WeiXinDebug()); }
/// <summary> /// 添加新用户到基础表 /// </summary> /// <param name="xml"></param> public void RegisterOAuthUser(RequestXML xml) { try { if (xml == null) { return; } if (string.IsNullOrEmpty(xml.FromUserName)) { return; } UserBaseInfoBLL ubll = new UserBaseInfoBLL(); UserBaseInfo umodel = ubll.GetModelByOpenId(xml.FromUserName, xml.ToUserName); if (umodel == null) { WeiXinUser wx = WxHelper.GetWxUserInfo(WxHelper.GetToken(), xml.FromUserName); if (wx != null && !string.IsNullOrEmpty(wx.openid)) { umodel = new UserBaseInfo(); umodel.headimgurl = wx.headimgurl; umodel.nickname = wx.nickname; umodel.openid = wx.openid; umodel.unionid = wx.unionid; umodel.country = wx.country; umodel.sex = wx.sex; umodel.city = wx.city; umodel.province = wx.province; umodel.serverid = xml.ToUserName; ubll.Add(umodel); } } } catch (Exception ex) { log4net.LogHelper.WriteError(this.GetType(), ex); } }
/// <summary> /// 通过unionid获取account /// </summary> /// <param name="wx"></param> /// <returns></returns> public Account GetAccountByWeixinUser(WeiXinUser wx, int usertype = 0) { Account accountmodel = null; if (!string.IsNullOrEmpty(wx.unionid)) { accountmodel = base.GetModel(string.Format("UnionId='{0}'", wx.unionid)); if (accountmodel == null) { //初始化新用户的默认信息,创建默认社区等 accountmodel = WeiXinRegister(wx.openid, usertype, wx.unionid); ////注册赠送单页版 //if (accountmodel != null) //{ // AddFreeSinglePage(accountmodel); //} } if (accountmodel != null && string.IsNullOrEmpty(accountmodel.UnionId)) { updateUnionId(accountmodel.Id, wx.unionid); } } return(accountmodel); }
/// <summary> /// </summary> /// 微信登录回调 public void WXLoginBack() { Client customer = new Client(); WeiXinUser weiXinUser = WeiXinService.GetWeiXinUser(string.Empty, Request.Params["code"].ToString()); string callbackUrl = Request.QueryString["state"].ToString(); if (weiXinUser != null && !string.IsNullOrEmpty(weiXinUser.Openid)) { Client cusomerInfo = ClientService.LoadClientByAppCustomerID(weiXinUser.Openid); if (cusomerInfo != null && cusomerInfo.SysNo > 0) { //更新用户头像以及昵称 cusomerInfo.Name = weiXinUser.NickName; cusomerInfo.HeaderImage = weiXinUser.HeadImgUrl; cusomerInfo.EditTime = DateTimeHelper.GetTimeZoneNow(); ClientService.UpdateClient(cusomerInfo); var appuser = new AppUserInfo() { AppCustomerID = weiXinUser.Openid, UserSysNo = cusomerInfo.SysNo, UserID = HttpUtility.UrlEncode(cusomerInfo.Name), HeadImage = cusomerInfo.HeaderImage, UserDisplayName = HttpUtility.UrlEncode(cusomerInfo.Name), ManagerSysNo = cusomerInfo.ManagerSysNo, UserType = UserType.Common, LastLoginDateText = DateTimeHelper.GetTimeZoneNow().ToString("yyyy-MM-dd HH:mm:ss"), ManagerLoginName = cusomerInfo.ManagerLoginName, ManagerName = HttpUtility.UrlEncode(cusomerInfo.ManagerName) }; if (cusomerInfo.ManagerSysNo.HasValue && cusomerInfo.ManagerSysNo.Value > 0) { appuser.UserType = UserType.Manager; var company = CompanyService.GetCompanyUser(cusomerInfo.ManagerSysNo.Value); if (company != null) { appuser.UserType = UserType.Installer; } } UserMgr.Logout(); UserMgr.WriteUserInfo(appuser); if (!string.IsNullOrEmpty(callbackUrl)) { Response.Redirect(callbackUrl); return; } Response.Redirect("/smoke/userInfo"); return; } else//新建client { customer.AppCustomerID = weiXinUser.Openid; customer.Name = weiXinUser.NickName; customer.HeaderImage = weiXinUser.HeadImgUrl; customer.EditTime = DateTimeHelper.GetTimeZoneNow(); customer.RegisterTime = DateTimeHelper.GetTimeZoneNow(); //创建用户 customer.SysNo = ClientService.InsertClient(customer); var appuser = new AppUserInfo() { AppCustomerID = weiXinUser.Openid, UserSysNo = customer.SysNo, UserID = HttpUtility.UrlEncode(customer.Name), UserDisplayName = HttpUtility.UrlEncode(customer.Name), HeadImage = customer.HeaderImage, UserType = UserType.Common, LastLoginDateText = DateTimeHelper.GetTimeZoneNow().ToString("yyyy-MM-dd HH:mm:ss") }; UserMgr.Logout(); UserMgr.WriteUserInfo(appuser); if (!string.IsNullOrEmpty(callbackUrl)) { Response.Redirect(callbackUrl); return; } Response.Redirect("/smoke/userInfo"); return; } } }
protected void Page_Load(object sender, EventArgs e) { CurrTel = new UserBLL().GetUserBasicInfoModelById(WebUserAuth.UserId.Value).TelNo; if (string.IsNullOrEmpty(CurrTel)) { CurrTel = "1********"; } CookieHelper.WriteCookie("shellben4tel", Tool.Common.Utils.StringHandler.MaskTelNo(CurrTel)); string cmd = Request.QueryString["cmd"]; if (cmd == "notbind") { NotBind(); return; } if (GlobalUtils.IsWeiXinBrowser) { try { string code = WEBRequest.GetQueryString("code"); string openId = WEBRequest.GetQueryString("openid"); if (openId.IsNotEmpty()) { GlobalUtils.WriteOpenIdToCookie(openId); } ThirdLoginSDK sdk = new ThirdLoginSDK(); sdk.InitSDK(ThirdLoginSDK.ThirdLoginType.WeiXin); //获取微信上用户信息 wxUserInfo = sdk.GetWXUserSubscribeInfor(code, openId.ToText()); if (wxUserInfo != null && !string.IsNullOrEmpty(wxUserInfo.nickname)) { CookieHelper.WriteCookie("shellben4wxname", wxUserInfo.nickname); openId = wxUserInfo.openid; } TuanDai.LogSystem.LogClient.LogClients.TraceLog(TdConfig.ApplicationName, "GetWeiXinUserInfo", "", JsonConvert.SerializeObject(wxUserInfo)); var posturl = GlobalUtils.MsgApiUrl; string err = ""; var descStr = TuanDai.WXSystem.Core.Common.MsgDesc.GetDescStr("{\"Data\":{\"WeiXinOpenId\":\"" + openId + "\"}}"); TuanDai.LogSystem.LogClient.LogClients.TraceLog(TdConfig.ApplicationName, "GetWeiXinUserInfo123", "", descStr); string resp = HttpClient.HttpUtil.HttpPostJson(TdConfig.ApplicationName, posturl + "/4/GetUserIdsByWeixinOpenId", descStr, out err, null, 3); if (!string.IsNullOrEmpty(resp)) { var returnmsg = JsonConvert .DeserializeObject <TuanDai.WXSystem.Core.Common.MsgApiResponseMessage <List <string> > >( resp); if (returnmsg != null) { if (returnmsg.Data.Count > 0) { foreach (var item in returnmsg.Data) { if (!uList.Exists(o => o.UserId == Guid.Parse(item))) { WeiXinUser user = new WeiXinUser(); user.UserId = Guid.Parse(item); user.DescUserId = Tool.DESC.EncryptTripleDES(user.UserId.ToString()); var tduser = new UserBLL().GetUserBasicInfoModelById(user.UserId); if (tduser != null && !string.IsNullOrEmpty(tduser.TelNo)) { user.Tel = tduser.TelNo; } uList.Add(user); } } uList = uList.Where(o => o.Tel.IsNotEmpty()).ToList(); if (uList != null && uList.Count > 0) { if (uList.Exists(o => o.UserId == WebUserAuth.UserId.Value)) { firstUser = uList.Where(o => o.UserId == WebUserAuth.UserId.Value).FirstOrDefault(); } else { firstUser = uList[0]; } } string redisErr = ""; RedisServerStack.StringSet(TdConfig.ApplicationName, "/redis/web", openId, uList, ref redisErr); } } } } catch (Exception ex) { TuanDai.LogSystem.LogClient.LogClients.ErrorLog(TdConfig.ApplicationName, "GetWeiXinUserInfo", WebUserAuth.UserId.Value.ToString(), "获取用户微信信息失败"); Response.Redirect("my_account.aspx", true); //Response.End(); } } else { Response.Redirect("my_account.aspx", true); //Response.End(); } if (wxUserInfo == null) { wxUserInfo = new ThirdLoginSDK.WXOAuthUser(); } }
/// <summary> /// 列出班级已登记的学生 /// </summary> /// <param name="model"></param> /// <returns></returns> public InvokeResult <DataTeamStudents> ListStudents(InputTeamIdModel model) { var xLog = new Logger(); xLog.AddLine("=================== Team ListStudents ========================"); string ip = HttpContext.Current.Request.UserHostAddress; xLog.AddLine($"Ip :{ip}"); xLog.AddLine("---------------------------------------------------------------"); xLog.AddLine($"Input Data:{Environment.NewLine}{JsonConvert.SerializeObject(model, Formatting.Indented)}"); var r = new InvokeResult <DataTeamStudents>() { Data = new DataTeamStudents() }; try { var xUser = new WeiXinUser(); if (xUser.CheckUnionId(model.UnionId, out _)) { var xTeam = new Team(); if (xTeam.ListStudents(model.TeamId, out var students)) { if (students != null) { r.Data.Students = new List <DataTeamStudent>(); foreach (var item in students) { var ts = new DataTeamStudent(); ts.AvatarUrl = item.AvatarUrl.FixImagePath(); //修正为全路径字符串 ts.Name = item.Name; ts.StudentId = item.StudentId; ts.IsMyChild = item.StudentParent.Any(x => x.Parent.UnionId == model.UnionId && x.Status == 1); r.Data.Students.Add(ts); } r.Success = true; xLog.AddLine($"Success."); } } else { r.Success = false; r.ErrorMessage = xTeam.ErrorMessage; r.ErrorNumber = xTeam.ErrorNumber; xLog.AddLine($"ListStudents Error:{r.ErrorMessage}"); } } else { r.Success = false; r.ErrorMessage = "当前用户未注册!"; r.ErrorNumber = xUser.ErrorNumber; xLog.AddLine($"CheckUnion Error:{r.ErrorMessage}"); } return(r); } catch (Exception ex) { xLog.AddLine("Exception:\n" + ex.Message); r.Success = false; r.ErrorMessage = ex.Message; return(r); } finally { xLog.AddLine($"Results:{Environment.NewLine}{JsonConvert.SerializeObject(r)}"); xLog.Save(); } }
public void AddUser(WeiXinUser model) { _dao.Add(model); }
/// <summary> /// 登录(获取基础信息) /// 需获取unionId时,为下一步获取用户详细信息做准备 /// </summary> /// <param name="model"></param> /// <returns></returns> public InvokeResult <DataLoginInfo> Login(InputLoginModel model) { var xLog = new Logger(); xLog.AddLine("=================== Member Login ========================"); xLog.AddLine($"JsCode :{model.JsCode}"); string ip = HttpContext.Current.Request.UserHostAddress; xLog.AddLine($"Ip :{ip}"); xLog.AddLine("---------------------------------------------------------------"); xLog.AddLine($"Input Data:{Environment.NewLine}{JsonConvert.SerializeObject(model, Formatting.Indented)}"); xLog.AddLine($"{WxOpenAppId} {WxOpenAppSecret}"); var r = new InvokeResult <DataLoginInfo>() { Data = new DataLoginInfo() }; try { var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, model.JsCode); if (jsonResult.errcode == ReturnCode.请求成功) { //使用SessionContainer管理登录信息(推荐) var unionId = jsonResult.unionid; var sessionId = Guid.NewGuid(); var sessionBag = SessionContainer.UpdateSession(sessionId.ToString(), jsonResult.openid, jsonResult.session_key, unionId); r.Data.OpenId = jsonResult.openid; r.Data.UnionId = jsonResult.unionid; xLog.AddLine($"JsonResult:{Environment.NewLine}{Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult, Formatting.Indented)}"); var xSession = new TinyAppSession(); if (!xSession.Add(jsonResult.openid, jsonResult.session_key, sessionId)) { xLog.AddLine($"Session update error:{xSession.ErrorMessage}"); } var openId = jsonResult.openid; unionId = jsonResult.unionid; if (string.IsNullOrEmpty(openId)) { openId = ""; } if (string.IsNullOrEmpty(unionId)) { unionId = ""; } var xUser = new WeiXinUser(); if (xUser.LoadByTinyAppAccount(unionId, openId, out var user)) { if (user != null) { r.Data.UnionId = unionId; r.Data.Avatar = user.HeadImage; r.Data.NickName = user.NickName; if (!string.IsNullOrEmpty(openId) && !string.IsNullOrEmpty(unionId) && (user.OpenId != user.UnionId) && !string.IsNullOrEmpty(user.HeadImage) && !string.IsNullOrEmpty(user.NickName)) { if (xUser.FetchRole(unionId, out _, out var parents, out var teachers)) { if (parents != null) { r.Data.Parents = new List <DataParentRole>(); foreach (var item in parents) { var p = new DataParentRole(); p.ParentId = item.ParentId; p.StudentId = item.StudentId; r.Data.Parents.Add(p); } } if (teachers != null) { r.Data.Teachers = new List <DataTeacherRole>(); foreach (var item in teachers) { var t = new DataTeacherRole(); t.TeacherId = item.TeacherId; t.TeamId = item.TeamId; r.Data.Teachers.Add(t); } } r.Success = true; } else { r.ErrorMessage = xUser.ErrorMessage; xLog.AddLine("获取角色失败:" + xUser.ErrorMessage); r.Success = false; } } else { r.ErrorNumber = 404; r.ErrorMessage = "信息不全!"; r.Success = false; } } else { r.Success = false; r.ErrorNumber = 404; r.ErrorMessage = "用户不存在!"; } } else { r.ErrorNumber = 404; r.Success = false; r.ErrorMessage = "用户不存在!"; } } else { r.Success = false; r.ErrorMessage = "请求失败:" + jsonResult.errmsg; } if (string.IsNullOrEmpty(r.Data.OpenId)) { r.Data.OpenId = ""; } if (string.IsNullOrEmpty(r.Data.UnionId)) { r.Data.UnionId = ""; } return(r); }
internal bool RefreshUserContactInfo(string openId) { bool result = false; Init(false); System.Threading.Thread.Sleep(50); httpClient.Url = "https://mp.weixin.qq.com/cgi-bin/getcontactinfo"; httpClient.Context.Referer = "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=10&pageidx=0&type=0&groupid=100&token={0}&lang=zh_CN".FormatWith(MPToken); Dictionary <string, string> postData = httpClient.PostingData; postData.Add("fakeid", openId); postData.Add("token", MPToken); postData.Add("lang", "zh_CN"); postData.Add("t", "ajax-getcontactinfo"); string response = httpClient.GetString(); Dictionary <string, string> dict = new Dictionary <string, string>(StringComparer.CurrentCultureIgnoreCase); Match match = contactInfoRegex.Match(response); while (match.Success) { string name = match.Groups["name"].Value; string value = match.Groups["value"].Value; if (!dict.ContainsKey(name)) { dict.Add(name, value); } match = match.NextMatch(); } dict.Remove("fakeid"); string userName = string.Empty; dict.TryGetValue("user_name", out userName); dict["username"] = userName; if (dict.Count >= 5 && !string.IsNullOrEmpty(userName)) { using (DbSession dbSession = new DbSession(WeiXinConstants.WeiXinConnString)) { WeiXinUser weiXinUser = dbSession.Query <WeiXinUser>(SqlCriteria.New.Equal("openid", openId)).FirstOrDefault(); if (weiXinUser != null) { IEntityProxy entityProxy = EntityProxyManager.Instance.GetEntityProxy <WeiXinUser>(); foreach (string key in dict.Keys) { entityProxy.SetPropertyValue(weiXinUser, key, dict[key]); } } dbSession.Save(weiXinUser); result = true; } } return(result); }
/// <summary> /// 加载指定班级基本信息 /// /// 如果有学生编号传入,则同时返回指定学生信息 /// </summary> /// <param name="model"></param> /// <returns></returns> public InvokeResult <DataTeamInfo> Load(InputTeamIdWidthStudentIdModel model) { var xLog = new Logger(); xLog.AddLine("=================== Team Load ========================"); string ip = HttpContext.Current.Request.UserHostAddress; xLog.AddLine($"Ip :{ip}"); xLog.AddLine("---------------------------------------------------------------"); xLog.AddLine($"Input Data:{Environment.NewLine}{JsonConvert.SerializeObject(model, Formatting.Indented)}"); var r = new InvokeResult <DataTeamInfo>() { Data = new DataTeamInfo() }; try { var xUser = new WeiXinUser(); if (xUser.CheckUnionId(model.UnionId, out _)) { var xTeam = new Team(); if (xTeam.Load(model.TeamId, out var team)) { if (team != null) { r.Data.ParentNum = team.ParentNum; var teamRoom = team.TeamClassroom.SingleOrDefault(x => x.Status == 1); r.Data.RoomName = teamRoom != null ? teamRoom.Room.Name : ""; r.Data.SchoolName = team.School.Name; r.Data.StudentNum = team.StudentNum; r.Data.TeacherNum = team.TeacherNum; r.Data.TeamId = team.TeamId; r.Data.TeamName = team.Name; } if (model.StudentId.HasValue) { var xStudent = new Student(); if (xStudent.Load(model.StudentId.Value, out var student)) { if (student != null) { r.Data.Student = new DataStudentInfo(); r.Data.Student.StudentId = student.StudentId; r.Data.Student.No = student.No; r.Data.Student.Name = student.Name; r.Data.Student.IdNo = student.IdNo; r.Data.Student.AvatarUrl = student.AvatarUrl.FixImagePath(); } } } r.Success = true; xLog.AddLine("Success."); } else { r.Success = false; r.ErrorMessage = xTeam.ErrorMessage; r.ErrorNumber = xTeam.ErrorNumber; xLog.AddLine($"ListStudents Error:{r.ErrorMessage}"); } } else { r.Success = false; r.ErrorMessage = "当前用户未注册!"; r.ErrorNumber = xUser.ErrorNumber; xLog.AddLine($"CheckUnion Error:{r.ErrorMessage}"); } return(r); } catch (Exception ex) { xLog.AddLine("Exception:\n" + ex.Message); r.Success = false; r.ErrorMessage = ex.Message; return(r); } finally { xLog.AddLine($"Results:{Environment.NewLine}{JsonConvert.SerializeObject(r)}"); xLog.Save(); } }
/// <summary> /// 根据整型Id或者Guid型TeamId /// </summary> /// <param name="model"></param> /// <returns></returns> public InvokeResult <Guid> LoadTeamId(InputBaseWithTeamIdModel model) { var xLog = new Logger(); xLog.AddLine("=================== Team LoadTeamId ========================"); string ip = HttpContext.Current.Request.UserHostAddress; xLog.AddLine($"Ip :{ip}"); xLog.AddLine("---------------------------------------------------------------"); xLog.AddLine($"Input Data:{Environment.NewLine}{JsonConvert.SerializeObject(model, Formatting.Indented)}"); var r = new InvokeResult <Guid>() { Data = Guid.Empty }; try { var xUser = new WeiXinUser(); if (xUser.CheckUnionId(model.UnionId, out _)) { var xTeam = new Team(); if (xTeam.Load(model.TeamId, out var team)) { if (team != null) { r.Data = team.TeamId; r.Success = true; } else { r.Success = false; r.ErrorMessage = xTeam.ErrorMessage; r.ErrorNumber = xTeam.ErrorNumber; xLog.AddLine($"ListStudents Error:{r.ErrorMessage}"); } } else { r.Success = false; r.ErrorMessage = xTeam.ErrorMessage; r.ErrorNumber = xTeam.ErrorNumber; xLog.AddLine($"ListStudents Error:{r.ErrorMessage}"); } } else { r.Success = false; r.ErrorMessage = "当前用户未注册!"; r.ErrorNumber = xUser.ErrorNumber; xLog.AddLine($"CheckUnion Error:{r.ErrorMessage}"); } return(r); } catch (Exception ex) { xLog.AddLine("Exception:\n" + ex.Message); r.Success = false; r.ErrorMessage = ex.Message; return(r); } finally { xLog.AddLine($"Results:{Environment.NewLine}{JsonConvert.SerializeObject(r)}"); xLog.Save(); } }
//保存授权信息 public bool SaveAuthAccount(WeiXinUser wxUser) { var flag = false; var sex = Sex.Man; switch (wxUser.sex) { case 1: sex = Sex.Man; break; case 2: sex = Sex.Woman; break; case 0: sex = Sex.None; break; } var isSave = false; var authAccount = aa.Get(wxUser.openid); if (authAccount == null) { authAccount = new LZY.BX.Model.AuthAccount(); isSave = true; } authAccount.OpenId = wxUser.openid; authAccount.Server = "Wx"; authAccount.NickName = wxUser.nickname; authAccount.Sex = sex.ToString(); authAccount.Province = wxUser.province; authAccount.City = wxUser.city; authAccount.Country = wxUser.country; authAccount.Headimgurl = wxUser.headimgurl; authAccount.Privilege = Newtonsoft.Json.JsonConvert.SerializeObject(wxUser.privilege); authAccount.Unionid = wxUser.subscribe.ToString();//subscribe=1 表示已经关注 0还没有关注 authAccount.AccessToken = wxUser.access_token; authAccount.RefreshToken = wxUser.refresh_token; authAccount.ExpiresIn = 0; authAccount.ExpiresOut = 0; authAccount.RefreshExpiresOut = 0; authAccount.LastUpdateTime = DateTime.Now; if (isSave) { authAccount.CreateTime = DateTime.Now; //保存内容 flag = aa.Save(authAccount); } else { //更新内容 flag = aa.Update(authAccount); } //缓存用户基础信息 Response.Cookies.Add(new System.Web.HttpCookie("wx_token", authAccount.OpenId)); return(flag); }
public async Task <ActionResult> BaseCallback(string code, string state, string authCode, string returnUrl) { //log.Info("code:" + code + " state:" + state + " authCode:" + authCode + " returnUrl:" + returnUrl); if (string.IsNullOrEmpty(code)) { ViewBag.Info = "您拒绝了授权!"; return(View("Info")); } OAuthAccessTokenResult result = null; //通过,用code换取access_token try { result = OAuthApi.GetAccessToken(WeiXinConfig.appId, WeiXinConfig.appSecret, code); if (result.errcode != ReturnCode.请求成功) { ViewBag.Info = "错误:" + result.errmsg; return(View("Info")); } //下面2个数据也可以自己封装成一个类,储存在数据库中(建议结合缓存) //如果可以确保安全,可以将access_token存入用户的cookie中,每一个人的access_token是不一样的 //Session["OAuthAccessTokenStartTime"] = DateTime.Now; //Session["OAuthAccessToken"] = result; //因为第一步选择的是OAuthScope.snsapi_userinfo,这里可以进一步获取用户详细信息 using (var db = new OlaEntities()) { var wxUser = await db.WeiXinUsers.FirstOrDefaultAsync(w => w.openid == result.openid); if (wxUser == null) { //log.Info(JsonConvert.SerializeObject(result)); OAuthUserInfo userInfo = OAuthApi.GetUserInfo(result.access_token, result.openid); //log.Info(JsonConvert.SerializeObject(userInfo)); if (string.IsNullOrEmpty(authCode)) { ViewBag.Info = "验证失败!请从正规途径进入!" + result.errmsg; return(View("Info")); } wxUser = new WeiXinUser { city = userInfo.city, country = userInfo.country, headimgurl = userInfo.headimgurl, nickname = userInfo.nickname, openid = userInfo.openid, province = userInfo.province, sex = userInfo.sex, unionid = userInfo.unionid, CreateTime = DateTime.Now, phone = null, AuthCode = authCode, state = (int)WeiXinUserStateEnum.Normal, }; db.WeiXinUsers.Add(wxUser); await db.SaveChangesAsync(); } if (string.IsNullOrEmpty(wxUser.phone)) { if (!string.IsNullOrEmpty(authCode)) { return(RedirectToAction("Register", new { authCode, wxUser.openid })); } else { ViewBag.Info = "验证失败!请从正规途径进入!"; return(View("Info")); } } if (wxUser.state != (int)WeiXinUserStateEnum.Normal) { ViewBag.Info = "您已经被限制访问该网站,请联系网站负责人!"; return(View("Info")); } WriteCookie(wxUser.Id); } //log.Info("login:"******"Index", "L")); } catch (Exception ex) { log.Error(ex.Message, ex); ViewBag.Info = ex.Message; return(View("Info")); } }