获取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