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;

    }

}

 

你可能感兴趣的:(asp.net)