獲取openid流程為首先根據微信開發參數構造AuthorizeUrl認證鏈接,用戶跳轉到該鏈接進行授權,授權完成將跳轉到回調頁(首次認證需要授權,后面將直接再跳轉至回調頁),此時回調頁中帶上一個GET參數code,使用該code請求微信接口得到用戶的openid。話不多說,直接上代碼。
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類輕松的就能獲取用戶的Openid
附上寫日志的一個老師傅寫類庫Sky.Logger,在項目中添加引用即可使用日志:鏈接: https://pan.baidu.com/s/1eHdNGZN0pmNHsO_yHzgE_g 密碼: ta2x