一键登录(qq,weibo)

首先需要去qq,weibo申请密钥,然后会得到APPID和APPKEY,然后一步步操作,都有提示。成功后把配置写在common函数以便后期调用。

<?php

//qq一键登录

function qqlogin_config(){
    define("QQDEBUG", false);
    if (defined("QQDEBUG") && QQDEBUG)
    {
        @ini_set("error_reporting", E_ALL);
        @ini_set("display_errors", TRUE);
    }else{
     error_reporting(E_ALL^E_NOTICE);
    }

    session_start();

    //申请到的appid
    $_SESSION["appid"]    = ''; 

    //申请到的appkey
    $_SESSION["appkey"]   = ""; 

    //QQ登录成功后跳转的地址,请确保地址真实可用,否则会导致登录失败。 
    //一定要注意回调地址
    $_SESSION["callback"] = "http://" . $_SERVER['SERVER_NAME'] . "/index.php/Home/OAuth/qqCallback"; 

    //QQ授权api接口.按需调用
    //$_SESSION["scope"] = "get_user_info,add_share,list_album,add_album,upload_pic,add_topic,add_one_blog,add_weibo";
    $_SESSION["scope"] = "get_user_info";
}

function qqlogin_do_post($url, $data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    curl_setopt($ch, CURLOPT_POST, TRUE); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
    curl_setopt($ch, CURLOPT_URL, $url);
    $ret = curl_exec($ch);

    curl_close($ch);
    return $ret;
}
    
/———————————————-
 
 
  微博一键登录
 

 ———————————————-/
 
/**
  微博一键登录 - 配置
 
/
function weibo_config(){
    define( "WB_AKEY" , '4002186908' );
    define( "WB_SKEY" , 'dd81902ee3460eba972f46487aac41e2' );
    define( "WB_CALLBACK_URL" , 'http://www.ayanglao.org.cn'  . U('Home/OAuth/weiboCallback'));
}

然后就是OAuthAction

<?php

class OAuthAction extends AppbaseAction {

public&nbsp;function&nbsp;qqLogin(){

        //….
        qqlogin_config();

        $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
        $login_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=
            . $_SESSION["appid"] . "&redirect_uri=" . urlencode($_SESSION["callback"])
            . "&state=" . $_SESSION['state']
            . "&scope=".$_SESSION["scope"];
     //echo $login_url;
     //print_r($_SESSION);
     //die();
        header("Location:$login_url");
        
    }

    public function qqCallback(){

        qqlogin_config();
//var_dump($_SESSION);

        /*
         获取token
        
/
        if($_REQUEST['state'] == $_SESSION['state']) //csrf
        {
            $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
                . "client_id=" . $_SESSION["appid"]. "&redirect_uri=" . urlencode($_SESSION["callback"])
                . "&client_secret=" . $_SESSION["appkey"]. "&code=" . $_REQUEST["code"];
            $response = file_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))
                {
                    echo "<h3>error-token:</h3>" . $msg->error;
                    echo "<h3>msg  :</h3>" . $msg->error_description;
                    exit;
                }
            }

            $params = array();
            parse_str($response, $params);

            //debug
            //print_r($params);die();

            //set access token to session
            $_SESSION["access_token"] = $params["access_token"];

        }
        else 
        {
            echo("The state does not match. You may be a victim of CSRF.");
        }

        /*
         获取open_id
        
/

        $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=
            . $_SESSION['access_token'];

        $str  = file_get_contents($graph_url);
        if (strpos($str, "callback") !== false)
        {
            $lpos = strpos($str, "(");
            $rpos = strrpos($str, ")");
            $str  = substr($str, $lpos + 1, $rpos - $lpos -1);
        }

        $user = json_decode($str);
        if (isset($user->error))
        {
            echo "<h3>error-openid:</h3>" . $user->error;
            echo "<h3>msg  :</h3>" . $user->error_description;
            exit;
        }

        //debug
        //echo("Hello " . $user->openid);

        //set openid to session
        $_SESSION["openid"] = $user->openid;
        
        // todo: 进行登录与注册的判断

        /*
         获取用户信息
        
/

        $graph_url = "https://graph.qq.com/user/get_user_info"
         . '?access_token=' . $_SESSION['access_token']
         . '&oauth_consumer_key=' . $_SESSION['appid']
            . '&openid=' . $_SESSION["openid"];

        $str  = file_get_contents($graph_url);

        $json_result = json_decode($str);
        if($json_result->ret == '0'){
         $nickname = $json_result->nickname; //昵称
         $avatar = $json_result->figureurl_qq_2; //40*40的qq头像
         $gender = $json_result->gender; //性别
     //echo '<meta charset="utf-8" />';
     //echo "昵称:$nickname<br>性别:$gender<br>QQ头像:<img src=$figureurl_qq_1 />";die();

     $row = M("member")->where("m_qq_openid='%s'",$SESSION["openid"])->find();
     if($row){
    session('m_id',$row['m_id']);
    session('m_nick_name',$row['m_nick_name']);
    session('m_login_name',$row['m_login_name']);
    session('is_org',-1);
    //U('Home/Home/index',null,true,true);
    if(session('shebei') == 1){
         //echo '<script>window.close();window.opener.location.href="http://www.13sai.com'.U('Wap/Home/index').'";</script>&#39;;
         echo '<script>window.location.href="http://www.13sai.com'.U('Wap/Home/index').'";</script>&#39;;
    }else{
         echo '<script>window.close();window.opener.location.href="http://www.13sai.com";</script>&#39;;
    }
    
     }else{
     // 创建新用户
                $count = M("member")->max('m_id');
                $count++;
                $rand = mt_rand(1000,9999);
                
          //$data['gender']  = $gender; 
          $data['m_avatar']  = $avatar; 
          $data['m_nick_name']  = mb_substr($nickname,0,6,"utf-8") . $count;
             $data['m_login_name'] = 'qq
'.$rand.''.$count;
         $data['m_password'] = md5(md5(time()));
          $data['m_qq_openid']  = $_SESSION["openid"]; 
         $data['from'] = 'qq';

         session('kj_object',$data);

          if(session('shebei') == 1){
         //echo '<script>window.close();window.opener.location.href="http://www.13sai.com'.U('Wap/Guide/binding').'";</script>&#39;;
         echo '<script>window.location.href="http://www.13sai.com'.U('Wap/Guide/binding').'";</script>&#39;;
    }else{
         echo '<script>window.close();window.opener.location.href="http://www.13sai.com'.U('Home/Guide/binding').'";</script>&#39;;
    }
          //echo '<script>window.close();window.opener.location.href="http://www.13sai.com";</script>&#39;;
     }
    
        }else{
         echo '111'.$str;
        }

    }

    
    //微博一键登录(登录)
    public function weiboLogin(){
        session_start();
        weibo_config();
        Vendor('Weibo.saetv2ex');

        $o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
        $code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );

        header("Location: " . $code_url);
    }

    //微博一键登录(回调)
    public function weiboCallback(){
        session_start();
        error_reporting(E_ERROR);
        weibo_config();
        Vendor('Weibo.saetv2ex');

        
        $o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );

        if (isset($_REQUEST['code'])) {
         $keys = array();
         $keys['code'] = $_REQUEST['code'];
         $keys['redirect_uri'] = WB_CALLBACK_URL;
         try {
         $token = $o->getAccessToken( 'code', $keys ) ;
         } catch (OAuthException $e) {
         }
        }

        if ($token) {
         $SESSION['token'] = $token;
         setcookie( 'weibojs
'.$o->client_id, http_build_query($token) );
        
         $c = new SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] );
         $ms  = $c->home_timeline(); // done
         $uid_get = $c->get_uid();
         $uid = $uid_get['uid'];
         $user_message = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息
        
         //保存几个基本信息
         $openid = $user_message['id'];
         $nickname = $user_message['screen_name'];
         $avatar = $user_message['profile_image_url'];
         $gender = $user_message['gender'];
         $gender = ($gender=='m')?'男':'女';

         /以下为写本地数据库/
        
         //通过 $openid 检查用户是否存在
         //if(存在){
             //
         //}else{
         // 创建新用户
         // 设置登录状态
         //}
         //dump($user_message);

         $row = M("member")->where("m_weibo_openid='%s'",$openid)->find();
     if($row){
    session('m_id',$row['m_id']);
    session('m_nick_name',$row['m_nick_name']);
    session('m_login_name',$row['m_login_name']);
    session('is_org',-1);
    //U('Home/Home/index',null,true,true);
    if(session('shebei') == 1){
         echo '<script>window.close();window.opener.location.href="http://www.13sai.com'.U('Wap/Home/index').'";</script>&#39;;
    }else{
         echo '<script>window.close();window.opener.location.href="http://www.13sai.com";</script>&#39;;
    }
    //echo '<script>window.close();window.opener.location.href="http://www.13sai.com";</script>&#39;;
     }else{
     // 创建新用户
                $count = M("member")->max('m_id');
                $count++;
                $rand = mt_rand(1000,9999);
                
          //$data['gender']  = $gender; 
          $data['m_avatar']  = $avatar; 
          $data['m_nick_name']  = mb_substr($nickname,0,6,"utf-8") . $count;
             $data['m_login_name'] = 'wb_'.$rand.''.$count;
         $data['m_password'] = md5(md5(time()));
          $data['m_weibo_openid']  = $openid; 
         $data['from'] = 'weibo';

         session('kj_object',$data);

          if(session('shebei') == 1){
         echo '<script>window.close();window.opener.location.href="http://www.13sai.com'.U('Wap/Guide/binding').'";</script>&#39;;
    }else{
         echo '<script>window.close();window.opener.location.href="http://www.13sai.com'.U('Home/Guide/binding').'";</script>&#39;;
    }
         

         //跳转到会员中心

        } else {
         echo '授权失败';
        }
    }

}

前台调用比较简单

                    <div class="yijian wd-center">
        <p class="wd-left">使用其他账号登录</p>
        <a onclick="toQzoneLogin()" class="other_login other_login_qq"><img src="/webui/home/images/Q.png"></a>
        <a onclick="toWeiboLogin()"><img src="/webui/home/images/weibo.png"></a>

    &nbsp;&nbsp;&nbsp;&nbsp;&lt;/div&gt;
    &nbsp;&nbsp;&nbsp;&nbsp;

<script>
function toQzoneLogin()
{
var A=window.open("http://www.ayanglao.org.cn{:U('Home/OAuth/qqLogin','',false)}/"+Math.random(),"TencentLogin","width=600,height=480,menubar=0,scrollbars=1, resizable=1,status=1,titlebar=0,toolbar=0,location=1");
}

function toWeiboLogin()
{
var A=window.open("http://www.ayanglao.org.cn{:U('Home/OAuth/weiboLogin','',false)}/"+Math.random(),"WeiboLogin","width=450,height=320,menubar=0,scrollbars=1, resizable=1,status=1,titlebar=0,toolbar=0,location=1");
}
</script>

这样就ok了。下次说说微信登录。


一键登录(qq,weibo)
https://github.13sai.com/2016/09/04/69/
作者
13sai
许可协议