示例#1
0
        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);
            }
        }
示例#2
0
        /// <summary>
        /// GetOrGenerateItemByWeixinAppOpenIdAsync
        /// </summary>
        /// <param name="generateGroupId"></param>
        /// <param name="generateStatus"></param>
        /// <param name="code"></param>
        /// <param name="encryptedData"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public async Task <UserInfo> GetOrGenerateItemByWeixinAppCodeAsync(Guid generateGroupId, UserStatus generateStatus, string code, string encryptedData, string iv)
        {
            try
            {
                var jsCode2JsonResult = await SnsApi.JsCode2JsonAsync(_weixinAppSettings.AppId, _weixinAppSettings.Secret, code);

                var decodedJsonString  = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeEncryptedData(jsCode2JsonResult.session_key, encryptedData, iv);
                var decodedPhoneNumber = Newtonsoft.Json.JsonConvert.DeserializeObject <DecodedPhoneNumber>(decodedJsonString);
                var userInfo           = await _manager.GetOrGenerateItemByWeixinAppOpenIdAsync(generateGroupId, generateStatus, jsCode2JsonResult.openid, decodedPhoneNumber.purePhoneNumber);

                if (userInfo != null && userInfo.Status == UserStatus.Normal)
                {
                    Cache(userInfo);
                }
                return(userInfo);
            }
            catch (Newtonsoft.Json.JsonReaderException ex)
            {
                _logger.LogError(ex, "微信小程序登录失败");
                return(null);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "微信小程序登录失败");
                return(null);
            }
        }
示例#3
0
        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> OnLogin([FromBody] JObject values)
        {
            var code = values["code"].ToString();

            // var encryptedData = values["encryptedData"].ToString();
            // var iv = values["iv"].ToString();

            try
            {
                // 登录
                var jsonResult = SnsApi.JsCode2Json(_wxOpenAppId, _wxOpenAppSecret, code);
                if (jsonResult.errcode == ReturnCode.请求成功)
                {
                    // 开放平台下存在同一主体小程序+公众号且用户已关注返回unionId,否则不返回
                    var unionid = jsonResult.unionid;
                    var issub   = string.IsNullOrEmpty(unionid) ? false : true;
                    if (!issub)
                    {
                        Console.WriteLine("未关注公众号");
                    }


                    // // 解密获取unionId
                    // var str = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeEncryptedData(jsonResult.session_key, encryptedData, iv);
                    // var advancedUserInfo = JsonConvert.DeserializeObject<dynamic>(str);
                    // string unionId = advancedUserInfo.unionId;

                    // //通过unionId 获取 公众号 openid

                    // // 获取公众号access_token
                    // var accessToken = await CommonApi.GetTokenAsync(_appId, _appSecret);
                    // var userInfo = await CommonApi.GetUserInfoAsync(accessToken.access_token, "oHxnJwvaKv04Fhm-5k9Cyu4D6ZCw");

                    // if (userInfo.subscribe == 1 && unionId == userInfo.unionid)
                    // {
                    //     Console.WriteLine("已关注");
                    // }
                    // else
                    // {
                    //     Console.WriteLine("未关注");
                    // }


                    // // Session["WxOpenUser"] = jsonResult;//使用Session保存登陆信息(不推荐)
                    // // 使用SessionContainer管理登录信息(推荐)
                    // var sessionBag = await SessionContainer.UpdateSessionAsync(null, jsonResult.openid, jsonResult.session_key, unionId);

                    // 注意:生产环境下SessionKey属于敏感信息,不能进行传输!
                    return(Ok(new { data = issub ? "已关注" : "未关注" }));
                }
                else
                {
                    return(Ok(new { success = false, msg = jsonResult.errmsg }));
                }
            }
            catch (Exception ex)
            {
                return(Ok(new { success = false, msg = ex.Message }));
            }
        }
示例#5
0
        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 async Task <IActionResult> OnLogin([FromBody] JObject param)
        {
            // 不设置权限访问可以不做以下验证
            if (!await _authorizationService.AuthorizeAsync(User, MiniProgramPermission.WeCharMiniProgramAccess))
            {
                return(Unauthorized(new { success = false, msg = "未授权访问" }));
            }
            try
            {
                var jsonResult = await SnsApi.JsCode2JsonAsync(_miniProgramSetting.WxOpenAppId, _miniProgramSetting.WxOpenAppSecret, param["code"].Value <string>());

                if (jsonResult.errcode == ReturnCode.请求成功)
                {
                    var unionId = "";
                    // 定义sessionId为openid
                    var sessionBag = await SessionContainer.UpdateSessionAsync(jsonResult.openid, jsonResult.openid, jsonResult.session_key, unionId);

                    // 返回 sessionId
                    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 }));
            }
        }
示例#7
0
        public async Task <AuthenticateResultModel> AuthenticateLogin([FromBody] AuthenticateInput input)
        {
            var openId = string.Empty;

#if DEBUG
            openId = "testopenid";
#else
            Console.WriteLine(WxOpenAppId);
            var jsonResult = await SnsApi.JsCode2JsonAsync(WxOpenAppId, WxOpenAppSecret, input.Code);

            if (jsonResult.errcode == ReturnCode.请求成功)
            {
                openId = jsonResult.openid;
            }
#endif
            Console.WriteLine(openId);
            var dto = await _userAppService.Authorize(openId, input.HeadId);

            IdentityUser login = new IdentityUser
            {
                RememberMe = true,
                UserId     = dto.Id.ToString(),
                Name       = dto.NickName,
            };

            var accessToken =
                CreateAccessToken(CreateJwtClaims(login.CreateIdentity(JwtBearerDefaults.AuthenticationScheme)));

            return(new AuthenticateResultModel
            {
                AccessToken = accessToken,
                ExpireInSeconds = (int)TimeSpan.FromDays(30).TotalSeconds,
                UserId = dto.Id.ToString()
            });
        }
        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 }));
            }
        }
示例#9
0
        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 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)));
            }
        }
示例#11
0
        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 }));
            }
        }
示例#12
0
        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 }));
            }
        }
示例#13
0
        public async Task <TData <WeiXinInfo> > GetWxOpenId([FromQuery] string code)
        {
            TData <WeiXinInfo> obj = new TData <WeiXinInfo>();
            var result             = await SnsApi.JsCode2JsonAsync(GlobalContext.SystemConfig.AppId, GlobalContext.SystemConfig.AppSecret, code);

            obj.Result = new WeiXinInfo {
                OpenId = result.openid, UnionId = result.unionid
            };
            obj.Tag = 1;
            return(obj);
        }
        public async Task <JsCode2JsonResult> Mini_Code2Session(string code, string appid, string appsecret)
        {
            var session = await SnsApi.JsCode2JsonAsync(appid, appsecret, code);

            if (session == null)
            {
                throw new UserFriendlyException("解密失败");
            }

            return(session);
        }
示例#15
0
        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);
            }
        }
示例#16
0
        /// <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);
            }
        }
示例#17
0
 public ActionResult CheckWxOpenSignature(string code, string rawData, string signature)
 {
     try
     {
         var jsonResult   = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code);
         var checkSuccess = EncryptHelper.CheckSignature(code, rawData, signature);
         return(Json(new { success = checkSuccess, msg = checkSuccess ? "签名校验成功" : "签名校验失败" }));
     }
     catch (Exception ex)
     {
         return(Json(new { success = false, msg = ex.Message }));
     }
 }
示例#18
0
        public async Task <string> GetWeixinAppOpenIdAsync(string code)
        {
            // https://developers.weixin.qq.com/miniprogram/dev/api/code2Session.html
            // GET https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
            try
            {
                var jsCode2JsonResult = await SnsApi.JsCode2JsonAsync(_weixinAppSettings.AppId, _weixinAppSettings.Secret, code);

                return(jsCode2JsonResult.openid);
            }
            catch (Exception)
            {
                return(null);
            }
        }
示例#19
0
        public async Task <string> GetWeixinWebOpenIdAsync(string code)
        {
            // https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN
            // GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
            try
            {
                var jsCode2JsonResult = await SnsApi.JsCode2JsonAsync(_weixinAppSettings.AppId, _weixinAppSettings.Secret, code);

                return(jsCode2JsonResult.openid);
            }
            catch (Exception)
            {
                return(null);
            }
        }
示例#20
0
        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 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 }));
            }
        }
示例#22
0
        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 }));
            }
        }
示例#23
0
        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 }));
            }
        }
示例#24
0
        public async Task <ApiResult <UserOutput> > MpLogin([FromQuery] MpLoginInput input)
        {
            var config = Resolve <IAutoConfigService>().GetValue <MiniProgramConfig>();
            var openId = SnsApi.JsCode2Json(config.AppID, config.AppSecret, input.Code)
                         .openid;

            if (openId.IsNullOrEmpty())
            {
                return(ApiResult.Failure <UserOutput>("获取openId失败"));
            }

            return(null);

            //try {
            //    var result = await _userManager.LoginByOpenIdAsync(openId);
            //    if (result.Succeeded) {
            //        var _user = Resolve<IUserService>().GetUserDetail(AutoModel.BasicUser.Id);
            //        var userOutput = Resolve<IUserDetailService>().GetUserOutput(_user.Id);
            //        return ApiResult.Success(userOutput); //登录成功,返回用户的详细信息
            //    } else {
            //        var user = new Domain.Entities.User {
            //            UserName = "******" + new Random(DateTime.Now.Millisecond).Next(int.MaxValue).ToString()
            //                           .PadLeft(10, '0') + Resolve<IUserService>().MaxUserId(),
            //            Name = input.nickname,
            //            //ParentId = usercode,
            //            Detail = new UserDetail {
            //                Password = "******".ToMd5HashString(),
            //                PayPassword = "******".ToMd5HashString(),
            //                Avator = input.avatarUrl,
            //                OpenId = openId,
            //                Sex = input.gender == 1 ? Sex.Man : (input.gender == 2 ? Sex.WoMan : Sex.UnKnown)
            //            }
            //        };
            //        user.Email = user.UserName + "@qnn.com";
            //        user.Mobile = user.UserName;
            //      //  _userManager.RegisterAsync(user, true).GetAwaiter().GetResult();

            //        var userOutput = Resolve<IUserDetailService>().GetUserOutput(user.Id);
            //        return ApiResult.Success(userOutput); //登录成功,返回用户的详细信息
            //    }
            //} catch (Exception e) {
            //    return ApiResult.Failure<UserOutput>(e.Message);
            //}
        }
示例#25
0
        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 });
            }
        }
示例#26
0
        //public async Task<IActionResult> Login(string code,string headurl = "",string nickname = "",string sex = "",string province = "",string city = "")
        public async Task <IActionResult> Post([FromBody] LoginModel loginModel)
        {
            //Todo 这里要去通过code 调取微信接口获取openId
            //https://blog.csdn.net/qq_39851704/article/details/79025557
            //code: res.code,//获取openid的话 需要向后台传递code,利用code请求api获取openid

            _logger.LogDebug($"获取到的Code = {loginModel.code};WxOpenAppId = {WxOpenAppId};WxOpenAppSecret = {WxOpenAppSecret} ");

#if DEBUG
            var openId      = loginModel.code;
            var session_key = loginModel.code;
            loginModel.nickname = "Software";
            loginModel.headurl  = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1079592840,2327344920&fm=27&gp=0.jpg";
            loginModel.sex      = "男";
            loginModel.province = "河南";
            loginModel.city     = "郑州";
#else
            var openId      = string.Empty;
            var session_key = string.Empty;
            var jsonResult  = await SnsApi.JsCode2JsonAsync(WxOpenAppId, WxOpenAppSecret, loginModel.code);

            if (jsonResult.errcode == ReturnCode.请求成功)
            {
                openId      = jsonResult.openid;
                session_key = jsonResult.session_key;
            }
#endif

            var member = await _membersServices.Login(openId, session_key, loginModel.headurl, loginModel.nickname, loginModel.sex, loginModel.province, loginModel.city);

            //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色
            var claims = new List <Claim> {
                new Claim(ClaimTypes.Name, loginModel.code),
                new Claim(ClaimTypes.NameIdentifier, member.Id.ToString()),
                new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString())
            };

            var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            identity.AddClaims(claims);
            var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
            return(new JsonResult(token));
        }
示例#27
0
        /// <summary>
        /// GetOrGenerateItemByWeixinAppOpenIdAsync
        /// </summary>
        /// <param name="generateGroupId"></param>
        /// <param name="generateStatus"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task <UserInfo> GetOrGenerateItemByWeixinAppCodeAsync(Guid generateGroupId, UserStatus generateStatus, string code)
        {
            try
            {
                var jsCode2JsonResult = await SnsApi.JsCode2JsonAsync(_weixinAppSettings.AppId, _weixinAppSettings.Secret, code);

                var userInfo = await _manager.GetOrGenerateItemByWeixinAppOpenIdAsync(generateGroupId, generateStatus, jsCode2JsonResult.openid);

                if (userInfo != null && userInfo.Status == UserStatus.Normal)
                {
                    Cache(userInfo);
                }
                return(userInfo);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "微信小程序登录失败");
                return(null);
            }
        }
        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);
        }
示例#29
0
        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 });
            }
        }
示例#30
0
        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);
            }
        }