public object Do_Login(BaseApi baseApi) { LoginParam loginParam = JsonConvert.DeserializeObject <LoginParam>(baseApi.param.ToString()); if (loginParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } var jsonResult = SnsApi.JsCode2Json(Global.APPID, Global.APPSECRET, loginParam.code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { AccessTokenContainer.Register(Global.APPID, Global.APPSECRET); var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); SessionUser sessionUser = new SessionUser(); sessionUser.userType = ""; sessionUser.openid = sessionBag.OpenId; sessionBag.Name = JsonConvert.SerializeObject(sessionUser); SessionContainer.Update(sessionBag.Key, sessionBag); return(new { token = sessionBag.Key, isReg = true }); } else { throw new ApiException(CodeMessage.SenparcCode, jsonResult.errmsg); } }
public JsonResponse OnLogin([FromBody] string code) { try { var jsonResult = SnsApi.JsCode2Json("wxf40f763aa2171652", "06c9233a3d979d45f665dbb507a01115", code); if (jsonResult.errcode == ReturnCode.请求成功) { var unionId = ""; var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId); HttpRuntime.Cache.Insert($"{sessionBag.OpenId}_openid", sessionBag.OpenId, null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration, CacheItemPriority.High, null); HttpRuntime.Cache.Insert($"{sessionBag.OpenId}_unionid", sessionBag.UnionId, null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration, CacheItemPriority.High, null); return(FastResponse(new { IsSuccess = true, Message = "", sessionId = sessionBag.Key, openId = sessionBag.OpenId, unionId = sessionBag.UnionId })); } else { return(FastResponse(new { IsSuccess = false, Message = jsonResult.errmsg })); } } catch (Exception ex) { return(FastResponse(new { IsSuccess = false, Message = ex.Message })); } }
public IActionResult GetOpenId(string code) { CommonResult result = new CommonResult(); try { var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code); if (jsonResult.errcode == ReturnCode.请求成功) { //使用SessionContainer管理登录信息(推荐) var unionId = jsonResult.unionid; var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, jsonResult.unionid); //ValidateUserLogin(openId); result.ResData = new { openId = jsonResult.openid, sessionId = sessionBag.Key }; result.ErrCode = ErrCode.successCode; } else { result.ErrMsg = jsonResult.errmsg; } } catch (Exception ex) { result.ErrMsg = ex.Message; } return(ToJsonContent(result)); }
public void DecodeUserInfoBySessionIdTest() { var sessionId = "ABCDEFG"; var sessionKey = "/mGmINZAe+7k6kNz32wxSw=="; var encryptedData = "CFcsIXmH2r0v9ehjEhS+uUpJkr8qGQyt+Za3YkhjVNNA+xGj2WB2QFxDXdKVSzc10LukeB2maCxZCqpPQrWQx6CKF/VkEx96hXpPuBMpWBnnLzupoJpkRW9gJGRz7dcXDnqzstf2etRumDeAFDyjEKZ6bqs+KTE7qHauMsctxg4TXPbzzvWQm783j9PoWsCm/0A+aGNWCfZSFuJgi5G+LjTVqcGqP+mlAnLIFmgGLTo3vWrekz0//2vCMhgcgwKjPMR+VZTB7UItvnWfF4h4oOajcMuEiwTifaFkyn7l4NtLroMYjOfId16B6XCTK0BvPhTw9GI3wPMDopwWF2q3Op8M2fYWJuVGFKbrAZvVY/ILeIxYLaHuwHAOYULLre5Mg1kQpURlQ6I6e6GjraJUoL1BqsM38DayY5xRRFJsehZgrWkOySWICuN20Bte7+2N8D6PvhsaNyQz+4Lp4XY/Nn+clNGoM1v6aKTCv7PY2wo="; var iv = "ASJ0whjRyLK1tvgb7bAVSw=="; var unionId = ""; SessionContainer.UpdateSession(sessionId, "OpenId", sessionKey, unionId); var userInfo = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeUserInfoBySessionId(sessionId, encryptedData, iv); Assert.IsNotNull(userInfo); Assert.AreEqual("wxfcb0a0031394a51c", userInfo.watermark.appid); Console.WriteLine(SerializerHelper.GetJsonString(userInfo)); //测试 EncryptHelper.DecodeEncryptedData() 方法 var userInfoStr = EncryptHelper.DecodeEncryptedData(sessionKey, encryptedData, iv); Console.WriteLine("userInfoStr:"); Console.WriteLine(SerializerHelper.GetJsonString(userInfoStr)); }
public ActionResult GetThirdSessionId([FromBody] GetThirdSessionIdRequest request) { try { var jsonResult = SnsApi.JsCode2Json("wxa0d2127a7dc890b8", "", request.Code); if (jsonResult.errcode == ReturnCode.请求成功) { var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); //注意:生产环境下SessionKey属于敏感信息,不能进行传输! return(Ok(new { success = true, msg = "OK", sessionId = sessionBag.Key })); } else { return(Ok(new { success = false, msg = jsonResult.errmsg })); } } catch (Exception ex) { if (ex is ErrorJsonResultException) { return(Ok(new { success = false, msg = ex.Message })); } return(Ok(new { success = false, msg = ex.Message })); } }
public ActionResult OnLogin(string code) { try { var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code); if (jsonResult.errcode == ReturnCode.请求成功) { //使用SessionContainer管理登录信息(推荐) var unionId = jsonResult.unionid; var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId); //注意:生产环境下SessionKey属于敏感信息,不能进行传输! //return Json(new { success = true, msg = "OK", sessionId = sessionBag.Key }); return(Json(HttpResult.Success(new { sessionId = sessionBag.Key }))); } else { //return Json(new { success = false, msg = jsonResult.errmsg }); return(Json(HttpResult.WeChatError(jsonResult.errmsg, null))); } } catch (Exception ex) { return(Json(HttpResult.WeChatError(ex.Message, null))); } }
public void SerializeDataTest() { var sessionBag = SessionContainer.UpdateSession(null, "OpenId", "SessionKey"); var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(sessionBag); Console.WriteLine(jsonString); }
public JsonResponse OnLogin(string code) { try { var jsonResult = SnsApi.JsCode2Json("wxad6fecee3bf4ba2f", "f2b4532be0ba85edee3425bfa86f2187", code); if (jsonResult.errcode == ReturnCode.请求成功) { var unionId = ""; var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId); HttpRuntime.Cache.Insert($"{sessionBag.OpenId}_openid", sessionBag.OpenId, null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration, CacheItemPriority.High, null); HttpRuntime.Cache.Insert($"{sessionBag.OpenId}_unionid", sessionBag.UnionId, null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration, CacheItemPriority.High, null); return(FastResponse(new { IsSuccess = true, Message = "", sessionId = sessionBag.Key, openId = sessionBag.OpenId, unionId = sessionBag.UnionId })); } else { return(FastResponse(new { IsSuccess = false, Message = jsonResult.errmsg })); } } catch (Exception ex) { return(FastResponse(new { IsSuccess = false, Message = ex.Message })); } }
public ActionResult OnLogin(string code) { try { var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code); if (jsonResult.errcode == ReturnCode.请求成功) { //Session["WxOpenUser"] = jsonResult;//使用Session保存登陆信息(不推荐) //使用SessionContainer管理登录信息(推荐) var unionId = ""; var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId); //注意:生产环境下SessionKey属于敏感信息,不能进行传输! return(Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, sessionKey = sessionBag.SessionKey })); } else { return(Json(new { success = false, msg = jsonResult.errmsg })); } } catch (Exception ex) { return(Json(new { success = false, msg = ex.Message })); } }
public async Task <IActionResult> Login([FromBody] LoginModel loginMode) { try { var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, loginMode.code); if (jsonResult.errcode == ReturnCode.请求成功) { //Session["WxOpenUser"] = jsonResult;//使用Session保存登陆信息(不推荐) //使用SessionContainer管理登录信息(推荐) if (!_context.User.Any(u => u.OpenID == jsonResult.openid)) { var userinfo = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(Senparc.Weixin.MP.Containers.AccessTokenContainer.GetAccessToken(WxOpenAppId), jsonResult.openid); var adduser = _context.User.Add(new WeWaiter.Data.User() { UserID = Guid.NewGuid().ToString().Replace("-", ""), JoinIn = DateTime.Now, LastActive = DateTime.Now, OpenID = jsonResult.openid, NickName = userinfo.nickname, Sex = userinfo.sex, City = userinfo.city, Country = userinfo.country, Language = userinfo.language, Province = userinfo.province, Subscribe = userinfo.subscribe, SubscribeScene = userinfo.subscribe_scene, SubscribeTime = userinfo.subscribe_time, UnionId = userinfo.unionid, Remark = userinfo.remark }); await _context.SaveChangesAsync(); } var usr = _context.User.FirstOrDefault(u => u.OpenID == jsonResult.openid); if (usr != null) { //https://github.com/aspnet/Home/issues/2193 var token = usr.CreateJsonWebToken(_appSettings); var sessionBag = SessionContainer.UpdateSession(usr.UserID, jsonResult.openid, jsonResult.session_key, jsonResult.unionid); return(Ok(new { code = 0, msg = "OK", token, ImageHost = Utils.Server.ImageHost })); } else { return(Ok(new { code = 1007, msg = "未能正确获取到用户数据" })); } } else { return(Ok(new { code = 1006, msg = jsonResult.errmsg })); } } catch (Exception ex) { return(Ok(new { code = 1008, msg = ex.Message })); } }
/// <summary> /// 登陆 /// </summary> /// <param name="baseApi"></param> /// <returns></returns> public object Do_GetToken(BaseApi baseApi) { LoginParam loginParam = JsonConvert.DeserializeObject <LoginParam>(baseApi.param.ToString()); if (loginParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } if (loginParam.code == Global.XCSECRET) { SessionBag sessionBagX = SessionContainer.GetSession(Global.XCOPENID); if (sessionBagX != null) { if (sessionBagX.Name != "") { SessionContainer.RemoveFromCache(sessionBagX.OpenId); } } AccessTokenContainer.Register(Global.APPID, Global.APPSECRET); var sessionBag = SessionContainer.UpdateSession(null, Global.XCOPENID, Global.XCOPENID); OpenDao openDao = new OpenDao(); SessionUser sessionUser = new SessionUser(); Member member = openDao.GetMember(Utils.GetOpenID(sessionBag.Key)); if (member == null) { throw new ApiException(CodeMessage.SenparcCode, CodeMessage.SenparcCode.ToString()); } else { sessionUser.userType = "MEMBER"; sessionUser.openid = sessionBag.OpenId; sessionUser.memberId = member.memberId; sessionBag.Name = JsonConvert.SerializeObject(sessionUser); SessionContainer.Update(sessionBag.Key, sessionBag); SessionBag bag = new SessionBag(); bag.Name = sessionBag.Key; SessionContainer.UpdateSession(Global.XCOPENID, sessionBag.Key, sessionBag.Key); return(new { token = sessionBag.Key }); } } else { throw new ApiException(CodeMessage.SenparcCode, CodeMessage.SenparcCode.ToString()); } }
public object Do_ShopUserLogin(BaseApi baseApi) { LoginParam loginParam = JsonConvert.DeserializeObject <LoginParam>(baseApi.param.ToString()); if (loginParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } var jsonResult = SnsApi.JsCode2Json(Global.STOREAPPID, Global.STOREAPPSECRET, loginParam.code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { AccessTokenContainer.Register(Global.STOREAPPID, Global.STOREAPPSECRET); var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, jsonResult.unionid); OpenDao openDao = new OpenDao(); SessionUser sessionUser = new SessionUser(); StoreUser storeUser = openDao.GetStoreUser(Utils.GetOpenID(sessionBag.Key)); if (storeUser == null) { sessionUser.userType = "UNKWON"; sessionBag.Name = JsonConvert.SerializeObject(sessionUser); SessionContainer.Update(sessionBag.Key, sessionBag, new TimeSpan(Global.SESSION_EXPIRY_H, Global.SESSION_EXPIRY_M, Global.SESSION_EXPIRY_S)); return(new { token = sessionBag.Key, isReg = false }); } else { sessionUser.userType = "STORE"; sessionUser.openid = sessionBag.OpenId; sessionUser.storeUserId = storeUser.storeUserId; sessionBag.Name = JsonConvert.SerializeObject(sessionUser); SessionContainer.Update(sessionBag.Key, sessionBag, new TimeSpan(Global.SESSION_EXPIRY_H, Global.SESSION_EXPIRY_M, Global.SESSION_EXPIRY_S)); return(new { token = sessionBag.Key, isReg = true, storeUser.storeId, storeUser.storeUserId, storeUser.storeUserName, storeUser.storeUserImg, storeUser.storeUserPhone, storeUser.storeUserSex }); } } else { throw new ApiException(CodeMessage.SenparcCode, jsonResult.errmsg); } }
/// <summary> /// 登陆 /// </summary> /// <param name="baseApi"></param> /// <returns></returns> public object Do_Login(BaseApi baseApi) { LoginParam loginParam = JsonConvert.DeserializeObject <LoginParam>(baseApi.param.ToString()); if (loginParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } var jsonResult = SnsApi.JsCode2Json(Global.APPID, Global.APPSECRET, loginParam.code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { AccessTokenContainer.Register(Global.APPID, Global.APPSECRET); var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); OpenDao openDao = new OpenDao(); SessionUser sessionUser = new SessionUser(); Member member = openDao.GetMember(Utils.GetOpenID(sessionBag.Key)); if (member == null) { sessionUser.userType = "GUEST"; sessionBag.Name = JsonConvert.SerializeObject(sessionUser); SessionContainer.Update(sessionBag.Key, sessionBag); return(new { token = sessionBag.Key, isReg = false }); } else { sessionUser.userType = "MEMBER"; sessionUser.openid = sessionBag.OpenId; sessionUser.memberId = member.memberId; sessionBag.Name = JsonConvert.SerializeObject(sessionUser); SessionContainer.Update(sessionBag.Key, sessionBag); return(new { token = sessionBag.Key, isReg = true, member.memberId, member.memberName, member.memberImg, member.memberPhone, member.memberSex, member.scanCode }); } } else { throw new ApiException(CodeMessage.SenparcCode, jsonResult.errmsg); } }
public ActionResult OnLogin(string code) { JsCode2JsonResult jsonResult = SnsApi.JsCode2Json(Comman.Appid, Comman.AppSecret, code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { SessionBag sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); Session[sessionBag.Key] = jsonResult; Session.Timeout = 60; StatusReport sr = EmployeeDal.CheckOpenIdExist(jsonResult.openid); return(Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, userInfo = sr })); } else { return(Json(new { success = false, mag = jsonResult.errmsg, result = jsonResult })); } }
public static string TryWeappAutoLogin(this IAccessControl ac, JObject data, out string errMsg) { errMsg = null; var app = ac.Context.RequestServices.GetService <IWeChatContainer>().GetApp(); var session = data.GetValue("sessionid", key => SessionContainer.GetSession(key)); if (session == null) { // session未建立,通过code登录换取session var result = WeChatApi.WxLogin(app, data.GetValue("code", "")); if (result.ErrorCodeValue == 0) { // success,成功时更新session session = SessionContainer.UpdateSession(null, result.openid, result.session_key, result.unionid); } else { errMsg = result.errmsg; } } if (session != null) { // 根据OpenID自动登录 var service = ac.Context.RequestServices.GetService <IUserService>(); var user = service.GetByAuth(app.Id, session.OpenId); if (user == null) { // OpenID对应的用户不存在,解密客户端数据 var cryptedData = data.GetValue("encryptedData", ""); var iv = data.GetValue("iv", ""); var userInfo = EncryptHelper.DecodeUserInfoBySessionId(session.Key, cryptedData, iv); // 自动创建用户 var mobile = data.GetValue <string>("mobile"); var wechatService = ac.Context.RequestServices.GetService <IWechatService>(); user = wechatService.WeappRegist(app, userInfo, mobile); } return($"{user.HashId}-{session.SessionKey}"); } return(null); }
public void UpdateSessionTest() { var openId = "openid"; var sessionKey = "sessionKey"; var bag = SessionContainer.UpdateSession(null, openId, sessionKey); Console.WriteLine("bag.Key:{0}", bag.Key); Console.WriteLine("bag.ExpireTime:{0}", bag.ExpireTime); var key = bag.Key; Thread.Sleep(1000); var bag2 = SessionContainer.GetSession(key); Assert.IsNotNull(bag2); Console.WriteLine("bag2.ExpireTime:{0}", bag2.ExpireTime); }
public void DecodeEncryptedDataTest() { Init(); var sessionId = "ABCDEFG"; var sessionKey = "/mGmINZAe+7k6kNz32wxSw=="; var encryptedData = "CFcsIXmH2r0v9ehjEhS+uUpJkr8qGQyt+Za3YkhjVNNA+xGj2WB2QFxDXdKVSzc10LukeB2maCxZCqpPQrWQx6CKF/VkEx96hXpPuBMpWBnnLzupoJpkRW9gJGRz7dcXDnqzstf2etRumDeAFDyjEKZ6bqs+KTE7qHauMsctxg4TXPbzzvWQm783j9PoWsCm/0A+aGNWCfZSFuJgi5G+LjTVqcGqP+mlAnLIFmgGLTo3vWrekz0//2vCMhgcgwKjPMR+VZTB7UItvnWfF4h4oOajcMuEiwTifaFkyn7l4NtLroMYjOfId16B6XCTK0BvPhTw9GI3wPMDopwWF2q3Op8M2fYWJuVGFKbrAZvVY/ILeIxYLaHuwHAOYULLre5Mg1kQpURlQ6I6e6GjraJUoL1BqsM38DayY5xRRFJsehZgrWkOySWICuN20Bte7+2N8D6PvhsaNyQz+4Lp4XY/Nn+clNGoM1v6aKTCv7PY2wo="; var iv = "ASJ0whjRyLK1tvgb7bAVSw=="; SessionContainer.UpdateSession(sessionId, "OpenId", sessionKey); var result = target.DecodeEncryptedData("userInfo", sessionId, encryptedData, iv); Assert.IsNotNull(result); }
public ActionResult OnLogin(string code) { var jsonResult = SnsApi.JsCode2Json(Common.Appid, Common.AppSecret, code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { //Session["WxOpenUser"] = jsonResult; var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); Session[sessionBag.Key] = jsonResult; Session.Timeout = 60; return(Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, result = Session[sessionBag.Key] })); } else { return(Json(new { success = false, mag = jsonResult.errmsg, result = jsonResult })); } }
public ActionResult OnLogin(string code) { try { var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code); if (jsonResult.errcode == ReturnCode.请求成功) { //Session["WxOpenUser"] = jsonResult;//使用Session保存登陆信息(不推荐) //使用SessionContainer管理登录信息(推荐) //var unionId = ""; var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, jsonResult.unionid); var userInfo = _userWeChatInfoServices.Exists(p => p.openid == jsonResult.openid); if (userInfo == false) { var user = new CoreCmsUserWeChatInfo(); user.openid = jsonResult.openid; user.type = (int)GlobalEnumVars.UserAccountTypes.微信小程序; user.sessionKey = sessionBag.SessionKey; user.gender = 1; user.createTime = DateTime.Now; var id = _userWeChatInfoServices.Insert(user); if (id > 0) { _userWeChatInfoServices.Update(p => new CoreCmsUserWeChatInfo() { userId = id }, p => p.id == id); } } //注意:生产环境下SessionKey属于敏感信息,不能进行传输! //return Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, sessionKey = sessionBag.SessionKey, data = jsonResult, sessionBag = sessionBag }); return(Json(new { success = true, msg = "OK", sessionId = sessionBag.Key })); } else { return(Json(new { success = false, msg = jsonResult.errmsg })); } } catch (Exception ex) { return(Json(new { success = false, msg = ex.Message })); } }
public ActionResult OnLogin(string code) { var jsonResult = SnsApi.JsCode2Json(SenparcClass.Service.Config.WxOpenAppId, SenparcClass.Service.Config.WxOpenAppSecret, code); if (jsonResult.errcode == ReturnCode.请求成功) { //Session["WxOpenUser"] = jsonResult;//使用Session保存登陆信息(不推荐) //使用SessionContainer管理登录信息(推荐) var sessionBag = SessionContainer.UpdateSession("ApartmentRent", jsonResult.openid, jsonResult.session_key); //注意:生产环境下SessionKey属于敏感信息,不能进行传输! return(Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, sessionKey = sessionBag.SessionKey })); } else { return(Json(new { success = false, msg = jsonResult.errmsg })); } }
public ActionResult OnLogin(string code, string shareNumber, string userId, string userName, string shareTime, string kindergartenName) { StatusReport sr = new StatusReport(); var jsonResult = SnsApi.JsCode2Json(Comman.Appid, Comman.AppSecret, code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { //Session["WxOpenUser"] = jsonResult; var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); Session[sessionBag.Key] = jsonResult; Session.Timeout = 60; sr = WXUserDal.SetNewUser(jsonResult.openid, kindergartenName); if (sr.status == "Success") { User user = (User)sr.data; string receiverId = user.id; if (!string.IsNullOrEmpty(shareNumber) && !string.IsNullOrEmpty(userId) && !string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(shareTime)) { if (userId != receiverId) { sr = WXShareDal.SetShareInfo(receiverId, shareNumber, userId, userName, shareTime, kindergartenName); using (StreamWriter sw = new StreamWriter("D:\\1_importTemp\\TestFile1.txt")) { sw.WriteLine(sr.result.ToString()); } } } sr.data = new { success = true, msg = "OK", sessionId = sessionBag.Key, user = user }; } else { sr.data = new { success = true, msg = "OK", sessionId = sessionBag.Key }; } return(Json(sr)); } else { sr.status = "Fail"; sr.data = new { success = false, mag = jsonResult.errmsg, result = jsonResult }; return(Json(sr)); //return Json(new { success = false, mag = jsonResult.errmsg, result = jsonResult }); } }
public void DecodeUserInfoBySessionIdTest2() { //测试 issue:https://github.com/JeffreySu/WeiXinMPSDK/issues/1825 var sessionId = "ABCDEFGHIJK"; var sessionKey = "0sVkQ4CtcaiYJtvoPLBecw=="; var encryptedData = "GiW4s+17o7RSaPOwGX8Ir1+3c/RYbHKvRzBg8UFlmIIiArLtU0ctkzjq1LRR5MH5CSPs63Jt4qCoFScSlRKlQ4/RVXXJFQV+r/1L+qKv/PdHRvVDLb+8P6CvPTurEuHsxlLyXTnnlEIu6IFYFzZWBMIp6+SHEK85mEb1gw4BtMmEy9EitnMskNjsEnmpI3M9r8ItKyQ8hinJejuno0JPXn3trc+2gMheNt4+4NwMTM6mzzGVO6g40NP7NjK9Tl6+An2TjBe+GGVFdrkl5hpYDXE/YO2FsL909faX3Y08msSuCVk5AsMGMJiUwddiu44KODdxCYfwLxBaIgYJEY6xLygFmAMuDg/L2g4/wDabBrhA5BNsD6lrcRRbvrHK65Lu3xd1oTXyMGbfUGTD4GLlLSJUX2FhcG7ZmHwg1jQUuKFHJu/AMQgdoPa/JONAu5Hjp0hL7ahr5LC0ghwdTfTowg3X1Ko9IgRxxj755eGgXQK7AnsMwjXzt4X+4YpOYpCb2LVSrTV2t4QjVNPe+Rjmsg=="; var iv = "4y2ftkwAM2mF6Qc89HydpA=="; var unionId = ""; SessionContainer.UpdateSession(sessionId, "OpenId", sessionKey, unionId); var userInfo = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeUserInfoBySessionId(sessionId, encryptedData, iv); Assert.IsNotNull(userInfo); Assert.AreEqual("wxfcb0a0031394a51c", userInfo.watermark.appid); Console.WriteLine(SerializerHelper.GetJsonString(userInfo)); }
public void CheckSignatureTest() { //储存Session var sessionId = "7f3f7489cb904d20bd4b5e9443f1bcab"; var rawData = "{\"nickName\":\"苏震巍\",\"gender\":1,\"language\":\"zh_CN\",\"city\":\"Suzhou\",\"province\":\"Jiangsu\",\"country\":\"CN\",\"avatarUrl\":\"http://wx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEKXyjX4N6I5Vx1aeiaBeJ2iaTLy15n0HgvjNbWEpKA3ZbdgXkOhWK7OH8iar3iaLxsZia5Ha4DnRPlMerw/0\"}"; var sessionKey = "lEIWEBVlmAj/Ng0t54iahA=="; var unionId = ""; SessionContainer.UpdateSession(sessionId, "openId", sessionKey, unionId); var sessionBag = SessionContainer.GetSession(sessionId); Assert.IsNotNull(sessionBag); Assert.AreEqual(sessionKey, sessionBag.SessionKey); var compareSignature = "1149a88c75125de3146040c90d7bcc4b2a564a34"; var result = EncryptHelper.CheckSignature(sessionId, rawData, compareSignature); Assert.IsTrue(result); }
private string GetWechatSessionId(string weiXinCode) { if (environment.EnvironmentName == "dev" || environment.EnvironmentName == "qa") { var tag = SessionContainer.UpdateSession(null, "071TIDkB14xCof0eHekB1I4NkB1TIDk5", "071TIDkB14xCof0eHekB1I4NkB1TIDk5"); return(tag.Key); } var jsonResult = SnsApi.JsCode2Json(wxConfiguration.AppId, wxConfiguration.AppSecret, weiXinCode); if (jsonResult.errcode == ReturnCode.请求成功) { SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); return(jsonResult.openid); } else { logger.LogError(JsonConvert.SerializeObject(jsonResult)); } return(string.Empty); }
public ActionResult OnLogin(string code) { StatusReport sr = new StatusReport(); var jsonResult = SnsApi.JsCode2Json(Common.Appid, Common.AppSecret, code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); Session[sessionBag.Key] = jsonResult; Session.Timeout = 60; string openId = sessionBag.OpenId; sr = ProprietorDal.CheckOpenIdExist(openId); sr.parameters = sessionBag.Key; return(Json(sr)); //return Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, result = Session[sessionBag.Key] }); } else { return(Json(sr.SetFail("微信登录失败:" + jsonResult.errmsg))); //return Json(new { success = false, mag = jsonResult.errmsg, result = jsonResult }); } }
public object Do_Login(object param) { LoginParam loginParam = JsonConvert.DeserializeObject <LoginParam>(param.ToString()); if (loginParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } var jsonResult = SnsApi.JsCode2Json(Global.APPID, Global.APPSECRET, loginParam.code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { var manager = Senparc.Weixin.Cache.Redis.RedisManager.Manager; AccessTokenContainer.Register(Global.APPID, Global.APPSECRET); var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key); return(new { sessionId = sessionBag.Key }); } else { throw new ApiException(CodeMessage.SenparcCode, jsonResult.errmsg); } }
/// <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); }
public object Do_Login(BaseApi baseApi) { LoginParam loginParam = JsonConvert.DeserializeObject <LoginParam>(baseApi.param.ToString()); if (loginParam == null) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } var jsonResult = SnsApi.JsCode2Json(Global.APPID, Global.APPSECRET, loginParam.code); if (jsonResult.errcode == Senparc.Weixin.ReturnCode.请求成功) { AccessTokenContainer.Register(Global.APPID, Global.APPSECRET); var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, jsonResult.unionid); OpenDao openDao = new OpenDao(); SessionUser sessionUser = new SessionUser(); if (loginParam.tempOpenId != null && loginParam.tempOpenId.StartsWith("3rd-")) { Member member1 = openDao.GetMember(Utils.GetOpenID(sessionBag.Key)); if (member1 == null) { openDao.UpdateMemberOpenID(Utils.GetOpenID(sessionBag.Key), loginParam.tempOpenId); } else { Member member2 = openDao.GetMember(loginParam.tempOpenId); if (member1.openid != member2.openid) { openDao.MoveMember(member1.memberId, member2.memberId, member2.heart); } } } Member member = openDao.GetMember(Utils.GetOpenID(sessionBag.Key)); if (member == null) { sessionUser.userType = "GUEST"; sessionBag.Name = JsonConvert.SerializeObject(sessionUser); SessionContainer.Update(sessionBag.Key, sessionBag, new TimeSpan(Global.SESSION_EXPIRY_H, Global.SESSION_EXPIRY_M, Global.SESSION_EXPIRY_S)); return(new { token = sessionBag.Key, isReg = false }); } else { sessionUser.userType = "MEMBER"; sessionUser.openid = sessionBag.OpenId; sessionUser.memberId = member.memberId; sessionBag.Name = JsonConvert.SerializeObject(sessionUser); SessionContainer.Update(sessionBag.Key, sessionBag, new TimeSpan(Global.SESSION_EXPIRY_H, Global.SESSION_EXPIRY_M, Global.SESSION_EXPIRY_S)); openDao.AddMemberHeartCommit(member); return(new { token = sessionBag.Key, isReg = true, member.memberId, member.memberName, member.memberImg, member.memberPhone, member.memberSex, member.scanCode }); } } else { throw new ApiException(CodeMessage.SenparcCode, jsonResult.errmsg); } }
public IActionResult WxLogin([FromBody] JObject data) { SessionBag sessionBag = null; var sessionId = data.GetValue("sessionid", ""); if (sessionId.HasValue()) { sessionBag = SessionContainer.GetSession(sessionId); } string message = null; if (sessionBag == null) { var code = data.GetValue("code", ""); var result = WeChatApi.WxLogin(app, code); if (result.ErrorCodeValue == 0) { sessionBag = SessionContainer.UpdateSession(null, result.openid, result.session_key, result.unionid); } else { message = result.errmsg; } } else { var obj = AppCtx.Session.ExecuteScalar( new RequestContext("wx", "exec_wx_login") .SetParam(new { appid = app.Id, authtype = "wechat", authid = sessionBag.OpenId }) ); if (obj == null) { var cryptedData = data.GetValue("encryptedData", ""); var iv = data.GetValue("iv", ""); var decodedUserInfo = EncryptHelper.DecodeUserInfoBySessionId(sessionBag.Key, cryptedData, iv); obj = AppCtx.Session.ExecuteScalar( new RequestContext("wx", "exec_wx_regist") .SetParam(new { newid = App.IdWorker.NextId(), nickname = decodedUserInfo.nickName, photo = decodedUserInfo.avatarUrl, province = decodedUserInfo.province, city = decodedUserInfo.city, country = decodedUserInfo.country, appid = app.Id, authtype = "wechat", authid = decodedUserInfo.openId, unionid = decodedUserInfo.unionId }) ); } return(Json(new { success = true, token = $"{sessionBag.Key}", message = "ok" })); } return(Json(new { success = false, message })); }
public IActionResult OnLogin(string code) { CommonResult result = new CommonResult(); try { var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code); if (jsonResult.errcode == ReturnCode.请求成功) { //使用SessionContainer管理登录信息(推荐) var unionId = jsonResult.unionid; var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId); //注意:生产环境下SessionKey属于敏感信息,不能进行传输! //return Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, sessionKey = sessionBag.SessionKey }); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); //User user = userApp.GetUserByUnionId(unionId); User user = userService.GetUserByOpenId("yuebon.openid.wxapplet", jsonResult.openid); if (user == null) { UserInputDto userInput = new UserInputDto(); userInput.OpenId = jsonResult.openid; user.UnionId = jsonResult.unionid; userInput.OpenIdType = "yuebon.openid.wxapplet"; userInput.NickName = "游客"; userInput.UnionId = jsonResult.unionid; result.Success = userService.CreateUserByWxOpenId(userInput); } //针对老用户更新UnionId if (user != null && string.IsNullOrEmpty(user.UnionId)) { user.UnionId = jsonResult.unionid; result.Success = userService.Update(user, user.Id); } string userId = string.Empty; if (result.ResData != null) { userId = result.ResData.ToString(); } if (user == null) { user = userService.GetUserByOpenId("yuebon.openid.wxapplet", jsonResult.openid); } var currentSession = (YuebonCurrentUser)(yuebonCacheHelper.Get("login_user_" + userId)); if (currentSession == null || string.IsNullOrWhiteSpace(currentSession.AccessToken)) { JwtOption jwtModel = App.GetService <JwtOption>(); TokenProvider tokenProvider = new TokenProvider(jwtModel); TokenResult tokenResult = tokenProvider.LoginToken(user, "wxapplet"); currentSession = new YuebonCurrentUser { UserId = user.Id, Account = user.Account, Name = user.RealName, NickName = user.NickName, AccessToken = tokenResult.AccessToken, AppKey = "wxapplet", CreateTime = DateTime.Now, HeadIcon = user.HeadIcon, Gender = user.Gender, ReferralUserId = user.ReferralUserId, MemberGradeId = user.MemberGradeId, Role = roleService.GetRoleEnCode(user.RoleId), MobilePhone = user.MobilePhone, WxSessionId = sessionBag.Key }; TimeSpan expiresSliding = DateTime.Now.AddMinutes(120) - DateTime.Now; yuebonCacheHelper.Add("login_user_" + user.Id, currentSession, expiresSliding, true); } CurrentUser = currentSession; result.ResData = currentSession; //new AuthorizeApp().GetAccessedControls(user.Account); result.ErrCode = ErrCode.successCode; result.Success = true; } else { result.ErrCode = ErrCode.failCode; result.ErrMsg = jsonResult.errmsg; } } catch (Exception ex) { result.ErrMsg = ex.Message; } return(ToJsonContent(result)); }