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

小说:淘宝联盟现在还赚钱吗作者:成顺更新时间:2019-03-19字数:28805

【第二十一篇】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
原文出处:http://www.cnblogs.com/kingdudu/p/8795928.html

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

 

当前文章:http://zxqss.com/ask/question_29620.html

发布时间:2019-03-19 06:29:39

什么软件可以赚零钱 手机赚赚是真的吗 怎样在淘宝赚差价 有几台电脑怎么赚钱 花生日记赚钱方法介绍 37个商机适合在家赚钱 好券代理佣金多少 美逛合伙人怎么退出 我下载了脉脉怎么赚不到钱 让流行语成为正能量的载体

美团众包过年时单价 达人店为什么没人管 虎牙佣金提现整数 超级惠赚怎样赚钱 苹果手机 零钱通 省钱优选联盟怎么赚钱 手机虎牙直播佣金提现 天猫超市加盟代理 用手机做兼职的推广语 摇旺理财投100元7天赚20元 启梦微赚平台正规吗 男朋友昨天晚上太穷了 宁波杭州湾新区世纪城 打码一天赚100块钱 零钱夺宝软件 苹果手机打字兼职 网络直播是如何赚钱的 网络赚钱兼职靠谱吗 学生赚一天20元技巧

编辑:侯侯

我要说两句: (0人参与)

发布