NET7下通过code取openid

 

NET7下通过code取openid
其实就是取到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 };
            }
        }
复制代码

 

posted @   牛腩  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-08-25 csc.exe已退出,代码为-532462766
点击右上角即可分享
微信分享提示