NET7下通过code取openid

发布时间 2023-08-25 12:00:59作者: 牛腩

 

NET7下通过code取openid
微信小程序文档:https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
其实就是取到code后再把code拼接到一个地址里再访问那个地址取到openid,

 

        /// <summary>
        /// 根据CODE取OPENID,再根据OPENID取用户实体
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet("GetByCode")]
        public ApiResult GetByCode(string code)
        {
            try
            {
                if (string.IsNullOrEmpty(code))
                {
                    throw new Exception("传入code为空");
                }
                var appid = "wx3fgdsagsgds";
                var secret = "0015950fdsagdsaghfds";
                var grant_type = "authorization_code";
                var url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&grant_type=" + grant_type + "&js_code=" + code;
                ResponseInfo response = HTTP.Send(url); //nuget: AgileHttp

                RemoteReturn ret = Newtonsoft.Json.JsonConvert.DeserializeObject<RemoteReturn>(response.GetResponseContent());
                if (ret.errcode == 0)
                {
                    #region 自动注册 
                    string openid = ret.openid;
                    Model.User u = _userRepository.FirstOrDefault(a => a.Open_Id == openid);
                    if (u == null)
                    {
                        string name = "微信用户" + openid.Substring(openid.Length - 4);
                        u = new User() { Open_Id = openid, Sex = 1, Belong_job_id = "", HeadImgUrl = "/upload/face.png", Small_headimgurl = "/upload/face.png", Id_Card = "", Integral = 0, Name = name, NickName = name, Phone = "", QrCode = "", Recommend_open_id = "", Role = "普通用户", };
                        _userRepository.Insert(u);
                    }
                    #endregion
                    return new ApiResult() { flag = true, message = "成功取出用户实体", data = u };
                }
                throw new Exception(ret.errmsg);
            }
            catch (Exception ex)
            {
                return new ApiResult() { flag = false, message = ex.Message };
            }
        }