Website Integration QQ Login function

Source: Internet
Author: User
Tags oauth openid unique id

Recently in a project, the customer asked the website can integrate QQ login function, has not done this aspect of the development, so go to QQ open Platform website to study the relevant information, through their own hard exploration, finally realized the integration of QQ login function, now the relevant development experience summed up, Hope to have a friend who has the need to help.

I. Pre-preparation

First you need to login QQ development platform to register an account, QQ Internet Platform official address: http://connect.qq.com/After the registration of a Development Account, the login backstage will have a similar to the following background, fill in the relevant information, specific can refer to. Finally we will have an app ID and app KEY, with these two things to achieve the following integrated QQ login function.


Two. Development work

When our account review, QQ development platform will give us an app ID and app KEY, with these two, we can carry out the work of development.
QQ is logged in using the OAuth2.0 protocol, OAuth (open authorization) is an open standard that allows users to authorize third-party websites to access information they store on other service providers without having to provide their usernames and passwords to third-party websites or to share all the content of their data. The specific content can refer to the QQ API document HTTP://WIKI.CONNECT.QQ.COM/OAUTH2-0%E7%AE%80%E4%BB%8B
QQ development platform has been php,java,js and other versions of the SDK, if you want to use these languages for development can directly refer to these SDKs, I would like to talk directly about the ASP version (MVC) development.

The first step is to first add the following configuration to the <appSettings> node in the Webconfig

<add key= "Qqappid" value= "QQ platform to the app ID"/><add key= "Qqappkey" value= "QQ development platform to the app key"/><add key= " Qqcallback "value=" http://www.mylanqiu.com/Account/QQConnect/"/><add key=" Qqauthorizeurl "value=" https:// Graph.qq.com/oauth2.0/authorize "/>

Step two. Add a login action to controllers (I'm using the MVC development approach, if it's a tradition.) NET can be added directly to the Page_Load event in. aspx as follows)

Public ActionResult Loginqq () {string state = new Random (100000). Next (99, 99999). ToString ();//random number session["qqstate"] = state;string AppID = configurationmanager.appsettings["Qqappid"];string Qqauthorizeurl = configurationmanager.appsettings["Qqauthorizeurl"];string callback = configurationmanager.appsettings["Qqcallback"];string Authenticationurl = string. Format ("{0}?client_id={1}&response_type=code&redirect_uri={2}&state={3}", Qqauthorizeurl, AppID, callback, State);//Interconnect address return new Redirectresult (Authenticationurl);}

This step is mainly to achieve the QQ platform to authenticate, the straight point of view is that after the click will appear the following screen


The third step . After clicking on the consent login (that is, QQ is already used in the QQ platform login), QQ platform will be configured by our above callback address is also my side to fill the http://www.mylanqiu.com/Account/ weiboconnect/return to this page, and will return a code to us, we will use this code to go to the QQ development platform to obtain access_token, and through this access_token to obtain the relevant user information login. The specific code is as follows:

<summary>///QQ Callback page///</summary>public ActionResult Qqconnect () {if (!string. IsNullOrEmpty (request.params["code") &&!string. IsNullOrEmpty (request.params["state"]) {var code = request.params[' Code '];var state = request.params[' state '];string RequestState = session["qqstate"] = = null? "": session["Qqstate"]. ToString (); if (state = = requeststate) {try{qqoauthhelper qauthhelper = new Qqoauthhelper ();//This is an auxiliary class, The code is given below qqoauthinfo Qqoauthinfo = qauthhelper.getoauthinfo (code); string OpenID = Qauthhelper.getopenid (qqoauthinfo) ;//access to the OpenID, this ID is QQ to our user's unique ID, can be used as our system user unique judgment exists in our own library session["Qqopenid"] = openid;string nickname = Qauthhelper.getuserinfo (Qqoauthinfo, OpenID);//Gets the user's nickname UserAccount useraccount = Accountbll.getuseraccountbyopenid ( OAuthPlatform.QQ.ToString (), OpenID), if (useraccount! = null)//Determines whether the OpenID is already in our library, and allows login {SetAuthCookie if already exists ( UserAccount); Response.Write ("<script> window.opener.location.reload (); Window.close ();</script>");} ViewData["nickname"] = Nickname;} catch (Exception ex) {return new Redirectresult ("~/error/error.htm");}} Else{return new Redirectresult ("~/error/error.htm");}} Else{return new Redirectresult ("~/error/error.htm");} return View ();}

Through the above steps can realize the website integration QQ login. The source code for the auxiliary class is given below:

Using system;using system.text;using system.configuration;using system.collections.generic;using System.Linq;using System.net;using system.web;using system.io;namespace com.abc.mylanqiu.bll{public class QQOAuthHelper{string AppID = configurationmanager.appsettings["Qqappid"];string AppKey = configurationmanager.appsettings["QQAppKey"];///< summary>///get OAuth information///</summary>///<param name= "code" ></param>///<returns></ Returns>public qqoauthinfo Getoauthinfo (String code) {String callback = System.Web.HttpUtility.UrlEncode ( configurationmanager.appsettings["Qqcallback"], Encoding.UTF8); string url = string. Format ("Https://graph.qq.com/oauth2.0/token?grant_type={0}&client_id={1}&client_secret={2}&code={3 }&AMP;REDIRECT_URI={4} "," Authorization_code ", AppID, AppKey, Code, callback); string res = Loadhtmlusergettype (URL, ENCODING.UTF8); Qqoauthinfo qqoauthinfo = new Qqoauthinfo () Qqoauthinfo.accesstoken = cutstring (res, "access_token=", "&expirEs_in= "); Qqoauthinfo.expiresin = cutstring (res," &expires_in= "," &refresh_token= "); Qqoauthinfo.refreshtoken = Res. Split (new string[] {"&refresh_token="}, Stringsplitoptions.none) [1];return Qqoauthinfo;} <summary>///intercepts strings in two strings in a string//</summary>///<param name= "str" > String </param>///< param name= "Startstr" > Start string </param>///<param name= "Endstr" > End string </param>///<returns> </returns>private string cutstring (String str, string startstr, String endstr) {int begin, End;begin = str. IndexOf (startstr, 0) + startstr.length; Start position end = str. IndexOf (endstr, begin); End position return str. Substring (begin, End-begin); Take the number of searches, use the end position-start position, and return}///<summary>////////</summary>///<param name= "URLString" > Requested url</param>//<param name= "Encoding" > Page encoding </param>//<returns></returns> public string Loadhtmlusergettype (String urlstring, Encoding Encoding) {HttpWebRequest hTtpwebrequest = null; HttpWebResponse httpwebrespones = null; Stream stream = null;string htmlstring = string. Empty;try{httpwebrequest = WebRequest.Create (urlstring) as HttpWebRequest;} catch (Exception ex) {throw new Exception ("An error occurred while creating the page request! ", ex);} Httpwebrequest.useragent = "mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;. NET CLR 2.0.50727; Maxthon 2.0) "; try{httpwebrespones = (HttpWebResponse) httpwebrequest.getresponse (); stream = Httpwebrespones.getresponsestream ();} catch (Exception ex) {throw new Exception ("An error occurred while accepting the server's return page! ", ex);} StreamReader StreamReader = new StreamReader (stream, encoding); try{htmlstring = Streamreader.readtoend ();} catch (Exception ex) {throw new Exception ("An error occurred while reading the page data! ", ex);} Streamreader.close (); stream. Close (); return htmlstring;} <summary>///get QQ account openid///</summary>///<param name= "Qqoauthinfo" ></param>///< Returns></returns>public string Getopenid (Qqoauthinfo qqoauthinfo) {String res = Loadhtmlusergettype ("https ://GRAPH.QQ. com/oauth2.0/me?access_token= "+ Qqoauthinfo.accesstoken, Encoding.UTF8); return cutstring (res, @" OpenID "": "" ", @" "" }");} <summary>///get QQ Nickname///</summary>///<param name= "Qqoauthinfo" ></param>///<param name = "OpenID" ></param>///<returns></returns>public string GetUserInfo (Qqoauthinfo QQOauthInfo, String OpenID) {string urlgetinfo = string. Format (@ "https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", Qqoauthinfo.accesstoken,appid, OpenID); string resuserinfo = Loadhtmlusergettype (Urlgetinfo, Encoding.UTF8); return Cutstring (Resuserinfo, @ "" "Nickname" ":" "", @ "" ",");}} public class Qqoauthinfo{public string Accesstoken {get; set;} public string Expiresin {get; set;} public string Refreshtoken {get; set;}}}

Four. Demo effect

We can directly visit the http://www.mylanqiu.com to see the actual effect, and finally thank you for reading, such as you have a lot of help to forward, to help more people, is so-called: Gift Rose Hand Fragrance! If there are deficiencies, please correct me!

Website Integration QQ Login function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.