热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

.netcore实现微信登陆

publicconststringappId;申请的微信给的appIdpublicconststringappSecret;申请的微信给的appsecretpublicco

public const string appId = "";//申请的微信给的appIdpublic const string appSecret = "";//申请的微信给的appsecretpublic const string redirecturl = "";//申请的微信的回调地址#region 微信登陆///

/// 微信授权页面/// /// public virtual IActionResult WechatAuthorize(){var url &#61; $"https://open.weixin.qq.com/connect/qrconnect?appid&#61;{appId}&redirect_uri&#61;{redirecturl}&response_type&#61;code&scope&#61;snsapi_login&state&#61;STATE#wechat_redirect";return new RedirectResult(url);}/// /// 微信回调方法/// /// public virtual IActionResult WechatLogin(){var code &#61; Request.Query["code"];var dis &#61; GetAuthorityWechatAccessToken(code);if (!dis.ContainsKey("openid") || !dis.ContainsKey("access_token"))return null;var userinfo &#61; GetWechatUserInfo(dis["access_token"], dis["openid"]);return null;}/// /// 微信比QQ在获取Token的时候返回了OpenId和UnionId。/// /// /// public virtual Dictionary<string,string> GetAuthorityWechatAccessToken(string code){if (string.IsNullOrEmpty(code))return null;var url &#61;string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid&#61;{0}&secret&#61;{1}&code&#61;{2}&grant_type&#61;authorization_code",appId, appSecret, code);HttpWebRequest request &#61; WebRequest.Create(url) as HttpWebRequest;var json &#61; WebRequestHelper.GetResponse(request, "utf-8");if (string.IsNullOrEmpty(json))return null;if (!json.Contains("access_token")){return null;}var dis &#61; json.DeserializeJsonstring, string>>();return dis;}/// /// 获取微信用户信息/// /// /// /// public virtual Dictionary<string,object>GetWechatUserInfo(string token,string openid){var url &#61; $"https://api.weixin.qq.com/sns/userinfo?access_token&#61;{token}&openid&#61;{openid}";HttpWebRequest request &#61; WebRequest.Create(url) as HttpWebRequest;var json &#61; WebRequestHelper.GetResponse(request, "utf-8");var dis &#61; json.DeserializeJsonstring, object>>();if (dis &#61;&#61; null || dis.ContainsKey("errcode"))return null;return dis;}#endregion
View Code

//请求接口方法
public static string GetResponse(WebRequest request, string encoding){using (WebResponse response &#61; request.GetResponse()){var stream &#61; response.GetResponseStream();if (stream &#61;&#61; null) return null;using (var reader &#61; new StreamReader(stream, Encoding.GetEncoding(encoding))){return reader.ReadToEnd();}}}

View Code

这个没有测试登陆&#xff0c;因为看文档和QQ登陆大同小异&#xff0c;连代码都是差不多的。所以就没有测试了。

望参考的游客&#xff0c;还仅供参考。

转:https://www.cnblogs.com/CnnBlog/p/11451374.html



推荐阅读
author-avatar
mobiledu2502898533
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有