asp.net core 微信获取用户openid

  获取openid流程为首先根据微信开发参数构造AuthorizeUrl认证链接,用户跳转到该链接进行授权,授权完成将跳转到回调页(首次认证需要授权,后面将直接再跳转至回调页),此时回调页中带上一个GET参数code,使用该code请求微信接口得到用户的openid。话不多说,直接上代码。

1.编写认证类OAuth

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class OAuth
    {
        public static HttpClient httpClient = new HttpClient();
        public static string GetAuthorizeUrl(string appId, string redirectUrl, string state= "state", string scope = "snsapi_base", string responseType = "code")
        {
            if (!string.IsNullOrEmpty(redirectUrl))
            {
                redirectUrl = HttpUtility.UrlEncode(redirectUrl, System.Text.Encoding.UTF8);
            }
            else
            {
                redirectUrl = null;
            }
            object[] args = new object[] { appId, redirectUrl, responseType, scope, state };
            return string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}#wechat_redirect", args);
        }
 
        public static string GetOpenIdUrl(string appId, string secret, string code, string grantType = "authorization_code")
        {
            object[] args = new object[] { appId, secret, code, grantType };
            string requestUri = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type={3}", args);
            return requestUri;
        }
 
        /// <summary>
        /// 获取openid
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="secret"></param>
        /// <param name="code"></param>
        /// <param name="grantType"></param>
        /// <returns></returns>
        public static string GetOpenid(string appId, string secret, string code, string grantType = "authorization_code")
        {
            string requestUri = GetOpenIdUrl(appId, secret, code, grantType);
            var responseStr = httpClient.GetAsync(requestUri).Result.Content.ReadAsStringAsync().Result;
            var obj = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseStr);
            string openid = string.Empty;
            if (!obj.TryGetValue("openid", out openid))
            {
                Log.Info($"获取openid失败appId={appId},secret={secret},code={code}");
            }
            return openid;
        }
    }

  2.在控制器中使用认证类获取用户openid,注意:访问该控制器地址确保微信回调时候也能访问到该地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/// <summary>
       /// 获取微信openid
       /// </summary>
       /// <param name="code"></param>
       /// <returns></returns>
       [HttpGet]
        public IActionResult GetWxOpenid(string code)
        {
            WxPayConfig wxPayConfig = new WxPayConfig();
            //首先构造微信请求授权url,重定向到该url中,其中redirectUrl是回调地址,必须保证该地址在公网上能访问,本例子构造的是返回到本控制器的方法。
            //若是从微信授权返回进入该方法,则会带上一个参数,code就不为空,若code为空则跳转微信授权
            if (string.IsNullOrEmpty(code))
            {
                var redirectUrl = OAuth.GetAuthorizeUrl(wxPayConfig.appid, "回调地址到公网本Action");
                return Redirect(redirectUrl);
            }
            else
            {
                //根据code和微信参数得到openid
                var openId = OAuth.GetOpenid(wxPayConfig.appid, wxPayConfig.appSecret, code);
                //业务处理
                 
            }
            return View();
        }

  通过使用OAuth类轻松的就能获取用户的Openid

附上写日志的一个老师傅写类库Sky.Logger,在项目中添加引用即可使用日志:链接: https://pan.baidu.com/s/1eHdNGZN0pmNHsO_yHzgE_g 密码: ta2x

posted @   jomz  阅读(6318)  评论(3编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示