【第二十一篇】C# MVC 微信授权登录 OAuth2.0授权登录

首先一定要熟读,最起码过一遍微信开发者文档

微信开发者文档

 

文档写的很清楚 

授权登录四步走

 

在正文开始前,我得讲清楚一个事情

敲黑板,划重点:微信一共有两个 access_token

一个是7200就过期的,一个是登录用的。这两个有本质区别,授权登录只会用到后者

======================正文开始======================

/// <summary>  
/// 微信登录  
/// </summary>  
/// <returns></returns>  
public ActionResult WechatLogin()  
{  
    if (!string.IsNullOrEmpty(Request["code"]))  
    {  
        //根据appid,secret,code取到用户的全部信息  
        Dictionary<string, object> dic = GetUserInfoByCode(AppId, AppSecret, Request["code"].ToString());  
        if (dic.ContainsKey("errcode"))  
        {  
            return Redirect("/WError/Index?Msg=" + dic["errmsg"].ToString());  
        }  
        string openid = dic["openid"].ToString();  
        //根据微信唯一标识openid  去数据库判断是否存在  
        //1.不存在就新增  
        Model.TBase_UserInfo u = BLL.TBase_UserInfo.Instence.GetUserByOpenId(openid);  
        if (u == null)  
        {  
            u = new Model.TBase_UserInfo();  
            u.Code = GetCode<Model.TBase_UserInfo>();  
            u.NickName = dic["nickname"].ToString();  
            u.HeadImage = dic["headimgurl"].ToString();  
            u.OpenId = openid;  
            u.IsOrder = 0;  
            u.Status = 1;  
            u.State = 1;  
            u.AddDate = DateTime.Now;  
  
            int id = BLL.TBase_UserInfo.Instence.Add(u);  
            u.ID = id;  
        }  
        Session[Esluo.Basic.Config.SESSION_KEY_FOR_USER] = u;  
        return Redirect("/WHome/Index");  
    }  
    else  
    {  
        string redirect_uri = HttpUtility.UrlEncode("http://" + Request.Url.Authority + Request.Url.PathAndQuery);  
        return Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state=STATE#wechat_redirect", AppId, redirect_uri, "snsapi_userinfo"));  
    }  
}  
/// <summary>  
/// 获得Code  
/// </summary>  
/// <typeparam name="T"></typeparam>  
/// <returns></returns>  
protected long GetCode<T>()  
{  
    Type type = typeof(T);  
    return BLL.TSYS_Code.Instence.GetCode(type.Name);  
}  
  
/// <summary>  
///用code换取获取用户信息(包括非关注用户的)(此access_token是网页授权的和普通无关)  
/// </summary>  
/// <param name="Appid"></param>  
/// <param name="Appsecret"></param>  
/// <param name="Code">回调页面带的code参数</param>  
/// <returns>获取用户信息(json格式)</returns>  
public Dictionary<string, object> GetUserInfoByCode(string Appid, string Appsecret, string Code)  
{  
    JavaScriptSerializer Jss = new JavaScriptSerializer();  
    string 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);  
    string ReText = WebRequestPostOrGet(url, "");//post/get方法获取信息  
    Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(ReText);  
    if (!DicText.ContainsKey("openid"))  
    {  
        return DicText;  
    }  
    else  
    {  
        Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(WebRequestPostOrGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + DicText["access_token"] + "&openid=" + DicText["openid"] + "&lang=zh_CN", ""));  
        return respDic;  
    }  
}  
 
#region Post/Get提交调用抓取  
/// <summary>  
/// Post/get 提交调用抓取  
/// </summary>  
/// <param name="url">提交地址</param>  
/// <param name="param">参数</param>  
/// <returns>string</returns>  
public static string WebRequestPostOrGet(string sUrl, string sParam)  
{  
    byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam);  
  
    Uri uriurl = new Uri(sUrl);  
    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);//HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + (url.IndexOf("?") > -1 ? "" : "?") + param);  
    req.Method = "Post";  
    req.Timeout = 120 * 1000;  
    req.ContentType = "application/x-www-form-urlencoded;";  
    req.ContentLength = bt.Length;  
  
    using (Stream reqStream = req.GetRequestStream())//using 使用可以释放using段内的内存  
    {  
        reqStream.Write(bt, 0, bt.Length);  
        reqStream.Flush();  
    }  
    try  
    {  
        using (WebResponse res = req.GetResponse())  
        {  
            //在这里对接收到的页面内容进行处理   
  
            Stream resStream = res.GetResponseStream();  
  
            StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8);  
  
            string resLine;  
  
            System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder();  
  
            while ((resLine = resStreamReader.ReadLine()) != null)  
            {  
                resStringBuilder.Append(resLine + System.Environment.NewLine);  
            }  
  
            resStream.Close();  
            resStreamReader.Close();  
  
            return resStringBuilder.ToString();  
        }  
    }  
    catch (Exception ex)  
    {  
        return ex.Message;//url错误时候回报错  
    }  
}  
#endregion Post/Get提交调用抓取  

没了

没错,就是这么简单,只有这么点内容就已经完成了整个微信授权登录的事情

 

--------------------------------------------------------------------------------------------------------- 

转载请记得说明作者和出处哦-.-
作者:KingDuDu
原文出处:https://www.cnblogs.com/kingdudu/articles/8795928.html

---------------------------------------------------------------------------------------------------------

 

posted @ 2018-04-11 15:19  KingDuDu  阅读(3359)  评论(1编辑  收藏  举报