QQ自动登录

1.首先要有个访问页面触发回调地址

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FgHouses
{
    public partial class QQHuLian : System.Web.UI.Page
    {
        ///调用方法
        string client_id = "101481920";//微信商户号
        string appid = "94a5e7857a915b86f5d3a2aa976c9c1d";//微信appid
        string Return_url = System.Configuration.ConfigurationManager.AppSettings["weburl"] + "/" + "api/qq_return.aspx";//回调地址
        //string Return_url = "http://jdfc.hzqianren.com/api/qq_return.aspx";
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(Authorize());
        }
        public string Authorize()
        {
            string state = new Random(100000).Next(99, 99999).ToString();//随机数
            //HttpHelper http = new HttpHelper();
            string url = string.Format("https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id={0}&redirect_uri={1}&state={2}", client_id, Return_url, state);
            string str = "";
            return str;
        }
      
    }
}

2.回调地址页面处理功能 (先粘代码为敬(*^__^*) 嘻嘻)

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Socut;
using UserCenter.UserCenter;
using yhw;
using System.Text.RegularExpressions;

namespace FgHouses
{
    public partial class qq_return : System.Web.UI.Page
    {
        string client_id = "101481920";
        string appid = "94a5e7857a915b86f5d3a2aa976c9c1d";
        string Return_url = System.Configuration.ConfigurationManager.AppSettings["weburl"] + "/" + "api/qq_return.aspx";
        //string Return_url = "http://jdfc.hzqianren.com/api/qq_return.aspx";
        protected void Page_Load(object sender, EventArgs e)
        {
            string code = base.Request.QueryString["code"].ToString();
            Back_User(code);
        }
        /// 
        /// 请求指定url地址并返回结果
        /// 
        /// 
        /// 
        public static string RequestUrl(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.MaximumAutomaticRedirections = 3;
            request.Timeout = 0x2710;
            Stream responseStream = ((HttpWebResponse)request.GetResponse()).GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            string str = reader.ReadToEnd();
            reader.Close();
            responseStream.Close();
            return str;
        }

        /////回调页面的代码
        public void Back_User(string code)
        {
            string str2 = AllCs.IPAddress.ToString();
            string state = new Random(100000).Next(99, 99999).ToString();//随机数
            User_info ui = new User_info();
            string url = string.Format("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id={0}&client_secret={1}&code={2}&redirect_uri={3}&state={4}", client_id, appid, code, Return_url, state);
            string uu = RequestUrl(url);//处理http请求帮助类
            string code1 = uu.Split('&')[0].Split('=')[1].ToString();//获得access_token

            //根基access_token获取用户唯一OpenID
            string url_me = string.Format("https://graph.qq.com/oauth2.0/me?access_token={0}", code1);
            string callback = RequestUrl(url_me);//这里获取的
            callback = callback.Substring(callback.IndexOf('(') + 1, (callback.IndexOf(')') - callback.IndexOf('(') - 1)).Trim();
            //  dynamic jsonP = JValue.Parse(callback); //这里我用的是一个序列化类库 Newtonsoft.Json.dll 6.0.4版本无奈公司版本过低 只能用4.0的版本 建议使用6.0.4版本
            a jsonP = JsonConvert.DeserializeObject(callback);//Newtonsoft.Json.dll 4.0或4.5版本
            string OpenID = jsonP.openid;//获取用户唯一的OpenID  .

            //  string sql = "select * from Y_person where Y_Y_OpenId ='" + OpenID + "'";
            Reader reader = new Reader("SELECT Y_psd,Y_name,Y_id,Y_ip,Y_logintime,Y_hits,Y_lock,Y_che FROM Y_person WHERE  QQopenid ='" + OpenID + "' ");
            //这里主要是判断此用户是否以自动登陆过,若登录过就会有QQopenid 更新信息存下cookie 若 没有就存cookie就行了
            if (reader.Read())
            {
                if (reader["Y_lock"].ToString() == "2")
                {
                    Data.ExecuteNonQuery("UPDATE Y_person SET Y_hits=Y_hits+1,Y_logintime = getdate(),Y_ip = '" + str2 + "' where  QQopenid ='" + OpenID + "'  ");
                    #region 注释为未使用方法存的cookie 用此来获取用户信息
                    //HttpCookie cookie = new HttpCookie("ycfcw");
                    //cookie.Values["name"] = reader["Y_name"].ToString();
                    //cookie.Values["psd"] = reader["Y_psd"].ToString();
                    //cookie.Values["personid"] = reader["Y_id"].ToString();
                    //cookie.Values["hits"] = reader["Y_hits"].ToString();
                    //cookie.Values["logintime"] = reader["Y_logintime"].ToString();
                    //cookie.Values["ip"] = reader["Y_ip"].ToString();
                    //cookie.Values["che"] = reader["Y_che"].ToString();
                    //base.Response.AppendCookie(cookie);
                    //cookie.Expires = DateTime.Now.AddDays(30.0);
                    #endregion
                    DAL.SessionHelper.Add("ycfcw", "ycfcw");
                    DAL.SessionHelper.Add("ycfcw-name", reader["Y_name"].ToString());
                    DAL.SessionHelper.Add("ycfcw-psd", reader["Y_psd"].ToString());
                    DAL.SessionHelper.Add("ycfcw-personid", reader["Y_id"].ToString());
                    DAL.SessionHelper.Add("ycfcw-hits", reader["Y_hits"].ToString());
                    DAL.SessionHelper.Add("ycfcw-logintime", reader["Y_logintime"].ToString());
                    DAL.SessionHelper.Add("ycfcw-ip", reader["Y_ip"].ToString());
                    DAL.SessionHelper.Add("ycfcw-che", reader["Y_che"].ToString());
                    string u = Request.ServerVariables["HTTP_USER_AGENT"];
                    #region 这个是判断是那端登录的  参数如下百度就有 方法各异仅供参考
                    Regex b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    if ((b.IsMatch(u) || v.IsMatch(u.Substring(0, 4))))
                    {
                        //手机访问
                        base.Response.Redirect("~/mobile/my/default.aspx");
                    }
                    else
                    {
                        //电脑访问
                        base.Response.Redirect("~/Member/default.aspx");
                    }

            #endregion
                }
                else
                {
                    base.Response.Write("");
                }
            }
            else
            {
                //根据OpenID获取用户信息 可以显示更多 用的就几个 需要的可以自己在下面加
                string getinfo = string.Format("https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", code1, client_id, OpenID);
                string user = RequestUrl(getinfo);
                b info = JsonConvert.DeserializeObject(user);
                //HttpCookie cookie = new HttpCookie("QQhl2");
                //cookie.Values["name"] = info.nickname;
                //cookie.Values["OpenID"] = OpenID;
                //cookie.Values["img_qq100"] = info.figureurl_qq_1;
                //cookie.Values["img_qq50"] = info.figureurl_qq_2;
                //cookie.Values["city"] = info.city;
                //cookie.Values["year"] = info.year.ToString();
                //cookie.Values["Type"] = "1";
                //base.Response.AppendCookie(cookie);
                //cookie.Expires = DateTime.Now.AddDays(30.0);
                DAL.SessionHelper.Add("QQhl2", "QQhl2");
                DAL.SessionHelper.Add("QQhl2-name", info.nickname);
                DAL.SessionHelper.Add("QQhl2-OpenID", OpenID);
                DAL.SessionHelper.Add("QQhl2-img_qq100", info.figureurl_qq_1);
                DAL.SessionHelper.Add("QQhl2-img_qq50", info.figureurl_qq_2);
                DAL.SessionHelper.Add("QQhl2-city", info.city);
                DAL.SessionHelper.Add("QQhl2-year", info.year.ToString());
                DAL.SessionHelper.Add("QQhl2-Type", "1");
                string u = Request.ServerVariables["HTTP_USER_AGENT"];
                Regex b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                if ((b.IsMatch(u) || v.IsMatch(u.Substring(0, 4))))
                {
                    //手机访问
                    base.Response.Redirect("~/mobile/zdlogin.aspx");
                }
                else
                {
                    //电脑访问
                    base.Response.Redirect("~/zhdizhi.aspx");
                }
          
                //b info = JsonConvert.DeserializeObject(user);
                //ui.Name = info.nickname;
                //ui.OpenID = OpenID;
                //ui.img_qq100 = info.figureurl_qq_1;
                //ui.img_qq50 = info.figureurl_qq_2;
                //ui.city = info.city;
                //ui.year = info.year;
                ////ui.Type = 1;
                //return ui;
            }
        }
    }
}

3.帮助类

public class b
{

    public string nickname { get; set; }

    public string figureurl_qq_1 { get; set; }
    public string figureurl_qq_2 { get; set; }
    public string city { get; set; }
    public int year { get; set; }
}
public class a
{

    public string client_id { get; set; }

    public string openid { get; set; }
}
public class User_info
{
    public string OpenID { get; set; }//用户唯一appid

    public string Name { get; set; }

    public string img_qq50 { get; set; } //QQ图像40*40

    public string img_qq100 { get; set; }

    public string city { get; set; }

    public int year { get; set; }
}

4.便是要在注册的时候主要就是加上这个QQopenid 用来判断并实现自动登录在添加时去判断上面的cookie是否为空,若不为空就加上这个openid这块方法改了就不粘了,你们用原始的就行无所谓的

代码如下

  if (DAL.SessionHelper.Get("QQhl2") != null)
                            {
                                if (DAL.SessionHelper.Get("QQhl2-name").ToString() != "")
                                {
                                    nickname = DAL.SessionHelper.Get("QQhl2-name").ToString();
                                }
                                if (DAL.SessionHelper.Get("QQhl2-img_qq100").ToString() != "")
                                {
                                    headurl = DAL.SessionHelper.Get("QQhl2-img_qq100").ToString();
                                }
                                if (DAL.SessionHelper.Get("QQhl2-OpenID").ToString() != "")
                                {
                                    openid = DAL.SessionHelper.Get("QQhl2-OpenID").ToString();
                                }
                                Data.ExecuteNonQuery(string.Concat(new object[] { 
                            "insert into Y_person (Y_truename,Y_mobile,Y_name,Y_psd,Y_issue,Y_answer,Y_ip,Y_che,Y_company,Y_tel,Y_address,Y_house,Y_lock,Y_email,Y_nickname,Y_pic,QQopenid) values ('", str12, "','", str11, "','", str2, "','", str6, "','", str4, "','", str5, "','", str, "',2,'", str8, 
                            "','", str9, "','", str10, "',1,", num, ",'"+semail+"','" + nickname + "','" + headurl + "','" + openid + "')"
                         }));
                                base.Response.Write("");
                                base.Response.End();
                            }

 

 

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