登陆整合实现-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().Next(, ).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)[];
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, ) + 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 = ;
oauthUserModelNew.Type = "qq";
oauthUserModelNew.UserID = usersInfo.UserId;
oauthUserModelNew.UserName = usersInfo.UserName;
if (!BLL.OauthUserBll.Add(oauthUserModelNew))
{
ShowError("绑定失败");
}
登陆整合实现-QQ互联认证(ASP.NET版本)的更多相关文章
- 分享一下,PHP实现第四方QQ微信扫码登陆,不接入qq互联以及微信开发者平台就可以实现用户对接鹅厂,phpQQ微信扫码登陆
自己抓的QQ包以及整合了网上一些已经封装好了的代码具体如下:QQ: <?php class QQ extends Curl_Api { //获取登录验证码 public function QRc ...
- QQ 互联认证 回调地址提示说要http :// 但是事实不用
真奇怪 腾讯最近人手不够吧 这样的错误也会犯错....
- QQ登录整合/oauth2.0认证-02-跳转到QQ互联页
---------------------------目录---------------------------------- QQ登录整合/oauth2.0认证-01-申请appkey和appid ...
- QQ登录整合/oauth2.0认证-04-调整到QQ互联进行QQ登录
---------------------------------目录------------------------------------- QQ登录整合/oauth2.0认证-03-对第二节的代 ...
- QQ互联OAuth2.0 .NET SDK 发布以及网站QQ登陆示例代码(转)
OAuth: OAuth(开放授权)是一个开放标准,允许用户授权第三方网站访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方网站或分享他们数据的所有内容. QQ登录OAuth2 ...
- QQ互联OAuth2.0 .NET SDK 发布以及网站QQ登陆示例代码
OAuth: OAuth(开放授权)是一个开放标准,允许用户授权第三方网站访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方网站或分享他们数据的所有内容. QQ登录OAuth2 ...
- QQ互联登陆(Java)
一.准备部分 1.账户注册 腾讯开放平台网址: https://connect.qq.com/index.html 首先需要到开放平台注册QQ互联开发者身份.注册之后创建一个网站应用,注意,需要备案成 ...
- ASP.NET MVC QQ互联接入
ASP.NET MVC QQ Connect 介绍 ASP.NET MVC QQ互联接入Demo. 项目地址:https://gitee.com/Liu_Cabbage/ASP.NET-MVC-QQ- ...
- 第三方登陆-qq互联
看到很多网站都有第三方登陆,使用业余时间自己也要实现一个第三方登陆的功能: 1.登陆qq互联的网站:https://connect.qq.com/index.html 2.点击头像进行资料申请 --- ...
随机推荐
- Linux 动态库剖析
进程与 API 动态链接的共享库是 GNU/Linux® 的一个重要方面.该种库允许可执行文件在运行时动态访问外部函数,从而(通过在需要时才会引入函数的方式)减少它们对内存的总体占用.本文研究了创建和 ...
- 关于Qt信号与槽机制的传递方向性研究(结论其实是错误的,但是可以看看分析过程)
最近由于项目的需求,一直在研究Qt.信号与槽机制是Qt的一大特色,该机制允许两者间传递参数,依次来实现对象间的通信.这个参数会分别存在于信号的参数列表和槽函数的参数列表中.需要注意的是,若将槽函数绑定 ...
- STM32关于优先级设定的理解 NVIC_SetPriority()
Systick模块初始化配置函数(Systick_config)中设定模块中断优先级的函数为: NVIC_SetPriority((SysTick_IRQn, (1<<__NVIC_PRI ...
- 用户 'IIS APPPOOL\DefaultAppPool' 登录失败解决办法
法一:将iis站点的应用程序池的用户改为本地用户,如果所示: 方法二: 1.打开sql server management studio安全性->登录名->右击新建登录名->常规- ...
- C3P0连接池参数解释
<!--acquireIncrement:链接用完了自动增量3个. --> <property name="acquireIncrement">3</ ...
- linux c: 静态库和动态库的生成和使用
场景: main函数需要两个接口,一个求和函数,一个打印函数. int sum(int i, int j); 求两个int数字的和. void show(int i, char* name); 打印i ...
- 杭电ACM 2052 Picture
Picture Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Su ...
- (转)跟我一起写MAKEFILE
概述 —— 什么是makefile?或许很多Winodws的程序员都不知道这个东西,因为那些Windows的IDE都为你做了这个工作,但我觉得要作一个好的和professional的程序员,makef ...
- Subsets 【dfs】
Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset must ...
- windows apache 配置多个服务 站点 Apache Service Monitor
把Apache安装为多个Window NT服务 ~~~ 可以在 services.msc中查看到1. 在DOS下跳到Apache安装目录里的bin目录(~~~或者用path命令 把apache的安装目 ...