public const string appId = "";//申请的微信给的appIdpublic const string appSecret = "";//申请的微信给的appsecretpublic const string redirecturl = "";//申请的微信的回调地址#region 微信登陆///
/// 微信授权页面/// /// 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);}/// /// 微信回调方法/// /// 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;}/// /// 微信比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.DeserializeJson
string, 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