PHP to achieve QQ fast login ____php

Source: Internet
Author: User

Objective:

PHP to achieve QQ fast login, listed three ways

Method One: Process-oriented, callback address and first triggering login write to a method page "because there is an if to judge", Method two, three: object-oriented
1. Call the login method first, send the request to Tencent,
2. Tencent carries the unique corresponding parameter openid,accesstoken of this website, returns to the corresponding callback page,
3. The callback page receives the parameters of Tencent, and then sends the corresponding request through the two parameters, such as querying the user's data.
4. Tencent to do the corresponding operation, such as the return of the user's data to you

Even if you do not understand, it does not matter, according to my following process to ensure that you can achieve.


Pre-Preparation:

Use Tencent's function, must say hello to others.

QQ Internet Home: http://connect.qq.com/

After entering the Web site, follow these steps: one. Access to the official website



Two. Apply to create a "website" Application




three. Fill in the information as required

Note Web address: Fill in the URL you want to set the fast login, eg:http://www.test.com;

Callback Address: Fill in your QQ fast landing, Tencent has to give you information, this message to this page to accept. eg:http://www.test.com/accept_info.php

"Detailed application to fill out, please see the official tip, here do not repeat"



Four. After the successful application, improve the information

final request, get app_id, App_key


five. Code section: write in your corresponding PHP file, as follows


Method One, process-oriented method
How to use: Configure $app_id, $app _secret, $my _url, other intact replication, $user _data for the returned login information
Code:

 Application of the AppID $app _id = "Your AppID";
            Application of the Appkey $app _secret = "Your Appkey";

            "Successful authorization" after the callback address, that is, this address in Tencent's information is stored $my _url = "Your callback URL";
            STEP1: Get authorization Code session_start (); $code = $_request["code"];//Store Authorization Code if (empty ($code)) {//state parameter is used to prevent C
                SRF attack, when a callback is successfully authorized, it is brought back to $_session[' state ' = MD5 (Uniqid (rand (), TRUE);
                    Stitching URL $dialog _url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=" . $app _id. "&redirect_uri=". UrlEncode ($my _url). "&state=".
                $_session[' state ']; Echo ("<script> top.location.href= '". $dialog _url.
            "' </script>");
            }//STEP2: Access Token if ($_request[' state ' = = $_session[' state '] by authorization code | | 1)
   {//Stitching URL             $token _url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&". "Client_id=". $app _id. "&redirect_uri=". UrlEncode ($my _url). "&client_secret=". $app _secret. "&code=".
                $code;
                $response = file_get_contents ($token _url);
                    if (Strpos ($response, "callback")!== false)//if the logged-on user temporarily changes his mind to cancel, return to True!==false, otherwise execute step3 {
                    $lpos = Strpos ($response, "(");
                    $rpos = Strrpos ($response, ")");
                    $response = substr ($response, $lpos + 1, $rpos-$lpos-1);
                    $msg = Json_decode ($response); if (Isset ($msg->error)) {echo  





Method Two. Object-oriented use class Qq_loginaction.class
How to use:
1. Proper configuration of Appid,appkey CALLBACK (callback URL) in Qq_loginaction.class
2. In the calling method, the code:
$QQ _login = new \component\qq_loginaction ();		The introduction of such a document can be
$qq _login->qq_login ();					Call the login method to send a quick logon request to Tencent


3. In the callback page, code:
$QC = new \component\qq_loginaction ();
$acs = $qc->qq_callback (); <span style= "White-space:pre" >		//access_token
$oid = $qc->get_openid ( ); <span style= "White-space:pre" >			//openid
$user _data = $qc->get_user_info (); <span style= " White-space:pre ">	//get_user_info () to obtain the user's information, see the API documentation for other methods of action


4. $user _data is the returned user data.

5.qq_loginaction.class.php file code: "ThinkPHP3.2"

<?php namespace Component;
Session_Start ();         Define (' APPID ', ' XXXX ');        AppID define (' Appkey ', ' XXXX ');      Appkey define (' CALLBACK ', ' XXXX ');      Callback address define (' SCOPE ', ' Get_user_info,list_album,add_album,upload_pic,add_topic,add_weibo ');
    Authorization interface List class Qq_loginaction {const GET_AUTH_CODE_URL = "Https://graph.qq.com/oauth2.0/authorize";
    Const GET_ACCESS_TOKEN_URL = "Https://graph.qq.com/oauth2.0/token";
    Const GET_OPENID_URL = "Https://graph.qq.com/oauth2.0/me"; Private $APIMap = Array ("Get_user_info" => Array (//Get user information) Https://graph.qq.com/user/ge
            T_user_info ", Array (" format "=>" JSON ")," add_t "=> Array (//post an ordinary microblog "https://graph.qq.com/t/add_t", Array ("format" => "JSON", "content", "#clientip", "#longitude", "
            Latitude "," #compatibleflag ")," POST ")," add_pic_t "=> Array (//post a photo microblog "Https://graph.qq.com/t/add_pic_t ", Array (" Content "," pic "," format "=>" JSON "," #clientip "," #longitude "," #la Titude "," #syncflag "," #compatiblefalg ")," POST ")," del_t "=> Array (/
        /delete a tweet "https://graph.qq.com/t/del_t", Array ("id", "format" => "JSON"), "POST" ), "Get_repost_list" => Array (//Get the forwarding or comment list for a single tweet) https://graph.qq.com/t/get_repost
        _list ", Array (" Flag "," Rootid "," Pageflag "," Pagetime "," Reqnum "," Twitterid "," format "=>" JSON ")
            ), "Get_info" => Array (//Get Current User Data "Https://graph.qq.com/user/get_info", Array ("format" => "JSON"), "Get_other_info" => Array (//Get other user information) htt
        Ps://graph.qq.com/user/get_other_info ", Array (" format "=>" JSON "," #name-1 "," #fopenid-1 ")), "Get_fanslist" =>Array ("Https://graph.qq.com/relation/get_fanslist",//My Microblog fan list array ("format" => "JSON", "re Qnum "," startindex "," #mode "," #install "," #sex ")," Get_idollist "=> Array (" Https://grap H.qq.com/relation/get_idollist ",//My Microblog listening list array (" format "=>" JSON "," Reqnum "," startindex "," #mode ","
            Install "))," Add_idol "=> Array (" Https://graph.qq.com/relation/add_idol ",//micro-blog to listen to a user Array ("format" => "JSON", "#name-1", "#fopenids-1"), "POST", "Del_idol" =>  Array (//Weibo to cancel listening to a user "Https://graph.qq.com/relation/del_idol", Array ("format" => "JSON",
    "#name-1", "#fopenid-1"), "POST");
    Private $KEYSARR; function __construct () {if ($_session["OpenID"]) {$this->keysarr = array ("Oauth_con Sumer_key "=> APPID," Access_token "=&Gt
        $_session[' Access_token '], "OpenID" => $_session["OpenID"]);
        }else{$this->keysarr = Array ("Oauth_consumer_key" => APPID); The Public Function Qq_login () {//-------generates a unique random string csrf attack $_session[' state ' = MD5 (Uniqid (rand (), TR
        UE)); $KEYSARR = Array ("Response_type" => "code", "client_id" => APPID, "Redirect_uri
        "=> CALLBACK", "state" => $_session[' state ', "scope" => scope); $login _url = Self::get_auth_code_url. '? '.
        Http_build_query ($KEYSARR);
    Header ("Location: $login _url");
            Public Function Qq_callback () {//--------verify state to prevent CSRF attack if ($_get[' state ']!= $_session[' state ') {
        return false; The//-------request parameter list $KEYSARR = Array ("Grant_type" => "Authorization_code", "Clie nt_id "=> APPID, "Redirect_uri" => CALLBACK, "Client_secret" => Appkey, "code" => $_get['
        Code ']); ------construct request Access_token URL $token _url = Self::get_access_token_url. '? '.
        Http_build_query ($KEYSARR);
        $response = $this->get_contents ($token _url);
            if (Strpos ($response, "callback")!== false) {$lpos = Strpos ($response, "(");
            $rpos = Strrpos ($response, ")");
            $response = substr ($response, $lpos + 1, $rpos-$lpos-1);
            $msg = Json_decode ($response);
            if (Isset ($msg->error)) {$this->showerror ($msg->error, $msg->error_description);
        }} $params = Array ();
        Parse_str ($response, $params);
        $_session["Access_token"]= $params ["Access_token"];
        $this->keysarr[' Access_token ']= $params [' Access_token '];
    return $params ["Access_token"];
      Public Function get_contents ($url) {  if (Ini_get ("allow_url_fopen") = = "1") {$response = file_get_contents ($url);
            }else{$ch = Curl_init ();
            curl_setopt ($ch, Curlopt_ssl_verifypeer, FALSE);
            curl_setopt ($ch, Curlopt_returntransfer, TRUE);
            curl_setopt ($ch, Curlopt_url, $url);
            $response = curl_exec ($ch);
        Curl_close ($ch);
        } if (empty ($response)) {return false;
    return $response; The Public Function Get_openid () {//-------request parameter list $KEYSARR = Array ("Access_token" => $_s
        ession["Access_token"]); $graph _url = Self::get_openid_url. '? '.
        Http_build_query ($KEYSARR);
        $response = $this->get_contents ($graph _url);
            --------detect if the error occurs if (Strpos ($response, "callback")!== false) {$lpos = Strpos ($response, "(");
            $rpos = Strrpos ($response, ")"); $response = substr ($response, $lpos + 1, $rpos-$lpos-1);
        } $user = Json_decode ($response);
        if (Isset ($user->error)) {$this->showerror ($user->error, $user->error_description);
        }//------record OpenID $_session[' OpenID ']= $user->openid;
        $this->keysarr[' OpenID ']= $user->openid;
    return $user->openid;
     /** * ShowError * Display error message * @param int $code Error code * @param string $description description information (optional)
            * * Public Function ShowError ($code, $description = ' $ ') {echo "<meta charset=\" utf-8\ ">";
            echo " 



Method III, object-oriented use of Tencent to the SDK
Usage: Tencent Sdk,api wrote very detailed, do not repeat

Address: http://wiki.connect.qq.com/%E7%BD%91%E7%AB%99%E6%8E%A5%E5%85%A5%E6%A6%82%E8%BF%B0



This is the realization of QQ quick login, in fact very simple, we can try.

What else is not clear, you can look at the official introduction, more detailed,


Tips: How to test QQ in local fast login

Method: Modify the Host configuration file

1. Open C:\Windows\System32\drivers\etc\host

2. Add 127.0.0.1 www.test.com

And then you can do it.

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.