Exemple #1
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);
            }
        }
        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 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 }));
            }
        }
Exemple #4
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);
        }
        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);
            }
        }
        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);
            }
        }
Exemple #8
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));
        }
Exemple #9
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);
            }
        }