[C#]QQ開放平台(QQ站外登錄)_流程和源碼示例[原創]


本人阿旭,近期研究QQ開放平台的程序開發。因為使用.NET語言,到官方SDK下載竟然是一個DLL,下來經過反編譯也沒搞清楚怎么弄,暈菜。后來網上見一PHP源碼,寫的不錯,按其原理,開發成了C#語言,本示例程序使用的OAuth2.0,是目前最新執口版本,寫下來希望對大家有所幫忙。

本文內容

QQ開放平台(QQ登錄)開發介紹

QQ開放平台是針對QQ網站以外的網站開發的信息共享接口,各網站通過實現QQ代碼實現,可以與QQ網站的交換數據。本文說的是騰訊的OpenID開發,相關OpenID的相關文章,是有相關技術標准的,大家可以看百科會更詳細。簡單來說,就是說,在用戶登錄網站時,只使用綁定QQ的QQ帳號進行登錄即可,無需每次去輸入各網站的密碼...

准備工作

訪問:http://opensns.qq.com/,點擊(圖1)上的QQ登錄鏈接,然后點擊(圖2)中“申請加入”鏈接,輸入你的QQ帳號進行QQ登錄驗證,點擊(圖3)中的“添加網站/應用”鏈接。輸入網站相關信息和網站驗證后,會顯示(圖4)顯示的管理中心界面。上面顯示着AppID和AppKey,下面的程序中將會用到,保密數據,請誤泄露哈!

 

qq開放平台

圖1

圖2

圖3

圖4

QQ開放平台中QQ登錄程序運行流程

1、客戶端瀏覽器轉向QQ驗證頁面,用戶輸入用戶名密碼后,QQ網站回調回開發者網站,並傳回Authorization Code。

2、開發者網站發送獲取到的Authorization Code后,將Authorization Code和AppID、AppKey使用Http協議發送給騰訊,騰訊驗證后返回登錄結果。

3、如果驗證成功,返回用戶的OpenID,OpenID是登錄用戶登錄后的在開發者網站中唯一標識,升度為32位,字符范圍為0-9A-F。

示例程序源碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using System.Collections.Specialized;
using System.Text.RegularExpressions;

public partial class _Default : System.Web.UI.Page
{
        private static Random RndSeed = new Random();

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

    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);
            //Response.Write(m.Groups[2].Value + "=" + m.Groups[3].Value + "<br/>");
        }
        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;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //應用的APPID
        string app_id = "粘貼你的APPID";
        //應用的APPKEY
        string app_secret = "粘貼你的APPKey";
        //成功授權后的回調地址
        string my_url = "http://www.yourSite.cn/Default.aspx";

        //Step1:獲取Authorization Code
        //session_start();
        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(my_url) + "&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=" + Server.UrlEncode(my_url)
            + "&client_secret=" + app_secret + "&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("<h3>error:</h3>" + msg["error"].ToString());
                    Response.Write("<h3>msg  :</h3>" + msg["error_description"]);
                    Response.End(); return;
                }
            }
            //Response.Write(response);
            //Step3:使用Access Token來獲取用戶的OpenID
            NameValueCollection ps = ParseUrlParameters(response);
            //*parse_str($response, $params);
            string graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" + ps["access_token"];
            string str = file_get_contents(graph_url, Encoding.Default);
            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("<h3>error:</h3>" + user["error"]);
                Response.Write("<h3>msg  :</h3>" + user["error_description"]);
                Response.End();
            }
            Response.Write("Hello " + user["openid"]);
        }
        else
        {
            Response.Write("The state does not match. You may be a victim of CSRF.request=" + Request["state"] + ",session=" + Session["state"]);
        }

        Response.End();
    }
}

本地測試方法

     1、用記事本打開:C:\Windows\System32\drivers\etc\hosts文件

     2、新增行“127.0.0.1       域 名”,比如:127.0.0.1    www.jishu.me即可(當前這個域名必須是QQ開放平台“添加網站/應用”時輸入的域名,否則會報錯)。

     3、重新啟動IE瀏覽器后,輸入域名即可訪問本地站點,注意IIS中綁定的IP要與Host文件中指定的IP一致。

版所所有阿旭博客,如要轉載,請注明來源:http://www.cnblogs.com/a-xu/archive/2012/04/07/qq_login.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM