Beispiel #1
0
        /// <summary>
        /// 微信加密数据解密
        /// </summary>
        /// <param name="encryptedData"></param>
        /// <param name="sessionId"></param>
        /// <param name="vi"></param>
        /// <returns></returns>
        public string WxDecrypt(string encryptedData, string sessionId, string vi)
        {
            var cacheKey   = string.Format(CacheKey.WX_SESSIONID_KEY, sessionId);
            var dict       = (Dictionary <string, object>)_cacheService.GetValue(cacheKey);
            var sessionKey = dict["session_key"].ToString();

            return(WXBizDataCrypt.AESDecrypt(encryptedData, sessionKey, vi));
        }
Beispiel #2
0
        public string GetUserInfo(string session_key, string iv, string encryptedData)
        {
            //获取用户数据
            string jo = WXBizDataCrypt.AESDecrypt(encryptedData, session_key, iv);
            //转成json格式
            JObject job = (JObject)JsonConvert.DeserializeObject(jo);

            //用户类 赋值
            tb_User userinfo = new tb_User();

            userinfo.OpenId    = job["openId"].ToString();
            userinfo.NickName  = job["nickName"].ToString();
            userinfo.AvatarUrl = job["avatarUrl"].ToString();
            object watermark = job["watermark"].ToString();
            object timestamp = job["watermark"]["timestamp"].ToString();
            int    count     = 1;

            //创建连接对象
            MySqlConnection conn = new MySqlConnection("server=192.168.43.80;User Id=root;password=1234;Database=restaurant");

            //打开连接池
            conn.Open();
            //查询是否有当前用户
            string       sql  = "SELECT * FROM `tb_user` where OpenId='" + userinfo.OpenId + "'";
            MySqlCommand cmd1 = new MySqlCommand(sql, conn);
            object       obj  = cmd1.ExecuteScalar();

            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                //添加当前用户的信息
                string       str1 = $"insert into tb_user(OpenId,NickName,AvatarUrl,Count,TimeStamp) VALUES('{userinfo.OpenId}', '{userinfo.NickName}', '{userinfo.AvatarUrl}', {count}, '{timestamp.ToString()}')";
                MySqlCommand cmd2 = new MySqlCommand(str1, conn);
                try
                {
                    int row = cmd2.ExecuteNonQuery();
                }
                catch (Exception)
                {
                    throw;
                }
            }
            else
            {
                //修改用户登录的次数
                string       str2 = $"update tb_user set Count=Count+1 where OpenId='{userinfo.OpenId}'";
                MySqlCommand cmd3 = new MySqlCommand(str2, conn);
                int          row  = cmd3.ExecuteNonQuery();
            }
            //关闭连接池
            conn.Close();
            return(jo);
        }
        public async Task <bool> ExcuteAsync(MiniProgramLoginContext context)
        {
            try
            {
                var session_key   = context.MiniProgramUser?.session_key;
                var encryptedData = context.MiniProgramUser.Input.GetProperty("encryptedData").GetString();
                var iv            = context.MiniProgramUser.Input.GetProperty("iv").GetString();
                this.httpContext  = context.HttpContext;
                this.httpResponse = httpContext.Response;
                var deMPUserInfo = WXBizDataCrypt.AESDecrypt(encryptedData, session_key, iv);
                var mpUser       = JsonSerializer.Deserialize <mp_user>(deMPUserInfo);
                var openId       = mpUser?.openId;
                var mpUserModel  = _baseService.GetModels(a => a.openId == openId).SingleOrDefault();
                if (mpUserModel != default) // 如果登录用户存在
                {
                    mpUserModel.updatedAt = DateTime.Now;
                    await _baseService.UpdateAsync(mpUserModel);

                    var sessionKeyModel = await _sessionKeyService.GetEntityAsync(a => a.uid == mpUserModel.id);

                    sessionKeyModel.sessionKey = session_key;
                    sessionKeyModel.updatedAt  = DateTime.Now;
                    await _sessionKeyService.UpdateAsync(sessionKeyModel);

                    // 生成jwt,返回给小程序端
                    var claims = new List <Claim>
                    {
                        new Claim("uid", mpUser.id.ToString()),
                        new Claim("nickName", mpUser.nickName),
                        new Claim("avatarUrl", mpUser.avatarUrl),
                        new Claim("openId", mpUser.openId),
                        new Claim("sessionKey", session_key)
                    };

                    var accessToken = IssueJwt(claims);
                    var userInfo    = MapUtils.ObjectToMap(mpUserModel);
                    userInfo.Add("authorizationToken", accessToken);
                    this.httpResponse.ContentType = "application/json";
                    this.httpResponse.StatusCode  = 200;
                    await WriteJsonAsync(new
                    {
                        code = 200,
                        msg  = "ok",
                        data = userInfo
                    });
                }
                else // 未找到关联本地账号
                {
                    // 将小程序登录用户信息保存到本地数据库,同时生成jwt返回给小程序端
                    // 将session_key保存到缓存中或token中或数据库中
                    mpUser.createdAt = DateTime.Now;
                    var insertResult = await _baseService.AddAsync(mpUser);

                    var sessionKeyModel = new session_key
                    {
                        uid        = insertResult.id,
                        createdAt  = DateTime.Now,
                        sessionKey = session_key
                    };
                    await _sessionKeyService.InsertAsync(sessionKeyModel);

                    var sessionKey = new session_key
                    {
                        uid        = mpUser.id,
                        sessionKey = session_key,
                        createdAt  = DateTime.Now
                    };
                    var claims = new List <Claim>
                    {
                        new Claim("uid", mpUser.id.ToString()),
                        new Claim("nickName", mpUser.nickName),
                        new Claim("avatarUrl", mpUser.avatarUrl),
                        new Claim("openId", mpUser.openId),
                        new Claim("sessionKey", session_key)
                    };
                    var accessToken = IssueJwt(claims);
                    var userInfo    = MapUtils.ObjectToMap(insertResult);
                    userInfo.Add("authorizationToken", accessToken);
                    this.httpResponse.ContentType = "application/json";
                    this.httpResponse.StatusCode  = 200;
                    await WriteJsonAsync(new
                    {
                        code = 200,
                        msg  = "ok",
                        data = userInfo
                    });
                }

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }