asp.net core 微信獲取用戶openid

  獲取openid流程爲首先根據微信開發參數構造AuthorizeUrl認證連接,用戶跳轉到該連接進行受權,受權完成將跳轉到回調頁(首次認證須要受權,後面將直接再跳轉至回調頁),此時回調頁中帶上一個GET參數code,使用該code請求微信接口獲得用戶的openid。話很少說,直接上代碼。api

1.編寫認證類OAuth微信

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,注意:訪問該控制器地址確保微信回調時候也能訪問到該地址微信開發

/// <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類輕鬆的就能獲取用戶的Openidapp

附上寫日誌的一個老師傅寫類庫Sky.Logger,在項目中添加引用便可使用日誌:連接: https://pan.baidu.com/s/1eHdNGZN0pmNHsO_yHzgE_g 密碼: ta2xurl

相關文章
相關標籤/搜索