1 string returnUrl = string.Empty; 2 string appId = ConfigurationManager.AppSettings["wx_AppKey"]; 3 string appSecret = ConfigurationManager.AppSettings["wx_AppSecret"]; 4 5 var weixinOAuth = new WeiXinOAuth(); 6 string code = Request.QueryString["code"]; 7 string state = Request.QueryString["state"]; 8 9 if (string.IsNullOrEmpty(code) || code == "authdeny")10 {11 if (string.IsNullOrEmpty(code))12 {13 //发起授权(第一次微信握手)14 string authUrl = weixinOAuth.GetWeiXinCode(appId, appSecret, Server.UrlEncode(Request.Url.ToString()), true);15 Response.Redirect(authUrl, true);16 }17 else18 {19 // 用户取消授权20 ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Error, "授权失败!");21 }22 }23 else24 {25 //获取微信的Access_Token(第二次微信握手)26 var modelResult = weixinOAuth.GetWeiXinAccessToken(appId, appSecret, code);27 //获取微信的用户信息(第三次微信握手)28 var userInfo = weixinOAuth.GetWeiXinUserInfo(modelResult.SuccessResult.access_token, modelResult.SuccessResult.openid);29 //用户信息(判断是否已经获取到用户的微信用户信息)30 if (userInfo.Result && userInfo.UserInfo.openid != "")31 {32 //根据OpenId判断数据库是否存在,如果存在,直接登录即可33 if (CurrentUser != null)34 {35 if (AccountBindings.GetUser(2, userInfo.UserInfo.openid) == null)36 {37 AccountBinding account = new AccountBinding();38 account.AccountType = 2;39 account.Identification = userInfo.UserInfo.openid;40 account.UserID = CurrentUser.UserID;41 account.OauthToken = modelResult.SuccessResult.access_token;42 account.OauthTokenSecret = appSecret;43 AccountBindings.CreateAccountBinding(account);44 45 ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Success, "绑定成功");46 }47 else48 {49 ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Hint, "此账号已在网站中绑定过,不可再绑定其他网站账号");50 }51 }52 else53 {54 User systemUser = AccountBindings.GetUser(2, userInfo.UserInfo.openid);55 if (systemUser != null)56 {57 FormsAuthentication.SetAuthCookie(systemUser.UserName, true);58 returnUrl = SiteUrls.Instance().UserDomainHome(systemUser);59 ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Success, "登录成功");60 }61 else62 {63 ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Success, string.Empty);64 ViewData["UserName"] = WebUtils.UrlEncode(userInfo.UserInfo.nickname);65 string nickName = WebUtils.UrlEncode(userInfo.UserInfo.nickname);66 string figureurl = userInfo.UserInfo.headimgurl;67 ViewData["FirstLogin"] = true;68 returnUrl = SPBUrlHelper.Action("ThirdRegister", "ChannelUser", new RouteValueDictionary { { "accountType", 2 }, { "openID", userInfo.UserInfo.openid }, { "OauthToken", modelResult.SuccessResult.access_token }, { "OauthTokenSecret", appSecret }, { "nickName", nickName }, { "figureurl", figureurl } });69 }70 }71 }72 else73 {74 ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Error, "参数错误,授权失败!");75 }76 }77 78 ViewData["returnUrl"] = returnUrl;79 return View("Pages/User/LoginCallback.aspx");
1 public enum Method { GET, POST, PUT, DELETE }; 2 /// <summary> 3 /// 获取微信Code 4 /// </summary> 5 /// <param name="appId">微信AppId</param> 6 /// <param name="appSecret">微信AppSecret</param> 7 /// <param name="redirectUrl">返回的登录地址,要进行Server.Un编码</param> 8 /// <param name="isWap">true=微信内部登录 false=pc网页登录</param> 9 public string GetWeiXinCode(string appId, string appSecret, string redirectUrl, bool isWap) 10 { 11 var r = new Random(); 12 //微信登录授权 13 //string url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appId + "&redirect_uri=" + redirectUrl +"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect"; 14 //微信OpenId授权 15 //string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + redirectUrl +"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect"; 16 //微信用户信息授权 17 var url = ""; 18 if (isWap) 19 { 20 url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + 21 redirectUrl + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; 22 } 23 else 24 { 25 url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appId + "&redirect_uri=" + redirectUrl + 26 "&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect"; 27 } 28 return url; 29 } 30 /// <summary> 31 /// 通过code获取access_token 32 /// </summary> 33 /// <param name="appId"></param> 34 /// <param name="appSecret"></param> 35 /// <param name="code"></param> 36 /// <returns></returns> 37 public WeiXinAccessTokenResult GetWeiXinAccessToken(string appId, string appSecret, string code) 38 { 39 string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + 40 "&code=" + code + "&grant_type=authorization_code"; 41 string jsonStr = _WebRequest(Method.GET, url, ""); 42 var result = new WeiXinAccessTokenResult(); 43 if (jsonStr.Contains("errcode")) 44 { 45 var errorResult = (WeiXinHelper.WeiXinErrorMsg)JsonConvert.Import(typeof(WeiXinHelper.WeiXinErrorMsg), jsonStr); 46 result.ErrorResult = errorResult; 47 result.Result = false; 48 } 49 else 50 { 51 var model = (WeiXinAccessTokenModel)JsonConvert.Import(typeof(WeiXinAccessTokenModel), jsonStr); 52 result.SuccessResult = model; 53 result.Result = true; 54 } 55 return result; 56 } 57 /// <summary> 58 /// 拉取用户信息 59 /// </summary> 60 /// <param name="accessToken"></param> 61 /// <param name="openId"></param> 62 /// <returns></returns> 63 public WeiXinHelper.WeiXinUserInfoResult GetWeiXinUserInfo(string accessToken, string openId) 64 { 65 string url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "?=zh_CN"; 66 string jsonStr = _WebRequest(Method.GET ,url,""); 67 var result = new WeiXinHelper.WeiXinUserInfoResult(); 68 if (jsonStr.Contains("errcode")) 69 { 70 var errorResult = (WeiXinHelper.WeiXinErrorMsg)JsonConvert.Import(typeof(WeiXinHelper.WeiXinErrorMsg), jsonStr); 71 result.ErrorMsg = errorResult; 72 result.Result = false; 73 } 74 else 75 { 76 var userInfo = (WeiXinHelper.WeiXinUserInfo)JsonConvert.Import(typeof(WeiXinHelper.WeiXinUserInfo), jsonStr); 77 result.UserInfo = userInfo; 78 result.Result = true; 79 } 80 return result; 81 } 82 83 84 private string _WebRequest(Method method, string url, string postData) 85 { 86 HttpWebRequest webRequest = null; 87 StreamWriter requestWriter = null; 88 string responseData = ""; 89 90 webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; 91 webRequest.Method = method.ToString(); 92 webRequest.ServicePoint.Expect100Continue = false; 93 94 if (method == Method.POST) 95 { 96 webRequest.ContentType = "application/x-www-form-urlencoded"; 97 requestWriter = new StreamWriter(webRequest.GetRequestStream()); 98 try 99 {100 requestWriter.Write(postData);101 }102 catch103 {104 throw;105 }106 finally107 {108 requestWriter.Close();109 requestWriter = null;110 }111 }112 113 responseData = _WebResponseGet(webRequest);114 115 webRequest = null;116 117 return responseData;118 119 }120 121 private string _WebResponseGet(HttpWebRequest webRequest)122 {123 StreamReader responseReader = null;124 string responseData = "";125 try126 {127 responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());128 responseData = responseReader.ReadToEnd();129 }130 catch131 {132 throw;133 }134 finally135 {136 webRequest.GetResponse().GetResponseStream().Close();137 responseReader.Close();138 responseReader = null;139 }140 141 return responseData;142 }143 }144 145 /// <summary>146 /// 通过code获取access_token 请求成功的实体147 /// </summary>148 public class WeiXinAccessTokenModel149 {150 /// <summary>151 /// 接口调用凭证152 /// </summary>153 public string access_token { get; set; }154 /// <summary>155 /// access_token接口调用凭证超时时间,单位(秒)156 /// </summary>157 public int expires_in { get; set; }158 /// <summary>159 /// 用户刷新access_token160 /// </summary>161 public string refresh_token { get; set; }162 /// <summary>163 /// 授权用户唯一标识164 /// </summary>165 public string openid { get; set; }166 /// <summary>167 /// 用户授权的作用域,使用逗号(,)分隔168 /// </summary>169 public string scope { get; set; }170 }171 172 public class WeiXinAccessTokenResult173 {174 public WeiXinAccessTokenModel SuccessResult { get; set; }175 public bool Result { get; set; }176 177 public WeiXinHelper.WeiXinErrorMsg ErrorResult { get; set; }178 }179 180 /// <summary>181 /// 微信帮助类182 /// </summary>183 public class WeiXinHelper184 {185 /// <summary>186 /// 微信错误访问的情况187 /// </summary>188 public class WeiXinErrorMsg189 {190 /// <summary>191 /// 错误编号192 /// </summary>193 public int errcode { get; set; }194 /// <summary>195 /// 错误提示消息196 /// </summary>197 public string errmsg { get; set; }198 }199 200 /// <summary>201 /// 获取微信用户信息202 /// </summary>203 public class WeiXinUserInfoResult204 {205 /// <summary>206 /// 微信用户信息207 /// </summary>208 public WeiXinUserInfo UserInfo { get; set; }209 /// <summary>210 /// 结果211 /// </summary>212 public bool Result { get; set; }213 /// <summary>214 /// 错误信息215 /// </summary>216 public WeiXinErrorMsg ErrorMsg { get; set; }217 }218 219 /// <summary>220 /// 微信授权成功后,返回的用户信息221 /// </summary>222 public class WeiXinUserInfo223 {224 /// <summary>225 /// 用户的唯一标识226 /// </summary>227 public string openid { get; set; }228 /// <summary>229 /// 用户昵称230 /// </summary>231 public string nickname { get; set; }232 /// <summary>233 /// 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知234 /// </summary>235 public string sex { get; set; }236 /// <summary>237 /// 用户个人资料填写的省份238 /// </summary>239 public string province { get; set; }240 /// <summary>241 /// 普通用户个人资料填写的城市242 /// </summary>243 public string city { get; set; }244 /// <summary>245 /// 国家,如中国为CN246 /// </summary>247 public string country { get; set; }248 /// <summary>249 /// 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空250 /// </summary>251 public string headimgurl { get; set; }252 /// <summary>253 /// 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)254 /// </summary>255 public string[] privilege { get; set; }256 }257 }