/// <summary> /// 保存微信用户信息 /// </summary> /// <param name="wxUserInfo"></param> public void SetWxUserInfo(WxUserInfo wxUserInfo) { Session[SysKeys.SESSION_WXUSER_INFO] = wxUserInfo; Session.Timeout = 45; //写入Cookies WebHelper.WriteCookie(wxuserKey, DESEncrypt.Encrypt(wxUserInfo.ToJson()), 60); }
public static WxUsers SetWxUserInfo(IWxUsersRepository repository, WxUserInfo userModel, PassTicketXmlInfo keys) { var result = repository.GetWxUsers(keys.wxuin) ?? new WxUsers(); result.Uin = keys.wxuin; result.UserName = userModel.UserName; result.NickName = userModel.NickName; result.HeadImgUrl = userModel.HeadImgUrl; result.PYInitial = userModel.PYInitial; result.PYQuanPin = userModel.PYQuanPin; result.StarFriend = userModel.StarFriend; result.Sex = userModel.Sex; result.UpdateTime = DateTime.Now; //设置keys result.Detail.WxKeys.Ret = keys.ret; result.Detail.WxKeys.Message = keys.message; result.Detail.WxKeys.Skey = keys.skey; result.Detail.WxKeys.WxSid = keys.wxsid; result.Detail.WxKeys.WxUin = keys.wxuin; result.Detail.WxKeys.PassTicket = keys.pass_ticket; result.Detail.WxKeys.Isgrayscale = keys.isgrayscale; result.Detail.WxKeysJson = JsonConvert.SerializeObject(result.Detail.WxKeys); if (result.Id <= 0) { repository.Add(result); } else { repository.Update(result); } return(result); }
/// <summary> /// snsapi_base 只能通过code获取openid,snsapi_userinfo 可通过code获取用户信息 /// </summary> /// <param name="scope"></param> /// <returns></returns> public ActionResult GetAuthorizeCode(string state) { string code = Request["code"]; if (code == null) { string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={2}#wechat_redirect", WxConfig.AppId, HttpUtility.UrlEncode(WxConfig.CurrentHost + Request.Url.AbsolutePath), state); //WxHelper.HttpGetRequest(url); return(Redirect(url)); } else { string openidUrl = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code ", WxConfig.AppId, WxConfig.Secret, code); string baseResult = WxHelper.HttpGetRequest(openidUrl); WxModel wxModel = JsonConvert.DeserializeObject <WxModel>(baseResult); log.LogHelper.WriteLog("获取access_token", baseResult); if (!string.IsNullOrWhiteSpace(wxModel.errcode)) { return(Content("参数错误")); } string userInfOUrl = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN ", wxModel.access_token, wxModel.openid); string userInfoResult = WxHelper.HttpGetRequest(userInfOUrl); log.LogHelper.WriteLog("获取用户信息", userInfoResult); WxUserInfo wxUserInfo = JsonConvert.DeserializeObject <WxUserInfo>(userInfoResult); Session["UserInfo"] = wxUserInfo; if (!string.IsNullOrWhiteSpace(wxUserInfo.errcode)) { return(Content("参数错误")); } return(Content(userInfoResult)); } }
/// <summary> /// 刷新获取最新access_token /// </summary> /// <param name="retoken">refresh_token 用来刷新获取access_token</param> /// <returns></returns> public string getNewToken(string openid) { var db = RedisManager.Instance.GetDatabase(); string json = db.StringGet(openid); //将json转换为对象 WxUserInfo infoModel = JsonConvert.DeserializeObject <WxUserInfo>(json); string url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appid + "&grant_type=refresh_token&refresh_token=" + infoModel.refresh_token; string getJson = BaseController.HttpGet(url); if (!string.IsNullOrEmpty(getJson)) { JObject jo = (JObject)JsonConvert.DeserializeObject(getJson); //json中不包含access_token键 说明调用失败 包含错误代码 if (jo.Property("access_token") != null) { //获取到最新access_token并同步修改到redis中 infoModel.access_token = jo["access_token"].ToString(); db.StringSet(openid, JsonConvert.SerializeObject(infoModel)); return(infoModel.access_token); } else { return("调用错误"); } } else { return("调用错误"); } }
private void setLogin(string mes) { WxUserInfo wxPersonalInfo = JsonMapper.ToObject <WxUserInfo>(mes); GlobalDataScript.szMachineID = wxPersonalInfo.openid; SocketLoginEvent.instance.OnWxLoginSucess(wxPersonalInfo); }
private string insertDemandApplyReport() { UserInfo user = (UserInfo)Session["user"]; string hospitalName = Request.Form["hospitalName"]; string productName = Request.Form["productName"]; string agentName = Request.Form["agentName"]; string spec = Request.Form["spec"]; string unit = Request.Form["unit"]; string applyNumber = Request.Form["applyNumber"]; string remark = Request.Form["remark"]; string approverIds = Request.Form["approverIds"]; string informer = Request.Form["chooseInformerId"]; string netSales = Request.Form["netSales"]; string stock = Request.Form["stock"]; WxUserInfo wxUserInfo = new WxUserInfo(); List <string> informerList = JsonHelper.DeserializeJsonToList <string>(informer); List <string> approverList = JsonHelper.DeserializeJsonToList <string>(approverIds); string msg = DemandApplyReportManage.insertDemandApplyReport(hospitalName, netSales, stock, productName, agentName, spec, unit, applyNumber, remark, user, wxUserInfo.WechartUserIdToUserId(approverList), informerList); JObject jObject = new JObject(); jObject.Add("msg", msg); return(jObject.ToString()); }
public RedirectResult InitLogin(ControllerContext context, string loginSuccessRedirectUrl, Action <WxUserInfo> loginSuccessAction) { string code = context.HttpContext.Request["code"]; string url; if (string.IsNullOrEmpty(code)) { url = string.Format( "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect", _appConfig.AppId, _redirectUri, _loginScope.ToStr(), string.Empty); return(new RedirectResult(url)); } WxUserInfo wxUserInfo = new WxUserInfo(); url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", _appConfig.AppId, _appConfig.AppSecret, code); string result = HttpHelper.Get(url); if (!string.IsNullOrEmpty(result)) { var o = JObject.Parse(result); wxUserInfo.LoginToken = o.Property("access_token") == null ? "" : o["access_token"].ToStr(); wxUserInfo.LoginRefreshToken = o.Property("refresh_token") == null ? "" : o["refresh_token"].ToStr(); wxUserInfo.OpenId = o.Property("openid") == null ? "" : o["openid"].ToStr(); int expires = o.Property("expires_in") == null ? 0 : o["expires_in"].ToInt(); if (!string.IsNullOrEmpty(wxUserInfo.LoginToken) && expires > 0) { wxUserInfo.LoginTokenOverTime = DateTime.Now.AddSeconds(expires); } } loginSuccessAction.Invoke(wxUserInfo); return(new RedirectResult(loginSuccessRedirectUrl)); }
public virtual ActionResult Index(string openid, string nickname, string headimgurl) { if (string.IsNullOrEmpty(openid)) { string thisUrl = HttpHelper.GetWebSite() + Request.RawUrl; return(Redirect(GetOAuthCallbackUrl(thisUrl, true))); } ViewData["IsBind"] = "false"; WxUserInfo wxuser = GetWxUserInfo(); if (wxuser != null) { ViewData["openid"] = wxuser.OpenId; ViewData["nickname"] = wxuser.NickName; ViewData["sex"] = wxuser.Sex == 0 ? "女" : "男"; ViewData["mobile"] = wxuser.Mobile; ViewData["username"] = ""; ViewData["company"] = "未绑定"; ViewData["customerId"] = "undefined"; ViewData["headimgurl"] = wxuser.Headimgurl; } else { ViewData["openid"] = openid; ViewData["nickname"] = "undefined"; ViewData["mobile"] = "undefined"; ViewData["sex"] = "男"; ViewData["username"] = "******"; ViewData["customerId"] = "undefined"; ViewData["company"] = "您尚未关注公众号"; ViewData["headimgurl"] = "~/Content/images/samples/scarlet-159.png"; } return(View()); }
/// <summary> /// 获取微信用户信息 /// </summary> /// <param name="token"></param> /// <param name="code"></param> /// <returns></returns> public static WxUserInfo GetWxUserInfo(WxAccessToken token, string code) { string url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token.access_token + "&openid=" + token.openid; WxUserInfo userInfo = JsonHelper.JsonStringToObj <WxUserInfo>(RequestHttp.HttpGet(url)); return(userInfo); }
private void GoUrlUnsubscribe(WxUserInfo usermodel) { //ConfigModel config = LogicConfig.GetConfigByCode("0155", "3"); //string linkurl = ConfigurationManager.AppSettings["WXWebAddressNew"] + "Lottery/ActAirportIndex.aspx?atvid=" + ActID + "¶m=" + ParamUcode; SubscribeMsgModel model = new SubscribeMsgModel(); model.WxOpenId = usermodel.openid; // model.UserId = usermodel. > 0 ? WebSession.UCode : -1; //model.SendMsg = config.Value3; //model.LinkUrl = linkurl; //model.LinkName = config.Value2; model.CreateBy = "活动关注"; //写关注数据 //string result = LotteryBase.InsertSubscribeMsg(model); //string GoUrl = string.Empty; //if (string.IsNullOrEmpty(result)) //{ // GoUrl = "http://mp.weixin.qq.com/s?biz=MzA5MzcwMDYwNQ==&mid=203814070&idx=1&sn=1b2a8da4d5831129415e753c68598a8f#rd"; // Response.Redirect(GoUrl); //} //else //{ // //插入数据失败 记录日志 //} }
/// <summary> /// 超过1条的相同关键字的自动回复 改用客服消息发送 /// </summary> /// <param name="wxUser"></param> /// <param name="lstKeywords"></param> public async Task SendKfAutoKeyword(WxUserInfo wxUser, List <WxAutoKeywordShow> lstKeywords) { foreach (var item in lstKeywords) { var res = await wxAutoKeywordHelper.AutoRespond(item, wxUser.OpenId); logHelper.Debug("SendKfAutoKeyword:自动应答发送结果:" + ComHelper.JsonSerialize(res)); } }
public async Task <int> InsertAsync(WxUserInfo entity) { string sql = @" INSERT INTO wxuserinfo(UnionId, NickName, Avatar, Gender, Country, Province, City, CreateTime, CreateBy) VALUE(@UnionId, @NickName, @Avatar, @Gender, @Country, @Province, @City, @CreateTime, @CreateBy); SELECT @@Identity;"; var id = await Instance.ExecuteScalarAsync <int>(sql, entity); return(id); }
public IHttpActionResult UserAuth(WxUserInfoDto dto) { IsJoinedResult rlt = new IsJoinedResult(); if (dto == null || dto.OpenId == null) { rlt.IsJoined = false; rlt.Code = 410; rlt.Msg = "参数错误"; return(Ok(rlt)); } var wxUserInfo = _context.WxUserInfos.FirstOrDefault(c => c.Openid == dto.OpenId); if (wxUserInfo == null) { using (var trans = _context.Database.BeginTransaction()) { try { wxUserInfo = new WxUserInfo(); wxUserInfo.Openid = dto.OpenId; wxUserInfo.HeadImgUrl = HttpUtility.UrlDecode(dto.HeadImgUrl); wxUserInfo.NickName = HttpUtility.UrlDecode(dto.NickName); var consumer = new Consumer(); consumer.Openid = dto.OpenId; _context.Consumers.Add(consumer); // var consumerInfo = _context.Consumers.FirstOrDefault(c=>c.Openid) _context.WxUserInfos.Add(wxUserInfo); _context.SaveChanges(); trans.Commit(); } catch (Exception e) { trans.Rollback(); //TODO: 返回错误 code 500 记录日志 } } } else { var consumer = _context.Consumers.First(c => c.Openid == dto.OpenId); if (!string.IsNullOrEmpty(consumer.Mobilephone)) { rlt.Code = 200; rlt.IsJoined = true; rlt.Msg = "用户已验证手机号码"; } } return(Ok(rlt)); }
public Boolean UserInfoExists(WxUserInfo wx) { if (userInfoDal.Exists(wx.openid)) { return(true); } else { return(false); } }
/// <summary> /// 微网站首页 /// </summary> /// <returns></returns> public PartialViewResult IndexPage(string code, string state) { WxUserInfo userinfo = new WxUserInfo(); var a = GetToken(code); if (a != null) { userinfo = GetUserInfo(a.access_token, a.Openid); } return(PartialView(userinfo)); }
//获取用户信息 public WxUserInfo GetUserInfo(string code) { string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", AppID, AppSecret, code); string s = GetWebRequest_Get(url); Dictionary <string, string> dict = jss.Deserialize <Dictionary <string, string> >(s); url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", dict["access_token"], dict["openid"]); s = GetWebRequest_Get(url); WxUserInfo userinfo = jss.Deserialize <WxUserInfo>(s); return(userinfo); }
/// <summary> /// 获取本地Cooker信息 /// </summary> /// <returns></returns> public WxUserInfo GetWxUserInfo() { if (Session[SysKeys.SESSION_WXUSER_INFO] != null) { WxUserInfo model = Session[SysKeys.SESSION_WXUSER_INFO] as WxUserInfo; return(model); } else { WxUserInfo model = DESEncrypt.Decrypt(WebHelper.GetCookie(wxuserKey).ToString()).ToObject <WxUserInfo>(); return(model); } }
public void TestLogin(string stri) { MyDebug.Log("TEST Wei xin"); var wx = new WxUserInfo(); var str = "test" + stri; wx.openid = str; wx.nickname = str; wx.unionid = str; wx.headimgurl = "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0"; SocketLoginEvent.instance.OnWxLoginSucess(wx); }
//获取微信支付JSAPI参数 public static string GetWxPayJSApiParam(WxUserInfo WxUserInfo, SOInfo SOInfo, out string Message) { //统一下单https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1 var data = new WxPayData(); //var goods_name = string.Join(",", SOInfo.GoodsInfos.Select(i => i.Title).ToArray()); data.SetValue("body", "test"); //goods_name.Length > 12 ? goods_name.Substring(0, 10) + "..." : goods_name //data.SetValue("attach", "test"); //附加数据 data.SetValue("out_trade_no", SOInfo.SalesOrder.BillNO); data.SetValue("total_fee", (int)Math.Round(SOInfo.SalesOrderItems.Sum(i => i.Amount) * 100, 0)); data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); //data.SetValue("goods_tag", "test"); //订单优惠标记 data.SetValue("trade_type", "JSAPI"); data.SetValue("openid", WxUserInfo.OpenID); WxPayData result = null; try { result = WxPayApi.UnifiedOrder(data); } catch (Exception e) { Message = e.Message; return(null); } if (result.GetValue("return_code") == null) { Message = "微信统一支付接口返回空值"; return(null); } if (result.GetValue("return_code").ToString() != "SUCCESS") { Message = result.GetValue("return_msg").ToString(); return(null); } //小程序支付文档https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5 var jsApiParam = new WxPayData(); jsApiParam.SetValue("appId", result.GetValue("appid")); jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp()); jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr()); jsApiParam.SetValue("package", "prepay_id=" + result.GetValue("prepay_id")); jsApiParam.SetValue("signType", "MD5"); jsApiParam.SetValue("paySign", jsApiParam.MakeSign()); //本地记录 OMS.SalesOrder.SetPayInfo(SOInfo.SalesOrder.ID, new SOPayInfo { PrePayID = result.GetValue("prepay_id").ToString(), }, false, out Message); if (Message != null) { return(null); } Message = null; return(jsApiParam.ToJson()); }
protected void Page_Load(object sender, EventArgs e) { int wxType = CRequest.GetInt("type"); string wxReurl = CRequest.GetString("reurl"); string wxCode = CRequest.GetString("code"); if (!Page.IsPostBack) { if (wxCode != "") { //获取全局token if (!WxLoginBLL.SaveXMLByApplactionToken()) { Log.WriterLog("获取全局token失败"); } WxAccessToken wx = WxLoginBLL.GetToken(wxCode); if (wx.openid != null) { WxUserInfo userInfo = WxLoginBLL.GetWxUserInfo(wx, wxCode); if (userInfo.openid != null) { object obj; WxUserInfoBLL uill = new WxUserInfoBLL(); uill.CheckUserInfo(userInfo); List <WxUserInfo> users = uill.QueryUserInfoByID(wx.openid); if (users != null && users.Count > 0) { string openId = CTools.SetOpenId(users[0].openid); obj = new { userid = users[0].u_id, openid = openId, token = CTools.GetMD5FromString(users[0].u_id + openId + "SSXXCJYXGS") }; Session["UserInfo"] = users[0]; Cookies.SetCookie("UserInfo", JsonHelper.ObjToJsonString <object>(obj), 90); Response.Redirect(WxConfig.WxHost); } } else { Response.Write("获取用户信息失败"); } } else { Response.Write("获取用户token失败"); } } } }
public void CheckUserInfo(WxUserInfo wx) { if (!userInfoDal.Exists(wx.openid)) { try { userInfoDal.Add(wx); } catch (Exception e) { Log.WriterLog(e.Source, e.Message); } } }
// 微信登陆成功 public void OnWxLoginSucess(WxUserInfo kWxUserInfo) { main = (int)MainCmd.MDM_MB_LOGON; sub = (int)MDM_GR_LOGON.SUB_MB_LOGON_OTHERPLATFORM; LoginData.wxUserInfo = kWxUserInfo; vxAccount = new CMD_GP_LogonAccounts(); vxAccount.dwPlazaVersion = LoginData.PlazaVersion; vxAccount.wModuleID = 65535; vxAccount.cbPlatformID = 5; //用户昵称 vxAccount.szNickName = new byte[64]; byte[] bt = NetUtil.StringToBytes(kWxUserInfo.nickname); Array.Copy(bt, vxAccount.szNickName, bt.Length); vxAccount.cbGender = (byte)kWxUserInfo.sex; //机器标识 vxAccount.szMachineID = new byte[66]; //bt = NetUtil.StringToBytes("A501164B366ECFC9E549163873094D50"); bt = NetUtil.StringToBytes(kWxUserInfo.openid); Array.Copy(bt, vxAccount.szMachineID, bt.Length); //真实名字 vxAccount.szCompellation = new byte[32]; //电话号码 vxAccount.szMobilePhone = new byte[24]; //用户Uin vxAccount.szUserUin = new byte[66]; bt = NetUtil.StringToBytes(kWxUserInfo.unionid); Array.Copy(bt, vxAccount.szUserUin, bt.Length); #region //s bt = NetUtil.StringToBytes("WX" + LoginData.wxUserInfo.openid); //Array.Copy(bt, vxAccount.szAccounts, bt.Length); //bt = NetUtil.StringToBytes(LoginData.wxUserInfo.headimgurl); //// Array.Copy(bt, vxAccount.szHeadHttp, bt.Length); //bt = NetUtil.StringToBytes("WeiXinPassword"); //Array.Copy(bt, vxAccount.szPassword, bt.Length); //GlobalDataScript.tagUserData = new TagGlobalUserData //{ // szAccounts = vxAccount.szAccounts, // // szHeadHttp = vxAccount.szHeadHttp, // szPassword = vxAccount.szPassword //}; #endregion send_buffer = NetUtil.StructToBytes(vxAccount); ISocketEngineSink(APIS.socketUrl, APIS.socketPort); UIManager.instance.Show(UIType.UILoading); // HttpManager.instance.GetWXReaure(url, ); }
public static WxUserInfo GetWxUserInfoByOpenID(string OpenID) { using (var EF = new EF()) { var user_exist = EF.WxUserInfos.FirstOrDefault(i => i.OpenID == OpenID); if (user_exist == null) { EF.WxUserInfos.Add(user_exist = new WxUserInfo { OpenID = OpenID, CreateTime = DateTime.Now }); EF.SaveChanges(); } return(user_exist); } }
public virtual ActionResult Register(string openid, string nickname, string headimgurl) { if (string.IsNullOrEmpty(openid)) { string thisUrl = HttpHelper.GetWebSite() + "/" + Request.RawUrl; return(Redirect(GetOAuthCallbackUrl(thisUrl, true))); } WxUserInfo wx = GetWxUserInfo(); if (wx != null) { return(View(wx)); } return(Content("尚未获得授权,请返回重试")); }
public HttpResponseMessage getWxToken(string code) { /** * 调用接口前提用户已经使用手机号注册 数据存在数据库中 * 此接口只需获取用户token时调用一次 * 用户token分两种 * access_token 有效期较短 只有两个小时 失效与否可以使用authToken() 判断 * refresh_token 有效期为30天 失效后调用此方法 重新获取用户token * 只返回用户openid */ HttpResponseMessage responseMessage = new HttpResponseMessage(); string url = "https://api.weixin.qq.com/sns/oauth2/access_token"; string data = "?appid=" + appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code"; string getJson = BaseController.HttpGet(url + data); JObject jo = (JObject)JsonConvert.DeserializeObject(getJson); if (jo.Property("errcode") == null && jo.Property("access_token") != null)//判断返回信息是否为错误信息 { //获取成功后存储用户唯一ID到用户信息表中 //在首页打开时候就弹出 无法获取到用户手机号 设置数据库中openid字段在用户正确获取验证码登陆后添加 //UserInfo userModel = userSer.Where(a => a.UserTel == tel).FirstOrDefault(); //userModel.WxOpenid = jo["openid"].ToString(); //userSer.Update(userModel); //以用户openid或者用户手机号为键名 存储用户token信息 以及用户其他信息 WxUserInfo wxUser = new WxUserInfo(); wxUser = JsonConvert.DeserializeObject <WxUserInfo>(getJson); //wxUser.UserTel = tel; wxUser.getdate = DateTime.Now; //将用户信息序列化为json存储到redis中 var db = RedisManager.Instance.GetDatabase(); db.StringSet(wxUser.openid, JsonConvert.SerializeObject(wxUser)); //前台返回信息 只返回用户openid存储到本地 responseMessage = new HttpResponseMessage { Content = new StringContent(wxUser.openid, Encoding.GetEncoding("UTF-8"), "text/plain") }; return(responseMessage); } else { //直接返回错误信息 responseMessage = new HttpResponseMessage { Content = new StringContent(getJson, Encoding.GetEncoding("UTF-8"), "text/plain") }; return(responseMessage); } }
public Sys_User Regist(WxUserInfo UserEntity) { try { var filter = string.Format(" WeiXin_Openid='{0}' ", UserEntity.openid); var entity = base.SelectByFilter(filter).FirstOrDefault(); if (entity == null) { entity = new Sys_User { UserID = Utils.CreateGUID(), UserName = UserEntity.nickname, WeiXin_Openid = UserEntity.openid, CreateTime = DateTime.Now, HeaderUrl = UserEntity.headimgurl, Sex = UserEntity.sex, }; if (base.Insert(entity)) { new UserAccountService().CreateAccount(entity.UserID); } else { return(null); } } else { entity.UserName = UserEntity.nickname; entity.Sex = UserEntity.sex; entity.HeaderUrl = UserEntity.headimgurl; if (!base.Update(entity)) { return(null); } } return(entity); } catch (Exception) { return(null); } }
public async Task <int> UpdateAsync(WxUserInfo entity) { string sql = @" UPDATE wxuserinfo SET UnionId = @UnionId, NickName = @NickName, Avatar = @Avatar, Gender = @Gender, Country = @Country, Province = @Province, City = @City, UpdateTime = @UpdateTime, UpdateBy = @UpdateBy WHERE Id = @Id;"; var id = await Instance.ExecuteAsync(sql, entity); return(id); }
/// <summary> /// 保存微信用户信息 /// </summary> /// <param name="wxUserInfo"></param> public void SetWxUserInfo(OAuthUserInfo userInfo) { WxUserInfo wxUserInfo = new WxUserInfo(); wxUserInfo.UserId = ""; wxUserInfo.OpenId = userInfo.openid; wxUserInfo.NickName = userInfo.nickname; wxUserInfo.Sex = userInfo.sex; wxUserInfo.Headimgurl = userInfo.headimgurl; wxUserInfo.Province = userInfo.province; wxUserInfo.City = userInfo.city; wxUserInfo.Country = userInfo.country; wxUserInfo.Unionid = userInfo.unionid; Session[SysKeys.SESSION_WXUSER_INFO] = wxUserInfo; Session.Timeout = 45; //写入Cookies WebHelper.WriteCookie(wxuserKey, DESEncrypt.Encrypt(wxUserInfo.ToJson()), 60); }
private string UpdateFromWx() { WxUserInfo wxHelper = new WxUserInfo(); string id = Request.Form["Id"]; string type = Request.Form["type"]; string res = ""; if (type == "department") { object val = wxHelper.GetWxDepartmentJson(id); res = UserInfoManage.SaveDepartmentFromWx(val); } else { object val = wxHelper.GetWxUserInfoJsonByDepartmentId("1"); res = UserInfoManage.SaveUserInfoFromWx(val); } return(res); }
//public ActionResult Login() //{ // string code = Request.QueryString["code"]; // string state = Request.QueryString["state"]; // string s = Request.QueryString["s"]; // if (!IsLogin) // { // OAuthAccessTokenResult result = OAuthApi.GetAccessToken(tenPayV3Info.AppId, tenPayV3Info.AppSecret, code); // if (result.errcode == Senparc.Weixin.ReturnCode.请求成功) // { // string openid = result.openid; // UserService x_userService = new UserService(); // var item = x_userService.Get(a => a.OpenId == openid).FirstOrDefault(); // if (item != null) // { // if (item.IsValid == 1) // { // Authentication.Instance.SetAuth(item, true); // } // else // { // return Redirect("/"); // } // } // else //获取用户的信息 // { // OAuthUserInfo wxUser = OAuthApi.GetUserInfo(result.access_token, code); // if (wxUser != null) // { // UserInfo uInfo = new UserInfo() // { // IsValid = 1, // CreateTime = DateTime.Now, // Lastlogintime = DateTime.Now, // NickName = wxUser.nickname, // OpenId = wxUser.openid, // HeadImage = wxUser.headimgurl // }; // uInfo.ID = Convert.ToInt32(x_userService.Insert(uInfo)); // Authentication.Instance.SetAuth(uInfo, true); // } // else // { // return Redirect("/"); // } // } // } // } // string url = "/"; // if (!string.IsNullOrEmpty(s)) // { // url = s; // } // return Redirect(url); //} public ActionResult RecLogin() { string json = Request.Form["jsondata"]; string data = AESHelper.Decode(json); //Logging4net.WriteInfo(data); if (!string.IsNullOrEmpty(data)) { JavaScriptSerializer jss = new JavaScriptSerializer(); WxUserInfo wxu = jss.Deserialize <WxUserInfo>(data); UserService x_userService = new UserService(); var item = x_userService.Get(a => a.OpenId == wxu.openid).FirstOrDefault(); if (item != null) { Logging4net.WriteInfo("isvalid:" + item.IsValid); if (item.IsValid == 1) { Authentication.Instance.SetAuth(item, true); return(RedirectToAction("index", "home")); } } else { UserInfo uInfo = new UserInfo() { IsValid = 1, CreateTime = DateTime.Now, //Lastlogintime = DateTime.Now, NickName = wxu.nickname, OpenId = wxu.openid, HeadImage = wxu.headimgurl, SubTime = DateTime.Now.AddYears(-100) }; uInfo.ID = Convert.ToInt32(x_userService.Insert(uInfo)); Authentication.Instance.SetAuth(uInfo, true); return(RedirectToAction("index", "home")); } } return(RedirectToAction("index", "home")); }