(一). 實現QQ登錄自己開發的網站
首先需要在http://connect.qq.com/申請一個網站應用的 APP ID 和APP KEY。申請流程如下:
1. 登錄QQ互聯之后,注冊成為開發者,填寫相關資料,根據自己選擇公司或者個人都行
2. 在【管理中心】點擊創建應用
3. 填寫應用的相關信息,填寫網站之后記得根據提示進行網站的驗證
4. 填寫回調地址,其實回調地址可以自己定義(如果是本地測試,可以用IP地址)
5. 以上步驟完成之后,就會獲取到APP ID 和APP KEY
接下來就是准備做開發了:
過程是參照博客園的 張善友 博友的文章來做的,原文地址:http://www.cnblogs.com/shanyou/archive/2012/02/05/2338797.html
1. 首先下載 SDK(http://opensns.codeplex.com/)。SDK依賴於Newtonsoft.Json和RestSharp兩個程序集,具體可以參考使用RestSharp 庫消費Restful Service。 主要是兩個類QzoneContext(QQ登陸的上下文數據) 和 QOpenClient (QQ互聯API入口),其他類主要是模型,配置類。
2. 配置文件中加入如下內容:
1 <configSections> 2 <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> 3 4 <sectionGroup name="QQSectionGroup"> 5 <section name="QzoneSection" type="System.Configuration.NameValueSectionHandler,System, Version=4.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089" /> 6 </sectionGroup> 7 8 </configSections> 9 10 <QQSectionGroup> 11 <QzoneSection> 12 <add key="AppKey" value="" /> 13 <add key="AppSecret" value="" /> 14 <add key="CallBackURI" value="http://www.xxxxxx.com/QQCallBack.html" /> 15 <add key="AuthorizeURL" value="https://graph.qq.com/oauth2.0/authorize" /> 16 </QzoneSection> 17 </QQSectionGroup>
3. 我這里是用 MVC 模式,后台代碼如下:
1 public ActionResult Index() 2 { 3 //this.Session[RETURNURL] = returnUrl; 4 var context = new QzoneContext(); 5 string state = Guid.NewGuid().ToString().Replace("-", ""); 6 Session["requeststate"] = state; 7 string scope = "get_user_info,add_share,list_album,upload_pic,check_page_fans,add_t,add_pic_t,del_t,get_repost_list,get_info,get_other_info,get_fanslist,get_idolist,add_idol,del_idol,add_one_blog,add_topic,get_tenpay_addr"; 8 model.authenticationUrl = context.GetAuthorizationUrl(state, scope); 9 10 return View(model); 11 }
前台頁面如下:
@model dynamic @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <meta property="wb:webmaster" content="9ff88f2c5fc7bf93" /> <title>Index</title> </head> <body> <div> 用戶名:<input type="text" /><br /> 密 碼:<input type="password" /><br /> <input type="button" value="登錄" /> </div> <div> <a href="@Model.authenticationUrl"><img src="~/Images/qq.png" />QQ賬號登錄</a> </div> </body> </html>
測試界面如下:點擊后可實現QQ登錄
這樣雖然實現了QQ 登錄,但是只能用你自己的開發者的QQ賬號來登錄,如果要使用任意QQ賬號登錄的話,需要應用通過TX審核。。。
注意:
如果是本地測試,IIS 發布的網站端口修改為80 ,修改 C:\Windows\System32\drivers\etc 中的hosts文件,添加IIS中的網站IP和對應域名: