asp.net 集成QQ2.0 登陆代码示例

using System;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Xml;
using System.Data;
using System.Collections;
using Game.Facade;
using Game.Kernel;
using Game.Entity.Accounts;
using Game.Utils;

public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        string redirecturl = System.Configuration.ConfigurationManager.AppSettings["redirecturl"];
        //申请QQ登录成功后,分配给应用的appid
        string app_id = System.Configuration.ConfigurationManager.AppSettings["appid"];
        //申请QQ登录成功后,分配给网站的appkey
        string app_key = System.Configuration.ConfigurationManager.AppSettings["appkey"];
        string strOpenId = Request.QueryString["openid"] ?? string.Empty;
        if (strOpenId.Length <= 0)
        {
            //Step1:获取Authorization Code  
            string code = Request.QueryString["code"];
            if (string.IsNullOrEmpty(code))
            {
                //state参数用于防止CSRF攻击,成功授权后回调时会原样带回  
                Session["state"] = GenerateRndNonce();//md5(uniqid(rand(), TRUE));   
                //拼接URL       
                string dialog_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
                   + app_id + "&redirect_uri=" + Server.UrlEncode(redirecturl) + "&state="
                   + Session["state"];
                Response.Write("<script> location.href='" + dialog_url + "'</script>");
                Response.End();
            }
            //Step2:通过Authorization Code获取Access Token  
            if (Request["state"].ToString().Equals(Session["state"].ToString()))
            {
                //拼接URL     
                string token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
                + "client_id=" + app_id + "&redirect_uri=" + redirecturl
                + "&client_secret=" + app_key + "&code=" + code;
                string response = file_get_contents(token_url, Encoding.UTF8);
                NameValueCollection msg;
                if (response.IndexOf("callback") != -1)
                {
                    int lpos = response.IndexOf("(");
                    int rpos = response.IndexOf(")");
                    response = response.Substring(lpos + 1, rpos - lpos - 1);
                    msg = ParseJson(response);
                    if (!string.IsNullOrEmpty(msg["error"]))
                    {
                        Response.Write("<script>" + "QQ第三方登录step2失败:" + msg["error"] + "\n" + msg["error_description"] + "</script>");
                        Response.Write("<script>window.close();</script>");
                        Response.End();
                    }
                }

                //Step3:使用Access Token来获取用户的OpenID  
                NameValueCollection ps = ParseUrlParameters(response);
                string graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" + ps["access_token"];
                string str = file_get_contents(graph_url, Encoding.UTF8);
                if (str.IndexOf("callback") != -1)
                {
                    int lpos = str.IndexOf("(");
                    int rpos = str.IndexOf(")");
                    str = str.Substring(lpos + 1, rpos - lpos - 1);
                }
                NameValueCollection user = ParseJson(str);
                if (!string.IsNullOrEmpty(user["error"]))
                {
                    Response.Write("<script>" + "QQ第三方登录step3失败:" + user["error"] + "\n" + user["error_description"] + "</script>");
                    Response.Write("<script>window.close();</script>");
                    Response.End();
                }
                //Step4:通过access_token,appid,openid获得用户信息
                string openid = user["openid"];
                string get_user_info_url = "https://graph.qq.com/user/get_user_info?access_token=" + ps["access_token"]
                    + "&oauth_consumer_key=" + user["client_id"]
                    + "&openid=" + openid + "&format=xml";
                string userInfo = file_get_contents(get_user_info_url, Encoding.UTF8);
                
                //NameValueCollection nvUserInfo = ParseJson(userInfo);
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(userInfo);
                XmlNodeList sectionNodeList = xml.GetElementsByTagName("data");
                string nickname = string.Empty;
                if (sectionNodeList[0].ChildNodes[2] == null)
                {
                    Response.Write("<script>" + "QQ第三方登录step4失败:" + sectionNodeList[0].ChildNodes[1].Name + "\n" 
                        + sectionNodeList[0].ChildNodes[1].InnerXml + "</script>");
                    Response.Write("<script>window.close();</script>");
                    Response.End();
                }
                string ret = sectionNodeList[0].ChildNodes[0].InnerText;
                string msg1 = sectionNodeList[0].ChildNodes[1].InnerText; 
                nickname = sectionNodeList[0].ChildNodes[2].InnerText;
                string figureurl = sectionNodeList[0].ChildNodes[3].InnerText;
                string gender = sectionNodeList[0].ChildNodes[8].InnerText;
                //到这里就获得了QQ用户的昵称(保存在nickname),和openId保存在(user["openid"]);
                //接下来可以判断数据库中是否有此openid,有就登录,没有就注册然后登录
                //注册的时候数据库中要加一张表userid,openid这样的绑定关系表
                //下次用户再次登录的时候先找表中是否已经有openid,如果有的话就取出对应的userid登录                
                bool isExit = false;
                AccountsFacade accountsFacade = new AccountsFacade();
                DataTable dt1 = accountsFacade.LoginByQQ(openid, out isExit);
                if (isExit)
                {
                    string userName = dt1.Rows[0]["Accounts"].ToString();
                    string userPass = dt1.Rows[0]["LogonPass"].ToString();
                    //直接登录
                    Message umsg = accountsFacade.Logon(userName, userPass,true);
                    UserInfo ui = umsg.EntityList[0] as UserInfo;
                    ui.LogonPass = TextEncrypt.EncryptPassword(userPass);
                    Fetch.SetUserCookie(ui.ToUserTicketInfo());
                    Response.Redirect("/Member/MIndex.aspx");
                    Response.End();
                }
                else
                {
                    //注册并生成用户名和密码 
                    gender = gender=="男"?"1":"0";
                    Response.Redirect(string.Format("Register.aspx?isByQq=1&nickname={0}&gender={1}&openid={2}", nickname, gender,openid));
                    Response.End();
                }
                
            }
        }
    }

    private static Random RndSeed = new Random();

    public string GenerateRndNonce()
    {
        return (RndSeed.Next(1, 0xf423f).ToString("000000") + RndSeed.Next(1, 0xf423f).ToString("000000"));
    }

    public string file_get_contents(string url, Encoding encode)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        WebResponse response = request.GetResponse();
        using (MemoryStream ms = new MemoryStream())
        {
            using (Stream stream = response.GetResponseStream())
            {
                int readc;
                byte[] buffer = new byte[1024];
                while ((readc = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, readc);
                }
            }
            return encode.GetString(ms.ToArray());
        }
    }

    NameValueCollection ParseJson(string json_code)
    {
        NameValueCollection mc = new NameValueCollection();
        Regex regex = new Regex(@"(\s*\""?([^""]*)\""?\s*\:\s*\""?([^""]*)\""?\,?)");
        json_code = json_code.Trim();
        if (json_code.StartsWith("{"))
        {
            json_code = json_code.Substring(1, json_code.Length - 2);
        }

        foreach (Match m in regex.Matches(json_code))
        {
            mc.Add(m.Groups[2].Value, m.Groups[3].Value);
        }
        return mc;
    }

    NameValueCollection ParseUrlParameters(string str_params)
    {
        NameValueCollection nc = new NameValueCollection();
        foreach (string p in str_params.Split('&'))
        {
            string[] p_s = p.Split('=');
            nc.Add(p_s[0], p_s[1]);
        }
        return nc;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
注意: 不需要很多的类库 全部下来只有三个文件 。一个类库和两个前台页面,你将类库放到AppCode下面。然后将账号绑定那一块注释掉就行了,或者将账号绑定部分换成你自己系统的。就可以了。程序报错可能是因为我在绑定账号那里用到了别的类,你注释掉就行了 ------------------------------------------------------------ 经过两天的努力 已经成功将QQ登录集成到了 城记网 上。感谢腾讯提供的帮助文档,和关键时刻给的技术支持。我的网站是asp.net写的,有需要的网友可以联系我。 呵呵。(尽管是垃圾站,只要你愿意,又有什么关系呢?) QQ Oauth 只提供PHP的接入demo ,针对 ASP.net 的只有一个网友开发的SDK包,下载地址还老打不开,后来我从CSDN上下载了一个,看了以后感觉太复杂了,我个人感觉做这么个小事情不需要搞个SDK出来,不如自己按帮助文档去写,这样自己写的方法灵活性就高一些,于是就按文档学习开发。其实文档写得很清晰,耐心一看就明白了。 不讲太多的郁闷的过程了,直接说解决办法。 办这个事情主要要知道下面几个事情。 两个重点(如下): 第一个重点:请求Token的步骤, 1:请求未授权的临时token。请求成功以后会转到QQ登录页面。 2:请求已授权的临时token。登陆成功以后获得。 3:请求已授权的Access token。 第二个重点:签名的算法。 签名的值计算有一个指定的规则,请参考腾讯开放社区帮助文档,这是最 好的资料。 注意点: 没有申请APPID和APPKEY的先去申请。 传递的每一参数都要URLENcode,注意是每一个,包括动态生成的签名。    参数之间是有顺序的,是升序排列的,无论有多少个,都要排序。    各个步骤之间是有关联的,下一步的提交往往需要上一步的返回参数。 我采取的文档结构: 总共三个文件 ,非常简单。 一个放在APPcode下面的类。用来发送请求和接待参数。 两个前台页面,主要是对类的调用。 下面把类的代码完全贴出,你知要一看见类,就知道怎么写前台页面了,很简单

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值