![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public const string appId = "";//申请的微信给的appId public const string appSecret = "";//申请的微信给的appsecret public const string redirecturl = "";//申请的微信的回调地址 #region 微信登陆 /// <summary> /// 微信授权页面 /// </summary> /// <returns></returns> public virtual IActionResult WechatAuthorize() { var url = $"https://open.weixin.qq.com/connect/qrconnect?appid={appId}&redirect_uri={redirecturl}&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect"; return new RedirectResult(url); } /// <summary> /// 微信回调方法 /// </summary> /// <returns></returns> public virtual IActionResult WechatLogin() { var code = Request.Query["code"]; var dis = GetAuthorityWechatAccessToken(code); if (!dis.ContainsKey("openid") || !dis.ContainsKey("access_token")) return null; var userinfo = GetWechatUserInfo(dis["access_token"], dis["openid"]); return null; } /// <summary> /// 微信比QQ在获取Token的时候返回了OpenId和UnionId。 /// </summary> /// <param name="code"></param> /// <returns></returns> public virtual Dictionary<string,string> GetAuthorityWechatAccessToken(string code) { if (string.IsNullOrEmpty(code)) return null; var url = string.Format( "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appId, appSecret, code); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; var json = WebRequestHelper.GetResponse(request, "utf-8"); if (string.IsNullOrEmpty(json)) return null; if (!json.Contains("access_token")) { return null; } var dis = json.DeserializeJson<Dictionary<string, string>>(); return dis; } /// <summary> /// 获取微信用户信息 /// </summary> /// <param name="token"></param> /// <param name="openid"></param> /// <returns></returns> public virtual Dictionary<string,object>GetWechatUserInfo(string token,string openid) { var url = $"https://api.weixin.qq.com/sns/userinfo?access_token={token}&openid={openid}"; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; var json = WebRequestHelper.GetResponse(request, "utf-8"); var dis = json.DeserializeJson<Dictionary<string, object>>(); if (dis == null || dis.ContainsKey("errcode")) return null; return dis; } #endregion
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//请求接口方法 public static string GetResponse(WebRequest request, string encoding) { using (WebResponse response = request.GetResponse()) { var stream = response.GetResponseStream(); if (stream == null) return null; using (var reader = new StreamReader(stream, Encoding.GetEncoding(encoding))) { return reader.ReadToEnd(); } } }
这个没有测试登陆,因为看文档和QQ登陆大同小异,连代码都是差不多的。所以就没有测试了。
望参考的游客,还仅供参考。