标签:
原文:登陆整合实现-QQ互联认证(ASP.NET版本)QQSettingConfig qqSettingConfig = MySiteConfig.GetConfig<QQSettingConfig>();//配置对象 配置QQ的 app id appkey 回调地址 public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string state = new Random(100000).Next(99, 99999).ToString();//随机数 context.Session["state"] = state; string callback = System.Web.HttpUtility.UrlEncode(qqSettingConfig.CallBackAddress + "/QQCallBack.aspx", Encoding.UTF8);//回调处理地址 string url = string.Format("https://graph.qq.com/oauth2.0/authorize?client_id={0}&response_type=code&redirect_uri={1}&state={2}", qqSettingConfig.APPID, callback, state);//互联地址 context.Response.Redirect(url); }
QQSettingConfig qqSettingConfig = MySiteConfig.GetConfig<QQSettingConfig>();//配置对象 配置QQ的 app id appkey 回调地址
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { try { string code = HttpContext.Current.QueryString["code"]; string state = HttpContext.Current.QueryString["state"]; ValidCodeState(code, state); QQOauthInfo qqOauthInfo = GetOauthInfo(code); string openID = GetOpenID(qqOauthInfo); string nickName = GetUserInfo(qqOauthInfo, openID); if (string.IsNullOrEmpty(nickName)) { WriteErrMsg("获取不到昵称"); } #region 开始进行注册或者登录 OauthUserModel oauthUserModel = BLL.OauthUserBll.GetInfoByOpenId("qq", openID); if (!oauthUserModel.IsNull) { //已经绑定过则登录 DealLogin(oauthUserModel); } else { //进行绑定 this.TxtRegUserName.Text = nickName; this.hidenNiName.Value = nickName; this.hidenOpenID.Value = openID; this.LabelNiName.Text = nickName; this.LabelOpenID.Text = openID; } #endregion } catch (Exception ex) { //ShowError("出错了:"+ ex.Message); } } }
/// <summary> /// 验证code和state /// </summary> /// <param name="code"></param> /// <param name="state"></param> private void ValidCodeState(string code, string state) { if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(state)) { ShowError("CODE或者STATE为空"); } if (Session["state"] == null || Session["state"].ToString() != state) { ShowError("STATE不正确"); } }
QQOauthInfo qqOauthInfo = GetOauthInfo(code); 方法如下 /// <summary> /// 获取oauth信息 /// </summary> /// <param name="code"></param> /// <returns></returns> private QQOauthInfo GetOauthInfo(string code) { string callback = System.Web.HttpUtility.UrlEncode(qqSettingConfig.CallBackAddress + "/QQCallBack.aspx", Encoding.UTF8); string url = string.Format("https://graph.qq.com/oauth2.0/token?grant_type={0}&client_id={1}&client_secret={2}&code={3}&redirect_uri={4}", "authorization_code", qqSettingConfig.APPID, qqSettingConfig.APPKEY, code, callback); string res = LoadHtmlUserGetType(url, Encoding.UTF8); if (!res.Contains("access_token=")) { ShowError("出错了:空access_token"); } QQOauthInfo qqOauthInfo = new QQOauthInfo(); qqOauthInfo.AccessToken = CutString(res, "access_token=", "&expires_in="); qqOauthInfo.ExpiresIn = CutString(res, "&expires_in=", "&refresh_token="); qqOauthInfo.RefreshToken = res.Split(new string[] { "&refresh_token=" }, StringSplitOptions.None)[1]; if (string.IsNullOrEmpty(qqOauthInfo.AccessToken) || string.IsNullOrEmpty(qqOauthInfo.ExpiresIn) || string.IsNullOrEmpty(qqOauthInfo.RefreshToken)) { ShowError("获取access_token等信息为空"); } return qqOauthInfo; } /// <summary> /// 截取字符串中两个字符串中的字符串 /// </summary> /// <param name="str">字符串</param> /// <param name="startStr">开始字符串</param> /// <param name="endStr">结束字符串</param> /// <returns></returns> public string CutString(string str, string startStr, string endStr) { int begin, end; begin = str.IndexOf(startStr, 0) + startStr.Length; //开始位置 end = str.IndexOf(endStr, begin); //结束位置 return str.Substring(begin, end - begin); //取搜索的条数,用结束的位置-开始的位置,并返回 } /// <summary> /// 通过GET方式获取页面的方法 /// </summary> /// <param name="urlString">请求的URL</param> /// <param name="encoding">页面编码</param> /// <returns></returns> public string LoadHtmlUserGetType(string urlString, Encoding encoding) { HttpWebRequest httpWebRequest = null; HttpWebResponse httpWebRespones = null; Stream stream = null; string htmlString = string.Empty; try { httpWebRequest = WebRequest.Create(urlString) as HttpWebRequest; } catch (Exception ex) { throw new Exception("建立页面请求时发生错误!", ex); } httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; Maxthon 2.0)"; try { httpWebRespones = (HttpWebResponse)httpWebRequest.GetResponse(); stream = httpWebRespones.GetResponseStream(); } catch (Exception ex) { throw new Exception("接受服务器返回页面时发生错误!", ex); } StreamReader streamReader = new StreamReader(stream, encoding); try { htmlString = streamReader.ReadToEnd(); } catch (Exception ex) { throw new Exception("读取页面数据时发生错误!", ex); } streamReader.Close(); stream.Close(); return htmlString; }
public class QQOauthInfo { public string AccessToken { get; set; } public string ExpiresIn { get; set; } public string RefreshToken { get; set; } }
string openID = GetOpenID(qqOauthInfo); 方法如下 /// <summary> /// 获取QQ账号的OpenID /// </summary> /// <param name="qqOauthInfo"></param> /// <returns></returns> private string GetOpenID(QQOauthInfo qqOauthInfo) { string res = LoadHtmlUserGetType("https://graph.qq.com/oauth2.0/me?access_token=" + qqOauthInfo.AccessToken, Encoding.UTF8); if (!res.Contains("openid")) { WriteErrMsg("出错了:获取用户的openid出错"); } return CutString(res, @"openid"":""", @"""}"); }
string nickName = GetUserInfo(qqOauthInfo, openID); 方法如下 /// <summary> /// 获取QQ昵称 /// </summary> /// <param name="qqOauthInfo"></param> /// <param name="openID"></param> /// <returns></returns> private string GetUserInfo(QQOauthInfo qqOauthInfo, string openID) { string urlGetInfo = string.Format(@"https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", qqOauthInfo.AccessToken, qqSettingConfig.APPID, openID); string resUserInfo = LoadHtmlUserGetType(urlGetInfo, Encoding.UTF8); if (!resUserInfo.Contains("\"msg\": \"\"")) { WriteErrMsg("出错了:获取用户信息出错"); } return CutString(resUserInfo, @"""nickname"": """, @""","); }
if (string.IsNullOrEmpty(nickName)) { ShowError("获取不到昵称"); } #region 开始进行注册或者登录 OauthUserModel oauthUserModel = BLL.OauthUserBll.GetInfoByOpenId("qq", openID); if (!oauthUserModel.IsNull) { //已经绑定过则登录 DealLogin(oauthUserModel); } else { //进行绑定 this.TxtRegUserName.Text = nickName; this.hidenNiName.Value = nickName; this.hidenOpenID.Value = openID; this.LabelNiName.Text = nickName; this.LabelOpenID.Text = openID; } #endregion
if exists( select 1 from sys.systable where table_name=‘PE_C_OauthUser‘ and table_type in (‘BASE‘, ‘GBL TEMP‘) ) then drop table PE_C_OauthUser end if; /*==============================================================*/ /* Table: PE_C_OauthUser */ /*==============================================================*/ create table PE_C_OauthUser ( ID int not null, NiName nvarchar(50) null, UserName nvarchar(50) null, Type nvarchar(50) null, AddTime datetime null, Status int null, OpenID nvarchar(150) null, UserID int null, constraint PK_PE_C_OAUTHUSER primary key clustered (ID) ); comment on table PE_C_OauthUser is ‘用户和QQ或者微信等其他的Oauth关联‘; comment on column PE_C_OauthUser.ID is ‘主键ID‘; comment on column PE_C_OauthUser.NiName is ‘昵称从QQ或者微信取得的昵称‘; comment on column PE_C_OauthUser.UserName is ‘我方系统用户名‘; comment on column PE_C_OauthUser.Type is ‘类型:如QQ WEIXIN‘; comment on column PE_C_OauthUser.AddTime is ‘添加时间‘; comment on column PE_C_OauthUser.Status is ‘状态‘; comment on column PE_C_OauthUser.OpenID is ‘是QQ则openid 微信则‘; comment on column PE_C_OauthUser.UserID is ‘我方系统用户ID‘; if exists( select 1 from sys.systable where table_name=‘PE_C_OauthUser‘ and table_type in (‘BASE‘, ‘GBL TEMP‘) ) then drop table PE_C_OauthUser end if; /*==============================================================*/ /* Table: PE_C_OauthUser */ /*==============================================================*/ create table PE_C_OauthUser ( ID int not null, NiName nvarchar(50) null, UserName nvarchar(50) null, Type nvarchar(50) null, AddTime datetime null, Status int null, OpenID nvarchar(150) null, UserID int null, constraint PK_PE_C_OAUTHUSER primary key clustered (ID) ); comment on table PE_C_OauthUser is ‘用户和QQ或者微信等其他的Oauth关联‘; comment on column PE_C_OauthUser.ID is ‘主键ID‘; comment on column PE_C_OauthUser.NiName is ‘昵称从QQ或者微信取得的昵称‘; comment on column PE_C_OauthUser.UserName is ‘我方系统用户名‘; comment on column PE_C_OauthUser.Type is ‘类型:如QQ WEIXIN‘; comment on column PE_C_OauthUser.AddTime is ‘添加时间‘; comment on column PE_C_OauthUser.Status is ‘状态‘; comment on column PE_C_OauthUser.OpenID is ‘是QQ则openid 微信则‘; comment on column PE_C_OauthUser.UserID is ‘我方系统用户ID‘;
if (!oauthUserModel.IsNull) { //已经绑定过则登录 DealLogin(oauthUserModel); }
//进行绑定 this.TxtRegUserName.Text = nickName; this.hidenNiName.Value = nickName; this.hidenOpenID.Value = openID; this.LabelNiName.Text = nickName; this.LabelOpenID.Text = openID;
//添加到绑定表 OauthUserModel oauthUserModelNew = new OauthUserModel(); oauthUserModelNew.AddTime = DateTime.Now; oauthUserModelNew.NiName = this.hidenNiName.Value; oauthUserModelNew.OpenID = this.hidenOpenID.Value; oauthUserModelNew.Status = 1; oauthUserModelNew.Type = "qq"; oauthUserModelNew.UserID = usersInfo.UserId; oauthUserModelNew.UserName = usersInfo.UserName; if (!BLL.OauthUserBll.Add(oauthUserModelNew)) { ShowError("绑定失败"); }
标签:
原文地址:http://www.cnblogs.com/lonelyxmas/p/4672987.html